Initial commit: OCA Financial packages (186 packages)

This commit is contained in:
Ernad Husremovic 2025-08-29 15:43:04 +02:00
commit 3e0e8473fb
8757 changed files with 947473 additions and 0 deletions

View file

@ -0,0 +1,7 @@
from . import report_statement_common
from . import activity_statement
from . import detailed_activity_statement
from . import outstanding_statement
from . import activity_statement_xlsx
from . import detailed_activity_statement_xlsx
from . import outstanting_statement_xlsx

View file

@ -0,0 +1,375 @@
# Copyright 2018 ForgeFlow, S.L. (https://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from collections import defaultdict
from odoo import _, api, models
from .outstanding_statement import OutstandingStatement
class ActivityStatement(models.AbstractModel):
"""Model of Activity Statement"""
_inherit = "statement.common"
_name = "report.partner_statement.activity_statement"
_description = "Partner Activity Statement"
def _get_title(self, partner, **kwargs):
kwargs["context"] = {
"lang": partner.lang,
}
if kwargs.get("is_detailed"):
if kwargs.get("account_type") == "receivable":
title = _(
"Detailed Statement "
"between %(starting_date)s and %(ending_date)s "
"in %(currency)s",
**kwargs,
)
else:
title = _(
"Detailed Supplier Statement "
"between %(starting_date)s and %(ending_date)s "
"in %(currency)s",
**kwargs,
)
else:
if kwargs.get("account_type") == "receivable":
title = _(
"Statement between %(starting_date)s and %(ending_date)s in %(currency)s",
**kwargs,
)
else:
title = _(
"Supplier Statement "
"between %(starting_date)s and %(ending_date)s "
"in %(currency)s",
**kwargs,
)
return title
def _initial_balance_sql_q1(self, partners, date_start, account_type):
excluded_accounts_ids = tuple(
self.env.context.get("excluded_accounts_ids", [])
) or (-1,)
return str(
self._cr.mogrify(
"""
SELECT l.partner_id, l.currency_id, l.company_id, l.id,
CASE WHEN l.balance > 0.0
THEN l.balance - sum(coalesce(pd.amount, 0.0))
ELSE l.balance + sum(coalesce(pc.amount, 0.0))
END AS open_amount,
CASE WHEN l.balance > 0.0
THEN l.amount_currency - sum(coalesce(pd.debit_amount_currency, 0.0))
ELSE l.amount_currency + sum(coalesce(pc.credit_amount_currency, 0.0))
END AS open_amount_currency
FROM account_move_line l
JOIN account_account aa ON (aa.id = l.account_id)
JOIN account_move m ON (l.move_id = m.id)
LEFT JOIN (SELECT pr.*
FROM account_partial_reconcile pr
INNER JOIN account_move_line l2
ON pr.credit_move_id = l2.id
WHERE l2.date < %(date_start)s
) as pd ON pd.debit_move_id = l.id
LEFT JOIN (SELECT pr.*
FROM account_partial_reconcile pr
INNER JOIN account_move_line l2
ON pr.debit_move_id = l2.id
WHERE l2.date < %(date_start)s
) as pc ON pc.credit_move_id = l.id
WHERE l.partner_id IN %(partners)s
AND aa.id not in %(excluded_accounts_ids)s
AND l.date < %(date_start)s AND not l.blocked
AND m.state IN ('posted')
AND aa.account_type = %(account_type)s
AND (
(pd.id IS NOT NULL AND
pd.max_date < %(date_start)s) OR
(pc.id IS NOT NULL AND
pc.max_date < %(date_start)s) OR
(pd.id IS NULL AND pc.id IS NULL)
)
GROUP BY l.partner_id, l.currency_id, l.company_id, l.balance, l.id
""",
locals(),
),
"utf-8",
)
def _initial_balance_sql_q2(self, sub):
return str(
self._cr.mogrify(
f"""
SELECT {sub}.partner_id, {sub}.currency_id,
sum(CASE WHEN {sub}.currency_id is not null
THEN {sub}.open_amount_currency
ELSE {sub}.open_amount
END) as balance, {sub}.company_id
FROM {sub}
GROUP BY {sub}.partner_id, {sub}.currency_id, {sub}.company_id""",
locals(),
),
"utf-8",
)
def _initial_balance_sql_q3(self, sub, company_id):
return str(
self._cr.mogrify(
f"""
SELECT {sub}.partner_id, {sub}.balance,
COALESCE({sub}.currency_id, c.currency_id) AS currency_id
FROM {sub}
JOIN res_company c ON (c.id = {sub}.company_id)
WHERE c.id = %(company_id)s""",
locals(),
),
"utf-8",
)
def _get_account_initial_balance(
self, company_id, partner_ids, date_start, account_type
):
balance_start = defaultdict(list)
partners = tuple(partner_ids)
# pylint: disable=E8103
self.env.cr.execute(
"""WITH Q1 AS (%s),
Q2 AS (%s),
Q3 AS (%s)
SELECT partner_id, currency_id, sum(balance) as balance
FROM Q3
GROUP BY partner_id, currency_id"""
% (
self._initial_balance_sql_q1(partners, date_start, account_type),
self._initial_balance_sql_q2("Q1"),
self._initial_balance_sql_q3("Q2", company_id),
)
)
for row in self.env.cr.dictfetchall():
balance_start[row.pop("partner_id")].append(row)
return balance_start
def _display_activity_lines_sql_q1(
self, partners, date_start, date_end, account_type
):
excluded_accounts_ids = tuple(
self.env.context.get("excluded_accounts_ids", [])
) or (-1,)
show_only_overdue = self.env.context.get("show_only_overdue", False)
payment_ref = _("Payment")
return str(
self._cr.mogrify(
"""
SELECT m.name AS move_id, l.partner_id, l.date,
array_agg(l.id ORDER BY l.id) as ids,
CASE WHEN (aj.type IN ('sale', 'purchase'))
THEN l.name
ELSE '/'
END as name,
CASE
WHEN (aj.type IN ('sale', 'purchase')) AND l.name IS NOT NULL
THEN l.ref
WHEN (aj.type in ('bank', 'cash'))
THEN %(payment_ref)s
ELSE m.ref
END as case_ref,
l.blocked, l.currency_id, l.company_id,
sum(CASE WHEN (l.currency_id is not null AND l.amount_currency > 0.0)
THEN l.amount_currency
ELSE l.debit
END) as debit,
sum(CASE WHEN (l.currency_id is not null AND l.amount_currency < 0.0)
THEN l.amount_currency * (-1)
ELSE l.credit
END) as credit,
CASE WHEN l.date_maturity is null
THEN l.date
ELSE l.date_maturity
END as date_maturity
FROM account_move_line l
JOIN account_account aa ON (aa.id = l.account_id)
JOIN account_move m ON (l.move_id = m.id)
JOIN account_journal aj ON (l.journal_id = aj.id)
WHERE l.partner_id IN %(partners)s
AND aa.id not in %(excluded_accounts_ids)s
AND %(date_start)s <= l.date
AND l.date <= %(date_end)s
AND m.state IN ('posted')
AND aa.account_type = %(account_type)s
AND CASE
WHEN %(show_only_overdue)s
THEN COALESCE(l.date_maturity, l.date) <= %(date_end)s
ELSE TRUE
END
GROUP BY l.partner_id, m.name, l.date, l.date_maturity,
CASE WHEN (aj.type IN ('sale', 'purchase'))
THEN l.name
ELSE '/'
END, case_ref, l.blocked, l.currency_id, l.company_id
""",
locals(),
),
"utf-8",
)
def _display_activity_lines_sql_q2(self, sub, company_id):
return str(
self._cr.mogrify(
f"""
SELECT {sub}.partner_id, {sub}.move_id, {sub}.date, {sub}.date_maturity,
{sub}.name, {sub}.case_ref as ref, {sub}.debit, {sub}.credit, {sub}.ids,
{sub}.debit-{sub}.credit as amount, {sub}.blocked,
COALESCE({sub}.currency_id, c.currency_id) AS currency_id
FROM {sub}
JOIN res_company c ON (c.id = {sub}.company_id)
WHERE c.id = %(company_id)s
""",
locals(),
),
"utf-8",
)
def _get_account_display_lines(
self, company_id, partner_ids, date_start, date_end, account_type
):
res = dict(map(lambda x: (x, []), partner_ids))
partners = tuple(partner_ids)
# pylint: disable=E8103
self.env.cr.execute(
"""
WITH Q1 AS (%s),
Q2 AS (%s)
SELECT partner_id, move_id, date, date_maturity, ids,
COALESCE(name, '') as name, COALESCE(ref, '') as ref,
debit, credit, amount, blocked, currency_id
FROM Q2
ORDER BY date, date_maturity, move_id"""
% (
self._display_activity_lines_sql_q1(
partners, date_start, date_end, account_type
),
self._display_activity_lines_sql_q2("Q1", company_id),
)
)
for row in self.env.cr.dictfetchall():
res[row.pop("partner_id")].append(row)
return res
def _display_activity_reconciled_lines_sql_q1(self, sub):
return str(
self._cr.mogrify(
f"""
SELECT unnest(ids) as id
FROM {sub}
""",
locals(),
),
"utf-8",
)
def _display_activity_reconciled_lines_sql_q2(self, sub, date_end):
return str(
self._cr.mogrify(
f"""
SELECT l.id as rel_id, m.name AS move_id, l.partner_id, l.date, l.name,
l.blocked, l.currency_id, l.company_id, {sub}.id,
CASE WHEN l.ref IS NOT NULL
THEN l.ref
ELSE m.ref
END as ref,
CASE WHEN (l.currency_id is not null AND l.amount_currency > 0.0)
THEN avg(l.amount_currency)
ELSE avg(l.debit)
END as debit,
CASE WHEN (l.currency_id is not null AND l.amount_currency < 0.0)
THEN avg(l.amount_currency * (-1))
ELSE avg(l.credit)
END as credit,
CASE WHEN l.balance > 0.0
THEN sum(coalesce(pc.amount, 0.0))
ELSE -sum(coalesce(pd.amount, 0.0))
END AS open_amount,
CASE WHEN l.balance > 0.0
THEN sum(coalesce(pc.debit_amount_currency, 0.0))
ELSE -sum(coalesce(pd.credit_amount_currency, 0.0))
END AS open_amount_currency,
CASE WHEN l.date_maturity is null
THEN l.date
ELSE l.date_maturity
END as date_maturity
FROM {sub}
LEFT JOIN account_partial_reconcile pd ON (
pd.debit_move_id = {sub}.id AND pd.max_date <= %(date_end)s)
LEFT JOIN account_partial_reconcile pc ON (
pc.credit_move_id = {sub}.id AND pc.max_date <= %(date_end)s)
LEFT JOIN account_move_line l ON (
pd.credit_move_id = l.id OR pc.debit_move_id = l.id)
LEFT JOIN account_move m ON (l.move_id = m.id)
WHERE l.date <= %(date_end)s AND m.state IN ('posted')
GROUP BY l.id, l.partner_id, m.name, l.date, l.date_maturity, l.name,
CASE WHEN l.ref IS NOT NULL
THEN l.ref
ELSE m.ref
END, {sub}.id,
l.blocked, l.currency_id, l.balance, l.amount_currency, l.company_id
""",
locals(),
),
"utf-8",
)
def _get_account_display_reconciled_lines(
self, company_id, partner_ids, date_start, date_end, account_type
):
partners = tuple(partner_ids)
# pylint: disable=E8103
self.env.cr.execute(
"""
WITH Q1 AS (%s),
Q2 AS (%s),
Q3 AS (%s),
Q4 AS (%s),
Q5 AS (%s),
Q6 AS (%s)
SELECT partner_id, currency_id, move_id, date, date_maturity, debit,
credit, amount, open_amount, COALESCE(name, '') as name,
COALESCE(ref, '') as ref, blocked, id
FROM Q6
ORDER BY date, date_maturity, move_id"""
% (
self._display_activity_lines_sql_q1(
partners, date_start, date_end, account_type
),
self._display_activity_lines_sql_q2("Q1", company_id),
self._display_activity_reconciled_lines_sql_q1("Q2"),
self._display_activity_reconciled_lines_sql_q2("Q3", date_end),
self._display_outstanding_lines_sql_q2("Q4"),
self._display_outstanding_lines_sql_q3("Q5", company_id),
)
)
return self.env.cr.dictfetchall()
@api.model
def _get_report_values(self, docids, data=None):
if not data:
data = {}
if "company_id" not in data:
wiz = self.env["activity.statement.wizard"].with_context(
active_ids=docids, model="res.partner"
)
data.update(wiz.create({})._prepare_statement())
data["amount_field"] = "amount"
return super()._get_report_values(docids, data)
ActivityStatement._display_outstanding_lines_sql_q2 = (
OutstandingStatement._display_outstanding_lines_sql_q2
)
ActivityStatement._display_outstanding_lines_sql_q3 = (
OutstandingStatement._display_outstanding_lines_sql_q3
)

