Skip to content

Commit

Permalink
[MIG] account_analytic_distribution_manual: Migration to 17.0
Browse files Browse the repository at this point in the history
  • Loading branch information
BernatObrador committed Oct 15, 2024
1 parent 9983efa commit c91ce16
Show file tree
Hide file tree
Showing 12 changed files with 115 additions and 94 deletions.
4 changes: 4 additions & 0 deletions account_analytic_distribution_manual/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ Contributors

- Carlos Lopez

- APSL - Nagarro <https://apsl.tech>

- Bernat Obrador

Maintainers
-----------

Expand Down
2 changes: 1 addition & 1 deletion account_analytic_distribution_manual/__manifest__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
{
"name": "Account analytic distribution manual",
"summary": "Account analytic distribution manual",
"version": "16.0.2.4.0",
"version": "17.0.1.0.0",
"license": "AGPL-3",
"website": "https://github.com/OCA/account-analytic",
"author": "Tecnativa, Odoo Community Association (OCA)",
Expand Down
56 changes: 30 additions & 26 deletions account_analytic_distribution_manual/hooks.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Copyright 2024 Tecnativa - Carlos Lopez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).

from odoo import SUPERUSER_ID, api, tools
from odoo import tools

# metadata for all models related to account_analytic_tag(m2m)
# add more models if needed
Expand Down Expand Up @@ -105,37 +105,40 @@
}


