size
int64 0
304k
| ext
stringclasses 1
value | lang
stringclasses 1
value | branch
stringclasses 1
value | content
stringlengths 0
304k
| avg_line_length
float64 0
238
| max_line_length
int64 0
304k
|
|---|---|---|---|---|---|---|
1,540
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).-
from odoo import api, models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
def init(self):
"""
The join between accounts_partners subquery and account_move_line
can be heavy to compute on big databases.
Join sample:
JOIN
account_move_line ml
ON ap.account_id = ml.account_id
AND ml.date < '2018-12-30'
AND ap.partner_id = ml.partner_id
AND ap.include_initial_balance = TRUE
By adding the following index, performances are strongly increased.
:return:
"""
self._cr.execute(
"SELECT indexname FROM pg_indexes WHERE indexname = " "%s",
("account_move_line_account_id_partner_id_index",),
)
if not self._cr.fetchone():
self._cr.execute(
"""
CREATE INDEX account_move_line_account_id_partner_id_index
ON account_move_line (account_id, partner_id)"""
)
@api.model
def search_count(self, args):
# In Big DataBase every time you change the domain widget this method
# takes a lot of time. This improves performance
if self.env.context.get("skip_search_count"):
return 0
return super(AccountMoveLine, self).search_count(args)
| 38.5
| 1,540
|
2,681
|
py
|
PYTHON
|
15.0
|
# © 2018 Forest and Biomass Romania SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class AccountGroup(models.Model):
_inherit = "account.group"
group_child_ids = fields.One2many(
comodel_name="account.group", inverse_name="parent_id", string="Child Groups"
)
level = fields.Integer(compute="_compute_level", recursive=True)
account_ids = fields.One2many(
comodel_name="account.account", inverse_name="group_id", string="Accounts"
)
compute_account_ids = fields.Many2many(
"account.account",
compute="_compute_group_accounts",
string="Compute accounts",
store=True,
)
complete_name = fields.Char(
"Full Name", compute="_compute_complete_name", recursive=True
)
complete_code = fields.Char(
"Full Code", compute="_compute_complete_code", recursive=True
)
@api.depends("name", "parent_id.complete_name")
def _compute_complete_name(self):
"""Forms complete name of location from parent location to child location."""
for group in self:
if group.parent_id.complete_name:
group.complete_name = "{}/{}".format(
group.parent_id.complete_name, group.name
)
else:
group.complete_name = group.name
@api.depends("code_prefix_start", "parent_id.complete_code")
def _compute_complete_code(self):
"""Forms complete code of location from parent location to child location."""
for group in self:
if group.parent_id.complete_code:
group.complete_code = "{}/{}".format(
group.parent_id.complete_code, group.code_prefix_start
)
else:
group.complete_code = group.code_prefix_start
@api.depends("parent_id", "parent_id.level")
def _compute_level(self):
for group in self:
if not group.parent_id:
group.level = 0
else:
group.level = group.parent_id.level + 1
@api.depends(
"code_prefix_start",
"account_ids",
"account_ids.code",
"group_child_ids",
"group_child_ids.account_ids.code",
)
def _compute_group_accounts(self):
account_obj = self.env["account.account"]
accounts = account_obj.search([])
for group in self:
prefix = group.code_prefix_start if group.code_prefix_start else group.name
gr_acc = accounts.filtered(lambda a: a.code.startswith(prefix)).ids
group.compute_account_ids = [(6, 0, gr_acc)]
| 36.712329
| 2,680
|
422
|
py
|
PYTHON
|
15.0
|
# © 2011 Guewen Baconnier (Camptocamp)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).-
from odoo import fields, models
class AccountAccount(models.Model):
_inherit = "account.account"
centralized = fields.Boolean(
help="If flagged, no details will be displayed in "
"the General Ledger report (the webkit one only), "
"only centralized amounts per period.",
)
| 32.384615
| 421
|
11,914
|
py
|
PYTHON
|
15.0
|
# © 2016 Julien Coux (Camptocamp)
# Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import operator
from datetime import date, datetime
from odoo import api, models
from odoo.tools import float_is_zero
class OpenItemsReport(models.AbstractModel):
_name = "report.account_financial_report.open_items"
_description = "Open Items Report"
_inherit = "report.account_financial_report.abstract_report"
def _get_account_partial_reconciled(self, company_id, date_at_object):
domain = [("max_date", ">", date_at_object), ("company_id", "=", company_id)]
fields = [
"debit_move_id",
"credit_move_id",
"amount",
"debit_amount_currency",
"credit_amount_currency",
]
accounts_partial_reconcile = self.env["account.partial.reconcile"].search_read(
domain=domain, fields=fields
)
debit_amount = {}
debit_amount_currency = {}
credit_amount = {}
credit_amount_currency = {}
for account_partial_reconcile_data in accounts_partial_reconcile:
debit_move_id = account_partial_reconcile_data["debit_move_id"][0]
credit_move_id = account_partial_reconcile_data["credit_move_id"][0]
if debit_move_id not in debit_amount.keys():
debit_amount[debit_move_id] = 0.0
debit_amount_currency[debit_move_id] = 0.0
debit_amount[debit_move_id] += account_partial_reconcile_data["amount"]
debit_amount_currency[debit_move_id] += account_partial_reconcile_data[
"debit_amount_currency"
]
if credit_move_id not in credit_amount.keys():
credit_amount[credit_move_id] = 0.0
credit_amount_currency[credit_move_id] = 0.0
credit_amount[credit_move_id] += account_partial_reconcile_data["amount"]
credit_amount_currency[credit_move_id] += account_partial_reconcile_data[
"credit_amount_currency"
]
account_partial_reconcile_data.update(
{"debit_move_id": debit_move_id, "credit_move_id": credit_move_id}
)
return (
accounts_partial_reconcile,
debit_amount,
credit_amount,
debit_amount_currency,
credit_amount_currency,
)
def _get_data(
self,
account_ids,
partner_ids,
date_at_object,
only_posted_moves,
company_id,
date_from,
):
domain = self._get_move_lines_domain_not_reconciled(
company_id, account_ids, partner_ids, only_posted_moves, date_from
)
ml_fields = self._get_ml_fields()
move_lines = self.env["account.move.line"].search_read(
domain=domain, fields=ml_fields
)
journals_ids = set()
partners_ids = set()
partners_data = {}
if date_at_object < date.today():
(
acc_partial_rec,
debit_amount,
credit_amount,
debit_amount_currency,
credit_amount_currency,
) = self._get_account_partial_reconciled(company_id, date_at_object)
if acc_partial_rec:
ml_ids = list(map(operator.itemgetter("id"), move_lines))
debit_ids = list(
map(operator.itemgetter("debit_move_id"), acc_partial_rec)
)
credit_ids = list(
map(operator.itemgetter("credit_move_id"), acc_partial_rec)
)
move_lines = self._recalculate_move_lines(
move_lines,
debit_ids,
credit_ids,
debit_amount,
credit_amount,
ml_ids,
account_ids,
company_id,
partner_ids,
only_posted_moves,
debit_amount_currency,
credit_amount_currency,
)
move_lines = [
move_line
for move_line in move_lines
if move_line["date"] <= date_at_object
and not float_is_zero(move_line["amount_residual"], precision_digits=2)
]
open_items_move_lines_data = {}
for move_line in move_lines:
journals_ids.add(move_line["journal_id"][0])
acc_id = move_line["account_id"][0]
# Partners data
if move_line["partner_id"]:
prt_id = move_line["partner_id"][0]
prt_name = move_line["partner_id"][1]
else:
prt_id = 0
prt_name = "Missing Partner"
if prt_id not in partners_ids:
partners_data.update({prt_id: {"id": prt_id, "name": prt_name}})
partners_ids.add(prt_id)
# Move line update
original = 0
if not float_is_zero(move_line["credit"], precision_digits=2):
original = move_line["credit"] * (-1)
if not float_is_zero(move_line["debit"], precision_digits=2):
original = move_line["debit"]
if move_line["ref"] == move_line["name"]:
if move_line["ref"]:
ref_label = move_line["ref"]
else:
ref_label = ""
elif not move_line["ref"]:
ref_label = move_line["name"]
elif not move_line["name"]:
ref_label = move_line["ref"]
else:
ref_label = move_line["ref"] + str(" - ") + move_line["name"]
move_line.update(
{
"date": move_line["date"],
"date_maturity": move_line["date_maturity"]
and move_line["date_maturity"].strftime("%d/%m/%Y"),
"original": original,
"partner_id": prt_id,
"partner_name": prt_name,
"ref_label": ref_label,
"journal_id": move_line["journal_id"][0],
"move_name": move_line["move_id"][1],
"entry_id": move_line["move_id"][0],
"currency_id": move_line["currency_id"][0]
if move_line["currency_id"]
else False,
"currency_name": move_line["currency_id"][1]
if move_line["currency_id"]
else False,
}
)
# Open Items Move Lines Data
if acc_id not in open_items_move_lines_data.keys():
open_items_move_lines_data[acc_id] = {prt_id: [move_line]}
else:
if prt_id not in open_items_move_lines_data[acc_id].keys():
open_items_move_lines_data[acc_id][prt_id] = [move_line]
else:
open_items_move_lines_data[acc_id][prt_id].append(move_line)
journals_data = self._get_journals_data(list(journals_ids))
accounts_data = self._get_accounts_data(open_items_move_lines_data.keys())
return (
move_lines,
partners_data,
journals_data,
accounts_data,
open_items_move_lines_data,
)
@api.model
def _calculate_amounts(self, open_items_move_lines_data):
total_amount = {}
for account_id in open_items_move_lines_data.keys():
total_amount[account_id] = {}
total_amount[account_id]["residual"] = 0.0
for partner_id in open_items_move_lines_data[account_id].keys():
total_amount[account_id][partner_id] = {}
total_amount[account_id][partner_id]["residual"] = 0.0
for move_line in open_items_move_lines_data[account_id][partner_id]:
total_amount[account_id][partner_id]["residual"] += move_line[
"amount_residual"
]
total_amount[account_id]["residual"] += move_line["amount_residual"]
return total_amount
@api.model
def _order_open_items_by_date(
self, open_items_move_lines_data, show_partner_details, partners_data
):
new_open_items = {}
if not show_partner_details:
for acc_id in open_items_move_lines_data.keys():
new_open_items[acc_id] = {}
move_lines = []
for prt_id in open_items_move_lines_data[acc_id]:
for move_line in open_items_move_lines_data[acc_id][prt_id]:
move_lines += [move_line]
move_lines = sorted(move_lines, key=lambda k: (k["date"]))
new_open_items[acc_id] = move_lines
else:
for acc_id in open_items_move_lines_data.keys():
new_open_items[acc_id] = {}
for prt_id in sorted(
open_items_move_lines_data[acc_id],
key=lambda i: partners_data[i]["name"],
):
new_open_items[acc_id][prt_id] = {}
move_lines = []
for move_line in open_items_move_lines_data[acc_id][prt_id]:
move_lines += [move_line]
move_lines = sorted(move_lines, key=lambda k: (k["date"]))
new_open_items[acc_id][prt_id] = move_lines
return new_open_items
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"]
account_ids = data["account_ids"]
partner_ids = data["partner_ids"]
date_at = data["date_at"]
date_at_object = datetime.strptime(date_at, "%Y-%m-%d").date()
date_from = data["date_from"]
only_posted_moves = data["only_posted_moves"]
show_partner_details = data["show_partner_details"]
(
move_lines_data,
partners_data,
journals_data,
accounts_data,
open_items_move_lines_data,
) = self._get_data(
account_ids,
partner_ids,
date_at_object,
only_posted_moves,
company_id,
date_from,
)
total_amount = self._calculate_amounts(open_items_move_lines_data)
open_items_move_lines_data = self._order_open_items_by_date(
open_items_move_lines_data, show_partner_details, partners_data
)
return {
"doc_ids": [wizard_id],
"doc_model": "open.items.report.wizard",
"docs": self.env["open.items.report.wizard"].browse(wizard_id),
"foreign_currency": data["foreign_currency"],
"show_partner_details": data["show_partner_details"],
"company_name": company.display_name,
"currency_name": company.currency_id.name,
"date_at": date_at_object.strftime("%d/%m/%Y"),
"hide_account_at_0": data["hide_account_at_0"],
"target_move": data["target_move"],
"journals_data": journals_data,
"partners_data": partners_data,
"accounts_data": accounts_data,
"total_amount": total_amount,
"Open_Items": open_items_move_lines_data,
}
def _get_ml_fields(self):
return self.COMMON_ML_FIELDS + [
"amount_residual",
"reconciled",
"currency_id",
"credit",
"date_maturity",
"amount_residual_currency",
"debit",
"amount_currency",
]
| 40.383051
| 11,913
|
8,395
|
py
|
PYTHON
|
15.0
|
# Author: Julien Coux
# Copyright 2016 Camptocamp SA
# Copyright 2021 Tecnativa - João Marques
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import _, models
class OpenItemsXslx(models.AbstractModel):
_name = "report.a_f_r.report_open_items_xlsx"
_description = "Open Items XLSX Report"
_inherit = "report.account_financial_report.abstract_report_xlsx"
def _get_report_name(self, report, data=False):
company_id = data.get("company_id", False)
report_name = _("Open Items")
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_report_columns(self, report):
res = {
0: {"header": _("Date"), "field": "date", "width": 11},
1: {"header": _("Entry"), "field": "move_name", "width": 18},
2: {"header": _("Journal"), "field": "journal", "width": 8},
3: {"header": _("Account"), "field": "account", "width": 9},
4: {"header": _("Partner"), "field": "partner_name", "width": 25},
5: {"header": _("Ref - Label"), "field": "ref_label", "width": 40},
6: {"header": _("Due date"), "field": "date_maturity", "width": 11},
7: {
"header": _("Original"),
"field": "original",
"type": "amount",
"width": 14,
},
8: {
"header": _("Residual"),
"field": "amount_residual",
"field_final_balance": "residual",
"type": "amount",
"width": 14,
},
}
if report.foreign_currency:
foreign_currency = {
9: {
"header": _("Cur."),
"field": "currency_name",
"field_currency_balance": "currency_name",
"type": "currency_name",
"width": 7,
},
10: {
"header": _("Cur. Original"),
"field": "amount_currency",
"field_final_balance": "amount_currency",
"type": "amount_currency",
"width": 14,
},
11: {
"header": _("Cur. Residual"),
"field": "amount_residual_currency",
"field_final_balance": "amount_currency",
"type": "amount_currency",
"width": 14,
},
}
res = {**res, **foreign_currency}
return res
def _get_report_filters(self, report):
return [
[_("Date at filter"), report.date_at.strftime("%d/%m/%Y")],
[
_("Target moves filter"),
_("All posted entries")
if report.target_move == "posted"
else _("All entries"),
],
[
_("Account balance at 0 filter"),
_("Hide") if report.hide_account_at_0 else _("Show"),
],
[
_("Show foreign currency"),
_("Yes") if report.foreign_currency else _("No"),
],
]
def _get_col_count_filter_name(self):
return 2
def _get_col_count_filter_value(self):
return 2
def _get_col_count_final_balance_name(self):
return 5
def _get_col_pos_final_balance_label(self):
return 5
def _generate_report_content(self, workbook, report, data, report_data):
res_data = self.env[
"report.account_financial_report.open_items"
]._get_report_values(report, data)
# For each account
Open_items = res_data["Open_Items"]
accounts_data = res_data["accounts_data"]
partners_data = res_data["partners_data"]
journals_data = res_data["journals_data"]
total_amount = res_data["total_amount"]
show_partner_details = res_data["show_partner_details"]
for account_id in Open_items.keys():
# Write account title
self.write_array_title(
accounts_data[account_id]["code"]
+ " - "
+ accounts_data[account_id]["name"],
report_data,
)
# For each partner
if Open_items[account_id]:
if show_partner_details:
for partner_id in Open_items[account_id]:
type_object = "partner"
# Write partner title
self.write_array_title(
partners_data[partner_id]["name"], report_data
)
# Display array header for move lines
self.write_array_header(report_data)
# Display account move lines
for line in Open_items[account_id][partner_id]:
line.update(
{
"account": accounts_data[account_id]["code"],
"journal": journals_data[line["journal_id"]][
"code"
],
}
)
self.write_line_from_dict(line, report_data)
# Display ending balance line for partner
partners_data[partner_id].update(
{
"currency_id": accounts_data[account_id]["currency_id"],
"currency_name": accounts_data[account_id][
"currency_name"
],
}
)
self.write_ending_balance_from_dict(
partners_data[partner_id],
type_object,
total_amount,
report_data,
account_id=account_id,
partner_id=partner_id,
)
# Line break
report_data["row_pos"] += 1
else:
# Display array header for move lines
self.write_array_header(report_data)
# Display account move lines
for line in Open_items[account_id]:
line.update(
{
"account": accounts_data[account_id]["code"],
"journal": journals_data[line["journal_id"]]["code"],
}
)
self.write_line_from_dict(line, report_data)
# Display ending balance line for account
type_object = "account"
self.write_ending_balance_from_dict(
accounts_data[account_id],
type_object,
total_amount,
report_data,
account_id=account_id,
)
# 2 lines break
report_data["row_pos"] += 2
def write_ending_balance_from_dict(
self,
my_object,
type_object,
total_amount,
report_data,
account_id=False,
partner_id=False,
):
"""Specific function to write ending balance for Open Items"""
if type_object == "partner":
name = my_object["name"]
my_object["residual"] = total_amount[account_id][partner_id]["residual"]
label = _("Partner ending balance")
elif type_object == "account":
name = my_object["code"] + " - " + my_object["name"]
my_object["residual"] = total_amount[account_id]["residual"]
label = _("Ending balance")
return super(OpenItemsXslx, self).write_ending_balance_from_dict(
my_object, name, label, report_data
)
| 38.861111
| 8,394
|
10,163
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Forest and Biomass Romania
# Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import operator
from odoo import api, models
class VATReport(models.AbstractModel):
_name = "report.account_financial_report.vat_report"
_description = "Vat Report Report"
def _get_tax_data(self, tax_ids):
taxes = self.env["account.tax"].browse(tax_ids)
tax_data = {}
for tax in taxes:
tax_data.update(
{
tax.id: {
"id": tax.id,
"name": tax.name,
"tax_group_id": tax.tax_group_id.id,
"type_tax_use": tax.type_tax_use,
"amount_type": tax.amount_type,
"tags_ids": tax.invoice_repartition_line_ids.tag_ids.ids,
}
}
)
return tax_data
@api.model
def _get_tax_report_domain(self, company_id, date_from, date_to, only_posted_moves):
domain = [
("company_id", "=", company_id),
("date", ">=", date_from),
("date", "<=", date_to),
("tax_line_id", "!=", False),
] + self.env["account.move.line"]._get_tax_exigible_domain()
if only_posted_moves:
domain += [("move_id.state", "=", "posted")]
else:
domain += [("move_id.state", "in", ["posted", "draft"])]
return domain
@api.model
def _get_net_report_domain(self, company_id, date_from, date_to, only_posted_moves):
domain = [
("company_id", "=", company_id),
("date", ">=", date_from),
("date", "<=", date_to),
] + self.env["account.move.line"]._get_tax_exigible_domain()
if only_posted_moves:
domain += [("move_id.state", "=", "posted")]
else:
domain += [("move_id.state", "in", ["posted", "draft"])]
return domain
def _get_vat_report_data(self, company_id, date_from, date_to, only_posted_moves):
tax_domain = self._get_tax_report_domain(
company_id, date_from, date_to, only_posted_moves
)
ml_fields = self._get_ml_fields_vat_report()
tax_move_lines = self.env["account.move.line"].search_read(
domain=tax_domain,
fields=ml_fields,
)
net_domain = self._get_net_report_domain(
company_id, date_from, date_to, only_posted_moves
)
taxed_move_lines = self.env["account.move.line"].search_read(
domain=net_domain,
fields=ml_fields,
)
taxed_move_lines = list(filter(lambda d: d["tax_ids"], taxed_move_lines))
vat_data = []
for tax_move_line in tax_move_lines:
vat_data.append(
{
"net": 0.0,
"tax": tax_move_line["balance"],
"tax_line_id": tax_move_line["tax_line_id"][0],
}
)
for taxed_move_line in taxed_move_lines:
for tax_id in taxed_move_line["tax_ids"]:
vat_data.append(
{
"net": taxed_move_line["balance"],
"tax": 0.0,
"tax_line_id": tax_id,
}
)
tax_ids = list(map(operator.itemgetter("tax_line_id"), vat_data))
tax_ids = list(set(tax_ids))
tax_data = self._get_tax_data(tax_ids)
return vat_data, tax_data
def _get_tax_group_data(self, tax_group_ids):
tax_groups = self.env["account.tax.group"].browse(tax_group_ids)
tax_group_data = {}
for tax_group in tax_groups:
tax_group_data.update(
{
tax_group.id: {
"id": tax_group.id,
"name": tax_group.name,
"code": str(tax_group.sequence),
}
}
)
return tax_group_data
def _get_vat_report_group_data(self, vat_report_data, tax_data, tax_detail):
vat_report = {}
for tax_move_line in vat_report_data:
tax_id = tax_move_line["tax_line_id"]
if tax_data[tax_id]["amount_type"] == "group":
pass
else:
tax_group_id = tax_data[tax_id]["tax_group_id"]
if tax_group_id not in vat_report.keys():
vat_report[tax_group_id] = {}
vat_report[tax_group_id]["net"] = 0.0
vat_report[tax_group_id]["tax"] = 0.0
vat_report[tax_group_id][tax_id] = dict(tax_data[tax_id])
vat_report[tax_group_id][tax_id].update({"net": 0.0, "tax": 0.0})
else:
if tax_id not in vat_report[tax_group_id].keys():
vat_report[tax_group_id][tax_id] = dict(tax_data[tax_id])
vat_report[tax_group_id][tax_id].update(
{"net": 0.0, "tax": 0.0}
)
vat_report[tax_group_id]["net"] += tax_move_line["net"]
vat_report[tax_group_id]["tax"] += tax_move_line["tax"]
vat_report[tax_group_id][tax_id]["net"] += tax_move_line["net"]
vat_report[tax_group_id][tax_id]["tax"] += tax_move_line["tax"]
tax_group_data = self._get_tax_group_data(vat_report.keys())
vat_report_list = []
for tax_group_id in vat_report.keys():
vat_report[tax_group_id]["name"] = tax_group_data[tax_group_id]["name"]
vat_report[tax_group_id]["code"] = tax_group_data[tax_group_id]["code"]
if tax_detail:
vat_report[tax_group_id]["taxes"] = []
for tax_id in vat_report[tax_group_id]:
if isinstance(tax_id, int):
vat_report[tax_group_id]["taxes"].append(
vat_report[tax_group_id][tax_id]
)
vat_report_list.append(vat_report[tax_group_id])
return vat_report_list
def _get_tags_data(self, tags_ids):
tags = self.env["account.account.tag"].browse(tags_ids)
tags_data = {}
for tag in tags:
tags_data.update({tag.id: {"code": "", "name": tag.name}})
return tags_data
def _get_vat_report_tag_data(self, vat_report_data, tax_data, tax_detail):
vat_report = {}
for tax_move_line in vat_report_data:
tax_id = tax_move_line["tax_line_id"]
tags_ids = tax_data[tax_id]["tags_ids"]
if tax_data[tax_id]["amount_type"] == "group":
continue
else:
if tags_ids:
for tag_id in tags_ids:
if tag_id not in vat_report.keys():
vat_report[tag_id] = {}
vat_report[tag_id]["net"] = 0.0
vat_report[tag_id]["tax"] = 0.0
vat_report[tag_id][tax_id] = dict(tax_data[tax_id])
vat_report[tag_id][tax_id].update({"net": 0.0, "tax": 0.0})
else:
if tax_id not in vat_report[tag_id].keys():
vat_report[tag_id][tax_id] = dict(tax_data[tax_id])
vat_report[tag_id][tax_id].update(
{"net": 0.0, "tax": 0.0}
)
vat_report[tag_id][tax_id]["net"] += tax_move_line["net"]
vat_report[tag_id][tax_id]["tax"] += tax_move_line["tax"]
vat_report[tag_id]["net"] += tax_move_line["net"]
vat_report[tag_id]["tax"] += tax_move_line["tax"]
tags_data = self._get_tags_data(vat_report.keys())
vat_report_list = []
for tag_id in vat_report.keys():
vat_report[tag_id]["name"] = tags_data[tag_id]["name"]
vat_report[tag_id]["code"] = tags_data[tag_id]["code"]
if tax_detail:
vat_report[tag_id]["taxes"] = []
for tax_id in vat_report[tag_id]:
if isinstance(tax_id, int):
vat_report[tag_id]["taxes"].append(vat_report[tag_id][tax_id])
vat_report_list.append(vat_report[tag_id])
return vat_report_list
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_from = data["date_from"]
date_to = data["date_to"]
based_on = data["based_on"]
tax_detail = data["tax_detail"]
only_posted_moves = data["only_posted_moves"]
vat_report_data, tax_data = self._get_vat_report_data(
company_id, date_from, date_to, only_posted_moves
)
if based_on == "taxgroups":
vat_report = self._get_vat_report_group_data(
vat_report_data, tax_data, tax_detail
)
else:
vat_report = self._get_vat_report_tag_data(
vat_report_data, tax_data, tax_detail
)
return {
"doc_ids": [wizard_id],
"doc_model": "open.items.report.wizard",
"docs": self.env["open.items.report.wizard"].browse(wizard_id),
"company_name": company.display_name,
"currency_name": company.currency_id.name,
"date_to": data["date_to"],
"date_from": data["date_from"],
"based_on": data["based_on"],
"tax_detail": data["tax_detail"],
"vat_report": vat_report,
}
def _get_ml_fields_vat_report(self):
return [
"id",
"tax_base_amount",
"balance",
"tax_line_id",
"tax_ids",
"analytic_tag_ids",
]
| 42.345833
| 10,163
|
10,126
|
py
|
PYTHON
|
15.0
|
# Author: Damien Crier
# Author: Julien Coux
# Copyright 2016 Camptocamp SA
# Copyright 2021 Tecnativa - João Marques
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import _, models
class JournalLedgerXslx(models.AbstractModel):
_name = "report.a_f_r.report_journal_ledger_xlsx"
_description = "Journal Ledger XLSX Report"
_inherit = "report.account_financial_report.abstract_report_xlsx"
def _get_report_name(self, report, data=False):
company_id = data.get("company_id", False)
report_name = _("Journal Ledger")
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_report_columns(self, report):
columns = [
{"header": _("Entry"), "field": "entry", "width": 18},
{"header": _("Date"), "field": "date", "width": 11},
{"header": _("Account"), "field": "account_code", "width": 9},
]
if report.with_auto_sequence:
columns.insert(
0, {"header": _("Sequence"), "field": "auto_sequence", "width": 10}
)
if report.with_account_name:
columns.append(
{"header": _("Account Name"), "field": "account_name", "width": 15}
)
columns += [
{"header": _("Partner"), "field": "partner", "width": 25},
{"header": _("Ref - Label"), "field": "label", "width": 40},
{"header": _("Taxes"), "field": "taxes_description", "width": 11},
{"header": _("Debit"), "field": "debit", "type": "amount", "width": 14},
{"header": _("Credit"), "field": "credit", "type": "amount", "width": 14},
]
if report.foreign_currency:
columns += [
{
"header": _("Currency"),
"field": "currency_name",
"width": 14,
"type": "currency_name",
},
{
"header": _("Amount Currency"),
"field": "amount_currency",
"type": "amount",
"width": 18,
},
]
columns_as_dict = {}
for i, column in enumerate(columns):
columns_as_dict[i] = column
return columns_as_dict
def _get_journal_tax_columns(self, report):
return {
0: {"header": _("Name"), "field": "tax_name", "width": 35},
1: {"header": _("Description"), "field": "tax_code", "width": 18},
2: {
"header": _("Base Debit"),
"field": "base_debit",
"type": "amount",
"width": 14,
},
3: {
"header": _("Base Credit"),
"field": "base_credit",
"type": "amount",
"width": 14,
},
4: {
"header": _("Base Balance"),
"field": "base_balance",
"type": "amount",
"width": 14,
},
5: {
"header": _("Tax Debit"),
"field": "tax_debit",
"type": "amount",
"width": 14,
},
6: {
"header": _("Tax Credit"),
"field": "tax_credit",
"type": "amount",
"width": 14,
},
7: {
"header": _("Tax Balance"),
"field": "tax_balance",
"type": "amount",
"width": 14,
},
}
def _get_col_count_filter_name(self):
return 2
def _get_col_count_filter_value(self):
return 3
def _get_report_filters(self, report):
target_label_by_value = {
value: label
for value, label in self.env[
"journal.ledger.report.wizard"
]._get_move_targets()
}
sort_option_label_by_value = {
value: label
for value, label in self.env[
"journal.ledger.report.wizard"
]._get_sort_options()
}
return [
[_("Company"), report.company_id.name],
[
_("Date range filter"),
_("From: %(date_from)s To: %(date_to)s")
% ({"date_from": report.date_from, "date_to": report.date_to}),
],
[
_("Target moves filter"),
_("%s") % target_label_by_value[report.move_target],
],
[
_("Entries sorted by"),
_("%s") % sort_option_label_by_value[report.sort_option],
],
[
_("Journals"),
", ".join(
[
"{} - {}".format(report_journal.code, report_journal.name)
for report_journal in report.journal_ids
]
),
],
]
def _generate_report_content(self, workbook, report, data, report_data):
res_data = self.env[
"report.account_financial_report.journal_ledger"
]._get_report_values(report, data)
group_option = report.group_option
if group_option == "journal":
for ledger in res_data["Journal_Ledgers"]:
self._generate_journal_content(
workbook, report, res_data, ledger, report_data
)
elif group_option == "none":
self._generate_no_group_content(workbook, report, res_data, report_data)
def _generate_no_group_content(self, workbook, report, res_data, report_data):
self._generate_moves_content(
workbook, "Report", report, res_data, res_data["Moves"], report_data
)
self._generate_no_group_taxes_summary(workbook, report, res_data, report_data)
def _generate_journal_content(
self, workbook, report, res_data, ledger, report_data
):
journal = self.env["account.journal"].browse(ledger["id"])
currency_name = (
journal.currency_id
and journal.currency_id.name
or journal.company_id.currency_id.name
)
sheet_name = "{} ({}) - {}".format(journal.code, currency_name, journal.name)
self._generate_moves_content(
workbook, sheet_name, report, res_data, ledger["report_moves"], report_data
)
self._generate_journal_taxes_summary(workbook, ledger, report_data)
def _generate_no_group_taxes_summary(self, workbook, report, res_data, report_data):
self._generate_taxes_summary(
workbook, "Tax Report", res_data["tax_line_data"], report_data
)
def _generate_journal_taxes_summary(self, workbook, ledger, report_data):
journal = self.env["account.journal"].browse(ledger["id"])
currency_name = (
journal.currency_id
and journal.currency_id.name
or journal.company_id.currency_id.name
)
sheet_name = "Tax - {} ({}) - {}".format(
journal.code, currency_name, journal.name
)
self._generate_taxes_summary(
workbook, sheet_name, ledger["tax_lines"], report_data
)
def _generate_moves_content(
self, workbook, sheet_name, report, res_data, moves, report_data
):
report_data["workbook"] = workbook
report_data["sheet"] = workbook.add_worksheet(sheet_name)
self._set_column_width(report_data)
report_data["row_pos"] = 1
self.write_array_title(sheet_name, report_data)
report_data["row_pos"] += 2
self.write_array_header(report_data)
account_ids_data = res_data["account_ids_data"]
partner_ids_data = res_data["partner_ids_data"]
currency_ids_data = res_data["currency_ids_data"]
move_ids_data = res_data["move_ids_data"]
for move in moves:
for line in move["report_move_lines"]:
currency_data = currency_ids_data.get(line["currency_id"], False)
currency_name = currency_data and currency_data["name"] or ""
account_data = account_ids_data.get(line["account_id"], False)
account_name = account_data and account_data["name"] or ""
account_code = account_data and account_data["code"] or ""
move_data = move_ids_data.get(line["move_id"], False)
move_entry = move_data and move_data["entry"] or ""
line["partner"] = self._get_partner_name(
line["partner_id"], partner_ids_data
)
line["auto_sequence"] = line["auto_sequence"]
line["account_code"] = account_code
line["account_name"] = account_name
line["currency_name"] = currency_name
line["entry"] = move_entry
line["taxes_description"] = report._get_ml_tax_description(
line,
res_data["tax_line_data"].get(line["tax_line_id"]),
res_data["move_line_ids_taxes_data"].get(
line["move_line_id"], False
),
)
self.write_line_from_dict(line, report_data)
report_data["row_pos"] += 1
def _generate_taxes_summary(
self, workbook, sheet_name, tax_lines_dict, report_data
):
report_data["workbook"] = workbook
report_data["sheet"] = workbook.add_worksheet(sheet_name)
report_data["row_pos"] = 1
self.write_array_title(sheet_name, report_data)
report_data["row_pos"] += 2
def _get_partner_name(self, partner_id, partner_data):
if partner_id in partner_data.keys():
return partner_data[partner_id]["name"]
else:
return ""
| 37.5
| 10,125
|
15,599
|
py
|
PYTHON
|
15.0
|
# Author: Damien Crier
# Author: Julien Coux
# Copyright 2016 Camptocamp SA
# Copyright 2021 Tecnativa - João Marques
# Copyright 2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import _, models
class GeneralLedgerXslx(models.AbstractModel):
_name = "report.a_f_r.report_general_ledger_xlsx"
_description = "General Ledger XLSL Report"
_inherit = "report.account_financial_report.abstract_report_xlsx"
def _get_report_name(self, report, data=False):
company_id = data.get("company_id", False)
report_name = _("General Ledger")
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_report_columns(self, report):
res = [
{"header": _("Date"), "field": "date", "width": 11},
{"header": _("Entry"), "field": "entry", "width": 18},
{"header": _("Journal"), "field": "journal", "width": 8},
{"header": _("Account"), "field": "account", "width": 9},
{"header": _("Taxes"), "field": "taxes_description", "width": 15},
{"header": _("Partner"), "field": "partner_name", "width": 25},
{"header": _("Ref - Label"), "field": "ref_label", "width": 40},
]
if report.show_cost_center:
res += [
{
"header": _("Analytic Account"),
"field": "analytic_account",
"width": 20,
},
]
if report.show_analytic_tags:
res += [
{"header": _("Tags"), "field": "tags", "width": 10},
]
res += [
{"header": _("Rec."), "field": "rec_name", "width": 15},
{
"header": _("Debit"),
"field": "debit",
"field_initial_balance": "initial_debit",
"field_final_balance": "final_debit",
"type": "amount",
"width": 14,
},
{
"header": _("Credit"),
"field": "credit",
"field_initial_balance": "initial_credit",
"field_final_balance": "final_credit",
"type": "amount",
"width": 14,
},
{
"header": _("Cumul. Bal."),
"field": "balance",
"field_initial_balance": "initial_balance",
"field_final_balance": "final_balance",
"type": "amount",
"width": 14,
},
]
if report.foreign_currency:
res += [
{
"header": _("Amount cur."),
"field": "bal_curr",
"field_initial_balance": "initial_bal_curr",
"field_final_balance": "final_bal_curr",
"type": "amount_currency",
"width": 10,
},
{
"header": _("Cumul cur."),
"field": "total_bal_curr",
"field_initial_balance": "initial_bal_curr",
"field_final_balance": "final_bal_curr",
"type": "amount_currency",
"width": 10,
},
]
res_as_dict = {}
for i, column in enumerate(res):
res_as_dict[i] = column
return res_as_dict
def _get_report_filters(self, report):
return [
[
_("Date range filter"),
_("From: %(date_from)s To: %(date_to)s")
% ({"date_from": report.date_from, "date_to": report.date_to}),
],
[
_("Target moves filter"),
_("All posted entries")
if report.target_move == "posted"
else _("All entries"),
],
[
_("Account balance at 0 filter"),
_("Hide") if report.hide_account_at_0 else _("Show"),
],
[_("Centralize filter"), _("Yes") if report.centralize else _("No")],
[
_("Show analytic tags"),
_("Yes") if report.show_analytic_tags else _("No"),
],
[
_("Show foreign currency"),
_("Yes") if report.foreign_currency else _("No"),
],
]
def _get_col_count_filter_name(self):
return 2
def _get_col_count_filter_value(self):
return 2
def _get_col_pos_initial_balance_label(self):
return 5
def _get_col_count_final_balance_name(self):
return 5
def _get_col_pos_final_balance_label(self):
return 5
# flake8: noqa: C901
def _generate_report_content(self, workbook, report, data, report_data):
res_data = self.env[
"report.account_financial_report.general_ledger"
]._get_report_values(report, data)
general_ledger = res_data["general_ledger"]
accounts_data = res_data["accounts_data"]
journals_data = res_data["journals_data"]
taxes_data = res_data["taxes_data"]
tags_data = res_data["tags_data"]
filter_partner_ids = res_data["filter_partner_ids"]
foreign_currency = res_data["foreign_currency"]
# For each account
for account in general_ledger:
# Write account title
total_bal_curr = 0
self.write_array_title(
account["code"] + " - " + accounts_data[account["id"]]["name"],
report_data,
)
if "list_grouped" not in account:
# Display array header for move lines
self.write_array_header(report_data)
# Display initial balance line for account
account.update(
{
"initial_debit": account["init_bal"]["debit"],
"initial_credit": account["init_bal"]["credit"],
"initial_balance": account["init_bal"]["balance"],
}
)
if foreign_currency:
account.update(
{"initial_bal_curr": account["init_bal"]["bal_curr"]}
)
self.write_initial_balance_from_dict(account, report_data)
# Display account move lines
for line in account["move_lines"]:
line.update(
{
"account": account["code"],
"journal": journals_data[line["journal_id"]]["code"],
}
)
if line["currency_id"]:
line.update(
{
"currency_name": line["currency_id"][1],
"currency_id": line["currency_id"][0],
}
)
if line["ref_label"] != "Centralized entries":
taxes_description = ""
tags = ""
for tax_id in line["tax_ids"]:
taxes_description += taxes_data[tax_id]["tax_name"] + " "
if line["tax_line_id"]:
taxes_description += line["tax_line_id"][1]
for tag_id in line["tag_ids"]:
tags += tags_data[tag_id]["name"] + " "
line.update(
{
"taxes_description": taxes_description,
"tags": tags,
}
)
if foreign_currency:
total_bal_curr += line["bal_curr"]
line.update({"total_bal_curr": total_bal_curr})
self.write_line_from_dict(line, report_data)
# Display ending balance line for account
account.update(
{
"final_debit": account["fin_bal"]["debit"],
"final_credit": account["fin_bal"]["credit"],
"final_balance": account["fin_bal"]["balance"],
}
)
if foreign_currency:
account.update(
{
"final_bal_curr": account["fin_bal"]["bal_curr"],
}
)
self.write_ending_balance_from_dict(account, report_data)
else:
# For each partner
total_bal_curr = 0
for group_item in account["list_grouped"]:
# Write partner title
self.write_array_title(group_item["name"], report_data)
# Display array header for move lines
self.write_array_header(report_data)
account.update(
{
"currency_id": accounts_data[account["id"]]["currency_id"],
"currency_name": accounts_data[account["id"]][
"currency_name"
],
}
)
# Display initial balance line for partner
group_item.update(
{
"initial_debit": group_item["init_bal"]["debit"],
"initial_credit": group_item["init_bal"]["credit"],
"initial_balance": group_item["init_bal"]["balance"],
"type": "partner",
"grouped_by": account["grouped_by"]
if "grouped_by" in account
else "",
"currency_id": accounts_data[account["id"]]["currency_id"],
"currency_name": accounts_data[account["id"]][
"currency_name"
],
}
)
if foreign_currency:
group_item.update(
{
"initial_bal_curr": group_item["init_bal"]["bal_curr"],
}
)
self.write_initial_balance_from_dict(group_item, report_data)
# Display account move lines
for line in group_item["move_lines"]:
line.update(
{
"account": account["code"],
"journal": journals_data[line["journal_id"]]["code"],
}
)
if line["currency_id"]:
line.update(
{
"currency_name": line["currency_id"][1],
"currency_id": line["currency_id"][0],
}
)
if line["ref_label"] != "Centralized entries":
taxes_description = ""
tags = ""
for tax_id in line["tax_ids"]:
taxes_description += (
taxes_data[tax_id]["tax_name"] + " "
)
for tag_id in line["tag_ids"]:
tags += tags_data[tag_id]["name"] + " "
line.update(
{
"taxes_description": taxes_description,
"tags": tags,
}
)
if foreign_currency:
total_bal_curr += line["bal_curr"]
line.update({"total_bal_curr": total_bal_curr})
self.write_line_from_dict(line, report_data)
# Display ending balance line for partner
group_item.update(
{
"final_debit": group_item["fin_bal"]["debit"],
"final_credit": group_item["fin_bal"]["credit"],
"final_balance": group_item["fin_bal"]["balance"],
}
)
if foreign_currency and group_item["currency_id"]:
group_item.update(
{
"final_bal_curr": group_item["fin_bal"]["bal_curr"],
}
)
self.write_ending_balance_from_dict(group_item, report_data)
# Line break
report_data["row_pos"] += 1
if not filter_partner_ids:
account.update(
{
"final_debit": account["fin_bal"]["debit"],
"final_credit": account["fin_bal"]["credit"],
"final_balance": account["fin_bal"]["balance"],
}
)
if foreign_currency and account["currency_id"]:
account.update(
{
"final_bal_curr": account["fin_bal"]["bal_curr"],
}
)
self.write_ending_balance_from_dict(account, report_data)
# 2 lines break
report_data["row_pos"] += 2
def write_initial_balance_from_dict(self, my_object, report_data):
"""Specific function to write initial balance for General Ledger"""
label = False
if "account" not in my_object["type"] and "grouped_by" in my_object:
if my_object["grouped_by"] == "partners":
label = _("Partner Initial balance")
elif my_object["grouped_by"] == "taxes":
label = _("Tax Initial balance")
label = label if label else _("Initial balance")
return super().write_initial_balance_from_dict(my_object, label, report_data)
def write_ending_balance_from_dict(self, my_object, report_data):
"""Specific function to write ending balance for General Ledger"""
label = name = False
if "account" in my_object["type"]:
name = my_object["code"] + " - " + my_object["name"]
elif "grouped_by" in my_object:
name = my_object["name"]
if my_object["grouped_by"] == "partners":
label = _("Partner ending balance")
elif my_object["grouped_by"] == "taxes":
label = _("Tax ending balance")
label = label if label else _("Ending balance")
return super().write_ending_balance_from_dict(
my_object, name, label, report_data
)
| 42.037736
| 15,596
|
30,676
|
py
|
PYTHON
|
15.0
|
# © 2016 Julien Coux (Camptocamp)
# © 2018 Forest and Biomass Romania SA
# Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, models
from odoo.tools.float_utils import float_is_zero
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),
("user_type_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.internal_type", "in", ["receivable", "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),
("user_type_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.internal_type", "in", ["receivable", "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", "=", False),
("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.internal_type", "in", ["receivable", "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),
("user_type_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.internal_type", "in", ["receivable", "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"],
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
@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
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
)
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]
if tb["partner_id"]:
prt_id = tb["partner_id"][0]
if tb["partner_id"] not in partners_ids:
partners_data.update(
{prt_id: {"id": prt_id, "name": tb["partner_id"][1]}}
)
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
partners_ids.add(tb["partner_id"])
for tb in tb_initial_prt:
acc_id = tb["account_id"][0]
if tb["partner_id"]:
prt_id = tb["partner_id"][0]
if tb["partner_id"] not in partners_ids:
partners_data.update(
{prt_id: {"id": prt_id, "name": tb["partner_id"][1]}}
)
total_amount = self._compute_acc_prt_amount(
total_amount, tb, acc_id, prt_id, foreign_currency
)
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]
@api.model
def _get_data(
self,
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,
):
accounts_domain = [("company_id", "=", company_id)]
if account_ids:
accounts_domain += [("id", "in", account_ids)]
# If explicit list of accounts is provided,
# don't include unaffected earnings account
unaffected_earnings_account = False
accounts = self.env["account.account"].search(accounts_domain)
tb_initial_acc = []
for account in accounts:
tb_initial_acc.append(
{"account_id": account.id, "balance": 0.0, "amount_currency": 0.0}
)
initial_domain_bs = self._get_initial_balances_bs_ml_domain(
account_ids,
journal_ids,
partner_ids,
company_id,
date_from,
only_posted_moves,
show_partner_details,
)
tb_initial_acc_bs = self.env["account.move.line"].read_group(
domain=initial_domain_bs,
fields=["account_id", "balance", "amount_currency"],
groupby=["account_id"],
)
initial_domain_pl = self._get_initial_balances_pl_ml_domain(
account_ids,
journal_ids,
partner_ids,
company_id,
date_from,
only_posted_moves,
show_partner_details,
fy_start_date,
)
tb_initial_acc_pl = self.env["account.move.line"].read_group(
domain=initial_domain_pl,
fields=["account_id", "balance", "amount_currency"],
groupby=["account_id"],
)
tb_initial_acc_rg = tb_initial_acc_bs + tb_initial_acc_pl
for account_rg in tb_initial_acc_rg:
element = list(
filter(
lambda acc_dict: acc_dict["account_id"]
== account_rg["account_id"][0],
tb_initial_acc,
)
)
if element:
element[0]["balance"] += account_rg["balance"]
element[0]["amount_currency"] += account_rg["amount_currency"]
if hide_account_at_0:
tb_initial_acc = [p for p in tb_initial_acc if p["balance"] != 0]
period_domain = self._get_period_ml_domain(
account_ids,
journal_ids,
partner_ids,
company_id,
date_to,
date_from,
only_posted_moves,
show_partner_details,
)
tb_period_acc = self.env["account.move.line"].read_group(
domain=period_domain,
fields=["account_id", "debit", "credit", "balance", "amount_currency"],
groupby=["account_id"],
)
if show_partner_details:
tb_initial_prt_bs = self.env["account.move.line"].read_group(
domain=initial_domain_bs,
fields=["account_id", "partner_id", "balance", "amount_currency"],
groupby=["account_id", "partner_id"],
lazy=False,
)
tb_initial_prt_pl = self.env["account.move.line"].read_group(
domain=initial_domain_pl,
fields=["account_id", "partner_id", "balance", "amount_currency"],
groupby=["account_id", "partner_id"],
)
tb_initial_prt = tb_initial_prt_bs + tb_initial_prt_pl
if hide_account_at_0:
tb_initial_prt = [p for p in tb_initial_prt if p["balance"] != 0]
tb_period_prt = self.env["account.move.line"].read_group(
domain=period_domain,
fields=[
"account_id",
"partner_id",
"debit",
"credit",
"balance",
"amount_currency",
],
groupby=["account_id", "partner_id"],
lazy=False,
)
total_amount = {}
partners_data = []
total_amount = self._compute_account_amount(
total_amount, tb_initial_acc, tb_period_acc, foreign_currency
)
if show_partner_details:
total_amount, partners_data = self._compute_partner_amount(
total_amount, tb_initial_prt, tb_period_prt, foreign_currency
)
# Remove accounts a 0 from collections
if hide_account_at_0:
company = self.env["res.company"].browse(company_id)
self._remove_accounts_at_cero(total_amount, show_partner_details, company)
accounts_ids = list(total_amount.keys())
unaffected_id = unaffected_earnings_account
if unaffected_id:
if unaffected_id not in accounts_ids:
accounts_ids.append(unaffected_id)
total_amount[unaffected_id] = {}
total_amount[unaffected_id]["initial_balance"] = 0.0
total_amount[unaffected_id]["balance"] = 0.0
total_amount[unaffected_id]["credit"] = 0.0
total_amount[unaffected_id]["debit"] = 0.0
total_amount[unaffected_id]["ending_balance"] = 0.0
if foreign_currency:
total_amount[unaffected_id]["initial_currency_balance"] = 0.0
total_amount[unaffected_id]["ending_currency_balance"] = 0.0
accounts_data = self._get_accounts_data(accounts_ids)
(
pl_initial_balance,
pl_initial_currency_balance,
) = self._get_pl_initial_balance(
account_ids,
journal_ids,
partner_ids,
company_id,
fy_start_date,
only_posted_moves,
show_partner_details,
foreign_currency,
)
if unaffected_id:
total_amount[unaffected_id]["ending_balance"] += pl_initial_balance
total_amount[unaffected_id]["initial_balance"] += pl_initial_balance
if foreign_currency:
total_amount[unaffected_id][
"ending_currency_balance"
] += pl_initial_currency_balance
total_amount[unaffected_id][
"initial_currency_balance"
] += pl_initial_currency_balance
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"]
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,
}
| 41.790191
| 30,674
|
29,866
|
py
|
PYTHON
|
15.0
|
# Author: Julien Coux
# Copyright 2016 Camptocamp SA
# Copyright 2021 Tecnativa - João Marques
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import models
class AbstractReportXslx(models.AbstractModel):
_name = "report.account_financial_report.abstract_report_xlsx"
_description = "Abstract XLSX Account Financial Report"
_inherit = "report.report_xlsx.abstract"
def get_workbook_options(self):
vals = super().get_workbook_options()
vals.update({"constant_memory": True})
return vals
def generate_xlsx_report(self, workbook, data, objects):
# Initialize report variables
report_data = {
"workbook": None,
"sheet": None, # main sheet which will contains report
"columns": None, # columns of the report
"row_pos": None, # row_pos must be incremented at each writing lines
"formats": None,
}
self._define_formats(workbook, report_data)
# Get report data
report_name = self._get_report_name(objects, data=data)
report_footer = self._get_report_footer()
filters = self._get_report_filters(objects)
report_data["columns"] = self._get_report_columns(objects)
report_data["workbook"] = workbook
report_data["sheet"] = workbook.add_worksheet(report_name[:31])
self._set_column_width(report_data)
# Fill report
report_data["row_pos"] = 0
self._write_report_title(report_name, report_data)
self._write_filters(filters, report_data)
self._generate_report_content(workbook, objects, data, report_data)
self._write_report_footer(report_footer, report_data)
def _define_formats(self, workbook, report_data):
"""Add cell formats to current workbook.
Those formats can be used on all cell.
Available formats are :
* format_bold
* format_right
* format_right_bold_italic
* format_header_left
* format_header_center
* format_header_right
* format_header_amount
* format_amount
* format_percent_bold_italic
"""
currency_id = self.env["res.company"]._default_currency_id()
report_data["formats"] = {
"format_bold": workbook.add_format({"bold": True}),
"format_right": workbook.add_format({"align": "right"}),
"format_left": workbook.add_format({"align": "left"}),
"format_right_bold_italic": workbook.add_format(
{"align": "right", "bold": True, "italic": True}
),
"format_header_left": workbook.add_format(
{"bold": True, "border": True, "bg_color": "#FFFFCC"}
),
"format_header_center": workbook.add_format(
{"bold": True, "align": "center", "border": True, "bg_color": "#FFFFCC"}
),
"format_header_right": workbook.add_format(
{"bold": True, "align": "right", "border": True, "bg_color": "#FFFFCC"}
),
"format_header_amount": workbook.add_format(
{"bold": True, "border": True, "bg_color": "#FFFFCC"}
),
"format_amount": workbook.add_format(),
"format_amount_bold": workbook.add_format({"bold": True}).set_num_format(
"#,##0." + "0" * currency_id.decimal_places
),
"format_percent_bold_italic": workbook.add_format(
{"bold": True, "italic": True}
),
}
report_data["formats"]["format_amount"].set_num_format(
"#,##0." + "0" * currency_id.decimal_places
)
report_data["formats"]["format_header_amount"].set_num_format(
"#,##0." + "0" * currency_id.decimal_places
)
report_data["formats"]["format_percent_bold_italic"].set_num_format("#,##0.00%")
def _set_column_width(self, report_data):
"""Set width for all defined columns.
Columns are defined with `_get_report_columns` method.
"""
for position, column in report_data["columns"].items():
report_data["sheet"].set_column(position, position, column["width"])
def _write_report_title(self, title, report_data):
"""Write report title on current line using all defined columns width.
Columns are defined with `_get_report_columns` method.
"""
report_data["sheet"].merge_range(
report_data["row_pos"],
0,
report_data["row_pos"],
len(report_data["columns"]) - 1,
title,
report_data["formats"]["format_bold"],
)
report_data["row_pos"] += 3
def _write_report_footer(self, footer, report_data):
"""Write report footer .
Columns are defined with `_get_report_columns` method.
"""
if footer:
report_data["row_pos"] += 1
report_data["sheet"].merge_range(
report_data["row_pos"],
0,
report_data["row_pos"],
len(report_data["columns"]) - 1,
footer,
report_data["formats"]["format_left"],
)
report_data["row_pos"] += 1
def _write_filters(self, filters, report_data):
"""Write one line per filters on starting on current line.
Columns number for filter name is defined
with `_get_col_count_filter_name` method.
Columns number for filter value is define
with `_get_col_count_filter_value` method.
"""
col_name = 1
col_count_filter_name = self._get_col_count_filter_name()
col_count_filter_value = self._get_col_count_filter_value()
col_value = col_name + col_count_filter_name + 1
for title, value in filters:
report_data["sheet"].merge_range(
report_data["row_pos"],
col_name,
report_data["row_pos"],
col_name + col_count_filter_name - 1,
title,
report_data["formats"]["format_header_left"],
)
report_data["sheet"].merge_range(
report_data["row_pos"],
col_value,
report_data["row_pos"],
col_value + col_count_filter_value - 1,
value,
)
report_data["row_pos"] += 1
report_data["row_pos"] += 2
def write_array_title(self, title, report_data):
"""Write array title on current line using all defined columns width.
Columns are defined with `_get_report_columns` method.
"""
report_data["sheet"].merge_range(
report_data["row_pos"],
0,
report_data["row_pos"],
len(report_data["columns"]) - 1,
title,
report_data["formats"]["format_bold"],
)
report_data["row_pos"] += 1
def write_array_header(self, report_data):
"""Write array header on current line using all defined columns name.
Columns are defined with `_get_report_columns` method.
"""
for col_pos, column in report_data["columns"].items():
report_data["sheet"].write(
report_data["row_pos"],
col_pos,
column["header"],
report_data["formats"]["format_header_center"],
)
report_data["row_pos"] += 1
def write_line(self, line_object, report_data):
"""Write a line on current line using all defined columns field name.
Columns are defined with `_get_report_columns` method.
"""
for col_pos, column in report_data["columns"].items():
value = getattr(line_object, column["field"])
cell_type = column.get("type", "string")
if cell_type == "many2one":
report_data["sheet"].write_string(
report_data["row_pos"],
col_pos,
value.name or "",
report_data["formats"]["format_right"],
)
elif cell_type == "string":
if (
hasattr(line_object, "account_group_id")
and line_object.account_group_id
):
report_data["sheet"].write_string(
report_data["row_pos"],
col_pos,
value or "",
report_data["formats"]["format_bold"],
)
else:
report_data["sheet"].write_string(
report_data["row_pos"], col_pos, value or ""
)
elif cell_type == "amount":
if (
hasattr(line_object, "account_group_id")
and line_object.account_group_id
):
cell_format = report_data["formats"]["format_amount_bold"]
else:
cell_format = report_data["formats"]["format_amount"]
report_data["sheet"].write_number(
report_data["row_pos"], col_pos, float(value), cell_format
)
elif cell_type == "amount_currency":
if line_object.currency_id:
format_amt = self._get_currency_amt_format(line_object, report_data)
report_data["sheet"].write_number(
report_data["row_pos"], col_pos, float(value), format_amt
)
report_data["row_pos"] += 1
def write_line_from_dict(self, line_dict, report_data):
"""Write a line on current line"""
for col_pos, column in report_data["columns"].items():
value = line_dict.get(column["field"], False)
cell_type = column.get("type", "string")
if cell_type == "string":
if line_dict.get("type", "") == "group_type":
report_data["sheet"].write_string(
report_data["row_pos"],
col_pos,
value or "",
report_data["formats"]["format_bold"],
)
else:
if (
not isinstance(value, str)
and not isinstance(value, bool)
and not isinstance(value, int)
):
value = value and value.strftime("%d/%m/%Y")
report_data["sheet"].write_string(
report_data["row_pos"], col_pos, value or ""
)
elif cell_type == "amount":
if (
line_dict.get("account_group_id", False)
and line_dict["account_group_id"]
):
cell_format = report_data["formats"]["format_amount_bold"]
else:
cell_format = report_data["formats"]["format_amount"]
report_data["sheet"].write_number(
report_data["row_pos"], col_pos, float(value), cell_format
)
elif cell_type == "amount_currency":
if line_dict.get("currency_name", False):
format_amt = self._get_currency_amt_format_dict(
line_dict, report_data
)
report_data["sheet"].write_number(
report_data["row_pos"], col_pos, float(value), format_amt
)
elif cell_type == "currency_name":
report_data["sheet"].write_string(
report_data["row_pos"],
col_pos,
value or "",
report_data["formats"]["format_right"],
)
else:
self.write_non_standard_column(cell_type, col_pos, value)
report_data["row_pos"] += 1
def write_initial_balance(self, my_object, label, report_data):
"""Write a specific initial balance line on current line
using defined columns field_initial_balance name.
Columns are defined with `_get_report_columns` method.
"""
col_pos_label = self._get_col_pos_initial_balance_label()
report_data["sheet"].write(
report_data["row_pos"],
col_pos_label,
label,
report_data["formats"]["format_right"],
)
for col_pos, column in report_data["columns"].items():
if column.get("field_initial_balance"):
value = getattr(my_object, column["field_initial_balance"])
cell_type = column.get("type", "string")
if cell_type == "string":
report_data["sheet"].write_string(
report_data["row_pos"], col_pos, value or ""
)
elif cell_type == "amount":
report_data["sheet"].write_number(
report_data["row_pos"],
col_pos,
float(value),
report_data["formats"]["format_amount"],
)
elif cell_type == "amount_currency":
if my_object.currency_id:
format_amt = self._get_currency_amt_format(
my_object, report_data
)
report_data["sheet"].write_number(
report_data["row_pos"], col_pos, float(value), format_amt
)
elif column.get("field_currency_balance"):
value = getattr(my_object, column["field_currency_balance"])
cell_type = column.get("type", "string")
if cell_type == "many2one":
if my_object.currency_id:
report_data["sheet"].write_string(
report_data["row_pos"],
col_pos,
value.name or "",
report_data["formats"]["format_right"],
)
report_data["row_pos"] += 1
def write_initial_balance_from_dict(self, my_object, label, report_data):
"""Write a specific initial balance line on current line
using defined columns field_initial_balance name.
Columns are defined with `_get_report_columns` method.
"""
col_pos_label = self._get_col_pos_initial_balance_label()
report_data["sheet"].write(
report_data["row_pos"],
col_pos_label,
label,
report_data["formats"]["format_right"],
)
for col_pos, column in report_data["columns"].items():
if column.get("field_initial_balance"):
value = my_object.get(column["field_initial_balance"], False)
cell_type = column.get("type", "string")
if cell_type == "string":
report_data["sheet"].write_string(
report_data["row_pos"], col_pos, value or ""
)
elif cell_type == "amount":
report_data["sheet"].write_number(
report_data["row_pos"],
col_pos,
float(value),
report_data["formats"]["format_amount"],
)
elif cell_type == "amount_currency":
if my_object["currency_id"]:
format_amt = self._get_currency_amt_format(
my_object, report_data
)
report_data["sheet"].write_number(
report_data["row_pos"], col_pos, float(value), format_amt
)
elif column.get("field_currency_balance"):
value = my_object.get(column["field_currency_balance"], False)
cell_type = column.get("type", "string")
if cell_type == "many2one":
if my_object["currency_id"]:
report_data["sheet"].write_string(
report_data["row_pos"],
col_pos,
value.name or "",
report_data["formats"]["format_right"],
)
report_data["row_pos"] += 1
def write_ending_balance(self, my_object, name, label, report_data):
"""Write a specific ending balance line on current line
using defined columns field_final_balance name.
Columns are defined with `_get_report_columns` method.
"""
for i in range(0, len(report_data["columns"])):
report_data["sheet"].write(
report_data["row_pos"],
i,
"",
report_data["formats"]["format_header_right"],
)
row_count_name = self._get_col_count_final_balance_name()
col_pos_label = self._get_col_pos_final_balance_label()
report_data["sheet"].merge_range(
report_data["row_pos"],
0,
report_data["row_pos"],
row_count_name - 1,
name,
report_data["formats"]["format_header_left"],
)
report_data["sheet"].write(
report_data["row_pos"],
col_pos_label,
label,
report_data["formats"]["format_header_right"],
)
for col_pos, column in report_data["columns"].items():
if column.get("field_final_balance"):
value = getattr(my_object, column["field_final_balance"])
cell_type = column.get("type", "string")
if cell_type == "string":
report_data["sheet"].write_string(
report_data["row_pos"],
col_pos,
value or "",
report_data["formats"]["format_header_right"],
)
elif cell_type == "amount":
report_data["sheet"].write_number(
report_data["row_pos"],
col_pos,
float(value),
report_data["formats"]["format_header_amount"],
)
elif cell_type == "amount_currency":
if my_object.currency_id:
format_amt = self._get_currency_amt_header_format(
my_object, report_data
)
report_data["sheet"].write_number(
report_data["row_pos"], col_pos, float(value), format_amt
)
elif column.get("field_currency_balance"):
value = getattr(my_object, column["field_currency_balance"])
cell_type = column.get("type", "string")
if cell_type == "many2one":
if my_object.currency_id:
report_data["sheet"].write_string(
report_data["row_pos"],
col_pos,
value.name or "",
report_data["formats"]["format_header_right"],
)
report_data["row_pos"] += 1
def write_ending_balance_from_dict(self, my_object, name, label, report_data):
"""Write a specific ending balance line on current line
using defined columns field_final_balance name.
Columns are defined with `_get_report_columns` method.
"""
for i in range(0, len(report_data["columns"])):
report_data["sheet"].write(
report_data["row_pos"],
i,
"",
report_data["formats"]["format_header_right"],
)
row_count_name = self._get_col_count_final_balance_name()
col_pos_label = self._get_col_pos_final_balance_label()
report_data["sheet"].merge_range(
report_data["row_pos"],
0,
report_data["row_pos"],
row_count_name - 1,
name,
report_data["formats"]["format_header_left"],
)
report_data["sheet"].write(
report_data["row_pos"],
col_pos_label,
label,
report_data["formats"]["format_header_right"],
)
for col_pos, column in report_data["columns"].items():
if column.get("field_final_balance"):
value = my_object.get(column["field_final_balance"], False)
cell_type = column.get("type", "string")
if cell_type == "string":
report_data["sheet"].write_string(
report_data["row_pos"],
col_pos,
value or "",
report_data["formats"]["format_header_right"],
)
elif cell_type == "amount":
report_data["sheet"].write_number(
report_data["row_pos"],
col_pos,
float(value),
report_data["formats"]["format_header_amount"],
)
elif cell_type == "amount_currency":
if my_object["currency_id"] and value:
format_amt = self._get_currency_amt_format_dict(
my_object, report_data
)
report_data["sheet"].write_number(
report_data["row_pos"], col_pos, float(value), format_amt
)
elif column.get("field_currency_balance"):
value = my_object.get(column["field_currency_balance"], False)
cell_type = column.get("type", "string")
if cell_type == "many2one":
if my_object["currency_id"]:
report_data["sheet"].write_string(
report_data["row_pos"],
col_pos,
value or "",
report_data["formats"]["format_header_right"],
)
elif cell_type == "currency_name":
report_data["sheet"].write_string(
report_data["row_pos"],
col_pos,
value or "",
report_data["formats"]["format_header_right"],
)
report_data["row_pos"] += 1
def _get_currency_amt_format(self, line_object, report_data):
"""Return amount format specific for each currency."""
if "account_group_id" in line_object and line_object["account_group_id"]:
format_amt = report_data["formats"]["format_amount_bold"]
field_prefix = "format_amount_bold"
else:
format_amt = report_data["formats"]["format_amount"]
field_prefix = "format_amount"
if "currency_id" in line_object and line_object.get("currency_id", False):
if isinstance(line_object["currency_id"], int):
currency = self.env["res.currency"].browse(line_object["currency_id"])
else:
currency = line_object["currency_id"]
field_name = "{}_{}".format(field_prefix, currency.name)
if hasattr(self, field_name):
format_amt = getattr(self, field_name)
else:
format_amt = report_data["workbook"].add_format()
report_data["field_name"] = format_amt
format_amt.set_num_format(self._report_xlsx_currency_format(currency))
return format_amt
def _get_currency_amt_format_dict(self, line_dict, report_data):
"""Return amount format specific for each currency."""
if line_dict.get("account_group_id", False) and line_dict["account_group_id"]:
format_amt = report_data["formats"]["format_amount_bold"]
field_prefix = "format_amount_bold"
else:
format_amt = report_data["formats"]["format_amount"]
field_prefix = "format_amount"
if line_dict.get("currency_id", False) and line_dict["currency_id"]:
if isinstance(line_dict["currency_id"], int):
currency = self.env["res.currency"].browse(line_dict["currency_id"])
else:
currency = line_dict["currency_id"]
field_name = "{}_{}".format(field_prefix, currency.name)
if hasattr(self, field_name):
format_amt = getattr(self, field_name)
else:
format_amt = report_data["workbook"].add_format()
report_data["field_name"] = format_amt
format_amt.set_num_format(self._report_xlsx_currency_format(currency))
return format_amt
def _get_currency_amt_header_format(self, line_object, report_data):
"""Return amount header format for each currency."""
format_amt = report_data["formats"]["format_header_amount"]
if line_object.currency_id:
field_name = "format_header_amount_%s" % line_object.currency_id.name
if hasattr(self, field_name):
format_amt = getattr(self, field_name)
else:
format_amt = report_data["workbook"].add_format(
{"bold": True, "border": True, "bg_color": "#FFFFCC"}
)
report_data["field_name"] = format_amt
format_amount = "#,##0." + (
"0" * line_object.currency_id.decimal_places
)
format_amt.set_num_format(format_amount)
return format_amt
def _get_currency_amt_header_format_dict(self, line_object, report_data):
"""Return amount header format for each currency."""
format_amt = report_data["formats"]["format_header_amount"]
if line_object["currency_id"]:
field_name = "format_header_amount_%s" % line_object["currency_name"]
if hasattr(self, field_name):
format_amt = getattr(self, field_name)
else:
format_amt = report_data["workbook"].add_format(
{"bold": True, "border": True, "bg_color": "#FFFFCC"}
)
report_data["field_name"] = format_amt
format_amount = "#,##0." + (
"0" * line_object["currency_id"].decimal_places
)
format_amt.set_num_format(format_amount)
return format_amt
def _generate_report_content(self, workbook, report, data, report_data):
"""
Allow to fetch report content to be displayed.
"""
raise NotImplementedError()
def _get_report_complete_name(self, report, prefix, data=None):
if report.company_id:
suffix = " - {} - {}".format(
report.company_id.name, report.company_id.currency_id.name
)
return prefix + suffix
return prefix
def _get_report_name(self, report, data=False):
"""
Allow to define the report name.
Report name will be used as sheet name and as report title.
:return: the report name
"""
raise NotImplementedError()
def _get_report_footer(self):
"""
Allow to define the report footer.
:return: the report footer
"""
return False
def _get_report_columns(self, report):
"""
Allow to define the report columns
which will be used to generate report.
:return: the report columns as dict
:Example:
{
0: {'header': 'Simple column',
'field': 'field_name_on_my_object',
'width': 11},
1: {'header': 'Amount column',
'field': 'field_name_on_my_object',
'type': 'amount',
'width': 14},
}
"""
raise NotImplementedError()
def _get_report_filters(self, report):
"""
:return: the report filters as list
:Example:
[
['first_filter_name', 'first_filter_value'],
['second_filter_name', 'second_filter_value']
]
"""
raise NotImplementedError()
def _get_col_count_filter_name(self):
"""
:return: the columns number used for filter names.
"""
raise NotImplementedError()
def _get_col_count_filter_value(self):
"""
:return: the columns number used for filter values.
"""
raise NotImplementedError()
def _get_col_pos_initial_balance_label(self):
"""
:return: the columns position used for initial balance label.
"""
raise NotImplementedError()
def _get_col_count_final_balance_name(self):
"""
:return: the columns number used for final balance name.
"""
raise NotImplementedError()
def _get_col_pos_final_balance_label(self):
"""
:return: the columns position used for final balance label.
"""
raise NotImplementedError()
def write_non_standard_column(self, cell_type, col_pos, value):
"""
Write columns out of the columns type defined here.
"""
raise NotImplementedError()
| 42.84792
| 29,865
|
12,060
|
py
|
PYTHON
|
15.0
|
# Author: Julien Coux
# Copyright 2016 Camptocamp SA
# Copyright 2021 Tecnativa - João Marques
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import _, models
class TrialBalanceXslx(models.AbstractModel):
_name = "report.a_f_r.report_trial_balance_xlsx"
_description = "Trial Balance XLSX Report"
_inherit = "report.account_financial_report.abstract_report_xlsx"
def _get_report_name(self, report, data=False):
company_id = data.get("company_id", False)
report_name = _("Trial Balance")
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_report_columns(self, report):
if not report.show_partner_details:
res = {
0: {"header": _("Code"), "field": "code", "width": 10},
1: {"header": _("Account"), "field": "name", "width": 60},
2: {
"header": _("Initial balance"),
"field": "initial_balance",
"type": "amount",
"width": 14,
},
3: {
"header": _("Debit"),
"field": "debit",
"type": "amount",
"width": 14,
},
4: {
"header": _("Credit"),
"field": "credit",
"type": "amount",
"width": 14,
},
5: {
"header": _("Period balance"),
"field": "balance",
"type": "amount",
"width": 14,
},
6: {
"header": _("Ending balance"),
"field": "ending_balance",
"type": "amount",
"width": 14,
},
}
if report.foreign_currency:
foreign_currency = {
7: {
"header": _("Initial balance"),
"field": "initial_currency_balance",
"type": "amount_currency",
"width": 14,
},
8: {
"header": _("Ending balance"),
"field": "ending_currency_balance",
"type": "amount_currency",
"width": 14,
},
}
res = {**res, **foreign_currency}
return res
else:
res = {
0: {"header": _("Partner"), "field": "name", "width": 70},
1: {
"header": _("Initial balance"),
"field": "initial_balance",
"type": "amount",
"width": 14,
},
2: {
"header": _("Debit"),
"field": "debit",
"type": "amount",
"width": 14,
},
3: {
"header": _("Credit"),
"field": "credit",
"type": "amount",
"width": 14,
},
4: {
"header": _("Period balance"),
"field": "balance",
"type": "amount",
"width": 14,
},
5: {
"header": _("Ending balance"),
"field": "ending_balance",
"type": "amount",
"width": 14,
},
}
if report.foreign_currency:
foreign_currency = {
6: {
"header": _("Initial balance"),
"field": "initial_currency_balance",
"type": "amount_currency",
"width": 14,
},
7: {
"header": _("Ending balance"),
"field": "ending_currency_balance",
"type": "amount_currency",
"width": 14,
},
}
res = {**res, **foreign_currency}
return res
def _get_report_filters(self, report):
return [
[
_("Date range filter"),
_("From: %(date_from)s To: %(date_to)s")
% ({"date_from": report.date_from, "date_to": report.date_to}),
],
[
_("Target moves filter"),
_("All posted entries")
if report.target_move == "posted"
else _("All entries"),
],
[
_("Account at 0 filter"),
_("Hide") if report.hide_account_at_0 else _("Show"),
],
[
_("Show foreign currency"),
_("Yes") if report.foreign_currency else _("No"),
],
[
_("Limit hierarchy levels"),
_("Level %s") % (report.show_hierarchy_level)
if report.limit_hierarchy_level
else _("No limit"),
],
]
def _get_col_count_filter_name(self):
return 2
def _get_col_count_filter_value(self):
return 3
def _generate_report_content(self, workbook, report, data, report_data):
res_data = self.env[
"report.account_financial_report.trial_balance"
]._get_report_values(report, data)
trial_balance = res_data["trial_balance"]
total_amount = res_data["total_amount"]
partners_data = res_data["partners_data"]
accounts_data = res_data["accounts_data"]
show_hierarchy = res_data["show_hierarchy"]
show_partner_details = res_data["show_partner_details"]
show_hierarchy_level = res_data["show_hierarchy_level"]
foreign_currency = res_data["foreign_currency"]
limit_hierarchy_level = res_data["limit_hierarchy_level"]
hide_parent_hierarchy_level = res_data["hide_parent_hierarchy_level"]
if not show_partner_details:
# Display array header for account lines
self.write_array_header(report_data)
# For each account
if not show_partner_details:
for balance in trial_balance:
if show_hierarchy and limit_hierarchy_level:
if show_hierarchy_level > balance["level"] and (
not hide_parent_hierarchy_level
or (show_hierarchy_level - 1) == balance["level"]
):
# Display account lines
self.write_line_from_dict(balance, report_data)
else:
self.write_line_from_dict(balance, report_data)
else:
for account_id in total_amount:
# Write account title
self.write_array_title(
accounts_data[account_id]["code"]
+ "- "
+ accounts_data[account_id]["name"],
report_data,
)
# Display array header for partner lines
self.write_array_header(report_data)
# For each partner
for partner_id in total_amount[account_id]:
if isinstance(partner_id, int):
# Display partner lines
self.write_line_from_dict_order(
total_amount[account_id][partner_id],
partners_data[partner_id],
report_data,
)
# Display account footer line
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"],
}
)
if foreign_currency:
accounts_data[account_id].update(
{
"initial_currency_balance": total_amount[account_id][
"initial_currency_balance"
],
"ending_currency_balance": total_amount[account_id][
"ending_currency_balance"
],
}
)
self.write_account_footer(
accounts_data[account_id],
accounts_data[account_id]["code"]
+ "- "
+ accounts_data[account_id]["name"],
report_data,
)
# Line break
report_data["row_pos"] += 2
def write_line_from_dict_order(self, total_amount, partner_data, report_data):
total_amount.update({"name": str(partner_data["name"])})
self.write_line_from_dict(total_amount, report_data)
def write_line(self, line_object, type_object, report_data):
"""Write a line on current line using all defined columns field name.
Columns are defined with `_get_report_columns` method.
"""
if type_object == "partner":
line_object.currency_id = line_object.report_account_id.currency_id
elif type_object == "account":
line_object.currency_id = line_object.currency_id
return super(TrialBalanceXslx, self).write_line(line_object, report_data)
def write_account_footer(self, account, name_value, report_data):
"""Specific function to write account footer for Trial Balance"""
format_amt = self._get_currency_amt_header_format_dict(account, report_data)
for col_pos, column in report_data["columns"].items():
if column["field"] == "name":
value = name_value
else:
value = account[column["field"]]
cell_type = column.get("type", "string")
if cell_type == "string":
report_data["sheet"].write_string(
report_data["row_pos"],
col_pos,
value or "",
report_data["formats"]["format_header_left"],
)
elif cell_type == "amount":
report_data["sheet"].write_number(
report_data["row_pos"],
col_pos,
float(value),
report_data["formats"]["format_header_amount"],
)
elif cell_type == "many2one" and account["currency_id"]:
report_data["sheet"].write_string(
report_data["row_pos"],
col_pos,
value.name or "",
report_data["formats"]["format_header_right"],
)
elif cell_type == "amount_currency" and account["currency_id"]:
report_data["sheet"].write_number(
report_data["row_pos"], col_pos, float(value), format_amt
)
else:
report_data["sheet"].write_string(
report_data["row_pos"],
col_pos,
"",
report_data["formats"]["format_header_right"],
)
report_data["row_pos"] += 1
| 39.79868
| 12,059
|
2,317
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Forest and Biomass Romania
# Copyright 2021 Tecnativa - João Marques
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import _, models
class VATReportXslx(models.AbstractModel):
_name = "report.a_f_r.report_vat_report_xlsx"
_description = "Vat Report XLSX Report"
_inherit = "report.account_financial_report.abstract_report_xlsx"
def _get_report_name(self, report, data):
company_id = data.get("company_id", False)
report_name = _("Vat Report")
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_report_columns(self, report):
return {
0: {"header": _("Code"), "field": "code", "width": 5},
1: {"header": _("Name"), "field": "name", "width": 100},
2: {"header": _("Net"), "field": "net", "type": "amount", "width": 14},
3: {"header": _("Tax"), "field": "tax", "type": "amount", "width": 14},
}
def _get_report_filters(self, report):
return [
[_("Date from"), report.date_from.strftime("%d/%m/%Y")],
[_("Date to"), report.date_to.strftime("%d/%m/%Y")],
[
_("Based on"),
_("Tax Tags") if report.based_on == "taxtags" else _("Tax Groups"),
],
]
def _get_col_count_filter_name(self):
return 0
def _get_col_count_filter_value(self):
return 2
def _generate_report_content(self, workbook, report, data, report_data):
res_data = self.env[
"report.account_financial_report.vat_report"
]._get_report_values(report, data)
vat_report = res_data["vat_report"]
tax_detail = res_data["tax_detail"]
# For each tax_tag tax_group
self.write_array_header(report_data)
for tag_or_group in vat_report:
# Write taxtag line
self.write_line_from_dict(tag_or_group, report_data)
# For each tax if detail taxes
if tax_detail:
for tax in tag_or_group["taxes"]:
self.write_line_from_dict(tax, report_data)
| 37.967213
| 2,316
|
35,447
|
py
|
PYTHON
|
15.0
|
# © 2016 Julien Coux (Camptocamp)
# Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com)
# Copyright 2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import calendar
import datetime
import operator
from odoo import _, api, models
from odoo.tools import float_is_zero
class GeneralLedgerReport(models.AbstractModel):
_name = "report.account_financial_report.general_ledger"
_description = "General Ledger Report"
_inherit = "report.account_financial_report.abstract_report"
def _get_tags_data(self, tags_ids):
tags = self.env["account.analytic.tag"].browse(tags_ids)
tags_data = {}
for tag in tags:
tags_data.update({tag.id: {"name": tag.name}})
return tags_data
def _get_taxes_data(self, taxes_ids):
taxes = self.env["account.tax"].browse(taxes_ids)
taxes_data = {}
for tax in taxes:
taxes_data.update(
{
tax.id: {
"id": tax.id,
"amount": tax.amount,
"amount_type": tax.amount_type,
"display_name": tax.display_name,
}
}
)
if tax.amount_type == "percent" or tax.amount_type == "division":
taxes_data[tax.id]["string"] = "%"
else:
taxes_data[tax.id]["string"] = ""
taxes_data[tax.id]["tax_name"] = (
tax.display_name
+ " ("
+ str(tax.amount)
+ taxes_data[tax.id]["string"]
+ ")"
)
return taxes_data
def _get_account_internal_types(self, grouped_by):
return ["receivable", "payable"] if grouped_by != "taxes" else ["other"]
def _get_acc_prt_accounts_ids(self, company_id, grouped_by):
accounts_domain = [
("company_id", "=", company_id),
("internal_type", "in", self._get_account_internal_types(grouped_by)),
]
acc_prt_accounts = self.env["account.account"].search(accounts_domain)
return acc_prt_accounts.ids
def _get_initial_balances_bs_ml_domain(
self, account_ids, company_id, date_from, base_domain, grouped_by, acc_prt=False
):
accounts_domain = [
("company_id", "=", company_id),
("user_type_id.include_initial_balance", "=", True),
]
if account_ids:
accounts_domain += [("id", "in", account_ids)]
domain = []
domain += base_domain
domain += [("date", "<", date_from)]
accounts = self.env["account.account"].search(accounts_domain)
domain += [("account_id", "in", accounts.ids)]
if acc_prt:
internal_types = self._get_account_internal_types(grouped_by)
domain += [("account_id.internal_type", "in", internal_types)]
return domain
def _get_initial_balances_pl_ml_domain(
self, account_ids, company_id, date_from, fy_start_date, base_domain
):
accounts_domain = [
("company_id", "=", company_id),
("user_type_id.include_initial_balance", "=", False),
]
if account_ids:
accounts_domain += [("id", "in", account_ids)]
domain = []
domain += base_domain
domain += [("date", "<", date_from), ("date", ">=", fy_start_date)]
accounts = self.env["account.account"].search(accounts_domain)
domain += [("account_id", "in", accounts.ids)]
return domain
def _get_accounts_initial_balance(self, initial_domain_bs, initial_domain_pl):
gl_initial_acc_bs = self.env["account.move.line"].read_group(
domain=initial_domain_bs,
fields=["account_id", "debit", "credit", "balance", "amount_currency"],
groupby=["account_id"],
)
gl_initial_acc_pl = self.env["account.move.line"].read_group(
domain=initial_domain_pl,
fields=["account_id", "debit", "credit", "balance", "amount_currency"],
groupby=["account_id"],
)
gl_initial_acc = gl_initial_acc_bs + gl_initial_acc_pl
return gl_initial_acc
def _get_initial_balance_fy_pl_ml_domain(
self, account_ids, company_id, fy_start_date, base_domain
):
accounts_domain = [
("company_id", "=", company_id),
("user_type_id.include_initial_balance", "=", False),
]
if account_ids:
accounts_domain += [("id", "in", account_ids)]
domain = []
domain += base_domain
domain += [("date", "<", fy_start_date)]
accounts = self.env["account.account"].search(accounts_domain)
domain += [("account_id", "in", accounts.ids)]
return domain
def _get_pl_initial_balance(
self, account_ids, company_id, fy_start_date, foreign_currency, base_domain
):
domain = self._get_initial_balance_fy_pl_ml_domain(
account_ids, company_id, fy_start_date, base_domain
)
initial_balances = self.env["account.move.line"].read_group(
domain=domain,
fields=["account_id", "debit", "credit", "balance", "amount_currency"],
groupby=["account_id"],
)
pl_initial_balance = {
"debit": 0.0,
"credit": 0.0,
"balance": 0.0,
"bal_curr": 0.0,
}
for initial_balance in initial_balances:
pl_initial_balance["debit"] += initial_balance["debit"]
pl_initial_balance["credit"] += initial_balance["credit"]
pl_initial_balance["balance"] += initial_balance["balance"]
pl_initial_balance["bal_curr"] += initial_balance["amount_currency"]
return pl_initial_balance
def _get_gl_initial_acc(
self, account_ids, company_id, date_from, fy_start_date, base_domain, grouped_by
):
initial_domain_bs = self._get_initial_balances_bs_ml_domain(
account_ids, company_id, date_from, base_domain, grouped_by
)
initial_domain_pl = self._get_initial_balances_pl_ml_domain(
account_ids, company_id, date_from, fy_start_date, base_domain
)
return self._get_accounts_initial_balance(initial_domain_bs, initial_domain_pl)
def _prepare_gen_ld_data_item(self, gl):
res = {}
for key_bal in ["init_bal", "fin_bal"]:
res[key_bal] = {}
for key_field in ["credit", "debit", "balance", "bal_curr"]:
field_name = key_field if key_field != "bal_curr" else "amount_currency"
res[key_bal][key_field] = gl[field_name]
return res
def _prepare_gen_ld_data(self, gl_initial_acc, domain, grouped_by):
data = {}
for gl in gl_initial_acc:
acc_id = gl["account_id"][0]
data[acc_id] = self._prepare_gen_ld_data_item(gl)
data[acc_id]["id"] = acc_id
if grouped_by:
data[acc_id][grouped_by] = False
method = "_prepare_gen_ld_data_group_%s" % grouped_by
if not hasattr(self, method):
return data
return getattr(self, method)(data, domain, grouped_by)
def _prepare_gen_ld_data_group_partners(self, data, domain, grouped_by):
gl_initial_acc_prt = self.env["account.move.line"].read_group(
domain=domain,
fields=[
"account_id",
"partner_id",
"debit",
"credit",
"balance",
"amount_currency",
],
groupby=["account_id", "partner_id"],
lazy=False,
)
if gl_initial_acc_prt:
for gl in gl_initial_acc_prt:
if not gl["partner_id"]:
prt_id = 0
prt_name = "Missing Partner"
else:
prt_id = gl["partner_id"][0]
prt_name = gl["partner_id"][1]
prt_name = prt_name._value
acc_id = gl["account_id"][0]
data[acc_id][prt_id] = self._prepare_gen_ld_data_item(gl)
data[acc_id][prt_id]["id"] = prt_id
data[acc_id][prt_id]["name"] = prt_name
data[acc_id][grouped_by] = True
return data
def _prepare_gen_ld_data_group_taxes(self, data, domain, grouped_by):
gl_initial_acc_prt = self.env["account.move.line"].read_group(
domain=domain,
fields=[
"account_id",
"debit",
"credit",
"balance",
"amount_currency",
"tax_line_id",
],
groupby=["account_id"],
lazy=False,
)
if gl_initial_acc_prt:
for gl in gl_initial_acc_prt:
if "tax_line_id" in gl and gl["tax_line_id"]:
tax_id = gl["tax_line_id"][0]
tax_name = gl["tax_line_id"][1]
tax_name = tax_name._value
else:
tax_id = 0
tax_name = "Missing Tax"
acc_id = gl["account_id"][0]
data[acc_id][tax_id] = self._prepare_gen_ld_data_item(gl)
data[acc_id][tax_id]["id"] = tax_id
data[acc_id][tax_id]["name"] = tax_name
data[acc_id][grouped_by] = True
return data
def _get_initial_balance_data(
self,
account_ids,
partner_ids,
company_id,
date_from,
foreign_currency,
only_posted_moves,
unaffected_earnings_account,
fy_start_date,
analytic_tag_ids,
cost_center_ids,
extra_domain,
grouped_by,
):
# If explicit list of accounts is provided,
# don't include unaffected earnings account
if account_ids:
unaffected_earnings_account = False
base_domain = []
if company_id:
base_domain += [("company_id", "=", company_id)]
if partner_ids:
base_domain += [("partner_id", "in", partner_ids)]
if only_posted_moves:
base_domain += [("move_id.state", "=", "posted")]
else:
base_domain += [("move_id.state", "in", ["posted", "draft"])]
if analytic_tag_ids:
base_domain += [("analytic_tag_ids", "in", analytic_tag_ids)]
if cost_center_ids:
base_domain += [("analytic_account_id", "in", cost_center_ids)]
if extra_domain:
base_domain += extra_domain
gl_initial_acc = self._get_gl_initial_acc(
account_ids, company_id, date_from, fy_start_date, base_domain, grouped_by
)
domain = self._get_initial_balances_bs_ml_domain(
account_ids, company_id, date_from, base_domain, grouped_by, acc_prt=True
)
data = self._prepare_gen_ld_data(gl_initial_acc, domain, grouped_by)
accounts_ids = list(data.keys())
unaffected_id = unaffected_earnings_account
if unaffected_id:
if unaffected_id not in accounts_ids:
accounts_ids.append(unaffected_id)
data[unaffected_id] = self._initialize_data(foreign_currency)
data[unaffected_id]["id"] = unaffected_id
data[unaffected_id]["mame"] = ""
data[unaffected_id][grouped_by] = False
pl_initial_balance = self._get_pl_initial_balance(
account_ids, company_id, fy_start_date, foreign_currency, base_domain
)
for key_bal in ["init_bal", "fin_bal"]:
fields_balance = ["credit", "debit", "balance"]
if foreign_currency:
fields_balance.append("bal_curr")
for field_name in fields_balance:
data[unaffected_id][key_bal][field_name] += pl_initial_balance[
field_name
]
return data
@api.model
def _get_move_line_data(self, move_line):
move_line_data = {
"id": move_line["id"],
"date": move_line["date"],
"entry": move_line["move_name"],
"entry_id": move_line["move_id"][0],
"journal_id": move_line["journal_id"][0],
"account_id": move_line["account_id"][0],
"partner_id": move_line["partner_id"][0]
if move_line["partner_id"]
else False,
"partner_name": move_line["partner_id"][1]
if move_line["partner_id"]
else "",
"ref": "" if not move_line["ref"] else move_line["ref"],
"name": "" if not move_line["name"] else move_line["name"],
"tax_ids": move_line["tax_ids"],
"tax_line_id": move_line["tax_line_id"],
"debit": move_line["debit"],
"credit": move_line["credit"],
"balance": move_line["balance"],
"bal_curr": move_line["amount_currency"],
"rec_id": move_line["full_reconcile_id"][0]
if move_line["full_reconcile_id"]
else False,
"rec_name": move_line["full_reconcile_id"][1]
if move_line["full_reconcile_id"]
else "",
"tag_ids": move_line["analytic_tag_ids"],
"currency_id": move_line["currency_id"],
"analytic_account": move_line["analytic_account_id"][1]
if move_line["analytic_account_id"]
else "",
"analytic_account_id": move_line["analytic_account_id"][0]
if move_line["analytic_account_id"]
else False,
}
if (
move_line_data["ref"] == move_line_data["name"]
or move_line_data["ref"] == ""
):
ref_label = move_line_data["name"]
elif move_line_data["name"] == "":
ref_label = move_line_data["ref"]
else:
ref_label = move_line_data["ref"] + str(" - ") + move_line_data["name"]
move_line_data.update({"ref_label": ref_label})
return move_line_data
@api.model
def _get_period_domain(
self,
account_ids,
partner_ids,
company_id,
only_posted_moves,
date_to,
date_from,
analytic_tag_ids,
cost_center_ids,
):
domain = [
("display_type", "=", False),
("date", ">=", date_from),
("date", "<=", date_to),
]
if account_ids:
domain += [("account_id", "in", account_ids)]
if company_id:
domain += [("company_id", "=", company_id)]
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 analytic_tag_ids:
domain += [("analytic_tag_ids", "in", analytic_tag_ids)]
if cost_center_ids:
domain += [("analytic_account_id", "in", cost_center_ids)]
return domain
def _initialize_data(self, foreign_currency):
res = {}
for key_bal in ["init_bal", "fin_bal"]:
res[key_bal] = {}
for key_field in ["balance", "credit", "debit"]:
res[key_bal][key_field] = 0.0
if foreign_currency:
res[key_bal]["bal_curr"] = 0.0
return res
def _get_reconciled_after_date_to_ids(self, full_reconcile_ids, date_to):
full_reconcile_ids = list(full_reconcile_ids)
domain = [
("max_date", ">", date_to),
("full_reconcile_id", "in", full_reconcile_ids),
]
fields = ["full_reconcile_id"]
reconciled_after_date_to = self.env["account.partial.reconcile"].search_read(
domain=domain, fields=fields
)
rec_after_date_to_ids = list(
map(operator.itemgetter("full_reconcile_id"), reconciled_after_date_to)
)
rec_after_date_to_ids = [i[0] for i in rec_after_date_to_ids]
return rec_after_date_to_ids
def _prepare_ml_items(self, move_line, grouped_by):
res = []
if grouped_by == "partners":
item_id = move_line["partner_id"][0] if move_line["partner_id"] else 0
item_name = (
move_line["partner_id"][1]
if move_line["partner_id"]
else "Missing Partner"
)
res.append({"id": item_id, "name": item_name})
elif grouped_by == "taxes":
if move_line["tax_line_id"]:
item_id = move_line["tax_line_id"][0]
item_name = move_line["tax_line_id"][1]
res.append({"id": item_id, "name": item_name})
elif move_line["tax_ids"]:
for tax_id in move_line["tax_ids"]:
tax_item = self.env["account.tax"].browse(tax_id)
res.append({"id": tax_item.id, "name": tax_item.name})
else:
res.append({"id": 0, "name": "Missing Tax"})
else:
res.append({"id": 0, "name": ""})
return res
def _get_period_ml_data(
self,
account_ids,
partner_ids,
company_id,
foreign_currency,
only_posted_moves,
date_from,
date_to,
gen_ld_data,
analytic_tag_ids,
cost_center_ids,
extra_domain,
grouped_by,
):
domain = self._get_period_domain(
account_ids,
partner_ids,
company_id,
only_posted_moves,
date_to,
date_from,
analytic_tag_ids,
cost_center_ids,
)
if extra_domain:
domain += extra_domain
ml_fields = self._get_ml_fields()
move_lines = self.env["account.move.line"].search_read(
domain=domain, fields=ml_fields, order="date,move_name"
)
journal_ids = set()
full_reconcile_ids = set()
taxes_ids = set()
tags_ids = set()
full_reconcile_data = {}
acc_prt_account_ids = self._get_acc_prt_accounts_ids(company_id, grouped_by)
for move_line in move_lines:
journal_ids.add(move_line["journal_id"][0])
for tax_id in move_line["tax_ids"]:
taxes_ids.add(tax_id)
for analytic_tag_id in move_line["analytic_tag_ids"]:
tags_ids.add(analytic_tag_id)
if move_line["full_reconcile_id"]:
rec_id = move_line["full_reconcile_id"][0]
if rec_id not in full_reconcile_ids:
full_reconcile_data.update(
{
rec_id: {
"id": rec_id,
"name": move_line["full_reconcile_id"][1],
}
}
)
full_reconcile_ids.add(rec_id)
acc_id = move_line["account_id"][0]
ml_id = move_line["id"]
if acc_id not in gen_ld_data.keys():
gen_ld_data[acc_id] = self._initialize_data(foreign_currency)
gen_ld_data[acc_id]["id"] = acc_id
gen_ld_data[acc_id]["mame"] = move_line["account_id"][1]
if grouped_by:
gen_ld_data[acc_id][grouped_by] = False
if acc_id in acc_prt_account_ids:
item_ids = self._prepare_ml_items(move_line, grouped_by)
for item in item_ids:
item_id = item["id"]
if item_id not in gen_ld_data[acc_id]:
if grouped_by:
gen_ld_data[acc_id][grouped_by] = True
gen_ld_data[acc_id][item_id] = self._initialize_data(
foreign_currency
)
gen_ld_data[acc_id][item_id]["id"] = item_id
gen_ld_data[acc_id][item_id]["name"] = item["name"]
gen_ld_data[acc_id][item_id][ml_id] = self._get_move_line_data(
move_line
)
gen_ld_data[acc_id][item_id]["fin_bal"]["credit"] += move_line[
"credit"
]
gen_ld_data[acc_id][item_id]["fin_bal"]["debit"] += move_line[
"debit"
]
gen_ld_data[acc_id][item_id]["fin_bal"]["balance"] += move_line[
"balance"
]
if foreign_currency:
gen_ld_data[acc_id][item_id]["fin_bal"][
"bal_curr"
] += move_line["amount_currency"]
else:
gen_ld_data[acc_id][ml_id] = self._get_move_line_data(move_line)
gen_ld_data[acc_id]["fin_bal"]["credit"] += move_line["credit"]
gen_ld_data[acc_id]["fin_bal"]["debit"] += move_line["debit"]
gen_ld_data[acc_id]["fin_bal"]["balance"] += move_line["balance"]
if foreign_currency:
gen_ld_data[acc_id]["fin_bal"]["bal_curr"] += move_line[
"amount_currency"
]
journals_data = self._get_journals_data(list(journal_ids))
accounts_data = self._get_accounts_data(gen_ld_data.keys())
taxes_data = self._get_taxes_data(list(taxes_ids))
tags_data = self._get_tags_data(list(tags_ids))
rec_after_date_to_ids = self._get_reconciled_after_date_to_ids(
full_reconcile_data.keys(), date_to
)
return (
gen_ld_data,
accounts_data,
journals_data,
full_reconcile_data,
taxes_data,
tags_data,
rec_after_date_to_ids,
)
@api.model
def _recalculate_cumul_balance(
self, move_lines, last_cumul_balance, rec_after_date_to_ids
):
for move_line in move_lines:
move_line["balance"] += last_cumul_balance
last_cumul_balance = move_line["balance"]
if move_line["rec_id"] in rec_after_date_to_ids:
move_line["rec_name"] = "(" + _("future") + ") " + move_line["rec_name"]
return move_lines
def _create_account(self, account, acc_id, gen_led_data, rec_after_date_to_ids):
move_lines = []
for ml_id in gen_led_data[acc_id].keys():
if not isinstance(ml_id, int):
account.update({ml_id: gen_led_data[acc_id][ml_id]})
else:
move_lines += [gen_led_data[acc_id][ml_id]]
move_lines = sorted(move_lines, key=lambda k: (k["date"]))
move_lines = self._recalculate_cumul_balance(
move_lines,
gen_led_data[acc_id]["init_bal"]["balance"],
rec_after_date_to_ids,
)
account.update({"move_lines": move_lines})
return account
def _create_account_not_show_item(
self, account, acc_id, gen_led_data, rec_after_date_to_ids, grouped_by
):
move_lines = []
for prt_id in gen_led_data[acc_id].keys():
if not isinstance(prt_id, int):
account.update({prt_id: gen_led_data[acc_id][prt_id]})
elif isinstance(gen_led_data[acc_id][prt_id], dict):
for ml_id in gen_led_data[acc_id][prt_id].keys():
if isinstance(ml_id, int):
move_lines += [gen_led_data[acc_id][prt_id][ml_id]]
move_lines = sorted(move_lines, key=lambda k: (k["date"]))
move_lines = self._recalculate_cumul_balance(
move_lines,
gen_led_data[acc_id]["init_bal"]["balance"],
rec_after_date_to_ids,
)
account.update({"move_lines": move_lines, grouped_by: False})
return account
def _get_list_grouped_item(
self, data, account, rec_after_date_to_ids, hide_account_at_0, rounding
):
list_grouped = []
for data_id in data.keys():
group_item = {}
move_lines = []
if not isinstance(data_id, int):
account.update({data_id: data[data_id]})
else:
for ml_id in data[data_id].keys():
if not isinstance(ml_id, int):
group_item.update({ml_id: data[data_id][ml_id]})
else:
move_lines += [data[data_id][ml_id]]
move_lines = sorted(move_lines, key=lambda k: (k["date"]))
move_lines = self._recalculate_cumul_balance(
move_lines,
data[data_id]["init_bal"]["balance"],
rec_after_date_to_ids,
)
group_item.update({"move_lines": move_lines})
if (
hide_account_at_0
and float_is_zero(
data[data_id]["init_bal"]["balance"],
precision_rounding=rounding,
)
and group_item["move_lines"] == []
):
continue
list_grouped += [group_item]
return account, list_grouped
def _create_general_ledger(
self,
gen_led_data,
accounts_data,
grouped_by,
rec_after_date_to_ids,
hide_account_at_0,
):
general_ledger = []
rounding = self.env.company.currency_id.rounding
for acc_id in gen_led_data.keys():
account = {}
account.update(
{
"code": accounts_data[acc_id]["code"],
"name": accounts_data[acc_id]["name"],
"type": "account",
"currency_id": accounts_data[acc_id]["currency_id"],
"centralized": accounts_data[acc_id]["centralized"],
"grouped_by": grouped_by,
}
)
if grouped_by and not gen_led_data[acc_id][grouped_by]:
account = self._create_account(
account, acc_id, gen_led_data, rec_after_date_to_ids
)
if (
hide_account_at_0
and float_is_zero(
gen_led_data[acc_id]["init_bal"]["balance"],
precision_rounding=rounding,
)
and account["move_lines"] == []
):
continue
else:
if grouped_by:
account, list_grouped = self._get_list_grouped_item(
gen_led_data[acc_id],
account,
rec_after_date_to_ids,
hide_account_at_0,
rounding,
)
account.update({"list_grouped": list_grouped})
if (
hide_account_at_0
and float_is_zero(
gen_led_data[acc_id]["init_bal"]["balance"],
precision_rounding=rounding,
)
and account["list_grouped"] == []
):
continue
else:
account = self._create_account_not_show_item(
account, acc_id, gen_led_data, rec_after_date_to_ids, grouped_by
)
if (
hide_account_at_0
and float_is_zero(
gen_led_data[acc_id]["init_bal"]["balance"],
precision_rounding=rounding,
)
and account["move_lines"] == []
):
continue
general_ledger += [account]
return general_ledger
@api.model
def _calculate_centralization(self, centralized_ml, move_line, date_to):
jnl_id = move_line["journal_id"]
month = move_line["date"].month
if jnl_id not in centralized_ml.keys():
centralized_ml[jnl_id] = {}
if month not in centralized_ml[jnl_id].keys():
centralized_ml[jnl_id][month] = {}
last_day_month = calendar.monthrange(move_line["date"].year, month)
date = datetime.date(move_line["date"].year, month, last_day_month[1])
if date > date_to:
date = date_to
centralized_ml[jnl_id][month].update(
{
"journal_id": jnl_id,
"ref_label": "Centralized entries",
"date": date,
"debit": 0.0,
"credit": 0.0,
"balance": 0.0,
"bal_curr": 0.0,
"partner_id": False,
"rec_id": 0,
"entry_id": False,
"tax_ids": [],
"tax_line_id": False,
"full_reconcile_id": False,
"id": False,
"tag_ids": False,
"currency_id": False,
"analytic_account_id": False,
}
)
centralized_ml[jnl_id][month]["debit"] += move_line["debit"]
centralized_ml[jnl_id][month]["credit"] += move_line["credit"]
centralized_ml[jnl_id][month]["balance"] += (
move_line["debit"] - move_line["credit"]
)
centralized_ml[jnl_id][month]["bal_curr"] += move_line["bal_curr"]
return centralized_ml
@api.model
def _get_centralized_ml(self, account, date_to, grouped_by):
centralized_ml = {}
if isinstance(date_to, str):
date_to = datetime.datetime.strptime(date_to, "%Y-%m-%d").date()
if grouped_by and account[grouped_by]:
for item in account["list_grouped"]:
for move_line in item["move_lines"]:
centralized_ml = self._calculate_centralization(
centralized_ml,
move_line,
date_to,
)
else:
for move_line in account["move_lines"]:
centralized_ml = self._calculate_centralization(
centralized_ml,
move_line,
date_to,
)
list_centralized_ml = []
for jnl_id in centralized_ml.keys():
list_centralized_ml += list(centralized_ml[jnl_id].values())
return list_centralized_ml
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"]
analytic_tag_ids = data["analytic_tag_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,
foreign_currency,
only_posted_moves,
unaffected_earnings_account,
fy_start_date,
analytic_tag_ids,
cost_center_ids,
extra_domain,
grouped_by,
)
centralize = data["centralize"]
(
gen_ld_data,
accounts_data,
journals_data,
full_reconcile_data,
taxes_data,
tags_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,
analytic_tag_ids,
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_analytic_tags": data["show_analytic_tags"],
"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,
"tags_data": tags_data,
"filter_partner_ids": True if partner_ids else False,
"currency_model": self.env["res.currency"],
}
def _get_ml_fields(self):
return self.COMMON_ML_FIELDS + [
"analytic_account_id",
"full_reconcile_id",
"analytic_tag_ids",
"tax_line_id",
"currency_id",
"credit",
"debit",
"amount_currency",
"balance",
"tax_ids",
"move_name",
]
| 39.735426
| 35,444
|
15,362
|
py
|
PYTHON
|
15.0
|
# Copyright 2019-20 ForgeFlow S.L. (https://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
import itertools
import operator
from odoo import models
class JournalLedgerReport(models.AbstractModel):
_name = "report.account_financial_report.journal_ledger"
_description = "Journal Ledger Report"
def _get_journal_ledger_data(self, journal):
return {
"id": journal.id,
"name": journal.name,
"currency_id": journal.currency_id.id,
"currency_name": journal.currency_id
and journal.currency_id.name
or journal.company_id.currency_id.name,
"debit": 0.0,
"credit": 0.0,
}
def _get_journal_ledgers_domain(self, wizard, journal_ids, company):
domain = []
if company:
domain += [("company_id", "=", company.id)]
if journal_ids:
domain += [("id", "in", journal_ids)]
return domain
def _get_journal_ledgers(self, wizard, journal_ids, company):
journals = self.env["account.journal"].search(
self._get_journal_ledgers_domain(wizard, journal_ids, company),
order="name asc",
)
journal_ledgers_data = []
for journal in journals:
journal_ledgers_data.append(self._get_journal_ledger_data(journal))
return journal_ledgers_data
def _get_moves_domain(self, wizard, journal_ids):
domain = [
("journal_id", "in", journal_ids),
("date", ">=", wizard.date_from),
("date", "<=", wizard.date_to),
]
if wizard.move_target != "all":
domain += [("state", "=", wizard.move_target)]
else:
domain += [("state", "in", ["posted", "draft"])]
return domain
def _get_moves_order(self, wizard, journal_ids):
search_order = ""
if wizard.sort_option == "move_name":
search_order = "name asc"
elif wizard.sort_option == "date":
search_order = "date asc, name asc"
return search_order
def _get_moves_data(self, move):
return {
"move_id": move.id,
"journal_id": move.journal_id.id,
"entry": move.name,
}
def _get_moves(self, wizard, journal_ids):
moves = self.env["account.move"].search(
self._get_moves_domain(wizard, journal_ids),
order=self._get_moves_order(wizard, journal_ids),
)
Moves = []
move_data = {}
for move in moves:
move_data[move.id] = self._get_moves_data(move)
Moves.append(move_data[move.id])
return moves.ids, Moves, move_data
def _get_move_lines_domain(self, move_ids, wizard, journal_ids):
return [("display_type", "=", False), ("move_id", "in", move_ids)]
def _get_move_lines_order(self, move_ids, wizard, journal_ids):
"""Add `move_id` to make sure the order of the records is correct
(especially if we use auto-sequence).
"""
return "move_id"
def _get_move_lines_data(self, ml, wizard, ml_taxes, auto_sequence, exigible):
base_debit = (
base_credit
) = tax_debit = tax_credit = base_balance = tax_balance = 0.0
if exigible:
base_debit = ml_taxes and ml.debit or 0.0
base_credit = ml_taxes and ml.credit or 0.0
base_balance = ml_taxes and ml.balance or 0.0
tax_debit = ml.tax_line_id and ml.debit or 0.0
tax_credit = ml.tax_line_id and ml.credit or 0.0
tax_balance = ml.tax_line_id and ml.balance or 0.0
return {
"move_line_id": ml.id,
"move_id": ml.move_id.id,
"date": ml.date,
"journal_id": ml.journal_id.id,
"account_id": ml.account_id.id,
"partner_id": ml.partner_id.id,
"label": ml.name,
"debit": ml.debit,
"credit": ml.credit,
"company_currency_id": ml.company_currency_id.id,
"amount_currency": ml.amount_currency,
"currency_id": ml.currency_id.id,
"tax_line_id": ml.tax_line_id.id,
"tax_ids": list(ml_taxes.keys()),
"base_debit": base_debit,
"base_credit": base_credit,
"tax_debit": tax_debit,
"tax_credit": tax_credit,
"base_balance": base_balance,
"tax_balance": tax_balance,
"auto_sequence": str(auto_sequence).zfill(6),
}
def _get_account_data(self, accounts):
data = {}
for account in accounts:
data[account.id] = self._get_account_id_data(account)
return data
def _get_account_id_data(self, account):
return {
"name": account.name,
"code": account.code,
"internal_type": account.internal_type,
}
def _get_partner_data(self, partners):
data = {}
for partner in partners:
data[partner.id] = self._get_partner_id_data(partner)
return data
def _get_partner_id_data(self, partner):
return {"name": partner.name}
def _get_currency_data(self, currencies):
data = {}
for currency in currencies:
data[currency.id] = self._get_currency_id_data(currency)
return data
def _get_currency_id_data(self, currency):
return {"name": currency.name}
def _get_tax_line_data(self, taxes):
data = {}
for tax in taxes:
data[tax.id] = self._get_tax_line_id_data(tax)
return data
def _get_tax_line_id_data(self, tax):
return {"name": tax.name, "description": tax.description}
def _get_query_taxes(self):
return """
SELECT aml_at_rel.account_move_line_id, aml_at_rel.account_tax_id,
at.description, at.name
FROM account_move_line_account_tax_rel AS aml_at_rel
LEFT JOIN
account_tax AS at on (at.id = aml_at_rel.account_tax_id)
WHERE account_move_line_id IN %(move_line_ids)s
"""
def _get_query_taxes_params(self, move_lines):
return {"move_line_ids": tuple(move_lines.ids)}
def _get_move_lines(self, move_ids, wizard, journal_ids):
move_lines = self.env["account.move.line"].search(
self._get_move_lines_domain(move_ids, wizard, journal_ids),
order=self._get_move_lines_order(move_ids, wizard, journal_ids),
)
move_lines_exigible = self.env["account.move.line"].search(
self._get_move_lines_domain(move_ids, wizard, journal_ids)
+ self.env["account.move.line"]._get_tax_exigible_domain(),
)
move_line_ids_taxes_data = {}
if move_lines:
# Get the taxes ids for the move lines
query_taxes_params = self._get_query_taxes_params(move_lines)
query_taxes = self._get_query_taxes()
self.env.cr.execute(query_taxes, query_taxes_params)
# Fetch the taxes associated to the move line
for (
move_line_id,
account_tax_id,
tax_description,
tax_name,
) in self.env.cr.fetchall():
if move_line_id not in move_line_ids_taxes_data.keys():
move_line_ids_taxes_data[move_line_id] = {}
move_line_ids_taxes_data[move_line_id][account_tax_id] = {
"name": tax_name,
"description": tax_description,
}
Move_Lines = {}
accounts = self.env["account.account"]
partners = self.env["res.partner"]
currencies = self.env["res.currency"]
tax_lines = self.env["account.tax"]
auto_sequence = len(move_ids)
for ml in move_lines:
if ml.account_id not in accounts:
accounts |= ml.account_id
if ml.partner_id not in partners:
partners |= ml.partner_id
if ml.currency_id not in currencies:
currencies |= ml.currency_id
if ml.tax_line_id not in tax_lines:
tax_lines |= ml.tax_line_id
if ml.move_id.id not in Move_Lines.keys():
Move_Lines[ml.move_id.id] = []
auto_sequence -= 1
taxes = (
ml.id in move_line_ids_taxes_data.keys()
and move_line_ids_taxes_data[ml.id]
or {}
)
exigible = ml in move_lines_exigible
Move_Lines[ml.move_id.id].append(
self._get_move_lines_data(ml, wizard, taxes, auto_sequence, exigible)
)
account_ids_data = self._get_account_data(accounts)
partner_ids_data = self._get_partner_data(partners)
currency_ids_data = self._get_currency_data(currencies)
tax_line_ids_data = self._get_tax_line_data(tax_lines)
return (
move_lines.ids,
Move_Lines,
account_ids_data,
partner_ids_data,
currency_ids_data,
tax_line_ids_data,
move_line_ids_taxes_data,
)
def _get_journal_tax_lines(self, wizard, moves_data):
journals_taxes_data = {}
for move_data in moves_data:
report_move_lines = move_data["report_move_lines"]
for report_move_line in report_move_lines:
ml_data = report_move_line
tax_ids = []
if ml_data["tax_line_id"]:
tax_ids.append(ml_data["tax_line_id"])
if ml_data["tax_ids"]:
tax_ids += ml_data["tax_ids"]
tax_ids = list(set(tax_ids))
journal_id = ml_data["journal_id"]
if journal_id not in journals_taxes_data.keys():
journals_taxes_data[journal_id] = {}
taxes = self.env["account.tax"].browse(tax_ids)
for tax in taxes:
if tax.id not in journals_taxes_data[journal_id]:
journals_taxes_data[journal_id][tax.id] = {
"base_debit": 0.0,
"base_credit": 0.0,
"base_balance": 0.0,
"tax_debit": 0.0,
"tax_credit": 0.0,
"tax_balance": 0.0,
"tax_name": tax.name,
"tax_code": tax.description,
}
field_keys = [
"base_debit",
"base_credit",
"base_balance",
"tax_debit",
"tax_credit",
"tax_balance",
]
for field_key in field_keys:
journals_taxes_data[journal_id][tax.id][field_key] += ml_data[
field_key
]
journals_taxes_data_2 = {}
for journal_id in journals_taxes_data.keys():
journals_taxes_data_2[journal_id] = []
for tax_id in journals_taxes_data[journal_id].keys():
journals_taxes_data_2[journal_id] += [
journals_taxes_data[journal_id][tax_id]
]
return journals_taxes_data_2
def _get_report_values(self, docids, data):
wizard_id = data["wizard_id"]
wizard = self.env["journal.ledger.report.wizard"].browse(wizard_id)
company = self.env["res.company"].browse(data["company_id"])
journal_ids = data["journal_ids"]
journal_ledgers_data = self._get_journal_ledgers(wizard, journal_ids, company)
move_ids, moves_data, move_ids_data = self._get_moves(wizard, journal_ids)
journal_moves_data = {}
for key, items in itertools.groupby(
moves_data, operator.itemgetter("journal_id")
):
if key not in journal_moves_data.keys():
journal_moves_data[key] = []
journal_moves_data[key] += list(items)
move_lines_data = (
account_ids_data
) = (
partner_ids_data
) = currency_ids_data = tax_line_ids_data = move_line_ids_taxes_data = {}
if move_ids:
move_lines = self._get_move_lines(move_ids, wizard, journal_ids)
move_lines_data = move_lines[1]
account_ids_data = move_lines[2]
partner_ids_data = move_lines[3]
currency_ids_data = move_lines[4]
tax_line_ids_data = move_lines[5]
for move_data in moves_data:
move_id = move_data["move_id"]
move_data["report_move_lines"] = []
if move_id in move_lines_data.keys():
move_data["report_move_lines"] += move_lines_data[move_id]
journals_taxes_data = {}
if moves_data:
journals_taxes_data = self._get_journal_tax_lines(wizard, moves_data)
for journal_ledger_data in journal_ledgers_data:
journal_id = journal_ledger_data["id"]
journal_ledger_data["tax_lines"] = journals_taxes_data.get(journal_id, [])
journal_totals = {}
for move_id in move_lines_data.keys():
for move_line_data in move_lines_data[move_id]:
journal_id = move_line_data["journal_id"]
if journal_id not in journal_totals.keys():
journal_totals[journal_id] = {"debit": 0.0, "credit": 0.0}
for item in ["debit", "credit"]:
journal_totals[journal_id][item] += move_line_data[item]
for journal_ledger_data in journal_ledgers_data:
journal_id = journal_ledger_data["id"]
if journal_id in journal_moves_data.keys():
journal_ledger_data["report_moves"] = journal_moves_data[journal_id]
else:
journal_ledger_data["report_moves"] = []
if journal_id in journal_totals.keys():
for item in ["debit", "credit"]:
journal_ledger_data[item] += journal_totals[journal_id][item]
return {
"doc_ids": [wizard_id],
"doc_model": "journal.ledger.report.wizard",
"docs": self.env["journal.ledger.report.wizard"].browse(wizard_id),
"group_option": data["group_option"],
"foreign_currency": data["foreign_currency"],
"with_account_name": data["with_account_name"],
"company_name": company.display_name,
"currency_name": company.currency_id.name,
"date_from": data["date_from"],
"date_to": data["date_to"],
"move_target": data["move_target"],
"with_auto_sequence": data["with_auto_sequence"],
"account_ids_data": account_ids_data,
"partner_ids_data": partner_ids_data,
"currency_ids_data": currency_ids_data,
"move_ids_data": move_ids_data,
"tax_line_data": tax_line_ids_data,
"move_line_ids_taxes_data": move_line_ids_taxes_data,
"Journal_Ledgers": journal_ledgers_data,
"Moves": moves_data,
}
| 41.184987
| 15,362
|
12,312
|
py
|
PYTHON
|
15.0
|
# Author: Julien Coux
# Copyright 2016 Camptocamp SA
# Copyright 2021 Tecnativa - João Marques
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import _, models
class AgedPartnerBalanceXslx(models.AbstractModel):
_name = "report.a_f_r.report_aged_partner_balance_xlsx"
_description = "Aged Partner Balance XLSL Report"
_inherit = "report.account_financial_report.abstract_report_xlsx"
def _get_report_name(self, report, data=False):
company_id = data.get("company_id", False)
report_name = _("Aged Partner Balance")
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_report_columns(self, report):
if not report.show_move_line_details:
return {
0: {"header": _("Partner"), "field": "name", "width": 70},
1: {
"header": _("Residual"),
"field": "residual",
"field_footer_total": "residual",
"type": "amount",
"width": 14,
},
2: {
"header": _("Current"),
"field": "current",
"field_footer_total": "current",
"field_footer_percent": "percent_current",
"type": "amount",
"width": 14,
},
3: {
"header": _("Age ≤ 30 d."),
"field": "30_days",
"field_footer_total": "30_days",
"field_footer_percent": "percent_30_days",
"type": "amount",
"width": 14,
},
4: {
"header": _("Age ≤ 60 d."),
"field": "60_days",
"field_footer_total": "60_days",
"field_footer_percent": "percent_60_days",
"type": "amount",
"width": 14,
},
5: {
"header": _("Age ≤ 90 d."),
"field": "90_days",
"field_footer_total": "90_days",
"field_footer_percent": "percent_90_days",
"type": "amount",
"width": 14,
},
6: {
"header": _("Age ≤ 120 d."),
"field": "120_days",
"field_footer_total": "120_days",
"field_footer_percent": "percent_120_days",
"type": "amount",
"width": 14,
},
7: {
"header": _("Older"),
"field": "older",
"field_footer_total": "older",
"field_footer_percent": "percent_older",
"type": "amount",
"width": 14,
},
}
return {
0: {"header": _("Date"), "field": "date", "width": 11},
1: {"header": _("Entry"), "field": "entry", "width": 18},
2: {"header": _("Journal"), "field": "journal", "width": 8},
3: {"header": _("Account"), "field": "account", "width": 9},
4: {"header": _("Partner"), "field": "partner", "width": 25},
5: {"header": _("Ref - Label"), "field": "ref_label", "width": 40},
6: {"header": _("Due date"), "field": "due_date", "width": 11},
7: {
"header": _("Residual"),
"field": "residual",
"field_footer_total": "residual",
"field_final_balance": "residual",
"type": "amount",
"width": 14,
},
8: {
"header": _("Current"),
"field": "current",
"field_footer_total": "current",
"field_footer_percent": "percent_current",
"field_final_balance": "current",
"type": "amount",
"width": 14,
},
9: {
"header": _("Age ≤ 30 d."),
"field": "30_days",
"field_footer_total": "30_days",
"field_footer_percent": "percent_30_days",
"field_final_balance": "30_days",
"type": "amount",
"width": 14,
},
10: {
"header": _("Age ≤ 60 d."),
"field": "60_days",
"field_footer_total": "60_days",
"field_footer_percent": "percent_60_days",
"field_final_balance": "60_days",
"type": "amount",
"width": 14,
},
11: {
"header": _("Age ≤ 90 d."),
"field": "90_days",
"field_footer_total": "90_days",
"field_footer_percent": "percent_90_days",
"field_final_balance": "90_days",
"type": "amount",
"width": 14,
},
12: {
"header": _("Age ≤ 120 d."),
"field": "120_days",
"field_footer_total": "120_days",
"field_footer_percent": "percent_120_days",
"field_final_balance": "120_days",
"type": "amount",
"width": 14,
},
13: {
"header": _("Older"),
"field": "older",
"field_footer_total": "older",
"field_footer_percent": "percent_older",
"field_final_balance": "older",
"type": "amount",
"width": 14,
},
}
def _get_report_filters(self, report):
return [
[_("Date at filter"), report.date_at.strftime("%d/%m/%Y")],
[
_("Target moves filter"),
_("All posted entries")
if report.target_move == "posted"
else _("All entries"),
],
]
def _get_col_count_filter_name(self):
return 2
def _get_col_count_filter_value(self):
return 3
def _get_col_pos_footer_label(self, report):
return 0 if not report.show_move_line_details else 5
def _get_col_count_final_balance_name(self):
return 5
def _get_col_pos_final_balance_label(self):
return 5
def _generate_report_content(self, workbook, report, data, report_data):
res_data = self.env[
"report.account_financial_report.aged_partner_balance"
]._get_report_values(report, data)
show_move_line_details = res_data["show_move_lines_details"]
aged_partner_balance = res_data["aged_partner_balance"]
if not show_move_line_details:
# For each account
for account in aged_partner_balance:
# Write account title
self.write_array_title(
account["code"] + " - " + account["name"], report_data
)
# Display array header for partners lines
self.write_array_header(report_data)
# Display partner lines
for partner in account["partners"]:
self.write_line_from_dict(partner, report_data)
# Display account lines
self.write_account_footer_from_dict(
report,
account,
("Total"),
"field_footer_total",
report_data["formats"]["format_header_right"],
report_data["formats"]["format_header_amount"],
False,
report_data,
)
self.write_account_footer_from_dict(
report,
account,
("Percents"),
"field_footer_percent",
report_data["formats"]["format_right_bold_italic"],
report_data["formats"]["format_percent_bold_italic"],
True,
report_data,
)
# 2 lines break
report_data["row_pos"] += 2
else:
# For each account
for account in aged_partner_balance:
# Write account title
self.write_array_title(
account["code"] + " - " + account["name"], report_data
)
# For each partner
for partner in account["partners"]:
# Write partner title
self.write_array_title(partner["name"], report_data)
# Display array header for move lines
self.write_array_header(report_data)
# Display account move lines
for line in partner["move_lines"]:
self.write_line_from_dict(line, report_data)
# Display ending balance line for partner
self.write_ending_balance_from_dict(partner, report_data)
# Line break
report_data["row_pos"] += 1
# Display account lines
self.write_account_footer_from_dict(
report,
account,
("Total"),
"field_footer_total",
report_data["formats"]["format_header_right"],
report_data["formats"]["format_header_amount"],
False,
report_data,
)
self.write_account_footer_from_dict(
report,
account,
("Percents"),
"field_footer_percent",
report_data["formats"]["format_right_bold_italic"],
report_data["formats"]["format_percent_bold_italic"],
True,
report_data,
)
# 2 lines break
report_data["row_pos"] += 2
def write_ending_balance_from_dict(self, my_object, report_data):
"""
Specific function to write ending partner balance
for Aged Partner Balance
"""
name = None
label = _("Partner cumul aged balance")
return super().write_ending_balance_from_dict(
my_object, name, label, report_data
)
def write_account_footer_from_dict(
self,
report,
account,
label,
field_name,
string_format,
amount_format,
amount_is_percent,
report_data,
):
"""
Specific function to write account footer for Aged Partner Balance
"""
col_pos_footer_label = self._get_col_pos_footer_label(report)
for col_pos, column in report_data["columns"].items():
if col_pos == col_pos_footer_label or column.get(field_name):
if col_pos == col_pos_footer_label:
value = label
else:
value = account.get(column[field_name], False)
cell_type = column.get("type", "string")
if cell_type == "string" or col_pos == col_pos_footer_label:
report_data["sheet"].write_string(
report_data["row_pos"], col_pos, value or "", string_format
)
elif cell_type == "amount":
number = float(value)
if amount_is_percent:
number /= 100
report_data["sheet"].write_number(
report_data["row_pos"], col_pos, number, amount_format
)
else:
report_data["sheet"].write_string(
report_data["row_pos"], col_pos, "", string_format
)
report_data["row_pos"] += 1
| 37.599388
| 12,295
|
5,965
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, models
class AgedPartnerBalanceReport(models.AbstractModel):
_name = "report.account_financial_report.abstract_report"
_description = "Abstract Report"
COMMON_ML_FIELDS = [
"account_id",
"partner_id",
"journal_id",
"date",
"ref",
"id",
"move_id",
"name",
]
@api.model
def _get_move_lines_domain_not_reconciled(
self, company_id, account_ids, partner_ids, only_posted_moves, date_from
):
domain = [
("account_id", "in", account_ids),
("company_id", "=", company_id),
("reconciled", "=", False),
]
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 date_from:
domain += [("date", ">", date_from)]
return domain
@api.model
def _get_new_move_lines_domain(
self, new_ml_ids, account_ids, company_id, partner_ids, only_posted_moves
):
domain = [
("account_id", "in", account_ids),
("company_id", "=", company_id),
("id", "in", new_ml_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"])]
return domain
def _recalculate_move_lines(
self,
move_lines,
debit_ids,
credit_ids,
debit_amount,
credit_amount,
ml_ids,
account_ids,
company_id,
partner_ids,
only_posted_moves,
debit_amount_currency,
credit_amount_currency,
):
debit_ids = set(debit_ids)
credit_ids = set(credit_ids)
in_credit_but_not_in_debit = credit_ids - debit_ids
reconciled_ids = list(debit_ids) + list(in_credit_but_not_in_debit)
reconciled_ids = set(reconciled_ids)
ml_ids = set(ml_ids)
new_ml_ids = reconciled_ids - ml_ids
new_ml_ids = list(new_ml_ids)
new_domain = self._get_new_move_lines_domain(
new_ml_ids, account_ids, company_id, partner_ids, only_posted_moves
)
company_currency = self.env["res.company"].browse(company_id).currency_id
ml_fields = self._get_ml_fields()
new_move_lines = self.env["account.move.line"].search_read(
domain=new_domain, fields=ml_fields
)
move_lines = move_lines + new_move_lines
for move_line in move_lines:
ml_id = move_line["id"]
if ml_id in debit_ids:
if move_line.get("amount_residual", False):
move_line["amount_residual"] += debit_amount[ml_id]
else:
move_line["amount_residual"] = debit_amount[ml_id]
if move_line.get("amount_residual_currency", False):
move_line["amount_residual_currency"] += debit_amount_currency[
ml_id
]
else:
move_line["amount_residual_currency"] = debit_amount_currency[ml_id]
if ml_id in credit_ids:
if move_line.get("amount_residual", False):
move_line["amount_residual"] -= credit_amount[ml_id]
else:
move_line["amount_residual"] = -credit_amount[ml_id]
if move_line.get("amount_residual_currency", False):
move_line["amount_residual_currency"] -= credit_amount_currency[
ml_id
]
else:
move_line["amount_residual_currency"] = -credit_amount_currency[
ml_id
]
# Set amount_currency=0 to keep the same behaviour as in v13
# Conditions: if there is no curency_id defined or it is equal
# to the company's curency_id
if "amount_currency" in move_line and (
"currency_id" not in move_line
or move_line["currency_id"] == company_currency.id
):
move_line["amount_currency"] = 0
return move_lines
def _get_accounts_data(self, accounts_ids):
accounts = self.env["account.account"].browse(accounts_ids)
accounts_data = {}
for account in accounts:
accounts_data.update(
{
account.id: {
"id": account.id,
"code": account.code,
"name": account.name,
"hide_account": False,
"group_id": account.group_id.id,
"currency_id": account.currency_id or False,
"currency_name": account.currency_id.name,
"centralized": account.centralized,
}
}
)
return accounts_data
def _get_journals_data(self, journals_ids):
journals = self.env["account.journal"].browse(journals_ids)
journals_data = {}
for journal in journals:
journals_data.update({journal.id: {"id": journal.id, "code": journal.code}})
return journals_data
def _get_ml_fields(self):
return self.COMMON_ML_FIELDS + [
"amount_residual",
"reconciled",
"currency_id",
"credit",
"date_maturity",
"amount_residual_currency",
"debit",
"amount_currency",
]
| 36.820988
| 5,965
|
16,271
|
py
|
PYTHON
|
15.0
|
# © 2016 Julien Coux (Camptocamp)
# Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import operator
from datetime import date, datetime, timedelta
from odoo import api, models
from odoo.tools import float_is_zero
class AgedPartnerBalanceReport(models.AbstractModel):
_name = "report.account_financial_report.aged_partner_balance"
_description = "Aged Partner Balance Report"
_inherit = "report.account_financial_report.abstract_report"
@api.model
def _initialize_account(self, ag_pb_data, acc_id):
ag_pb_data[acc_id] = {}
ag_pb_data[acc_id]["id"] = acc_id
ag_pb_data[acc_id]["residual"] = 0.0
ag_pb_data[acc_id]["current"] = 0.0
ag_pb_data[acc_id]["30_days"] = 0.0
ag_pb_data[acc_id]["60_days"] = 0.0
ag_pb_data[acc_id]["90_days"] = 0.0
ag_pb_data[acc_id]["120_days"] = 0.0
ag_pb_data[acc_id]["older"] = 0.0
return ag_pb_data
@api.model
def _initialize_partner(self, ag_pb_data, acc_id, prt_id):
ag_pb_data[acc_id][prt_id] = {}
ag_pb_data[acc_id][prt_id]["id"] = acc_id
ag_pb_data[acc_id][prt_id]["residual"] = 0.0
ag_pb_data[acc_id][prt_id]["current"] = 0.0
ag_pb_data[acc_id][prt_id]["30_days"] = 0.0
ag_pb_data[acc_id][prt_id]["60_days"] = 0.0
ag_pb_data[acc_id][prt_id]["90_days"] = 0.0
ag_pb_data[acc_id][prt_id]["120_days"] = 0.0
ag_pb_data[acc_id][prt_id]["older"] = 0.0
ag_pb_data[acc_id][prt_id]["move_lines"] = []
return ag_pb_data
@api.model
def _calculate_amounts(
self, ag_pb_data, acc_id, prt_id, residual, due_date, date_at_object
):
ag_pb_data[acc_id]["residual"] += residual
ag_pb_data[acc_id][prt_id]["residual"] += residual
today = date_at_object
if not due_date or today <= due_date:
ag_pb_data[acc_id]["current"] += residual
ag_pb_data[acc_id][prt_id]["current"] += residual
elif today <= due_date + timedelta(days=30):
ag_pb_data[acc_id]["30_days"] += residual
ag_pb_data[acc_id][prt_id]["30_days"] += residual
elif today <= due_date + timedelta(days=60):
ag_pb_data[acc_id]["60_days"] += residual
ag_pb_data[acc_id][prt_id]["60_days"] += residual
elif today <= due_date + timedelta(days=90):
ag_pb_data[acc_id]["90_days"] += residual
ag_pb_data[acc_id][prt_id]["90_days"] += residual
elif today <= due_date + timedelta(days=120):
ag_pb_data[acc_id]["120_days"] += residual
ag_pb_data[acc_id][prt_id]["120_days"] += residual
else:
ag_pb_data[acc_id]["older"] += residual
ag_pb_data[acc_id][prt_id]["older"] += residual
return ag_pb_data
def _get_account_partial_reconciled(self, company_id, date_at_object):
domain = [("max_date", ">", date_at_object), ("company_id", "=", company_id)]
fields = [
"debit_move_id",
"credit_move_id",
"amount",
"debit_amount_currency",
"credit_amount_currency",
]
accounts_partial_reconcile = self.env["account.partial.reconcile"].search_read(
domain=domain, fields=fields
)
debit_amount = {}
debit_amount_currency = {}
credit_amount = {}
credit_amount_currency = {}
for account_partial_reconcile_data in accounts_partial_reconcile:
debit_move_id = account_partial_reconcile_data["debit_move_id"][0]
credit_move_id = account_partial_reconcile_data["credit_move_id"][0]
if debit_move_id not in debit_amount.keys():
debit_amount[debit_move_id] = 0.0
debit_amount_currency[debit_move_id] = 0.0
debit_amount_currency[debit_move_id] += account_partial_reconcile_data[
"debit_amount_currency"
]
debit_amount[debit_move_id] += account_partial_reconcile_data["amount"]
if credit_move_id not in credit_amount.keys():
credit_amount[credit_move_id] = 0.0
credit_amount_currency[credit_move_id] = 0.0
credit_amount[credit_move_id] += account_partial_reconcile_data["amount"]
credit_amount_currency[credit_move_id] += account_partial_reconcile_data[
"credit_amount_currency"
]
account_partial_reconcile_data.update(
{"debit_move_id": debit_move_id, "credit_move_id": credit_move_id}
)
return (
accounts_partial_reconcile,
debit_amount,
credit_amount,
debit_amount_currency,
credit_amount_currency,
)
def _get_move_lines_data(
self,
company_id,
account_ids,
partner_ids,
date_at_object,
date_from,
only_posted_moves,
show_move_line_details,
):
domain = self._get_move_lines_domain_not_reconciled(
company_id, account_ids, partner_ids, only_posted_moves, date_from
)
ml_fields = self._get_ml_fields()
line_model = self.env["account.move.line"]
move_lines = line_model.search_read(domain=domain, fields=ml_fields)
journals_ids = set()
partners_ids = set()
partners_data = {}
ag_pb_data = {}
if date_at_object < date.today():
(
acc_partial_rec,
debit_amount,
credit_amount,
debit_amount_currency,
credit_amount_currency,
) = self._get_account_partial_reconciled(company_id, date_at_object)
if acc_partial_rec:
ml_ids = list(map(operator.itemgetter("id"), move_lines))
debit_ids = list(
map(operator.itemgetter("debit_move_id"), acc_partial_rec)
)
credit_ids = list(
map(operator.itemgetter("credit_move_id"), acc_partial_rec)
)
move_lines = self._recalculate_move_lines(
move_lines,
debit_ids,
credit_ids,
debit_amount,
credit_amount,
ml_ids,
account_ids,
company_id,
partner_ids,
only_posted_moves,
debit_amount_currency,
credit_amount_currency,
)
move_lines = [
move_line
for move_line in move_lines
if move_line["date"] <= date_at_object
and not float_is_zero(move_line["amount_residual"], precision_digits=2)
]
for move_line in move_lines:
journals_ids.add(move_line["journal_id"][0])
acc_id = move_line["account_id"][0]
if move_line["partner_id"]:
prt_id = move_line["partner_id"][0]
prt_name = move_line["partner_id"][1]
else:
prt_id = 0
prt_name = ""
if prt_id not in partners_ids:
partners_data.update({prt_id: {"id": prt_id, "name": prt_name}})
partners_ids.add(prt_id)
if acc_id not in ag_pb_data.keys():
ag_pb_data = self._initialize_account(ag_pb_data, acc_id)
if prt_id not in ag_pb_data[acc_id]:
ag_pb_data = self._initialize_partner(ag_pb_data, acc_id, prt_id)
move_line_data = {}
if show_move_line_details:
if move_line["ref"] == move_line["name"]:
if move_line["ref"]:
ref_label = move_line["ref"]
else:
ref_label = ""
elif not move_line["ref"]:
ref_label = move_line["name"]
elif not move_line["name"]:
ref_label = move_line["ref"]
else:
ref_label = move_line["ref"] + str(" - ") + move_line["name"]
move_line_data.update(
{
"line_rec": line_model.browse(move_line["id"]),
"date": move_line["date"],
"entry": move_line["move_id"][1],
"jnl_id": move_line["journal_id"][0],
"acc_id": acc_id,
"partner": prt_name,
"ref_label": ref_label,
"due_date": move_line["date_maturity"],
"residual": move_line["amount_residual"],
}
)
ag_pb_data[acc_id][prt_id]["move_lines"].append(move_line_data)
ag_pb_data = self._calculate_amounts(
ag_pb_data,
acc_id,
prt_id,
move_line["amount_residual"],
move_line["date_maturity"],
date_at_object,
)
journals_data = self._get_journals_data(list(journals_ids))
accounts_data = self._get_accounts_data(ag_pb_data.keys())
return ag_pb_data, accounts_data, partners_data, journals_data
@api.model
def _compute_maturity_date(self, ml, date_at_object):
ml.update(
{
"current": 0.0,
"30_days": 0.0,
"60_days": 0.0,
"90_days": 0.0,
"120_days": 0.0,
"older": 0.0,
}
)
due_date = ml["due_date"]
amount = ml["residual"]
today = date_at_object
if not due_date or today <= due_date:
ml["current"] += amount
elif today <= due_date + timedelta(days=30):
ml["30_days"] += amount
elif today <= due_date + timedelta(days=60):
ml["60_days"] += amount
elif today <= due_date + timedelta(days=90):
ml["90_days"] += amount
elif today <= due_date + timedelta(days=120):
ml["120_days"] += amount
else:
ml["older"] += amount
def _create_account_list(
self,
ag_pb_data,
accounts_data,
partners_data,
journals_data,
show_move_line_details,
date_at_oject,
):
aged_partner_data = []
for account in accounts_data.values():
acc_id = account["id"]
account.update(
{
"residual": ag_pb_data[acc_id]["residual"],
"current": ag_pb_data[acc_id]["current"],
"30_days": ag_pb_data[acc_id]["30_days"],
"60_days": ag_pb_data[acc_id]["60_days"],
"90_days": ag_pb_data[acc_id]["90_days"],
"120_days": ag_pb_data[acc_id]["120_days"],
"older": ag_pb_data[acc_id]["older"],
"partners": [],
}
)
for prt_id in ag_pb_data[acc_id]:
if isinstance(prt_id, int):
partner = {
"name": partners_data[prt_id]["name"],
"residual": ag_pb_data[acc_id][prt_id]["residual"],
"current": ag_pb_data[acc_id][prt_id]["current"],
"30_days": ag_pb_data[acc_id][prt_id]["30_days"],
"60_days": ag_pb_data[acc_id][prt_id]["60_days"],
"90_days": ag_pb_data[acc_id][prt_id]["90_days"],
"120_days": ag_pb_data[acc_id][prt_id]["120_days"],
"older": ag_pb_data[acc_id][prt_id]["older"],
}
if show_move_line_details:
move_lines = []
for ml in ag_pb_data[acc_id][prt_id]["move_lines"]:
ml.update(
{
"journal": journals_data[ml["jnl_id"]]["code"],
"account": accounts_data[ml["acc_id"]]["code"],
}
)
self._compute_maturity_date(ml, date_at_oject)
move_lines.append(ml)
move_lines = sorted(move_lines, key=lambda k: (k["date"]))
partner.update({"move_lines": move_lines})
account["partners"].append(partner)
aged_partner_data.append(account)
return aged_partner_data
@api.model
def _calculate_percent(self, aged_partner_data):
for account in aged_partner_data:
if abs(account["residual"]) > 0.01:
total = account["residual"]
account.update(
{
"percent_current": abs(
round((account["current"] / total) * 100, 2)
),
"percent_30_days": abs(
round((account["30_days"] / total) * 100, 2)
),
"percent_60_days": abs(
round((account["60_days"] / total) * 100, 2)
),
"percent_90_days": abs(
round((account["90_days"] / total) * 100, 2)
),
"percent_120_days": abs(
round((account["120_days"] / total) * 100, 2)
),
"percent_older": abs(
round((account["older"] / total) * 100, 2)
),
}
)
else:
account.update(
{
"percent_current": 0.0,
"percent_30_days": 0.0,
"percent_60_days": 0.0,
"percent_90_days": 0.0,
"percent_120_days": 0.0,
"percent_older": 0.0,
}
)
return aged_partner_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"]
account_ids = data["account_ids"]
partner_ids = data["partner_ids"]
date_at = data["date_at"]
date_at_object = datetime.strptime(date_at, "%Y-%m-%d").date()
date_from = data["date_from"]
only_posted_moves = data["only_posted_moves"]
show_move_line_details = data["show_move_line_details"]
(
ag_pb_data,
accounts_data,
partners_data,
journals_data,
) = self._get_move_lines_data(
company_id,
account_ids,
partner_ids,
date_at_object,
date_from,
only_posted_moves,
show_move_line_details,
)
aged_partner_data = self._create_account_list(
ag_pb_data,
accounts_data,
partners_data,
journals_data,
show_move_line_details,
date_at_object,
)
aged_partner_data = self._calculate_percent(aged_partner_data)
return {
"doc_ids": [wizard_id],
"doc_model": "open.items.report.wizard",
"docs": self.env["open.items.report.wizard"].browse(wizard_id),
"company_name": company.display_name,
"currency_name": company.currency_id.name,
"date_at": date_at,
"only_posted_moves": only_posted_moves,
"aged_partner_balance": aged_partner_data,
"show_move_lines_details": show_move_line_details,
}
def _get_ml_fields(self):
return self.COMMON_ML_FIELDS + [
"amount_residual",
"reconciled",
"date_maturity",
]
| 40.879397
| 16,270
|
899
|
py
|
PYTHON
|
15.0
|
import setuptools
with open('VERSION.txt', 'r') as f:
version = f.read().strip()
setuptools.setup(
name="odoo-addons-oca-account-financial-reporting",
description="Meta package for oca-account-financial-reporting Odoo addons",
version=version,
install_requires=[
'odoo-addon-account_financial_report>=15.0dev,<15.1dev',
'odoo-addon-account_purchase_stock_report_non_billed>=15.0dev,<15.1dev',
'odoo-addon-account_sale_stock_report_non_billed>=15.0dev,<15.1dev',
'odoo-addon-account_tax_balance>=15.0dev,<15.1dev',
'odoo-addon-mis_builder_cash_flow>=15.0dev,<15.1dev',
'odoo-addon-mis_template_financial_report>=15.0dev,<15.1dev',
'odoo-addon-partner_statement>=15.0dev,<15.1dev',
],
classifiers=[
'Programming Language :: Python',
'Framework :: Odoo',
'Framework :: Odoo :: 15.0',
]
)
| 37.458333
| 899
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
994
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 ForgeFlow, S.L. (http://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Partner Statement",
"version": "15.0.1.0.1",
"category": "Accounting & Finance",
"summary": "OCA Financial Reports",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-financial-reporting",
"license": "AGPL-3",
"depends": ["account", "report_xlsx", "report_xlsx_helper"],
"data": [
"security/ir.model.access.csv",
"security/statement_security.xml",
"views/activity_statement.xml",
"views/outstanding_statement.xml",
"views/aging_buckets.xml",
"views/res_config_settings.xml",
"wizard/statement_wizard.xml",
],
"assets": {
"web.report_assets_common": [
"/partner_statement/static/src/scss/layout_statement.scss",
],
},
"installable": True,
"application": False,
}
| 34.275862
| 994
|
4,771
|
py
|
PYTHON
|
15.0
|
# 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 date
from odoo import fields
from odoo.tests.common import TransactionCase
class TestActivityStatement(TransactionCase):
"""Tests for Activity Statement."""
def setUp(self):
super().setUp()
self.res_users_model = self.env["res.users"]
self.company = self.env.ref("base.main_company")
self.company.external_report_layout_id = self.env.ref(
"web.external_layout_standard"
)
self.partner1 = self.env.ref("base.res_partner_1")
self.partner2 = self.env.ref("base.res_partner_2")
self.g_account_user = self.env.ref("account.group_account_user")
self.user = self._create_user("user_1", [self.g_account_user], self.company).id
self.statement_model = self.env["report.partner_statement.activity_statement"]
self.wiz = self.env["activity.statement.wizard"]
self.report_name = "partner_statement.activity_statement"
self.report_name_xlsx = "p_s.report_activity_statement_xlsx"
self.report_title = "Activity Statement"
self.today = fields.Date.context_today(self.wiz)
def _create_user(self, login, groups, company):
group_ids = [group.id for group in groups]
user = self.res_users_model.create(
{
"name": login,
"login": login,
"email": "example@yourcompany.com",
"company_id": company.id,
"company_ids": [(4, company.id)],
"groups_id": [(6, 0, group_ids)],
}
)
return user
def test_customer_activity_statement(self):
wiz_id = self.wiz.with_context(
active_ids=[self.partner1.id, self.partner2.id]
).create({})
wiz_id.aging_type = "months"
wiz_id.show_aging_buckets = False
statement = wiz_id.button_export_pdf()
self.assertDictEqual(
statement,
{
**{
"type": "ir.actions.report",
"report_name": self.report_name,
"report_type": "qweb-pdf",
},
**statement,
},
"There was an error and the PDF report was not generated.",
)
statement_xlsx = wiz_id.button_export_xlsx()
self.assertDictEqual(
statement_xlsx,
{
**{
"type": "ir.actions.report",
"report_name": self.report_name_xlsx,
"report_type": "xlsx",
},
**statement_xlsx,
},
"There was an error and the PDF report was not generated.",
)
data = wiz_id._prepare_statement()
docids = data["partner_ids"]
report = self.statement_model._get_report_values(docids, data)
self.assertIsInstance(
report, dict, "There was an error while compiling the report."
)
self.assertIn(
"bucket_labels", report, "There was an error while compiling the report."
)
def test_customer_activity_report_no_wizard(self):
docids = [self.partner1.id, self.partner2.id]
report = self.statement_model._get_report_values(docids, False)
self.assertIsInstance(
report, dict, "There was an error while compiling the report."
)
self.assertIn(
"bucket_labels", report, "There was an error while compiling the report."
)
def test_date_formatting(self):
date_fmt = "%d/%m/%Y"
test_date = date(2018, 9, 30)
res = self.statement_model._format_date_to_partner_lang(test_date, date_fmt)
self.assertEqual(res, "30/09/2018")
test_date_string = "2018-09-30"
res = self.statement_model._format_date_to_partner_lang(
test_date_string, date_fmt
)
self.assertEqual(res, "30/09/2018")
def test_onchange_aging_type(self):
"""Test that partner data is filled accordingly"""
wiz_id = self.wiz.with_context(
active_ids=[self.partner1.id, self.partner2.id]
).new()
wiz_id.aging_type = "months"
wiz_id.onchange_aging_type()
self.assertEqual(wiz_id.date_end.month, wiz_id.date_start.month)
self.assertTrue(wiz_id.date_end.day > wiz_id.date_start.day)
self.assertTrue(wiz_id.date_end < self.today)
wiz_id.aging_type = "days"
wiz_id.onchange_aging_type()
self.assertEqual((wiz_id.date_end - wiz_id.date_start).days, 30)
self.assertTrue(wiz_id.date_end == self.today)
| 35.87218
| 4,771
|
1,296
|
py
|
PYTHON
|
15.0
|
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo.tests.common import TransactionCase
class TestResConfigSettings(TransactionCase):
def setUp(self):
super().setUp()
self.config = self.env["res.config.settings"]
self.cr.execute(
"SELECT uid FROM res_groups_users_rel "
"WHERE gid IN (SELECT res_id FROM ir_model_data "
" WHERE module='account' AND name='group_account_invoice') "
"ORDER BY uid DESC LIMIT 1"
)
self.account_user = self.cr.fetchone()[0]
self.user_obj = self.env["res.users"].with_user(self.account_user)
def test_groups(self):
conf = self.config.create(
{
"default_aging_type": "months",
"group_activity_statement": True,
"group_outstanding_statement": False,
}
)
conf.set_values()
self.assertFalse(
self.user_obj._has_group("partner_statement.group_outstanding_statement")
)
self.assertTrue(
self.user_obj._has_group("partner_statement.group_activity_statement")
)
res = self.env["ir.default"].get("activity.statement.wizard", "aging_type")
self.assertEqual(res, "months")
| 37.028571
| 1,296
|
3,531
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 ForgeFlow, S.L. (https://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo.tests.common import TransactionCase
class TestOutstandingStatement(TransactionCase):
"""Tests for Outstanding Statement."""
def setUp(self):
super().setUp()
self.res_users_model = self.env["res.users"]
self.company = self.env.ref("base.main_company")
self.company.external_report_layout_id = self.env.ref(
"web.external_layout_standard"
)
self.partner1 = self.env.ref("base.res_partner_2")
self.partner2 = self.env.ref("base.res_partner_3")
self.g_account_user = self.env.ref("account.group_account_user")
self.user = self._create_user("user_1", [self.g_account_user], self.company).id
self.statement_model = self.env[
"report.partner_statement.outstanding_statement"
]
self.wiz = self.env["outstanding.statement.wizard"]
self.report_name = "partner_statement.outstanding_statement"
self.report_name_xlsx = "p_s.report_outstanding_statement_xlsx"
self.report_title = "Outstanding Statement"
def _create_user(self, login, groups, company):
group_ids = [group.id for group in groups]
user = self.res_users_model.create(
{
"name": login,
"login": login,
"email": "example@yourcompany.com",
"company_id": company.id,
"company_ids": [(4, company.id)],
"groups_id": [(6, 0, group_ids)],
}
)
return user
def test_customer_outstanding_statement(self):
wiz_id = self.wiz.with_context(
active_ids=[self.partner1.id, self.partner2.id]
).create({})
wiz_id.aging_type = "months"
statement = wiz_id.button_export_pdf()
self.assertDictEqual(
statement,
{
**{
"type": "ir.actions.report",
"report_name": self.report_name,
"report_type": "qweb-pdf",
},
**statement,
},
"There was an error and the PDF report was not generated.",
)
statement_xlsx = wiz_id.button_export_xlsx()
self.assertDictEqual(
statement_xlsx,
{
**{
"type": "ir.actions.report",
"report_name": self.report_name_xlsx,
"report_type": "xlsx",
},
**statement_xlsx,
},
"There was an error and the PDF report was not generated.",
)
data = wiz_id._prepare_statement()
docids = data["partner_ids"]
report = self.statement_model._get_report_values(docids, data)
self.assertIsInstance(
report, dict, "There was an error while compiling the report."
)
self.assertIn(
"bucket_labels", report, "There was an error while compiling the report."
)
def test_customer_outstanding_report_no_wizard(self):
docids = [self.partner1.id]
report = self.statement_model._get_report_values(docids, False)
self.assertIsInstance(
report, dict, "There was an error while compiling the report."
)
self.assertIn(
"bucket_labels", report, "There was an error while compiling the report."
)
| 34.960396
| 3,531
|
1,063
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 ForgeFlow, S.L. (http://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import models
class OutstandingStatementWizard(models.TransientModel):
"""Outstanding Statement wizard."""
_name = "outstanding.statement.wizard"
_inherit = "statement.common.wizard"
_description = "Outstanding Statement Wizard"
def _print_report(self, report_type):
self.ensure_one()
data = self._prepare_statement()
if report_type == "xlsx":
report_name = "p_s.report_outstanding_statement_xlsx"
else:
report_name = "partner_statement.outstanding_statement"
return (
self.env["ir.actions.report"]
.search(
[("report_name", "=", report_name), ("report_type", "=", report_type)],
limit=1,
)
.report_action(self, data=data)
)
def _export(self, report_type):
"""Default export is PDF."""
return self._print_report(report_type)
| 33.21875
| 1,063
|
2,077
|
py
|
PYTHON
|
15.0
|
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
group_activity_statement = fields.Boolean(
"Enable OCA Activity Statements",
group="account.group_account_invoice",
implied_group="partner_statement.group_activity_statement",
)
default_aging_type = fields.Selection(
[("days", "Age by Days"), ("months", "Age by Months")],
string="Aging Method",
required=True,
default="days",
default_model="statement.common.wizard",
)
default_show_aging_buckets = fields.Boolean(
string="Show Aging Buckets", default_model="statement.common.wizard"
)
default_filter_partners_non_due = fields.Boolean(
string="Exclude partners with no due entries",
default_model="statement.common.wizard",
)
default_filter_negative_balances = fields.Boolean(
"Exclude Negative Balances", default_model="statement.common.wizard"
)
group_outstanding_statement = fields.Boolean(
"Enable OCA Outstanding Statements",
group="account.group_account_invoice",
implied_group="partner_statement.group_outstanding_statement",
)
def set_values(self):
self = self.with_context(active_test=False)
# default values fields
IrDefault = self.env["ir.default"].sudo()
for name, field in self._fields.items():
if (
name.startswith("default_")
and field.default_model == "statement.common.wizard"
):
if isinstance(self[name], models.BaseModel):
if self._fields[name].type == "many2one":
value = self[name].id
else:
value = self[name].ids
else:
value = self[name]
IrDefault.set("activity.statement.wizard", name[8:], value)
IrDefault.set("outstanding.statement.wizard", name[8:], value)
return super().set_values()
| 35.810345
| 2,077
|
2,526
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Graeme Gellatly
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models
class StatementCommon(models.AbstractModel):
_name = "statement.common.wizard"
_description = "Statement Reports Common Wizard"
name = fields.Char()
company_id = fields.Many2one(
comodel_name="res.company",
default=lambda self: self.env.company,
string="Company",
required=True,
)
date_end = fields.Date(required=True, default=fields.Date.context_today)
show_aging_buckets = fields.Boolean(default=True)
number_partner_ids = fields.Integer(
default=lambda self: len(self._context["active_ids"])
)
filter_partners_non_due = fields.Boolean(
string="Don't show partners with no due entries", default=True
)
filter_negative_balances = fields.Boolean("Exclude Negative Balances", default=True)
aging_type = fields.Selection(
[("days", "Age by Days"), ("months", "Age by Months")],
string="Aging Method",
default="days",
required=True,
)
account_type = fields.Selection(
[("receivable", "Receivable"), ("payable", "Payable")],
default="receivable",
)
@api.onchange("aging_type")
def onchange_aging_type(self):
if self.aging_type == "months":
self.date_end = fields.Date.context_today(self).replace(
day=1
) - relativedelta(days=1)
else:
self.date_end = fields.Date.context_today(self)
def _prepare_statement(self):
self.ensure_one()
return {
"date_end": self.date_end,
"company_id": self.company_id.id,
"partner_ids": self._context["active_ids"],
"show_aging_buckets": self.show_aging_buckets,
"filter_non_due_partners": self.filter_partners_non_due,
"account_type": self.account_type,
"aging_type": self.aging_type,
"filter_negative_balances": self.filter_negative_balances,
}
def button_export_html(self):
self.ensure_one()
report_type = "qweb-html"
return self._export(report_type)
def button_export_pdf(self):
self.ensure_one()
report_type = "qweb-pdf"
return self._export(report_type)
def button_export_xlsx(self):
self.ensure_one()
report_type = "xlsx"
return self._export(report_type)
| 32.384615
| 2,526
|
1,812
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 ForgeFlow, S.L. (http://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models
class ActivityStatementWizard(models.TransientModel):
"""Activity Statement wizard."""
_inherit = "statement.common.wizard"
_name = "activity.statement.wizard"
_description = "Activity Statement Wizard"
@api.model
def _get_date_start(self):
return (
fields.Date.context_today(self).replace(day=1) - relativedelta(days=1)
).replace(day=1)
date_start = fields.Date(required=True, default=_get_date_start)
@api.onchange("aging_type")
def onchange_aging_type(self):
res = super().onchange_aging_type()
if self.aging_type == "months":
self.date_start = self.date_end.replace(day=1)
else:
self.date_start = self.date_end - relativedelta(days=30)
return res
def _prepare_statement(self):
res = super()._prepare_statement()
res.update({"date_start": self.date_start})
return res
def _print_report(self, report_type):
self.ensure_one()
data = self._prepare_statement()
if report_type == "xlsx":
report_name = "p_s.report_activity_statement_xlsx"
else:
report_name = "partner_statement.activity_statement"
return (
self.env["ir.actions.report"]
.search(
[("report_name", "=", report_name), ("report_type", "=", report_type)],
limit=1,
)
.report_action(self, data=data)
)
def _export(self, report_type):
"""Default export is PDF."""
return self._print_report(report_type)
| 32.357143
| 1,812
|
6,305
|
py
|
PYTHON
|
15.0
|
# 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 _display_lines_sql_q1(self, partners, date_end, account_type):
partners = tuple(partners)
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_account_type at ON (at.id = aa.user_type_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 at.type = %(account_type)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')
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_lines_sql_q2(self):
return str(
self._cr.mogrify(
"""
SELECT Q1.partner_id, Q1.currency_id, Q1.move_id,
Q1.date, Q1.date_maturity, Q1.debit, Q1.credit,
Q1.name, Q1.ref, Q1.blocked, Q1.company_id,
CASE WHEN Q1.currency_id is not null
THEN Q1.open_amount_currency
ELSE Q1.open_amount
END as open_amount
FROM Q1
""",
locals(),
),
"utf-8",
)
def _display_lines_sql_q3(self, company_id):
return str(
self._cr.mogrify(
"""
SELECT Q2.partner_id, Q2.move_id, Q2.date, Q2.date_maturity,
Q2.name, Q2.ref, Q2.debit, Q2.credit,
Q2.debit-Q2.credit AS amount, blocked,
COALESCE(Q2.currency_id, c.currency_id) AS currency_id,
Q2.open_amount
FROM Q2
JOIN res_company c ON (c.id = Q2.company_id)
WHERE c.id = %(company_id)s AND Q2.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, name, ref, blocked
FROM Q3
ORDER BY date, date_maturity, move_id"""
% (
self._display_lines_sql_q1(partners, date_end, account_type),
self._display_lines_sql_q2(),
self._display_lines_sql_q3(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)
| 39.905063
| 6,305
|
17,411
|
py
|
PYTHON
|
15.0
|
# 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 _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 _show_buckets_sql_q1(self, partners, date_end, account_type):
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)
JOIN account_account_type at ON (at.id = aa.user_type_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 at.type = %(account_type)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')
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):
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 (
{
"lines": [],
"buckets": [],
"balance_forward": balance_forward,
"amount_due": balance_forward,
},
currencies,
)
def _add_currency_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"]
aging_type = data["aging_type"]
today = fields.Date.today()
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
lines = self._get_account_display_lines(
company_id, partner_ids, date_start, date_end, account_type
)
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 = {}
# organise 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)),
"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"]
)
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
)
line_currency = currency_dict[line["currency_id"]]
if not line["blocked"]:
line_currency["amount_due"] += line[amount_field]
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["lines"].extend(
self._add_currency_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
)
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,
"bucket_labels": bucket_labels,
"get_inv_addr": self._get_invoice_address,
}
| 39.213964
| 17,411
|
7,222
|
py
|
PYTHON
|
15.0
|
# 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
class ActivityStatement(models.AbstractModel):
"""Model of Activity Statement"""
_inherit = "statement.common"
_name = "report.partner_statement.activity_statement"
_description = "Partner Activity Statement"
def _initial_balance_sql_q1(self, partners, date_start, account_type):
return str(
self._cr.mogrify(
"""
SELECT l.partner_id, 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
FROM account_move_line l
JOIN account_account aa ON (aa.id = l.account_id)
JOIN account_account_type at ON (at.id = aa.user_type_id)
JOIN account_move m ON (l.move_id = m.id)
WHERE l.partner_id IN %(partners)s
AND at.type = %(account_type)s
AND l.date < %(date_start)s AND not l.blocked
AND m.state IN ('posted')
GROUP BY l.partner_id, l.currency_id, l.company_id
""",
locals(),
),
"utf-8",
)
def _initial_balance_sql_q2(self, company_id):
return str(
self._cr.mogrify(
"""
SELECT Q1.partner_id, debit-credit AS balance,
COALESCE(Q1.currency_id, c.currency_id) AS currency_id
FROM Q1
JOIN res_company c ON (c.id = Q1.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)
SELECT partner_id, currency_id, balance
FROM Q2"""
% (
self._initial_balance_sql_q1(partners, date_start, account_type),
self._initial_balance_sql_q2(company_id),
)
)
for row in self.env.cr.dictfetchall():
balance_start[row.pop("partner_id")].append(row)
return balance_start
def _display_lines_sql_q1(self, partners, date_start, date_end, account_type):
return str(
self._cr.mogrify(
"""
SELECT m.name AS move_id, l.partner_id, l.date,
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 ('sale', 'purchase') AND l.name IS NULL
THEN m.ref
WHEN (aj.type in ('bank', 'cash'))
THEN 'Payment'
ELSE ''
END as 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_account_type at ON (at.id = aa.user_type_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 at.type = %(account_type)s
AND %(date_start)s <= l.date
AND l.date <= %(date_end)s
AND m.state IN ('posted')
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
WHEN (aj.type IN ('sale', 'purchase')) AND l.name IS NOT NULL
THEN l.ref
WHEN aj.type IN ('sale', 'purchase') AND l.name IS NULL
THEN m.ref
WHEN (aj.type in ('bank', 'cash'))
THEN 'Payment'
ELSE ''
END,
l.blocked, l.currency_id, l.company_id
""",
locals(),
),
"utf-8",
)
def _display_lines_sql_q2(self, company_id):
return str(
self._cr.mogrify(
"""
SELECT Q1.partner_id, Q1.move_id, Q1.date, Q1.date_maturity,
Q1.name, Q1.ref, Q1.debit, Q1.credit,
Q1.debit-Q1.credit as amount, Q1.blocked,
COALESCE(Q1.currency_id, c.currency_id) AS currency_id
FROM Q1
JOIN res_company c ON (c.id = Q1.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, name, ref, debit,
credit, amount, blocked, currency_id
FROM Q2
ORDER BY date, date_maturity, move_id"""
% (
self._display_lines_sql_q1(
partners, date_start, date_end, account_type
),
self._display_lines_sql_q2(company_id),
)
)
for row in self.env.cr.dictfetchall():
res[row.pop("partner_id")].append(row)
return res
@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)
| 37.419689
| 7,222
|
11,112
|
py
|
PYTHON
|
15.0
|
# Author: Christopher Ormaza
# Copyright 2021 ForgeFlow S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import _, fields, models
from odoo.addons.report_xlsx_helper.report.report_xlsx_format import FORMATS
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 _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 = _(
"%(payable)sStatement between %(start)s and %(end)s in %(currency)s"
) % {
"payable": account_type == "payable" and _("Supplier ") or "",
"start": partner_data.get("start"),
"end": partner_data.get("end"),
"currency": currency.display_name,
}
sheet.merge_range(
row_pos, 0, row_pos, 6, statement_header, FORMATS["format_right_bold"]
)
row_pos += 1
sheet.write(
row_pos, 0, _("Reference Number"), FORMATS["format_theader_yellow_center"]
)
sheet.write(row_pos, 1, _("Date"), FORMATS["format_theader_yellow_center"])
sheet.merge_range(
row_pos,
2,
row_pos,
4,
_("Description"),
FORMATS["format_theader_yellow_center"],
)
sheet.write(
row_pos, 5, _("Open Amount"), FORMATS["format_theader_yellow_center"]
)
sheet.write(row_pos, 6, _("Balance"), FORMATS["format_theader_yellow_center"])
row_pos += 1
sheet.write(
row_pos, 1, partner_data.get("start"), FORMATS["format_tcell_date_left"]
)
sheet.merge_range(
row_pos, 2, row_pos, 4, _("Balance Forward"), FORMATS["format_tcell_left"]
)
sheet.write(
row_pos,
6,
currency_data.get("balance_forward"),
FORMATS["current_money_format"],
)
for line in currency_data.get("lines"):
row_pos += 1
name_to_show = (
line.get("name", "") == "/" or not line.get("name", "")
) and line.get("ref", "")
if 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", "")
sheet.write(
row_pos, 0, line.get("move_id", ""), FORMATS["format_tcell_left"]
)
sheet.write(
row_pos, 1, line.get("date", ""), FORMATS["format_tcell_date_left"]
)
sheet.merge_range(
row_pos, 2, row_pos, 4, name_to_show, FORMATS["format_distributed"]
)
sheet.write(
row_pos, 5, line.get("amount", ""), FORMATS["current_money_format"]
)
sheet.write(
row_pos, 6, line.get("balance", ""), FORMATS["current_money_format"]
)
row_pos += 1
sheet.write(
row_pos, 1, partner_data.get("end"), FORMATS["format_tcell_date_left"]
)
sheet.merge_range(
row_pos, 2, row_pos, 4, _("Ending Balance"), FORMATS["format_tcell_left"]
)
sheet.write(
row_pos, 6, currency_data.get("amount_due"), FORMATS["current_money_format"]
)
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):
for i in range(7):
sheet.set_column(0, i, 20)
def generate_xlsx_report(self, workbook, data, objects):
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,
fields.Date.from_string(data.get("date_end")),
FORMATS["format_date_left"],
)
self._size_columns(sheet)
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}
)
row_pos = self._write_currency_lines(
row_pos, sheet, partner, currency, data
)
row_pos = self._write_currency_buckets(
row_pos, sheet, partner, currency, data
)
| 37.795918
| 11,112
|
10,935
|
py
|
PYTHON
|
15.0
|
# Author: Christopher Ormaza
# Copyright 2021 ForgeFlow S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import _, fields, models
from odoo.addons.report_xlsx_helper.report.report_xlsx_format import FORMATS
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 _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 = _("%(payable)sStatement up to %(end)s in %(currency)s") % {
"payable": account_type == "payable" and _("Supplier ") or "",
"end": partner_data.get("end"),
"currency": currency.display_name,
}
sheet.merge_range(
row_pos, 0, row_pos, 6, statement_header, FORMATS["format_right_bold"]
)
row_pos += 1
sheet.write(
row_pos, 0, _("Reference Number"), FORMATS["format_theader_yellow_center"]
)
sheet.write(row_pos, 1, _("Date"), FORMATS["format_theader_yellow_center"])
sheet.write(row_pos, 2, _("Due Date"), FORMATS["format_theader_yellow_center"])
sheet.write(
row_pos, 3, _("Description"), FORMATS["format_theader_yellow_center"]
)
sheet.write(row_pos, 4, _("Original"), FORMATS["format_theader_yellow_center"])
sheet.write(
row_pos, 5, _("Open Amount"), FORMATS["format_theader_yellow_center"]
)
sheet.write(row_pos, 6, _("Balance"), FORMATS["format_theader_yellow_center"])
for line in currency_data.get("lines"):
row_pos += 1
name_to_show = (
line.get("name", "") == "/" or not line.get("name", "")
) and line.get("ref", "")
if 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", "")
sheet.write(
row_pos, 0, line.get("move_id", ""), FORMATS["format_tcell_left"]
)
sheet.write(
row_pos, 1, line.get("date", ""), FORMATS["format_tcell_date_left"]
)
sheet.write(
row_pos,
2,
line.get("date_maturity", ""),
FORMATS["format_tcell_date_left"],
)
sheet.write(row_pos, 3, name_to_show, FORMATS["format_distributed"])
sheet.write(
row_pos, 4, line.get("amount", ""), FORMATS["current_money_format"]
)
sheet.write(
row_pos, 5, line.get("open_amount", ""), FORMATS["current_money_format"]
)
sheet.write(
row_pos, 6, line.get("balance", ""), FORMATS["current_money_format"]
)
row_pos += 1
sheet.write(
row_pos, 1, partner_data.get("end"), FORMATS["format_tcell_date_left"]
)
sheet.merge_range(
row_pos, 2, row_pos, 4, _("Ending Balance"), FORMATS["format_tcell_left"]
)
sheet.write(
row_pos, 6, currency_data.get("amount_due"), FORMATS["current_money_format"]
)
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):
for i in range(7):
sheet.set_column(0, i, 20)
def generate_xlsx_report(self, workbook, data, objects):
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,
fields.Date.from_string(data.get("date_end")),
FORMATS["format_date_left"],
)
self._size_columns(sheet)
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}
)
row_pos = self._write_currency_lines(
row_pos, sheet, partner, currency, data
)
row_pos = self._write_currency_buckets(
row_pos, sheet, partner, currency, data
)
| 38.639576
| 10,935
|
1,044
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Hunki Enterprises BV
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Profit & Loss / Balance sheet MIS templates",
"version": "15.0.1.0.1",
"license": "AGPL-3",
"author": "Hunki Enterprises BV,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-financial-reporting",
"category": "Localization",
"depends": ["mis_builder"],
"data": [
"data/mis_report_style.xml",
"data/mis_report.xml",
"data/mis_report_kpi.xml",
"data/mis_report_subreport.xml",
"views/mis_report_instance_views.xml",
"views/templates.xml",
],
"assets": {
"web.assets_backend": [
"mis_template_financial_report/static/src/css/mis_template_financial_report.css",
],
"web.report_assets_common": [
"mis_template_financial_report/static/src/css/report.css"
],
},
"qweb": ["static/src/xml/mis_template_financial_report.xml"],
"maintainers": ["hbrunn"],
}
| 34.8
| 1,044
|
784
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Hunki Enterprises BV
# Copyright 2021 Opener B.V. <stefan@opener.am>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.addons.mis_builder.tests.test_mis_report_instance import TestMisReportInstance
class TestMisTemplateFinancialReport(TestMisReportInstance):
def test_mis_template_financial_report(self):
instance = self.env["mis.report.instance"].create(
{
"name": "Balance Sheet",
"report_id": self.env.ref("mis_template_financial_report.report_bs").id,
}
)
self.assertTrue(instance.allow_horizontal)
instance.horizontal = True
result_dict = instance.compute()
self.assertEqual(len(result_dict.get("horizontal_matrices", [])), 2)
| 43.555556
| 784
|
2,775
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Hunki Enterprises BV
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import copy
from collections import OrderedDict
from odoo import api, fields, models
class MisReportInstance(models.Model):
_inherit = "mis.report.instance"
allow_horizontal = fields.Boolean(compute="_compute_allow_horizontal")
horizontal = fields.Boolean()
@api.depends("report_id")
def _compute_allow_horizontal(self):
"""Indicate that the instance supports horizontal rendering."""
for instance in self:
instance.allow_horizontal = set(
instance.report_id.get_external_id().values()
) & {
"mis_template_financial_report.report_bs",
"mis_template_financial_report.report_pl",
}
def compute(self):
if not self.horizontal:
return super().compute()
full_matrix = self._compute_matrix()
matrices = self._compute_horizontal_matrices(full_matrix)
result = full_matrix.as_dict()
result["horizontal_matrices"] = [
extra_matrix.as_dict() for extra_matrix in matrices
]
return result
def _compute_horizontal_matrices(self, matrix=None):
"""Compute the matrix (if not passed) and return the split versions"""
return self._split_matrix(
matrix or self._compute_matrix(),
[
(
self.env.ref("mis_template_financial_report.kpi_profit"),
self.env.ref("mis_template_financial_report.kpi_pl_to_report"),
self.env.ref("mis_template_financial_report.kpi_assets"),
)
],
)
def _split_matrix(self, original_matrix, kpi_defs=None, keep_remaining=True):
"""Split a matrix by duplicating it as shallowly as possible and removing
rows according to kpi_defs
KPIs not listed there will end up together in the last matrix if
`keep_remaining` is set.
:param kpi_defs: [(kpi_first_matrix1, ...), (kpi_second_matrix1, ...)]
:return: list of KpiMatrix
"""
result = []
remaining_rows = original_matrix._kpi_rows.copy()
for kpis in kpi_defs:
matrix = copy.copy(original_matrix)
matrix._kpi_rows = OrderedDict(
[
(kpi, remaining_rows.pop(kpi))
for kpi in kpis
if kpi in remaining_rows
]
)
result.append(matrix)
if remaining_rows and keep_remaining:
matrix = copy.copy(original_matrix)
matrix._kpi_rows = remaining_rows
result.append(matrix)
return result
| 33.433735
| 2,775
|
804
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 ADHOC SA
# Copyright 2021 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "MIS Builder Cash Flow",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"author": "ADHOC SA, " "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-financial-reporting",
"depends": ["mis_builder"],
"data": [
"security/mis_cash_flow_security.xml",
"report/mis_cash_flow_views.xml",
"views/mis_cash_flow_forecast_line_views.xml",
"views/account_account_views.xml",
"data/mis_report_style.xml",
"data/mis_report.xml",
"data/mis_report_instance.xml",
],
"installable": True,
"maintainers": ["jjscarafia"],
"development_status": "Beta",
}
| 33.5
| 804
|
5,487
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from datetime import timedelta
from odoo.exceptions import ValidationError
from odoo.fields import Date
from odoo.tests.common import TransactionCase, tagged
from odoo.tools import mute_logger
@tagged("post_install", "-at_install")
class TestCashFlow(TransactionCase):
def setUp(self):
super().setUp()
self.company = self.env["res.company"].create({"name": "TEST"})
self.report = self.browse_ref("mis_builder_cash_flow.mis_instance_cash_flow")
self.report.company_id = self.company
self.bank_account = self.env["account.account"].create(
{
"company_id": self.company.id,
"code": "TEST1",
"name": "Bank account 01",
"user_type_id": self.browse_ref(
"account.data_account_type_liquidity"
).id,
}
)
self.bank_account_hide = self.env["account.account"].create(
{
"company_id": self.company.id,
"code": "TEST2",
"name": "Bank account 02",
"user_type_id": self.browse_ref(
"account.data_account_type_liquidity"
).id,
"hide_in_cash_flow": True,
}
)
self.account = self.env["account.account"].create(
{
"company_id": self.company.id,
"code": "TEST3",
"name": "Account",
"user_type_id": self.browse_ref(
"account.data_account_type_receivable"
).id,
"reconcile": True,
}
)
self.journal = self.env["account.journal"].create(
{
"name": "Journal",
"code": "JOURNAL",
"company_id": self.company.id,
"type": "general",
}
)
def test_company_constrain(self):
with self.assertRaises(ValidationError):
self.env["mis.cash_flow.forecast_line"].create(
{"account_id": self.account.id, "date": Date.today(), "balance": 1000}
)
def test_report_instance(self):
self.check_matrix()
move = self.env["account.move"].create(
{
"name": "Move",
"journal_id": self.journal.id,
"company_id": self.company.id,
"move_type": "entry",
"line_ids": [
(
0,
0,
{
"account_id": self.bank_account.id,
"debit": 1500,
"credit": 0,
"company_id": self.company.id,
},
),
(
0,
0,
{
"account_id": self.bank_account_hide.id,
"debit": 500,
"credit": 0,
"company_id": self.company.id,
},
),
(
0,
0,
{
"account_id": self.account.id,
"debit": 0,
"credit": 2000,
"company_id": self.company.id,
},
),
],
}
)
move._post()
self.check_matrix(
args=[
("liquidity", "Current", 1500),
("balance", "Current", 1500),
("in_receivable", "Current", -2000),
],
ignore_rows=["balance", "period_balance", "in_total"],
)
date = Date.today() + timedelta(weeks=8)
self.env["mis.cash_flow.forecast_line"].create(
{
"account_id": self.account.id,
"date": date,
"balance": 1000,
"company_id": self.company.id,
}
)
self.check_matrix(
[
("liquidity", "Current", 1500),
("balance", "Current", 1500),
("in_receivable", "Current", -2000),
("in_forecast", "+8w", 1000),
],
ignore_rows=["balance", "period_balance", "in_total"],
)
def check_matrix(self, args=None, ignore_rows=None):
if not args:
args = []
if not ignore_rows:
ignore_rows = []
with mute_logger("odoo.addons.mis_builder.models.kpimatrix"):
matrix = self.report._compute_matrix()
for row in matrix.iter_rows():
if row.kpi.name in ignore_rows:
continue
for cell in row.iter_cells():
if not cell:
continue
found = False
label = cell.subcol.col.label
for exp in args:
if exp[0] == row.kpi.name and exp[1] == label:
found = True
self.assertEqual(cell.val, exp[2])
break
if not found:
self.assertEqual(cell.val, 0)
| 34.949045
| 5,487
|
1,310
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 ADHOC SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class MisCashFlowForecastLine(models.Model):
_name = "mis.cash_flow.forecast_line"
_description = "MIS Cash Flow Forecast Line"
date = fields.Date(
required=True,
index=True,
)
account_id = fields.Many2one(
comodel_name="account.account",
string="Account",
required=True,
help="The account of the forecast line is only for informative purpose",
)
partner_id = fields.Many2one(
comodel_name="res.partner",
string="Partner",
)
name = fields.Char(
required=True,
default="/",
)
balance = fields.Float(
required=True,
)
company_id = fields.Many2one(
"res.company",
string="Company",
required=True,
default=lambda self: self.env.company,
index=True,
)
@api.constrains("company_id", "account_id")
def _check_company_id_account_id(self):
if self.filtered(lambda x: x.company_id != x.account_id.company_id):
raise ValidationError(
_("The Company and the Company of the Account must be the same.")
)
| 28.478261
| 1,310
|
278
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 ADHOC SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class AccountAccount(models.Model):
_inherit = "account.account"
hide_in_cash_flow = fields.Boolean(
string="Hide in Cash Flow?",
)
| 23.166667
| 278
|
590
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
class MisReportInstancePeriod(models.Model):
_inherit = "mis.report.instance.period"
def _get_additional_move_line_filter(self):
"""Add the posted condition ."""
domain = super()._get_additional_move_line_filter()
if (
self._get_aml_model_name() == "mis.cash_flow"
and self.report_instance_id.target_move == "posted"
):
domain += [("state", "=", "posted")]
return domain
| 34.705882
| 590
|
4,390
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 ADHOC SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from psycopg2.extensions import AsIs
from odoo import fields, models, tools
class MisCashFlow(models.Model):
_name = "mis.cash_flow"
_description = "MIS Cash Flow"
_auto = False
line_type = fields.Selection(
[("forecast_line", "Forecast Line"), ("move_line", "Journal Item")],
index=True,
readonly=True,
)
name = fields.Char(
readonly=True,
)
account_id = fields.Many2one(
comodel_name="account.account",
string="Account",
auto_join=True,
index=True,
readonly=True,
)
partner_id = fields.Many2one(
comodel_name="res.partner",
string="Partner",
readonly=True,
)
move_line_id = fields.Many2one(
comodel_name="account.move.line",
string="Journal Item",
auto_join=True,
readonly=True,
)
company_id = fields.Many2one(
comodel_name="res.company",
string="Company",
auto_join=True,
readonly=True,
index=True,
)
credit = fields.Float(
readonly=True,
)
debit = fields.Float(
readonly=True,
)
date = fields.Date(
readonly=True,
index=True,
)
reconciled = fields.Boolean(
readonly=True,
)
full_reconcile_id = fields.Many2one(
"account.full.reconcile",
string="Matching Number",
readonly=True,
index=True,
)
account_internal_type = fields.Selection(
related="account_id.user_type_id.type", readonly=True
)
state = fields.Selection(
selection="_selection_parent_state",
)
def _selection_parent_state(self):
return self.env["account.move"].fields_get(allfields=["state"])["state"][
"selection"
]
def init(self):
query = """
SELECT
-- we use negative id to avoid duplicates and we don't use
-- ROW_NUMBER() because the performance was very poor
-aml.id as id,
'move_line' as line_type,
aml.id as move_line_id,
aml.account_id as account_id,
CASE
WHEN aml.amount_residual > 0
THEN aml.amount_residual
ELSE 0.0
END AS debit,
CASE
WHEN aml.amount_residual < 0
THEN -aml.amount_residual
ELSE 0.0
END AS credit,
aml.reconciled as reconciled,
aml.full_reconcile_id as full_reconcile_id,
aml.partner_id as partner_id,
aml.company_id as company_id,
aml.name as name,
aml.parent_state as state,
COALESCE(aml.date_maturity, aml.date) as date
FROM account_move_line as aml
WHERE aml.parent_state != 'cancel'
UNION ALL
SELECT
fl.id as id,
'forecast_line' as line_type,
NULL as move_line_id,
fl.account_id as account_id,
CASE
WHEN fl.balance > 0
THEN fl.balance
ELSE 0.0
END AS debit,
CASE
WHEN fl.balance < 0
THEN -fl.balance
ELSE 0.0
END AS credit,
NULL as reconciled,
NULL as full_reconcile_id,
fl.partner_id as partner_id,
fl.company_id as company_id,
fl.name as name,
'posted' as state,
fl.date as date
FROM mis_cash_flow_forecast_line as fl
"""
tools.drop_view_if_exists(self.env.cr, self._table)
self._cr.execute(
"CREATE OR REPLACE VIEW %s AS (%s)", (AsIs(self._table), AsIs(query))
)
def action_open_related_line(self):
self.ensure_one()
if self.line_type == "move_line":
return self.move_line_id.get_formview_action()
else:
return (
self.env["mis.cash_flow.forecast_line"]
.browse(self.id)
.get_formview_action()
)
| 30.275862
| 4,390
|
606
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Carlos Roca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Account Purchase Stock Report Non Billed",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-financial-reporting",
"depends": [
"account_sale_stock_report_non_billed",
"purchase_stock_picking_invoice_link",
"purchase_stock",
],
"data": [],
"installable": True,
"maintainers": ["CarlosRoca13"],
"development_status": "Beta",
}
| 33.666667
| 606
|
16,388
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Carlos Roca
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
from dateutil.relativedelta import relativedelta
from odoo import fields
from odoo.tests import Form, common, tagged
@tagged("-at_install", "post_install")
class TestAccountPurchaseStockReportNonBilled(common.TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.supplier = cls.env["res.partner"].create({"name": "Supplier for Test"})
cls.product = cls.env["product.product"].create({"name": "Product for Test"})
po_form = Form(cls.env["purchase.order"])
po_form.partner_id = cls.supplier
with po_form.order_line.new() as po_line_form:
po_line_form.product_id = cls.product
po_line_form.price_unit = 15.0
cls.po = po_form.save()
def get_picking_done_po(self):
self.po.button_confirm()
picking = self.po.picking_ids[0]
picking.action_confirm()
picking.move_lines.quantity_done = 1.0
picking.button_validate()
return picking
def test_01_report_move_not_invoiced(self):
picking = self.get_picking_done_po()
wiz = self.env["account.sale.stock.report.non.billed.wiz"].create(
{"date_check": fields.Date.today()}
)
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in picking.move_lines:
self.assertIn(move.id, domain_ids)
def test_02_report_move_full_invoiced(self):
picking = self.get_picking_done_po()
inv_action = self.po.action_create_invoice()
invoice = self.env["account.move"].browse([(inv_action["res_id"])])
invoice.invoice_date = self.po.create_date
invoice.action_post()
wiz = self.env["account.sale.stock.report.non.billed.wiz"].create(
{"date_check": fields.Date.today()}
)
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in picking.move_lines:
self.assertNotIn(move.id, domain_ids)
def test_03_report_move_partially_invoiced(self):
# First done just one move + invoice
self.po.button_confirm()
picking = self.po.picking_ids[0]
picking.action_confirm()
move_done = picking.move_lines[0]
move_done.quantity_done = 1.0
picking.button_validate()
inv_action = self.po.action_create_invoice()
invoice = self.env["account.move"].browse([(inv_action["res_id"])])
invoice.invoice_date = self.po.create_date
invoice.action_post()
# Done other moves to appear at report
picking_ret = self.po.picking_ids.filtered(lambda p: p.state == "assigned")
picking_ret.action_confirm()
picking_ret.move_lines.quantity_done = 1.0
picking_ret.button_validate()
moves_not_done = picking_ret.move_lines
wiz = self.env["account.sale.stock.report.non.billed.wiz"].create(
{"date_check": fields.Date.today()}
)
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
self.assertNotIn(move_done.id, domain_ids)
for move in moves_not_done:
self.assertIn(move.id, domain_ids)
def test_04_report_move_full_invoice_refund(self):
self.po.button_confirm()
# Validate shipment
picking = self.po.picking_ids[0]
# Process pickings
picking.action_confirm()
picking.move_lines.quantity_done = 1.0
picking.button_validate()
# Create invoice
inv_action = self.po.action_create_invoice()
invoice = self.env["account.move"].browse([(inv_action["res_id"])])
invoice.invoice_date = self.po.create_date
invoice.action_post()
wiz = self.env["account.sale.stock.report.non.billed.wiz"].create(
{"date_check": fields.Date.today()}
)
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in picking.move_lines:
self.assertNotIn(move.id, domain_ids)
# Refund invoice
wiz_invoice_refund = (
self.env["account.move.reversal"]
.with_context(active_model="account.move", active_ids=invoice.ids)
.create(
{
"refund_method": "cancel",
"reason": "test",
"journal_id": invoice.journal_id.id,
}
)
)
wiz_invoice_refund.reverse_moves()
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in picking.move_lines:
self.assertIn(move.id, domain_ids)
# Create invoice again
inv_action = self.po.action_create_invoice()
new_invoice = self.env["account.move"].browse([(inv_action["res_id"])])
new_invoice.invoice_date = self.po.create_date
new_invoice.action_post()
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in picking.move_lines:
self.assertNotIn(move.id, domain_ids)
def test_05_report_move_partial_pickings_full_invoice(self):
self.po.order_line.product_qty = 5
self.po.button_confirm()
picking = self.po.picking_ids[0]
picking.action_confirm()
picking.move_lines.quantity_done = 3.0
res_dict = picking.button_validate()
move_lines = picking.move_lines
self.env["stock.backorder.confirmation"].with_context(
**res_dict["context"]
).process()
picking = self.po.picking_ids.filtered(lambda p: p.state != "done")
picking.action_confirm()
picking.move_lines.quantity_done = 2.0
picking.button_validate()
move_lines += picking.move_lines
wiz = self.env["account.sale.stock.report.non.billed.wiz"].create(
{"date_check": fields.Date.today()}
)
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in move_lines:
self.assertIn(move.id, domain_ids)
inv_action = self.po.action_create_invoice()
invoice = self.env["account.move"].browse([(inv_action["res_id"])])
invoice.invoice_date = self.po.create_date
invoice.action_post()
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in move_lines:
self.assertNotIn(move.id, domain_ids)
def test_06_report_move_partial_pickings_each_invoice(self):
self.po.order_line.product_qty = 5
self.po.button_confirm()
picking = self.po.picking_ids[0]
picking.action_confirm()
picking.move_lines.quantity_done = 3.0
res_dict = picking.button_validate()
move_lines = picking.move_lines
self.env["stock.backorder.confirmation"].with_context(
**res_dict["context"]
).process()
inv_action = self.po.action_create_invoice()
invoice = self.env["account.move"].browse([(inv_action["res_id"])])
invoice.invoice_date = self.po.create_date
invoice.action_post()
picking = self.po.picking_ids.filtered(lambda p: p.state != "done")
picking.action_confirm()
picking.move_lines.quantity_done = 2.0
picking.button_validate()
wiz = self.env["account.sale.stock.report.non.billed.wiz"].create(
{"date_check": fields.Date.today()}
)
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in move_lines:
self.assertNotIn(move.id, domain_ids)
for move in picking.move_lines:
self.assertIn(move.id, domain_ids)
inv_action = self.po.action_create_invoice()
invoice = self.env["account.move"].browse([(inv_action["res_id"])])
invoice.invoice_date = self.po.create_date
invoice.action_post()
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in move_lines + picking.move_lines:
self.assertNotIn(move.id, domain_ids)
def test_07_report_move_full_invoice_return_without_update(self):
self.po.button_confirm()
# Validate shipment
picking = self.po.picking_ids[0]
# Process pickings
picking.action_confirm()
picking.move_lines.quantity_done = 1.0
picking.button_validate()
# Create invoice
inv_action = self.po.action_create_invoice()
invoice = self.env["account.move"].browse([(inv_action["res_id"])])
invoice.invoice_date = self.po.create_date
invoice.action_post()
wiz = self.env["account.sale.stock.report.non.billed.wiz"].create(
{"date_check": fields.Date.today()}
)
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in picking.move_lines:
self.assertNotIn(move.id, domain_ids)
# Return move
wiz_return_form = Form(
self.env["stock.return.picking"].with_context(
active_model="stock.picking", active_id=picking.id
)
)
wiz_return = wiz_return_form.save()
wiz_return.product_return_moves.to_refund = False
return_id = wiz_return.create_returns()["res_id"]
picking_return = self.env["stock.picking"].browse(return_id)
picking_return.move_line_ids.write({"qty_done": 1})
picking_return.button_validate()
for move in picking_return.move_lines:
self.assertNotIn(move.id, domain_ids)
def test_08_move_return_return_full_invoiced(self):
self.po.button_confirm()
# Validate shipment
picking = self.po.picking_ids[0]
# Process pickings
picking.action_confirm()
picking.move_lines.quantity_done = 1.0
picking.button_validate()
wiz_return_form = Form(
self.env["stock.return.picking"].with_context(
active_model="stock.picking", active_id=picking.id
)
)
wiz_return = wiz_return_form.save()
return_id = wiz_return.create_returns()["res_id"]
picking_return = self.env["stock.picking"].browse(return_id)
picking_return.move_line_ids.write({"qty_done": 1})
picking_return.button_validate()
wiz_return_return_form = Form(
self.env["stock.return.picking"].with_context(
active_model="stock.picking", active_id=picking_return.id
)
)
wiz_return_return = wiz_return_return_form.save()
return_return_id = wiz_return_return.create_returns()["res_id"]
picking_return_return = self.env["stock.picking"].browse(return_return_id)
picking_return_return.move_line_ids.write({"qty_done": 1})
picking_return_return.button_validate()
inv_action = self.po.action_create_invoice()
invoice = self.env["account.move"].browse([(inv_action["res_id"])])
invoice.invoice_date = self.po.create_date
invoice.action_post()
wiz = self.env["account.sale.stock.report.non.billed.wiz"].create(
{"date_check": fields.Date.today()}
)
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in picking.move_lines:
self.assertNotIn(move.id, domain_ids)
for move in picking_return.move_lines:
self.assertNotIn(move.id, domain_ids)
for move in picking_return_return.move_lines:
self.assertNotIn(move.id, domain_ids)
def test_09_move_return_return_non_invoiced(self):
self.po.button_confirm()
# Validate shipment
picking = self.po.picking_ids[0]
# Process pickings
picking.action_confirm()
picking.move_lines.quantity_done = 1.0
picking.button_validate()
wiz_return_form = Form(
self.env["stock.return.picking"].with_context(
active_model="stock.picking", active_id=picking.id
)
)
wiz_return = wiz_return_form.save()
return_id = wiz_return.create_returns()["res_id"]
picking_return = self.env["stock.picking"].browse(return_id)
picking_return.move_line_ids.write({"qty_done": 1})
picking_return.button_validate()
wiz_return_return_form = Form(
self.env["stock.return.picking"].with_context(
active_model="stock.picking", active_id=picking_return.id
)
)
wiz_return_return = wiz_return_return_form.save()
return_return_id = wiz_return_return.create_returns()["res_id"]
picking_return_return = self.env["stock.picking"].browse(return_return_id)
picking_return_return.move_line_ids.write({"qty_done": 1})
picking_return_return.button_validate()
wiz = self.env["account.sale.stock.report.non.billed.wiz"].create(
{"date_check": fields.Date.today()}
)
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in picking.move_lines:
self.assertNotIn(move.id, domain_ids)
for move in picking_return.move_lines:
self.assertNotIn(move.id, domain_ids)
for move in picking_return_return.move_lines:
self.assertIn(move.id, domain_ids)
def test_10_move_invoice_return_without_update_qty(self):
self.po.button_confirm()
# Validate shipment
picking = self.po.picking_ids[0]
# Process pickings
picking.action_confirm()
picking.move_lines.quantity_done = 1.0
picking.button_validate()
inv_action = self.po.action_create_invoice()
invoice = self.env["account.move"].browse([(inv_action["res_id"])])
invoice.invoice_date = self.po.create_date
invoice.action_post()
wiz_return_form = Form(
self.env["stock.return.picking"].with_context(
active_model="stock.picking", active_id=picking.id, to_refund=False
)
)
wiz_return = wiz_return_form.save()
return_id = wiz_return.create_returns()["res_id"]
picking_return = self.env["stock.picking"].browse(return_id)
picking_return.move_line_ids.write({"qty_done": 1})
picking_return.button_validate()
wiz_return_return_form = Form(
self.env["stock.return.picking"].with_context(
active_model="stock.picking",
active_id=picking_return.id,
to_refund=False,
)
)
wiz_return_return = wiz_return_return_form.save()
return_return_id = wiz_return_return.create_returns()["res_id"]
picking_return_return = self.env["stock.picking"].browse(return_return_id)
picking_return_return.move_line_ids.write({"qty_done": 1})
picking_return_return.button_validate()
wiz = self.env["account.sale.stock.report.non.billed.wiz"].create(
{"date_check": fields.Date.today()}
)
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in picking.move_lines:
self.assertNotIn(move.id, domain_ids)
for move in picking_return.move_lines:
self.assertNotIn(move.id, domain_ids)
for move in picking_return_return.move_lines:
self.assertNotIn(move.id, domain_ids)
def test_11_report_move_full_invoiced_out_of_date(self):
self.po.button_confirm()
# Validate shipment
picking = self.po.picking_ids[0]
# Process pickings
picking.action_confirm()
picking.move_lines.quantity_done = 1.0
picking.button_validate()
# Emulate prepaying invoice
inv_action = self.po.action_create_invoice()
invoice = self.env["account.move"].browse([(inv_action["res_id"])])
invoice.invoice_date = fields.Date.today() - relativedelta(days=5)
invoice.action_post()
wiz = self.env["account.sale.stock.report.non.billed.wiz"].create(
{"date_check": fields.Date.today(), "interval_restrict_invoices": True}
)
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in picking.move_lines:
self.assertIn(move.id, domain_ids)
| 42.900524
| 16,388
|
1,299
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Carlos Roca
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
from odoo import api, models
from odoo.osv import expression
class AccountSaleStockReportNonBilledWiz(models.TransientModel):
_inherit = "account.sale.stock.report.non.billed.wiz"
def _get_search_domain(self):
domain = super()._get_search_domain()
res_domain = expression.OR(
[
domain,
[
("date_done", ">=", self.stock_move_non_billed_threshold),
("date_done", "<=", self.date_check),
("purchase_line_id", "!=", False),
("state", "=", "done"),
("scrapped", "=", False),
"|",
("location_id.usage", "=", "supplier"),
"&",
("location_dest_id.usage", "=", "supplier"),
("to_refund", "=", True),
],
]
)
return res_domain
@api.model
def discart_kits_from_moves(self, stock_moves):
res = super().discart_kits_from_moves(stock_moves)
return res + stock_moves.filtered(
lambda move: move.product_id == move.purchase_line_id.product_id
)
| 35.108108
| 1,299
|
3,371
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Carlos Roca
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
from odoo import api, models
class StockMove(models.Model):
_inherit = "stock.move"
@api.depends("purchase_line_id")
def _compute_currency_id(self):
for move in self:
if move.purchase_line_id:
move.currency_id = move.purchase_line_id.currency_id
else:
return super(StockMove, move)._compute_currency_id()
def get_quantity_invoiced(self, invoice_lines):
if self.purchase_line_id:
if not invoice_lines:
return 0
qty_invoiced = abs(
sum(
invoice_lines.mapped(
lambda l: l.quantity
if (l.move_id.move_type == "in_invoice" and not self.to_refund)
or (l.move_id.move_type == "in_refund" and self.to_refund)
else -l.quantity
)
)
)
# Check when grouping different moves in an invoice line
moves = invoice_lines.mapped("move_line_ids")
date_start = self.env.context.get("moves_date_start")
date_end = self.env.context.get("moves_date_end")
if date_start and date_end:
moves = moves.filtered(
lambda ml: ml.date_done >= date_start and ml.date_done <= date_end
)
total_qty = moves.get_total_devolution_moves()
if qty_invoiced != total_qty:
invoiced = 0.0
for move in moves:
qty = (
move.quantity_done
if move.quantity_done <= (qty_invoiced - invoiced)
else qty_invoiced - invoiced
)
if move.check_is_return():
qty = -qty
if move == self:
return qty
invoiced += qty
return 0
return (
self.quantity_done
if not self.check_is_return()
else -self.quantity_done
)
return super().get_quantity_invoiced(invoice_lines)
def _set_not_invoiced_values(self, qty_to_invoice, invoiced_qty):
self.ensure_one()
if self.purchase_line_id:
self.quantity_not_invoiced = qty_to_invoice - invoiced_qty
price_unit = self.purchase_line_id.price_unit
if "discount" in self.purchase_line_id._fields:
price_unit = self.purchase_line_id.price_unit * (
1 - self.purchase_line_id.discount / 100
)
self.price_not_invoiced = (qty_to_invoice - invoiced_qty) * price_unit
else:
return super()._set_not_invoiced_values(qty_to_invoice, invoiced_qty)
@api.depends("purchase_line_id")
@api.depends_context("date_check_invoiced_moves")
def _compute_not_invoiced_values(self):
return super()._compute_not_invoiced_values()
def _get_model_id_origin_document(self):
if not self.purchase_line_id:
return super()._get_model_id_origin_document()
return self.purchase_line_id.order_id._name, self.purchase_line_id.order_id.id
| 40.614458
| 3,371
|
714
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Carlos Roca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Account Sale Stock Report Non Billed",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-financial-reporting",
"depends": ["stock_picking_invoice_link"],
"data": [
"views/res_config_settings_views.xml",
"views/stock_move_non_billed_views.xml",
"security/ir.model.access.csv",
"wizard/account_sale_stock_report_non_billed_wiz_views.xml",
],
"installable": True,
"maintainers": ["CarlosRoca13"],
"development_status": "Beta",
}
| 37.578947
| 714
|
11,875
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Carlos Roca
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
from dateutil.relativedelta import relativedelta
from odoo import fields
from odoo.tests import Form, tagged
from odoo.addons.stock_picking_invoice_link.tests.test_stock_picking_invoice_link import (
TestStockPickingInvoiceLink,
)
@tagged("post_install")
class TestAccountSaleStrockReportNonBilled(TestStockPickingInvoiceLink):
def setUp(self):
super().setUp()
self.prod_order.invoice_policy = "delivery"
def get_picking_done_so(self):
picking = self.so.picking_ids.filtered(
lambda x: x.picking_type_code == "outgoing"
and x.state in ("confirmed", "assigned", "partially_available")
)
picking.move_line_ids.write({"qty_done": 2})
picking.button_validate()
return picking
def test_01_report_move_not_invoiced(self):
pick_1 = self.get_picking_done_so()
wiz = self.env["account.sale.stock.report.non.billed.wiz"].create(
{"date_check": fields.Date.today()}
)
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in pick_1.move_lines:
self.assertIn(move.id, domain_ids)
def test_02_report_move_full_invoiced(self):
pick_1 = self.get_picking_done_so()
inv = self.so._create_invoices()
inv.action_post()
wiz = self.env["account.sale.stock.report.non.billed.wiz"].create(
{"date_check": fields.Date.today()}
)
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in pick_1.move_lines:
self.assertNotIn(move.id, domain_ids)
def test_03_report_move_partially_invoiced(self):
# First done just one move + invoice
picking = self.so.picking_ids.filtered(
lambda x: x.picking_type_code == "outgoing"
and x.state in ("confirmed", "assigned", "partially_available")
)
move_done = picking.move_lines[0]
moves_not_done = picking.move_lines[1:]
move_done.move_line_ids.write({"qty_done": 2})
backorder_wiz = picking.button_validate()
backorder_wiz = Form(
self.env[backorder_wiz["res_model"]].with_context(
**backorder_wiz["context"]
)
).save()
backorder_wiz.process()
self.assertEqual(picking.state, "done")
inv = self.so._create_invoices()
inv.action_post()
# Done other moves to appear at report
self.get_picking_done_so()
wiz = self.env["account.sale.stock.report.non.billed.wiz"].create(
{"date_check": fields.Date.today()}
)
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
self.assertNotIn(move_done.id, domain_ids)
for move in moves_not_done:
self.assertIn(move.id, domain_ids)
def test_04_report_move_full_invoice_refund(self):
pick_1 = self.get_picking_done_so()
inv = self.so._create_invoices()
inv.action_post()
# Refund invoice
wiz_invoice_refund = (
self.env["account.move.reversal"]
.with_context(active_model="account.move", active_ids=inv.ids)
.create(
{
"refund_method": "cancel",
"reason": "test",
"journal_id": inv.journal_id.id,
}
)
)
wiz_invoice_refund.reverse_moves()
wiz = self.env["account.sale.stock.report.non.billed.wiz"].create(
{"date_check": fields.Date.today()}
)
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in pick_1.move_lines:
self.assertIn(move.id, domain_ids)
def test_05_report_move_full_return_no_invoiced(self):
picking = self.get_picking_done_so()
wiz_return_form = Form(
self.env["stock.return.picking"].with_context(
active_model="stock.picking", active_id=picking.id
)
)
wiz_return = wiz_return_form.save()
return_id = wiz_return.create_returns()["res_id"]
picking_return = self.env["stock.picking"].browse(return_id)
picking_return.move_line_ids.write({"qty_done": 2})
picking_return.button_validate()
wiz = self.env["account.sale.stock.report.non.billed.wiz"].create(
{"date_check": fields.Date.today()}
)
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in picking.move_lines:
self.assertNotIn(move.id, domain_ids)
for move in picking_return.move_lines:
self.assertNotIn(move.id, domain_ids)
def test_06_report_move_full_return_invoiced(self):
picking = self.get_picking_done_so()
inv = self.so._create_invoices()
inv.action_post()
wiz_return_form = Form(
self.env["stock.return.picking"].with_context(
active_model="stock.picking", active_id=picking.id
)
)
wiz_return = wiz_return_form.save()
return_id = wiz_return.create_returns()["res_id"]
picking_return = self.env["stock.picking"].browse(return_id)
picking_return.move_line_ids.write({"qty_done": 2})
picking_return.button_validate()
wiz = self.env["account.sale.stock.report.non.billed.wiz"].create(
{"date_check": fields.Date.today()}
)
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in picking.move_lines:
self.assertNotIn(move.id, domain_ids)
for move in picking_return.move_lines:
self.assertIn(move.id, domain_ids)
inv = self.so._create_invoices(final=True)
inv.action_post()
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in picking_return.move_lines:
self.assertNotIn(move.id, domain_ids)
def test_07_move_return_return_full_invoiced(self):
picking = self.get_picking_done_so()
wiz_return_form = Form(
self.env["stock.return.picking"].with_context(
active_model="stock.picking", active_id=picking.id
)
)
wiz_return = wiz_return_form.save()
return_id = wiz_return.create_returns()["res_id"]
picking_return = self.env["stock.picking"].browse(return_id)
picking_return.move_line_ids.write({"qty_done": 2})
picking_return.button_validate()
wiz_return_return_form = Form(
self.env["stock.return.picking"].with_context(
active_model="stock.picking", active_id=picking_return.id
)
)
wiz_return_return = wiz_return_return_form.save()
return_return_id = wiz_return_return.create_returns()["res_id"]
picking_return_return = self.env["stock.picking"].browse(return_return_id)
picking_return_return.move_line_ids.write({"qty_done": 2})
picking_return_return.button_validate()
self.so._create_invoices(final=True)
wiz = self.env["account.sale.stock.report.non.billed.wiz"].create(
{"date_check": fields.Date.today()}
)
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in picking.move_lines:
self.assertNotIn(move.id, domain_ids)
for move in picking_return.move_lines:
self.assertNotIn(move.id, domain_ids)
for move in picking_return_return.move_lines:
self.assertNotIn(move.id, domain_ids)
def test_08_move_return_return_non_invoiced(self):
picking = self.get_picking_done_so()
wiz_return_form = Form(
self.env["stock.return.picking"].with_context(
active_model="stock.picking", active_id=picking.id
)
)
wiz_return = wiz_return_form.save()
return_id = wiz_return.create_returns()["res_id"]
picking_return = self.env["stock.picking"].browse(return_id)
picking_return.move_line_ids.write({"qty_done": 2})
picking_return.button_validate()
wiz_return_return_form = Form(
self.env["stock.return.picking"].with_context(
active_model="stock.picking", active_id=picking_return.id
)
)
wiz_return_return = wiz_return_return_form.save()
return_return_id = wiz_return_return.create_returns()["res_id"]
picking_return_return = self.env["stock.picking"].browse(return_return_id)
picking_return_return.move_line_ids.write({"qty_done": 2})
picking_return_return.button_validate()
wiz = self.env["account.sale.stock.report.non.billed.wiz"].create(
{"date_check": fields.Date.today()}
)
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in picking.move_lines:
self.assertNotIn(move.id, domain_ids)
for move in picking_return.move_lines:
self.assertNotIn(move.id, domain_ids)
for move in picking_return_return.move_lines:
self.assertIn(move.id, domain_ids)
def test_09_move_invoice_return_without_update_qty(self):
picking = self.get_picking_done_so()
self.so._create_invoices(final=True)
wiz_return_form = Form(
self.env["stock.return.picking"].with_context(
active_model="stock.picking",
active_id=picking.id,
default_to_refund=False,
)
)
wiz_return = wiz_return_form.save()
return_id = wiz_return.create_returns()["res_id"]
picking_return = self.env["stock.picking"].browse(return_id)
picking_return.move_line_ids.write({"qty_done": 2})
picking_return.button_validate()
wiz_return_return_form = Form(
self.env["stock.return.picking"].with_context(
active_model="stock.picking",
active_id=picking_return.id,
default_to_refund=False,
)
)
wiz_return_return = wiz_return_return_form.save()
return_return_id = wiz_return_return.create_returns()["res_id"]
picking_return_return = self.env["stock.picking"].browse(return_return_id)
picking_return_return.move_line_ids.write({"qty_done": 2})
picking_return_return.button_validate()
wiz = self.env["account.sale.stock.report.non.billed.wiz"].create(
{"date_check": fields.Date.today()}
)
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in picking.move_lines:
self.assertNotIn(move.id, domain_ids)
for move in picking_return.move_lines:
self.assertNotIn(move.id, domain_ids)
for move in picking_return_return.move_lines:
self.assertNotIn(move.id, domain_ids)
def test_10_report_move_full_invoiced_out_of_date(self):
picking = self.so.picking_ids.filtered(
lambda x: x.picking_type_code == "outgoing"
and x.state in ("confirmed", "assigned", "partially_available")
)
picking.move_line_ids.write({"qty_done": 2})
picking.button_validate()
# Emulate prepaying invoice
inv = self.so._create_invoices()
inv.date = fields.Date.today() - relativedelta(days=5)
wiz = self.env["account.sale.stock.report.non.billed.wiz"].create(
{"date_check": fields.Date.today(), "interval_restrict_invoices": True}
)
action = wiz.open_at_date()
domain_ids = action["domain"][0][2]
for move in picking.move_lines:
self.assertIn(move.id, domain_ids)
| 42.259786
| 11,875
|
5,776
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Carlos Roca
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
from odoo import _, api, fields, models
from odoo.tools import float_is_zero
class AccountSaleStockReportNonBilledWiz(models.TransientModel):
_name = "account.sale.stock.report.non.billed.wiz"
_description = "Wizard to open stock moves that have not been invoiced at that time"
def _default_stock_move_non_billed_threshold(self):
return self.env.company.stock_move_non_billed_threshold
stock_move_non_billed_threshold = fields.Date(
default=lambda self: self._default_stock_move_non_billed_threshold()
)
date_check = fields.Date(string="Date", default=fields.Date.today)
interval_restrict_invoices = fields.Boolean(
string="Restrict invoices using the date interval"
)
def _get_search_domain(self):
return [
("date_done", ">=", self.stock_move_non_billed_threshold),
("date_done", "<=", self.date_check),
("sale_line_id", "!=", False),
("state", "=", "done"),
("scrapped", "=", False),
"|",
("location_dest_id.usage", "=", "customer"),
"&",
("location_id.usage", "=", "customer"),
("to_refund", "=", True),
]
@api.model
def discart_kits_from_moves(self, stock_moves):
return stock_moves.filtered(
lambda move: move.product_id == move.sale_line_id.product_id
)
@api.model
def _get_neutralized_moves(self, stock_moves):
neutralized_moves = self.env["stock.move"]
for move in stock_moves.sorted("origin_returned_move_id"):
# Not show returns that not update qty on stock
if move.origin_returned_move_id and not move.to_refund:
neutralized_moves |= move
if move in neutralized_moves:
continue
dp = self.env["decimal.precision"].precision_get("Product Unit of Measure")
date_start = (
self.stock_move_non_billed_threshold
if self.interval_restrict_invoices
else False
)
if float_is_zero(
move.quantity_done
- sum(move.returned_move_ids.mapped("quantity_done")),
precision_digits=dp,
) and not (
move.invoice_line_ids
+ move.returned_move_ids.mapped("invoice_line_ids")
).filtered(
lambda l: l.check_invoice_line_in_date(
self.date_check, date_start=date_start
)
):
neutralized_moves |= move + move.returned_move_ids
return neutralized_moves
def open_at_date(self):
dp = self.env["decimal.precision"].precision_get("Product Unit of Measure")
# Get the moves after the threshold
domain = self._get_search_domain()
stock_moves = self.env["stock.move"].search(domain)
# Filter the moves with the domain
stock_moves = stock_moves.filtered_domain(self._get_search_domain())
stock_moves = self.discart_kits_from_moves(stock_moves)
stock_moves -= self._get_neutralized_moves(stock_moves)
final_stock_move_ids = []
date_start = (
self.stock_move_non_billed_threshold
if self.interval_restrict_invoices
else False
)
for move in stock_moves:
invoices_not_cancel = move.invoice_line_ids.filtered(
lambda l: l.move_id.state != "cancel"
)
moves_in_date = invoices_not_cancel.mapped("move_line_ids").filtered(
lambda m: m.date_done >= self.stock_move_non_billed_threshold
and m.date_done <= self.date_check
)
inv_lines = moves_in_date.mapped("invoice_line_ids").filtered(
lambda l: l.check_invoice_line_in_date(
self.date_check, date_start=date_start
)
)
qty_to_invoice = (
move.quantity_done
if not move.check_is_return()
else -move.quantity_done
)
calculated_qty = move.with_context(
moves_date_start=self.stock_move_non_billed_threshold,
moves_date_end=self.date_check,
).get_quantity_invoiced(inv_lines)
if not float_is_zero(qty_to_invoice - calculated_qty, precision_digits=dp):
final_stock_move_ids.append(move.id)
tree_view_id = self.env.ref(
"account_sale_stock_report_non_billed.view_move_tree"
).id
pivot_view_id = self.env.ref(
"account_sale_stock_report_non_billed.view_move_pivot_no_invoiced"
).id
search_view_id = self.env.ref(
"account_sale_stock_report_non_billed.view_move_search"
).id
context = dict(self.env.context, date_check_invoiced_moves=self.date_check)
if self.interval_restrict_invoices:
context = dict(
context,
date_check_invoiced_moves_start=self.stock_move_non_billed_threshold,
)
action = {
"type": "ir.actions.act_window",
"views": [(tree_view_id, "tree"), (pivot_view_id, "pivot")],
"view_mode": "tree,pivot",
"search_view_id": search_view_id,
"name": _("Non billed moves (%(from)s -> %(to)s)")
% {"from": self.stock_move_non_billed_threshold, "to": self.date_check},
"res_model": "stock.move",
"domain": [("id", "in", final_stock_move_ids)],
"context": context,
}
return action
| 41.855072
| 5,776
|
743
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Carlos Roca
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
from odoo import models
class StockMove(models.Model):
_inherit = "account.move.line"
def check_invoice_line_in_date(self, date_check, date_start=False):
self.ensure_one()
start = True
if date_start:
start = (
self.move_id.invoice_date
or self.move_id.date
or self.create_date.date()
) >= date_start
return (
start
and (
self.move_id.invoice_date
or self.move_id.date
or self.create_date.date()
)
<= date_check
)
| 27.518519
| 743
|
7,763
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Carlos Roca
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockMove(models.Model):
_inherit = "stock.move"
quantity_not_invoiced = fields.Float(
string="Qty. to invoice",
compute="_compute_not_invoiced_values",
digits="Product Unit of Measure",
compute_sudo=True,
)
price_not_invoiced = fields.Float(
string="Amount to invoice",
compute="_compute_not_invoiced_values",
digits="Product Price",
compute_sudo=True,
)
currency_id = fields.Many2one(
comodel_name="res.currency", compute="_compute_currency_id", compute_sudo=True
)
date_done = fields.Date(
string="Effective Date", compute="_compute_date_done", store=True
)
@api.depends("picking_id.date_done")
def _compute_date_done(self):
self.date_done = False
for move in self:
if move.picking_id.date_done:
move.date_done = move.picking_id.date_done.date()
@api.depends("sale_line_id")
def _compute_currency_id(self):
"""Method to be overwritten when new implementations are made, e.g. with
purchase_stock_picking_invoice_link.
"""
self.currency_id = False
for move in self:
if move.sale_line_id:
move.currency_id = move.sale_line_id.currency_id
def check_is_return(self):
self.ensure_one()
if not self.origin_returned_move_id:
return False
else:
return not self.origin_returned_move_id.check_is_return()
def get_total_devolution_moves(self):
total_qty = 0
for move in self:
# Avoid moves related to returns that not update qty on stock
if move.origin_returned_move_id and not move.to_refund:
continue
if not move.check_is_return():
total_qty += move.quantity_done
else:
total_qty -= move.quantity_done
return total_qty
def get_quantity_invoiced(self, invoice_lines):
if not invoice_lines:
return 0
total_invoiced = abs(
sum(
invoice_lines.mapped(
lambda l: l.quantity
if (l.move_id.move_type == "out_invoice" and not self.to_refund)
or (l.move_id.move_type == "out_refund" and self.to_refund)
else -l.quantity
)
)
)
# Check when grouping different moves in an invoice line
moves = invoice_lines.mapped("move_line_ids")
date_start = self.env.context.get("moves_date_start")
date_end = self.env.context.get("moves_date_end")
if date_start and date_end:
moves = moves.filtered(
lambda ml: ml.date_done >= date_start and ml.date_done <= date_end
)
total_qty = moves.get_total_devolution_moves()
if total_invoiced != total_qty:
invoiced = 0.0
for move in moves:
qty = (
move.quantity_done
if move.quantity_done <= (total_invoiced - invoiced)
else total_invoiced - invoiced
)
if move.check_is_return():
qty = -qty
if move == self:
return qty
invoiced += qty
return 0
return self.quantity_done if not self.check_is_return() else -self.quantity_done
def _set_not_invoiced_values(self, qty_to_invoice, invoiced_qty):
self.ensure_one()
self.quantity_not_invoiced = qty_to_invoice - invoiced_qty
self.price_not_invoiced = (
qty_to_invoice - invoiced_qty
) * self.sale_line_id.price_reduce
@api.depends("sale_line_id")
@api.depends_context("date_check_invoiced_moves")
def _compute_not_invoiced_values(self):
for move in self:
if not self.env.context.get("date_check_invoiced_moves"):
move.quantity_not_invoiced = 0
move.price_not_invoiced = 0
continue
date_start = self.env.context.get("date_check_invoiced_moves_start", False)
date_end = self.env.context.get("date_check_invoiced_moves", False)
if date_start:
date_start = fields.Date.from_string(date_start)
if date_end:
date_end = fields.Date.from_string(date_start)
invoices_not_cancel = move.invoice_line_ids.filtered(
lambda l: l.move_id.state != "cancel"
)
moves_in_date = invoices_not_cancel.mapped("move_line_ids").filtered(
lambda m: m.date_done >= date_start and m.date_done <= date_end
)
inv_lines = moves_in_date.mapped("invoice_line_ids").filtered(
lambda l: l.check_invoice_line_in_date(
date_end,
date_start=date_start,
)
)
qty_to_invoice = (
move.quantity_done
if not move.check_is_return()
else -move.quantity_done
)
calculated_qty = move.with_context(
moves_date_start=date_start,
moves_date_end=date_end,
).get_quantity_invoiced(inv_lines)
move._set_not_invoiced_values(qty_to_invoice, calculated_qty)
@api.model
def read_group(
self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True
):
"""Method to add the computed values 'quantity_not_invoiced' and
'price_not_invoiced' to the result. Without doing it we get an error when trying
to get the info on a pivot view.
As the fields are not stored, before call super() method we had to remove
the keys from 'fields' argument to avoid errors.
"""
aux_fields = []
if "quantity_not_invoiced:sum" in fields:
aux_fields.append("quantity_not_invoiced:sum")
fields.remove("quantity_not_invoiced:sum")
if "price_not_invoiced:sum" in fields:
aux_fields.append("price_not_invoiced:sum")
fields.remove("price_not_invoiced:sum")
res = super().read_group(
domain,
fields,
groupby,
offset=offset,
limit=limit,
orderby=orderby,
lazy=lazy,
)
qty_not_inv = "quantity_not_invoiced:sum" in aux_fields
price_not_inv = "price_not_invoiced:sum" in aux_fields
if qty_not_inv or price_not_inv:
for line in res:
quantity = 0.0
price = 0.0
moves = self.search(line.get("__domain", domain))
for move in moves:
quantity += move.quantity_not_invoiced if qty_not_inv else 0.0
price += move.price_not_invoiced if price_not_inv else 0.0
line["quantity_not_invoiced"] = quantity
line["price_not_invoiced"] = price
return res
def _get_model_id_origin_document(self):
if not self.sale_line_id:
return
return self.sale_line_id.order_id._name, self.sale_line_id.order_id.id
def open_origin_document(self):
model, res_id = self._get_model_id_origin_document()
return {
"type": "ir.actions.act_window",
"views": [(False, "form")],
"view_mode": "form",
"res_model": model,
"res_id": res_id,
"context": self.env.context,
}
| 38.621891
| 7,763
|
334
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Carlos Roca
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
from odoo import fields, models
class ResCompany(models.Model):
_inherit = "res.company"
stock_move_non_billed_threshold = fields.Date(
string="Non Billed Threshold Date", default=fields.Date.today
)
| 27.833333
| 334
|
554
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Carlos Roca
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
stock_move_non_billed_threshold = fields.Date(
related="company_id.stock_move_non_billed_threshold", readonly=False
)
default_interval_restrict_invoices = fields.Boolean(
string="Restrict invoices using the date interval",
default_model="account.sale.stock.report.non.billed.wiz",
)
| 34.625
| 554
|
579
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Stock landed costs purchase auto",
"version": "15.0.1.0.0",
"category": "Inventory",
"website": "https://github.com/OCA/stock-logistics-workflow",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"depends": ["stock_landed_costs", "purchase_stock"],
"data": ["views/purchase_order_view.xml", "views/stock_landed_cost_view.xml"],
"installable": True,
"maintainers": ["victoralmau"],
}
| 41.214286
| 577
|
1,463
|
py
|
PYTHON
|
15.0
|
# Copyright 2021-2023 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo.tests import Form, common
class TestPurchaseOrder(common.TransactionCase):
def setUp(self):
super().setUp()
self.company = self.env.ref("base.main_company")
self.product_storable = self.env["product.product"].create(
{"name": "Producto Storable", "type": "product"}
)
self.partner = self.env["res.partner"].create({"name": "Mr Odoo"})
self.company.lc_journal_id = self.env["account.journal"].create(
{
"name": "Test LC",
"type": "general",
"code": "MISC-LC",
"company_id": self.company.id,
}
)
def _create_purchase_order(self):
order_form = Form(self.env["purchase.order"])
order_form.partner_id = self.partner
with order_form.order_line.new() as line_form:
line_form.product_id = self.product_storable
order = order_form.save()
return order
def test_order_lc(self):
order = self._create_purchase_order()
order.button_confirm()
self.assertTrue(order.landed_cost_ids)
picking = order.picking_ids[0]
picking.move_ids_without_package.quantity_done = 1
picking.button_validate()
lc = order.landed_cost_ids[0]
self.assertTrue(picking in lc.picking_ids)
| 36.525
| 1,461
|
2,541
|
py
|
PYTHON
|
15.0
|
# Copyright 2021-2023 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class PurchaseOrder(models.Model):
_inherit = "purchase.order"
landed_cost_ids = fields.One2many(
comodel_name="stock.landed.cost",
inverse_name="purchase_id",
string="Landed Costs",
)
landed_cost_number = fields.Integer(compute="_compute_landed_cost_number")
def _compute_landed_cost_number(self):
domain = [("purchase_id", "in", self.ids)]
res = self.env["stock.landed.cost"].read_group(
domain=domain, fields=["purchase_id"], groupby=["purchase_id"]
)
landed_cost_dict = {x["purchase_id"][0]: x["purchase_id_count"] for x in res}
for item in self:
item.landed_cost_number = landed_cost_dict.get(item.id, 0)
def _prepare_landed_cost_values(self, picking):
return {
"purchase_id": self.id,
"picking_ids": [(4, picking.id)],
}
def _create_picking_with_stock_landed_cost(self, picking):
self.ensure_one()
landed_cost = (
self.env["stock.landed.cost"]
.with_company(self.company_id)
.create(self._prepare_landed_cost_values(picking))
)
self.write({"landed_cost_ids": [(4, landed_cost.id)]})
def _create_picking(self):
all_pickings = self.mapped("picking_ids")
res = super()._create_picking()
for order in self:
order_pickings = order.picking_ids - all_pickings
if order_pickings:
order._create_picking_with_stock_landed_cost(
fields.first(order_pickings)
)
return res
def action_view_stock_landed_cost(self):
action = self.env["ir.actions.act_window"]._for_xml_id(
"stock_landed_costs.action_stock_landed_cost"
)
action["context"] = {"search_default_purchase_id": self.id}
return action
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
def _create_or_update_picking(self):
all_pickings = self.mapped("order_id.picking_ids")
res = super()._create_or_update_picking()
for order in self.mapped("order_id"):
order_pickings = order.picking_ids - all_pickings
if order_pickings:
order._create_picking_with_stock_landed_cost(
fields.first(order_pickings)
)
return res
| 35.760563
| 2,539
|
303
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class StockLandedCost(models.Model):
_inherit = "stock.landed.cost"
purchase_id = fields.Many2one(comodel_name="purchase.order", string="Purchase")
| 30.1
| 301
|
775
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
{
"name": "Stock Lot On Hand First",
"summary": "Allows to display lots on hand first in M2o fields",
"version": "15.0.1.0.0",
"development_status": "Alpha",
"category": "Inventory/Inventory",
"website": "https://github.com/OCA/stock-logistics-workflow",
"author": "Camptocamp, Odoo Community Association (OCA)",
"maintainers": ["grindtildeath"],
"license": "AGPL-3",
"installable": True,
"depends": ["stock_lot_product_qty_search", "base_view_inheritance_extension"],
"data": [
"views/stock_move_line.xml",
"views/stock_move.xml",
"views/stock_picking_type.xml",
"views/stock_picking.xml",
],
}
| 36.904762
| 775
|
5,328
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo.tests import TransactionCase
from odoo.tools import float_is_zero
class TestLotOnHandFirst(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.uom_precision = cls.env["decimal.precision"].precision_get(
"Product Unit of Measure"
)
cls.product = cls.env.ref("stock.product_cable_management_box").copy()
cls.stock_location = cls.env.ref("stock.stock_location_stock")
cls.delivery_order_picking_type = cls.env.ref("stock.picking_type_out")
@classmethod
def _create_lot(cls, product, lot_name, qty=0):
lot = cls.env["stock.production.lot"].create(
{
"name": lot_name,
"product_id": product.id,
"company_id": cls.env.company.id,
}
)
if not float_is_zero(qty, precision_digits=cls.uom_precision):
cls.env["stock.quant"]._update_available_quantity(
product, cls.stock_location, qty, lot_id=lot
)
return lot
def test_lot_on_hand_first(self):
"""Check lots without a qty are at the end of the list"""
# Create a few lots with quantities
lot_1 = self._create_lot(self.product, "LOT-000001", 0)
lot_2 = self._create_lot(self.product, "LOT-000002", 1)
lot_3 = self._create_lot(self.product, "LOT-000003", 2)
lot_4 = self._create_lot(self.product, "LOT-000004", 0)
lot_5 = self._create_lot(self.product, "LOT-000005", 1)
name_get_res = (
self.env["stock.production.lot"]
.with_context(name_search_qty_on_hand_first=True)
.name_search(args=[("product_id", "=", self.product.id)])
)
expected_res = [
(lot_2.id, lot_2.name),
(lot_3.id, lot_3.name),
(lot_5.id, lot_5.name),
(lot_1.id, lot_1.name),
(lot_4.id, lot_4.name),
]
self.assertEqual(name_get_res, expected_res)
def test_lot_on_hand_first_no_qty(self):
"""Check name_get does not break if we do not have a lot with qty"""
# Create a few lots with quantities
lot_1 = self._create_lot(self.product, "LOT-000001", 0)
lot_2 = self._create_lot(self.product, "LOT-000002", 0)
lot_3 = self._create_lot(self.product, "LOT-000003", 0)
name_get_res = (
self.env["stock.production.lot"]
.with_context(name_search_qty_on_hand_first=True)
.name_search(args=[("product_id", "=", self.product.id)])
)
expected_res = [
(lot_1.id, lot_1.name),
(lot_2.id, lot_2.name),
(lot_3.id, lot_3.name),
]
self.assertEqual(name_get_res, expected_res)
def test_compute_display_lots_on_hand_first(self):
"""Test computed stored field"""
self.assertTrue(self.delivery_order_picking_type.use_existing_lots)
# Set lots on hand=True is stored properly
self.delivery_order_picking_type.display_lots_on_hand_first = True
self.assertTrue(self.delivery_order_picking_type.display_lots_on_hand_first)
self.assertTrue(self.delivery_order_picking_type.use_existing_lots)
# Unmark use_existing_lots must unmark display_lots_on_hand_first
self.delivery_order_picking_type.use_existing_lots = False
self.assertFalse(self.delivery_order_picking_type.use_existing_lots)
self.assertFalse(self.delivery_order_picking_type.display_lots_on_hand_first)
# Mark use_existing_lots should not change display_lots_on_hand_first
self.delivery_order_picking_type.use_existing_lots = True
self.assertTrue(self.delivery_order_picking_type.use_existing_lots)
self.assertFalse(self.delivery_order_picking_type.display_lots_on_hand_first)
def test_lot_on_hand_first_with_limit(self):
"""Check lots without a qty are at the end of the list"""
# Create a few lots with quantities
lot_1 = self._create_lot(self.product, "LOT-000001", 0)
lot_2 = self._create_lot(self.product, "LOT-000002", 0)
lot_3 = self._create_lot(self.product, "LOT-000003", 0)
lot_4 = self._create_lot(self.product, "LOT-000004", 0)
lot_5 = self._create_lot(self.product, "LOT-000005", 0)
lot_6 = self._create_lot(self.product, "LOT-000006", 0)
self._create_lot(self.product, "LOT-000007", 0)
self._create_lot(self.product, "LOT-000008", 0)
lot_9 = self._create_lot(self.product, "LOT-000009", 5)
lot_10 = self._create_lot(self.product, "LOT-000010", 5)
name_get_res = (
self.env["stock.production.lot"]
.with_context(name_search_qty_on_hand_first=True)
.name_search(args=[("product_id", "=", self.product.id)], limit=8)
)
expected_res = [
(lot_9.id, lot_9.name),
(lot_10.id, lot_10.name),
(lot_1.id, lot_1.name),
(lot_2.id, lot_2.name),
(lot_3.id, lot_3.name),
(lot_4.id, lot_4.name),
(lot_5.id, lot_5.name),
(lot_6.id, lot_6.name),
]
self.assertEqual(name_get_res, expected_res)
| 43.672131
| 5,328
|
809
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo import api, fields, models
class StockPickingType(models.Model):
_inherit = "stock.picking.type"
display_lots_on_hand_first = fields.Boolean(
compute="_compute_display_lots_on_hand_first",
store=True,
readonly=False,
help="When marked, lots that do not have a quantity in stock will be displayed"
" last in the selection",
)
@api.depends("use_existing_lots")
def _compute_display_lots_on_hand_first(self):
"""Reset display_lots_on_hand_first if use_existing_lots is set to False"""
for picking_type in self:
if not picking_type.use_existing_lots:
picking_type.display_lots_on_hand_first = False
| 35.173913
| 809
|
331
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo import fields, models
class StockMove(models.Model):
_inherit = "stock.move"
display_lots_on_hand_first = fields.Boolean(
related="picking_type_id.display_lots_on_hand_first",
readonly=True,
)
| 23.642857
| 331
|
1,949
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo import api, models
from odoo.osv.expression import AND
class ProductionLot(models.Model):
_inherit = "stock.production.lot"
@api.model
def _name_search(self, name="", args=None, operator="ilike", limit=80):
"""Move lots without a qty on hand at the end of the list"""
if self.env.context.get("name_search_qty_on_hand_first"):
args = list(args or [])
with_quantity_domain = AND([args, [("product_qty", ">", 0)]])
with_quantity_count = self.env["stock.production.lot"].search_count(
with_quantity_domain
)
if with_quantity_count >= limit:
args = with_quantity_domain
else:
with_quantity_ids = super()._name_search(
name=name, args=with_quantity_domain, operator=operator, limit=limit
)
without_quantity_ids = super()._name_search(
name=name,
args=AND([args, [("product_qty", "=", 0)]]),
operator=operator,
limit=limit - with_quantity_count,
)
# _name_search is supposed to return a odoo.osv.query.Query object
# that will be evaluated as a list of ids when used in the browse function.
# Since we cannot merge the Query objects to respect the intended order
# in which we want to display the results, we return the list of ids
# that will be used by browse in the name_search implementation.
return (
self.browse(with_quantity_ids).ids
+ self.browse(without_quantity_ids).ids
)
return super()._name_search(
name=name, args=args, operator=operator, limit=limit
)
| 42.369565
| 1,949
|
337
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo import fields, models
class StockPicking(models.Model):
_inherit = "stock.picking"
display_lots_on_hand_first = fields.Boolean(
related="picking_type_id.display_lots_on_hand_first",
readonly=True,
)
| 24.071429
| 337
|
541
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
{
"name": "Sale Line Returned Qty",
"summary": "Track returned quantity of sale order lines.",
"version": "15.0.1.0.0",
"category": "Sales",
"website": "https://github.com/OCA/stock-logistics-workflow",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"license": "LGPL-3",
"installable": True,
"depends": ["sale_stock"],
"data": ["views/sale_order_views.xml"],
}
| 36.066667
| 541
|
2,578
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 ForgeFlow (http://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo.tests import Form, common
class TestSaleLineReturnedQty(common.TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.warehouse = cls.env.ref("stock.warehouse0")
cls.product = cls.env["product.product"].create(
{"name": "test", "type": "product"}
)
cls.env["stock.quant"].create(
{
"product_id": cls.product.id,
"location_id": cls.warehouse.lot_stock_id.id,
"quantity": 100,
}
)
cls.partner = cls.env["res.partner"].create({"name": "test - partner"})
order_form = Form(cls.env["sale.order"])
order_form.partner_id = cls.partner
with order_form.order_line.new() as line_form:
line_form.product_id = cls.product
line_form.product_uom_qty = 10
line_form.price_unit = 1000
cls.order = order_form.save()
def _return_picking(self, picking, qty, to_refund=True):
"""Helper method to create a return of the original picking. It could
be refundable or not"""
return_wiz_form = Form(
self.env["stock.return.picking"].with_context(
active_ids=picking.ids,
active_id=picking.ids[0],
active_model="stock.picking",
)
)
return_wiz = return_wiz_form.save()
return_wiz.product_return_moves.quantity = qty
return_wiz.product_return_moves.to_refund = to_refund
res = return_wiz.create_returns()
return_picking = self.env["stock.picking"].browse(res["res_id"])
self._validate_picking(return_picking)
def _validate_picking(self, picking):
"""Helper method to confirm the pickings"""
for line in picking.move_lines:
line.quantity_done = line.product_uom_qty
picking._action_done()
def test_returned_qty(self):
self.order.action_confirm()
so_line = self.order.order_line[0]
self.assertEqual(so_line.qty_returned, 0.0)
# Partial delivery one
picking = self.order.picking_ids
picking.action_assign()
picking.move_lines.quantity_done = 10.0
picking._action_done()
self.assertEqual(so_line.qty_returned, 0.0)
# Make a return for 5 units
self._return_picking(picking, 5.0, to_refund=True)
self.assertEqual(so_line.qty_returned, 5.0)
| 39.661538
| 2,578
|
1,247
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class SaleOrderLine(models.Model):
_inherit = "sale.order.line"
qty_returned = fields.Float(
compute="_compute_qty_returned",
string="Returned Qty",
store=True,
readonly=True,
compute_sudo=True,
digits="Product Unit of Measure",
default=0.0,
copy=False,
)
@api.depends(
"move_ids.state",
"move_ids.scrapped",
"move_ids.product_uom_qty",
"move_ids.product_uom",
)
def _compute_qty_returned(self):
for line in self:
qty = 0.0
if line.qty_delivered_method == "stock_move":
_, incoming_moves = line._get_outgoing_incoming_moves()
for move in incoming_moves:
if move.state != "done":
continue
qty += move.product_uom._compute_quantity(
move.product_uom_qty,
line.product_uom,
rounding_method="HALF-UP",
)
line.qty_returned = qty
| 31.175
| 1,247
|
618
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Stock Picking Assign Serial Final",
"summary": "Generate serial numbers until to a final serial number",
"version": "15.0.1.0.0",
"development_status": "Beta",
"category": "stock",
"website": "https://github.com/OCA/stock-logistics-workflow",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"depends": ["stock"],
"data": ["wizards/stock_assign_serial_views.xml"],
"maintainers": ["sergio-teruel"],
}
| 38.625
| 618
|
1,219
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests import TransactionCase
from .common import CommonStockPickingAssignSerialFinal
class TestStockPickingAutoCreateLot(
CommonStockPickingAssignSerialFinal, TransactionCase
):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.product = cls._create_product()
cls.product_serial = cls._create_product(tracking="serial")
cls._create_picking()
cls._create_move(product=cls.product_serial, qty=5.0)
def test_wizard_assign_serial_final(self):
self.picking.action_assign()
move = self.picking.move_lines.filtered(
lambda m: m.product_id == self.product_serial
)
wiz = (
self.env["stock.assign.serial"]
.with_context(
default_product_id=move.product_id.id,
default_move_id=move.id,
default_next_serial_number="XZ000001MTR",
)
.create({})
)
self.assertEqual(wiz.next_serial_count, 5)
wiz.final_serial_number = "XZ000007MTR"
self.assertEqual(wiz.next_serial_count, 7)
| 34.828571
| 1,219
|
2,036
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
class CommonStockPickingAssignSerialFinal(object):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
cls.lot_obj = cls.env["stock.production.lot"]
cls.warehouse = cls.env.ref("stock.warehouse0")
cls.picking_type_in = cls.env.ref("stock.picking_type_in")
cls.supplier_location = cls.env.ref("stock.stock_location_suppliers")
cls.supplier = cls.env["res.partner"].create({"name": "Supplier - test"})
@classmethod
def _create_product(cls, tracking="serial", auto=True):
name = "{tracking} - {auto}".format(tracking=tracking, auto=auto)
return cls.env["product.product"].create(
{"name": name, "detailed_type": "product", "tracking": tracking}
)
@classmethod
def _create_picking(cls):
cls.picking = (
cls.env["stock.picking"]
.with_context(default_picking_type_id=cls.picking_type_in.id)
.create(
{
"partner_id": cls.supplier.id,
"picking_type_id": cls.picking_type_in.id,
"location_id": cls.supplier_location.id,
}
)
)
@classmethod
def _create_move(cls, product=None, qty=1.0):
location_dest = cls.picking.picking_type_id.default_location_dest_id
cls.move = cls.env["stock.move"].create(
{
"name": "test-{product}".format(product=product.name),
"product_id": product.id,
"picking_id": cls.picking.id,
"picking_type_id": cls.picking.picking_type_id.id,
"product_uom_qty": qty,
"product_uom": product.uom_id.id,
"location_id": cls.supplier_location.id,
"location_dest_id": location_dest.id,
}
)
| 39.921569
| 2,036
|
1,382
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import re
from odoo import api, fields, models
class AssignSerialFinalMixin(models.AbstractModel):
_name = "assign.serial.final.mixin"
_description = "Mixin for assign last S/N"
_next_serial_field = ""
final_serial_number = fields.Char("Final SN")
next_serial_count = fields.Integer(
compute="_compute_next_serial_count",
store=True,
readonly=False,
)
@api.depends(lambda x: x._get_next_serial_depends())
def _compute_next_serial_count(self):
for rec in self:
if not (rec[rec._next_serial_field] and rec.final_serial_number):
rec.next_serial_count = 0
continue
lot_search = re.search(r"-?\d+\.?\d*", rec[rec._next_serial_field])
start_num = lot_search.group()
lot_search_to = re.search(r"-?\d+\.?\d*", rec.final_serial_number)
end_num = lot_search_to.group()
if start_num and end_num:
rec.next_serial_count = int(end_num) - int(start_num) + 1
else:
rec.next_serial_count = 0
@api.model
def _get_next_serial_depends(self):
if not self._next_serial_field:
return []
return [self._next_serial_field, "final_serial_number"]
| 35.435897
| 1,382
|
411
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import models
class StockMove(models.Model):
_inherit = ["stock.move", "assign.serial.final.mixin"]
_name = "stock.move"
_next_serial_field = "next_serial"
def action_show_details(self):
self.final_serial_number = False
return super().action_show_details()
| 29.357143
| 411
|
338
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import models
class StockAssignSerialNumbers(models.TransientModel):
_inherit = ["stock.assign.serial", "assign.serial.final.mixin"]
_name = "stock.assign.serial"
_next_serial_field = "next_serial_number"
| 33.8
| 338
|
765
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
{
"name": "Stock Picking Product Assortment Availability Inline",
"summary": "Glue module to display stock available when an assortment is defined "
"for a partner",
"version": "15.0.1.0.0",
"category": "Warehouse Management",
"website": "https://github.com/OCA/stock-logistics-workflow",
"author": "Tecnativa, Odoo Community Association (OCA)",
"maintainers": ["Sergio-teruel"],
"license": "AGPL-3",
"installable": True,
"depends": [
"stock_picking_product_assortment",
"stock_picking_product_availability_inline",
],
"data": ["views/stock_picking_view.xml"],
"auto_install": True,
}
| 36.428571
| 765
|
1,641
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests import Form, TransactionCase, tagged
@tagged("post_install", "-at_install")
class TestStockPickingProductAssortmentAvailabilityInline(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.partner = cls.env["res.partner"].create({"name": "Partner"})
cls.product = cls.env["product.product"].create(
{"name": "Product", "type": "product"}
)
cls.warehouse1 = cls.env["stock.warehouse"].create(
{"name": "Warehouse 1", "code": "AI1"}
)
StockQuant = cls.env["stock.quant"]
StockQuant.create(
{
"product_id": cls.product.id,
"product_uom_id": cls.product.uom_id.id,
"location_id": cls.warehouse1.lot_stock_id.id,
"quantity": 10.00,
}
)
def test_stock_picking_product_rec_name(self):
self.env.ref("product.decimal_product_uom").write({"digits": 3})
picking_form = Form(
self.env["stock.picking"].with_context(
warehouse=self.warehouse1.id, sp_product_stock_inline=True
)
)
picking_form.partner_id = self.partner
picking_form.picking_type_id = self.env.ref("stock.picking_type_out")
with picking_form.move_ids_without_package.new() as line_form:
line_form.product_id = self.product
self.assertTrue(
line_form.product_id.display_name.endswith("(10.000 Units)")
)
| 39.071429
| 1,641
|
623
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
{
"name": "Stock Move Consumable Location From Putaway",
"summary": "Use putaway location as source of move lines for consumables",
"version": "15.0.1.0.0",
"development_status": "Alpha",
"category": "Inventory/Inventory",
"website": "https://github.com/OCA/stock-logistics-workflow",
"author": "Camptocamp, Odoo Community Association (OCA)",
"maintainers": ["grindtildeath"],
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": [
"stock",
],
}
| 34.611111
| 623
|
1,669
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo.tests import Form
from odoo.addons.stock.tests.common import TestStockCommon
class TestConsumableMoveLocation(TestStockCommon):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.consu_product = cls.env["product.product"].create(
{"name": "Consumable", "type": "consu"}
)
cls.putaway_location = cls.env["stock.location"].create(
{
"name": "putaway loc for consumable",
"usage": "internal",
"location_id": cls.stock_location,
}
)
cls.putaway = cls.env["stock.putaway.rule"].create(
{
"product_id": cls.consu_product.id,
"location_in_id": cls.stock_location,
"location_out_id": cls.putaway_location.id,
}
)
def test_outgoing_move(self):
move_form = Form(self.env["stock.move"])
move_form.product_id = self.consu_product
move_form.location_id = self.env["stock.location"].browse(self.stock_location)
move_form.location_dest_id = self.env["stock.location"].browse(
self.pack_location
)
move = move_form.save()
self.assertEqual(move.state, "draft")
self.assertEqual(move.location_id.id, self.stock_location)
self.assertFalse(move.move_line_ids)
move._action_confirm()
self.assertEqual(move.state, "assigned")
self.assertTrue(move.move_line_ids)
self.assertEqual(move.move_line_ids.location_id, self.putaway_location)
| 37.931818
| 1,669
|
653
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo import models
class StockMove(models.Model):
_inherit = "stock.move"
def _prepare_move_line_vals(self, quantity=None, reserved_quant=None):
res = super()._prepare_move_line_vals(
quantity=quantity, reserved_quant=reserved_quant
)
if (
self.product_id.detailed_type == "consu"
and self.location_id.usage == "internal"
):
putaway_loc = self.location_id._get_putaway_strategy(self.product_id)
res["location_id"] = putaway_loc.id
return res
| 34.368421
| 653
|
582
|
py
|
PYTHON
|
15.0
|
# Copyright 2015-17 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Stock Picking Show Backorder",
"version": "15.0.1.0.1",
"category": "Warehouse Management",
"summary": "Provides a new field on stock pickings, allowing to display "
"the corresponding backorders.",
"author": "ForgeFlow, " "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/stock-logistics-workflow",
"depends": ["stock"],
"data": ["views/stock_view.xml"],
"installable": True,
"license": "AGPL-3",
}
| 36.375
| 582
|
1,910
|
py
|
PYTHON
|
15.0
|
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo.tests.common import TransactionCase
class TestStockPickingShowBackorder(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.src_location = cls.env.ref("stock.stock_location_stock")
cls.dest_location = cls.env.ref("stock.stock_location_customers")
cls.product = cls.env["product.product"].create({"name": "Test product"})
cls.partner = cls.env["res.partner"].create({"name": "Test partner"})
cls.picking = cls.env["stock.picking"].create(
{
"partner_id": cls.partner.id,
"picking_type_id": cls.env.ref("stock.picking_type_out").id,
"location_id": cls.src_location.id,
"location_dest_id": cls.dest_location.id,
}
)
cls.move = cls.env["stock.move"].create(
{
"name": "/",
"picking_id": cls.picking.id,
"product_id": cls.product.id,
"product_uom_qty": 20,
"product_uom": cls.product.uom_id.id,
"location_id": cls.src_location.id,
"location_dest_id": cls.dest_location.id,
}
)
def test_stock_picking_show_backorder(self):
# Picking in draf state
self.assertEqual(self.picking.state, "draft")
# Confirm picking
self.picking.action_confirm()
self.assertEqual(self.picking.state, "assigned")
move_line = self.env["stock.move.line"].search(
[("picking_id", "=", self.picking.id)], limit=1
)
move_line.qty_done = 1.0
self.picking._action_done()
self.assertEqual(self.picking.state, "done")
# The backorder should be created
self.assertEqual(len(self.picking.backorder_ids), 1, "It should be 1")
| 40.638298
| 1,910
|
396
|
py
|
PYTHON
|
15.0
|
# Copyright 2015-17 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class StockPicking(models.Model):
_inherit = "stock.picking"
backorder_ids = fields.One2many(
comodel_name="stock.picking",
inverse_name="backorder_id",
copy=False,
string="Backorders",
readonly=True,
)
| 24.75
| 396
|
671
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Camptocamp
# Copyright 2020-2021 Jacques-Etienne Baudoux (BCIM) <je@bcim.be>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Delivery Procurement Group Carrier",
"Summary": "Record the carrier on the procurement group",
"version": "15.0.1.0.0",
"development_status": "Alpha",
"author": "Camptocamp, BCIM, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/stock-logistics-workflow",
"category": "Warehouse Management",
"depends": ["sale_stock", "delivery"],
"data": [
"views/procurement_group.xml",
],
"installable": True,
"license": "AGPL-3",
}
| 35.315789
| 671
|
1,928
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Camptocamp (https://www.camptocamp.com)
# Copyright 2020 Jacques-Etienne Baudoux (BCIM) <je@bcim.be>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests import tagged
from odoo.addons.sale.tests.common import TestSaleCommonBase
@tagged("post_install", "-at_install")
class TestProcurementGroupCarrier(TestSaleCommonBase):
# FIXME: TestSale is very heavy and create tons of records w/ no tracking disable
# for every test. Move to TransactionCase!
def setUp(self):
super().setUp()
self.carrier1 = self.env["delivery.carrier"].create(
{
"name": "My Test Carrier",
"product_id": self.env.ref("delivery.product_product_delivery").id,
}
)
self.partner = self.env["res.partner"].create({"name": "Test Partner"})
def test_sale_procurement_group_carrier(self):
"""Check the SO procurement group contains the carrier on SO confirmation"""
product = self.env.ref("product.product_delivery_01")
sale_order_line_vals = {
"name": product.name,
"product_id": product.id,
"product_uom_qty": 1,
"product_uom": product.uom_id.id,
"price_unit": product.list_price,
}
sale_order_vals = {
"partner_id": self.partner.id,
"partner_invoice_id": self.partner.id,
"partner_shipping_id": self.partner.id,
"carrier_id": self.carrier1.id,
"order_line": [(0, 0, sale_order_line_vals)],
"pricelist_id": self.env.ref("product.list0").id,
}
so = self.env["sale.order"].create(sale_order_vals)
so.action_confirm()
self.assertTrue(so.picking_ids)
self.assertEqual(so.procurement_group_id.carrier_id, so.carrier_id)
so.action_draft()
self.assertFalse(so.procurement_group_id)
| 41.021277
| 1,928
|
657
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Camptocamp (https://www.camptocamp.com)
# Copyright 2020-2021 Jacques-Etienne Baudoux (BCIM) <je@bcim.be>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import models
class SaleOrder(models.Model):
_inherit = "sale.order"
def action_draft(self):
res = super().action_draft()
self.procurement_group_id = False
return res
class SaleOrderLine(models.Model):
_inherit = "sale.order.line"
def _prepare_procurement_group_vals(self):
vals = super()._prepare_procurement_group_vals()
vals["carrier_id"] = self.order_id.carrier_id.id
return vals
| 28.565217
| 657
|
380
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Camptocamp (https://www.camptocamp.com)
# Copyright 2020-2021 Jacques-Etienne Baudoux (BCIM) <je@bcim.be>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class ProcurementGroup(models.Model):
_inherit = "procurement.group"
carrier_id = fields.Many2one("delivery.carrier", string="Delivery Method")
| 34.545455
| 380
|
643
|
py
|
PYTHON
|
15.0
|
# Copyright 2017-2022 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
{
"name": "Stock Picking Operation Quick Change",
"summary": "Change location of all picking operations",
"version": "15.0.1.1.0",
"category": "Warehouse",
"website": "https://github.com/OCA/stock-logistics-workflow",
"author": "Tecnativa, " "Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"depends": ["stock"],
"data": [
"security/ir.model.access.csv",
"wizards/stock_picking_wizard_view.xml",
"views/stock_picking_view.xml",
],
}
| 33.842105
| 643
|
6,249
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.exceptions import UserError
from odoo.tests import tagged
from odoo.tests.common import TransactionCase
@tagged("post_install", "-at_install")
class TestOperationQuickChange(TransactionCase):
def setUp(self):
super().setUp()
self.Location = self.env["stock.location"]
self.PickingType = self.env["stock.picking.type"]
self.Picking = self.env["stock.picking"]
self.Product = self.env["product.template"]
self.Wizard = self.env["stock.picking.operation.wizard"]
self.warehouse = self.env["stock.warehouse"].create(
{"name": "warehouse - test", "code": "WH-TEST"}
)
# self.warehouse.lot_stock_id.id
self.product = self.Product.create(
{
"name": "Product - Test",
"type": "product",
"list_price": 100.00,
"standard_price": 100.00,
}
)
self.qty_on_hand(self.product.product_variant_ids)
self.product2 = self.Product.create(
{
"name": "Product2 - Test",
"type": "product",
"list_price": 100.00,
"standard_price": 100.00,
}
)
self.qty_on_hand(self.product2.product_variant_ids)
self.customer = self.env["res.partner"].create({"name": "Customer - test"})
self.picking_type = self.PickingType.search(
[("warehouse_id", "=", self.warehouse.id), ("code", "=", "outgoing")]
)
self.picking = self.Picking.create(
{
"name": "picking - test 01",
"location_id": self.warehouse.lot_stock_id.id,
"location_dest_id": self.warehouse.wh_output_stock_loc_id.id,
"picking_type_id": self.picking_type.id,
"move_lines": [
(
0,
0,
{
"name": self.product.name,
"product_id": self.product.product_variant_ids.id,
"product_uom_qty": 20.0,
"product_uom": self.product.uom_id.id,
"location_id": self.warehouse.lot_stock_id.id,
"location_dest_id": self.warehouse.wh_output_stock_loc_id.id,
},
),
(
0,
0,
{
"name": self.product.name,
"product_id": self.product2.product_variant_ids.id,
"product_uom_qty": 60.0,
"product_uom": self.product.uom_id.id,
"location_id": self.warehouse.lot_stock_id.id,
"location_dest_id": self.warehouse.wh_output_stock_loc_id.id,
},
),
],
}
)
def qty_on_hand(self, product):
self.env["stock.quant"].with_context(inventory_mode=True).create(
{
"product_id": product.id,
"inventory_quantity": 200,
"location_id": self.warehouse.lot_stock_id.id,
}
)._apply_inventory()
def test_picking_operation_change_location_dest_all(self):
self.picking.action_assign()
new_location_dest_id = self.Location.create(
{
"name": "New Test Customer Location",
"location_id": self.picking.location_dest_id.location_id.id,
}
)
wiz = self.Wizard.with_context(
active_model=self.picking._name,
active_ids=self.picking.ids,
).create({"new_location_dest_id": new_location_dest_id.id, "change_all": True})
move_lines = self.picking.mapped("move_line_ids")
self.assertEqual(wiz.location_dest_id, self.picking.location_dest_id)
self.assertEqual(wiz.old_location_dest_id, move_lines[:1].location_dest_id)
wiz.action_apply()
move_lines = self.picking.mapped("move_line_ids.location_dest_id")
self.assertEqual(len(move_lines), 1)
def test_picking_operation_change_location_dest(self):
new_location_dest_id = self.Location.create(
{
"name": "New Test Customer Location",
"location_id": self.picking.location_dest_id.location_id.id,
}
)
other_location_dest_id = self.Location.create(
{
"name": "New Test Customer Location",
"location_id": self.picking.location_dest_id.location_id.id,
}
)
self.picking.action_assign()
move_lines = self.picking.mapped("move_line_ids")
move_lines[:1].write({"location_dest_id": other_location_dest_id.id})
wiz = self.Wizard.with_context(
active_model=self.picking._name,
active_ids=self.picking.ids,
).create(
{
"old_location_dest_id": self.picking.location_dest_id.id,
"new_location_dest_id": new_location_dest_id.id,
}
)
wiz.action_apply()
move_lines = self.picking.mapped("move_line_ids.location_dest_id")
self.assertEqual(len(move_lines), 2)
def test_picking_operation_change_location_dest_failed(self):
self.picking.action_assign()
for move in self.picking.move_lines:
move.quantity_done = 1
self.picking._action_done()
new_location_dest_id = self.Location.create(
{
"name": "New Test Customer Location",
"location_id": self.picking.location_dest_id.location_id.id,
}
)
wiz = self.Wizard.with_context(
active_model=self.picking._name,
active_ids=self.picking.ids,
).create({"new_location_dest_id": new_location_dest_id.id, "change_all": True})
with self.assertRaises(UserError):
wiz.action_apply()
| 40.843137
| 6,249
|
4,734
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
from odoo.exceptions import UserError
class StockPickingOperationWizard(models.TransientModel):
_name = "stock.picking.operation.wizard"
_description = "Stock Picking Operation Wizard"
def _prepare_default_values(self, picking):
return {
"picking_id": picking.id,
"location_dest_id": picking.location_dest_id.id,
}
@api.model
def default_get(self, fields):
res = super().default_get(fields)
active_model = self.env.context["active_model"]
active_ids = self.env.context["active_ids"] or []
picking = self.env[active_model].browse(active_ids)
res.update(self._prepare_default_values(picking))
return res
def _default_old_dest_location_id(self):
stock_picking_obj = self.env["stock.picking"]
pickings = stock_picking_obj.browse(self.env.context["active_ids"])
first_move_line = pickings.mapped("move_line_ids")[:1]
return first_move_line.location_dest_id.id
def _get_allowed_locations(self):
return ["internal"]
def _get_allowed_location_domain(self):
return [("usage", "in", self._get_allowed_locations())]
def _get_allowed_picking_states(self):
return ["assigned"]
picking_id = fields.Many2one(comodel_name="stock.picking")
location_dest_id = fields.Many2one(
comodel_name="stock.location",
string="Actual destination location",
required=True,
readonly=True,
)
old_location_dest_id = fields.Many2one(
comodel_name="stock.location",
string="Old destination location",
default=_default_old_dest_location_id,
domain=lambda self: self._get_allowed_location_domain(),
)
new_location_dest_id = fields.Many2one(
comodel_name="stock.location",
string="New destination location",
required=True,
domain=lambda self: self._get_allowed_location_domain(),
)
allowed_product_ids = fields.Many2many(
comodel_name="product.product",
compute="_compute_allowed_product_ids",
)
product_id = fields.Many2one(
comodel_name="product.product",
domain="[('id', 'in', allowed_product_ids)]",
)
change_all = fields.Boolean(
help="Check if you want change all operations without filter "
"by old location",
)
@api.depends("picking_id")
def _compute_allowed_product_ids(self):
for record in self:
record.allowed_product_ids = record.picking_id.move_lines.mapped(
"product_id"
)
def check_allowed_pickings(self, pickings):
forbidden_pickings = pickings.filtered(
lambda x: x.state not in self._get_allowed_picking_states()
)
if forbidden_pickings:
raise UserError(
_(
"You can not change operations destination location if "
"picking state is not in %s"
)
% ",".join(self._get_allowed_picking_states())
)
pickings_with_chained_moves = pickings.filtered(
lambda x: x.move_lines.mapped("move_dest_ids")
)
if pickings_with_chained_moves:
raise UserError(
_(
"You cannot change destination location if any of the moves "
"has a destination move."
)
)
def action_apply(self):
stock_picking_obj = self.env["stock.picking"]
pickings = stock_picking_obj.browse(self.env.context["active_ids"])
self.check_allowed_pickings(pickings)
move_lines = pickings.mapped("move_line_ids")
vals = {"location_dest_id": self.new_location_dest_id.id}
if self.change_all:
# Write all operations destination location
move_lines.write(vals)
else:
matched_op = move_lines
# Only write operations destination location if the location is
# the same that old location value
if self.old_location_dest_id:
matched_op = matched_op.filtered(
lambda x: x.location_dest_id == self.old_location_dest_id
)
# Only write operations destination location if the product is the same
if self.product_id:
matched_op = matched_op.filtered(
lambda x: x.product_id == self.product_id
)
matched_op.write(vals)
return {"type": "ir.actions.act_window_close"}
| 36.984375
| 4,734
|
553
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Stock Delivery Note",
"summary": """
This module allows to fill in a delivery note that will be displayed
on delivery report""",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"author": "ACSONE SA/NV,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/stock-logistics-workflow",
"depends": ["stock", "delivery"],
"data": ["views/stock_picking.xml", "reports/report_picking.xml"],
}
| 36.866667
| 553
|
284
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class StockPicking(models.Model):
_inherit = "stock.picking"
delivery_note = fields.Text(help="This field will be displayed on delivery report")
| 25.818182
| 284
|
501
|
py
|
PYTHON
|
15.0
|
# Copyright 2014-2017 Pedro M. Baeza <pedro.baeza@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Show returns on stock pickings",
"version": "15.0.1.0.0",
"author": "Tecnativa, " "Odoo Community Association (OCA)",
"category": "Warehouse Management",
"website": "https://github.com/OCA/stock-logistics-workflow",
"license": "AGPL-3",
"depends": ["stock"],
"data": ["views/stock_picking_view.xml"],
"installable": True,
}
| 35.785714
| 501
|
2,837
|
py
|
PYTHON
|
15.0
|
# Copyright 2014-2017 Pedro M. Baeza <pedro.baeza@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests.common import Form, TransactionCase, tagged
@tagged("post_install", "-at_install")
class TestStockPickingShowReturn(TransactionCase):
def setUp(self):
super(TestStockPickingShowReturn, self).setUp()
self.product = self.env["product.product"].create({"name": "Test product"})
picking_type = self.env.ref("stock.picking_type_internal")
self.picking = self.env["stock.picking"].create(
{
"picking_type_id": picking_type.id,
"location_id": picking_type.default_location_src_id.id,
"location_dest_id": picking_type.default_location_dest_id.id,
"move_lines": [
(
0,
0,
{
"name": self.product.name,
"location_id": picking_type.default_location_src_id.id,
"location_dest_id": picking_type.default_location_dest_id.id,
"product_id": self.product.id,
"product_uom": self.product.uom_id.id,
"product_uom_qty": 1,
},
)
],
}
)
def get_return_picking_wizard(self, picking):
stock_return_picking_form = Form(
self.env["stock.return.picking"].with_context(
active_ids=picking.ids,
active_id=picking.ids[0],
active_model="stock.picking",
)
)
return stock_return_picking_form.save()
def test_returned_ids_field(self):
self.picking.action_assign()
self.picking.move_line_ids.qty_done = 1
self.picking._action_done()
wizard = self.get_return_picking_wizard(self.picking)
wizard.create_returns()
self.picking._compute_returned_ids()
self.assertTrue(self.picking.returned_ids)
def test_source_picking_id_field(self):
self.picking.action_assign()
self.picking.move_line_ids.qty_done = 1
self.picking._action_done()
wizard = self.get_return_picking_wizard(self.picking)
wizard.create_returns()
self.picking._compute_returned_ids()
picking_returned = self.picking.returned_ids[0]
# Get first picking returned to check if origin is self.picking
picking_origin = picking_returned.source_picking_id
self.assertEqual(picking_origin, self.picking)
# Open origin returned picking form view
action = picking_returned.action_show_source_picking()
self.assertEqual(action["res_id"], self.picking.id)
| 42.343284
| 2,837
|
1,340
|
py
|
PYTHON
|
15.0
|
# Copyright 2014-2017 Pedro M. Baeza <pedro.baeza@tecnativa.com>
# Copyright 2018-2019 Sergio Teruel <sergio.teruel@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
from odoo.fields import first
class StockPicking(models.Model):
_inherit = "stock.picking"
returned_ids = fields.Many2many(
comodel_name="stock.picking",
compute="_compute_returned_ids",
string="Returned pickings",
)
source_picking_id = fields.Many2one(
comodel_name="stock.picking",
compute="_compute_source_picking_id",
string="Source picking",
)
def _compute_returned_ids(self):
for picking in self:
picking.returned_ids = picking.mapped(
"move_lines.returned_move_ids.picking_id"
)
@api.depends("move_lines.origin_returned_move_id")
def _compute_source_picking_id(self):
"""Get source piking from this picking. Only one origin is possible."""
for picking in self:
picking.source_picking_id = first(
picking.mapped("move_lines.origin_returned_move_id.picking_id")
)
def action_show_source_picking(self):
"""Open source picking form action"""
return self.source_picking_id.get_formview_action()
| 34.358974
| 1,340
|
526
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Stock Picking Purchase Order Link",
"summary": "Link between picking and purchase order",
"version": "15.0.1.0.1",
"license": "AGPL-3",
"author": "ForgeFlow S.L., Odoo Community Association (OCA)",
"website": "https://github.com/OCA/stock-logistics-workflow",
"application": False,
"installable": True,
"depends": ["purchase_stock"],
"data": ["views/stock_picking_view.xml"],
}
| 35.066667
| 526
|
2,178
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 ForgeFlow S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from datetime import date
from odoo.tests.common import TransactionCase
class TestStockPickingPurchaseOrderLink(TransactionCase):
def setUp(self):
super(TestStockPickingPurchaseOrderLink, self).setUp()
self.stock_location_obj = self.env["stock.location"]
self.stock_picking_type_obj = self.env["stock.picking.type"]
self.stock_picking_obj = self.env["stock.picking"]
self.product_product_obj = self.env["product.product"]
self.warehouse = self.env["stock.warehouse"].create(
{"name": "warehouse - test", "code": "WH-TEST"}
)
self.product = self.product_product_obj.create(
{
"name": "product_template_obj - Test",
"type": "product",
"standard_price": 100.00,
}
)
self.partner = self.env["res.partner"].create({"name": "Vendor - test"})
self.picking_type = self.stock_picking_type_obj.search(
[("warehouse_id", "=", self.warehouse.id), ("code", "=", "incoming")]
)
purchase_order = self.env["purchase.order"].create(
{
"partner_id": self.partner.id,
"order_line": [
(
0,
0,
{
"name": self.product.name,
"product_id": self.product.id,
"product_qty": 1.0,
"product_uom": self.product.uom_po_id.id,
"price_unit": 10.0,
"date_planned": date.today(),
},
)
],
}
)
purchase_order.button_confirm()
self.picking = self.stock_picking_obj.search(
[("purchase_id", "=", purchase_order.id)]
)
def test_picking_to_sale_order(self):
result = self.picking.action_view_purchase_order()
self.assertEqual(result["res_id"], self.picking.purchase_id.id)
| 38.210526
| 2,178
|
665
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 ForgeFlow S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
class StockPicking(models.Model):
_inherit = "stock.picking"
def action_view_purchase_order(self):
"""This function returns an action that display existing purchase order
of given picking.
"""
self.ensure_one()
action = self.env["ir.actions.actions"]._for_xml_id(
"purchase.purchase_form_action"
)
form = self.env.ref("purchase.purchase_order_form")
action["views"] = [(form.id, "form")]
action["res_id"] = self.purchase_id.id
return action
| 31.666667
| 665
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.