View file

@ -0,0 +1,458 @@
# Author: Christopher Ormaza
# Copyright 2021 ForgeFlow S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import _, models
from odoo.addons.report_xlsx_helper.report.report_xlsx_format import FORMATS
def copy_format(book, fmt):
properties = [f[4:] for f in dir(fmt) if f[0:4] == "set_"]
dft_fmt = book.add_format()
return book.add_format(
{
k: v
for k, v in fmt.__dict__.items()
if k in properties and dft_fmt.__dict__[k] != v
}
)
class ActivityStatementXslx(models.AbstractModel):
_name = "report.p_s.report_activity_statement_xlsx"
_description = "Activity Statement XLSL Report"
_inherit = "report.report_xlsx.abstract"
def _get_report_name(self, report, data=False):
company_id = data.get("company_id", False)
report_name = _("Activity Statement")
if company_id:
company = self.env["res.company"].browse(company_id)
suffix = " - {} - {}".format(company.name, company.currency_id.name)
report_name = report_name + suffix
return report_name
def _get_currency_header_row_data(self, partner, currency, data):
return (
[
{
"col_pos": col_pos,
"sheet_func": "write",
"args": args,
}
for col_pos, args in enumerate(
[
(
_("Reference Number"),
FORMATS["format_theader_yellow_center"],
),
(_("Date"), FORMATS["format_theader_yellow_center"]),
]
)
]
+ [
{
"col_pos": 2,
"sheet_func": "merge_range",
"span": 1,
"args": (_("Description"), FORMATS["format_theader_yellow_center"]),
},
]
+ [
{
"col_pos": col_pos,
"sheet_func": "write",
"args": args,
}
for col_pos, args in enumerate(
[
(_("Original Amount"), FORMATS["format_theader_yellow_center"]),
(_("Applied Amount"), FORMATS["format_theader_yellow_center"]),
(_("Open Amount"), FORMATS["format_theader_yellow_center"]),
],
4,
)
]
)
def _get_currency_subheader_row_data(self, partner, currency, data):
partner_data = data.get("data", {}).get(partner.id, {})
currency_data = partner_data.get("currencies", {}).get(currency.id)
return [
{
"col_pos": 1,
"sheet_func": "write",
"args": (
partner_data.get("prior_day"),
FORMATS["format_tcell_date_left"],
),
},
{
"col_pos": 2,
"sheet_func": "merge_range",
"span": 3,
"args": (_("Balance Forward"), FORMATS["format_tcell_left"]),
},
{
"col_pos": 6,
"sheet_func": "write",
"args": (
currency_data.get("balance_forward"),
FORMATS["current_money_format"],
),
},
]
def _get_currency_line_row_data(self, partner, currency, data, line):
if line.get("blocked"):
format_tcell_left = FORMATS["format_tcell_left_blocked"]
format_tcell_date_left = FORMATS["format_tcell_date_left_blocked"]
format_distributed = FORMATS["format_distributed_blocked"]
current_money_format = FORMATS["current_money_format_blocked"]
else:
format_tcell_left = FORMATS["format_tcell_left"]
format_tcell_date_left = FORMATS["format_tcell_date_left"]
format_distributed = FORMATS["format_distributed"]
current_money_format = FORMATS["current_money_format"]
name_to_show = (
line.get("name", "") == "/" or not line.get("name", "")
) and line.get("ref", "")
if line.get("name", "") and line.get("name", "") != "/":
if not line.get("ref", ""):
name_to_show = line.get("name", "")
else:
if (line.get("name", "") in line.get("ref", "")) or (
line.get("name", "") == line.get("ref", "")
):
name_to_show = line.get("name", "")
elif line.get("ref", "") not in line.get("name", ""):
name_to_show = line.get("ref", "")
return (
[
{
"col_pos": col_pos,
"sheet_func": "write",
"args": args,
}
for col_pos, args in enumerate(
[
(line.get("move_id", ""), format_tcell_left),
(line.get("date", ""), format_tcell_date_left),
]
)
]
+ [
{
"col_pos": 2,
"sheet_func": "merge_range",
"span": 1,
"args": (name_to_show, format_distributed),
},
]
+ [
{
"col_pos": col_pos,
"sheet_func": "write",
"args": args,
}
for col_pos, args in enumerate(
[
(line.get("amount", ""), current_money_format),
(line.get("applied_amount", ""), current_money_format),
(line.get("open_amount", ""), current_money_format),
],
4,
)
]
)
def _get_currency_footer_row_data(self, partner, currency, data):
partner_data = data.get("data", {}).get(partner.id, {})
currency_data = partner_data.get("currencies", {}).get(currency.id)
return [
{
"col_pos": 1,
"sheet_func": "write",
"args": (partner_data.get("end"), FORMATS["format_tcell_date_left"]),
},
{
"col_pos": 2,
"sheet_func": "merge_range",
"span": 3,
"args": (_("Ending Balance"), FORMATS["format_tcell_left"]),
},
{
"col_pos": 6,
"sheet_func": "write",
"args": (
currency_data.get("amount_due"),
FORMATS["current_money_format"],
),
},
]
def _write_row_data(self, sheet, row_pos, row_data):
for cell_data in row_data:
sheet_func_name = cell_data.get("sheet_func", "")
sheet_func = getattr(sheet, sheet_func_name, None)
if callable(sheet_func):
col_pos = cell_data["col_pos"]
args = cell_data["args"]
span = cell_data.get("span")
if span:
args = row_pos, col_pos + span, *args
sheet_func(row_pos, col_pos, *args)
def _write_currency_header(self, row_pos, sheet, partner, currency, data):
row_data = self._get_currency_header_row_data(partner, currency, data)
self._write_row_data(sheet, row_pos, row_data)
return row_pos
def _write_currency_subheader(self, row_pos, sheet, partner, currency, data):
row_data = self._get_currency_subheader_row_data(partner, currency, data)
self._write_row_data(sheet, row_pos, row_data)
return row_pos
def _write_currency_line(self, row_pos, sheet, partner, currency, data, line):
row_data = self._get_currency_line_row_data(partner, currency, data, line)
self._write_row_data(sheet, row_pos, row_data)
return row_pos
def _write_currency_footer(self, row_pos, sheet, partner, currency, data):
row_data = self._get_currency_footer_row_data(partner, currency, data)
self._write_row_data(sheet, row_pos, row_data)
return row_pos
def _write_currency_lines(self, row_pos, sheet, partner, currency, data):
partner_data = data.get("data", {}).get(partner.id, {})
currency_data = partner_data.get("currencies", {}).get(currency.id)
account_type = data.get("account_type", False)
row_pos += 2
statement_header = data["get_title"](
partner,
is_detailed=False,
account_type=account_type,
starting_date=partner_data.get("start"),
ending_date=partner_data.get("end"),
currency=currency.display_name,
)
sheet.merge_range(
row_pos, 0, row_pos, 6, statement_header, FORMATS["format_left_bold"]
)
row_pos += 1
row_pos = self._write_currency_header(row_pos, sheet, partner, currency, data)
row_pos += 1
row_pos = self._write_currency_subheader(
row_pos, sheet, partner, currency, data
)
for line in currency_data.get("lines"):
row_pos += 1
row_pos = self._write_currency_line(
row_pos, sheet, partner, currency, data, line
)
row_pos += 1
row_pos = self._write_currency_footer(row_pos, sheet, partner, currency, data)
return row_pos
def _write_currency_buckets(self, row_pos, sheet, partner, currency, data):
report_model = self.env["report.partner_statement.activity_statement"]
partner_data = data.get("data", {}).get(partner.id, {})
currency_data = partner_data.get("currencies", {}).get(currency.id)
if currency_data.get("buckets"):
row_pos += 2
buckets_header = _("Aging Report at %(end)s in %(currency)s") % {
"end": partner_data.get("end"),
"currency": currency.display_name,
}
sheet.merge_range(
row_pos, 0, row_pos, 6, buckets_header, FORMATS["format_right_bold"]
)
buckets_data = currency_data.get("buckets")
buckets_labels = report_model._get_bucket_labels(
partner_data.get("end"), data.get("aging_type")
)
row_pos += 1
for i in range(len(buckets_labels)):
sheet.write(
row_pos,
i,
buckets_labels[i],
FORMATS["format_theader_yellow_center"],
)
row_pos += 1
sheet.write(
row_pos,
0,
buckets_data.get("current", 0.0),
FORMATS["current_money_format"],
)
sheet.write(
row_pos,
1,
buckets_data.get("b_1_30", 0.0),
FORMATS["current_money_format"],
)
sheet.write(
row_pos,
2,
buckets_data.get("b_30_60", 0.0),
FORMATS["current_money_format"],
)
sheet.write(
row_pos,
3,
buckets_data.get("b_60_90", 0.0),
FORMATS["current_money_format"],
)
sheet.write(
row_pos,
4,
buckets_data.get("b_90_120", 0.0),
FORMATS["current_money_format"],
)
sheet.write(
row_pos,
5,
buckets_data.get("b_over_120", 0.0),
FORMATS["current_money_format"],
)
sheet.write(
row_pos,
6,
buckets_data.get("balance", 0.0),
FORMATS["current_money_format"],
)
return row_pos
def _size_columns(self, sheet, data):
for i in range(7):
sheet.set_column(0, i, 20)
def generate_xlsx_report(self, workbook, data, objects):
lang = objects.lang or self.env.user.partner_id.lang
self = self.with_context(lang=lang)
report_model = self.env["report.partner_statement.activity_statement"]
self._define_formats(workbook)
FORMATS["format_distributed"] = workbook.add_format({"align": "vdistributed"})
company_id = data.get("company_id", False)
if company_id:
company = self.env["res.company"].browse(company_id)
else:
company = self.env.user.company_id
data.update(report_model._get_report_values(data.get("partner_ids"), data))
partners = self.env["res.partner"].browse(data.get("partner_ids"))
sheet = workbook.add_worksheet(_("Activity Statement"))
sheet.set_landscape()
row_pos = 0
sheet.merge_range(
row_pos,
0,
row_pos,
6,
_("Statement of Account from %s") % (company.display_name,),
FORMATS["format_ws_title"],
)
row_pos += 1
sheet.write(row_pos, 1, _("Date:"), FORMATS["format_theader_yellow_right"])
sheet.write(
row_pos,
2,
data.get("data", {}).get(partners.ids[0], {}).get("today"),
FORMATS["format_date_left"],
)
self._size_columns(sheet, data)
for partner in partners:
invoice_address = data.get(
"get_inv_addr", lambda x: self.env["res.partner"]
)(partner)
row_pos += 3
sheet.write(
row_pos, 1, _("Statement to:"), FORMATS["format_theader_yellow_right"]
)
sheet.merge_range(
row_pos,
2,
row_pos,
3,
invoice_address.display_name,
FORMATS["format_left"],
)
if invoice_address.vat:
sheet.write(
row_pos,
4,
_("VAT:"),
FORMATS["format_theader_yellow_right"],
)
sheet.write(
row_pos,
5,
invoice_address.vat,
FORMATS["format_left"],
)
row_pos += 1
sheet.write(
row_pos, 1, _("Statement from:"), FORMATS["format_theader_yellow_right"]
)
sheet.merge_range(
row_pos,
2,
row_pos,
3,
company.partner_id.display_name,
FORMATS["format_left"],
)
if company.vat:
sheet.write(
row_pos,
4,
_("VAT:"),
FORMATS["format_theader_yellow_right"],
)
sheet.write(
row_pos,
5,
company.vat,
FORMATS["format_left"],
)
partner_data = data.get("data", {}).get(partner.id)
currencies = partner_data.get("currencies", {}).keys()
if currencies:
row_pos += 1
for currency_id in currencies:
currency = self.env["res.currency"].browse(currency_id)
if currency.position == "after":
money_string = "#,##0.%s " % (
"0" * currency.decimal_places
) + "[${}]".format(currency.symbol)
elif currency.position == "before":
money_string = "[${}]".format(currency.symbol) + " #,##0.%s" % (
"0" * currency.decimal_places
)
FORMATS["current_money_format"] = workbook.add_format(
{"align": "right", "num_format": money_string}
)
bg_grey = "#ADB5BD"
FORMATS["format_tcell_left_blocked"] = copy_format(
workbook, FORMATS["format_tcell_left"]
)
FORMATS["format_tcell_left_blocked"].set_bg_color(bg_grey)
FORMATS["format_tcell_date_left_blocked"] = copy_format(
workbook, FORMATS["format_tcell_date_left"]
)
FORMATS["format_tcell_date_left_blocked"].set_bg_color(bg_grey)
FORMATS["format_distributed_blocked"] = copy_format(
workbook, FORMATS["format_distributed"]
)
FORMATS["format_distributed_blocked"].set_bg_color(bg_grey)
FORMATS["current_money_format_blocked"] = copy_format(
workbook, FORMATS["current_money_format"]
)
FORMATS["current_money_format_blocked"].set_bg_color(bg_grey)
row_pos = self._write_currency_lines(
row_pos, sheet, partner, currency, data
)
row_pos = self._write_currency_buckets(
row_pos, sheet, partner, currency, data
)