def post_init_hook(cr, registry):
if tools.table_exists(cr, "account_analytic_tag"):
env = api.Environment(cr, SUPERUSER_ID, {})
def post_init_hook(env):
if tools.table_exists(env.cr, "account_analytic_tag"):
DistributionManual = env["account.analytic.distribution.manual"]
sql = """
WITH counted_tags AS (
WITH counted_tags AS (
SELECT
tag.id,
tag.name,
tag.active,
tag.company_id,
ROW_NUMBER() OVER (PARTITION BY tag.name ORDER BY tag.id)
AS row_count
FROM account_analytic_tag tag
)
SELECT
CASE
WHEN row_count = 1 THEN tag.name
ELSE CONCAT(tag.name, ' (', tag.id, ')')
END AS name,
tag.id,
tag.name,
tag.active,
tag.company_id,
ROW_NUMBER() OVER (PARTITION BY tag.name ORDER BY tag.id) AS row_count
FROM account_analytic_tag tag
WHERE tag.active_analytic_distribution = true
)
SELECT
CASE
WHEN row_count = 1 THEN tag.name
ELSE CONCAT(tag.name, ' (', tag.id, ')')
END AS name,
tag.id,
tag.active,
tag.company_id,
distribution.account_id,
distribution.percentage
FROM
counted_tags tag
INNER JOIN
account_analytic_distribution distribution
ON tag.id = distribution.tag_id;
distribution.account_id,
distribution.percentage
FROM
counted_tags tag
INNER JOIN account_analytic_tag_account_move_line_rel rel ON
rel.account_analytic_tag_id = tag.id
INNER JOIN account_move_line line ON
line.id = rel.account_move_line_id
CROSS JOIN LATERAL jsonb_each(line.analytic_distribution)
AS distribution(account_id, percentage)
;
"""
env.cr.execute(sql)
distribution_by_tag = {}
Expand Down Expand Up @@ -167,6 +170,7 @@ def post_init_hook(cr, registry):
if (
res_model_name in env
and "manual_distribution_id" in env[res_model_name]._fields
and tools.table_exists(env.cr, table_m2m)
):
sql = f"""
SELECT {column1}, {column2}
Expand Down

This file was deleted.

6 changes: 3 additions & 3 deletions account_analytic_distribution_manual/models/base.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# Copyright 2024 Tecnativa - Carlos Lopez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import json

from lxml import etree

Expand Down Expand Up @@ -35,12 +34,13 @@ def get_view(self, view_id=None, view_type="form", **options):

def add_field(node, view_type, res_model):
attribute = "column_invisible" if view_type == "tree" else "invisible"
modifiers = json.dumps({attribute: True})
field_options = {
"name": manual_distribution_field_name,
"modifiers": modifiers,
}
field_element = etree.SubElement(node, "field", field_options)
# Now, attributes need to be set directly on the 'field_element'.
# If they are passed through 'field_options', it won't work correctly.
field_element.set(attribute, "1")
new_arch, new_models = View.postprocess_and_fields(field_element, res_model)
_merge_view_fields(all_models, new_models)
return field_element
Expand Down
2 changes: 2 additions & 0 deletions account_analytic_distribution_manual/readme/CONTRIBUTORS.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
- Tecnativa (<https://www.tecnativa.com>):
- Carlos Lopez
- APSL - Nagarro \<<https://apsl.tech>\>
- Bernat Obrador
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@
class AccountInvoiceReport(models.Model):
_inherit = "account.invoice.report"

manual_distribution_id = fields.Many2one(
"account.analytic.distribution.manual", readonly=True
)
manual_distribution_id = fields.Many2one("account.analytic.distribution.manual")

def _select(self):
return super()._select() + ", line.manual_distribution_id"
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,10 @@ <h2><a class="toc-backref" href="#toc-entry-7">Contributors</a></h2>
<li>Carlos Lopez</li>
</ul>
</li>
<li>APSL - Nagarro &lt;<a class="reference external" href="https://apsl.tech">https://apsl.tech</a>&gt;<ul>
<li>Bernat Obrador</li>
</ul>
</li>
</ul>
</div>
<div class="section" id="maintainers">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
/** @odoo-module **/

import {AnalyticDistribution} from "@analytic/components/analytic_distribution/analytic_distribution";
import {AutoComplete} from "@web/core/autocomplete/autocomplete";
import {_t} from "@web/core/l10n/translation";
import {patch} from "@web/core/utils/patch";
const {useState} = owl;

patch(AnalyticDistribution.prototype, "account_analytic_distribution_manual", {
patch(AnalyticDistribution.prototype, {
setup() {
this._super();
super.setup(...arguments);
this.manual_distribution_by_id = {};
this.state_manual_distribution = useState({
id: this.props.record.data.manual_distribution_id
Expand All @@ -17,13 +19,13 @@ patch(AnalyticDistribution.prototype, "account_analytic_distribution_manual", {
});
},
async willStart() {
await this._super();
await super.willStart(...arguments);
if (this.state_manual_distribution.id) {
this.refreshManualDistribution(this.state_manual_distribution.id);
}
},
async willUpdate(nextProps) {
await this._super(nextProps);
await super.willUpdate(nextProps);
const record_id = this.props.record.data.id || 0;
const current_manual_distribution_id = this.state_manual_distribution.id;
const new_manual_distribution_id = nextProps.record.data.manual_distribution_id
Expand All @@ -42,13 +44,15 @@ patch(AnalyticDistribution.prototype, "account_analytic_distribution_manual", {
}
},
async save() {
await this._super();
await this.props.record.update({
manual_distribution_id: [
this.state_manual_distribution.id,
this.state_manual_distribution.label,
],
});
await super.save();
if (this.state_manual_distribution.id) {
await this.props.record.update({
manual_distribution_id: [
this.state_manual_distribution.id,
this.state_manual_distribution.label,
],
});
}
},
async refreshManualDistribution(manual_distribution_id) {
if (manual_distribution_id === 0) {
Expand Down Expand Up @@ -77,7 +81,7 @@ patch(AnalyticDistribution.prototype, "account_analytic_distribution_manual", {
}
},
get tags() {
let res = this._super();
let res = super.tags(...arguments);
if (this.state_manual_distribution.id) {
// Remove the delete button from tags
// it will be added only to the manual distribution tag
Expand All @@ -98,16 +102,13 @@ patch(AnalyticDistribution.prototype, "account_analytic_distribution_manual", {
analytic_distribution: [],
};
// Clear all distribution
for (const group_id in this.list) {
this.list[group_id].distribution = [];
}
this.autoFill();
this.state.formattedData = [];
},
// Autocomplete
sourcesAnalyticDistributionManual() {
return [
{
placeholder: this.env._t("Loading..."),
placeholder: _t("Loading..."),
options: (searchTerm) =>
this.loadOptionsSourceDistributionManual(searchTerm),
},
Expand All @@ -130,7 +131,7 @@ patch(AnalyticDistribution.prototype, "account_analytic_distribution_manual", {
}
if (!options.length) {
options.push({
label: this.env._t("No Analytic Distribution Manual found"),
label: _t("No Analytic Distribution Manual found"),
classList: "o_m2o_no_result",
unselectable: true,
});
Expand Down Expand Up @@ -165,33 +166,61 @@ patch(AnalyticDistribution.prototype, "account_analytic_distribution_manual", {
this.deleteManualTag();
}
},
async processSelectedOption(selected_option) {
for (const idsString in selected_option.analytic_distribution) {
const percentage = selected_option.analytic_distribution[idsString];

// Parse the IDs of selected_options, converting the key (e.g., "1,3") into an array of IDs [1, 3].
const idsArray = idsString.split(",").map((id) => parseInt(id, 10));
const lineToAdd = {
id: this.nextId++,
analyticAccounts: this.plansToArray(),
percentage: percentage / 100,
};

for (let i = 0; i < idsArray.length; i++) {
const accountId = idsArray[i];
const accountData = await this.getAccountDetails(accountId);
if (accountData) {
lineToAdd.analyticAccounts.push({
accountId: accountData.id,
accountDisplayName: accountData.display_name,
planColor: accountData.color,
accountRootPlanId: accountData.root_plan_id[0],
planId: accountData.root_plan_id[0],
planName: accountData.root_plan_id[1],
});
}
}
this.state.formattedData.push(lineToAdd);
}
},
async getAccountDetails(accountId) {
const record = await this.orm.read(
"account.analytic.account",
[accountId],
["name", "color", "root_plan_id"]
);
const accountDetails = {
id: accountId,
display_name: record[0].name,
color: record[0].color,
root_plan_id: record[0].root_plan_id,
};
return accountDetails;
},
async onSelectDistributionManual(option) {
const selected_option = Object.getPrototypeOf(option);
this.state_manual_distribution = {
id: selected_option.value,
label: selected_option.label,
analytic_distribution: selected_option.analytic_distribution,
};
const account_ids = Object.keys(selected_option.analytic_distribution).map(
(id) => parseInt(id, 10)
);
const analytic_accounts = await this.fetchAnalyticAccounts([
["id", "in", account_ids],
]);
// Clear all distribution
for (const group_id in this.list) {
this.list[group_id].distribution = [];
}
for (const account of analytic_accounts) {
// Add new tags
const planId = account.root_plan_id[0];
const tag = this.newTag(planId);
tag.analytic_account_id = account.id;
tag.analytic_account_name = account.display_name;
tag.percentage = selected_option.analytic_distribution[account.id];
this.list[planId].distribution.push(tag);
}
this.state.formattedData = [];

this.autoFill();
await this.processSelectedOption(selected_option);
},
});

AnalyticDistribution.components = {...AnalyticDistribution.components, AutoComplete};
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@
id="analytic_distribution_inherit"
t-inherit="analytic.AnalyticDistributionPopup"
t-inherit-mode="extension"
owl="1"
>
<xpath expr="//span[@t-if='!sortedList.length']" position="before">
<xpath expr="//span[@t-if='!allPlans.length']" position="before">
<div class="pb-4 border-bottom">
<strong>Manual distribution</strong>
<AutoComplete
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
name="web_ribbon"
title="Archived"
bg_color="bg-danger"
attrs="{'invisible': [('active', '=', True)]}"
invisible="active"
/>
<div class="oe_title">
<label for="name" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<field name="inherit_id" ref="analytic.view_account_analytic_line_tree" />
<field name="arch" type="xml">
<field name="amount" position="after">
<field name="manual_distribution_id" optional="hide" />
<field name="manual_distribution_id" optional="hide" readonly="1" />
</field>
</field>
</record>
Expand All @@ -15,7 +15,7 @@
<field name="inherit_id" ref="analytic.view_account_analytic_line_form" />
<field name="arch" type="xml">
<field name="account_id" position="after">
<field name="manual_distribution_id" />
<field name="manual_distribution_id" readonly="1" />
</field>
</field>
</record>
Expand Down

0 comments on commit c91ce16

Please sign in to comment.