remove year's result in reports other than BS &PL

This commit is contained in:
Florian du Garage Num 2024-11-20 19:44:54 +01:00
parent 1306043f22
commit f0dd16ab38
4 changed files with 107 additions and 1162 deletions

View File

@ -16,7 +16,18 @@ It is based on modules:
- Displays unaffected earnings (report à nouveau) and year's result
### Trial Balance
- Displays unaffected earnings and year's earnings
- Displays unaffected earnings
### General Ledger
- Displays unaffected and year's earnings
- Displays unaffected earnings
## ChangeLog
- v16.0.0.0.5:
- remove year's earning in trial balance
- remove year's earning in general ledger
- remove rear's earning in FEC
- v16.0.0.0.4: Add general ledger
- v16.0.0.0.3: Add Trial Balance
- v16.0.0.0.2: Add Mis Report
- v16.0.0.0.1: Add FEC

View File

@ -8,53 +8,12 @@ from odoo.tools import float_is_zero
class GnGeneralLedgerReport(models.AbstractModel):
_inherit = "report.account_financial_report.general_ledger"
def _get_year_balance_fy_pl_ml_domain(
self, account_ids, company_id, date_from, date_to, base_domain
):
accounts_domain = [
("company_id", "=", company_id),
("include_initial_balance", "=", False),
]
if account_ids:
accounts_domain += [("id", "in", account_ids)]
domain = []
domain += base_domain
domain += [("date", ">=", date_from), ("date", "<=", date_to)]
accounts = self.env["account.account"].search(accounts_domain)
domain += [("account_id", "in", accounts.ids)]
return domain
def _get_pl_year_balance(
self, account_ids, company_id, date_from, date_to, foreign_currency, base_domain
):
domain = self._get_year_balance_fy_pl_ml_domain(
account_ids, company_id, date_from, date_to, base_domain
)
year_balances = self.env["account.move.line"].read_group(
domain=domain,
fields=["account_id", "debit", "credit", "balance", "amount_currency:sum"],
groupby=["account_id"],
)
pl_year_balance = {
"debit": 0.0,
"credit": 0.0,
"balance": 0.0,
"bal_curr": 0.0,
}
for year_balance in year_balances:
pl_year_balance["debit"] += year_balance["debit"]
pl_year_balance["credit"] += year_balance["credit"]
pl_year_balance["balance"] += year_balance["balance"]
pl_year_balance["bal_curr"] += year_balance["amount_currency"]
return pl_year_balance
def _get_initial_balance_data(
self,
account_ids,
partner_ids,
company_id,
date_from,
date_to,
foreign_currency,
only_posted_moves,
unaffected_earnings_account,
@ -90,25 +49,17 @@ class GnGeneralLedgerReport(models.AbstractModel):
accounts_ids = list(data.keys())
unaffected_id = unaffected_earnings_account
if unaffected_id:
result_profit_account = self.env['account.account'].search([('code', '=', '120000')])
result_loss_account = self.env['account.account'].search([('code', '=', '129000')])
unaffected_profit_account = self.env['account.account'].search([('code', '=', '110000')])
unaffected_loss_account = self.env['account.account'].search([('code', '=', '119000')])
if result_profit_account and \
result_loss_account and \
unaffected_profit_account and \
if unaffected_profit_account and \
unaffected_loss_account:
result_profit_id = result_profit_account[0]['id']
result_loss_id = result_loss_account[0]['id']
unaffected_profit_id = unaffected_profit_account[0]['id']
unaffected_loss_id = unaffected_loss_account[0]['id']
if result_profit_id and result_loss_id and \
unaffected_profit_id and unaffected_loss_id:
if unaffected_profit_id and unaffected_loss_id:
for account_id in [result_profit_id, result_loss_id, unaffected_profit_id, unaffected_loss_id]:
for account_id in [unaffected_profit_id, unaffected_loss_id]:
if account_id not in accounts_ids:
accounts_ids.append(account_id)
data[account_id] = self._initialize_data(foreign_currency)
@ -119,9 +70,7 @@ class GnGeneralLedgerReport(models.AbstractModel):
pl_initial_balance = self._get_pl_initial_balance(
account_ids, company_id, fy_start_date, foreign_currency, base_domain
)
pl_year_balance = self._get_pl_year_balance(
account_ids, company_id, date_from, date_to, foreign_currency, base_domain
)
for key_bal in ["init_bal", "fin_bal"]:
fields_balance = ["credit", "debit", "balance"]
if foreign_currency:
@ -136,114 +85,4 @@ class GnGeneralLedgerReport(models.AbstractModel):
data[unaffected_profit_id][key_bal][field_name] += pl_initial_balance[
field_name
]
if pl_year_balance['balance'] > 0:
if key_bal == "fin_bal":
data[result_loss_id][key_bal][field_name] += pl_year_balance[
field_name
]
elif pl_year_balance['balance'] < 0:
if key_bal == "fin_bal":
data[result_profit_id][key_bal][field_name] += pl_year_balance[
field_name
]
return data
def _get_report_values(self, docids, data):
wizard_id = data["wizard_id"]
company = self.env["res.company"].browse(data["company_id"])
company_id = data["company_id"]
date_to = data["date_to"]
date_from = data["date_from"]
partner_ids = data["partner_ids"]
account_ids = data["account_ids"]
cost_center_ids = data["cost_center_ids"]
grouped_by = data["grouped_by"]
hide_account_at_0 = data["hide_account_at_0"]
foreign_currency = data["foreign_currency"]
only_posted_moves = data["only_posted_moves"]
unaffected_earnings_account = data["unaffected_earnings_account"]
fy_start_date = data["fy_start_date"]
extra_domain = data["domain"]
gen_ld_data = self._get_initial_balance_data(
account_ids,
partner_ids,
company_id,
date_from,
date_to,
foreign_currency,
only_posted_moves,
unaffected_earnings_account,
fy_start_date,
cost_center_ids,
extra_domain,
grouped_by,
)
centralize = data["centralize"]
(
gen_ld_data,
accounts_data,
journals_data,
full_reconcile_data,
taxes_data,
analytic_data,
rec_after_date_to_ids,
) = self._get_period_ml_data(
account_ids,
partner_ids,
company_id,
foreign_currency,
only_posted_moves,
date_from,
date_to,
gen_ld_data,
cost_center_ids,
extra_domain,
grouped_by,
)
general_ledger = self._create_general_ledger(
gen_ld_data,
accounts_data,
grouped_by,
rec_after_date_to_ids,
hide_account_at_0,
)
if centralize:
for account in general_ledger:
if account["centralized"]:
centralized_ml = self._get_centralized_ml(
account, date_to, grouped_by
)
account["move_lines"] = centralized_ml
account["move_lines"] = self._recalculate_cumul_balance(
account["move_lines"],
gen_ld_data[account["id"]]["init_bal"]["balance"],
rec_after_date_to_ids,
)
if grouped_by and account[grouped_by]:
account[grouped_by] = False
del account["list_grouped"]
general_ledger = sorted(general_ledger, key=lambda k: k["code"])
return {
"doc_ids": [wizard_id],
"doc_model": "general.ledger.report.wizard",
"docs": self.env["general.ledger.report.wizard"].browse(wizard_id),
"foreign_currency": data["foreign_currency"],
"company_name": company.display_name,
"company_currency": company.currency_id,
"currency_name": company.currency_id.name,
"date_from": data["date_from"],
"date_to": data["date_to"],
"only_posted_moves": data["only_posted_moves"],
"hide_account_at_0": data["hide_account_at_0"],
"show_cost_center": data["show_cost_center"],
"general_ledger": general_ledger,
"accounts_data": accounts_data,
"journals_data": journals_data,
"full_reconcile_data": full_reconcile_data,
"taxes_data": taxes_data,
"centralize": centralize,
"analytic_data": analytic_data,
"filter_partner_ids": True if partner_ids else False,
"currency_model": self.env["res.currency"],
}
return data

View File

@ -10,423 +10,7 @@ import logging
_logger = logging.getLogger(__name__)
class TrialBalanceReport(models.AbstractModel):
_name = "report.account_financial_report.trial_balance"
_description = "Trial Balance Report"
_inherit = "report.account_financial_report.abstract_report"
def _get_initial_balances_bs_ml_domain(
self,
account_ids,
journal_ids,
partner_ids,
company_id,
date_from,
only_posted_moves,
show_partner_details,
):
accounts_domain = [
("company_id", "=", company_id),
("include_initial_balance", "=", True),
]
if account_ids:
accounts_domain += [("id", "in", account_ids)]
domain = [("date", "<", date_from)]
accounts = self.env["account.account"].search(accounts_domain)
domain += [("account_id", "in", accounts.ids)]
if company_id:
domain += [("company_id", "=", company_id)]
if journal_ids:
domain += [("journal_id", "in", journal_ids)]
if partner_ids:
domain += [("partner_id", "in", partner_ids)]
if only_posted_moves:
domain += [("move_id.state", "=", "posted")]
else:
domain += [("move_id.state", "in", ["posted", "draft"])]
if show_partner_details:
domain += [
(
"account_id.account_type",
"in",
["asset_receivable", "liability_payable"],
)
]
return domain
def _get_initial_balances_pl_ml_domain(
self,
account_ids,
journal_ids,
partner_ids,
company_id,
date_from,
only_posted_moves,
show_partner_details,
fy_start_date,
):
accounts_domain = [
("company_id", "=", company_id),
("include_initial_balance", "=", False),
]
if account_ids:
accounts_domain += [("id", "in", account_ids)]
domain = [("date", "<", date_from), ("date", ">=", fy_start_date)]
accounts = self.env["account.account"].search(accounts_domain)
domain += [("account_id", "in", accounts.ids)]
if company_id:
domain += [("company_id", "=", company_id)]
if journal_ids:
domain += [("journal_id", "in", journal_ids)]
if partner_ids:
domain += [("partner_id", "in", partner_ids)]
if only_posted_moves:
domain += [("move_id.state", "=", "posted")]
else:
domain += [("move_id.state", "in", ["posted", "draft"])]
if show_partner_details:
domain += [
(
"account_id.account_type",
"in",
["asset_receivable", "liability_payable"],
)
]
return domain
@api.model
def _get_period_ml_domain(
self,
account_ids,
journal_ids,
partner_ids,
company_id,
date_to,
date_from,
only_posted_moves,
show_partner_details,
):
domain = [
("display_type", "not in", ["line_note", "line_section"]),
("date", ">=", date_from),
("date", "<=", date_to),
]
if company_id:
domain += [("company_id", "=", company_id)]
if account_ids:
domain += [("account_id", "in", account_ids)]
if journal_ids:
domain += [("journal_id", "in", journal_ids)]
if partner_ids:
domain += [("partner_id", "in", partner_ids)]
if only_posted_moves:
domain += [("move_id.state", "=", "posted")]
else:
domain += [("move_id.state", "in", ["posted", "draft"])]
if show_partner_details:
domain += [
(
"account_id.account_type",
"in",
["asset_receivable", "liability_payable"],
)
]
return domain
def _get_initial_balance_fy_pl_ml_domain(
self,
account_ids,
journal_ids,
partner_ids,
company_id,
fy_start_date,
only_posted_moves,
show_partner_details,
):
accounts_domain = [
("company_id", "=", company_id),
("include_initial_balance", "=", False),
]
if account_ids:
accounts_domain += [("id", "in", account_ids)]
domain = [("date", "<", fy_start_date)]
accounts = self.env["account.account"].search(accounts_domain)
domain += [("account_id", "in", accounts.ids)]
if company_id:
domain += [("company_id", "=", company_id)]
if journal_ids:
domain += [("journal_id", "in", journal_ids)]
if partner_ids:
domain += [("partner_id", "in", partner_ids)]
if only_posted_moves:
domain += [("move_id.state", "=", "posted")]
else:
domain += [("move_id.state", "in", ["posted", "draft"])]
if show_partner_details:
domain += [
(
"account_id.account_type",
"in",
["asset_receivable", "liability_payable"],
)
]
return domain
def _get_pl_initial_balance(
self,
account_ids,
journal_ids,
partner_ids,
company_id,
fy_start_date,
only_posted_moves,
show_partner_details,
foreign_currency,
):
domain = self._get_initial_balance_fy_pl_ml_domain(
account_ids,
journal_ids,
partner_ids,
company_id,
fy_start_date,
only_posted_moves,
show_partner_details,
)
initial_balances = self.env["account.move.line"].read_group(
domain=domain,
fields=["account_id", "balance", "amount_currency:sum"],
groupby=["account_id"],
)
pl_initial_balance = 0.0
pl_initial_currency_balance = 0.0
for initial_balance in initial_balances:
pl_initial_balance += initial_balance["balance"]
if foreign_currency:
pl_initial_currency_balance += round(
initial_balance["amount_currency"], 2
)
return pl_initial_balance, pl_initial_currency_balance
def _get_year_balance_fy_pl_ml_domain(
self,
account_ids,
journal_ids,
partner_ids,
company_id,
date_from,
date_to,
only_posted_moves,
show_partner_details,
):
accounts_domain = [
("company_id", "=", company_id),
("include_initial_balance", "=", False),
]
if account_ids:
accounts_domain += [("id", "in", account_ids)]
domain = [("date", ">=", date_from), ("date", "<=", date_to)]
accounts = self.env["account.account"].search(accounts_domain)
domain += [("account_id", "in", accounts.ids)]
if company_id:
domain += [("company_id", "=", company_id)]
if journal_ids:
domain += [("journal_id", "in", journal_ids)]
if partner_ids:
domain += [("partner_id", "in", partner_ids)]
if only_posted_moves:
domain += [("move_id.state", "=", "posted")]
else:
domain += [("move_id.state", "in", ["posted", "draft"])]
if show_partner_details:
domain += [
(
"account_id.account_type",
"in",
["asset_receivable", "liability_payable"],
)
]
return domain
def _get_pl_year_balance(
self,
account_ids,
journal_ids,
partner_ids,
company_id,
date_from,
date_to,
only_posted_moves,
show_partner_details,
foreign_currency,
):
domain = self._get_year_balance_fy_pl_ml_domain(
account_ids,
journal_ids,
partner_ids,
company_id,
date_from,
date_to,
only_posted_moves,
show_partner_details,
)
year_balances = self.env["account.move.line"].read_group(
domain=domain,
fields=["account_id", "balance", "amount_currency:sum"],
groupby=["account_id"],
)
pl_year_balance = 0.0
pl_year_currency_balance = 0.0
for year_balance in year_balances:
pl_year_balance += year_balance["balance"]
if foreign_currency:
pl_year_currency_balance += round(
year_balance["amount_currency"], 2
)
return pl_year_balance, pl_year_currency_balance
@api.model
def _compute_account_amount(
self, total_amount, tb_initial_acc, tb_period_acc, foreign_currency
):
for tb in tb_period_acc:
acc_id = tb["account_id"][0]
total_amount[acc_id] = self._prepare_total_amount(tb, foreign_currency)
total_amount[acc_id]["credit"] = tb["credit"]
total_amount[acc_id]["debit"] = tb["debit"]
total_amount[acc_id]["balance"] = tb["balance"]
total_amount[acc_id]["initial_balance"] = 0.0
if foreign_currency:
total_amount[acc_id]["initial_currency_balance"] = 0.0
for tb in tb_initial_acc:
acc_id = tb["account_id"]
if acc_id not in total_amount.keys():
total_amount[acc_id] = self._prepare_total_amount(tb, foreign_currency)
else:
total_amount[acc_id]["initial_balance"] = tb["balance"]
total_amount[acc_id]["ending_balance"] += tb["balance"]
if foreign_currency:
total_amount[acc_id]["initial_currency_balance"] = round(
tb["amount_currency"], 2
)
total_amount[acc_id]["ending_currency_balance"] += round(
tb["amount_currency"], 2
)
return total_amount
@api.model
def _prepare_total_amount(self, tb, foreign_currency):
res = {
"credit": 0.0,
"debit": 0.0,
"balance": 0.0,
"initial_balance": tb["balance"],
"ending_balance": tb["balance"],
}
if foreign_currency:
res["initial_currency_balance"] = round(tb["amount_currency"], 2)
res["ending_currency_balance"] = round(tb["amount_currency"], 2)
return res
@api.model
def _compute_acc_prt_amount(
self, total_amount, tb, acc_id, prt_id, foreign_currency
):
# Add keys to dict if not exists
if acc_id not in total_amount:
total_amount[acc_id] = self._prepare_total_amount(tb, foreign_currency)
if prt_id not in total_amount[acc_id]:
total_amount[acc_id][prt_id] = self._prepare_total_amount(
tb, foreign_currency
)
else:
# Increase balance field values
total_amount[acc_id][prt_id]["initial_balance"] = tb["balance"]
total_amount[acc_id][prt_id]["ending_balance"] += tb["balance"]
if foreign_currency:
total_amount[acc_id][prt_id]["initial_currency_balance"] = round(
tb["amount_currency"], 2
)
total_amount[acc_id][prt_id]["ending_currency_balance"] += round(
tb["amount_currency"], 2
)
total_amount[acc_id][prt_id]["partner_name"] = (
tb["partner_id"][1] if tb["partner_id"] else _("Missing Partner")
)
return total_amount
@api.model
def _compute_partner_amount(
self, total_amount, tb_initial_prt, tb_period_prt, foreign_currency
):
partners_ids = set()
partners_data = {}
for tb in tb_period_prt:
acc_id = tb["account_id"][0]
prt_id = tb["partner_id"][0] if tb["partner_id"] else 0
if prt_id not in partners_ids:
partner_name = (
tb["partner_id"][1] if tb["partner_id"] else _("Missing Partner")
)
partners_data.update({prt_id: {"id": prt_id, "name": partner_name}})
total_amount[acc_id][prt_id] = self._prepare_total_amount(
tb, foreign_currency
)
total_amount[acc_id][prt_id]["credit"] = tb["credit"]
total_amount[acc_id][prt_id]["debit"] = tb["debit"]
total_amount[acc_id][prt_id]["balance"] = tb["balance"]
total_amount[acc_id][prt_id]["initial_balance"] = 0.0
total_amount[acc_id][prt_id]["partner_name"] = partners_data[prt_id]["name"]
partners_ids.add(prt_id)
for tb in tb_initial_prt:
acc_id = tb["account_id"][0]
prt_id = tb["partner_id"][0] if tb["partner_id"] else 0
if prt_id not in partners_ids:
partner_name = (
tb["partner_id"][1] if tb["partner_id"] else _("Missing Partner")
)
partners_data.update({prt_id: {"id": prt_id, "name": partner_name}})
total_amount = self._compute_acc_prt_amount(
total_amount, tb, acc_id, prt_id, foreign_currency
)
# sort on partner_name
for acc_id, total_data in total_amount.items():
tmp_list = sorted(
total_data.items(),
key=lambda x: isinstance(x[0], int)
and isinstance(x[1], dict)
and x[1]["partner_name"]
or x[0],
)
total_amount[acc_id] = {}
for key, value in tmp_list:
total_amount[acc_id][key] = value
return total_amount, partners_data
def _remove_accounts_at_cero(self, total_amount, show_partner_details, company):
def is_removable(d):
rounding = company.currency_id.rounding
return (
float_is_zero(d["initial_balance"], precision_rounding=rounding)
and float_is_zero(d["credit"], precision_rounding=rounding)
and float_is_zero(d["debit"], precision_rounding=rounding)
and float_is_zero(d["ending_balance"], precision_rounding=rounding)
)
accounts_to_remove = []
for acc_id, ta_data in total_amount.items():
if is_removable(ta_data):
accounts_to_remove.append(acc_id)
elif show_partner_details:
partner_to_remove = []
for key, value in ta_data.items():
# If the show_partner_details option is checked,
# the partner data is in the same account data dict
# but with the partner id as the key
if isinstance(key, int) and is_removable(value):
partner_to_remove.append(key)
for partner_id in partner_to_remove:
del ta_data[partner_id]
for account_id in accounts_to_remove:
del total_amount[account_id]
_inherit = "report.account_financial_report.trial_balance"
@api.model
def _get_data(
@ -562,25 +146,21 @@ class TrialBalanceReport(models.AbstractModel):
# Adding accounts for year's result
result_profit_account = self.env['account.account'].search([('code', '=', '120000')])
result_loss_account = self.env['account.account'].search([('code', '=', '129000')])
# result_profit_account = self.env['account.account'].search([('code', '=', '120000')])
# result_loss_account = self.env['account.account'].search([('code', '=', '129000')])
unaffected_profit_account = self.env['account.account'].search([('code', '=', '110000')])
unaffected_loss_account = self.env['account.account'].search([('code', '=', '119000')])
if result_profit_account and \
result_loss_account and \
unaffected_profit_account and \
if unaffected_profit_account and \
unaffected_loss_account:
result_profit_id = result_profit_account[0]['id']
result_loss_id = result_loss_account[0]['id']
unaffected_profit_id = unaffected_profit_account[0]['id']
unaffected_loss_id = unaffected_loss_account[0]['id']
if result_profit_id and result_loss_id and \
unaffected_profit_id and unaffected_loss_id:
if unaffected_profit_id and unaffected_loss_id:
#for account_id in [result_profit_id, result_loss_id, unaffected_profit_id, unaffected_loss_id]:
for account_id in [unaffected_profit_id, unaffected_loss_id]:
for account_id in [result_profit_id, result_loss_id, unaffected_profit_id, unaffected_loss_id]:
if account_id not in accounts_ids:
accounts_ids.append(account_id)
total_amount[account_id] = {}
@ -607,21 +187,21 @@ class TrialBalanceReport(models.AbstractModel):
foreign_currency,
)
(
pl_year_balance,
pl_year_currency_balance,
) = self._get_pl_year_balance(
account_ids,
journal_ids,
partner_ids,
company_id,
date_from,
date_to,
only_posted_moves,
show_partner_details,
foreign_currency,
)
_logger.warning("pl_year_balance: %s" % pl_year_balance)
# (
# pl_year_balance,
# pl_year_currency_balance,
# ) = self._get_pl_year_balance(
# account_ids,
# journal_ids,
# partner_ids,
# company_id,
# date_from,
# date_to,
# only_posted_moves,
# show_partner_details,
# foreign_currency,
# )
# _logger.warning("pl_year_balance: %s" % pl_year_balance)
if pl_initial_balance > 0:
@ -644,25 +224,25 @@ class TrialBalanceReport(models.AbstractModel):
total_amount[unaffected_profit_id][
"initial_currency_balance"
] += pl_initial_currency_balance
if pl_year_balance > 0:
total_amount[result_loss_id]["ending_balance"] += pl_year_balance
total_amount[result_loss_id]["debit"] += pl_year_balance
total_amount[result_loss_id]["balance"] += pl_year_balance
if foreign_currency:
total_amount[result_loss_id][
"ending_currency_balance"
] += pl_year_currency_balance
total_amount[result_loss_id][
"initial_currency_balance"
] += pl_year_currency_balance
elif pl_year_balance < 0:
total_amount[result_profit_id]["ending_balance"] += pl_year_balance
total_amount[result_profit_id]["credit"] -= pl_year_balance
total_amount[result_profit_id]["balance"] += pl_year_balance
if foreign_currency:
total_amount[result_profit_id][
"ending_currency_balance"
] += pl_year_currency_balance
# if pl_year_balance > 0:
# total_amount[result_loss_id]["ending_balance"] += pl_year_balance
# total_amount[result_loss_id]["debit"] += pl_year_balance
# total_amount[result_loss_id]["balance"] += pl_year_balance
# if foreign_currency:
# total_amount[result_loss_id][
# "ending_currency_balance"
# ] += pl_year_currency_balance
# total_amount[result_loss_id][
# "initial_currency_balance"
# ] += pl_year_currency_balance
# elif pl_year_balance < 0:
# total_amount[result_profit_id]["ending_balance"] += pl_year_balance
# total_amount[result_profit_id]["credit"] -= pl_year_balance
# total_amount[result_profit_id]["balance"] += pl_year_balance
# if foreign_currency:
# total_amount[result_profit_id][
# "ending_currency_balance"
# ] += pl_year_currency_balance
if hide_account_at_0:
company = self.env["res.company"].browse(company_id)
@ -672,261 +252,4 @@ class TrialBalanceReport(models.AbstractModel):
accounts_data = self._get_accounts_data(accounts_ids)
return total_amount, accounts_data, partners_data
def _get_hierarchy_groups(self, group_ids, groups_data, foreign_currency):
for group_id in group_ids:
parent_id = groups_data[group_id]["parent_id"]
while parent_id:
if parent_id not in groups_data.keys():
group = self.env["account.group"].browse(parent_id)
groups_data[group.id] = {
"id": group.id,
"code": group.code_prefix_start,
"name": group.name,
"parent_id": group.parent_id.id,
"parent_path": group.parent_path,
"complete_code": group.complete_code,
"account_ids": group.compute_account_ids.ids,
"type": "group_type",
"initial_balance": 0,
"debit": 0,
"credit": 0,
"balance": 0,
"ending_balance": 0,
}
if foreign_currency:
groups_data[group.id].update(
initial_currency_balance=0,
ending_currency_balance=0,
)
acc_keys = ["debit", "credit", "balance"]
acc_keys += ["initial_balance", "ending_balance"]
for acc_key in acc_keys:
groups_data[parent_id][acc_key] += groups_data[group_id][acc_key]
if foreign_currency:
groups_data[group_id]["initial_currency_balance"] += groups_data[
group_id
]["initial_currency_balance"]
groups_data[group_id]["ending_currency_balance"] += groups_data[
group_id
]["ending_currency_balance"]
parent_id = groups_data[parent_id]["parent_id"]
return groups_data
def _get_groups_data(self, accounts_data, total_amount, foreign_currency):
accounts_ids = list(accounts_data.keys())
accounts = self.env["account.account"].browse(accounts_ids)
account_group_relation = {}
for account in accounts:
accounts_data[account.id]["complete_code"] = (
account.group_id.complete_code + " / " + account.code
if account.group_id.id
else ""
)
if account.group_id.id:
if account.group_id.id not in account_group_relation.keys():
account_group_relation.update({account.group_id.id: [account.id]})
else:
account_group_relation[account.group_id.id].append(account.id)
groups = self.env["account.group"].browse(account_group_relation.keys())
groups_data = {}
for group in groups:
groups_data.update(
{
group.id: {
"id": group.id,
"code": group.code_prefix_start,
"name": group.name,
"parent_id": group.parent_id.id,
"parent_path": group.parent_path,
"type": "group_type",
"complete_code": group.complete_code,
"account_ids": group.compute_account_ids.ids,
"initial_balance": 0.0,
"credit": 0.0,
"debit": 0.0,
"balance": 0.0,
"ending_balance": 0.0,
}
}
)
if foreign_currency:
groups_data[group.id]["initial_currency_balance"] = 0.0
groups_data[group.id]["ending_currency_balance"] = 0.0
for group_id in account_group_relation.keys():
for account_id in account_group_relation[group_id]:
groups_data[group_id]["initial_balance"] += total_amount[account_id][
"initial_balance"
]
groups_data[group_id]["debit"] += total_amount[account_id]["debit"]
groups_data[group_id]["credit"] += total_amount[account_id]["credit"]
groups_data[group_id]["balance"] += total_amount[account_id]["balance"]
groups_data[group_id]["ending_balance"] += total_amount[account_id][
"ending_balance"
]
if foreign_currency:
groups_data[group_id]["initial_currency_balance"] += total_amount[
account_id
]["initial_currency_balance"]
groups_data[group_id]["ending_currency_balance"] += total_amount[
account_id
]["ending_currency_balance"]
group_ids = list(groups_data.keys())
groups_data = self._get_hierarchy_groups(
group_ids,
groups_data,
foreign_currency,
)
return groups_data
def _get_computed_groups_data(self, accounts_data, total_amount, foreign_currency):
groups = self.env["account.group"].search([("id", "!=", False)])
groups_data = {}
for group in groups:
len_group_code = len(group.code_prefix_start)
groups_data.update(
{
group.id: {
"id": group.id,
"code": group.code_prefix_start,
"name": group.name,
"parent_id": group.parent_id.id,
"parent_path": group.parent_path,
"type": "group_type",
"complete_code": group.complete_code,
"account_ids": group.compute_account_ids.ids,
"initial_balance": 0.0,
"credit": 0.0,
"debit": 0.0,
"balance": 0.0,
"ending_balance": 0.0,
}
}
)
if foreign_currency:
groups_data[group.id]["initial_currency_balance"] = 0.0
groups_data[group.id]["ending_currency_balance"] = 0.0
for account in accounts_data.values():
if group.code_prefix_start == account["code"][:len_group_code]:
acc_id = account["id"]
group_id = group.id
groups_data[group_id]["initial_balance"] += total_amount[acc_id][
"initial_balance"
]
groups_data[group_id]["debit"] += total_amount[acc_id]["debit"]
groups_data[group_id]["credit"] += total_amount[acc_id]["credit"]
groups_data[group_id]["balance"] += total_amount[acc_id]["balance"]
groups_data[group_id]["ending_balance"] += total_amount[acc_id][
"ending_balance"
]
if foreign_currency:
groups_data[group_id][
"initial_currency_balance"
] += total_amount[acc_id]["initial_currency_balance"]
groups_data[group_id][
"ending_currency_balance"
] += total_amount[acc_id]["ending_currency_balance"]
return groups_data
def _get_report_values(self, docids, data):
show_partner_details = data["show_partner_details"]
wizard_id = data["wizard_id"]
company = self.env["res.company"].browse(data["company_id"])
company_id = data["company_id"]
partner_ids = data["partner_ids"]
journal_ids = data["journal_ids"]
account_ids = data["account_ids"]
date_to = data["date_to"]
date_from = data["date_from"]
hide_account_at_0 = data["hide_account_at_0"]
show_hierarchy = data["show_hierarchy"]
show_hierarchy_level = data["show_hierarchy_level"]
foreign_currency = data["foreign_currency"]
only_posted_moves = data["only_posted_moves"]
unaffected_earnings_account = data["unaffected_earnings_account"]
_logger.warning("unaffected_earnings_account: %s" % unaffected_earnings_account)
fy_start_date = data["fy_start_date"]
total_amount, accounts_data, partners_data = self._get_data(
account_ids,
journal_ids,
partner_ids,
company_id,
date_to,
date_from,
foreign_currency,
only_posted_moves,
show_partner_details,
hide_account_at_0,
unaffected_earnings_account,
fy_start_date,
)
trial_balance = []
if not show_partner_details:
for account_id in accounts_data.keys():
accounts_data[account_id].update(
{
"initial_balance": total_amount[account_id]["initial_balance"],
"credit": total_amount[account_id]["credit"],
"debit": total_amount[account_id]["debit"],
"balance": total_amount[account_id]["balance"],
"ending_balance": total_amount[account_id]["ending_balance"],
"type": "account_type",
}
)
if foreign_currency:
accounts_data[account_id].update(
{
"ending_currency_balance": total_amount[account_id][
"ending_currency_balance"
],
"initial_currency_balance": total_amount[account_id][
"initial_currency_balance"
],
}
)
if show_hierarchy:
groups_data = self._get_groups_data(
accounts_data, total_amount, foreign_currency
)
trial_balance = list(groups_data.values())
trial_balance += list(accounts_data.values())
trial_balance = sorted(trial_balance, key=lambda k: k["complete_code"])
for trial in trial_balance:
counter = trial["complete_code"].count("/")
trial["level"] = counter
else:
trial_balance = list(accounts_data.values())
trial_balance = sorted(trial_balance, key=lambda k: k["code"])
else:
if foreign_currency:
for account_id in accounts_data.keys():
total_amount[account_id]["currency_id"] = accounts_data[account_id][
"currency_id"
]
total_amount[account_id]["currency_name"] = accounts_data[
account_id
]["currency_name"]
return {
"doc_ids": [wizard_id],
"doc_model": "trial.balance.report.wizard",
"docs": self.env["trial.balance.report.wizard"].browse(wizard_id),
"foreign_currency": data["foreign_currency"],
"company_name": company.display_name,
"company_currency": company.currency_id,
"currency_name": company.currency_id.name,
"date_from": data["date_from"],
"date_to": data["date_to"],
"only_posted_moves": data["only_posted_moves"],
"hide_account_at_0": data["hide_account_at_0"],
"show_partner_details": data["show_partner_details"],
"limit_hierarchy_level": data["limit_hierarchy_level"],
"show_hierarchy": show_hierarchy,
"hide_parent_hierarchy_level": data["hide_parent_hierarchy_level"],
"trial_balance": trial_balance,
"total_amount": total_amount,
"accounts_data": accounts_data,
"partners_data": partners_data,
"show_hierarchy_level": show_hierarchy_level,
"currency_model": self.env["res.currency"],
}
return total_amount, accounts_data, partners_data

View File

@ -1,3 +1,17 @@
# Copyright 2013-2020 Akretion France (http://www.akretion.com)
# @author: Alexis de Lattre <alexis.delattre@akretion.com>
# Copyright 2016-2020 Odoo SA (https://www.odoo.com/fr_FR/)
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
# This module is a fork of l10n_fr_fec from official addons
# (which itself was copied from OCA with my authorisation)
# The construction of SQL requests don't respect pylint E8103
# The problem is that fixing this would require large changes in the code
# which would make this module a deeper fork of l10n_fr_fec
# and would make it more difficult to compare the 2 modules and port
# changes/improvements between each other
# pylint: skip-file
import base64
import csv
import logging
@ -14,84 +28,10 @@ try:
except ImportError:
logger.debug("Cannot import unidecode")
class AccountFrFecGn(models.TransientModel):
class AccountFrFecOca(models.TransientModel):
_inherit = "account.fr.fec.oca"
def _do_query_year_earnings(self):
"""Compute the sum of ending balances for all accounts that are
of a type that does not bring forward the balance in new fiscal years.
This is needed because we have to display only one line for the initial
balance of all expense/revenue accounts in the FEC.
"""
# BENEFIT and LOSS
sql_query = """
SELECT
'CLO' AS JournalCode,
'Balance finale' AS JournalLib,
'CLOTURE/' || %(formatted_date_year)s AS EcritureNum,
%(formatted_date_to)s AS EcritureDate,
'120000' AS CompteNum,
E'Résultat de l\\'exercice (Bénéfice)' AS CompteLib,
'' AS CompAuxNum,
'' AS CompAuxLib,
'-' AS PieceRef,
%(formatted_date_to)s AS PieceDate,
'Clôture de l exercice' AS EcritureLib,
replace(
CASE WHEN COALESCE(sum(aml.balance), 0) <= 0
THEN '0,00'
ELSE to_char(SUM(aml.balance), '000000000000000D99')
END, '.', ',') AS Debit,
replace(
CASE WHEN COALESCE(sum(aml.balance), 0) >= 0
THEN '0,00'
ELSE to_char(-SUM(aml.balance), '000000000000000D99')
END, '.', ',') AS Credit,
'' AS EcritureLet,
'' AS DateLet,
%(formatted_date_to)s AS ValidDate,
'' AS Montantdevise,
'' AS Idevise
FROM
account_move_line aml
LEFT JOIN account_move am ON am.id = aml.move_id
JOIN account_account aa ON aa.id = aml.account_id
WHERE
am.date >= %(date_from)s
AND am.date <= %(date_to)s
AND am.company_id = %(company_id)s
AND aa.include_initial_balance IS NOT true
AND (aml.debit != 0 OR aml.credit != 0)
"""
# For official report: only use posted entries
if self.export_type == "official":
sql_query += " AND am.state = 'posted' "
else:
sql_query += " AND am.state IN ('draft', 'posted') "
company = self.company_id
formatted_date_to = fields.Date.to_string(self.date_to).replace("-", "")
date_from = self.date_from
date_to = self.date_to
formatted_date_year = date_to.year
self._cr.execute(
sql_query,
{
"formatted_date_year": formatted_date_year,
"formatted_date_to": formatted_date_to,
"date_from": self.date_from,
"date_to": self.date_to,
"company_id": company.id,
},
)
listrow = []
row = self._cr.fetchone()
listrow = list(row)
# Hack to replace 120 by 129 when it's a loss
if listrow[11] != "0,00" and listrow[12] == "0,00" and listrow[4] == "120000":
listrow[4] = "129000"
listrow[5] = "Résultat de l'exercice (perte)"
return listrow
def _do_query_unaffected_earnings(self):
"""Compute the sum of ending balances for all accounts that are
of a type that does not bring forward the balance in new fiscal years.
@ -105,8 +45,8 @@ class AccountFrFecGn(models.TransientModel):
'Balance initiale' AS JournalLib,
'OUVERTURE/' || %(formatted_date_year)s AS EcritureNum,
%(formatted_date_from)s AS EcritureDate,
'110000' AS CompteNum,
E'Report à nouveau (Crédit)' AS CompteLib,
'999999' AS CompteNum,
E'Bénéfice ou perte de l\\'année en cours' AS CompteLib,
'' AS CompAuxNum,
'' AS CompAuxLib,
'-' AS PieceRef,
@ -158,182 +98,12 @@ class AccountFrFecGn(models.TransientModel):
listrow = []
row = self._cr.fetchone()
listrow = list(row)
# Hack to replace 110 by 119 when it's a loss
if listrow[11] != "0,00" and listrow[12] == "0,00" and listrow[4] == "110000":
listrow[4] = "119000"
listrow[5] = "Report à nouveau (perte)"
# Hack to replace 120 by 129 when it's a loss
# if listrow[11] != "0,00" and listrow[12] == "0,00" and listrow[4] == "110000":
# listrow[4] = "119000"
# listrow[5] = "Report à nouveau (perte)"
return listrow
def _get_aux_fields(self, sql_args):
aux_dict = {
"auxlib": """
COALESCE(REGEXP_REPLACE(replace(rp.name, '|', '/'), '[\\t\\r\\n]', ' ', 'g'), '')
"""
}
if self.partner_identifier == "ref":
aux_dict[
"auxnum"
] = """
CASE WHEN rp.ref IS null OR rp.ref = ''
THEN COALESCE('ID' || rp.id, '')
ELSE REGEXP_REPLACE(replace(rp.ref, '|', '/'), '[\\t\\r\\n]', ' ', 'g')
END
"""
else:
aux_dict["auxnum"] = """rp.id::text"""
if self.partner_option == "receivable_payable":
aux_sql = (
"""
CASE WHEN aa.account_type IN ('asset_receivable', 'liability_payable', 'expense', 'income')
THEN %(auxnum)s
ELSE ''
END
AS CompAuxNum,
CASE WHEN aa.account_type IN ('asset_receivable', 'liability_payable', 'expense', 'income')
THEN %(auxlib)s
ELSE ''
END
AS CompAuxLib,
"""
% aux_dict
)
elif self.partner_option == "accounts":
sql_args["partner_account_ids"] = tuple(self.partner_account_ids.ids)
aux_sql = (
"""
CASE WHEN aa.id IN %%(partner_account_ids)s
THEN %(auxnum)s
ELSE ''
END
AS CompAuxNum,
CASE WHEN aa.id IN %%(partner_account_ids)s
THEN %(auxlib)s
ELSE ''
END
AS CompAuxLib,
"""
% aux_dict
)
else:
aux_sql = (
"""
%(auxnum)s AS CompAuxNum, %(auxlib)s AS CompAuxLib,
"""
% aux_dict
)
return aux_sql
def _do_reverse_balances_for_closing(self):
# CLOSING BALANCE - expense/income
company = self.company_id
formatted_date_to = fields.Date.to_string(self.date_to).replace("-", "")
date_from = self.date_from
date_to = self.date_to
formatted_date_year = date_to.year
currency_digits = 2
sql_args = { # Use for the 2 INITIAL BALANCEs and for LINES
"formatted_date_year": formatted_date_year,
"formatted_date_to": formatted_date_to,
"date_from": date_from,
"date_to": date_to,
"company_id": company.id,
"currency_digits": currency_digits,
}
aux_fields = self._get_aux_fields(sql_args)
sql_query = (
"""
SELECT
'CLO' AS JournalCode,
'Balance finale' AS JournalLib,
'CLOTURE/' || %(formatted_date_year)s AS EcritureNum,
%(formatted_date_to)s AS EcritureDate,
MIN(aa.code) AS CompteNum,
replace(MIN(aa.name), '|', '/') AS CompteLib,
"""
+ aux_fields
+ """
'-' AS PieceRef,
%(formatted_date_to)s AS PieceDate,
'Clôture de l exercice' AS EcritureLib,
replace(
CASE WHEN sum(aml.balance) >= 0
THEN '0,00'
ELSE to_char(-SUM(aml.balance), '000000000000000D99')
END, '.', ',') AS Debit,
replace(
CASE WHEN sum(aml.balance) <= 0
THEN '0,00'
ELSE to_char(SUM(aml.balance), '000000000000000D99')
END, '.', ',') AS Credit,
'' AS EcritureLet,
'' AS DateLet,
%(formatted_date_to)s AS ValidDate,
'' AS Montantdevise,
'' AS Idevise,
MIN(aa.id) AS CompteID
FROM
account_move_line aml
LEFT JOIN account_move am ON am.id=aml.move_id
LEFT JOIN res_partner rp ON rp.id=aml.partner_id
JOIN account_account aa ON aa.id = aml.account_id
WHERE
am.date >= %(date_from)s
AND am.date <= %(date_to)s
AND am.company_id = %(company_id)s
AND (aml.debit != 0 OR aml.credit != 0)
"""
)
# For official report: only use posted entries
if self.export_type == "official":
sql_query += " AND am.state = 'posted' "
else:
sql_query += " AND am.state IN ('draft', 'posted') "
sql_query_expenses = sql_query
sql_query_expenses += """
GROUP BY aml.account_id, aa.account_type, rp.ref, rp.id
HAVING round(sum(aml.balance), %(currency_digits)s) != 0
AND aa.account_type = 'expense'
"""
self._cr.execute(sql_query_expenses, sql_args)
rows_to_write = []
for row in self._cr.fetchall():
listrow = list(row)
account_id = listrow.pop()
rows_to_write.append(listrow)
sql_query_income = sql_query
sql_query_income += """
GROUP BY aml.account_id, aa.account_type, rp.ref, rp.id
HAVING round(sum(aml.balance), %(currency_digits)s) != 0
AND aa.account_type = 'income'
"""
self._cr.execute(sql_query_income, sql_args)
for row in self._cr.fetchall():
listrow = list(row)
account_id = listrow.pop()
rows_to_write.append(listrow)
return rows_to_write
def _get_siren(self, company):
# Get SIREN from SIRET and not from VAT
# so that it also work on companies that are not subject to VAT
if not company.siret:
raise UserError(_("Missing SIRET on company %s.") % company.display_name)
siren = company.siret[:9]
return siren
# flake8: noqa: C901
def generate_fec(self):
self.ensure_one()
@ -354,8 +124,6 @@ class AccountFrFecGn(models.TransientModel):
company = self.company_id
### HEADER
header = [
"JournalCode", # 0
"JournalLib", # 1
@ -378,9 +146,7 @@ class AccountFrFecGn(models.TransientModel):
]
rows_to_write = [header]
### END HEADER
### UNAFFECTED_EARNINGS IN OUVERTURE
unaffected_earnings_account = self.env["account.account"].search(
[
("account_type", "=", "equity_unaffected"),
@ -396,7 +162,6 @@ class AccountFrFecGn(models.TransientModel):
# initial balance of the current year earnings account
unaffected_earnings_results = self._do_query_unaffected_earnings()
unaffected_earnings_line = False
### END UNAFFECTED_EARNINGS IN OUVERTURE
# INITIAL BALANCE other than payable/receivable
sql_query = """
@ -477,6 +242,7 @@ class AccountFrFecGn(models.TransientModel):
# of each fiscal year, because benefit or loss
# is supposed to be re-affected by the general assembly
# during the year
logger.warning("found line with unaffected")
unaffected_earnings_line = True
current_amount = float(listrow[11].replace(",", ".")) - float(
listrow[12].replace(",", ".")
@ -487,12 +253,17 @@ class AccountFrFecGn(models.TransientModel):
listrow_amount = current_amount + unaffected_earnings_amount
if float_is_zero(listrow_amount, precision_digits=currency_digits):
continue
logger.warning("listrow amount %s" % listrow_amount)
if listrow_amount > 0:
listrow[11] = str(listrow_amount).replace(".", ",")
listrow[12] = "0,00"
listrow[4] = "119000"
listrow[5] = "Report à nouveau (Perte)"
else:
listrow[11] = "0,00"
listrow[12] = str(-listrow_amount).replace(".", ",")
listrow[4] = "110000"
listrow[5] = "Report à nouveau (Bénéfice)"
rows_to_write.append(listrow)
# if the unaffected earnings account wasn't in the selection yet:
@ -514,12 +285,16 @@ class AccountFrFecGn(models.TransientModel):
limit=1,
)
# We comment this section so we keep using 120 and 129 instead of 999 account for earnings
if float(unaffected_earnings_results[11].replace(",", ".")) > 0:
unaffected_earnings_results[4] = "119000"
unaffected_earnings_results[5] = "Report à nouveau (Perte)"
elif float(unaffected_earnings_results[12].replace(",", ".")) > 0:
unaffected_earnings_results[4] = "110000"
unaffected_earnings_results[5] = "Report à nouveau (Bénéfice)"
# if unaffected_earnings_account:
# unaffected_earnings_results[4] = unaffected_earnings_account.code
# unaffected_earnings_results[5] = unaffected_earnings_account.name
rows_to_write.append(unaffected_earnings_results)
rows_to_write.append(unaffected_earnings_results)
aux_fields = self._get_aux_fields(sql_args)
@ -586,7 +361,6 @@ class AccountFrFecGn(models.TransientModel):
for row in self._cr.fetchall():
listrow = list(row)
account_id = listrow.pop()
rows_to_write.append(listrow)
# LINES
@ -675,20 +449,18 @@ class AccountFrFecGn(models.TransientModel):
self._cr.execute(sql_query, sql_args)
for row in self._cr.fetchall():
listrow = list(row)
if listrow[4] == "999999":
if float(unaffected_earnings_results[11].replace(",", ".")) > float(0):
listrow[4] = "119000"
listrow[5] = "Report à nouveau (Perte)"
elif float(unaffected_earnings_results[12].replace(",", ".")) > float(0):
listrow[4] = "110000"
listrow[5] = "Report à nouveau (Bénéfice)"
row = tuple(listrow)
rows_to_write.append(list(row))
# Create Closing move
year_earning_results = self._do_query_year_earnings()
rows_to_write.append(year_earning_results)
reversed_balance_lines = self._do_reverse_balances_for_closing()
for row in reversed_balance_lines:
rows_to_write.append(row)
# End Closing Move
fecvalue = self._csv_write_rows(rows_to_write)
end_date = fields.Date.to_string(self.date_to).replace("-", "")
suffix = ""
@ -714,4 +486,4 @@ class AccountFrFecGn(models.TransientModel):
% (self._name, self.id, self.filename),
"target": "self",
}
return action
return action