View file

@ -0,0 +1,71 @@
# Copyright 2022 ForgeFlow, S.L. (https://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import _, models
from .outstanding_statement import OutstandingStatement
class DetailedActivityStatement(models.AbstractModel):
"""Model of Detailed Activity Statement"""
_inherit = "report.partner_statement.activity_statement"
_name = "report.partner_statement.detailed_activity_statement"
_description = "Partner Detailed Activity Statement"
def _get_title(self, partner, **kwargs):
kwargs["context"] = {
"lang": partner.lang,
}
if kwargs.get("line_type") == "prior_lines":
if kwargs.get("account_type") == "receivable":
title = _(
"Prior Balance up to %(ending_date)s in %(currency)s", **kwargs
)
else:
title = _(
"Supplier Prior Balance up to %(ending_date)s in %(currency)s",
**kwargs
)
elif kwargs.get("line_type") == "ending_lines":
if kwargs.get("account_type") == "receivable":
title = _(
"Ending Balance up to %(ending_date)s in %(currency)s", **kwargs
)
else:
title = _(
"Supplier Ending Balance up to %(ending_date)s in %(currency)s",
**kwargs
)
else:
title = super()._get_title(partner, **kwargs)
return title
def _get_account_display_prior_lines(
self, company_id, partner_ids, date_start, date_end, account_type
):
return self._get_account_display_lines2(
company_id, partner_ids, date_start, date_end, account_type
)
def _get_account_display_ending_lines(
self, company_id, partner_ids, date_start, date_end, account_type
):
return self._get_account_display_lines2(
company_id, partner_ids, date_start, date_end, account_type
)
def _add_currency_prior_line(self, line, currency):
return self._add_currency_line2(line, currency)
def _add_currency_ending_line(self, line, currency):
return self._add_currency_line2(line, currency)
DetailedActivityStatement._get_account_display_lines2 = (
OutstandingStatement._get_account_display_lines
)
DetailedActivityStatement._display_outstanding_lines_sql_q1 = (
OutstandingStatement._display_outstanding_lines_sql_q1
)
DetailedActivityStatement._add_currency_line2 = OutstandingStatement._add_currency_line

View file

@ -0,0 +1,763 @@
# Author: Miquel Raïch
# Copyright 2022 ForgeFlow S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import _, models
from odoo.addons.report_xlsx_helper.report.report_xlsx_format import FORMATS
def copy_format(book, fmt):
properties = [f[4:] for f in dir(fmt) if f[0:4] == "set_"]
dft_fmt = book.add_format()
return book.add_format(
{
k: v
for k, v in fmt.__dict__.items()
if k in properties and dft_fmt.__dict__[k] != v
}
)
class DetailedActivityStatementXslx(models.AbstractModel):
_name = "report.p_s.report_detailed_activity_statement_xlsx"
_description = "Detailed Activity Statement XLSL Report"
_inherit = "report.p_s.report_activity_statement_xlsx"
def _get_report_name(self, report, data=False):
company_id = data.get("company_id", False)
report_name = _("Detailed Activity Statement")
if company_id:
company = self.env["res.company"].browse(company_id)
suffix = " - {} - {}".format(company.name, company.currency_id.name)
report_name = report_name + suffix
return report_name
def _get_currency_subheader_row_data(self, partner, currency, data):
partner_data = data.get("data", {}).get(partner.id, {})
currency_data = partner_data.get("currencies", {}).get(currency.id)
return [
{
"col_pos": 1,
"sheet_func": "write",
"args": (
partner_data.get("prior_day"),
FORMATS["format_tcell_date_left"],
),
},
{
"col_pos": 2,
"sheet_func": "merge_range",
"span": 3,
"args": (_("Initial Balance"), FORMATS["format_tcell_left"]),
},
{
"col_pos": 6,
"sheet_func": "write",
"args": (
currency_data.get("balance_forward"),
FORMATS["current_money_format"],
),
},
]
def _get_currency_line_row_data(self, partner, currency, data, line):
if line.get("blocked") and not line.get("reconciled_line"):
format_tcell_left = FORMATS["format_tcell_left_blocked"]
format_tcell_date_left = FORMATS["format_tcell_date_left_blocked"]
format_distributed = FORMATS["format_distributed_blocked"]
current_money_format = FORMATS["current_money_format_blocked"]
elif (
line.get("reconciled_line")
and not line.get("blocked")
and not line.get("outside-date-rank")
):
format_tcell_left = FORMATS["format_tcell_left_reconciled"]
format_tcell_date_left = FORMATS["format_tcell_date_left_reconciled"]
format_distributed = FORMATS["format_distributed_reconciled"]
current_money_format = FORMATS["current_money_format_reconciled"]
elif (
line.get("blocked")
and line.get("reconciled_line")
and not line.get("outside-date-rank")
):
format_tcell_left = FORMATS["format_tcell_left_blocked_reconciled"]
format_tcell_date_left = FORMATS[
"format_tcell_date_left_blocked_reconciled"
]
format_distributed = FORMATS["format_distributed_blocked_reconciled"]
current_money_format = FORMATS["current_money_format_blocked_reconciled"]
elif (
line.get("reconciled_line")
and not line.get("blocked")
and line.get("outside-date-rank")
):
format_tcell_left = FORMATS[
"format_tcell_left_reconciled_outside-date-rank"
]
format_tcell_date_left = FORMATS[
"format_tcell_date_left_reconciled_outside-date-rank"
]
format_distributed = FORMATS[
"format_distributed_reconciled_outside-date-rank"
]
current_money_format = FORMATS[
"current_money_format_reconciled_outside-date-rank"
]
elif (
line.get("blocked")
and line.get("reconciled_line")
and line.get("outside-date-rank")
):
format_tcell_left = FORMATS[
"format_tcell_left_blocked_reconciled_outside-date-rank"
]
format_tcell_date_left = FORMATS[
"format_tcell_date_left_blocked_reconciled_outside-date-rank"
]
format_distributed = FORMATS[
"format_distributed_blocked_reconciled_outside-date-rank"
]
current_money_format = FORMATS[
"current_money_format_blocked_reconciled_outside-date-rank"
]
else:
format_tcell_left = FORMATS["format_tcell_left"]
format_tcell_date_left = FORMATS["format_tcell_date_left"]
format_distributed = FORMATS["format_distributed"]
current_money_format = FORMATS["current_money_format"]
name_to_show = (
line.get("name", "") == "/" or not line.get("name", "")
) and line.get("ref", "")
if line.get("name", "") and line.get("name", "") != "/":
if not line.get("ref", ""):
name_to_show = line.get("name", "")
else:
if (line.get("name", "") in line.get("ref", "")) or (
line.get("name", "") == line.get("ref", "")
):
name_to_show = line.get("name", "")
elif line.get("ref", "") not in line.get("name", ""):
name_to_show = line.get("ref", "")
return (
[
{
"col_pos": col_pos,
"sheet_func": "write",
"args": args,
}
for col_pos, args in enumerate(
[
(line.get("move_id", ""), format_tcell_left),
(line.get("date", ""), format_tcell_date_left),
]
)
]
+ [
{
"col_pos": 2,
"sheet_func": "merge_range",
"span": 1,
"args": (name_to_show, format_distributed),
},
]
+ [
{
"col_pos": col_pos,
"sheet_func": "write",
"args": args,
}
for col_pos, args in enumerate(
[
(
line.get("amount", "")
if not line.get("reconciled_line")
else "",
current_money_format,
),
(line.get("applied_amount", ""), current_money_format),
(
line.get("open_amount", "")
if not line.get("reconciled_line")
else "",
current_money_format,
),
],
4,
)
]
)
def _write_currency_lines(self, row_pos, sheet, partner, currency, data):
partner_data = data.get("data", {}).get(partner.id, {})
currency_data = partner_data.get("currencies", {}).get(currency.id)
account_type = data.get("account_type", False)
row_pos += 2
statement_header = data["get_title"](
partner,
is_detailed=True,
account_type=account_type,
starting_date=partner_data.get("start"),
ending_date=partner_data.get("end"),
currency=currency.display_name,
)
sheet.merge_range(
row_pos, 0, row_pos, 6, statement_header, FORMATS["format_left_bold"]
)
row_pos += 1
row_pos = self._write_currency_header(row_pos, sheet, partner, currency, data)
row_pos += 1
row_pos = self._write_currency_subheader(
row_pos, sheet, partner, currency, data
)
for line in currency_data.get("lines"):
row_pos += 1
row_pos = self._write_currency_line(
row_pos, sheet, partner, currency, data, line
)
row_pos += 1
row_pos = self._write_currency_footer(row_pos, sheet, partner, currency, data)
return row_pos
def _get_currency_prior_header_row_data(self, partner, currency, data):
return [
{
"col_pos": col_pos,
"sheet_func": "write",
"args": args,
}
for col_pos, args in enumerate(
[
(_("Reference Number"), FORMATS["format_theader_yellow_center"]),
(_("Date"), FORMATS["format_theader_yellow_center"]),
(_("Due Date"), FORMATS["format_theader_yellow_center"]),
(_("Description"), FORMATS["format_theader_yellow_center"]),
(_("Original"), FORMATS["format_theader_yellow_center"]),
(_("Open Amount"), FORMATS["format_theader_yellow_center"]),
(_("Balance"), FORMATS["format_theader_yellow_center"]),
]
)
]
def _get_currency_prior_line_row_data(self, partner, currency, data, line):
if line.get("blocked") and not line.get("reconciled_line"):
format_tcell_left = FORMATS["format_tcell_left_blocked"]
format_tcell_date_left = FORMATS["format_tcell_date_left_blocked"]
format_distributed = FORMATS["format_distributed_blocked"]
current_money_format = FORMATS["current_money_format_blocked"]
elif line.get("reconciled_line") and not line.get("blocked"):
format_tcell_left = FORMATS["format_tcell_left_reconciled"]
format_tcell_date_left = FORMATS["format_tcell_date_left_reconciled"]
format_distributed = FORMATS["format_distributed_reconciled"]
current_money_format = FORMATS["current_money_format_reconciled"]
elif line.get("blocked") and line.get("reconciled_line"):
format_tcell_left = FORMATS["format_tcell_left_blocked_reconciled"]
format_tcell_date_left = FORMATS[
"format_tcell_date_left_blocked_reconciled"
]
format_distributed = FORMATS["format_distributed_blocked_reconciled"]
current_money_format = FORMATS["current_money_format_blocked_reconciled"]
else:
format_tcell_left = FORMATS["format_tcell_left"]
format_tcell_date_left = FORMATS["format_tcell_date_left"]
format_distributed = FORMATS["format_distributed"]
current_money_format = FORMATS["current_money_format"]
name_to_show = (
line.get("name", "") == "/" or not line.get("name", "")
) and line.get("ref", "")
if line.get("name", "") and line.get("name", "") != "/":
if not line.get("ref", ""):
name_to_show = line.get("name", "")
else:
if (line.get("ref", "") in line.get("name", "")) or (
line.get("name", "") == line.get("ref", "")
):
name_to_show = line.get("name", "")
else:
name_to_show = line.get("ref", "")
return [
{
"col_pos": col_pos,
"sheet_func": "write",
"args": args,
}
for col_pos, args in enumerate(
[
(line.get("move_id", ""), format_tcell_left),
(line.get("date", ""), format_tcell_date_left),
(line.get("date_maturity", ""), format_tcell_date_left),
(name_to_show, format_distributed),
(line.get("amount", ""), current_money_format),
(line.get("open_amount", ""), current_money_format),
(line.get("balance", ""), current_money_format),
]
)
]
def _get_currency_footer_prior_row_data(self, partner, currency, data):
partner_data = data.get("data", {}).get(partner.id, {})
currency_data = partner_data.get("currencies", {}).get(currency.id)
return [
{
"col_pos": 1,
"sheet_func": "write",
"args": (
partner_data.get("prior_day"),
FORMATS["format_tcell_date_left"],
),
},
{
"col_pos": 2,
"sheet_func": "merge_range",
"span": 3,
"args": (_("Ending Balance"), FORMATS["format_tcell_left"]),
},
{
"col_pos": 6,
"sheet_func": "write",
"args": (
currency_data.get("balance_forward"),
FORMATS["current_money_format"],
),
},
]
def _write_currency_prior_header(self, row_pos, sheet, partner, currency, data):
row_data = self._get_currency_prior_header_row_data(partner, currency, data)
self._write_row_data(sheet, row_pos, row_data)
return row_pos
def _write_currency_prior_line(self, row_pos, sheet, partner, currency, data, line):
row_data = self._get_currency_prior_line_row_data(partner, currency, data, line)
self._write_row_data(sheet, row_pos, row_data)
return row_pos
def _write_currency_prior_footer(self, row_pos, sheet, partner, currency, data):
row_data = self._get_currency_footer_prior_row_data(partner, currency, data)
self._write_row_data(sheet, row_pos, row_data)
return row_pos
def _write_currency_prior_lines(self, row_pos, sheet, partner, currency, data):
partner_data = data.get("data", {}).get(partner.id, {})
currency_data = partner_data.get("currencies", {}).get(currency.id)
account_type = data.get("account_type", False)
row_pos += 2
statement_header = data["get_title"](
partner,
is_detailed=False,
account_type=account_type,
starting_date=partner_data.get("start"),
ending_date=partner_data.get("end"),
currency=currency.display_name,
)
sheet.merge_range(
row_pos,
0,
row_pos,
6,
statement_header,
FORMATS["format_left_bold"],
)
row_pos += 1
row_pos = self._write_currency_prior_header(
row_pos, sheet, partner, currency, data
)
for line in currency_data.get("prior_lines"):
row_pos += 1
row_pos = self._write_currency_prior_line(
row_pos, sheet, partner, currency, data, line
)
row_pos += 1
row_pos = self._write_currency_prior_footer(
row_pos, sheet, partner, currency, data
)
return row_pos
def _get_currency_ending_header_row_data(self, partner, currency, data):
return [
{
"col_pos": col_pos,
"sheet_func": "write",
"args": args,
}
for col_pos, args in enumerate(
[
(_("Reference Number"), FORMATS["format_theader_yellow_center"]),
(_("Date"), FORMATS["format_theader_yellow_center"]),
(_("Due Date"), FORMATS["format_theader_yellow_center"]),
(_("Description"), FORMATS["format_theader_yellow_center"]),
(_("Original"), FORMATS["format_theader_yellow_center"]),
(_("Open Amount"), FORMATS["format_theader_yellow_center"]),
(_("Balance"), FORMATS["format_theader_yellow_center"]),
]
)
]
def _get_currency_ending_line_row_data(self, partner, currency, data, line):
if line.get("blocked") and not line.get("reconciled_line"):
format_tcell_left = FORMATS["format_tcell_left_blocked"]
format_tcell_date_left = FORMATS["format_tcell_date_left_blocked"]
format_distributed = FORMATS["format_distributed_blocked"]
current_money_format = FORMATS["current_money_format_blocked"]
elif line.get("reconciled_line") and not line.get("blocked"):
format_tcell_left = FORMATS["format_tcell_left_reconciled"]
format_tcell_date_left = FORMATS["format_tcell_date_left_reconciled"]
format_distributed = FORMATS["format_distributed_reconciled"]
current_money_format = FORMATS["current_money_format_reconciled"]
elif line.get("blocked") and line.get("reconciled_line"):
format_tcell_left = FORMATS["format_tcell_left_blocked_reconciled"]
format_tcell_date_left = FORMATS[
"format_tcell_date_left_blocked_reconciled"
]
format_distributed = FORMATS["format_distributed_blocked_reconciled"]
current_money_format = FORMATS["current_money_format_blocked_reconciled"]
else:
format_tcell_left = FORMATS["format_tcell_left"]
format_tcell_date_left = FORMATS["format_tcell_date_left"]
format_distributed = FORMATS["format_distributed"]
current_money_format = FORMATS["current_money_format"]
name_to_show = (
line.get("name", "") == "/" or not line.get("name", "")
) and line.get("ref", "")
if line.get("name", "") and line.get("name", "") != "/":
if not line.get("ref", ""):
name_to_show = line.get("name", "")
else:
if (line.get("ref", "") in line.get("name", "")) or (
line.get("name", "") == line.get("ref", "")
):
name_to_show = line.get("name", "")
else:
name_to_show = line.get("ref", "")
return [
{
"col_pos": col_pos,
"sheet_func": "write",
"args": args,
}
for col_pos, args in enumerate(
[
(line.get("move_id", ""), format_tcell_left),
(line.get("date", ""), format_tcell_date_left),
(line.get("date_maturity", ""), format_tcell_date_left),
(name_to_show, format_distributed),
(line.get("amount", ""), current_money_format),
(line.get("open_amount", ""), current_money_format),
(line.get("balance", ""), current_money_format),
]
)
]
def _get_currency_footer_ending_row_data(self, partner, currency, data):
partner_data = data.get("data", {}).get(partner.id, {})
currency_data = partner_data.get("currencies", {}).get(currency.id)
return [
{
"col_pos": 1,
"sheet_func": "write",
"args": (partner_data.get("end"), FORMATS["format_tcell_date_left"]),
},
{
"col_pos": 2,
"sheet_func": "merge_range",
"span": 3,
"args": (_("Ending Balance"), FORMATS["format_tcell_left"]),
},
{
"col_pos": 6,
"sheet_func": "write",
"args": (
currency_data.get("amount_due"),
FORMATS["current_money_format"],
),
},
]
def _write_currency_ending_header(self, row_pos, sheet, partner, currency, data):
row_data = self._get_currency_ending_header_row_data(partner, currency, data)
self._write_row_data(sheet, row_pos, row_data)
return row_pos
def _write_currency_ending_line(
self, row_pos, sheet, partner, currency, data, line
):
row_data = self._get_currency_ending_line_row_data(
partner, currency, data, line
)
self._write_row_data(sheet, row_pos, row_data)
return row_pos
def _write_currency_ending_footer(self, row_pos, sheet, partner, currency, data):
row_data = self._get_currency_footer_ending_row_data(partner, currency, data)
self._write_row_data(sheet, row_pos, row_data)
return row_pos
def _write_currency_ending_lines(self, row_pos, sheet, partner, currency, data):
partner_data = data.get("data", {}).get(partner.id, {})
currency_data = partner_data.get("currencies", {}).get(currency.id)
account_type = data.get("account_type", False)
row_pos += 2
statement_header = data["get_title"](
partner,
is_detailed=False,
account_type=account_type,
starting_date=partner_data.get("start"),
ending_date=partner_data.get("end"),
currency=currency.display_name,
)
sheet.merge_range(
row_pos,
0,
row_pos,
6,
statement_header,
FORMATS["format_left_bold"],
)
row_pos += 1
row_pos = self._write_currency_ending_header(
row_pos, sheet, partner, currency, data
)
for line in currency_data.get("ending_lines"):
row_pos += 1
row_pos = self._write_currency_ending_line(
row_pos, sheet, partner, currency, data, line
)
row_pos += 1
row_pos = self._write_currency_ending_footer(
row_pos, sheet, partner, currency, data
)
return row_pos
def _size_columns(self, sheet, data):
for i in range(7):
sheet.set_column(0, i, 20)
def generate_xlsx_report(self, workbook, data, objects):
lang = objects.lang or self.env.user.partner_id.lang
self = self.with_context(lang=lang)
report_model = self.env["report.partner_statement.detailed_activity_statement"]
self._define_formats(workbook)
FORMATS["format_distributed"] = workbook.add_format({"align": "vdistributed"})
company_id = data.get("company_id", False)
if company_id:
company = self.env["res.company"].browse(company_id)
else:
company = self.env.user.company_id
data.update(report_model._get_report_values(data.get("partner_ids"), data))
partners = self.env["res.partner"].browse(data.get("partner_ids"))
sheet = workbook.add_worksheet(_("Detailed Activity Statement"))
sheet.set_landscape()
row_pos = 0
sheet.merge_range(
row_pos,
0,
row_pos,
6,
_("Statement of Account from %s") % (company.display_name,),
FORMATS["format_ws_title"],
)
row_pos += 1
sheet.write(row_pos, 1, _("Date:"), FORMATS["format_theader_yellow_right"])
sheet.write(
row_pos,
2,
data.get("data", {}).get(partners.ids[0], {}).get("today"),
FORMATS["format_date_left"],
)
self._size_columns(sheet, data)
for partner in partners:
invoice_address = data.get(
"get_inv_addr", lambda x: self.env["res.partner"]
)(partner)
row_pos += 3
sheet.write(
row_pos, 1, _("Statement to:"), FORMATS["format_theader_yellow_right"]
)
sheet.merge_range(
row_pos,
2,
row_pos,
3,
invoice_address.display_name,
FORMATS["format_left"],
)
if invoice_address.vat:
sheet.write(
row_pos,
4,
_("VAT:"),
FORMATS["format_theader_yellow_right"],
)
sheet.write(
row_pos,
5,
invoice_address.vat,
FORMATS["format_left"],
)
row_pos += 1
sheet.write(
row_pos, 1, _("Statement from:"), FORMATS["format_theader_yellow_right"]
)
sheet.merge_range(
row_pos,
2,
row_pos,
3,
company.partner_id.display_name,
FORMATS["format_left"],
)
if company.vat:
sheet.write(
row_pos,
4,
_("VAT:"),
FORMATS["format_theader_yellow_right"],
)
sheet.write(
row_pos,
5,
company.vat,
FORMATS["format_left"],
)
partner_data = data.get("data", {}).get(partner.id)
currencies = partner_data.get("currencies", {}).keys()
if currencies:
row_pos += 1
for currency_id in currencies:
currency = self.env["res.currency"].browse(currency_id)
if currency.position == "after":
money_string = "#,##0.%s " % (
"0" * currency.decimal_places
) + "[${}]".format(currency.symbol)
elif currency.position == "before":
money_string = "[${}]".format(currency.symbol) + " #,##0.%s" % (
"0" * currency.decimal_places
)
FORMATS["current_money_format"] = workbook.add_format(
{"align": "right", "num_format": money_string}
)
bg_grey = "#ADB5BD"
fc_red = "#DC3545"
FORMATS["format_tcell_left_blocked"] = copy_format(
workbook, FORMATS["format_tcell_left"]
)
FORMATS["format_tcell_left_blocked"].set_bg_color(bg_grey)
FORMATS["format_tcell_date_left_blocked"] = copy_format(
workbook, FORMATS["format_tcell_date_left"]
)
FORMATS["format_tcell_date_left_blocked"].set_bg_color(bg_grey)
FORMATS["format_distributed_blocked"] = copy_format(
workbook, FORMATS["format_distributed"]
)
FORMATS["format_distributed_blocked"].set_bg_color(bg_grey)
FORMATS["current_money_format_blocked"] = copy_format(
workbook, FORMATS["current_money_format"]
)
FORMATS["current_money_format_blocked"].set_bg_color(bg_grey)
FORMATS["format_tcell_left_reconciled"] = copy_format(
workbook, FORMATS["format_tcell_left"]
)
FORMATS["format_tcell_left_reconciled"].set_italic(True)
FORMATS["format_tcell_left_reconciled"].set_font_size(10)
FORMATS["format_tcell_left_reconciled"].set_indent(1)
FORMATS["format_tcell_date_left_reconciled"] = copy_format(
workbook, FORMATS["format_tcell_date_left"]
)
FORMATS["format_tcell_date_left_reconciled"].set_italic(True)
FORMATS["format_tcell_date_left_reconciled"].set_font_size(10)
FORMATS["format_distributed_reconciled"] = copy_format(
workbook, FORMATS["format_distributed"]
)
FORMATS["format_distributed_reconciled"].set_italic(True)
FORMATS["format_distributed_reconciled"].set_font_size(10)
FORMATS["current_money_format_reconciled"] = copy_format(
workbook, FORMATS["current_money_format"]
)
FORMATS["current_money_format_reconciled"].set_italic(True)
FORMATS["current_money_format_reconciled"].set_font_size(10)
FORMATS["format_tcell_left_blocked_reconciled"] = copy_format(
workbook, FORMATS["format_tcell_left_reconciled"]
)
FORMATS["format_tcell_left_blocked_reconciled"].set_bg_color(bg_grey)
FORMATS["format_tcell_date_left_blocked_reconciled"] = copy_format(
workbook, FORMATS["format_tcell_date_left_reconciled"]
)
FORMATS["format_tcell_date_left_blocked_reconciled"].set_bg_color(
bg_grey
)
FORMATS["format_distributed_blocked_reconciled"] = copy_format(
workbook, FORMATS["format_distributed_reconciled"]
)
FORMATS["format_distributed_blocked_reconciled"].set_bg_color(bg_grey)
FORMATS["current_money_format_blocked_reconciled"] = copy_format(
workbook, FORMATS["current_money_format_reconciled"]
)
FORMATS["current_money_format_blocked_reconciled"].set_bg_color(bg_grey)
FORMATS["format_tcell_left_reconciled_outside-date-rank"] = copy_format(
workbook, FORMATS["format_tcell_left_reconciled"]
)
FORMATS[
"format_tcell_left_reconciled_outside-date-rank"
].set_font_color(fc_red)
FORMATS[
"format_tcell_date_left_reconciled_outside-date-rank"
] = copy_format(workbook, FORMATS["format_tcell_date_left_reconciled"])
FORMATS[
"format_tcell_date_left_reconciled_outside-date-rank"
].set_font_color(fc_red)
FORMATS[
"format_distributed_reconciled_outside-date-rank"
] = copy_format(workbook, FORMATS["format_distributed_reconciled"])
FORMATS[
"format_distributed_reconciled_outside-date-rank"
].set_font_color(fc_red)
FORMATS[
"current_money_format_reconciled_outside-date-rank"
] = copy_format(workbook, FORMATS["current_money_format_reconciled"])
FORMATS[
"current_money_format_reconciled_outside-date-rank"
].set_font_color(fc_red)
FORMATS[
"format_tcell_left_blocked_reconciled_outside-date-rank"
] = copy_format(
workbook, FORMATS["format_tcell_left_blocked_reconciled"]
)
FORMATS[
"format_tcell_left_blocked_reconciled_outside-date-rank"
].set_font_color(fc_red)
FORMATS[
"format_tcell_date_left_blocked_reconciled_outside-date-rank"
] = copy_format(
workbook, FORMATS["format_tcell_date_left_blocked_reconciled"]
)
FORMATS[
"format_tcell_date_left_blocked_reconciled_outside-date-rank"
].set_font_color(fc_red)
FORMATS[
"format_distributed_blocked_reconciled_outside-date-rank"
] = copy_format(
workbook, FORMATS["format_distributed_blocked_reconciled"]
)
FORMATS[
"format_distributed_blocked_reconciled_outside-date-rank"
].set_font_color(fc_red)
FORMATS[
"current_money_format_blocked_reconciled_outside-date-rank"
] = copy_format(
workbook, FORMATS["current_money_format_blocked_reconciled"]
)
FORMATS[
"current_money_format_blocked_reconciled_outside-date-rank"
].set_font_color(fc_red)
row_pos = self._write_currency_prior_lines(
row_pos, sheet, partner, currency, data
)
row_pos = self._write_currency_lines(
row_pos, sheet, partner, currency, data
)
row_pos = self._write_currency_ending_lines(
row_pos, sheet, partner, currency, data
)
row_pos = self._write_currency_buckets(
row_pos, sheet, partner, currency, data
)

View file

@ -0,0 +1,183 @@
# Copyright 2018 ForgeFlow, S.L. (https://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import _, api, models
from odoo.tools.float_utils import float_is_zero
class OutstandingStatement(models.AbstractModel):
"""Model of Outstanding Statement"""
_inherit = "statement.common"
_name = "report.partner_statement.outstanding_statement"
_description = "Partner Outstanding Statement"
def _get_title(self, partner, **kwargs):
kwargs["context"] = {
"lang": partner.lang,
}
if kwargs.get("account_type") == "receivable":
title = _("Statement up to %(ending_date)s in %(currency)s", **kwargs)
else:
title = _(
"Supplier Statement up to %(ending_date)s in %(currency)s", **kwargs
)
return title
def _display_outstanding_lines_sql_q1(self, partners, date_end, account_type):
partners = tuple(partners)
excluded_accounts_ids = tuple(
self.env.context.get("excluded_accounts_ids", [])
) or (-1,)
show_only_overdue = self.env.context.get("show_only_overdue", False)
return str(
self._cr.mogrify(
"""
SELECT l.id, m.name AS move_id, l.partner_id, l.date, l.name,
l.blocked, l.currency_id, l.company_id,
CASE WHEN l.ref IS NOT NULL
THEN l.ref
ELSE m.ref
END as ref,
CASE WHEN (l.currency_id is not null AND l.amount_currency > 0.0)
THEN avg(l.amount_currency)
ELSE avg(l.debit)
END as debit,
CASE WHEN (l.currency_id is not null AND l.amount_currency < 0.0)
THEN avg(l.amount_currency * (-1))
ELSE avg(l.credit)
END as credit,
CASE WHEN l.balance > 0.0
THEN l.balance - sum(coalesce(pd.amount, 0.0))
ELSE l.balance + sum(coalesce(pc.amount, 0.0))
END AS open_amount,
CASE WHEN l.balance > 0.0
THEN l.amount_currency - sum(coalesce(pd.debit_amount_currency, 0.0))
ELSE l.amount_currency + sum(coalesce(pc.credit_amount_currency, 0.0))
END AS open_amount_currency,
CASE WHEN l.date_maturity is null
THEN l.date
ELSE l.date_maturity
END as date_maturity
FROM account_move_line l
JOIN account_account aa ON (aa.id = l.account_id)
JOIN account_move m ON (l.move_id = m.id)
LEFT JOIN (SELECT pr.*
FROM account_partial_reconcile pr
INNER JOIN account_move_line l2
ON pr.credit_move_id = l2.id
WHERE l2.date <= %(date_end)s
) as pd ON pd.debit_move_id = l.id
LEFT JOIN (SELECT pr.*
FROM account_partial_reconcile pr
INNER JOIN account_move_line l2
ON pr.debit_move_id = l2.id
WHERE l2.date <= %(date_end)s
) as pc ON pc.credit_move_id = l.id
WHERE l.partner_id IN %(partners)s
AND aa.id not in %(excluded_accounts_ids)s
AND (
(pd.id IS NOT NULL AND
pd.max_date <= %(date_end)s) OR
(pc.id IS NOT NULL AND
pc.max_date <= %(date_end)s) OR
(pd.id IS NULL AND pc.id IS NULL)
) AND l.date <= %(date_end)s AND m.state IN ('posted')
AND aa.account_type = %(account_type)s
AND CASE
WHEN %(show_only_overdue)s
THEN COALESCE(l.date_maturity, l.date) <= %(date_end)s
ELSE TRUE
END
GROUP BY l.id, l.partner_id, m.name, l.date, l.date_maturity, l.name,
CASE WHEN l.ref IS NOT NULL
THEN l.ref
ELSE m.ref
END,
l.blocked, l.currency_id, l.balance, l.amount_currency, l.company_id
""",
locals(),
),
"utf-8",
)
def _display_outstanding_lines_sql_q2(self, sub):
return str(
self._cr.mogrify(
f"""
SELECT {sub}.partner_id, {sub}.currency_id, {sub}.move_id,
{sub}.date, {sub}.date_maturity, {sub}.debit, {sub}.credit,
{sub}.name, {sub}.ref, {sub}.blocked, {sub}.company_id,
CASE WHEN {sub}.currency_id is not null
THEN {sub}.open_amount_currency
ELSE {sub}.open_amount
END as open_amount, {sub}.id
FROM {sub}
""",
locals(),
),
"utf-8",
)
def _display_outstanding_lines_sql_q3(self, sub, company_id):
return str(
self._cr.mogrify(
f"""
SELECT {sub}.partner_id, {sub}.move_id, {sub}.date,
{sub}.date_maturity, {sub}.name, {sub}.ref, {sub}.debit,
{sub}.credit, {sub}.debit-{sub}.credit AS amount,
COALESCE({sub}.currency_id, c.currency_id) AS currency_id,
{sub}.open_amount, {sub}.blocked, {sub}.id
FROM {sub}
JOIN res_company c ON (c.id = {sub}.company_id)
WHERE c.id = %(company_id)s AND {sub}.open_amount != 0.0
""",
locals(),
),
"utf-8",
)
def _get_account_display_lines(
self, company_id, partner_ids, date_start, date_end, account_type
):
res = dict(map(lambda x: (x, []), partner_ids))
partners = tuple(partner_ids)
# pylint: disable=E8103
self.env.cr.execute(
"""
WITH Q1 as (%s),
Q2 AS (%s),
Q3 AS (%s)
SELECT partner_id, currency_id, move_id, date, date_maturity, debit,
credit, amount, open_amount, COALESCE(name, '') as name,
COALESCE(ref, '') as ref, blocked, id
FROM Q3
ORDER BY date, date_maturity, move_id"""
% (
self._display_outstanding_lines_sql_q1(
partners, date_end, account_type
),
self._display_outstanding_lines_sql_q2("Q1"),
self._display_outstanding_lines_sql_q3("Q2", company_id),
)
)
for row in self.env.cr.dictfetchall():
res[row.pop("partner_id")].append(row)
return res
def _add_currency_line(self, line, currency):
if float_is_zero(line["open_amount"], precision_rounding=currency.rounding):
return []
return [line]
@api.model
def _get_report_values(self, docids, data=None):
if not data:
data = {}
if "company_id" not in data:
wiz = self.env["outstanding.statement.wizard"].with_context(
active_ids=docids, model="res.partner"
)
data.update(wiz.create({})._prepare_statement())
data["amount_field"] = "open_amount"
return super()._get_report_values(docids, data)

View file

@ -0,0 +1,376 @@
# Author: Christopher Ormaza
# Copyright 2021 ForgeFlow S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import _, models
from odoo.addons.report_xlsx_helper.report.report_xlsx_format import FORMATS
def copy_format(book, fmt):
properties = [f[4:] for f in dir(fmt) if f[0:4] == "set_"]
dft_fmt = book.add_format()
return book.add_format(
{
k: v
for k, v in fmt.__dict__.items()
if k in properties and dft_fmt.__dict__[k] != v
}
)
class OutstandingStatementXslx(models.AbstractModel):
_name = "report.p_s.report_outstanding_statement_xlsx"
_description = "Outstanding Statement XLSL Report"
_inherit = "report.report_xlsx.abstract"
def _get_report_name(self, report, data=False):
company_id = data.get("company_id", False)
report_name = _("Outstanding Statement")
if company_id:
company = self.env["res.company"].browse(company_id)
suffix = " - {} - {}".format(company.name, company.currency_id.name)
report_name = report_name + suffix
return report_name
def _get_currency_header_row_data(self, partner, currency, data):
return [
{
"col_pos": col_pos,
"sheet_func": "write",
"args": args,
}
for col_pos, args in enumerate(
[
(_("Reference Number"), FORMATS["format_theader_yellow_center"]),
(_("Date"), FORMATS["format_theader_yellow_center"]),
(_("Due Date"), FORMATS["format_theader_yellow_center"]),
(_("Description"), FORMATS["format_theader_yellow_center"]),
(_("Original"), FORMATS["format_theader_yellow_center"]),
(_("Open Amount"), FORMATS["format_theader_yellow_center"]),
(_("Balance"), FORMATS["format_theader_yellow_center"]),
]
)
]
def _get_currency_line_row_data(self, partner, currency, data, line):
if line.get("blocked"):
format_tcell_left = FORMATS["format_tcell_left_blocked"]
format_tcell_date_left = FORMATS["format_tcell_date_left_blocked"]
format_distributed = FORMATS["format_distributed_blocked"]
current_money_format = FORMATS["current_money_format_blocked"]
else:
format_tcell_left = FORMATS["format_tcell_left"]
format_tcell_date_left = FORMATS["format_tcell_date_left"]
format_distributed = FORMATS["format_distributed"]
current_money_format = FORMATS["current_money_format"]
name_to_show = (
line.get("name", "") == "/" or not line.get("name", "")
) and line.get("ref", "")
if line.get("name", "") and line.get("name", "") != "/":
if not line.get("ref", ""):
name_to_show = line.get("name", "")
else:
if (line.get("ref", "") in line.get("name", "")) or (
line.get("name", "") == line.get("ref", "")
):
name_to_show = line.get("name", "")
else:
name_to_show = line.get("ref", "")
return [
{
"col_pos": col_pos,
"sheet_func": "write",
"args": args,
}
for col_pos, args in enumerate(
[
(line.get("move_id", ""), format_tcell_left),
(line.get("date", ""), format_tcell_date_left),
(line.get("date_maturity", ""), format_tcell_date_left),
(name_to_show, format_distributed),
(line.get("amount", ""), current_money_format),
(line.get("open_amount", ""), current_money_format),
(line.get("balance", ""), current_money_format),
]
)
]
def _get_currency_footer_row_data(self, partner, currency, data):
partner_data = data.get("data", {}).get(partner.id, {})
currency_data = partner_data.get("currencies", {}).get(currency.id)
return [
{
"col_pos": 1,
"sheet_func": "write",
"args": (partner_data.get("end"), FORMATS["format_tcell_date_left"]),
},
{
"col_pos": 2,
"sheet_func": "merge_range",
"span": 3,
"args": (_("Ending Balance"), FORMATS["format_tcell_left"]),
},
{
"col_pos": 6,
"sheet_func": "write",
"args": (
currency_data.get("amount_due"),
FORMATS["current_money_format"],
),
},
]
def _write_row_data(self, sheet, row_pos, row_data):
for cell_data in row_data:
sheet_func_name = cell_data.get("sheet_func", "")
sheet_func = getattr(sheet, sheet_func_name, None)
if callable(sheet_func):
col_pos = cell_data["col_pos"]
args = cell_data["args"]
span = cell_data.get("span")
if span:
args = row_pos, col_pos + span, *args
sheet_func(row_pos, col_pos, *args)
def _write_currency_header(self, row_pos, sheet, partner, currency, data):
row_data = self._get_currency_header_row_data(partner, currency, data)
self._write_row_data(sheet, row_pos, row_data)
return row_pos
def _write_currency_line(self, row_pos, sheet, partner, currency, data, line):
row_data = self._get_currency_line_row_data(partner, currency, data, line)
self._write_row_data(sheet, row_pos, row_data)
return row_pos
def _write_currency_footer(self, row_pos, sheet, partner, currency, data):
row_data = self._get_currency_footer_row_data(partner, currency, data)
self._write_row_data(sheet, row_pos, row_data)
return row_pos
def _write_currency_lines(self, row_pos, sheet, partner, currency, data):
partner_data = data.get("data", {}).get(partner.id, {})
currency_data = partner_data.get("currencies", {}).get(currency.id)
account_type = data.get("account_type", False)
row_pos += 2
statement_header = data["get_title"](
partner,
account_type=account_type,
ending_date=partner_data.get("end"),
currency=currency.display_name,
)
sheet.merge_range(
row_pos, 0, row_pos, 6, statement_header, FORMATS["format_left_bold"]
)
row_pos += 1
row_pos = self._write_currency_header(row_pos, sheet, partner, currency, data)
for line in currency_data.get("lines"):
row_pos += 1
row_pos = self._write_currency_line(
row_pos, sheet, partner, currency, data, line
)
row_pos += 1
row_pos = self._write_currency_footer(row_pos, sheet, partner, currency, data)
return row_pos
def _write_currency_buckets(self, row_pos, sheet, partner, currency, data):
report_model = self.env["report.partner_statement.outstanding_statement"]
partner_data = data.get("data", {}).get(partner.id, {})
currency_data = partner_data.get("currencies", {}).get(currency.id)
if currency_data.get("buckets"):
row_pos += 2
buckets_header = _("Aging Report at %(end)s in %(currency)s") % {
"end": partner_data.get("end"),
"currency": currency.display_name,
}
sheet.merge_range(
row_pos, 0, row_pos, 6, buckets_header, FORMATS["format_right_bold"]
)
buckets_data = currency_data.get("buckets")
buckets_labels = report_model._get_bucket_labels(
partner_data.get("end"), data.get("aging_type")
)
row_pos += 1
for i in range(len(buckets_labels)):
sheet.write(
row_pos,
i,
buckets_labels[i],
FORMATS["format_theader_yellow_center"],
)
row_pos += 1
sheet.write(
row_pos,
0,
buckets_data.get("current", 0.0),
FORMATS["current_money_format"],
)
sheet.write(
row_pos,
1,
buckets_data.get("b_1_30", 0.0),
FORMATS["current_money_format"],
)
sheet.write(
row_pos,
2,
buckets_data.get("b_30_60", 0.0),
FORMATS["current_money_format"],
)
sheet.write(
row_pos,
3,
buckets_data.get("b_60_90", 0.0),
FORMATS["current_money_format"],
)
sheet.write(
row_pos,
4,
buckets_data.get("b_90_120", 0.0),
FORMATS["current_money_format"],
)
sheet.write(
row_pos,
5,
buckets_data.get("b_over_120", 0.0),
FORMATS["current_money_format"],
)
sheet.write(
row_pos,
6,
buckets_data.get("balance", 0.0),
FORMATS["current_money_format"],
)
return row_pos
def _size_columns(self, sheet, data):
for i in range(7):
sheet.set_column(0, i, 20)
def generate_xlsx_report(self, workbook, data, objects):
lang = objects.lang or self.env.user.partner_id.lang
self = self.with_context(lang=lang)
report_model = self.env["report.partner_statement.outstanding_statement"]
self._define_formats(workbook)
FORMATS["format_distributed"] = workbook.add_format({"align": "vdistributed"})
company_id = data.get("company_id", False)
if company_id:
company = self.env["res.company"].browse(company_id)
else:
company = self.env.user.company_id
data.update(report_model._get_report_values(data.get("partner_ids"), data))
partners = self.env["res.partner"].browse(data.get("partner_ids"))
sheet = workbook.add_worksheet(_("Outstanding Statement"))
sheet.set_landscape()
row_pos = 0
sheet.merge_range(
row_pos,
0,
row_pos,
6,
_("Statement of Account from %s") % (company.display_name,),
FORMATS["format_ws_title"],
)
row_pos += 1
sheet.write(row_pos, 1, _("Date:"), FORMATS["format_theader_yellow_right"])
sheet.write(
row_pos,
2,
data.get("data", {}).get(partners.ids[0], {}).get("today"),
FORMATS["format_date_left"],
)
self._size_columns(sheet, data)
for partner in partners:
invoice_address = data.get(
"get_inv_addr", lambda x: self.env["res.partner"]
)(partner)
row_pos += 3
sheet.write(
row_pos, 1, _("Statement to:"), FORMATS["format_theader_yellow_right"]
)
sheet.merge_range(
row_pos,
2,
row_pos,
3,
invoice_address.display_name,
FORMATS["format_left"],
)
if invoice_address.vat:
sheet.write(
row_pos,
4,
_("VAT:"),
FORMATS["format_theader_yellow_right"],
)
sheet.write(
row_pos,
5,
invoice_address.vat,
FORMATS["format_left"],
)
row_pos += 1
sheet.write(
row_pos, 1, _("Statement from:"), FORMATS["format_theader_yellow_right"]
)
sheet.merge_range(
row_pos,
2,
row_pos,
3,
company.partner_id.display_name,
FORMATS["format_left"],
)
if company.vat:
sheet.write(
row_pos,
4,
_("VAT:"),
FORMATS["format_theader_yellow_right"],
)
sheet.write(
row_pos,
5,
company.vat,
FORMATS["format_left"],
)
partner_data = data.get("data", {}).get(partner.id)
currencies = partner_data.get("currencies", {}).keys()
if currencies:
row_pos += 1
for currency_id in currencies:
currency = self.env["res.currency"].browse(currency_id)
if currency.position == "after":
money_string = "#,##0.%s " % (
"0" * currency.decimal_places
) + "[${}]".format(currency.symbol)
elif currency.position == "before":
money_string = "[${}]".format(currency.symbol) + " #,##0.%s" % (
"0" * currency.decimal_places
)
FORMATS["current_money_format"] = workbook.add_format(
{"align": "right", "num_format": money_string}
)
bg_grey = "#ADB5BD"
FORMATS["format_tcell_left_blocked"] = copy_format(
workbook, FORMATS["format_tcell_left"]
)
FORMATS["format_tcell_left_blocked"].set_bg_color(bg_grey)
FORMATS["format_tcell_date_left_blocked"] = copy_format(
workbook, FORMATS["format_tcell_date_left"]
)
FORMATS["format_tcell_date_left_blocked"].set_bg_color(bg_grey)
FORMATS["format_distributed_blocked"] = copy_format(
workbook, FORMATS["format_distributed"]
)
FORMATS["format_distributed_blocked"].set_bg_color(bg_grey)
FORMATS["current_money_format_blocked"] = copy_format(
workbook, FORMATS["current_money_format"]
)
FORMATS["current_money_format_blocked"].set_bg_color(bg_grey)
row_pos = self._write_currency_lines(
row_pos, sheet, partner, currency, data
)
row_pos = self._write_currency_buckets(
row_pos, sheet, partner, currency, data
)

View file

@ -0,0 +1,613 @@
# Copyright 2018 ForgeFlow, S.L. (https://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from datetime import datetime, timedelta
from odoo import _, api, fields, models
from odoo.tools.misc import DEFAULT_SERVER_DATE_FORMAT
class ReportStatementCommon(models.AbstractModel):
"""Abstract Report Statement for use in other models"""
_name = "statement.common"
_description = "Statement Reports Common"
def _get_invoice_address(self, part):
inv_addr_id = part.address_get(["invoice"]).get("invoice", part.id)
return self.env["res.partner"].browse(inv_addr_id)
def _get_title(self, partner, **kwargs):
raise NotImplementedError
def _get_aging_buckets_title(self, partner, **kwargs):
kwargs["context"] = {
"lang": partner.lang,
}
return _("Aging Report at %(ending_date)s in %(currency)s", **kwargs)
def _format_date_to_partner_lang(
self, date, date_format=DEFAULT_SERVER_DATE_FORMAT
):
if isinstance(date, str):
date = datetime.strptime(date, DEFAULT_SERVER_DATE_FORMAT)
return date.strftime(date_format) if date else ""
def _get_account_display_lines(
self, company_id, partner_ids, date_start, date_end, account_type
):
raise NotImplementedError
def _get_account_initial_balance(
self, company_id, partner_ids, date_start, account_type
):
return {}
def _get_account_display_prior_lines(
self, company_id, partner_ids, date_start, date_end, account_type
):
return {}
def _get_account_display_reconciled_lines(
self, company_id, partner_ids, date_start, date_end, account_type
):
return {}
def _get_account_display_ending_lines(
self, company_id, partner_ids, date_start, date_end, account_type
):
return {}
def _show_buckets_sql_q1(self, partners, date_end, account_type):
excluded_accounts_ids = tuple(
self.env.context.get("excluded_accounts_ids", [])
) or (-1,)
show_only_overdue = self.env.context.get("show_only_overdue", False)
return str(
self._cr.mogrify(
"""
SELECT l.partner_id, l.currency_id, l.company_id, l.move_id,
CASE WHEN l.balance > 0.0
THEN l.balance - sum(coalesce(pd.amount, 0.0))
ELSE l.balance + sum(coalesce(pc.amount, 0.0))
END AS open_due,
CASE WHEN l.balance > 0.0
THEN l.amount_currency - sum(coalesce(pd.debit_amount_currency, 0.0))
ELSE l.amount_currency + sum(coalesce(pc.credit_amount_currency, 0.0))
END AS open_due_currency,
CASE WHEN l.date_maturity is null
THEN l.date
ELSE l.date_maturity
END as date_maturity
FROM account_move_line l
JOIN account_move m ON (l.move_id = m.id)
JOIN account_account aa ON (aa.id = l.account_id)
LEFT JOIN (SELECT pr.*
FROM account_partial_reconcile pr
INNER JOIN account_move_line l2
ON pr.credit_move_id = l2.id
WHERE l2.date <= %(date_end)s
) as pd ON pd.debit_move_id = l.id
LEFT JOIN (SELECT pr.*
FROM account_partial_reconcile pr
INNER JOIN account_move_line l2
ON pr.debit_move_id = l2.id
WHERE l2.date <= %(date_end)s
) as pc ON pc.credit_move_id = l.id
WHERE l.partner_id IN %(partners)s
AND aa.id not in %(excluded_accounts_ids)s
AND (
(pd.id IS NOT NULL AND
pd.max_date <= %(date_end)s) OR
(pc.id IS NOT NULL AND
pc.max_date <= %(date_end)s) OR
(pd.id IS NULL AND pc.id IS NULL)
) AND l.date <= %(date_end)s AND not l.blocked
AND m.state IN ('posted')
AND aa.account_type = %(account_type)s
AND CASE
WHEN %(show_only_overdue)s
THEN COALESCE(l.date_maturity, l.date) <= %(date_end)s
ELSE TRUE
END
GROUP BY l.partner_id, l.currency_id, l.date, l.date_maturity,
l.amount_currency, l.balance, l.move_id, l.company_id, l.id
""",
locals(),
),
"utf-8",
)
def _show_buckets_sql_q2(self, date_end, minus_30, minus_60, minus_90, minus_120):
return str(
self._cr.mogrify(
"""
SELECT partner_id, currency_id, date_maturity, open_due,
open_due_currency, move_id, company_id,
CASE
WHEN %(date_end)s <= date_maturity AND currency_id is null
THEN open_due
WHEN %(date_end)s <= date_maturity AND currency_id is not null
THEN open_due_currency
ELSE 0.0
END as current,
CASE
WHEN %(minus_30)s < date_maturity
AND date_maturity < %(date_end)s
AND currency_id is null
THEN open_due
WHEN %(minus_30)s < date_maturity
AND date_maturity < %(date_end)s
AND currency_id is not null
THEN open_due_currency
ELSE 0.0
END as b_1_30,
CASE
WHEN %(minus_60)s < date_maturity
AND date_maturity <= %(minus_30)s
AND currency_id is null
THEN open_due
WHEN %(minus_60)s < date_maturity
AND date_maturity <= %(minus_30)s
AND currency_id is not null
THEN open_due_currency
ELSE 0.0
END as b_30_60,
CASE
WHEN %(minus_90)s < date_maturity
AND date_maturity <= %(minus_60)s
AND currency_id is null
THEN open_due
WHEN %(minus_90)s < date_maturity
AND date_maturity <= %(minus_60)s
AND currency_id is not null
THEN open_due_currency
ELSE 0.0
END as b_60_90,
CASE
WHEN %(minus_120)s < date_maturity
AND date_maturity <= %(minus_90)s
AND currency_id is null
THEN open_due
WHEN %(minus_120)s < date_maturity
AND date_maturity <= %(minus_90)s
AND currency_id is not null
THEN open_due_currency
ELSE 0.0
END as b_90_120,
CASE
WHEN date_maturity <= %(minus_120)s
AND currency_id is null
THEN open_due
WHEN date_maturity <= %(minus_120)s
AND currency_id is not null
THEN open_due_currency
ELSE 0.0
END as b_over_120
FROM Q1
GROUP BY partner_id, currency_id, date_maturity, open_due,
open_due_currency, move_id, company_id
""",
locals(),
),
"utf-8",
)
def _show_buckets_sql_q3(self, company_id):
return str(
self._cr.mogrify(
"""
SELECT Q2.partner_id, current, b_1_30, b_30_60, b_60_90, b_90_120,
b_over_120,
COALESCE(Q2.currency_id, c.currency_id) AS currency_id
FROM Q2
JOIN res_company c ON (c.id = Q2.company_id)
WHERE c.id = %(company_id)s
""",
locals(),
),
"utf-8",
)
def _show_buckets_sql_q4(self):
return """
SELECT partner_id, currency_id, sum(current) as current,
sum(b_1_30) as b_1_30, sum(b_30_60) as b_30_60,
sum(b_60_90) as b_60_90, sum(b_90_120) as b_90_120,
sum(b_over_120) as b_over_120
FROM Q3
GROUP BY partner_id, currency_id
"""
def _get_bucket_dates(self, date_end, aging_type):
return getattr(
self, "_get_bucket_dates_%s" % aging_type, self._get_bucket_dates_days
)(date_end)
def _get_bucket_dates_days(self, date_end):
return {
"date_end": date_end,
"minus_30": date_end - timedelta(days=30),
"minus_60": date_end - timedelta(days=60),
"minus_90": date_end - timedelta(days=90),
"minus_120": date_end - timedelta(days=120),
}
def _get_bucket_dates_months(self, date_end):
res = {}
d = date_end
for k in ("date_end", "minus_30", "minus_60", "minus_90", "minus_120"):
res[k] = d
d = d.replace(day=1) - timedelta(days=1)
return res
def _get_account_show_buckets(
self, company_id, partner_ids, date_end, account_type, aging_type
):
buckets = dict(map(lambda x: (x, []), partner_ids))
partners = tuple(partner_ids)
full_dates = self._get_bucket_dates(date_end, aging_type)
# pylint: disable=E8103
# All input queries are properly escaped - false positive
self.env.cr.execute(
"""
WITH Q1 AS (%s),
Q2 AS (%s),
Q3 AS (%s),
Q4 AS (%s)
SELECT partner_id, currency_id, current, b_1_30, b_30_60, b_60_90,
b_90_120, b_over_120,
current+b_1_30+b_30_60+b_60_90+b_90_120+b_over_120
AS balance
FROM Q4
GROUP BY partner_id, currency_id, current, b_1_30, b_30_60,
b_60_90, b_90_120, b_over_120"""
% (
self._show_buckets_sql_q1(partners, date_end, account_type),
self._show_buckets_sql_q2(
full_dates["date_end"],
full_dates["minus_30"],
full_dates["minus_60"],
full_dates["minus_90"],
full_dates["minus_120"],
),
self._show_buckets_sql_q3(company_id),
self._show_buckets_sql_q4(),
)
)
for row in self.env.cr.dictfetchall():
buckets[row.pop("partner_id")].append(row)
return buckets
def _get_bucket_labels(self, date_end, aging_type):
return getattr(
self, "_get_bucket_labels_%s" % aging_type, self._get_bucket_dates_days
)(date_end)
def _get_bucket_labels_days(self, date_end):
return [
_("Current"),
_("1 - 30 Days"),
_("31 - 60 Days"),
_("61 - 90 Days"),
_("91 - 120 Days"),
_("121 Days +"),
_("Total"),
]
def _get_bucket_labels_months(self, date_end):
return [
_("Current"),
_("1 Month"),
_("2 Months"),
_("3 Months"),
_("4 Months"),
_("Older"),
_("Total"),
]
def _get_line_currency_defaults(
self, currency_id, currencies, balance_forward, amount_due
):
if currency_id not in currencies:
# This will only happen if currency is inactive
currencies[currency_id] = self.env["res.currency"].browse(currency_id)
return (
{
"prior_lines": [],
"lines": [],
"ending_lines": [],
"buckets": [],
"balance_forward": balance_forward,
"amount_due": amount_due,
"ending_balance": 0.0,
},
currencies,
)
def _add_currency_line(self, line, currency):
return [line]
def _add_currency_prior_line(self, line, currency):
return [line]
def _add_currency_ending_line(self, line, currency):
return [line]
@api.model
def _get_report_values(self, docids, data=None):
# flake8: noqa: C901
"""
@return: returns a dict of parameters to pass to qweb report.
the most important pair is {'data': res} which contains all
the data for each partner. It is structured like:
{partner_id: {
'start': date string,
'end': date_string,
'today': date_string
'currencies': {
currency_id: {
'lines': [{'date': date string, ...}, ...],
'balance_forward': float,
'amount_due': float,
'buckets': {
'p1': float, 'p2': ...
}
}
}
}
"""
company_id = data["company_id"]
partner_ids = data["partner_ids"]
date_start = data.get("date_start")
if date_start and isinstance(date_start, str):
date_start = datetime.strptime(
date_start, DEFAULT_SERVER_DATE_FORMAT
).date()
date_end = data["date_end"]
if isinstance(date_end, str):
date_end = datetime.strptime(date_end, DEFAULT_SERVER_DATE_FORMAT).date()
account_type = data["account_type"]
excluded_accounts_ids = data["excluded_accounts_ids"]
if excluded_accounts_ids:
self = self.with_context(
excluded_accounts_ids=excluded_accounts_ids,
)
show_only_overdue = data["show_only_overdue"]
if show_only_overdue:
self = self.with_context(
show_only_overdue=show_only_overdue,
)
aging_type = data["aging_type"]
is_activity = data.get("is_activity")
is_detailed = data.get("is_detailed")
today = fields.Date.context_today(self)
amount_field = data.get("amount_field", "amount")
# There should be relatively few of these, so to speed performance
# we cache them - default needed if partner lang not set
self._cr.execute(
"""
SELECT p.id, l.date_format
FROM res_partner p LEFT JOIN res_lang l ON p.lang=l.code
WHERE p.id IN %(partner_ids)s
""",
{"partner_ids": tuple(partner_ids)},
)
date_formats = {r[0]: r[1] for r in self._cr.fetchall()}
default_fmt = self.env["res.lang"]._lang_get(self.env.user.lang).date_format
currencies = {x.id: x for x in self.env["res.currency"].search([])}
res = {}
# get base data
prior_day = date_start - timedelta(days=1) if date_start else None
prior_lines = (
self._get_account_display_prior_lines(
company_id, partner_ids, prior_day, prior_day, account_type
)
if is_detailed
else {}
)
lines = self._get_account_display_lines(
company_id, partner_ids, date_start, date_end, account_type
)
ending_lines = (
self._get_account_display_ending_lines(
company_id, partner_ids, date_start, date_end, account_type
)
if is_detailed
else {}
)
reconciled_lines = (
self._get_account_display_reconciled_lines(
company_id, partner_ids, date_start, date_end, account_type
)
if is_activity
else {}
)
balances_forward = self._get_account_initial_balance(
company_id, partner_ids, date_start, account_type
)
if data["show_aging_buckets"]:
buckets = self._get_account_show_buckets(
company_id, partner_ids, date_end, account_type, aging_type
)
bucket_labels = self._get_bucket_labels(date_end, aging_type)
else:
bucket_labels = {}
# organize and format for report
format_date = self._format_date_to_partner_lang
partners_to_remove = set()
for partner_id in partner_ids:
res[partner_id] = {
"today": format_date(today, date_formats.get(partner_id, default_fmt)),
"start": format_date(
date_start, date_formats.get(partner_id, default_fmt)
),
"end": format_date(date_end, date_formats.get(partner_id, default_fmt)),
"prior_day": format_date(
prior_day, date_formats.get(partner_id, default_fmt)
),
"currencies": {},
}
currency_dict = res[partner_id]["currencies"]
for line in balances_forward.get(partner_id, []):
(
currency_dict[line["currency_id"]],
currencies,
) = self._get_line_currency_defaults(
line["currency_id"],
currencies,
line["balance"],
0.0 if is_detailed else line["balance"],
)
for line in prior_lines.get(partner_id, []):
if line["currency_id"] not in currency_dict:
(
currency_dict[line["currency_id"]],
currencies,
) = self._get_line_currency_defaults(
line["currency_id"], currencies, 0.0, 0.0
)
line_currency = currency_dict[line["currency_id"]]
if not line["blocked"]:
line_currency["amount_due"] += line["open_amount"]
line["balance"] = line_currency["amount_due"]
line["date"] = format_date(
line["date"], date_formats.get(partner_id, default_fmt)
)
line["date_maturity"] = format_date(
line["date_maturity"], date_formats.get(partner_id, default_fmt)
)
line_currency["prior_lines"].extend(
self._add_currency_prior_line(line, currencies[line["currency_id"]])
)
for line in lines[partner_id]:
if line["currency_id"] not in currency_dict:
(
currency_dict[line["currency_id"]],
currencies,
) = self._get_line_currency_defaults(
line["currency_id"], currencies, 0.0, 0.0
)
line_currency = currency_dict[line["currency_id"]]
if not is_activity:
if not line["blocked"]:
line_currency["amount_due"] += line[amount_field]
line["balance"] = line_currency["amount_due"]
else:
if not line["blocked"]:
line_currency["ending_balance"] += line[amount_field]
line["balance"] = line_currency["ending_balance"]
line["outside-date-rank"] = False
line["date"] = format_date(
line["date"], date_formats.get(partner_id, default_fmt)
)
line["date_maturity"] = format_date(
line["date_maturity"], date_formats.get(partner_id, default_fmt)
)
line["reconciled_line"] = False
if is_activity:
line["open_amount"] = 0.0
line["applied_amount"] = 0.0
line_currency["lines"].extend(
self._add_currency_line(line, currencies[line["currency_id"]])
)
for line2 in reconciled_lines:
if line2["id"] in line["ids"]:
line2["reconciled_line"] = True
line2["applied_amount"] = line2["open_amount"]
if line2["date"] >= date_start and line2["date"] <= date_end:
line2["outside-date-rank"] = False
if not line2["blocked"]:
line["applied_amount"] += line2["open_amount"]
else:
line2["outside-date-rank"] = True
line2["date"] = format_date(
line2["date"], date_formats.get(partner_id, default_fmt)
)
line2["date_maturity"] = format_date(
line2["date_maturity"],
date_formats.get(partner_id, default_fmt),
)
if is_detailed:
line_currency["lines"].extend(
self._add_currency_line(
line2, currencies[line["currency_id"]]
)
)
if is_activity:
line["open_amount"] = line["amount"] + line["applied_amount"]
if not line["blocked"]:
line_currency["amount_due"] += line["open_amount"]
if is_detailed:
for line_currency in currency_dict.values():
line_currency["amount_due"] = 0.0
for line in ending_lines.get(partner_id, []):
line_currency = currency_dict[line["currency_id"]]
if not line["blocked"]:
line_currency["amount_due"] += line["open_amount"]
line["balance"] = line_currency["amount_due"]
line["date"] = format_date(
line["date"], date_formats.get(partner_id, default_fmt)
)
line["date_maturity"] = format_date(
line["date_maturity"], date_formats.get(partner_id, default_fmt)
)
line_currency["ending_lines"].extend(
self._add_currency_ending_line(
line, currencies[line["currency_id"]]
)
)
if data["show_aging_buckets"]:
for line in buckets[partner_id]:
if line["currency_id"] not in currency_dict:
(
currency_dict[line["currency_id"]],
currencies,
) = self._get_line_currency_defaults(
line["currency_id"], currencies, 0.0, 0.0
)
line_currency = currency_dict[line["currency_id"]]
line_currency["buckets"] = line
if len(partner_ids) > 1:
values = currency_dict.values()
if not any([v["lines"] or v["balance_forward"] for v in values]):
if data["filter_non_due_partners"]:
partners_to_remove.add(partner_id)
continue
else:
res[partner_id]["no_entries"] = True
if data["filter_negative_balances"]:
if not all([v["amount_due"] >= 0.0 for v in values]):
partners_to_remove.add(partner_id)
for partner in partners_to_remove:
del res[partner]
partner_ids.remove(partner)
return {
"doc_ids": partner_ids,
"doc_model": "res.partner",
"docs": self.env["res.partner"].browse(partner_ids),
"data": res,
"company": self.env["res.company"].browse(company_id),
"Currencies": currencies,
"account_type": account_type,
"excluded_accounts_ids": excluded_accounts_ids,
"show_only_overdue": show_only_overdue,
"is_detailed": is_detailed,
"bucket_labels": bucket_labels,
"get_inv_addr": self._get_invoice_address,
"get_title": self._get_title,
"get_aging_buckets_title": self._get_aging_buckets_title,
}