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
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
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
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
662
py
PYTHON
15.0
# Copyright 2015 Pedro M. Baeza # Copyright 2017 Vicent Cubells - Tecnativa <vicent.cubells@tecnativa.com> # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { "name": "Account netting", "version": "15.0.1.0.0", "summary": "Compensate AR/AP accounts from the same partner", "category": "Accounting & Finance", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "website": "https://github.com/OCA/account-financial-tools", "depends": ["account"], "data": [ "security/ir.model.access.csv", "wizards/account_move_make_netting_view.xml", ], "installable": True, }
34.842105
662
8,750
py
PYTHON
15.0
# Copyright 2015 Pedro M. Baeza # Copyright 2017 Tecnativa - Vicent Cubells # Copyright 2022 Tecnativa - Víctor Martínez # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from datetime import datetime import odoo.tests.common as common from odoo.exceptions import ValidationError from odoo.tests import Form, tagged @tagged("post_install") class TestAccountNetting(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() res_users_account_manager = cls.env.ref("account.group_account_manager") partner_manager = cls.env.ref("base.group_partner_manager") cls.env.user.write( {"groups_id": [(6, 0, [res_users_account_manager.id, partner_manager.id])]} ) cls.company = cls.env.ref("base.main_company") # only adviser can create an account cls.aa_model = cls.env["account.account"] cls.account_receivable = cls._get_account(cls, "receivable") cls.account_payable = cls._get_account(cls, "payable") cls.account_revenue = cls._get_account(cls, "revenue") cls.account_expense = cls._get_account(cls, "expenses") cls.partner_model = cls.env["res.partner"] cls.partner = cls._create_partner(cls, "Supplier/Customer") cls.partner1 = cls._create_partner(cls, "Supplier/Customer 1") cls.miscellaneous_journal = cls.env["account.journal"].search( [("type", "=", "general")], limit=1 ) # We need a product with taxes at 0 so that the amounts are as expected. cls.account_tax = cls.env["account.tax"].create( {"name": "0%", "amount_type": "fixed", "type_tax_use": "sale", "amount": 0} ) cls.product = cls.env["product.product"].create( { "name": "Product Test", "list_price": 10, "taxes_id": [(6, 0, [cls.account_tax.id])], } ) out_invoice_partner = cls._create_move(cls, "out_invoice", cls.partner, 100) out_invoice_partner.action_post() cls.move_line_1 = out_invoice_partner.line_ids.filtered( lambda x: x.account_id == cls.account_receivable ) in_invoice_partner = cls._create_move(cls, "in_invoice", cls.partner, 1200) in_invoice_partner.action_post() cls.move_line_2 = in_invoice_partner.line_ids.filtered( lambda x: x.account_id == cls.account_payable ) cls.move_line_3 = in_invoice_partner.line_ids.filtered( lambda x: x.account_id == cls.account_expense ) in_invoice_partner1 = cls._create_move(cls, "in_invoice", cls.partner1, 200) in_invoice_partner1.action_post() cls.move_line_4 = in_invoice_partner1.line_ids.filtered( lambda x: x.account_id == cls.account_payable ) in_refund_partner1 = cls._create_move(cls, "in_refund", cls.partner1, 200) in_refund_partner1.action_post() cls.move_line_5 = in_refund_partner1.line_ids.filtered( lambda x: x.account_id == cls.account_payable ) in_refund_partner1 = cls._create_move(cls, "in_refund", cls.partner1, 200) in_refund_partner1.action_post() cls.move_line_6 = in_refund_partner1.line_ids.filtered( lambda x: x.account_id == cls.account_payable ) def _get_account(self, user_type): user_type_ref = "account.data_account_type_%s" % user_type return self.aa_model.search( [ ("user_type_id", "=", self.env.ref(user_type_ref).id), ("company_id", "=", self.company.id), ], limit=1, ) def _create_partner(self, name): return self.partner_model.create( { "name": name, "property_account_receivable_id": self.account_receivable.id, "property_account_payable_id": self.account_payable.id, } ) def _create_move(self, move_type, partner, price): move_form = Form( self.env["account.move"].with_context( default_move_type=move_type, ) ) move_form.partner_id = partner move_form.invoice_date = datetime.now() with move_form.invoice_line_ids.new() as line_form: line_form.product_id = self.product line_form.price_unit = price return move_form.save() def test_compensation(self): # Test exception line 33 from account_move_make_netting obj = self.env["account.move.make.netting"].with_context( active_ids=[self.move_line_1.id] ) with self.assertRaises(ValidationError): wizard = obj.create( { "move_line_ids": [(6, 0, [self.move_line_1.id])], "journal_id": self.miscellaneous_journal.id, } ) # Test exception line 39 from account_move_make_netting obj = self.env["account.move.make.netting"].with_context( active_ids=[self.move_line_1.id, self.move_line_3.id] ) with self.assertRaises(ValidationError): wizard = obj.create( { "move_line_ids": [ (6, 0, [self.move_line_1.id, self.move_line_3.id]) ], "journal_id": self.miscellaneous_journal.id, } ) # Test exception line 45 from account_move_make_netting obj = self.env["account.move.make.netting"].with_context( active_ids=[self.move_line_4.id, self.move_line_5.id] ) with self.assertRaises(ValidationError): wizard = obj.create( { "move_line_ids": [ (6, 0, [self.move_line_4.id, self.move_line_5.id]) ], "journal_id": self.miscellaneous_journal.id, } ) # Test exception line 42 from account_move_make_netting moves = self.env["account.move.line"].browse( [self.move_line_4.id, self.move_line_5.id] ) moves.reconcile() obj = self.env["account.move.make.netting"].with_context( active_ids=[self.move_line_4.id, self.move_line_5.id] ) with self.assertRaises(ValidationError): wizard = obj.create( { "move_line_ids": [ (6, 0, [self.move_line_4.id, self.move_line_5.id]) ], "journal_id": self.miscellaneous_journal.id, } ) # Test exception line 52 from account_move_make_netting obj = self.env["account.move.make.netting"].with_context( active_ids=[self.move_line_1.id, self.move_line_6.id] ) with self.assertRaises(ValidationError): wizard = obj.create( { "move_line_ids": [ (6, 0, [self.move_line_1.id, self.move_line_6.id]) ], "journal_id": self.miscellaneous_journal.id, } ) obj = self.env["account.move.make.netting"].with_context( active_ids=[self.move_line_1.id, self.move_line_2.id] ) wizard = obj.create( { "move_line_ids": [(6, 0, [self.move_line_1.id, self.move_line_2.id])], "journal_id": self.miscellaneous_journal.id, } ) res = wizard.button_compensate() move = self.env["account.move"].browse(res["res_id"]) self.assertEqual( len(move.line_ids), 2, "AR/AP netting move has an incorrect line number" ) move_line_receivable = move.line_ids.filtered( lambda x: x.account_id == self.account_receivable ) self.assertEqual( move_line_receivable.credit, 100, "Incorrect credit amount for receivable move line", ) self.assertTrue( move_line_receivable.reconciled and move_line_receivable.full_reconcile_id, "Receivable move line should be totally reconciled", ) move_line_payable = move.line_ids.filtered( lambda x: x.account_id == self.account_payable ) self.assertEqual( move_line_payable.debit, 100, "Incorrect debit amount for payable move line" ) self.assertTrue( move_line_payable.reconciled and not move_line_payable.full_reconcile_id, "Receivable move line should be partially reconciled", )
41.459716
8,748
5,370
py
PYTHON
15.0
# Copyright 2015 Pedro M. Baeza # Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import _, api, exceptions, fields, models class AccountMoveMakeNetting(models.TransientModel): _name = "account.move.make.netting" _description = "Wizard to generate account moves for netting" journal_id = fields.Many2one( comodel_name="account.journal", required=True, domain="[('type', '=', 'general')]", ) move_line_ids = fields.Many2many(comodel_name="account.move.line") balance = fields.Float(readonly=True) balance_type = fields.Selection( selection=[("pay", "To pay"), ("receive", "To receive")], readonly=True, ) @api.model def default_get(self, fields_list): if len(self.env.context.get("active_ids", [])) < 2: raise exceptions.ValidationError( _("You should compensate at least 2 journal entries.") ) move_lines = self.env["account.move.line"].browse( self.env.context["active_ids"] ) if any( x not in ("payable", "receivable") for x in move_lines.mapped("account_id.user_type_id.type") ): raise exceptions.ValidationError( _("All entries must have a receivable or payable account") ) if any(move_lines.mapped("reconciled")): raise exceptions.ValidationError(_("All entries mustn't been reconciled")) if len(move_lines.mapped("account_id")) == 1: raise exceptions.ValidationError( _( "The 'Compensate' function is intended to balance " "operations on different accounts for the same partner.\n" "In this case all selected entries belong to the same " "account.\n Please use the 'Reconcile' function." ) ) if len(move_lines.mapped("partner_id")) != 1: raise exceptions.ValidationError( _( "All entries should have a partner and the partner must " "be the same for all." ) ) res = super().default_get(fields_list) res["move_line_ids"] = [(6, 0, move_lines.ids)] debit_move_lines_debit = move_lines.filtered("debit") credit_move_lines_debit = move_lines.filtered("credit") balance = abs(sum(debit_move_lines_debit.mapped("amount_residual"))) - abs( sum(credit_move_lines_debit.mapped("amount_residual")) ) res["balance"] = abs(balance) res["balance_type"] = "pay" if balance < 0 else "receive" return res def button_compensate(self): self.ensure_one() # Create account move move = self.env["account.move"].create( {"ref": _("AR/AP netting"), "journal_id": self.journal_id.id} ) # Group amounts by account account_groups = self.move_line_ids.read_group( [("id", "in", self.move_line_ids.ids)], ["account_id", "amount_residual"], ["account_id"], ) debtors = [] creditors = [] total_debtors = 0 total_creditors = 0 for account_group in account_groups: balance = account_group["amount_residual"] group_vals = { "account_id": account_group["account_id"][0], "balance": abs(balance), } if balance > 0: debtors.append(group_vals) total_debtors += balance else: creditors.append(group_vals) total_creditors += abs(balance) # Create move lines netting_amount = min(total_creditors, total_debtors) field_map = {1: "debit", 0: "credit"} move_lines = [] for i, group in enumerate([debtors, creditors]): available_amount = netting_amount for account_group in group: if account_group["balance"] > available_amount: amount = available_amount else: amount = account_group["balance"] move_line_vals = { field_map[i]: amount, "partner_id": self.move_line_ids[0].partner_id.id, "name": move.ref, "account_id": account_group["account_id"], } move_lines.append((0, 0, move_line_vals)) available_amount -= account_group["balance"] if available_amount <= 0: break if move_lines: move.write({"line_ids": move_lines}) move.action_post() # Make reconciliation for move_line in move.line_ids: to_reconcile = move_line + self.move_line_ids.filtered( lambda x: x.account_id == move_line.account_id ) to_reconcile.reconcile() # Open created move action = self.env["ir.actions.act_window"]._for_xml_id( "account.action_move_journal_line" ) action["view_mode"] = "form" del action["views"] del action["view_id"] action["res_id"] = move.id return action
39.777778
5,370
619
py
PYTHON
15.0
# Copyright 2010-2014 Camptocamp - Vincent Renaville # Copyright 2016 Tecnativa - Vicent Cubells # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Balance on journal items", "summary": "Display balance totals in move line view", "version": "15.0.1.1.0", "category": "Accounting", "website": "https://github.com/OCA/account-financial-tools", "author": "Camptocamp," "Tecnativa," "Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["account"], "data": ["views/account_move_line_view.xml"], }
38.6875
619
488
py
PYTHON
15.0
# Copyright 2021 ForgeFlow, S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Assets Management Menu", "version": "15.0.1.0.0", "license": "AGPL-3", "depends": ["account_asset_management", "account_usability"], "author": "ForgeFlow, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "category": "Accounting & Finance", "data": ["views/menuitem.xml"], "auto_install": True, }
34.857143
488
505
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Account Move Fiscal Month", "summary": """Display the fiscal month on journal entries/item""", "version": "15.0.1.0.0", "license": "AGPL-3", "author": "ACSONE SA/NV,Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "depends": ["account_fiscal_month"], "data": ["views/account_move.xml", "views/account_move_line.xml"], }
38.846154
505
6,387
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.fields import Date from odoo.tests.common import TransactionCase class TestAccountMoveFiscalMonth(TransactionCase): def setUp(self): super(TestAccountMoveFiscalMonth, self).setUp() self.AccountObj = self.env["account.account"] self.AccountJournalObj = self.env["account.journal"] self.AccountMoveObj = self.env["account.move"] self.DateRangeObj = self.env["date.range"] self.bank_journal = self.AccountJournalObj.search( [("type", "=", "bank")], limit=1 ) self.account_type_recv = self.env.ref("account.data_account_type_receivable") self.account_type_rev = self.env.ref("account.data_account_type_revenue") self.account_recv = self.AccountObj.create( { "code": "RECV_DR", "name": "Receivable (test)", "reconcile": True, "user_type_id": self.account_type_recv.id, } ) self.account_sale = self.AccountObj.create( { "code": "SALE_DR", "name": "Receivable (sale)", "reconcile": True, "user_type_id": self.account_type_rev.id, } ) self.date_range_type_month = self.env.ref( "account_fiscal_month.date_range_fiscal_month" ) self.date_range_january_2017 = self.DateRangeObj.create( { "name": "January 2017", "date_start": "2017-01-01", "date_end": "2017-01-31", "type_id": self.date_range_type_month.id, } ) self.date_range_february_2017 = self.DateRangeObj.create( { "name": "February 2017", "date_start": "2017-02-01", "date_end": "2017-02-28", "type_id": self.date_range_type_month.id, } ) self.date_range_january_2018 = self.DateRangeObj.create( { "name": "January 2018", "date_start": "2018-01-01", "date_end": "2018-01-31", "type_id": self.date_range_type_month.id, } ) def create_account_move(self, date_str): return self.AccountMoveObj.create( { "journal_id": self.bank_journal.id, "date": date_str, "line_ids": [ ( 0, 0, { "name": "Debit", "debit": 1000, "account_id": self.account_recv.id, }, ), ( 0, 0, { "name": "Credit", "credit": 1000, "account_id": self.account_sale.id, }, ), ], } ) def test_01_account_move_date_range_fm_id_compute(self): january_1st = Date.from_string("2017-01-01") move = self.create_account_move(january_1st) self.assertEqual( move.date_range_fm_id, self.date_range_january_2017, msg="Move period should be January 2017", ) self.assertTrue( all( [ line.date_range_fm_id == self.date_range_january_2017 for line in move.line_ids ] ), msg="All lines period should be January 2017", ) march_1st = Date.from_string("2017-03-01") move = self.create_account_move(march_1st) self.assertFalse( bool(move.date_range_fm_id), msg="Move shouldn't have any date range" ) def test_02_account_move_date_range_fm_id_search(self): january_2017_1st = Date.from_string("2017-01-01") february_2017_1st = Date.from_string("2017-02-01") march_2017_1st = Date.from_string("2017-03-01") january_2018_1st = Date.from_string("2018-01-01") move_jan_2017 = self.create_account_move(january_2017_1st) move_feb_2017 = self.create_account_move(february_2017_1st) move_march_2017 = self.create_account_move(march_2017_1st) move_jan_2018 = self.create_account_move(january_2018_1st) moves = self.AccountMoveObj.search([("date_range_fm_id", "ilike", "January")]) self.assertTrue( all( [ move_jan_2017 in moves, move_feb_2017 not in moves, move_march_2017 not in moves, move_jan_2018 in moves, ] ), msg="There should be only moves in January", ) moves = self.AccountMoveObj.search([("date_range_fm_id", "ilike", "2017")]) self.assertTrue( all( [ move_jan_2017 in moves, move_feb_2017 in moves, move_march_2017 not in moves, move_jan_2018 not in moves, ] ) ) moves = self.AccountMoveObj.search( [("date_range_fm_id", "=", self.date_range_january_2017.id)] ) self.assertTrue( all( [ move_jan_2017 in moves, move_feb_2017 not in moves, move_march_2017 not in moves, move_jan_2018 not in moves, ] ) ) moves = self.AccountMoveObj.search( [ ( "date_range_fm_id", "in", (self.date_range_january_2017.id, self.date_range_february_2017.id), ), ] ) self.assertTrue( all( [ move_jan_2017 in moves, move_feb_2017 in moves, move_march_2017 not in moves, move_jan_2018 not in moves, ] ) )
32.586735
6,387
1,581
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models from odoo.osv import expression class AccountMove(models.Model): _inherit = "account.move" date_range_fm_id = fields.Many2one( comodel_name="date.range", string="Fiscal month", compute="_compute_date_range_fm", search="_search_date_range_fm", ) @api.depends("date", "company_id") def _compute_date_range_fm(self): for rec in self: date = rec.date company = rec.company_id rec.date_range_fm_id = company and company.find_daterange_fm(date) or False @api.model def _search_date_range_fm(self, operator, value): if operator in ("=", "!=", "in", "not in"): date_range_domain = [("id", operator, value)] else: date_range_domain = [("name", operator, value)] date_ranges = self.env["date.range"].search(date_range_domain) domain = [] for date_range in date_ranges: domain = expression.OR( [ domain, [ "&", "&", ("date", ">=", date_range.date_start), ("date", "<=", date_range.date_end), "|", ("company_id", "=", False), ("company_id", "=", date_range.company_id.id), ], ] ) return domain
31.62
1,581
293
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class AccountMoveLine(models.Model): _inherit = "account.move.line" date_range_fm_id = fields.Many2one( related="move_id.date_range_fm_id", )
22.538462
293
984
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging def pre_init_hook(cr): """Precreate account_internal_group and fill with appropriate values to prevent a MemoryError when the ORM attempts to call its compute method on a large amount of preexisting moves.""" logger = logging.getLogger(__name__) logger.info( "Add account_move_line.account_internal_group column if it does not yet exist" ) cr.execute( "ALTER TABLE account_move_line ADD COLUMN IF NOT EXISTS account_internal_group VARCHAR" ) cr.execute( """ UPDATE account_move_line aml0 SET account_internal_group = aa.internal_group FROM account_move_line aml INNER JOIN account_account aa ON aa.id = aml.account_id WHERE aml.id = aml0.id AND aml.account_internal_group IS NULL """ ) logger.info("Finished adding account_move_line.account_internal_group column")
37.846154
984
669
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Account Move Total By Account Internal Group", "version": "15.0.1.0.0", "author": "ForgeFlow, Odoo Community Association (OCA)", "summary": "Adds Totals by Account Internal Group in Journal Entries", "website": "https://github.com/OCA/account-financial-tools", "license": "AGPL-3", "depends": ["account"], "category": "Accounting", "data": [ "views/account_move_views.xml", ], "installable": True, "maintainer": "AaronHForgeFlow", "development_status": "Beta", "pre_init_hook": "pre_init_hook", }
33.45
669
4,423
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase class TestAccountMoveTotalsByAccountType(TransactionCase): @classmethod def setUpClass(cls): super(TestAccountMoveTotalsByAccountType, cls).setUpClass() cls.account_model = cls.env["account.account"] cls.acc_type_model = cls.env["account.account.type"] cls.company = cls.env.ref("base.main_company") # Create account for Goods Received Not Invoiced acc_type = cls._create_account_type(cls, "liability", "other") name = "Goods Received Not Invoiced" code = "grni" cls.account_grni = cls._create_account(cls, acc_type, name, code, cls.company) # Create account for Cost of Goods Sold acc_type = cls._create_account_type(cls, "expense", "other") name = "Cost of Goods Sold" code = "cogs" cls.account_cogs = cls._create_account(cls, acc_type, name, code, cls.company) # Create account for Inventory acc_type = cls._create_account_type(cls, "asset", "other") name = "Inventory" code = "inventory" cls.account_inventory = cls._create_account( cls, acc_type, name, code, cls.company ) # Create Income account # Create account for Inventory acc_type = cls._create_account_type(cls, "income", "other") name = "Income" code = "income" cls.account_income = cls._create_account(cls, acc_type, name, code, cls.company) cls.journal = cls.env["account.journal"].search( [("company_id", "=", cls.env.user.company_id.id)], limit=1 ) cls.partner = cls.env.ref("base.res_partner_12") def _create_account_move(self, dr_account, cr_account): move_vals = { "journal_id": self.journal.id, "date": "1900-01-01", "line_ids": [ ( 0, 0, { "debit": 100.0, "credit": 0.0, "account_id": dr_account.id, "partner_id": self.partner.id, }, ), ( 0, 0, { "debit": 0.0, "credit": 100.0, "account_id": cr_account.id, "partner_id": self.partner.id, }, ), ], } return self.env["account.move"].create(move_vals) def _create_account_type(self, name, a_type): acc_type = self.acc_type_model.create( {"name": name, "type": a_type, "internal_group": name} ) return acc_type def _create_account(self, acc_type, name, code, company): """Create an account.""" account = self.account_model.create( { "name": name, "code": code, "user_type_id": acc_type.id, "company_id": company.id, "reconcile": True, } ) return account def test_01_account_internal_group_balance(self): """Create JE with different account types and check the amount total by internal group """ account_move = self._create_account_move( self.account_inventory, self.account_grni ) self.assertEqual( account_move.amount_total_signed_account_internal_group_asset, 100, "Wrong asset", ) self.assertEqual( account_move.amount_total_signed_account_internal_group_liability, -100, "Wrong liability", ) self.assertEqual( account_move.amount_total_signed_account_internal_group_expense, 0, "Wrong expense", ) account_move = self._create_account_move(self.account_cogs, self.account_income) self.assertEqual( account_move.amount_total_signed_account_internal_group_expense, 100, "Wrong Expense", ) self.assertEqual( account_move.amount_total_signed_account_internal_group_income, -100, "Wrong Income", )
35.95935
4,423
3,050
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class AccountMove(models.Model): _inherit = "account.move" amount_total_signed_account_internal_group_equity = fields.Monetary( compute="_compute_amount_total_signed_account_internal_group" ) amount_total_signed_account_internal_group_asset = fields.Monetary( compute="_compute_amount_total_signed_account_internal_group" ) amount_total_signed_account_internal_group_liability = fields.Monetary( compute="_compute_amount_total_signed_account_internal_group" ) amount_total_signed_account_internal_group_income = fields.Monetary( compute="_compute_amount_total_signed_account_internal_group" ) amount_total_signed_account_internal_group_expense = fields.Monetary( compute="_compute_amount_total_signed_account_internal_group" ) amount_total_signed_account_internal_group_off_balance = fields.Monetary( compute="_compute_amount_total_signed_account_internal_group" ) def _compute_amount_total_signed_account_internal_group(self): for move in self: domain = [("move_id", "=", move.id)] aml_groups = self.env["account.move.line"].read_group( domain=domain, fields=["balance", "account_internal_group"], groupby=["account_internal_group"], lazy=False, ) move.amount_total_signed_account_internal_group_asset = sum( ag["balance"] for ag in [ g for g in aml_groups if g["account_internal_group"] == "asset" ] ) move.amount_total_signed_account_internal_group_equity = sum( ag["balance"] for ag in [ g for g in aml_groups if g["account_internal_group"] == "equity" ] ) move.amount_total_signed_account_internal_group_liability = sum( ag["balance"] for ag in [ g for g in aml_groups if g["account_internal_group"] == "liability" ] ) move.amount_total_signed_account_internal_group_income = sum( ag["balance"] for ag in [ g for g in aml_groups if g["account_internal_group"] == "income" ] ) move.amount_total_signed_account_internal_group_expense = sum( ag["balance"] for ag in [ g for g in aml_groups if g["account_internal_group"] == "expense" ] ) move.amount_total_signed_account_internal_group_off_balance = sum( ag["balance"] for ag in [ g for g in aml_groups if g["account_internal_group"] == "off_balance" ] )
40.666667
3,050
471
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class AccountMoveLine(models.Model): _inherit = "account.move.line" # Making standard field stored in order to do the calculations faster account_internal_group = fields.Selection( related="account_id.user_type_id.internal_group", string="Internal Group", readonly=True, store=True, )
29.4375
471
637
py
PYTHON
15.0
# Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Assets Management - Low Value Asset", "version": "15.0.1.0.0", "license": "AGPL-3", "author": "Ecosoft, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "category": "Accounting & Finance", "depends": ["account_asset_management"], "data": [ "wizard/account_asset_remove.xml", "views/account_asset_views.xml", ], "installable": True, "maintainers": ["kittiu"], "development_status": "Alpha", }
33.526316
637
3,352
py
PYTHON
15.0
# Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields from odoo.tests import tagged from odoo.tests.common import Form from odoo.addons.account.tests.common import AccountTestInvoicingCommon @tagged("post_install", "-at_install") class TestAssetLowValue(AccountTestInvoicingCommon): @classmethod def setUpClass(cls): super().setUpClass() cls.asset_model = cls.env["account.asset"] cls.asset_profile_model = cls.env["account.asset.profile"] cls.remove_model = cls.env["account.asset.remove"] # Low value asset profile expense_account = cls.company_data["default_account_expense"] cls.profile_low_value = cls.asset_profile_model.create( { "account_expense_depreciation_id": expense_account.id, "account_asset_id": expense_account.id, "account_depreciation_id": expense_account.id, "account_residual_value_id": expense_account.id, "journal_id": cls.company_data["default_journal_purchase"].id, "name": "Asset Low Value", "method_time": "year", "method_number": 0, "method_period": "year", } ) # Invoice cls.partner = cls.env["res.partner"].create({"name": "Test Partner"}) cls.product = cls.env["product.product"].create( {"name": "Test", "standard_price": 500.0} ) move_form = Form( cls.env["account.move"].with_context( default_move_type="in_invoice", check_move_validity=False ) ) move_form.invoice_date = fields.Date.context_today(cls.env.user) move_form.partner_id = cls.partner with move_form.invoice_line_ids.new() as line_form: line_form.name = "test" line_form.product_id = cls.product line_form.price_unit = 2000.00 line_form.quantity = 1 cls.invoice = move_form.save() def test_01_asset_low_value(self): invoice = self.invoice move_form = Form(invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.asset_profile_id = self.profile_low_value invoice = move_form.save() invoice.action_post() asset = invoice.invoice_line_ids.mapped("asset_id") move_count = len(asset.account_move_line_ids) self.assertTrue(asset.low_value) asset.validate() self.assertEqual(asset.value_residual, 0) self.assertEqual(asset.state, "open") asset.remove() remove_model = self.env["account.asset.remove"].with_context(active_id=asset.id) with Form(remove_model) as f: f.posting_regime = "residual_value" remove = f.save() remove.remove() self.assertEqual(asset.state, "removed") self.assertEqual( len(asset.account_move_line_ids), move_count ) # no new account moves # Search test low_value_assets = self.asset_model.search([("low_value", "=", True)]) self.assertIn(asset, low_value_assets) normal_assets = self.asset_model.search([("low_value", "!=", True)]) self.assertNotIn(asset, normal_assets)
41.382716
3,352
560
py
PYTHON
15.0
# Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class AccountAssetRemove(models.TransientModel): _inherit = "account.asset.remove" def remove(self): self.ensure_one() asset_id = self.env.context.get("active_id") asset = self.env["account.asset"].browse(asset_id) if asset.low_value: asset.write({"state": "removed", "date_remove": self.date_remove}) return True return super().remove()
32.941176
560
2,842
py
PYTHON
15.0
# Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models class AccountAsset(models.Model): _inherit = "account.asset" low_value = fields.Boolean( string="Low Value Asset", compute="_compute_low_value", search="_search_low_value", help="Low-Value Asset (LVA) is true when the asset profile set\n" "1. Asset Account = Expense (low value asset)\n" "2. Number of Years = 0 years\n" "In essense, the low value asset is not really and asset but an expense " "tracked as asset, as such, it has no residual value. And when removed, " "only status is changed (no accounting entry).", ) @api.depends("profile_id", "method_number") def _compute_low_value(self): expense_account = self.env.ref("account.data_account_type_expenses") for asset in self: asset.low_value = ( asset.profile_id.account_asset_id.user_type_id == expense_account and asset.method_number == 0 ) @api.model def _search_low_value(self, operator, value): expense_account = self.env.ref("account.data_account_type_expenses") if operator == "=": return [ ("profile_id.account_asset_id.user_type_id", "=", expense_account.id), ("method_number", "=", 0), ] if operator == "!=": return [ "|", ("profile_id.account_asset_id.user_type_id", "!=", expense_account.id), ("method_number", "!=", 0), ] def _compute_depreciation(self): res = super()._compute_depreciation() # For low value asset, there is no depreciation for asset in self: if asset.low_value: asset.value_residual = 0 return res def validate(self): res = super().validate() # For low value asset, state = "open" even value_residual = 0 for asset in self: if asset.low_value: asset.state = "open" return res def remove(self): self.ensure_one() ctx = dict(self.env.context, active_ids=self.ids, active_id=self.id) # Removing low value asset, use different wizard if self.low_value: view = self.env.ref("account_asset_low_value.asset_low_value_remove_form") return { "name": _("Remove Low Value Asset"), "view_mode": "form", "res_model": "account.asset.remove", "view_id": view.id, "target": "new", "type": "ir.actions.act_window", "context": ctx, } return super().remove()
36.909091
2,842
809
py
PYTHON
15.0
# Copyright 2022 Moduon Team S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). { "name": "General sequence in account journals", "summary": "Add configurable sequence to account moves, per journal", "version": "15.0.1.1.0", "category": "Accounting/Accounting", "website": "https://github.com/OCA/account-financial-tools", "author": "Moduon, Odoo Community Association (OCA)", "license": "LGPL-3", "external_dependencies": {"python": ["freezegun"]}, "maintainers": ["yajo"], "depends": [ "account", ], "data": [ "security/ir.model.access.csv", "views/account_journal.xml", "views/account_move_line.xml", "views/account_move.xml", "wizards/account_move_renumber_wizard_views.xml", ], }
35.173913
809
3,750
py
PYTHON
15.0
# Copyright 2022 Moduon # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from freezegun import freeze_time from odoo.tests.common import Form, new_test_user, tagged, users from odoo.tools import mute_logger from odoo.addons.account.tests.common import TestAccountReconciliationCommon @freeze_time("2022-05-11", tick=True) @tagged("post_install", "-at_install") class RenumberCase(TestAccountReconciliationCommon): @classmethod def setUpClass(cls): super().setUpClass() cls.invoicer = new_test_user( cls.env, "test_invoicer", "account.group_account_invoice" ) cls.manager = new_test_user( cls.env, "test_manager", "account.group_account_manager" ) @users("test_invoicer") def test_invoice_gets_entry_number(self): # Draft invoice without entry number invoice = self._create_invoice() self.assertFalse(invoice.entry_number) # Gets one once posted invoice.action_post() self.assertTrue(invoice.entry_number.startswith("2022/")) # Lost number when canceled with mute_logger( "odoo.addons.account_journal_general_sequence.models.account_move" ): invoice.button_cancel() self.assertFalse(invoice.entry_number) @users("test_manager") def test_renumber(self): # Post invoices in wrong order next_year_invoice = self._create_invoice( date_invoice="2023-12-31", auto_validate=True ) next_year_invoice.flush(["entry_number"], next_year_invoice) new_invoice = self._create_invoice( date_invoice="2022-05-10", auto_validate=True ) new_invoice.flush(["entry_number"], new_invoice) old_invoice = self._create_invoice( date_invoice="2022-04-30", auto_validate=True ) old_invoice.flush(["entry_number"], old_invoice) self.assertLess(new_invoice.entry_number, old_invoice.entry_number) # Fix entry number order with wizard; default values are OK wiz_f = Form(self.env["account.move.renumber.wizard"]) self.assertEqual(len(wiz_f.available_sequence_ids), 1) wiz = wiz_f.save() wiz.action_renumber() self.assertGreater(new_invoice.entry_number, old_invoice.entry_number) # Add opening move opening_invoice = self._create_invoice( date_invoice="2022-01-01", auto_validate=True ) self.assertGreater(opening_invoice.entry_number, new_invoice.entry_number) # Renumber again, starting from zero wiz_f = Form(self.env["account.move.renumber.wizard"]) wiz = wiz_f.save() wiz.action_renumber() self.assertEqual(opening_invoice.entry_number, "2022/0000000001") self.assertEqual(old_invoice.entry_number, "2022/0000000002") self.assertEqual(new_invoice.entry_number, "2022/0000000003") self.assertEqual(next_year_invoice.entry_number, "2023/0000000001") @users("test_invoicer") def test_install_no_entry_number(self): """No entry numbers assigned on module installation.""" # Imitate installation environment self.env = self.env( context=dict(self.env.context, module="account_journal_general_sequence") ) self.env["ir.module.module"].sudo().search( [("name", "=", "account_journal_general_sequence")] ).state = "to install" # Do some action that would make the move get an entry number invoice = self._create_invoice() self.assertFalse(invoice.entry_number) invoice.action_post() # Ensure there's no entry number self.assertFalse(invoice.entry_number)
41.666667
3,750
2,634
py
PYTHON
15.0
# Copyright 2022 Moduon # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). import logging from odoo import api, fields, models _logger = logging.getLogger(__name__) ADDON = "account_journal_general_sequence" class AccountMove(models.Model): _inherit = "account.move" _sql_constraints = [ ( "entry_number_unique", "UNIQUE(entry_number, journal_id)", "Entry number must be unique per journal.", ), ] entry_number = fields.Char( index=True, readonly=True, store=True, compute="_compute_entry_number", help="Automatic numbering, based on journal configuration.", ) @api.depends("state") def _compute_entry_number(self): """Assign an entry number when posting.""" # Skip if installing module, for performance reasons if self.env.context.get("module") == ADDON: module = self.env["ir.module.module"].search([("name", "=", ADDON)]) if module.state == "to install": _logger.info( "Skipping entry number generation at install for %s.", self, ) return canceled = self.filtered_domain( [("state", "=", "cancel"), ("entry_number", "!=", False)] ) canceled.entry_number = False if canceled: no_gap_seqs = canceled.mapped( "journal_id.entry_number_sequence_id" ).filtered_domain([("implementation", "=", "no_gap")]) if no_gap_seqs: _logger.warning( "Emptied entry_number for %r after cancellation. " "This created gaps on %r.", canceled, no_gap_seqs, ) chosen = self.filtered_domain( [("state", "=", "posted"), ("entry_number", "=", False)] ) # Cache all the new numbers to avoid wasting recomputations, caused by # searches done by _next() in the loop below chosen_map = {} for move in chosen.sorted(lambda one: (one.date, one.name, one.id)): chosen_map[move.id] = move.journal_id.entry_number_sequence_id._next( move.date ) # Write all the new numbers in the chosen moves for move_id, new_number in chosen_map.items(): self.browse(move_id).entry_number = new_number if chosen: _logger.info("Added entry_number to %d account moves", len(chosen)) _logger.debug("Added entry_number to %r", chosen)
36.082192
2,634
1,295
py
PYTHON
15.0
# Copyright 2022 Moduon # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). import logging from odoo import _, fields, models _logger = logging.getLogger(__name__) class AccountJournal(models.Model): _inherit = "account.journal" entry_number_sequence_id = fields.Many2one( comodel_name="ir.sequence", string="Account entry number sequence", default=lambda self: self._default_entry_number_sequence(), copy=False, help="Sequence used for account entry numbering.", ) def _default_entry_number_sequence(self): """Get the default sequence for all journals.""" result = self.env["ir.sequence"].search( [("code", "=", "account_journal_general_sequence.default")] ) if result: return result _logger.info("Creating default sequence for account move numbers") result = self.env["ir.sequence"].create( { "name": _("Account entry default numbering"), "code": "account_journal_general_sequence.default", "implementation": "no_gap", "prefix": "%(range_year)s/", "padding": 10, "use_date_range": True, } ) return result
33.205128
1,295
265
py
PYTHON
15.0
# Copyright 2022 Moduon # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import fields, models class AccountMoveLine(models.Model): _inherit = "account.move.line" entry_number = fields.Char(related="move_id.entry_number")
26.5
265
3,088
py
PYTHON
15.0
# Copyright 2022 Moduon # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from datetime import date from odoo import _, api, exceptions, fields, models class AccountMoveRenumberWizard(models.TransientModel): _name = "account.move.renumber.wizard" _description = "Account move entry renumbering wizard" starting_date = fields.Date( required=True, default=lambda self: self._default_starting_date(), help="Renumber account moves starting this day.", ) starting_number = fields.Integer( default=1, help="Reset sequence to this number before starting." ) available_sequence_ids = fields.Many2many( comodel_name="ir.sequence", string="Available sequences", default=lambda self: self._default_available_sequence_ids(), ) sequence_id = fields.Many2one( comodel_name="ir.sequence", string="Sequence", required=True, default=lambda self: self._default_entry_number_sequence(), domain="[('id', 'in', available_sequence_ids)]", help="Sequence to use for renumbering. Affects all journals that use this sequence.", ) @api.model def _default_starting_date(self): """Start by default on day 1 of current year.""" return date(date.today().year, 1, 1) @api.model def _default_entry_number_sequence(self): """Get default sequence if it exists.""" return self.env["ir.sequence"].search( [("code", "=", "account_journal_general_sequence.default")] ) @api.model def _default_available_sequence_ids(self): """Let view display only journal-related sequences.""" return self.env["account.journal"].search([]).mapped("entry_number_sequence_id") def action_renumber(self): """Renumber moves. Makes sure moves exist. Sorts them. Resets sequences. Renumbers them. """ # Find posted moves that match wizard criteria moves = self.env["account.move"].search( [ ("state", "=", "posted"), ("date", ">=", self.starting_date), ("journal_id.entry_number_sequence_id", "=", self.sequence_id.id), ], order="date, id", ) if not moves: raise exceptions.UserError(_("No account moves found.")) # Reset sequence future_ranges = self.env["ir.sequence.date_range"].search( [ ("date_from", ">", self.starting_date), ("sequence_id", "=", self.sequence_id.id), ] ) # Safe `sudo` calls; wizard only available for accounting managers future_ranges.sudo().unlink() current_range = self.sequence_id._get_current_sequence(self.starting_date) current_range.sudo().number_next = self.starting_number self.sequence_id.sudo().number_next = self.starting_number # Renumber the moves moves.entry_number = False moves.flush(["entry_number"]) moves._compute_entry_number()
37.204819
3,088
499
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Account Move Line Tax Editable", "summary": "Allows to edit taxes on non-posted account move lines", "version": "15.0.1.0.1", "license": "AGPL-3", "author": "ACSONE SA/NV, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "depends": ["account"], "data": ["views/account_move.xml", "views/account_move_line.xml"], }
38.384615
499
3,083
py
PYTHON
15.0
# Copyright 2019 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import odoo.tests.common as common from odoo import fields class TestAccountMoveLineTaxEditable(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() acc_obj = cls.env["account.account"] account100 = acc_obj.create( { "code": "100", "name": "Account 100", "user_type_id": cls.env.ref("account.data_account_type_receivable").id, "reconcile": True, } ) account300 = acc_obj.create( { "code": "300", "name": "Account 300", "user_type_id": cls.env.ref( "account.data_account_type_other_income" ).id, } ) journal = cls.env["account.journal"].create( {"name": "Test journal", "type": "sale", "code": "TEST"} ) move_vals = { "journal_id": journal.id, "name": "move test", "date": fields.Date.today(), "line_ids": [ ( 0, 0, { "name": "move test line 1", "debit": 0.0, "credit": 1000.0, "account_id": account300.id, }, ), ( 0, 0, { "name": "move test line 2", "debit": 1000.0, "credit": 0.0, "account_id": account100.id, }, ), ], } cls.move = cls.env["account.move"].create(move_vals) cls.tax15 = cls.env["account.tax"].create( { "name": "Test tax 15", "amount": 15, } ) def test_compute_is_tax_editable(self): self.assertEqual(self.move.line_ids.mapped("is_tax_editable"), [True, True]) self.move.action_post() self.assertEqual(self.move.line_ids.mapped("is_tax_editable"), [False, False]) def test_tax_edited(self): line1 = self.move.line_ids[0] line1.tax_line_id = self.tax15.id line2 = self.move.line_ids[1] self.move.action_post() self.assertEqual(line1.tax_line_id.id, self.tax15.id) self.assertEqual(line2.tax_line_id.id, False) self.assertEqual(line1.tax_repartition_line_id.tax_id.id, self.tax15.id) def test_tax_not_edited(self): """In this case we set the tax_repartition_line_id field, simulating that the move came from an invoice with tax applied. Thus, tax_line_id should be computed""" line1 = self.move.line_ids[1] line1.tax_repartition_line_id = self.tax15.invoice_repartition_line_ids[1] self.assertEqual(line1.tax_line_id.id, self.tax15.id)
34.640449
3,083
1,805
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class AccountMoveLine(models.Model): _inherit = "account.move.line" is_tax_editable = fields.Boolean( string="Is tax data editable?", compute="_compute_is_tax_editable" ) tax_line_id = fields.Many2one(inverse="_inverse_tax_line_id") @api.depends("move_id.state") def _compute_is_tax_editable(self): for rec in self: rec.is_tax_editable = rec.move_id.state == "draft" def _inverse_tax_line_id(self): for rec in self: repartition_type = rec.tax_repartition_line_id.repartition_type or "tax" factor_percent = rec.tax_repartition_line_id.factor_percent or 100 has_account = bool(rec.tax_repartition_line_id.account_id) if rec.move_id.move_type in ("out_refund", "in_refund"): repartition_lines = rec.tax_line_id.refund_repartition_line_ids else: repartition_lines = rec.tax_line_id.invoice_repartition_line_ids lines = repartition_lines.filtered( lambda rl: rl.repartition_type == repartition_type and rl.factor_percent == factor_percent ) if len(lines) > 1: lines = ( lines.filtered( lambda rl: rl.repartition_type == "base" or has_account is bool(rl.account_id) )[:1] or lines[:1] ) elif not lines: lines = repartition_lines.filtered( lambda rl: rl.repartition_type == repartition_type )[:1] rec.tax_repartition_line_id = lines
38.404255
1,805
1,220
py
PYTHON
15.0
# Copyright (C) 2019 - Today: GRAP (http://www.grap.coop) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Account - Missing Menus & Saxon Accounting", "version": "15.0.1.0.2", "category": "Accounting", "license": "AGPL-3", "summary": "Adds missing menu entries for Account module and" " adds the option to enable Saxon Accounting", "author": "GRAP, Akretion, Odoo Community Association (OCA)", "maintainers": ["legalsylvain"], "website": "https://github.com/OCA/account-financial-tools", "depends": ["account"], "data": [ "views/menu.xml", "views/res_config_settings_views.xml", "views/view_account_account_template.xml", "views/view_account_bank_statement.xml", "views/view_account_chart_template.xml", "views/view_account_fiscal_position_template.xml", "views/view_account_group.xml", "views/view_account_tag.xml", "views/view_account_tax_group.xml", "views/view_account_tax_template.xml", "views/view_account_type.xml", ], "demo": ["demo/res_groups.xml"], "installable": True, }
39.354839
1,220
358
py
PYTHON
15.0
# Copyright 2018 FOREST AND BIOMASS ROMANIA SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class AccountTaxGroup(models.Model): _inherit = "account.tax.group" tax_ids = fields.One2many( comodel_name="account.tax", inverse_name="tax_group_id", string="Taxes", )
25.571429
358
358
py
PYTHON
15.0
# Copyright 2018 FOREST AND BIOMASS ROMANIA SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class AccountGroup(models.Model): _inherit = "account.group" account_ids = fields.One2many( comodel_name="account.account", inverse_name="group_id", string="Accounts", )
25.571429
358
560
py
PYTHON
15.0
# Copyright 2021 Opener B.V. <stefan@opener.amsterdam> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" anglo_saxon_accounting = fields.Boolean( related="company_id.anglo_saxon_accounting", readonly=False, string="Use anglo-saxon accounting", help=( "Record the cost of a good as an expense when this good is " "invoiced to a final customer." ), )
32.941176
560
385
py
PYTHON
15.0
# Copyright 2018 FOREST AND BIOMASS ROMANIA SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class AccountAccountTag(models.Model): _inherit = "account.account.tag" account_ids = fields.Many2many( comodel_name="account.account", relation="account_account_account_tag", string="Accounts", )
27.5
385
1,189
py
PYTHON
15.0
# Copyright 2009-2019 Noviat # Copyright 2019 Tecnativa - Pedro M. Baeza # Copyright 2021 Tecnativa - João Marques # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Assets Management", "version": "15.0.1.0.4", "license": "AGPL-3", "depends": ["account", "report_xlsx_helper"], "excludes": ["account_asset"], "development_status": "Mature", "external_dependencies": {"python": ["python-dateutil"]}, "author": "Noviat, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "category": "Accounting & Finance", "data": [ "security/account_asset_security.xml", "security/ir.model.access.csv", "wizard/account_asset_compute.xml", "wizard/account_asset_remove.xml", "views/account_account.xml", "views/account_asset.xml", "views/account_asset_group.xml", "views/account_asset_profile.xml", "views/account_move.xml", "views/account_move_line.xml", "views/menuitem.xml", "data/cron.xml", "wizard/wiz_account_asset_report.xml", "wizard/wiz_asset_move_reverse.xml", ], }
36
1,188
38,435
py
PYTHON
15.0
# Copyright (c) 2014 ACSONE SA/NV (acsone.eu). # Copyright 2009-2018 Noviat # Copyright 2021 Tecnativa - João Marques # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import calendar import time from datetime import date, datetime from odoo import Command, fields from odoo.tests import tagged from odoo.tests.common import Form from odoo.addons.account.tests.common import AccountTestInvoicingCommon @tagged("post_install", "-at_install") class TestAssetManagement(AccountTestInvoicingCommon): @classmethod def setUpClass(cls): super().setUpClass() # ENVIRONMENTS cls.asset_model = cls.env["account.asset"] cls.asset_profile_model = cls.env["account.asset.profile"] cls.dl_model = cls.env["account.asset.line"] cls.remove_model = cls.env["account.asset.remove"] # INSTANCES cls.partner = cls.env["res.partner"].create({"name": "Test Partner"}) cls.product = cls.env["product.product"].create( {"name": "Test", "standard_price": 500.0} ) cls.invoice = ( cls.env["account.move"] .with_context(check_move_validity=False) .create( { "move_type": "in_invoice", "invoice_date": fields.Date.context_today(cls.env.user), "partner_id": cls.partner.id, "invoice_line_ids": [ Command.create( { "name": "test", "product_id": cls.product.id, "price_unit": 2000.00, "quantity": 1, } ), ], } ) ) cls.invoice_2 = ( cls.env["account.move"] .with_context(check_move_validity=False) .create( { "move_type": "in_invoice", "invoice_date": fields.Date.context_today(cls.env.user), "partner_id": cls.partner.id, "invoice_line_ids": [ Command.create( { "name": "test 2", "product_id": cls.product.id, "price_unit": 10000.00, "quantity": 1, } ), Command.create( { "name": "test 3", "product_id": cls.product.id, "price_unit": 20000.00, "quantity": 1, } ), ], } ) ) # analytic configuration cls.env.user.write( { "groups_id": [ (4, cls.env.ref("analytic.group_analytic_accounting").id), (4, cls.env.ref("analytic.group_analytic_tags").id), ], } ) cls.analytic_account = cls.env["account.analytic.account"].create( {"name": "test_analytic_account"} ) cls.analytic_tag = cls.env["account.analytic.tag"].create( {"name": "test_analytic_tag"} ) # Asset Profile 1 cls.ict3Y = cls.asset_profile_model.create( { "account_expense_depreciation_id": cls.company_data[ "default_account_expense" ].id, "account_asset_id": cls.company_data["default_account_assets"].id, "account_depreciation_id": cls.company_data[ "default_account_assets" ].id, "journal_id": cls.company_data["default_journal_purchase"].id, "name": "Hardware - 3 Years", "method_time": "year", "method_number": 3, "method_period": "year", } ) # Asset Profile 2 cls.car5y = cls.asset_profile_model.create( { "account_expense_depreciation_id": cls.company_data[ "default_account_expense" ].id, "account_asset_id": cls.company_data["default_account_assets"].id, "account_depreciation_id": cls.company_data[ "default_account_assets" ].id, "journal_id": cls.company_data["default_journal_purchase"].id, "name": "Cars - 5 Years", "method_time": "year", "method_number": 5, "method_period": "year", "account_analytic_id": cls.analytic_account.id, "analytic_tag_ids": [(4, cls.analytic_tag.id)], } ) def test_invoice_line_without_product(self): tax = self.env["account.tax"].create( { "name": "TAX 15%", "amount_type": "percent", "type_tax_use": "purchase", "amount": 15.0, } ) invoice = ( self.env["account.move"] .with_context(check_move_validity=False) .create( { "move_type": "in_invoice", "invoice_date": fields.Date.context_today(self.env.user), "partner_id": self.partner.id, "invoice_line_ids": [ Command.create( { "name": "Line 1", "price_unit": 200.0, "quantity": 1, "tax_ids": [tax.id], } ), ], } ) ) self.assertEqual(invoice.partner_id, self.partner) def test_00_fiscalyear_lock_date_month(self): asset = self.asset_model.create( { "name": "test asset", "profile_id": self.car5y.id, "purchase_value": 1500, "date_start": "1901-02-01", "method_time": "year", "method_number": 3, "method_period": "month", } ) asset.compute_depreciation_board() asset.refresh() self.assertTrue(asset.depreciation_line_ids[0].init_entry) for i in range(1, 36): self.assertFalse(asset.depreciation_line_ids[i].init_entry) def test_00_fiscalyear_lock_date_year(self): asset = self.asset_model.create( { "name": "test asset", "profile_id": self.car5y.id, "purchase_value": 1500, "date_start": "1901-02-01", "method_time": "year", "method_number": 3, "method_period": "year", } ) asset.compute_depreciation_board() asset.refresh() self.assertTrue(asset.depreciation_line_ids[0].init_entry) for i in range(1, 4): self.assertFalse(asset.depreciation_line_ids[i].init_entry) def test_01_nonprorata_basic(self): """Basic tests of depreciation board computations and postings.""" # First create demo assets and do some sanity checks # Asset Model 1 ict0 = self.asset_model.create( { "state": "draft", "method_time": "year", "method_number": 3, "method_period": "year", "name": "Laptop", "code": "PI00101", "purchase_value": 1500.0, "profile_id": self.ict3Y.id, "date_start": time.strftime("%Y-01-01"), } ) # Sanity checks self.assertEqual(ict0.state, "draft") self.assertEqual(ict0.purchase_value, 1500) self.assertEqual(ict0.salvage_value, 0) self.assertEqual(ict0.depreciation_base, 1500) self.assertEqual(len(ict0.depreciation_line_ids), 1) # Asset Model 2 vehicle0 = self.asset_model.create( { "state": "draft", "method_time": "year", "method_number": 5, "method_period": "year", "name": "CEO's Car", "purchase_value": 12000.0, "salvage_value": 2000.0, "profile_id": self.car5y.id, "date_start": time.strftime("%Y-01-01"), } ) # Sanity checks self.assertEqual(vehicle0.state, "draft") self.assertEqual(vehicle0.purchase_value, 12000) self.assertEqual(vehicle0.salvage_value, 2000) self.assertEqual(vehicle0.depreciation_base, 10000) self.assertEqual(len(vehicle0.depreciation_line_ids), 1) # Compute the depreciation boards ict0.compute_depreciation_board() ict0.refresh() self.assertEqual(len(ict0.depreciation_line_ids), 4) self.assertEqual(ict0.depreciation_line_ids[1].amount, 500) vehicle0.compute_depreciation_board() vehicle0.refresh() self.assertEqual(len(vehicle0.depreciation_line_ids), 6) self.assertEqual(vehicle0.depreciation_line_ids[1].amount, 2000) # Post the first depreciation line ict0.validate() ict0.depreciation_line_ids[1].create_move() ict0.refresh() self.assertEqual(ict0.state, "open") self.assertEqual(ict0.value_depreciated, 500) self.assertEqual(ict0.value_residual, 1000) vehicle0.validate() created_move_ids = vehicle0.depreciation_line_ids[1].create_move() for move_id in created_move_ids: move = self.env["account.move"].browse(move_id) expense_line = move.line_ids.filtered( lambda line: line.account_id.internal_group == "expense" ) self.assertEqual( expense_line.analytic_account_id.id, self.analytic_account.id, ) self.assertEqual(expense_line.analytic_tag_ids.id, self.analytic_tag.id) vehicle0.refresh() self.assertEqual(vehicle0.state, "open") self.assertEqual(vehicle0.value_depreciated, 2000) self.assertEqual(vehicle0.value_residual, 8000) def test_02_prorata_basic(self): """Prorata temporis depreciation basic test.""" asset = self.asset_model.create( { "name": "test asset", "profile_id": self.car5y.id, "purchase_value": 3333, "salvage_value": 0, "date_start": time.strftime("%Y-07-07"), "method_time": "year", "method_number": 5, "method_period": "month", "prorata": True, } ) asset.compute_depreciation_board() asset.refresh() if calendar.isleap(date.today().year): self.assertAlmostEqual( asset.depreciation_line_ids[1].amount, 46.44, places=2 ) else: self.assertAlmostEqual( asset.depreciation_line_ids[1].amount, 47.33, places=2 ) self.assertAlmostEqual(asset.depreciation_line_ids[2].amount, 55.55, places=2) self.assertAlmostEqual(asset.depreciation_line_ids[3].amount, 55.55, places=2) self.assertAlmostEqual(asset.depreciation_line_ids[4].amount, 55.55, places=2) self.assertAlmostEqual(asset.depreciation_line_ids[5].amount, 55.55, places=2) self.assertAlmostEqual(asset.depreciation_line_ids[6].amount, 55.55, places=2) if calendar.isleap(date.today().year): self.assertAlmostEqual( asset.depreciation_line_ids[-1].amount, 9.11, places=2 ) else: self.assertAlmostEqual( asset.depreciation_line_ids[-1].amount, 8.22, places=2 ) def test_03_proprata_init_prev_year(self): """Prorata temporis depreciation with init value in prev year.""" # Create an asset in current year asset = self.asset_model.create( { "name": "test asset", "profile_id": self.car5y.id, "purchase_value": 3333, "salvage_value": 0, "date_start": "%d-07-07" % (datetime.now().year - 1,), "method_time": "year", "method_number": 5, "method_period": "month", "prorata": True, } ) # Create a initial depreciation line in previous year self.dl_model.create( { "asset_id": asset.id, "amount": 325.08, "line_date": "%d-12-31" % (datetime.now().year - 1,), "type": "depreciate", "init_entry": True, } ) self.assertEqual(len(asset.depreciation_line_ids), 2) asset.compute_depreciation_board() asset.refresh() # check the depreciated value is the initial value self.assertAlmostEqual(asset.value_depreciated, 325.08, places=2) # check computed values in the depreciation board self.assertAlmostEqual(asset.depreciation_line_ids[3].amount, 55.55, places=2) if calendar.isleap(date.today().year - 1): # for leap years the first year depreciation amount of 325.08 # is too high and hence a correction is applied to the next # entry of the table self.assertAlmostEqual( asset.depreciation_line_ids[2].amount, 54.66, places=2 ) self.assertAlmostEqual( asset.depreciation_line_ids[3].amount, 55.55, places=2 ) self.assertAlmostEqual( asset.depreciation_line_ids[-1].amount, 9.11, places=2 ) else: self.assertAlmostEqual( asset.depreciation_line_ids[2].amount, 55.55, places=2 ) self.assertAlmostEqual( asset.depreciation_line_ids[-1].amount, 8.22, places=2 ) def test_04_prorata_init_cur_year(self): """Prorata temporis depreciation with init value in curent year.""" asset = self.asset_model.create( { "name": "test asset", "profile_id": self.car5y.id, "purchase_value": 3333, "salvage_value": 0, "date_start": time.strftime("%Y-07-07"), "method_time": "year", "method_number": 5, "method_period": "month", "prorata": True, } ) self.dl_model.create( { "asset_id": asset.id, "amount": 279.44, "line_date": time.strftime("%Y-11-30"), "type": "depreciate", "init_entry": True, } ) self.assertEqual(len(asset.depreciation_line_ids), 2) asset.compute_depreciation_board() asset.refresh() # check the depreciated value is the initial value self.assertAlmostEqual(asset.value_depreciated, 279.44, places=2) # check computed values in the depreciation board if calendar.isleap(date.today().year): self.assertAlmostEqual( asset.depreciation_line_ids[2].amount, 44.75, places=2 ) else: self.assertAlmostEqual( asset.depreciation_line_ids[2].amount, 45.64, places=2 ) self.assertAlmostEqual(asset.depreciation_line_ids[3].amount, 55.55, places=2) if calendar.isleap(date.today().year): self.assertAlmostEqual( asset.depreciation_line_ids[-1].amount, 9.11, places=2 ) else: self.assertAlmostEqual( asset.depreciation_line_ids[-1].amount, 8.22, places=2 ) def test_05_degressive_linear(self): """Degressive-Linear with annual and quarterly depreciation.""" # annual depreciation asset = self.asset_model.create( { "name": "test asset", "profile_id": self.car5y.id, "purchase_value": 1000, "salvage_value": 0, "date_start": time.strftime("%Y-07-07"), "method_time": "year", "method": "degr-linear", "method_progress_factor": 0.40, "method_number": 5, "method_period": "year", "prorata": False, } ) asset.compute_depreciation_board() asset.refresh() # check values in the depreciation board self.assertEqual(len(asset.depreciation_line_ids), 5) self.assertAlmostEqual(asset.depreciation_line_ids[1].amount, 400.00, places=2) self.assertAlmostEqual(asset.depreciation_line_ids[2].amount, 240.00, places=2) self.assertAlmostEqual(asset.depreciation_line_ids[3].amount, 200.00, places=2) self.assertAlmostEqual(asset.depreciation_line_ids[4].amount, 160.00, places=2) # quarterly depreciation asset = self.asset_model.create( { "name": "test asset", "profile_id": self.car5y.id, "purchase_value": 1000, "salvage_value": 0, "date_start": time.strftime("%Y-07-07"), "method_time": "year", "method": "degr-linear", "method_progress_factor": 0.40, "method_number": 5, "method_period": "quarter", "prorata": False, } ) asset.compute_depreciation_board() asset.refresh() # check values in the depreciation board self.assertEqual(len(asset.depreciation_line_ids), 15) # lines prior to asset start period are grouped in the first entry self.assertAlmostEqual(asset.depreciation_line_ids[1].amount, 300.00, places=2) self.assertAlmostEqual(asset.depreciation_line_ids[3].amount, 60.00, places=2) self.assertAlmostEqual(asset.depreciation_line_ids[7].amount, 50.00, places=2) self.assertAlmostEqual(asset.depreciation_line_ids[13].amount, 40.00, places=2) def test_06_degressive_limit(self): """Degressive with annual depreciation.""" asset = self.asset_model.create( { "name": "test asset", "profile_id": self.car5y.id, "purchase_value": 1000, "salvage_value": 100, "date_start": time.strftime("%Y-07-07"), "method_time": "year", "method": "degr-limit", "method_progress_factor": 0.40, "method_number": 5, "method_period": "year", "prorata": False, } ) asset.compute_depreciation_board() asset.refresh() # check values in the depreciation board self.assertEqual(len(asset.depreciation_line_ids), 6) self.assertAlmostEqual(asset.depreciation_line_ids[1].amount, 400.00, places=2) self.assertAlmostEqual(asset.depreciation_line_ids[2].amount, 240.00, places=2) self.assertAlmostEqual(asset.depreciation_line_ids[3].amount, 144.00, places=2) self.assertAlmostEqual(asset.depreciation_line_ids[4].amount, 86.40, places=2) self.assertAlmostEqual(asset.depreciation_line_ids[5].amount, 29.60, places=2) def test_07_linear_limit(self): """Degressive with annual depreciation.""" asset = self.asset_model.create( { "name": "test asset", "profile_id": self.car5y.id, "purchase_value": 1000, "salvage_value": 100, "date_start": time.strftime("%Y-07-07"), "method_time": "year", "method": "linear-limit", "method_number": 5, "method_period": "year", "prorata": False, } ) asset.compute_depreciation_board() asset.refresh() # check values in the depreciation board self.assertEqual(len(asset.depreciation_line_ids), 6) self.assertAlmostEqual(asset.depreciation_line_ids[1].amount, 200.00, places=2) self.assertAlmostEqual(asset.depreciation_line_ids[-1].amount, 100.00, places=2) def test_08_asset_removal(self): """Asset removal""" asset = self.asset_model.create( { "name": "test asset removal", "profile_id": self.car5y.id, "purchase_value": 5000, "salvage_value": 0, "date_start": "2019-01-01", "method_time": "year", "method_number": 5, "method_period": "quarter", "prorata": False, } ) asset.compute_depreciation_board() asset.validate() wiz_ctx = {"active_id": asset.id, "early_removal": True} wiz = self.remove_model.with_context(**wiz_ctx).create( { "date_remove": "2019-01-31", "sale_value": 0.0, "posting_regime": "gain_loss_on_sale", "account_plus_value_id": self.company_data[ "default_account_revenue" ].id, "account_min_value_id": self.company_data["default_account_expense"].id, } ) wiz.remove() asset.refresh() self.assertEqual(len(asset.depreciation_line_ids), 3) self.assertAlmostEqual(asset.depreciation_line_ids[1].amount, 81.46, places=2) self.assertAlmostEqual(asset.depreciation_line_ids[2].amount, 4918.54, places=2) def test_09_asset_from_invoice(self): all_asset = self.env["account.asset"].search([]) invoice = self.invoice asset_profile = self.car5y asset_profile.asset_product_item = False self.assertTrue(len(invoice.invoice_line_ids) > 0) line = invoice.invoice_line_ids[0] self.assertTrue(line.price_unit > 0.0) invoice.invoice_line_ids[0].write( {"quantity": 2, "asset_profile_id": asset_profile.id} ) invoice._onchange_invoice_line_ids() invoice.action_post() # get all asset after invoice validation current_asset = self.env["account.asset"].search([]) # get the new asset new_asset = current_asset - all_asset # check that a new asset is created self.assertEqual(len(new_asset), 1) # check that the new asset has the correct purchase value self.assertAlmostEqual( new_asset.purchase_value, line.price_unit * line.quantity, places=2 ) def test_10_asset_from_invoice_product_item(self): all_asset = self.env["account.asset"].search([]) invoice = self.invoice asset_profile = self.car5y asset_profile.asset_product_item = True self.assertTrue(len(invoice.invoice_line_ids) > 0) line = invoice.invoice_line_ids[0] self.assertTrue(line.price_unit > 0.0) line.quantity = 2 line.asset_profile_id = asset_profile self.assertEqual(len(invoice.invoice_line_ids), 2) invoice.action_post() # get all asset after invoice validation current_asset = self.env["account.asset"].search([]) # get the new asset new_asset = current_asset - all_asset # check that a new asset is created self.assertEqual(len(new_asset), 2) for asset in new_asset: # check that the new asset has the correct purchase value self.assertAlmostEqual(asset.purchase_value, line.price_unit, places=2) def test_11_assets_from_invoice(self): all_assets = self.env["account.asset"].search([]) ctx = dict(self.invoice_2._context) invoice = self.invoice_2.with_context(**ctx) asset_profile = self.car5y asset_profile.asset_product_item = True # Compute depreciation lines on invoice validation asset_profile.open_asset = True self.assertTrue(len(invoice.invoice_line_ids) == 2) invoice.invoice_line_ids.write( {"quantity": 1, "asset_profile_id": asset_profile.id} ) invoice.action_post() # Retrieve all assets after invoice validation current_assets = self.env["account.asset"].search([]) # What are the new assets? new_assets = current_assets - all_assets self.assertEqual(len(new_assets), 2) for asset in new_assets: dlines = asset.depreciation_line_ids.filtered( lambda l: l.type == "depreciate" ) dlines = dlines.sorted(key=lambda l: l.line_date) self.assertAlmostEqual(dlines[0].depreciated_value, 0.0) self.assertAlmostEqual(dlines[-1].remaining_value, 0.0) def test_12_prorata_days_calc(self): """Prorata temporis depreciation with days calc option.""" asset = self.asset_model.create( { "name": "test asset", "profile_id": self.car5y.id, "purchase_value": 3333, "salvage_value": 0, "date_start": "2019-07-07", "method_time": "year", "method_number": 5, "method_period": "month", "prorata": True, "days_calc": True, "use_leap_years": False, } ) asset.compute_depreciation_board() asset.refresh() day_rate = 3333 / 1827 # 3333 / 1827 depreciation days for i in range(1, 10): self.assertAlmostEqual( asset.depreciation_line_ids[i].amount, asset.depreciation_line_ids[i].line_days * day_rate, places=2, ) # Last depreciation remaining self.assertAlmostEqual(asset.depreciation_line_ids[-1].amount, 11.05, places=2) def test_13_use_leap_year(self): # When you use the depreciation with years method and using lap years, # the depreciation amount is calculated as 10000 / 1826 days * 365 days # = yearly depreciation amount of 1998.90. # Then 1998.90 / 12 = 166.58 asset = self.asset_model.create( { "name": "test asset", "profile_id": self.car5y.id, "purchase_value": 10000, "salvage_value": 0, "date_start": time.strftime("2019-01-01"), "method_time": "year", "method_number": 5, "method_period": "month", "prorata": False, "days_calc": False, "use_leap_years": True, } ) asset.compute_depreciation_board() asset.refresh() for i in range(2, 11): self.assertAlmostEqual( asset.depreciation_line_ids[i].amount, 166.58, places=2 ) self.assertAlmostEqual( asset.depreciation_line_ids[13].depreciated_value, 1998.90, places=2 ) def test_14_not_use_leap_year(self): # When you run a depreciation with method = 'year' and no not use # lap years you divide 1000 / 5 years = 2000, then divided by 12 months # to get 166.67 per month, equal for all periods. asset = self.asset_model.create( { "name": "test asset", "profile_id": self.car5y.id, "purchase_value": 10000, "salvage_value": 0, "date_start": time.strftime("2019-01-01"), "method_time": "year", "method_number": 5, "method_period": "month", "prorata": False, "days_calc": False, "use_leap_years": False, } ) asset.compute_depreciation_board() asset.refresh() for _i in range(1, 11): self.assertAlmostEqual( asset.depreciation_line_ids[1].amount, 166.67, places=2 ) # In the last month of the fiscal year we compensate for the small # deviations if that is necessary. self.assertAlmostEqual(asset.depreciation_line_ids[12].amount, 166.63, places=2) def test_15_account_asset_group(self): """Group's name_get behaves differently depending on code and context""" group_fa = self.env["account.asset.group"].create( { "name": "Fixed Assets", "code": "FA", } ) group_tfa = self.env["account.asset.group"].create( { "name": "Tangible Fixed Assets", "code": "TFA", } ) # Groups are displayed by code (if any) plus name self.assertEqual( self.env["account.asset.group"].name_search("FA"), [(group_fa.id, "FA Fixed Assets")], ) # Groups with code are shown by code in list views self.assertEqual( self.env["account.asset.group"] .with_context(params={"view_type": "list"}) .name_search("FA"), [(group_fa.id, "FA")], ) self.assertEqual( self.env["account.asset.group"].name_search("TFA"), [(group_tfa.id, "TFA Tangible Fixed Assets")], ) group_tfa.code = False group_fa.code = False self.assertEqual(group_fa.name_get(), [(group_fa.id, "Fixed Assets")]) # Groups without code are shown by truncated name in lists self.assertEqual( group_tfa.name_get(), [(group_tfa.id, "Tangible Fixed Assets")] ) self.assertEqual( group_tfa.with_context(params={"view_type": "list"}).name_get(), [(group_tfa.id, "Tangible Fixed A...")], ) self.assertFalse(self.env["account.asset.group"].name_search("stessA dexiF")) def test_16_use_number_of_depreciations(self): # When you run a depreciation with method = 'number' profile = self.car5y profile.method_time = "number" asset = self.asset_model.create( { "name": "test asset", "profile_id": profile.id, "purchase_value": 10000, "salvage_value": 0, "date_start": time.strftime("2019-01-01"), "method_time": "year", "method_number": 5, "method_period": "month", "prorata": False, "days_calc": False, "use_leap_years": False, } ) asset.compute_depreciation_board() asset.refresh() for _i in range(1, 11): self.assertAlmostEqual( asset.depreciation_line_ids[1].amount, 166.67, places=2 ) # In the last month of the fiscal year we compensate for the small # deviations if that is necessary. self.assertAlmostEqual(asset.depreciation_line_ids[12].amount, 166.63, places=2) def test_17_carry_forward_missed_depreciations(self): """Asset with accumulate missed depreciations.""" asset_profile = self.car5y # Create an asset with carry_forward_missed_depreciations # Theoretically, the depreciation would be 5000 / 12 months # which is 416.67 per month asset = self.asset_model.create( { "name": "test asset", "profile_id": asset_profile.id, "purchase_value": 5000, "salvage_value": 0, "date_start": time.strftime("2021-01-01"), "method_time": "year", "method_number": 1, "method_period": "month", "carry_forward_missed_depreciations": True, } ) # Set the fiscalyear lock date for the company self.company_data["company"].fiscalyear_lock_date = time.strftime("2021-05-31") # Compute the depreciation board asset.compute_depreciation_board() asset.refresh() d_lines = asset.depreciation_line_ids init_lines = d_lines[1:6] # Jan to May entries are before the lock date -> marked as init self.assertTrue(init_lines.mapped("init_entry")) # Depreciation amount for these lines is set to 0 for line in init_lines: self.assertEqual(line.amount, 0.0) # The amount to be carried is 416.67 * 5 = 2083.35 # This amount is accumulated in the first depreciation for the current # available period -> 416.67 + 2083.35 = 2500.02 self.assertAlmostEqual(d_lines[6].amount, 2500.02, places=2) # The rest of the lines should have the corresponding amount of 416.67 # just as usual for _i in range(7, 12): self.assertAlmostEqual(d_lines[_i].amount, 416.67, places=2) # In the last month the small deviations are compensated self.assertAlmostEqual(d_lines[12].amount, 416.63, places=2) def test_18_reverse_entries(self): """Test that cancelling a posted entry creates a reversal.""" ict0 = self.asset_model.create( { "state": "draft", "method_time": "year", "method_number": 3, "method_period": "year", "name": "Laptop", "code": "PI00101", "purchase_value": 1500.0, "profile_id": self.ict3Y.id, "date_start": time.strftime("%Y-01-01"), } ) ict0.profile_id.allow_reversal = True # compute the depreciation boards ict0.compute_depreciation_board() ict0.refresh() # post the first depreciation line ict0.validate() ict0.depreciation_line_ids[1].create_move() original_move = ict0.depreciation_line_ids[1].move_id ict0.refresh() self.assertEqual(ict0.state, "open") self.assertEqual(ict0.value_depreciated, 500) self.assertEqual(ict0.value_residual, 1000) depreciation_line = ict0.depreciation_line_ids[1] wiz_res = depreciation_line.unlink_move() self.assertTrue( "res_model" in wiz_res and wiz_res["res_model"] == "wiz.asset.move.reverse" ) wiz = Form( self.env["wiz.asset.move.reverse"].with_context( **{ "active_model": depreciation_line._name, "active_id": depreciation_line.id, "active_ids": [depreciation_line.id], } ) ) reverse_wizard = wiz.save() reverse_wizard.write({"journal_id": depreciation_line.move_id.journal_id.id}) reverse_wizard.reverse_move() ict0.refresh() self.assertEqual(ict0.value_depreciated, 0) self.assertEqual(ict0.value_residual, 1500) self.assertEqual(len(original_move.reversal_move_id), 1) def test_19_unlink_entries(self): """Test that cancelling a posted entry creates a reversal, if the journal entry has the inalterability hash.""" ict0 = self.asset_model.create( { "state": "draft", "method_time": "year", "method_number": 3, "method_period": "year", "name": "Laptop", "code": "PI00101", "purchase_value": 1500.0, "profile_id": self.ict3Y.id, "date_start": time.strftime("%Y-01-01"), } ) # compute the depreciation boards ict0.compute_depreciation_board() ict0.refresh() # post the first depreciation line ict0.validate() ict0.depreciation_line_ids[1].create_move() original_move_id = ict0.depreciation_line_ids[1].move_id.id ict0.refresh() self.assertEqual(ict0.state, "open") self.assertEqual(ict0.value_depreciated, 500) self.assertEqual(ict0.value_residual, 1000) ict0.depreciation_line_ids[1].unlink_move() ict0.refresh() self.assertEqual(ict0.value_depreciated, 0) self.assertEqual(ict0.value_residual, 1500) move = self.env["account.move"].search([("id", "=", original_move_id)]) self.assertFalse(move) def test_20_asset_removal_with_value_residual(self): """Asset removal with value residual""" asset = self.asset_model.create( { "name": "test asset removal", "profile_id": self.car5y.id, "purchase_value": 1000, "salvage_value": 0, "date_start": "2019-01-01", "method_time": "number", "method_number": 10, "method_period": "month", "prorata": False, } ) asset.compute_depreciation_board() asset.validate() lines = asset.depreciation_line_ids.filtered(lambda x: not x.init_entry) self.assertEqual(len(lines), 10) last_line = lines[-1] last_line["amount"] = last_line["amount"] - 0.10 for asset_line in lines: asset_line.create_move() self.assertEqual(asset.value_residual, 0.10) asset.compute_depreciation_board() lines = asset.depreciation_line_ids.filtered(lambda x: not x.init_entry) self.assertEqual(len(lines), 11) last_line = lines[-1] self.assertEqual(last_line.amount, 0.10) last_line.create_move() self.assertEqual(asset.value_residual, 0) self.assertEqual(asset.state, "close")
40.499473
38,434
3,264
py
PYTHON
15.0
# Copyright 2009-2019 Noviat. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import time from odoo import fields from odoo.tests import tagged from odoo.addons.account.tests.common import AccountTestInvoicingCommon @tagged("post_install", "-at_install") class TestAssetManagementXls(AccountTestInvoicingCommon): @classmethod def setUpClass(cls): super(TestAssetManagementXls, cls).setUpClass() module = __name__.split("addons.")[1].split(".")[0] cls.xls_report_name = "{}.asset_report_xls".format(module) cls.wiz_model = cls.env["wiz.account.asset.report"] cls.company = cls.env.ref("base.main_company") # Ensure we have something to report on group_fa = cls.env["account.asset.group"].create( { "name": "Fixed Assets", "code": "FA", } ) group_tfa = cls.env["account.asset.group"].create( { "name": "Tangible Fixed Assets", "code": "TFA", "parent_id": group_fa.id, } ) ict3Y = cls.env["account.asset.profile"].create( { "account_expense_depreciation_id": cls.company_data[ "default_account_expense" ].id, "account_asset_id": cls.company_data["default_account_assets"].id, "account_depreciation_id": cls.company_data[ "default_account_assets" ].id, "group_ids": [(6, 0, group_tfa.ids)], "journal_id": cls.company_data["default_journal_purchase"].id, "name": "Hardware - 3 Years", "method_time": "year", "method_number": 3, "method_period": "year", } ) cls.env["account.asset"].create( { "state": "draft", "method_time": "year", "method_number": 3, "method_period": "year", "name": "Laptop", "code": "PI00101", "purchase_value": 1500.0, "profile_id": ict3Y.id, "date_start": time.strftime("%Y-01-01"), } ).validate() fy_dates = cls.company.compute_fiscalyear_dates(fields.date.today()) wiz_vals = { "asset_group_id": group_fa.id, "date_from": fy_dates["date_from"], "date_to": fy_dates["date_to"], } cls.xls_report = cls.wiz_model.create(wiz_vals) cls.report_action = cls.xls_report.xls_export() def test_01_action_xls(self): """Check report XLS action and generate report""" self.assertGreaterEqual( self.report_action.items(), { "type": "ir.actions.report", "report_type": "xlsx", "report_name": self.xls_report_name, }.items(), ) model = self.env["report.%s" % self.report_action["report_name"]].with_context( active_model=self.xls_report._name, **self.report_action["context"] ) model.create_xlsx_report(self.xls_report.ids, data=self.report_action["data"])
37.090909
3,264
2,078
py
PYTHON
15.0
# Copyright 2009-2018 Noviat # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, fields, models class AccountAssetCompute(models.TransientModel): _name = "account.asset.compute" _description = "Compute Assets" date_end = fields.Date( string="Date", required=True, default=fields.Date.today, help="All depreciation lines prior to this date will be automatically" " posted", ) note = fields.Text() def asset_compute(self): assets = self.env["account.asset"].search([("state", "=", "open")]) created_move_ids, error_log = assets._compute_entries( self.date_end, check_triggers=True ) if error_log: module = __name__.split("addons.")[1].split(".")[0] result_view = self.env.ref( "{}.{}_view_form_result".format(module, self._table) ) self.note = _("Compute Assets errors") + ":\n" + error_log return { "name": _("Compute Assets result"), "res_id": self.id, "view_mode": "form", "res_model": "account.asset.compute", "view_id": result_view.id, "target": "new", "type": "ir.actions.act_window", "context": {"asset_move_ids": created_move_ids}, } return { "name": _("Created Asset Moves"), "view_mode": "tree,form", "res_model": "account.move", "view_id": False, "domain": [("id", "in", created_move_ids)], "type": "ir.actions.act_window", } def view_asset_moves(self): self.ensure_one() domain = [("id", "in", self.env.context.get("asset_move_ids", []))] return { "name": _("Created Asset Moves"), "view_mode": "tree,form", "res_model": "account.move", "view_id": False, "domain": domain, "type": "ir.actions.act_window", }
33.516129
2,078
14,110
py
PYTHON
15.0
# Copyright 2009-2018 Noviat # Copyright 2021 Tecnativa - João Marques # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from dateutil.relativedelta import relativedelta from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError _logger = logging.getLogger(__name__) class AccountAssetRemove(models.TransientModel): _name = "account.asset.remove" _description = "Remove Asset" _check_company_auto = True company_id = fields.Many2one( comodel_name="res.company", string="Company", readonly=True, required=True, default=lambda self: self._default_company_id(), ) date_remove = fields.Date( string="Asset Removal Date", required=True, default=fields.Date.today, help="Removal date must be after the last posted entry " "in case of early removal", ) force_date = fields.Date(string="Force accounting date") sale_value = fields.Float(default=lambda self: self._default_sale_value()) account_sale_id = fields.Many2one( comodel_name="account.account", string="Asset Sale Account", domain="[('deprecated', '=', False), ('company_id', '=', company_id)]", default=lambda self: self._default_account_sale_id(), ) account_plus_value_id = fields.Many2one( comodel_name="account.account", string="Plus-Value Account", domain="[('deprecated', '=', False), ('company_id', '=', company_id)]", default=lambda self: self._default_account_plus_value_id(), ) account_min_value_id = fields.Many2one( comodel_name="account.account", string="Min-Value Account", domain="[('deprecated', '=', False), ('company_id', '=', company_id)]", default=lambda self: self._default_account_min_value_id(), ) account_residual_value_id = fields.Many2one( comodel_name="account.account", string="Residual Value Account", domain="[('deprecated', '=', False), ('company_id', '=', company_id)]", default=lambda self: self._default_account_residual_value_id(), ) posting_regime = fields.Selection( selection=lambda self: self._selection_posting_regime(), string="Removal Entry Policy", required=True, default=lambda self: self._get_posting_regime(), help="Removal Entry Policy \n" " * Residual Value: The non-depreciated value will be " "posted on the 'Residual Value Account' \n" " * Gain/Loss on Sale: The Gain or Loss will be posted on " "the 'Plus-Value Account' or 'Min-Value Account' ", ) note = fields.Text("Notes") @api.constrains("sale_value") def _check_sale_value(self): if self.sale_value < 0: raise ValidationError(_("The Sale Value must be positive!")) @api.model def _default_company_id(self): asset_id = self.env.context.get("active_id") asset = self.env["account.asset"].browse(asset_id) return asset.company_id @api.model def _default_sale_value(self): return self._get_sale()["sale_value"] @api.model def _default_account_sale_id(self): return self._get_sale()["account_sale_id"] def _get_sale(self): asset_id = self.env.context.get("active_id") sale_value = 0.0 account_sale_id = False inv_lines = self.env["account.move.line"].search( [ ("asset_id", "=", asset_id), ("move_id.move_type", "in", ("out_invoice", "out_refund")), ] ) for line in inv_lines: inv = line.move_id comp_curr = inv.company_currency_id inv_curr = inv.currency_id if line.move_id.payment_state == "paid" or line.parent_state == "draft": account_sale_id = line.account_id.id amount = line.price_subtotal if inv_curr != comp_curr: amount = comp_curr.compute(amount) sale_value += amount return {"sale_value": sale_value, "account_sale_id": account_sale_id} @api.model def _default_account_plus_value_id(self): asset_id = self.env.context.get("active_id") asset = self.env["account.asset"].browse(asset_id) return asset.profile_id.account_plus_value_id @api.model def _default_account_min_value_id(self): asset_id = self.env.context.get("active_id") asset = self.env["account.asset"].browse(asset_id) return asset.profile_id.account_min_value_id @api.model def _default_account_residual_value_id(self): asset_id = self.env.context.get("active_id") asset = self.env["account.asset"].browse(asset_id) return asset.profile_id.account_residual_value_id @api.model def _selection_posting_regime(self): return [ ("residual_value", _("Residual Value")), ("gain_loss_on_sale", _("Gain/Loss on Sale")), ] @api.model def _get_posting_regime(self): asset_obj = self.env["account.asset"] asset = asset_obj.browse(self.env.context.get("active_id")) country = asset and asset.company_id.country_id.code or False if country in self._residual_value_regime_countries(): return "residual_value" else: return "gain_loss_on_sale" def _residual_value_regime_countries(self): return ["FR"] def remove(self): self.ensure_one() asset_line_obj = self.env["account.asset.line"] asset_id = self.env.context.get("active_id") asset = self.env["account.asset"].browse(asset_id) asset_ref = ( asset.code and "{} (ref: {})".format(asset.name, asset.code) or asset.name ) if self.env.context.get("early_removal"): residual_value = self._prepare_early_removal(asset) else: residual_value = asset.value_residual dlines = asset_line_obj.search( [ ("asset_id", "=", asset.id), ("type", "=", "depreciate"), ("move_check", "!=", False), ], order="line_date desc", ) if dlines: last_date = dlines[0].line_date else: create_dl = asset_line_obj.search( [("asset_id", "=", asset.id), ("type", "=", "create")] )[0] last_date = create_dl.line_date if self.date_remove < last_date: raise UserError( _("The removal date must be after " "the last depreciation date.") ) line_name = asset._get_depreciation_entry_name(len(dlines) + 1) journal_id = asset.profile_id.journal_id.id if not self.force_date: date_remove = self.date_remove else: date_remove = self.force_date # create move move_vals = { "date": date_remove, "ref": line_name, "journal_id": journal_id, "narration": self.note, } move = self.env["account.move"].create(move_vals) # create asset line asset_line_vals = { "amount": residual_value, "asset_id": asset_id, "name": line_name, "line_date": self.date_remove, "move_id": move.id, "type": "remove", } asset_line_obj.create(asset_line_vals) asset.write({"state": "removed", "date_remove": self.date_remove}) # create move lines move_lines = self._get_removal_data(asset, residual_value) move.with_context(allow_asset=True).write({"line_ids": move_lines}) return { "name": _("Asset '%s' Removal Journal Entry") % asset_ref, "view_mode": "tree,form", "res_model": "account.move", "view_id": False, "type": "ir.actions.act_window", "context": self.env.context, "domain": [("id", "=", move.id)], } def _prepare_early_removal(self, asset): """ Generate last depreciation entry on the day before the removal date. """ date_remove = self.date_remove asset_line_obj = self.env["account.asset.line"] digits = self.env["decimal.precision"].precision_get("Account") def _dlines(asset): lines = asset.depreciation_line_ids dlines = lines.filtered( lambda l: l.type == "depreciate" and not l.init_entry and not l.move_check ) dlines = dlines.sorted(key=lambda l: l.line_date) return dlines dlines = _dlines(asset) if not dlines: asset.compute_depreciation_board() dlines = _dlines(asset) if not dlines: return asset.value_residual first_to_depreciate_dl = dlines[0] first_date = first_to_depreciate_dl.line_date if date_remove > first_date: raise UserError( _( "You can't make an early removal if all the depreciation " "lines for previous periods are not posted." ) ) if first_to_depreciate_dl.previous_id: last_depr_date = first_to_depreciate_dl.previous_id.line_date else: create_dl = asset_line_obj.search( [("asset_id", "=", asset.id), ("type", "=", "create")] ) last_depr_date = create_dl.line_date # Never create move. same_month = ( last_depr_date.month == first_to_depreciate_dl.line_date.month and 1 or 0 ) period_number_days = (first_date - last_depr_date).days + same_month new_line_date = date_remove + relativedelta(days=-1) to_depreciate_days = (new_line_date - last_depr_date).days + same_month to_depreciate_amount = round( float(to_depreciate_days) / float(period_number_days) * first_to_depreciate_dl.amount, digits, ) residual_value = asset.value_residual - to_depreciate_amount if to_depreciate_amount: update_vals = { "amount": to_depreciate_amount, "line_date": new_line_date, "line_days": to_depreciate_days, } first_to_depreciate_dl.write(update_vals) dlines[0].create_move() dlines -= dlines[0] dlines.unlink() return residual_value def _get_removal_data(self, asset, residual_value): move_lines = [] partner_id = asset.partner_id and asset.partner_id.id or False profile = asset.profile_id # asset and asset depreciation account reversal depr_amount = asset.depreciation_base - residual_value if depr_amount: move_line_vals = { "name": asset.name, "account_id": profile.account_depreciation_id.id, "debit": depr_amount > 0 and depr_amount or 0.0, "credit": depr_amount < 0 and -depr_amount or 0.0, "partner_id": partner_id, "asset_id": asset.id, } move_lines.append((0, 0, move_line_vals)) move_line_vals = { "name": asset.name, "account_id": profile.account_asset_id.id, "debit": (asset.depreciation_base < 0 and -asset.depreciation_base or 0.0), "credit": (asset.depreciation_base > 0 and asset.depreciation_base or 0.0), "partner_id": partner_id, "asset_id": asset.id, } move_lines.append((0, 0, move_line_vals)) if residual_value: if self.posting_regime == "residual_value": move_line_vals = { "name": asset.name, "account_id": self.account_residual_value_id.id, "analytic_account_id": asset.account_analytic_id.id, "analytic_tag_ids": [(4, tag.id) for tag in asset.analytic_tag_ids], "debit": residual_value, "credit": 0.0, "partner_id": partner_id, "asset_id": asset.id, } move_lines.append((0, 0, move_line_vals)) elif self.posting_regime == "gain_loss_on_sale": if self.sale_value: sale_value = self.sale_value move_line_vals = { "name": asset.name, "account_id": self.account_sale_id.id, "analytic_account_id": asset.account_analytic_id.id, "analytic_tag_ids": [ (4, tag.id) for tag in asset.analytic_tag_ids ], "debit": sale_value, "credit": 0.0, "partner_id": partner_id, "asset_id": asset.id, } move_lines.append((0, 0, move_line_vals)) balance = self.sale_value - residual_value account_id = ( self.account_plus_value_id.id if balance > 0 else self.account_min_value_id.id ) move_line_vals = { "name": asset.name, "account_id": account_id, "analytic_account_id": asset.account_analytic_id.id, "analytic_tag_ids": [(4, tag.id) for tag in asset.analytic_tag_ids], "debit": balance < 0 and -balance or 0.0, "credit": balance > 0 and balance or 0.0, "partner_id": partner_id, "asset_id": asset.id, } move_lines.append((0, 0, move_line_vals)) return move_lines
37.624
14,109
2,052
py
PYTHON
15.0
# Copyright 2021 ForgeFlow, S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class WizAssetMoveReverse(models.TransientModel): _name = "wiz.asset.move.reverse" _description = "Reverse posted journal entry on depreciation line" line_id = fields.Many2one( comodel_name="account.asset.line", string="Asset Line", readonly=True, required=True, ) date_reversal = fields.Date( string="Reversal date", required=True, default=fields.Date.context_today, ) reason = fields.Char() journal_id = fields.Many2one( "account.journal", string="Use Specific Journal", help="If empty, uses the journal of the journal entry to be reversed.", ) @api.model def default_get(self, fields): res = super(WizAssetMoveReverse, self).default_get(fields) line_ids = ( self.env["account.asset.line"].browse(self.env.context["active_ids"]) if self.env.context.get("active_model") == "account.asset.line" else self.env["account.asset.line"] ) res["line_id"] = line_ids[0].id if line_ids else False return res def reverse_move(self): move = self.line_id.move_id move_reversal = ( self.env["account.move.reversal"] .with_context(active_model="account.move", active_ids=move.ids) .create( { "date": fields.Date.today(), "reason": self.reason, "refund_method": "refund", "journal_id": self.journal_id.id, } ) ) reversal = move_reversal.with_context(allow_asset=True).reverse_moves() reverse_move = self.env["account.move"].browse(reversal["res_id"]) reverse_move.action_post() self.line_id.with_context( unlink_from_asset=True ).update_asset_line_after_unlink_move() return True
34.779661
2,052
2,421
py
PYTHON
15.0
# Copyright 2009-2019 Noviat # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import unicodedata from odoo import _, api, fields, models from odoo.exceptions import UserError class WizAccountAssetReport(models.TransientModel): _name = "wiz.account.asset.report" _description = "Financial Assets report" asset_group_id = fields.Many2one( comodel_name="account.asset.group", string="Asset Group", default=lambda self: self._default_asset_group_id(), ) date_from = fields.Date(string="Start Date", required=True) date_to = fields.Date(string="End Date", required=True) draft = fields.Boolean(string="Include draft assets") company_id = fields.Many2one( comodel_name="res.company", string="Company", required=True, default=lambda self: self._default_company_id(), ) @api.model def _default_asset_group_id(self): return ( self.env["account.asset.group"] .search([("parent_id", "=", False)], limit=1) .id ) @api.model def _default_company_id(self): return self.env.company @api.onchange("company_id") def _onchange_company_id(self): fy_dates = self.company_id.compute_fiscalyear_dates(fields.date.today()) self.date_from = fy_dates["date_from"] self.date_to = fy_dates["date_to"] @api.constrains("date_from", "date_to") def _check_dates(self): for wiz in self: if wiz.date_to <= wiz.date_from: raise UserError(_("The Start Date must precede the Ending Date.")) def xls_export(self): self.ensure_one() report_name = "account_asset_management.asset_report_xls" if self.asset_group_id: prefix = ( unicodedata.normalize("NFKD", self.asset_group_id.name) .encode("ascii", "ignore") .decode("ascii") ) prefix = "".join(x for x in prefix if x.isalnum()) report_file = "{}_asset_report".format(prefix) else: report_file = "asset_report" report = { "type": "ir.actions.report", "report_type": "xlsx", "report_name": report_name, "context": dict(self.env.context, report_file=report_file), "data": {"dynamic_report": True}, } return report
33.164384
2,421
9,927
py
PYTHON
15.0
# Copyright 2009-2018 Noviat # Copyright 2021 Tecnativa - João Marques # Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from odoo import _, api, fields, models from odoo.exceptions import UserError from odoo.tests.common import Form _logger = logging.getLogger(__name__) # List of move's fields that can't be modified if move is linked # with a depreciation line FIELDS_AFFECTS_ASSET_MOVE = {"journal_id", "date"} # List of move line's fields that can't be modified if move is linked # with a depreciation line FIELDS_AFFECTS_ASSET_MOVE_LINE = { "credit", "debit", "account_id", "journal_id", "date", "asset_profile_id", "asset_id", } class AccountMove(models.Model): _inherit = "account.move" asset_count = fields.Integer(compute="_compute_asset_count") def _compute_asset_count(self): for rec in self: assets = ( self.env["account.asset.line"] .search([("move_id", "=", rec.id)]) .mapped("asset_id") ) rec.asset_count = len(assets) def unlink(self): # for move in self: deprs = self.env["account.asset.line"].search( [("move_id", "in", self.ids), ("type", "in", ["depreciate", "remove"])] ) if deprs and not self.env.context.get("unlink_from_asset"): raise UserError( _( "You are not allowed to remove an accounting entry " "linked to an asset." "\nYou should remove such entries from the asset." ) ) # trigger store function deprs.write({"move_id": False}) return super().unlink() def write(self, vals): if set(vals).intersection(FIELDS_AFFECTS_ASSET_MOVE): deprs = ( self.env["account.asset.line"] .sudo() .search([("move_id", "in", self.ids), ("type", "=", "depreciate")]) ) if deprs: raise UserError( _( "You cannot change an accounting entry " "linked to an asset depreciation line." ) ) return super().write(vals) def _prepare_asset_vals(self, aml): depreciation_base = aml.balance return { "name": aml.name, "code": self.name, "profile_id": aml.asset_profile_id, "purchase_value": depreciation_base, "partner_id": aml.partner_id, "date_start": self.date, "account_analytic_id": aml.analytic_account_id, } def action_post(self): ret_val = super().action_post() for move in self: for aml in move.line_ids.filtered( lambda line: line.asset_profile_id and not line.tax_line_id ): vals = move._prepare_asset_vals(aml) if not aml.name: raise UserError( _("Asset name must be set in the label of the line.") ) if aml.asset_id: continue asset_form = Form( self.env["account.asset"] .with_company(move.company_id) .with_context(create_asset_from_move_line=True, move_id=move.id) ) for key, val in vals.items(): setattr(asset_form, key, val) asset = asset_form.save() asset.analytic_tag_ids = aml.analytic_tag_ids aml.with_context( allow_asset=True, allow_asset_removal=True ).asset_id = asset.id refs = [ "<a href=# data-oe-model=account.asset data-oe-id=%s>%s</a>" % tuple(name_get) for name_get in move.line_ids.filtered( "asset_profile_id" ).asset_id.name_get() ] if refs: message = _("This invoice created the asset(s): %s") % ", ".join(refs) move.message_post(body=message) return ret_val def button_draft(self): invoices = self.filtered(lambda r: r.is_purchase_document()) if invoices: invoices.line_ids.asset_id.unlink() return super().button_draft() def _reverse_move_vals(self, default_values, cancel=True): move_vals = super()._reverse_move_vals(default_values, cancel) if move_vals["move_type"] not in ("out_invoice", "out_refund"): for line_command in move_vals.get("line_ids", []): line_vals = line_command[2] # (0, 0, {...}) asset = self.env["account.asset"].browse(line_vals["asset_id"]) # We remove the asset if we recognize that we are reversing # the asset creation if asset: asset_line = self.env["account.asset.line"].search( [("asset_id", "=", asset.id), ("type", "=", "create")], limit=1 ) if asset_line and asset_line.move_id == self: asset.unlink() line_vals.update(asset_profile_id=False, asset_id=False) return move_vals def action_view_assets(self): assets = ( self.env["account.asset.line"] .search([("move_id", "=", self.id)]) .mapped("asset_id") ) action = self.env.ref("account_asset_management.account_asset_action") action_dict = action.sudo().read()[0] if len(assets) == 1: res = self.env.ref( "account_asset_management.account_asset_view_form", False ) action_dict["views"] = [(res and res.id or False, "form")] action_dict["res_id"] = assets.id elif assets: action_dict["domain"] = [("id", "in", assets.ids)] else: action_dict = {"type": "ir.actions.act_window_close"} return action_dict class AccountMoveLine(models.Model): _inherit = "account.move.line" asset_profile_id = fields.Many2one( comodel_name="account.asset.profile", string="Asset Profile", compute="_compute_asset_profile", store=True, readonly=False, ) asset_id = fields.Many2one( comodel_name="account.asset", string="Asset", ondelete="restrict", ) @api.depends("account_id", "asset_id") def _compute_asset_profile(self): for rec in self: if rec.account_id.asset_profile_id and not rec.asset_id: rec.asset_profile_id = rec.account_id.asset_profile_id elif rec.asset_id: rec.asset_profile_id = rec.asset_id.profile_id @api.onchange("asset_profile_id") def _onchange_asset_profile_id(self): if self.asset_profile_id.account_asset_id: self.account_id = self.asset_profile_id.account_asset_id @api.model_create_multi def create(self, vals_list): for vals in vals_list: move = self.env["account.move"].browse(vals.get("move_id")) if not move.is_sale_document(): if vals.get("asset_id") and not self.env.context.get("allow_asset"): raise UserError( _( "You are not allowed to link " "an accounting entry to an asset." "\nYou should generate such entries from the asset." ) ) records = super().create(vals_list) for record in records: record._expand_asset_line() return records def write(self, vals): if set(vals).intersection(FIELDS_AFFECTS_ASSET_MOVE_LINE) and not ( self.env.context.get("allow_asset_removal") and list(vals.keys()) == ["asset_id"] ): # Check if at least one asset is linked to a move linked_asset = False for move_line in self.filtered(lambda r: not r.move_id.is_sale_document()): linked_asset = move_line.asset_id if linked_asset: raise UserError( _( "You cannot change an accounting item " "linked to an asset depreciation line." ) ) if ( self.filtered(lambda r: not r.move_id.is_sale_document()) and vals.get("asset_id") and not self.env.context.get("allow_asset") ): raise UserError( _( "You are not allowed to link " "an accounting entry to an asset." "\nYou should generate such entries from the asset." ) ) super().write(vals) if "quantity" in vals or "asset_profile_id" in vals: for record in self: record._expand_asset_line() return True def _expand_asset_line(self): self.ensure_one() if self.asset_profile_id and self.quantity > 1.0: profile = self.asset_profile_id if profile.asset_product_item: aml = self.with_context(check_move_validity=False) qty = self.quantity name = self.name aml.write({"quantity": 1, "name": "{} {}".format(name, 1)}) aml._onchange_price_subtotal() for i in range(1, int(qty)): aml.copy({"name": "{} {}".format(name, i + 1)}) aml.move_id._onchange_invoice_line_ids()
37.590909
9,924
13,191
py
PYTHON
15.0
# Copyright 2009-2018 Noviat # Copyright 2021 Tecnativa - João Marques # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import UserError class AccountAssetLine(models.Model): _name = "account.asset.line" _description = "Asset depreciation table line" _order = "type, line_date" _check_company_auto = True name = fields.Char(string="Depreciation Name", size=64, readonly=True) asset_id = fields.Many2one( comodel_name="account.asset", string="Asset", required=True, ondelete="cascade", check_company=True, index=True, ) previous_id = fields.Many2one( comodel_name="account.asset.line", string="Previous Depreciation Line", readonly=True, ) parent_state = fields.Selection( related="asset_id.state", string="State of Asset", readonly=True ) depreciation_base = fields.Float( related="asset_id.depreciation_base", string="Depreciation Base", readonly=True ) amount = fields.Float(digits="Account", required=True) remaining_value = fields.Float( compute="_compute_values", digits="Account", string="Next Period Depreciation", store=True, ) depreciated_value = fields.Float( compute="_compute_values", digits="Account", string="Amount Already Depreciated", store=True, ) line_date = fields.Date(string="Date", required=True) line_days = fields.Integer(string="Days", readonly=True) move_id = fields.Many2one( comodel_name="account.move", string="Depreciation Entry", readonly=True, check_company=True, ) move_check = fields.Boolean( compute="_compute_move_check", string="Posted", store=True ) type = fields.Selection( selection=[ ("create", "Depreciation Base"), ("depreciate", "Depreciation"), ("remove", "Asset Removal"), ], readonly=True, default="depreciate", ) init_entry = fields.Boolean( string="Initial Balance Entry", help="Set this flag for entries of previous fiscal years " "for which Odoo has not generated accounting entries.", ) company_id = fields.Many2one( "res.company", store=True, readonly=True, related="asset_id.company_id", ) @api.depends("amount", "previous_id", "type") def _compute_values(self): self.depreciated_value = 0.0 self.remaining_value = 0.0 dlines = self if self.env.context.get("no_compute_asset_line_ids"): # skip compute for lines in unlink exclude_ids = self.env.context["no_compute_asset_line_ids"] dlines = self.filtered(lambda l: l.id not in exclude_ids) dlines = dlines.filtered(lambda l: l.type == "depreciate") dlines = dlines.sorted(key=lambda l: l.line_date) # Give value 0 to the lines that are not going to be calculated # to avoid cache miss error all_excluded_lines = self - dlines all_excluded_lines.depreciated_value = 0 all_excluded_lines.remaining_value = 0 # Group depreciation lines per asset asset_ids = dlines.mapped("asset_id") grouped_dlines = [] for asset in asset_ids: grouped_dlines.append(dlines.filtered(lambda l: l.asset_id.id == asset.id)) for dlines in grouped_dlines: for i, dl in enumerate(dlines): if i == 0: depreciation_base = dl.depreciation_base tmp = depreciation_base - dl.previous_id.remaining_value depreciated_value = dl.previous_id and tmp or 0.0 remaining_value = depreciation_base - depreciated_value - dl.amount else: depreciated_value += dl.previous_id.amount remaining_value -= dl.amount dl.depreciated_value = depreciated_value dl.remaining_value = remaining_value @api.depends("move_id") def _compute_move_check(self): for line in self: line.move_check = bool(line.move_id) @api.onchange("amount") def _onchange_amount(self): if self.type == "depreciate": self.remaining_value = ( self.depreciation_base - self.depreciated_value - self.amount ) def write(self, vals): for dl in self: line_date = vals.get("line_date") or dl.line_date asset_lines = dl.asset_id.depreciation_line_ids if list(vals.keys()) == ["move_id"] and not vals["move_id"]: # allow to remove an accounting entry via the # 'Delete Move' button on the depreciation lines. if not self.env.context.get("unlink_from_asset"): raise UserError( _( "You are not allowed to remove an accounting entry " "linked to an asset." "\nYou should remove such entries from the asset." ) ) elif list(vals.keys()) == ["asset_id"]: continue elif ( dl.move_id and not self.env.context.get("allow_asset_line_update") and dl.type != "create" ): raise UserError( _( "You cannot change a depreciation line " "with an associated accounting entry." ) ) elif vals.get("init_entry"): check = asset_lines.filtered( lambda l: l.move_check and l.type == "depreciate" and l.line_date <= line_date ) if check: raise UserError( _( "You cannot set the 'Initial Balance Entry' flag " "on a depreciation line " "with prior posted entries." ) ) elif vals.get("line_date"): if dl.type == "create": check = asset_lines.filtered( lambda l: l.type != "create" and (l.init_entry or l.move_check) and l.line_date < fields.Date.to_date(vals["line_date"]) ) if check: raise UserError( _( "You cannot set the Asset Start Date " "after already posted entries." ) ) else: check = asset_lines.filtered( lambda al: al != dl and (al.init_entry or al.move_check) and al.line_date > fields.Date.to_date(vals["line_date"]) ) if check: raise UserError( _( "You cannot set the date on a depreciation line " "prior to already posted entries." ) ) return super().write(vals) def unlink(self): for dl in self: if dl.type == "create" and dl.amount: raise UserError( _("You cannot remove an asset line " "of type 'Depreciation Base'.") ) elif dl.move_id: raise UserError( _( "You cannot delete a depreciation line with " "an associated accounting entry." ) ) previous = dl.previous_id next_line = dl.asset_id.depreciation_line_ids.filtered( lambda l: l.previous_id == dl and l not in self ) if next_line: next_line.previous_id = previous return super( AccountAssetLine, self.with_context(no_compute_asset_line_ids=self.ids) ).unlink() def _setup_move_data(self, depreciation_date): asset = self.asset_id move_data = { "date": depreciation_date, "ref": "{} - {}".format(asset.name, self.name), "journal_id": asset.profile_id.journal_id.id, } return move_data def _setup_move_line_data(self, depreciation_date, account, ml_type, move): """Prepare data to be propagated to account.move.line""" asset = self.asset_id amount = self.amount analytic_id = False analytic_tags = self.env["account.analytic.tag"] if ml_type == "depreciation": debit = amount < 0 and -amount or 0.0 credit = amount > 0 and amount or 0.0 elif ml_type == "expense": debit = amount > 0 and amount or 0.0 credit = amount < 0 and -amount or 0.0 analytic_id = asset.account_analytic_id.id analytic_tags = asset.analytic_tag_ids move_line_data = { "name": asset.name, "ref": self.name, "move_id": move.id, "account_id": account.id, "credit": credit, "debit": debit, "journal_id": asset.profile_id.journal_id.id, "partner_id": asset.partner_id.id, "analytic_account_id": analytic_id, "analytic_tag_ids": [(4, tag.id) for tag in analytic_tags], "date": depreciation_date, "asset_id": asset.id, } return move_line_data def create_move(self): created_move_ids = [] asset_ids = set() ctx = dict(self.env.context, allow_asset=True, check_move_validity=False) for line in self: asset = line.asset_id depreciation_date = line.line_date am_vals = line._setup_move_data(depreciation_date) move = self.env["account.move"].with_context(**ctx).create(am_vals) depr_acc = asset.profile_id.account_depreciation_id exp_acc = asset.profile_id.account_expense_depreciation_id aml_d_vals = line._setup_move_line_data( depreciation_date, depr_acc, "depreciation", move ) self.env["account.move.line"].with_context(**ctx).create(aml_d_vals) aml_e_vals = line._setup_move_line_data( depreciation_date, exp_acc, "expense", move ) self.env["account.move.line"].with_context(**ctx).create(aml_e_vals) move.action_post() line.with_context(allow_asset_line_update=True).write({"move_id": move.id}) created_move_ids.append(move.id) asset_ids.add(asset.id) # we re-evaluate the assets to determine if we can close them for asset in self.env["account.asset"].browse(list(asset_ids)): if asset.company_currency_id.is_zero(asset.value_residual): asset.state = "close" return created_move_ids def open_move(self): self.ensure_one() return { "name": _("Journal Entry"), "view_mode": "form", "res_id": self.move_id.id, "res_model": "account.move", "view_id": False, "type": "ir.actions.act_window", "context": self.env.context, } def update_asset_line_after_unlink_move(self): self.write({"move_id": False}) if self.parent_state == "close": self.asset_id.write({"state": "open"}) elif self.parent_state == "removed" and self.type == "remove": self.asset_id.write({"state": "close", "date_remove": False}) self.unlink() def unlink_move(self): for line in self: if line.asset_id.profile_id.allow_reversal: context = dict(self._context or {}) context.update( { "active_model": self._name, "active_ids": line.ids, "active_id": line.id, } ) return { "name": _("Reverse Move"), "view_mode": "form", "res_model": "wiz.asset.move.reverse", "target": "new", "type": "ir.actions.act_window", "context": context, } else: move = line.move_id move.button_draft() move.with_context(force_delete=True, unlink_from_asset=True).unlink() line.with_context( unlink_from_asset=True ).update_asset_line_after_unlink_move() return True
39.491018
13,190
946
py
PYTHON
15.0
# Copyright 2009-2017 Noviat # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class AccountAccount(models.Model): _inherit = "account.account" asset_profile_id = fields.Many2one( comodel_name="account.asset.profile", string="Asset Profile", help="Default Asset Profile when creating invoice lines " "with this account.", ) @api.constrains("asset_profile_id") def _check_asset_profile(self): for account in self: if ( account.asset_profile_id and account.asset_profile_id.account_asset_id != account ): raise ValidationError( _( "The Asset Account defined in the Asset Profile " "must be equal to the account." ) )
32.62069
946
9,032
py
PYTHON
15.0
# Copyright 2009-2018 Noviat # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import UserError class AccountAssetProfile(models.Model): _name = "account.asset.profile" _check_company_auto = True _description = "Asset profile" _order = "name" name = fields.Char(size=64, required=True, index=True) note = fields.Text() account_analytic_id = fields.Many2one( comodel_name="account.analytic.account", string="Analytic account" ) analytic_tag_ids = fields.Many2many( comodel_name="account.analytic.tag", string="Analytic tags" ) account_asset_id = fields.Many2one( comodel_name="account.account", domain="[('deprecated', '=', False), ('company_id', '=', company_id)]", string="Asset Account", check_company=True, required=True, ) account_depreciation_id = fields.Many2one( comodel_name="account.account", domain="[('deprecated', '=', False), ('company_id', '=', company_id)]", string="Depreciation Account", check_company=True, required=True, ) account_expense_depreciation_id = fields.Many2one( comodel_name="account.account", domain="[('deprecated', '=', False), ('company_id', '=', company_id)]", string="Depr. Expense Account", check_company=True, required=True, ) account_plus_value_id = fields.Many2one( comodel_name="account.account", domain="[('deprecated', '=', False), ('company_id', '=', company_id)]", check_company=True, string="Plus-Value Account", ) account_min_value_id = fields.Many2one( comodel_name="account.account", domain="[('deprecated', '=', False), ('company_id', '=', company_id)]", check_company=True, string="Min-Value Account", ) account_residual_value_id = fields.Many2one( comodel_name="account.account", domain="[('deprecated', '=', False), ('company_id', '=', company_id)]", check_company=True, string="Residual Value Account", ) journal_id = fields.Many2one( comodel_name="account.journal", domain="[('type', '=', 'general'), ('company_id', '=', company_id)]", string="Journal", check_company=True, required=True, ) company_id = fields.Many2one( comodel_name="res.company", string="Company", required=True, default=lambda self: self._default_company_id(), ) group_ids = fields.Many2many( comodel_name="account.asset.group", relation="account_asset_profile_group_rel", column1="profile_id", column2="group_id", check_company=True, string="Asset Groups", ) method = fields.Selection( selection=lambda self: self._selection_method(), string="Computation Method", required=True, help="Choose the method to use to compute the depreciation lines.\n" " * Linear: Calculated on basis of: " "Depreciation Base / Number of Depreciations. " "Depreciation Base = Purchase Value - Salvage Value.\n" " * Linear-Limit: Linear up to Salvage Value. " "Depreciation Base = Purchase Value.\n" " * Degressive: Calculated on basis of: " "Residual Value * Degressive Factor.\n" " * Degressive-Linear (only for Time Method = Year): " "Degressive becomes linear when the annual linear " "depreciation exceeds the annual degressive depreciation.\n" " * Degressive-Limit: Degressive up to Salvage Value. " "The Depreciation Base is equal to the asset value.", default="linear", ) method_number = fields.Integer( string="Number of Years", help="The number of years needed to depreciate your asset", default=5, ) method_period = fields.Selection( selection=lambda self: self._selection_method_period(), string="Period Length", required=True, default="year", help="Period length for the depreciation accounting entries", ) method_progress_factor = fields.Float(string="Degressive Factor", default=0.3) method_time = fields.Selection( selection=lambda self: self._selection_method_time(), string="Time Method", required=True, default="year", help="Choose the method to use to compute the dates and " "number of depreciation lines.\n" " * Number of Years: Specify the number of years " "for the depreciation.\n" " * Number of Depreciations: Fix the number of " "depreciation lines and the time between 2 depreciations.\n", ) days_calc = fields.Boolean( string="Calculate by days", default=False, help="Use number of days to calculate depreciation amount", ) use_leap_years = fields.Boolean( default=False, help="If not set, the system will distribute evenly the amount to " "amortize across the years, based on the number of years. " "So the amount per year will be the " "depreciation base / number of years.\n " "If set, the system will consider if the current year " "is a leap year. The amount to depreciate per year will be " "calculated as depreciation base / (depreciation end date - " "start date + 1) * days in the current year.", ) prorata = fields.Boolean( string="Prorata Temporis", compute="_compute_prorrata", readonly=False, store=True, help="Indicates that the first depreciation entry for this asset " "has to be done from the depreciation start date instead of " "the first day of the fiscal year.", ) open_asset = fields.Boolean( string="Skip Draft State", help="Check this if you want to automatically confirm the assets " "of this profile when created by invoices.", ) asset_product_item = fields.Boolean( string="Create an asset by product item", help="By default during the validation of an invoice, an asset " "is created by invoice line as long as an accounting entry is " "created by invoice line. " "With this setting, an accounting entry will be created by " "product item. So, there will be an asset by product item.", ) active = fields.Boolean(default=True) allow_reversal = fields.Boolean( "Allow Reversal of journal entries", help="If set, when pressing the Delete/Reverse Move button in a " "posted depreciation line will prompt the option to reverse the " "journal entry, instead of deleting them.", ) @api.model def _default_company_id(self): return self.env.company @api.model def _selection_method(self): return [ ("linear", _("Linear")), ("linear-limit", _("Linear up to Salvage Value")), ("degressive", _("Degressive")), ("degr-linear", _("Degressive-Linear")), ("degr-limit", _("Degressive up to Salvage Value")), ] @api.model def _selection_method_period(self): return [("month", _("Month")), ("quarter", _("Quarter")), ("year", _("Year"))] @api.model def _selection_method_time(self): return [ ("year", _("Number of Years or end date")), ("number", _("Number of Depreciations")), ] @api.constrains("method", "method_time") def _check_method(self): if any(a.method == "degr-linear" and a.method_time != "year" for a in self): raise UserError( _("Degressive-Linear is only supported for Time Method = Year.") ) @api.depends("method_time") def _compute_prorrata(self): for profile in self: if profile.method_time != "year": profile.prorata = True @api.model def create(self, vals): if vals.get("method_time") != "year" and not vals.get("prorata"): vals["prorata"] = True profile = super().create(vals) acc_id = vals.get("account_asset_id") if acc_id: account = self.env["account.account"].browse(acc_id) if not account.asset_profile_id: account.write({"asset_profile_id": profile.id}) return profile def write(self, vals): if vals.get("method_time"): if vals["method_time"] != "year" and not vals.get("prorata"): vals["prorata"] = True res = super().write(vals) # TODO last profile in self is defined as default on the related # account. must be improved. account = self.env["account.account"].browse(vals.get("account_asset_id")) if self and account and not account.asset_profile_id: account.write({"asset_profile_id": self[-1].id}) return res
38.931034
9,032
782
py
PYTHON
15.0
# Copyright 2009-2018 Noviat # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class AccountAssetRecomputeTrigger(models.Model): _name = "account.asset.recompute.trigger" _description = "Asset table recompute triggers" reason = fields.Char(required=True) company_id = fields.Many2one("res.company", string="Company", required=True) date_trigger = fields.Datetime( "Trigger Date", readonly=True, help="Date of the event triggering the need to recompute the Asset Tables.", ) date_completed = fields.Datetime("Completion Date", readonly=True) state = fields.Selection( selection=[("open", "Open"), ("done", "Done")], default="open", readonly=True, )
34
782
2,523
py
PYTHON
15.0
# Copyright 2009-2020 Noviat # Copyright 2019 Tecnativa - Pedro M. Baeza # Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models from odoo.osv import expression class AccountAssetGroup(models.Model): _name = "account.asset.group" _description = "Asset Group" _order = "code, name" _parent_store = True _check_company_auto = True name = fields.Char(size=64, required=True, index=True) code = fields.Char(index=True) parent_path = fields.Char(index=True) company_id = fields.Many2one( comodel_name="res.company", string="Company", required=True, default=lambda self: self._default_company_id(), ) parent_id = fields.Many2one( comodel_name="account.asset.group", string="Parent Asset Group", ondelete="restrict", check_company=True, ) child_ids = fields.One2many( comodel_name="account.asset.group", inverse_name="parent_id", string="Child Asset Groups", check_company=True, ) @api.model def _default_company_id(self): return self.env.company def name_get(self): result = [] params = self.env.context.get("params") list_view = params and params.get("view_type") == "list" short_name_len = 16 for rec in self: if rec.code: full_name = rec.code + " " + rec.name short_name = rec.code else: full_name = rec.name if len(full_name) > short_name_len: short_name = full_name[:16] + "..." else: short_name = full_name if list_view: name = short_name else: name = full_name result.append((rec.id, name)) return result @api.model def _name_search( self, name, args=None, operator="ilike", limit=100, name_get_uid=None ): args = args or [] domain = [] if name: domain = [ "|", ("code", "=ilike", name.split(" ")[0] + "%"), ("name", operator, name), ] if operator in expression.NEGATIVE_TERM_OPERATORS: domain = ["&", "!"] + domain[1:] return self._search( expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid )
31.123457
2,521
50,136
py
PYTHON
15.0
# Copyright 2009-2018 Noviat # Copyright 2019 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import calendar import logging from datetime import date from functools import reduce from sys import exc_info from traceback import format_exception from dateutil.relativedelta import relativedelta from odoo import _, api, fields, models from odoo.exceptions import UserError from odoo.osv import expression _logger = logging.getLogger(__name__) READONLY_STATES = { "open": [("readonly", True)], "close": [("readonly", True)], "removed": [("readonly", True)], } class DummyFy(object): def __init__(self, *args, **argv): for key, arg in argv.items(): setattr(self, key, arg) class AccountAsset(models.Model): _name = "account.asset" _inherit = ["mail.thread", "mail.activity.mixin"] _description = "Asset" _order = "date_start desc, code, name" _check_company_auto = True account_move_line_ids = fields.One2many( comodel_name="account.move.line", inverse_name="asset_id", string="Entries", readonly=True, copy=False, check_company=True, ) move_line_check = fields.Boolean( compute="_compute_move_line_check", string="Has accounting entries" ) name = fields.Char( string="Asset Name", required=True, states=READONLY_STATES, ) code = fields.Char( string="Reference", size=32, states=READONLY_STATES, ) purchase_value = fields.Float( required=True, states=READONLY_STATES, help="This amount represent the initial value of the asset." "\nThe Depreciation Base is calculated as follows:" "\nPurchase Value - Salvage Value.", ) salvage_value = fields.Float( digits="Account", states=READONLY_STATES, help="The estimated value that an asset will realize upon " "its sale at the end of its useful life.\n" "This value is used to determine the depreciation amounts.", ) depreciation_base = fields.Float( compute="_compute_depreciation_base", digits="Account", store=True, help="This amount represent the depreciation base " "of the asset (Purchase Value - Salvage Value).", ) value_residual = fields.Float( compute="_compute_depreciation", digits="Account", string="Residual Value", store=True, ) value_depreciated = fields.Float( compute="_compute_depreciation", digits="Account", string="Depreciated Value", store=True, ) note = fields.Text() profile_id = fields.Many2one( comodel_name="account.asset.profile", string="Asset Profile", change_default=True, required=True, states=READONLY_STATES, check_company=True, ) group_ids = fields.Many2many( comodel_name="account.asset.group", compute="_compute_group_ids", readonly=False, store=True, relation="account_asset_group_rel", column1="asset_id", column2="group_id", string="Asset Groups", ) date_start = fields.Date( string="Asset Start Date", required=True, states=READONLY_STATES, help="You should manually add depreciation lines " "with the depreciations of previous fiscal years " "if the Depreciation Start Date is different from the date " "for which accounting entries need to be generated.", ) date_remove = fields.Date(string="Asset Removal Date", readonly=True) state = fields.Selection( selection=[ ("draft", "Draft"), ("open", "Running"), ("close", "Close"), ("removed", "Removed"), ], string="Status", required=True, default="draft", copy=False, help="When an asset is created, the status is 'Draft'.\n" "If the asset is confirmed, the status goes in 'Running' " "and the depreciation lines can be posted " "to the accounting.\n" "If the last depreciation line is posted, " "the asset goes into the 'Close' status.\n" "When the removal entries are generated, " "the asset goes into the 'Removed' status.", ) active = fields.Boolean(default=True) partner_id = fields.Many2one( comodel_name="res.partner", string="Partner", states=READONLY_STATES, ) method = fields.Selection( selection=lambda self: self.env["account.asset.profile"]._selection_method(), string="Computation Method", compute="_compute_method", readonly=False, store=True, states=READONLY_STATES, help="Choose the method to use to compute the depreciation lines.\n" " * Linear: Calculated on basis of: " "Depreciation Base / Number of Depreciations. " "Depreciation Base = Purchase Value - Salvage Value.\n" " * Linear-Limit: Linear up to Salvage Value. " "Depreciation Base = Purchase Value.\n" " * Degressive: Calculated on basis of: " "Residual Value * Degressive Factor.\n" " * Degressive-Linear (only for Time Method = Year): " "Degressive becomes linear when the annual linear " "depreciation exceeds the annual degressive depreciation.\n" " * Degressive-Limit: Degressive up to Salvage Value. " "The Depreciation Base is equal to the asset value.", ) method_number = fields.Integer( string="Number of Years", compute="_compute_method_number", readonly=False, store=True, states=READONLY_STATES, help="The number of years needed to depreciate your asset", ) method_period = fields.Selection( selection=lambda self: self.env[ "account.asset.profile" ]._selection_method_period(), string="Period Length", compute="_compute_method_period", readonly=False, store=True, states=READONLY_STATES, help="Period length for the depreciation accounting entries", ) method_end = fields.Date( string="Ending Date", compute="_compute_method_end", readonly=False, store=True, states=READONLY_STATES, ) method_progress_factor = fields.Float( string="Degressive Factor", compute="_compute_method_progress_factor", readonly=False, store=True, states=READONLY_STATES, ) method_time = fields.Selection( selection=lambda self: self.env[ "account.asset.profile" ]._selection_method_time(), string="Time Method", compute="_compute_method_time", readonly=False, store=True, states=READONLY_STATES, help="Choose the method to use to compute the dates and " "number of depreciation lines.\n" " * Number of Years: Specify the number of years " "for the depreciation.\n" " * Number of Depreciations: Fix the number of " "depreciation lines and the time between 2 depreciations.\n", ) days_calc = fields.Boolean( string="Calculate by days", compute="_compute_days_calc", readonly=False, store=True, help="Use number of days to calculate depreciation amount", ) use_leap_years = fields.Boolean( compute="_compute_use_leap_years", readonly=False, store=True, help="If not set, the system will distribute evenly the amount to " "amortize across the years, based on the number of years. " "So the amount per year will be the " "depreciation base / number of years.\n " "If set, the system will consider if the current year " "is a leap year. The amount to depreciate per year will be " "calculated as depreciation base / (depreciation end date - " "start date + 1) * days in the current year.", ) prorata = fields.Boolean( string="Prorata Temporis", compute="_compute_prorrata", readonly=False, store=True, states=READONLY_STATES, help="Indicates that the first depreciation entry for this asset " "has to be done from the depreciation start date instead of " "the first day of the fiscal year.", ) depreciation_line_ids = fields.One2many( comodel_name="account.asset.line", inverse_name="asset_id", string="Depreciation Lines", copy=False, states=READONLY_STATES, check_company=True, ) company_id = fields.Many2one( comodel_name="res.company", string="Company", required=True, readonly=True, default=lambda self: self._default_company_id(), ) company_currency_id = fields.Many2one( comodel_name="res.currency", related="company_id.currency_id", string="Company Currency", store=True, readonly=True, ) account_analytic_id = fields.Many2one( comodel_name="account.analytic.account", string="Analytic account", compute="_compute_account_analytic_id", readonly=False, store=True, ) analytic_tag_ids = fields.Many2many( comodel_name="account.analytic.tag", string="Analytic tags", compute="_compute_analytic_tag_ids", readonly=False, store=True, ) carry_forward_missed_depreciations = fields.Boolean( string="Accumulate missed depreciations", help="""If create an asset in a fiscal period that is now closed the accumulated amount of depreciations that cannot be posted will be carried forward to the first depreciation line of the current open period.""", ) @api.model def _default_company_id(self): return self.env.company @api.depends("depreciation_line_ids.move_id") def _compute_move_line_check(self): for asset in self: asset.move_line_check = bool( asset.depreciation_line_ids.filtered("move_id") ) @api.depends("purchase_value", "salvage_value", "method") def _compute_depreciation_base(self): for asset in self: if asset.method in ["linear-limit", "degr-limit"]: asset.depreciation_base = asset.purchase_value else: asset.depreciation_base = asset.purchase_value - asset.salvage_value @api.depends( "depreciation_base", "depreciation_line_ids.type", "depreciation_line_ids.amount", "depreciation_line_ids.previous_id", "depreciation_line_ids.init_entry", "depreciation_line_ids.move_check", ) def _compute_depreciation(self): for asset in self: lines = asset.depreciation_line_ids.filtered( lambda l: l.type in ("depreciate", "remove") and (l.init_entry or l.move_check) ) value_depreciated = sum(line.amount for line in lines) residual = asset.depreciation_base - value_depreciated depreciated = value_depreciated asset.update({"value_residual": residual, "value_depreciated": depreciated}) @api.depends("profile_id") def _compute_group_ids(self): for asset in self: if asset.profile_id: asset.group_ids = asset.profile_id.group_ids @api.depends("profile_id") def _compute_method(self): for asset in self: asset.method = asset.profile_id.method @api.depends("profile_id", "method_end") def _compute_method_number(self): for asset in self: if asset.method_end: asset.method_number = 0 else: asset.method_number = asset.profile_id.method_number @api.depends("profile_id") def _compute_method_period(self): for asset in self: asset.method_period = asset.profile_id.method_period @api.depends("method_number") def _compute_method_end(self): for asset in self: if asset.method_number: asset.method_end = False @api.depends("profile_id") def _compute_method_progress_factor(self): for asset in self: asset.method_progress_factor = asset.profile_id.method_progress_factor @api.depends("profile_id") def _compute_method_time(self): for asset in self: asset.method_time = asset.profile_id.method_time @api.depends("profile_id") def _compute_days_calc(self): for asset in self: asset.days_calc = asset.profile_id.days_calc @api.depends("profile_id") def _compute_use_leap_years(self): for asset in self: asset.use_leap_years = asset.profile_id.use_leap_years @api.depends("profile_id", "method_time") def _compute_prorrata(self): for asset in self: if asset.method_time != "year": asset.prorata = True else: asset.prorata = asset.profile_id.prorata @api.depends("profile_id") def _compute_account_analytic_id(self): for asset in self: asset.account_analytic_id = asset.profile_id.account_analytic_id @api.depends("profile_id") def _compute_analytic_tag_ids(self): for asset in self: asset.analytic_tag_ids = asset.profile_id.analytic_tag_ids @api.constrains("method", "method_time") def _check_method(self): if self.filtered( lambda a: a.method == "degr-linear" and a.method_time != "year" ): raise UserError( _("Degressive-Linear is only supported for Time Method = Year.") ) @api.constrains("date_start", "method_end", "method_number", "method_time") def _check_dates(self): if self.filtered( lambda a: a.method_time == "year" and not a.method_number and a.method_end and a.method_end <= a.date_start ): raise UserError(_("The Start Date must precede the Ending Date.")) @api.constrains("profile_id") def _check_profile_change(self): if self.depreciation_line_ids.filtered("move_id"): raise UserError( _( "You cannot change the profile of an asset " "with accounting entries." ) ) @api.onchange("purchase_value", "salvage_value", "date_start", "method") def _onchange_purchase_salvage_value(self): if self.method in ["linear-limit", "degr-limit"]: self.depreciation_base = self.purchase_value or 0.0 else: purchase_value = self.purchase_value or 0.0 salvage_value = self.salvage_value or 0.0 self.depreciation_base = purchase_value - salvage_value dl_create_line = self.depreciation_line_ids.filtered( lambda r: r.type == "create" ) if dl_create_line: dl_create_line.update( {"amount": self.depreciation_base, "line_date": self.date_start} ) @api.model def create(self, vals): asset = super().create(vals) if self.env.context.get("create_asset_from_move_line"): # Trigger compute of depreciation_base asset.salvage_value = 0.0 asset._create_first_asset_line() return asset def write(self, vals): res = super().write(vals) for asset in self: if self.env.context.get("asset_validate_from_write"): continue asset._create_first_asset_line() if asset.profile_id.open_asset and self.env.context.get( "create_asset_from_move_line" ): asset.compute_depreciation_board() # extra context to avoid recursion asset.with_context(asset_validate_from_write=True).validate() return res def _create_first_asset_line(self): self.ensure_one() if self.depreciation_base and not self.depreciation_line_ids: asset_line_obj = self.env["account.asset.line"] line_name = self._get_depreciation_entry_name(0) asset_line_vals = { "amount": self.depreciation_base, "asset_id": self.id, "name": line_name, "line_date": self.date_start, "init_entry": True, "type": "create", } asset_line = asset_line_obj.create(asset_line_vals) if self.env.context.get("create_asset_from_move_line"): asset_line.move_id = self.env.context["move_id"] def unlink(self): for asset in self: if asset.state != "draft": raise UserError(_("You can only delete assets in draft state.")) if asset.depreciation_line_ids.filtered( lambda r: r.type == "depreciate" and r.move_check ): raise UserError( _( "You cannot delete an asset that contains " "posted depreciation lines." ) ) # update accounting entries linked to lines of type 'create' amls = self.with_context(allow_asset_removal=True).mapped( "account_move_line_ids" ) amls.write({"asset_id": False}) return super().unlink() @api.model def name_search(self, name, args=None, operator="ilike", limit=100): args = args or [] domain = [] if name: domain = ["|", ("code", "=ilike", name + "%"), ("name", operator, name)] if operator in expression.NEGATIVE_TERM_OPERATORS: domain = ["&", "!"] + domain[1:] assets = self.search(domain + args, limit=limit) return assets.name_get() @api.depends("name", "code") def name_get(self): result = [] for asset in self: name = asset.name if asset.code: name = " - ".join([asset.code, name]) result.append((asset.id, name)) return result def validate(self): for asset in self: if asset.company_currency_id.is_zero(asset.value_residual): asset.state = "close" else: asset.state = "open" if not asset.depreciation_line_ids.filtered( lambda l: l.type != "create" ): asset.compute_depreciation_board() return True def remove(self): self.ensure_one() ctx = dict(self.env.context, active_ids=self.ids, active_id=self.id) early_removal = False if self.method in ["linear-limit", "degr-limit"]: if self.value_residual != self.salvage_value: early_removal = True elif self.value_residual: early_removal = True if early_removal: ctx.update({"early_removal": True}) return { "name": _("Generate Asset Removal entries"), "view_mode": "form", "res_model": "account.asset.remove", "target": "new", "type": "ir.actions.act_window", "context": ctx, } def set_to_draft(self): return self.write({"state": "draft"}) def open_entries(self): self.ensure_one() # needed for avoiding errors after grouping in assets context = dict(self.env.context) context.pop("group_by", None) return { "name": _("Journal Entries"), "view_mode": "tree,form", "res_model": "account.move", "view_id": False, "type": "ir.actions.act_window", "context": context, "domain": [("id", "in", self.account_move_line_ids.mapped("move_id").ids)], } def _group_lines(self, table): """group lines prior to depreciation start period.""" def group_lines(x, y): y.update({"amount": x["amount"] + y["amount"]}) return y depreciation_start_date = self.date_start lines = table[0]["lines"] lines1 = [] lines2 = [] flag = lines[0]["date"] < depreciation_start_date for line in lines: if flag: lines1.append(line) if line["date"] >= depreciation_start_date: flag = False else: lines2.append(line) if lines1: lines1 = [reduce(group_lines, lines1)] lines1[0]["depreciated_value"] = 0.0 table[0]["lines"] = lines1 + lines2 def _compute_depreciation_line( self, depreciated_value_posted, table_i_start, line_i_start, table, last_line, posted_lines, ): digits = self.env["decimal.precision"].precision_get("Account") company = self.company_id fiscalyear_lock_date = company.fiscalyear_lock_date or fields.Date.to_date( "1901-01-01" ) seq = len(posted_lines) depr_line = last_line last_date = table[-1]["lines"][-1]["date"] depreciated_value = depreciated_value_posted amount_to_allocate = 0.0 for entry in table[table_i_start:]: for line in entry["lines"][line_i_start:]: seq += 1 name = self._get_depreciation_entry_name(seq) amount = line["amount"] if self.carry_forward_missed_depreciations: if line["init"]: amount_to_allocate += amount amount = 0 else: amount += amount_to_allocate amount_to_allocate = 0.0 if line["date"] == last_date: # ensure that the last entry of the table always # depreciates the remaining value amount = self.depreciation_base - depreciated_value if self.method in ["linear-limit", "degr-limit"]: amount -= self.salvage_value if amount or self.carry_forward_missed_depreciations: vals = { "previous_id": depr_line.id, "amount": round(amount, digits), "asset_id": self.id, "name": name, "line_date": line["date"], "line_days": line["days"], "init_entry": fiscalyear_lock_date >= line["date"], } depreciated_value += round(amount, digits) depr_line = self.env["account.asset.line"].create(vals) else: seq -= 1 line_i_start = 0 def compute_depreciation_board(self): line_obj = self.env["account.asset.line"] digits = self.env["decimal.precision"].precision_get("Account") for asset in self: if asset.value_residual == 0.0: continue domain = [ ("asset_id", "=", asset.id), ("type", "=", "depreciate"), "|", ("move_check", "=", True), ("init_entry", "=", True), ] posted_lines = line_obj.search(domain, order="line_date desc") if posted_lines: last_line = posted_lines[0] else: last_line = line_obj domain = [ ("asset_id", "=", asset.id), ("type", "=", "depreciate"), ("move_id", "=", False), ("init_entry", "=", False), ] old_lines = line_obj.search(domain) if old_lines: old_lines.unlink() table = asset._compute_depreciation_table() if not table: continue asset._group_lines(table) # check table with posted entries and # recompute in case of deviation depreciated_value_posted = depreciated_value = 0.0 if posted_lines: total_table_lines = sum(len(entry["lines"]) for entry in table) move_check_lines = asset.depreciation_line_ids.filtered("move_check") last_depreciation_date = last_line.line_date last_date_in_table = table[-1]["lines"][-1]["date"] # If the number of lines in the table is the same as the depreciation # lines, we will not show an error even if the dates are the same. if (last_date_in_table < last_depreciation_date) or ( last_date_in_table == last_depreciation_date and total_table_lines != len(move_check_lines) ): raise UserError( _( "The duration of the asset conflicts with the " "posted depreciation table entry dates." ) ) for _table_i, entry in enumerate(table): residual_amount_table = entry["lines"][-1]["remaining_value"] if ( entry["date_start"] <= last_depreciation_date <= entry["date_stop"] ): break if entry["date_stop"] == last_depreciation_date: _table_i += 1 _line_i = 0 else: entry = table[_table_i] date_min = entry["date_start"] for _line_i, line in enumerate(entry["lines"]): residual_amount_table = line["remaining_value"] if date_min <= last_depreciation_date <= line["date"]: break date_min = line["date"] if line["date"] == last_depreciation_date: _line_i += 1 table_i_start = _table_i line_i_start = _line_i # check if residual value corresponds with table # and adjust table when needed depreciated_value_posted = depreciated_value = sum( posted_line.amount for posted_line in posted_lines ) residual_amount = asset.depreciation_base - depreciated_value amount_diff = round(residual_amount_table - residual_amount, digits) if amount_diff: # We will auto-create a new line because the number of lines in # the tables are the same as the posted depreciations and there # is still a residual value. Only in this case we will need to # add a new line to the table with the amount of the difference. if len(move_check_lines) == total_table_lines: table[table_i_start]["lines"].append( table[table_i_start]["lines"][line_i_start - 1] ) line = table[table_i_start]["lines"][line_i_start] line["days"] = 0 line["amount"] = amount_diff # compensate in first depreciation entry # after last posting line = table[table_i_start]["lines"][line_i_start] line["amount"] -= amount_diff else: # no posted lines table_i_start = 0 line_i_start = 0 asset._compute_depreciation_line( depreciated_value_posted, table_i_start, line_i_start, table, last_line, posted_lines, ) return True def _get_fy_duration(self, fy, option="days"): """Returns fiscal year duration. @param option: - days: duration in days - months: duration in months, a started month is counted as a full month - years: duration in calendar years, considering also leap years """ fy_date_start = fy.date_from fy_date_stop = fy.date_to days = (fy_date_stop - fy_date_start).days + 1 months = ( (fy_date_stop.year - fy_date_start.year) * 12 + (fy_date_stop.month - fy_date_start.month) + 1 ) if option == "days": return days elif option == "months": return months elif option == "years": year = fy_date_start.year cnt = fy_date_stop.year - fy_date_start.year + 1 for i in range(cnt): cy_days = calendar.isleap(year) and 366 or 365 if i == 0: # first year if fy_date_stop.year == year: duration = (fy_date_stop - fy_date_start).days + 1 else: duration = (date(year, 12, 31) - fy_date_start).days + 1 factor = float(duration) / cy_days elif i == cnt - 1: # last year duration = (fy_date_stop - date(year, 1, 1)).days + 1 factor += float(duration) / cy_days else: factor += 1.0 year += 1 return factor def _get_fy_duration_factor(self, entry, firstyear): """ localization: override this method to change the logic used to calculate the impact of extended/shortened fiscal years """ duration_factor = 1.0 fy = entry["fy"] if self.prorata: if firstyear: depreciation_date_start = self.date_start fy_date_stop = entry["date_stop"] first_fy_asset_days = (fy_date_stop - depreciation_date_start).days + 1 first_fy_duration = self._get_fy_duration(fy, option="days") first_fy_year_factor = self._get_fy_duration(fy, option="years") duration_factor = ( float(first_fy_asset_days) / first_fy_duration * first_fy_year_factor ) else: duration_factor = self._get_fy_duration(fy, option="years") else: fy_months = self._get_fy_duration(fy, option="months") duration_factor = float(fy_months) / 12 return duration_factor def _get_depreciation_start_date(self, fy): """ In case of 'Linear': the first month is counted as a full month if the fiscal year starts in the middle of a month. """ if self.prorata: depreciation_start_date = self.date_start else: depreciation_start_date = fy.date_from return depreciation_start_date def _get_depreciation_stop_date(self, depreciation_start_date): if self.method_time == "year" and not self.method_end: depreciation_stop_date = depreciation_start_date + relativedelta( years=self.method_number, days=-1 ) elif self.method_time == "number": if self.method_period == "month": depreciation_stop_date = depreciation_start_date + relativedelta( months=self.method_number, days=-1 ) elif self.method_period == "quarter": m = [x for x in [3, 6, 9, 12] if x >= depreciation_start_date.month][0] first_line_date = depreciation_start_date + relativedelta( month=m, day=31 ) months = self.method_number * 3 depreciation_stop_date = first_line_date + relativedelta( months=months - 1, days=-1 ) elif self.method_period == "year": depreciation_stop_date = depreciation_start_date + relativedelta( years=self.method_number, days=-1 ) elif self.method_time == "year" and self.method_end: depreciation_stop_date = self.method_end return depreciation_stop_date def _get_first_period_amount( self, table, entry, depreciation_start_date, line_dates ): """ Return prorata amount for Time Method 'Year' in case of 'Prorata Temporis' """ amount = entry.get("period_amount") if self.prorata and self.method_time == "year": dates = [x for x in line_dates if x <= entry["date_stop"]] full_periods = len(dates) - 1 amount = entry["fy_amount"] - amount * full_periods return amount def _get_amount_linear( self, depreciation_start_date, depreciation_stop_date, entry ): """ Override this method if you want to compute differently the yearly amount. """ if not self.use_leap_years and self.method_number: return self.depreciation_base / self.method_number year = entry["date_stop"].year cy_days = calendar.isleap(year) and 366 or 365 days = (depreciation_stop_date - depreciation_start_date).days + 1 return (self.depreciation_base / days) * cy_days def _compute_year_amount( self, residual_amount, depreciation_start_date, depreciation_stop_date, entry ): """ Localization: override this method to change the degressive-linear calculation logic according to local legislation. """ if self.method_time != "year": raise UserError( _( "The '_compute_year_amount' method is only intended for " "Time Method 'Number of Years'." ) ) year_amount_linear = self._get_amount_linear( depreciation_start_date, depreciation_stop_date, entry ) if self.method == "linear": return year_amount_linear if self.method == "linear-limit": if (residual_amount - year_amount_linear) < self.salvage_value: return residual_amount - self.salvage_value else: return year_amount_linear year_amount_degressive = residual_amount * self.method_progress_factor if self.method == "degressive": return year_amount_degressive if self.method == "degr-linear": if year_amount_linear > year_amount_degressive: return min(year_amount_linear, residual_amount) else: return min(year_amount_degressive, residual_amount) if self.method == "degr-limit": if (residual_amount - year_amount_degressive) < self.salvage_value: return residual_amount - self.salvage_value else: return year_amount_degressive else: raise UserError(_("Illegal value %s in asset.method.") % self.method) def _compute_line_dates(self, table, start_date, stop_date): """ The posting dates of the accounting entries depend on the chosen 'Period Length' as follows: - month: last day of the month - quarter: last of the quarter - year: last day of the fiscal year Override this method if another posting date logic is required. """ line_dates = [] if self.method_period == "month": line_date = start_date + relativedelta(day=31) if self.method_period == "quarter": m = [x for x in [3, 6, 9, 12] if x >= start_date.month][0] line_date = start_date + relativedelta(month=m, day=31) elif self.method_period == "year": line_date = table[0]["date_stop"] i = 1 while line_date < stop_date: line_dates.append(line_date) if self.method_period == "month": line_date = line_date + relativedelta(months=1, day=31) elif self.method_period == "quarter": line_date = line_date + relativedelta(months=3, day=31) elif self.method_period == "year": line_date = table[i]["date_stop"] i += 1 # last entry if not (self.method_time == "number" and len(line_dates) == self.method_number): if self.days_calc: line_dates.append(stop_date) else: line_dates.append(line_date) return line_dates def _compute_depreciation_amount_per_fiscal_year( self, table, line_dates, depreciation_start_date, depreciation_stop_date ): digits = self.env["decimal.precision"].precision_get("Account") fy_residual_amount = self.depreciation_base i_max = len(table) - 1 asset_sign = self.depreciation_base >= 0 and 1 or -1 day_amount = 0.0 if self.days_calc: days = (depreciation_stop_date - depreciation_start_date).days + 1 day_amount = self.depreciation_base / days for i, entry in enumerate(table): if self.method_time == "year": year_amount = self._compute_year_amount( fy_residual_amount, depreciation_start_date, depreciation_stop_date, entry, ) if self.method_period == "year": period_amount = year_amount elif self.method_period == "quarter": period_amount = year_amount / 4 elif self.method_period == "month": period_amount = year_amount / 12 if i == i_max: if self.method in ["linear-limit", "degr-limit"]: fy_amount = fy_residual_amount - self.salvage_value else: fy_amount = fy_residual_amount else: firstyear = i == 0 and True or False fy_factor = self._get_fy_duration_factor(entry, firstyear) fy_amount = year_amount * fy_factor if asset_sign * (fy_amount - fy_residual_amount) > 0: fy_amount = fy_residual_amount period_amount = round(period_amount, digits) fy_amount = round(fy_amount, digits) else: fy_amount = False if self.method_time == "number": number = self.method_number else: number = len(line_dates) period_amount = round(self.depreciation_base / number, digits) entry.update( { "period_amount": period_amount, "fy_amount": fy_amount, "day_amount": day_amount, } ) if self.method_time == "year": fy_residual_amount -= fy_amount if round(fy_residual_amount, digits) == 0: break i_max = i table = table[: i_max + 1] return table def _compute_depreciation_table_lines( self, table, depreciation_start_date, depreciation_stop_date, line_dates ): digits = self.env["decimal.precision"].precision_get("Account") asset_sign = 1 if self.depreciation_base >= 0 else -1 i_max = len(table) - 1 remaining_value = self.depreciation_base depreciated_value = 0.0 company = self.company_id fiscalyear_lock_date = company.fiscalyear_lock_date or fields.Date.to_date( "1901-01-01" ) for i, entry in enumerate(table): lines = [] fy_amount_check = 0.0 fy_amount = entry["fy_amount"] li_max = len(line_dates) - 1 prev_date = max(entry["date_start"], depreciation_start_date) for li, line_date in enumerate(line_dates): line_days = (line_date - prev_date).days + 1 if round(remaining_value, digits) == 0.0: break if line_date > min(entry["date_stop"], depreciation_stop_date) and not ( i == i_max and li == li_max ): prev_date = line_date break else: prev_date = line_date + relativedelta(days=1) if ( self.method == "degr-linear" and asset_sign * (fy_amount - fy_amount_check) < 0 ): break if i == 0 and li == 0: if entry.get("day_amount") > 0.0: amount = line_days * entry.get("day_amount") else: amount = self._get_first_period_amount( table, entry, depreciation_start_date, line_dates ) amount = round(amount, digits) else: if entry.get("day_amount") > 0.0: amount = line_days * entry.get("day_amount") else: amount = entry.get("period_amount") # last year, last entry # Handle rounding deviations. if i == i_max and li == li_max: amount = remaining_value remaining_value = 0.0 else: remaining_value -= amount fy_amount_check += amount line = { "date": line_date, "days": line_days, "amount": amount, "depreciated_value": depreciated_value, "remaining_value": remaining_value, "init": fiscalyear_lock_date >= line_date, } lines.append(line) depreciated_value += amount # Handle rounding and extended/shortened FY deviations. # # Remark: # In account_asset_management version < 8.0.2.8.0 # the FY deviation for the first FY # was compensated in the first FY depreciation line. # The code has now been simplified with compensation # always in last FT depreciation line. if self.method_time == "year" and not entry.get("day_amount"): if round(fy_amount_check - fy_amount, digits) != 0: diff = fy_amount_check - fy_amount amount = amount - diff remaining_value += diff lines[-1].update( {"amount": amount, "remaining_value": remaining_value} ) depreciated_value -= diff if not lines: table.pop(i) else: entry["lines"] = lines line_dates = line_dates[li:] for entry in table: if not entry["fy_amount"]: entry["fy_amount"] = sum(line["amount"] for line in entry["lines"]) def _get_fy_info(self, date): """Return an homogeneus data structure for fiscal years.""" fy_info = self.company_id.compute_fiscalyear_dates(date) if "record" not in fy_info: fy_info["record"] = DummyFy( date_from=fy_info["date_from"], date_to=fy_info["date_to"] ) return fy_info def _compute_depreciation_table(self): table = [] if ( self.method_time in ["year", "number"] and not self.method_number and not self.method_end ): return table asset_date_start = self.date_start depreciation_start_date = self._get_depreciation_start_date( self._get_fy_info(asset_date_start)["record"] ) depreciation_stop_date = self._get_depreciation_stop_date( depreciation_start_date ) fy_date_start = asset_date_start while fy_date_start <= depreciation_stop_date: fy_info = self._get_fy_info(fy_date_start) table.append( { "fy": fy_info["record"], "date_start": fy_info["date_from"], "date_stop": fy_info["date_to"], } ) fy_date_start = fy_info["date_to"] + relativedelta(days=1) # Step 1: # Calculate depreciation amount per fiscal year. # This is calculation is skipped for method_time != 'year'. line_dates = self._compute_line_dates( table, depreciation_start_date, depreciation_stop_date ) table = self._compute_depreciation_amount_per_fiscal_year( table, line_dates, depreciation_start_date, depreciation_stop_date ) # Step 2: # Spread depreciation amount per fiscal year # over the depreciation periods. self._compute_depreciation_table_lines( table, depreciation_start_date, depreciation_stop_date, line_dates ) return table def _get_depreciation_entry_name(self, seq): """use this method to customise the name of the accounting entry""" return (self.code or str(self.id)) + "/" + str(seq) def _compute_entries(self, date_end, check_triggers=False): # TODO : add ir_cron job calling this method to # generate periodical accounting entries result = [] error_log = "" if check_triggers: recompute_obj = self.env["account.asset.recompute.trigger"] recomputes = recompute_obj.sudo().search([("state", "=", "open")]) if recomputes: trigger_companies = recomputes.mapped("company_id") for asset in self: if asset.company_id.id in trigger_companies.ids: asset.compute_depreciation_board() depreciations = self.env["account.asset.line"].search( [ ("asset_id", "in", self.ids), ("type", "=", "depreciate"), ("init_entry", "=", False), ("line_date", "<=", date_end), ("move_check", "=", False), ], order="line_date", ) for depreciation in depreciations: try: with self.env.cr.savepoint(): result += depreciation.create_move() except Exception: e = exc_info()[0] tb = "".join(format_exception(*exc_info())) asset_ref = depreciation.asset_id.name if depreciation.asset_id.code: asset_ref = "[{}] {}".format(depreciation.asset_id.code, asset_ref) error_log += _( "\nError while processing asset '{ref}': {exception}" ).format(ref=asset_ref, exception=str(e)) error_msg = _("Error while processing asset '{ref}': \n\n{tb}").format( ref=asset_ref, tb=tb ) _logger.error("%s, %s", self._name, error_msg) if check_triggers and recomputes: companies = recomputes.mapped("company_id") triggers = recomputes.filtered(lambda r: r.company_id.id in companies.ids) if triggers: recompute_vals = { "date_completed": fields.Datetime.now(), "state": "done", } triggers.sudo().write(recompute_vals) return (result, error_log) @api.model def _xls_acquisition_fields(self): """ Update list in custom module to add/drop columns or change order """ return [ "account", "name", "code", "date_start", "purchase_value", "depreciation_base", "salvage_value", ] @api.model def _xls_active_fields(self): """ Update list in custom module to add/drop columns or change order """ return [ "account", "name", "code", "date_start", "purchase_value", "depreciation_base", "salvage_value", "period_start_value", "period_depr", "period_end_value", "period_end_depr", "method", "method_number", "prorata", "state", ] @api.model def _xls_removal_fields(self): """ Update list in custom module to add/drop columns or change order """ return [ "account", "name", "code", "date_remove", "purchase_value", "depreciation_base", "salvage_value", ] @api.model def _xls_asset_template(self): """ Template updates """ return {} @api.model def _xls_acquisition_template(self): """ Template updates """ return {} @api.model def _xls_active_template(self): """ Template updates """ return {} @api.model def _xls_removal_template(self): """ Template updates """ return {}
37.331348
50,136
28,593
py
PYTHON
15.0
# Copyright 2009-2019 Noviat # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from odoo import _, models from odoo.exceptions import UserError from odoo.tools.translate import translate from odoo.addons.report_xlsx_helper.report.report_xlsx_format import ( FORMATS, XLS_HEADERS, ) _logger = logging.getLogger(__name__) IR_TRANSLATION_NAME = "account.asset.report" class AssetReportXlsx(models.AbstractModel): _name = "report.account_asset_management.asset_report_xls" _description = "Dynamic XLS asset report generator" _inherit = "report.report_xlsx.abstract" def _(self, src): lang = self.env.context.get("lang", "en_US") val = translate(self.env.cr, IR_TRANSLATION_NAME, "report", lang, src) or src return val def _get_ws_params(self, wb, data, wiz): self._get_assets(wiz, data) s1 = self._get_acquisition_ws_params(wb, data, wiz) s2 = self._get_active_ws_params(wb, data, wiz) s3 = self._get_removal_ws_params(wb, data, wiz) return [s1, s2, s3] def _get_asset_template(self): asset_template = { "account": { "header": {"type": "string", "value": self._("Account")}, "asset": { "type": "string", "value": self._render( "asset.profile_id.account_asset_id.code or ''" ), }, "totals": {"type": "string", "value": self._("Totals")}, "width": 20, }, "name": { "header": {"type": "string", "value": self._("Name")}, "asset_group": { "type": "string", "value": self._render("group.name or ''"), }, "asset": {"type": "string", "value": self._render("asset.name")}, "width": 40, }, "code": { "header": {"type": "string", "value": self._("Reference")}, "asset_group": { "type": "string", "value": self._render("group.code or ''"), }, "asset": {"type": "string", "value": self._render("asset.code or ''")}, "width": 20, }, "date_start": { "header": {"type": "string", "value": self._("Asset Start Date")}, "asset": { "value": self._render("asset.date_start or ''"), "format": FORMATS["format_tcell_date_left"], }, "width": 20, }, "date_remove": { "header": {"type": "string", "value": self._("Asset Removal Date")}, "asset": { "value": self._render("asset.date_remove or ''"), "format": FORMATS["format_tcell_date_left"], }, "width": 20, }, "depreciation_base": { "header": { "type": "string", "value": self._("Depreciation Base"), "format": FORMATS["format_theader_yellow_right"], }, "asset_group": { "type": "number", "value": self._render('group_entry["_depreciation_base"]'), "format": FORMATS["format_theader_blue_amount_right"], }, "asset": { "type": "number", "value": self._render("asset.depreciation_base"), "format": FORMATS["format_tcell_amount_right"], }, "totals": { "type": "formula", "value": self._render("asset_total_formula"), "format": FORMATS["format_theader_yellow_amount_right"], }, "width": 18, }, "salvage_value": { "header": { "type": "string", "value": self._("Salvage Value"), "format": FORMATS["format_theader_yellow_right"], }, "asset_group": { "type": "number", "value": self._render('group_entry["_salvage_value"]'), "format": FORMATS["format_theader_blue_amount_right"], }, "asset": { "type": "number", "value": self._render("asset.salvage_value"), "format": FORMATS["format_tcell_amount_right"], }, "totals": { "type": "formula", "value": self._render("salvage_total_formula"), "format": FORMATS["format_theader_yellow_amount_right"], }, "width": 18, }, "purchase_value": { "header": { "type": "string", "value": self._("Purchase Value"), "format": FORMATS["format_theader_yellow_right"], }, "asset_group": { "type": "number", "value": self._render('group_entry["_purchase_value"]'), "format": FORMATS["format_theader_blue_amount_right"], }, "asset": { "type": "number", "value": self._render("asset.purchase_value"), "format": FORMATS["format_tcell_amount_right"], }, "totals": { "type": "formula", "value": self._render("purchase_total_formula"), "format": FORMATS["format_theader_yellow_amount_right"], }, "width": 18, }, "period_start_value": { "header": { "type": "string", "value": self._("Period Start Value"), "format": FORMATS["format_theader_yellow_right"], }, "asset_group": { "type": "number", "value": self._render('group_entry["_period_start_value"]'), "format": FORMATS["format_theader_blue_amount_right"], }, "asset": { "type": "number", "value": self._render('asset_entry["_period_start_value"]'), "format": FORMATS["format_tcell_amount_right"], }, "totals": { "type": "formula", "value": self._render("period_start_total_formula"), "format": FORMATS["format_theader_yellow_amount_right"], }, "width": 18, }, "period_depr": { "header": { "type": "string", "value": self._("Period Depreciation"), "format": FORMATS["format_theader_yellow_right"], }, "asset_group": { "type": "formula", "value": self._render("period_diff_formula"), "format": FORMATS["format_theader_blue_amount_right"], }, "asset": { "type": "formula", "value": self._render("period_diff_formula"), "format": FORMATS["format_tcell_amount_right"], }, "totals": { "type": "formula", "value": self._render("period_diff_formula"), "format": FORMATS["format_theader_yellow_amount_right"], }, "width": 18, }, "period_end_value": { "header": { "type": "string", "value": self._("Period End Value"), "format": FORMATS["format_theader_yellow_right"], }, "asset_group": { "type": "number", "value": self._render('group_entry["_period_end_value"]'), "format": FORMATS["format_theader_blue_amount_right"], }, "asset": { "type": "number", "value": self._render('asset_entry["_period_end_value"]'), "format": FORMATS["format_tcell_amount_right"], }, "totals": { "type": "formula", "value": self._render("period_end_total_formula"), "format": FORMATS["format_theader_yellow_amount_right"], }, "width": 18, }, "period_end_depr": { "header": { "type": "string", "value": self._("Tot. Depreciation"), "format": FORMATS["format_theader_yellow_right"], }, "asset_group": { "type": "formula", "value": self._render("total_depr_formula"), "format": FORMATS["format_theader_blue_amount_right"], }, "asset": { "type": "formula", "value": self._render("total_depr_formula"), "format": FORMATS["format_tcell_amount_right"], }, "totals": { "type": "formula", "value": self._render("total_depr_formula"), "format": FORMATS["format_theader_yellow_amount_right"], }, "width": 18, }, "method": { "header": { "type": "string", "value": self._("Comput. Method"), "format": FORMATS["format_theader_yellow_center"], }, "asset": { "type": "string", "value": self._render("asset.method or ''"), "format": FORMATS["format_tcell_center"], }, "width": 20, }, "method_number": { "header": { "type": "string", "value": self._("Number of Years"), "format": FORMATS["format_theader_yellow_center"], }, "asset": { "type": "number", "value": self._render("asset.method_number"), "format": FORMATS["format_tcell_integer_center"], }, "width": 20, }, "prorata": { "header": { "type": "string", "value": self._("Prorata Temporis"), "format": FORMATS["format_theader_yellow_center"], }, "asset": { "type": "boolean", "value": self._render("asset.prorata"), "format": FORMATS["format_tcell_center"], }, "width": 20, }, "state": { "header": { "type": "string", "value": self._("Status"), "format": FORMATS["format_theader_yellow_center"], }, "asset": { "type": "string", "value": self._render("asset.state"), "format": FORMATS["format_tcell_center"], }, "width": 8, }, } asset_template.update(self.env["account.asset"]._xls_asset_template()) return asset_template def _get_acquisition_ws_params(self, wb, data, wiz): acquisition_template = self._get_asset_template() acquisition_template.update( self.env["account.asset"]._xls_acquisition_template() ) wl_acq = self.env["account.asset"]._xls_acquisition_fields() title = self._get_title(wiz, "acquisition", frmt="normal") title_short = self._get_title(wiz, "acquisition", frmt="short") sheet_name = title_short[:31].replace("/", "-") return { "ws_name": sheet_name, "generate_ws_method": "_asset_report", "title": title, "wanted_list": wl_acq, "col_specs": acquisition_template, "report_type": "acquisition", } def _get_active_ws_params(self, wb, data, wiz): active_template = self._get_asset_template() active_template.update(self.env["account.asset"]._xls_active_template()) wl_act = self.env["account.asset"]._xls_active_fields() title = self._get_title(wiz, "active", frmt="normal") title_short = self._get_title(wiz, "active", frmt="short") sheet_name = title_short[:31].replace("/", "-") return { "ws_name": sheet_name, "generate_ws_method": "_asset_report", "title": title, "wanted_list": wl_act, "col_specs": active_template, "report_type": "active", } def _get_removal_ws_params(self, wb, data, wiz): removal_template = self._get_asset_template() removal_template.update(self.env["account.asset"]._xls_removal_template()) wl_dsp = self.env["account.asset"]._xls_removal_fields() title = self._get_title(wiz, "removal", frmt="normal") title_short = self._get_title(wiz, "removal", frmt="short") sheet_name = title_short[:31].replace("/", "-") return { "ws_name": sheet_name, "generate_ws_method": "_asset_report", "title": title, "wanted_list": wl_dsp, "col_specs": removal_template, "report_type": "removal", } def _get_title(self, wiz, report, frmt="normal"): prefix = "{} - {}".format(wiz.date_from, wiz.date_to) if report == "acquisition": if frmt == "normal": title = prefix + " : " + _("New Acquisitions") else: title = "ACQ" elif report == "active": if frmt == "normal": title = prefix + " : " + _("Active Assets") else: title = "ACT" else: if frmt == "normal": title = prefix + " : " + _("Removed Assets") else: title = "DSP" return title def _report_title(self, ws, row_pos, ws_params, data, wiz): return self._write_ws_title(ws, row_pos, ws_params) def _empty_report(self, ws, row_pos, ws_params, data, wiz): report = ws_params["report_type"] if report == "acquisition": suffix = _("New Acquisitions") elif report == "active": suffix = _("Active Assets") else: suffix = _("Removed Assets") no_entries = _("No") + " " + suffix ws.write_string(row_pos, 0, no_entries, FORMATS["format_left_bold"]) def _get_assets(self, wiz, data): """Add the selected assets, both grouped and ungrouped, to `data`""" dom = [ ("date_start", "<=", wiz.date_to), "|", ("date_remove", "=", False), ("date_remove", ">=", wiz.date_from), ] parent_group = wiz.asset_group_id if parent_group: def _child_get(parent): groups = [parent] children = parent.child_ids children = children.sorted(lambda r: r.code or r.name) for child in children: if child in groups: raise UserError( _( "Inconsistent reporting structure." "\nPlease correct Asset Group '{group}' (id {id})" ).format(group=child.name, id=child.id) ) groups.extend(_child_get(child)) return groups groups = _child_get(parent_group) dom.append(("group_ids", "in", [x.id for x in groups])) if not wiz.draft: dom.append(("state", "!=", "draft")) assets = self.env["account.asset"].search(dom) grouped_assets = {} self._group_assets(assets, parent_group, grouped_assets) data.update( { "assets": assets, "grouped_assets": grouped_assets, } ) @staticmethod def acquisition_filter(wiz, asset): return asset.date_start >= wiz.date_from @staticmethod def active_filter(wiz, asset): return True @staticmethod def removal_filter(wiz, asset): return ( asset.date_remove and asset.date_remove >= wiz.date_from and asset.date_remove <= wiz.date_to ) def _group_assets(self, assets, group, grouped_assets): if group: group_assets = assets.filtered(lambda r: group in r.group_ids) else: group_assets = assets group_assets = group_assets.sorted( lambda r: (r.date_start or "", r.code or "", r.name) ) grouped_assets[group] = {"assets": group_assets} for child in group.child_ids: self._group_assets(assets, child, grouped_assets[group]) def _create_report_entries( self, ws_params, wiz, entries, group, group_val, error_dict ): report = ws_params["report_type"] def asset_filter(asset): filt = getattr(self, "{}_filter".format(report)) return filt(wiz, asset) def _has_assets(group, group_val): assets = group_val.get("assets") assets = assets.filtered(asset_filter) if assets: return True for child in group.child_ids: if _has_assets(child, group_val[child]): return True return False assets = group_val.get("assets") assets = assets.filtered(asset_filter) # remove empty entries if not _has_assets(group, group_val): return asset_entries = [] group_entry = { "_purchase_value": 0.0, "_depreciation_base": 0.0, "_salvage_value": 0.0, "_period_start_value": 0.0, "_period_end_value": 0.0, "group": group, } for asset in assets: asset_entry = {"asset": asset} group_entry["_purchase_value"] += asset.purchase_value group_entry["_depreciation_base"] += asset.depreciation_base group_entry["_salvage_value"] += asset.salvage_value dls_all = asset.depreciation_line_ids.filtered( lambda r: r.type == "depreciate" ) dls_all = dls_all.sorted(key=lambda r: r.line_date) if not dls_all: error_dict["no_table"] += asset # period_start_value dls = dls_all.filtered(lambda r: r.line_date <= wiz.date_from) if dls: value_depreciated = dls[-1].depreciated_value + dls[-1].amount else: value_depreciated = 0.0 asset_entry["_period_start_value"] = ( asset.depreciation_base - value_depreciated ) group_entry["_period_start_value"] += asset_entry["_period_start_value"] # period_end_value dls = dls_all.filtered(lambda r: r.line_date <= wiz.date_to) if dls: value_depreciated = dls[-1].depreciated_value + dls[-1].amount else: value_depreciated = 0.0 asset_entry["_period_end_value"] = ( asset.depreciation_base - value_depreciated ) group_entry["_period_end_value"] += asset_entry["_period_end_value"] asset_entries.append(asset_entry) todos = [] for g in group.child_ids: if _has_assets(g, group_val[g]): todos.append(g) entries.append(group_entry) entries.extend(asset_entries) for todo in todos: self._create_report_entries( ws_params, wiz, entries, todo, group_val[todo], error_dict ) def _asset_report(self, workbook, ws, ws_params, data, wiz): report = ws_params["report_type"] ws.set_portrait() ws.fit_to_pages(1, 0) ws.set_header(XLS_HEADERS["xls_headers"]["standard"]) ws.set_footer(XLS_HEADERS["xls_footers"]["standard"]) wl = ws_params["wanted_list"] if "account" not in wl: raise UserError( _( "The 'account' field is a mandatory entry of the " "'_xls_%s_fields' list !" ) % report ) self._set_column_width(ws, ws_params) row_pos = 0 row_pos = self._report_title(ws, row_pos, ws_params, data, wiz) def asset_filter(asset): filt = getattr(self, "{}_filter".format(report)) return filt(wiz, asset) assets = data["assets"].filtered(asset_filter) if not assets: return self._empty_report(ws, row_pos, ws_params, data, wiz) row_pos = self._write_line( ws, row_pos, ws_params, col_specs_section="header", default_format=FORMATS["format_theader_yellow_left"], ) ws.freeze_panes(row_pos, 0) row_pos_start = row_pos purchase_value_pos = "purchase_value" in wl and wl.index("purchase_value") depreciation_base_pos = "depreciation_base" in wl and wl.index( "depreciation_base" ) salvage_value_pos = "salvage_value" in wl and wl.index("salvage_value") period_start_value_pos = "period_start_value" in wl and wl.index( "period_start_value" ) period_end_value_pos = "period_end_value" in wl and wl.index("period_end_value") entries = [] root = wiz.asset_group_id root_val = data["grouped_assets"][root] error_dict = { "no_table": self.env["account.asset"], "dups": self.env["account.asset"], } self._create_report_entries(ws_params, wiz, entries, root, root_val, error_dict) # traverse entries in reverse order to calc totals for i, entry in enumerate(reversed(entries)): if "group" in entry: parent = entry["group"].parent_id for parent_entry in reversed(entries[: -i - 1]): if "group" in parent_entry and parent_entry["group"] == parent: parent_entry["_purchase_value"] += entry["_purchase_value"] parent_entry["_depreciation_base"] += entry[ "_depreciation_base" ] parent_entry["_salvage_value"] += entry["_salvage_value"] parent_entry["_period_start_value"] += entry[ "_period_start_value" ] parent_entry["_period_end_value"] += entry["_period_end_value"] continue processed = [] for entry in entries: period_start_value_cell = period_start_value_pos and self._rowcol_to_cell( row_pos, period_start_value_pos ) period_end_value_cell = period_end_value_pos and self._rowcol_to_cell( row_pos, period_end_value_pos ) depreciation_base_cell = depreciation_base_pos and self._rowcol_to_cell( row_pos, depreciation_base_pos ) period_diff_formula = period_end_value_cell and ( period_start_value_cell + "-" + period_end_value_cell ) total_depr_formula = period_end_value_cell and ( depreciation_base_cell + "-" + period_end_value_cell ) if "group" in entry: row_pos = self._write_line( ws, row_pos, ws_params, col_specs_section="asset_group", render_space={ "group": entry["group"], "group_entry": entry, "period_diff_formula": period_diff_formula, "total_depr_formula": total_depr_formula, }, default_format=FORMATS["format_theader_blue_left"], ) else: asset = entry["asset"] if asset in processed: error_dict["dups"] += asset continue else: processed.append(asset) row_pos = self._write_line( ws, row_pos, ws_params, col_specs_section="asset", render_space={ "asset": entry["asset"], "asset_entry": entry, "period_diff_formula": period_diff_formula, "total_depr_formula": total_depr_formula, }, default_format=FORMATS["format_tcell_left"], ) purchase_total_formula = purchase_value_pos and self._rowcol_to_cell( row_pos_start, purchase_value_pos ) asset_total_formula = depreciation_base_pos and self._rowcol_to_cell( row_pos_start, depreciation_base_pos ) salvage_total_formula = salvage_value_pos and self._rowcol_to_cell( row_pos_start, salvage_value_pos ) period_start_total_formula = period_start_value_pos and self._rowcol_to_cell( row_pos_start, period_start_value_pos ) period_end_total_formula = period_end_value_pos and self._rowcol_to_cell( row_pos_start, period_end_value_pos ) period_start_value_cell = period_start_value_pos and self._rowcol_to_cell( row_pos, period_start_value_pos ) period_end_value_cell = period_end_value_pos and self._rowcol_to_cell( row_pos, period_end_value_pos ) depreciation_base_cell = depreciation_base_pos and self._rowcol_to_cell( row_pos, depreciation_base_pos ) period_diff_formula = period_end_value_cell and ( period_start_value_cell + "-" + period_end_value_cell ) total_depr_formula = period_end_value_cell and ( depreciation_base_cell + "-" + period_end_value_cell ) row_pos = self._write_line( ws, row_pos, ws_params, col_specs_section="totals", render_space={ "purchase_total_formula": purchase_total_formula, "asset_total_formula": asset_total_formula, "salvage_total_formula": salvage_total_formula, "period_start_total_formula": period_start_total_formula, "period_end_total_formula": period_end_total_formula, "period_diff_formula": period_diff_formula, "total_depr_formula": total_depr_formula, }, default_format=FORMATS["format_theader_yellow_left"], ) for k in error_dict: if error_dict[k]: if k == "no_table": reason = _("Missing depreciation table") elif k == "dups": reason = _("Duplicate reporting entries") else: reason = _("Undetermined error") row_pos += 1 err_msg = _("Assets to be corrected") + ": " err_msg += "%s" % [x[1] for x in error_dict[k].name_get()] err_msg += " - " + _("Reason") + ": " + reason ws.write_string(row_pos, 0, err_msg, FORMATS["format_left_bold"])
38.639189
28,593
492
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Account Fiscal Month", "summary": """Provide a fiscal month date range type""", "version": "15.0.1.0.0", "license": "AGPL-3", "author": "ACSONE SA/NV, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "depends": ["account", "date_range"], "data": ["data/date_range_type.xml", "views/date_range_type.xml"], }
37.846154
492
2,377
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from psycopg2 import IntegrityError from odoo.exceptions import UserError from odoo.fields import Date from odoo.tests.common import TransactionCase from odoo.tools import mute_logger class TestAccountFiscalMonth(TransactionCase): def setUp(self): super(TestAccountFiscalMonth, self).setUp() self.DateRangeObj = self.env["date.range"] self.DateRangeType = self.env["date.range.type"] self.company = self.env.ref("base.main_company") self.date_range_type = self.DateRangeType.create( {"name": "Other Type", "allow_overlap": False} ) self.date_range_type_month = self.env.ref( "account_fiscal_month.date_range_fiscal_month" ) self.date_range_1 = self.DateRangeObj.create( { "name": "Other", "date_start": "2017-01-01", "date_end": "2017-01-31", "type_id": self.date_range_type.id, "company_id": self.company.id, } ) self.date_range_january_2017 = self.DateRangeObj.create( { "name": "January 2017", "date_start": "2017-01-01", "date_end": "2017-01-31", "type_id": self.date_range_type_month.id, "company_id": self.company.id, } ) self.date_range_january_no_comp_2017 = self.DateRangeObj.create( { "name": "January 2017", "date_start": "2017-01-01", "date_end": "2017-01-31", "type_id": self.date_range_type_month.id, "company_id": False, } ) def test_00_delete_type(self): with self.assertRaises(IntegrityError), mute_logger("odoo.sql_db"): self.date_range_type.unlink() def test_01_delete_type_fiscal_month(self): with self.assertRaises(UserError): self.date_range_type_month.unlink() def test_02_search_date_range(self): january_2017_1st = Date.from_string("2017-01-01") date_ranges = self.company.find_daterange_fm(january_2017_1st) self.assertEqual(len(date_ranges), 1) self.assertEqual(date_ranges[0], self.date_range_january_2017)
34.449275
2,377
612
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, fields, models from odoo.exceptions import UserError class DateRangeType(models.Model): _inherit = "date.range.type" fiscal_month = fields.Boolean(string="Is fiscal month?", readonly=True) def unlink(self): date_range_type_fm = self.env.ref( "account_fiscal_month.date_range_fiscal_month" ) if date_range_type_fm.id in self.ids: raise UserError(_("You can't delete date range type: " "Fiscal month")) return super().unlink()
32.210526
612
721
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class ResCompany(models.Model): _inherit = "res.company" def find_daterange_fm(self, date_str): self.ensure_one() fm_id = self.env.ref("account_fiscal_month.date_range_fiscal_month") return self.env["date.range"].search( [ ("type_id", "=", fm_id.id), ("date_start", "<=", date_str), ("date_end", ">=", date_str), "|", ("company_id", "=", self.id), ("company_id", "=", False), ], limit=1, order="company_id asc", )
28.84
721
556
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Account Chart update OSS OCA", "version": "15.0.1.0.0", "author": "ForgeFlow, Odoo Community Association (OCA)", "maintainers": ["LoisRForgeFlow"], "website": "https://github.com/OCA/account-financial-tools", "category": "Accounting", "license": "AGPL-3", "depends": [ "account_chart_update", "l10n_eu_oss_oca", ], "installable": True, "auto_install": True, }
30.888889
556
462
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class WizardUpdateChartsAccounts(models.TransientModel): _inherit = "wizard.update.charts.accounts" def _domain_taxes_to_deactivate(self, found_taxes_ids): domain = super()._domain_taxes_to_deactivate(found_taxes_ids) domain.append(("oss_country_id", "=", False)) return domain
35.538462
462
963
py
PYTHON
15.0
# Copyright 2021 Akretion France (http://www.akretion.com/) # Copyright 2022 Vauxoo (https://www.vauxoo.com/) # @author: Alexis de Lattre <alexis.delattre@akretion.com> # @author: Moisés López <moylop260@vauxoo.com> # @author: Francisco Luna <fluna@vauxoo.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Account Move Number Sequence", "version": "15.0.1.2.1", "category": "Accounting", "license": "AGPL-3", "summary": "Generate journal entry number from sequence", "author": "Akretion,Vauxoo,Odoo Community Association (OCA)", "maintainers": ["alexis-via", "moylop260", "frahikLV"], "website": "https://github.com/OCA/account-financial-tools", "depends": [ "account", ], "data": [ "views/account_journal.xml", "views/account_move.xml", "security/ir.model.access.csv", ], "post_init_hook": "create_journal_sequences", "installable": True, }
35.592593
961
1,334
py
PYTHON
15.0
# Copyright 2021 Akretion France (http://www.akretion.com/) # Copyright 2022 Vauxoo (https://www.vauxoo.com/) # @author: Alexis de Lattre <alexis.delattre@akretion.com> # @author: Moisés López <moylop260@vauxoo.com> # @author: Francisco Luna <fluna@vauxoo.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import SUPERUSER_ID, api def create_journal_sequences(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) journals = ( env["account.journal"] .with_context(active_test=False) .search([("sequence_id", "=", False)]) ) for journal in journals: journal_vals = { "code": journal.code, "name": journal.name, "company_id": journal.company_id.id, } seq_vals = journal._prepare_sequence(journal_vals) seq_vals.update(journal._prepare_sequence_current_moves()) vals = {"sequence_id": env["ir.sequence"].create(seq_vals).id} if journal.type in ("sale", "purchase") and journal.refund_sequence: rseq_vals = journal._prepare_sequence(journal_vals, refund=True) rseq_vals.update(journal._prepare_sequence_current_moves(refund=True)) vals["refund_sequence_id"] = env["ir.sequence"].create(rseq_vals).id journal.write(vals) return
41.625
1,332
8,758
py
PYTHON
15.0
# Copyright 2021 Akretion France (http://www.akretion.com/) # @author: Alexis de Lattre <alexis.delattre@akretion.com> # @author: Moisés López <moylop260@vauxoo.com> # @author: Francisco Luna <fluna@vauxoo.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from datetime import datetime from freezegun import freeze_time from odoo import fields from odoo.exceptions import UserError from odoo.tests import tagged from odoo.tests.common import TransactionCase @tagged("post_install", "-at_install") class TestAccountMoveNameSequence(TransactionCase): def setUp(self): super().setUp() self.company = self.env.ref("base.main_company") self.misc_journal = self.env["account.journal"].create( { "name": "Test Journal Move name seq", "code": "ADLM", "type": "general", "company_id": self.company.id, } ) self.purchase_journal = self.env["account.journal"].create( { "name": "Test Purchase Journal Move name seq", "code": "ADLP", "type": "purchase", "company_id": self.company.id, "refund_sequence": True, } ) self.accounts = self.env["account.account"].search( [("company_id", "=", self.company.id)], limit=2 ) self.account1 = self.accounts[0] self.account2 = self.accounts[1] self.date = datetime.now() def test_seq_creation(self): self.assertTrue(self.misc_journal.sequence_id) seq = self.misc_journal.sequence_id self.assertEqual(seq.company_id, self.company) self.assertEqual(seq.implementation, "no_gap") self.assertEqual(seq.padding, 4) self.assertTrue(seq.use_date_range) self.assertTrue(self.purchase_journal.sequence_id) self.assertTrue(self.purchase_journal.refund_sequence_id) seq = self.purchase_journal.refund_sequence_id self.assertEqual(seq.company_id, self.company) self.assertEqual(seq.implementation, "no_gap") self.assertEqual(seq.padding, 4) self.assertTrue(seq.use_date_range) def test_misc_move_name(self): move = self.env["account.move"].create( { "date": self.date, "journal_id": self.misc_journal.id, "line_ids": [ (0, 0, {"account_id": self.account1.id, "debit": 10}), (0, 0, {"account_id": self.account2.id, "credit": 10}), ], } ) self.assertEqual(move.name, "/") move.action_post() seq = self.misc_journal.sequence_id move_name = "%s%s" % (seq.prefix, "1".zfill(seq.padding)) move_name = move_name.replace("%(range_year)s", str(self.date.year)) self.assertEqual(move.name, move_name) self.assertTrue(seq.date_range_ids) drange_count = self.env["ir.sequence.date_range"].search_count( [ ("sequence_id", "=", seq.id), ("date_from", "=", fields.Date.add(self.date, month=1, day=1)), ] ) self.assertEqual(drange_count, 1) move.button_draft() move.action_post() self.assertEqual(move.name, move_name) def test_prefix_move_name_use_move_date(self): seq = self.misc_journal.sequence_id seq.prefix = "TEST-%(year)s-%(month)s-" self.env["ir.sequence.date_range"].sudo().create( { "date_from": "2021-07-01", "date_to": "2022-06-30", "sequence_id": seq.id, } ) with freeze_time("2022-01-01"): move = self.env["account.move"].create( { "date": "2021-12-31", "journal_id": self.misc_journal.id, "line_ids": [ (0, 0, {"account_id": self.account1.id, "debit": 10}), (0, 0, {"account_id": self.account2.id, "credit": 10}), ], } ) move.action_post() self.assertEqual(move.name, "TEST-2021-12-0001") with freeze_time("2022-01-01"): move = self.env["account.move"].create( { "date": "2022-06-30", "journal_id": self.misc_journal.id, "line_ids": [ (0, 0, {"account_id": self.account1.id, "debit": 10}), (0, 0, {"account_id": self.account2.id, "credit": 10}), ], } ) move.action_post() self.assertEqual(move.name, "TEST-2022-06-0002") with freeze_time("2022-01-01"): move = self.env["account.move"].create( { "date": "2022-07-01", "journal_id": self.misc_journal.id, "line_ids": [ (0, 0, {"account_id": self.account1.id, "debit": 10}), (0, 0, {"account_id": self.account2.id, "credit": 10}), ], } ) move.action_post() self.assertEqual(move.name, "TEST-2022-07-0001") def test_in_refund(self): in_refund_invoice = self.env["account.move"].create( { "journal_id": self.purchase_journal.id, "invoice_date": self.date, "partner_id": self.env.ref("base.res_partner_3").id, "move_type": "in_refund", "invoice_line_ids": [ ( 0, 0, { "account_id": self.account1.id, "price_unit": 42.0, "quantity": 12, }, ) ], } ) self.assertEqual(in_refund_invoice.name, "/") in_refund_invoice.action_post() seq = self.purchase_journal.refund_sequence_id move_name = "%s%s" % (seq.prefix, "1".zfill(seq.padding)) move_name = move_name.replace("%(range_year)s", str(self.date.year)) self.assertEqual(in_refund_invoice.name, move_name) in_refund_invoice.button_draft() in_refund_invoice.action_post() self.assertEqual(in_refund_invoice.name, move_name) def test_remove_invoice_error(self): invoice = self.env["account.move"].create( { "date": self.date, "journal_id": self.misc_journal.id, "line_ids": [ (0, 0, {"account_id": self.account1.id, "debit": 10}), (0, 0, {"account_id": self.account2.id, "credit": 10}), ], } ) self.assertEqual(invoice.name, "/") invoice.action_post() error_msg = "You cannot delete an item linked to a posted entry." with self.assertRaisesRegex(UserError, error_msg): invoice.unlink() invoice.button_draft() invoice.button_cancel() error_msg = "You cannot delete this entry, as it has already consumed a" with self.assertRaisesRegex(UserError, error_msg): invoice.unlink() def test_remove_invoice_error_secuence_standard(self): implementation = {"implementation": "standard"} self.purchase_journal.sequence_id.write(implementation) self.purchase_journal.refund_sequence_id.write(implementation) in_refund_invoice = self.env["account.move"].create( { "journal_id": self.purchase_journal.id, "invoice_date": self.date, "partner_id": self.env.ref("base.res_partner_3").id, "move_type": "in_refund", "invoice_line_ids": [ ( 0, 0, { "account_id": self.account1.id, "price_unit": 42.0, "quantity": 12, }, ) ], } ) self.assertEqual(in_refund_invoice.name, "/") in_refund_invoice.action_post() error_msg = "You cannot delete an item linked to a posted entry." with self.assertRaisesRegex(UserError, error_msg): in_refund_invoice.unlink() in_refund_invoice.button_draft() in_refund_invoice.button_cancel() self.assertTrue(in_refund_invoice.unlink())
39.264574
8,756
2,987
py
PYTHON
15.0
# Copyright 2021 Akretion France (http://www.akretion.com/) # @author: Alexis de Lattre <alexis.delattre@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class AccountMove(models.Model): _inherit = "account.move" name = fields.Char(compute="_compute_name_by_sequence") # highest_name, sequence_prefix and sequence_number are not needed any more # -> compute=False to improve perf highest_name = fields.Char(compute=False) sequence_prefix = fields.Char(compute=False) sequence_number = fields.Integer(compute=False) _sql_constraints = [ ( "name_state_diagonal", "CHECK(COALESCE(name, '') NOT IN ('/', '') OR state!='posted')", 'A move can not be posted with name "/" or empty value\n' "Check the journal sequence, please", ), ] @api.depends("state", "journal_id", "date") def _compute_name_by_sequence(self): for move in self: name = move.name or "/" # I can't use posted_before in this IF because # posted_before is set to True in _post() at the same # time as state is set to "posted" if ( move.state == "posted" and (not move.name or move.name == "/") and move.journal_id and move.journal_id.sequence_id ): if ( move.move_type in ("out_refund", "in_refund") and move.journal_id.type in ("sale", "purchase") and move.journal_id.refund_sequence and move.journal_id.refund_sequence_id ): seq = move.journal_id.refund_sequence_id else: seq = move.journal_id.sequence_id # next_by_id(date) only applies on ir.sequence.date_range selection # => we use with_context(ir_sequence_date=date).next_by_id() # which applies on ir.sequence.date_range selection AND prefix name = seq.with_context(ir_sequence_date=move.date).next_by_id() move.name = name # We must by-pass this constraint of sequence.mixin def _constrains_date_sequence(self): return True def _is_end_of_seq_chain(self): invoices_no_gap_sequences = self.filtered( lambda inv: inv.journal_id.sequence_id.implementation == "no_gap" ) invoices_other_sequences = self - invoices_no_gap_sequences if not invoices_other_sequences and invoices_no_gap_sequences: return False return super(AccountMove, invoices_other_sequences)._is_end_of_seq_chain() def _post(self, soft=True): self.flush() return super()._post(soft=soft) def _get_last_sequence(self, relaxed=False, with_prefix=None, lock=True): return super()._get_last_sequence(relaxed, None, lock)
40.917808
2,987
10,225
py
PYTHON
15.0
# Copyright 2021 Akretion France (http://www.akretion.com/) # Copyright 2022 Vauxoo (https://www.vauxoo.com/) # @author: Alexis de Lattre <alexis.delattre@akretion.com> # @author: Moisés López <moylop260@vauxoo.com> # @author: Francisco Luna <fluna@vauxoo.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from odoo import _, api, fields, models from odoo.exceptions import ValidationError _logger = logging.getLogger(__name__) class AccountJournal(models.Model): _inherit = "account.journal" sequence_id = fields.Many2one( "ir.sequence", string="Entry Sequence", copy=False, check_company=True, domain="[('company_id', '=', company_id)]", help="This sequence will be used to generate the journal entry number.", ) refund_sequence_id = fields.Many2one( "ir.sequence", string="Credit Note Entry Sequence", copy=False, check_company=True, domain="[('company_id', '=', company_id)]", help="This sequence will be used to generate the journal entry number for refunds.", ) # Redefine the default to True as <=v13.0 refund_sequence = fields.Boolean(default=True) @api.constrains("refund_sequence_id", "sequence_id") def _check_journal_sequence(self): for journal in self: if ( journal.refund_sequence_id and journal.sequence_id and journal.refund_sequence_id == journal.sequence_id ): raise ValidationError( _( "On journal '%s', the same sequence is used as " "Entry Sequence and Credit Note Entry Sequence.", journal.display_name, ) ) if journal.sequence_id and not journal.sequence_id.company_id: msg = _( "The company is not set on sequence '%(sequence)s' configured on " "journal '%(journal)s'.", sequence=journal.sequence_id.display_name, journal=journal.display_name, ) raise ValidationError(msg) if journal.refund_sequence_id and not journal.refund_sequence_id.company_id: msg = _( "The company is not set on sequence '%(sequence)s' configured as " "credit note sequence of journal '%(journal)s'.", sequence=journal.refund_sequence_id.display_name, journal=journal.display_name, ) raise ValidationError(msg) @api.model def create(self, vals): if not vals.get("sequence_id"): vals["sequence_id"] = self._create_sequence(vals).id if ( vals.get("type") in ("sale", "purchase") and vals.get("refund_sequence", True) and not vals.get("refund_sequence_id") ): vals["refund_sequence_id"] = self._create_sequence(vals, refund=True).id return super().create(vals) @api.model def _prepare_sequence(self, vals, refund=False): code = vals.get("code") and vals["code"].upper() or "" prefix = "%s%s/%%(range_year)s/" % (refund and "R" or "", code) seq_vals = { "name": "%s%s" % (vals.get("name", _("Sequence")), refund and _("Refund") + " " or ""), "company_id": vals.get("company_id") or self.env.company.id, "implementation": "no_gap", "prefix": prefix, "padding": 4, "use_date_range": True, } return seq_vals @api.model def _create_sequence(self, vals, refund=False): seq_vals = self._prepare_sequence(vals, refund=refund) return self.env["ir.sequence"].sudo().create(seq_vals) def _prepare_sequence_current_moves(self, refund=False): """Get sequence dict values the journal based on current moves""" self.ensure_one() move_domain = [ ("journal_id", "=", self.id), ("name", "!=", "/"), ] if self.refund_sequence: #  Based on original Odoo behavior if refund: move_domain.append(("move_type", "in", ("out_refund", "in_refund"))) else: move_domain.append(("move_type", "not in", ("out_refund", "in_refund"))) last_move = self.env["account.move"].search( move_domain, limit=1, order="id DESC" ) msg_err = ( "Journal %s could not get sequence %s values based on current moves. " "Using default values." % (self.id, refund and "refund" or "") ) if not last_move: _logger.warning("%s %s", msg_err, "No moves found") return {} try: with self.env.cr.savepoint(): # get the current sequence values could be buggy to get # But even we can use the default values # or do manual changes instead of raising errors last_sequence = last_move._get_last_sequence() if not last_sequence: last_sequence = ( last_move._get_last_sequence(relaxed=True) or last_move._get_starting_sequence() ) __, seq_format_values = last_move._get_sequence_format_param( last_sequence ) prefix1 = seq_format_values["prefix1"] prefix = prefix1 if seq_format_values["year_length"] == 4: prefix += "%(range_year)s" elif seq_format_values["year_length"] == 2: prefix += "%(range_y)s" else: # If there is not year so current values are valid seq_vals = { "padding": seq_format_values["seq_length"], "suffix": seq_format_values["suffix"], "prefix": prefix, "date_range_ids": [], "use_date_range": False, "number_next_actual": seq_format_values["seq"] + 1, } return seq_vals prefix2 = seq_format_values.get("prefix2") or "" prefix += prefix2 month = seq_format_values.get("month") # It is 0 if only have year if month: prefix += "%(range_month)s" prefix3 = seq_format_values.get("prefix3") or "" where_name_value = "%s%s%s%s%s%%" % ( prefix1, "_" * seq_format_values["year_length"], prefix2, "_" * bool(month) * 2, prefix3, ) prefixes = prefix1 + prefix2 select_year = ( "split_part(name, '%s', %d)" % (prefix2, prefixes.count(prefix2)) if prefix2 else "''" ) prefixes += prefix3 select_month = ( "split_part(name, '%s', %d)" % (prefix3, prefixes.count(prefix3)) if prefix3 else "''" ) select_max_number = ( "MAX(split_part(name, '%s', %d)::INTEGER) AS max_number" % ( prefixes[-1], prefixes.count(prefixes[-1]) + 1, ) ) query = ( "SELECT %s, %s, %s FROM account_move " "WHERE name LIKE %%s AND journal_id=%%s GROUP BY 1,2" ) % ( select_year, select_month, select_max_number, ) # It is not using user input # pylint: disable=sql-injection self.env.cr.execute(query, (where_name_value, self.id)) res = self.env.cr.fetchall() prefix += prefix3 seq_vals = { "padding": seq_format_values["seq_length"], "suffix": seq_format_values["suffix"], "prefix": prefix, "date_range_ids": [], "use_date_range": True, } for year, month, max_number in res: if not year and not month: seq_vals.update( { "use_date_range": False, "number_next_actual": max_number + 1, } ) continue if len(year) == 2: # Year >=50 will be considered as last century 1950 # Year <=49 will be considered as current century 2049 if int(year) >= 50: year = "19" + year else: year = "20" + year if month: date_from = fields.Date.to_date("%s-%s-1" % (year, month)) date_to = fields.Date.end_of(date_from, "month") else: date_from = fields.Date.to_date("%s-1-1" % year) date_to = fields.Date.to_date("%s-12-31" % year) seq_vals["date_range_ids"].append( ( 0, 0, { "date_from": date_from, "date_to": date_to, "number_next_actual": max_number + 1, }, ) ) return seq_vals except Exception as e: _logger.warning("%s %s", msg_err, e) return {}
41.722449
10,222
1,919
py
PYTHON
15.0
from odoo import fields, models class IrSequence(models.Model): _inherit = "ir.sequence" def _create_date_range_seq(self, date): # Fix issue creating new date range for future dates # It assigns more than one month # TODO: Remove if odoo merge the following PR: # https://github.com/odoo/odoo/pull/91019 date_obj = fields.Date.from_string(date) sequence_range = self.env["ir.sequence.date_range"] prefix_suffix = "%s %s" % (self.prefix, self.suffix) if "%(range_day)s" in prefix_suffix: date_from = date_obj date_to = date_obj elif "%(range_month)s" in prefix_suffix: date_from = fields.Date.start_of(date_obj, "month") date_to = fields.Date.end_of(date_obj, "month") else: date_from = fields.Date.start_of(date_obj, "year") date_to = fields.Date.end_of(date_obj, "year") date_range = sequence_range.search( [ ("sequence_id", "=", self.id), ("date_from", ">=", date), ("date_from", "<=", date_to), ], order="date_from desc", limit=1, ) if date_range: date_to = fields.Date.subtract(date_range.date_from, days=1) date_range = sequence_range.search( [ ("sequence_id", "=", self.id), ("date_to", ">=", date_from), ("date_to", "<=", date), ], order="date_to desc", limit=1, ) if date_range: date_to = fields.Date.add(date_range.date_to, days=1) sequence_range_vals = { "date_from": date_from, "date_to": date_to, "sequence_id": self.id, } seq_date_range = sequence_range.sudo().create(sequence_range_vals) return seq_date_range
36.903846
1,919
848
py
PYTHON
15.0
# Copyright 2015-2017 See manifest # Copyright 2018 Raf Ven <raf.ven@dynapps.be> # Copyright 2019 Akretion France (http://www.akretion.com/) # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { "name": "Account Move Template", "version": "15.0.1.0.0", "category": "Accounting", "summary": "Templates for recurring Journal Entries", "author": "Agile Business Group, Aurium Technologies, Vauxoo, ForgeFlow, " "Akretion, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "license": "AGPL-3", "depends": ["account"], "data": [ "security/account_move_template_security.xml", "security/ir.model.access.csv", "wizard/account_move_template_run_view.xml", "view/account_move_template.xml", ], "installable": True, }
36.869565
848
8,299
py
PYTHON
15.0
# Copyright 2018-2019 ForgeFlow, S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import logging from psycopg2 import IntegrityError from odoo import Command, fields from odoo.tests.common import TransactionCase from odoo.tools import mute_logger _logger = logging.getLogger(__name__) class TestAccountMoveTemplate(TransactionCase): def with_context(self, *args, **kwargs): context = dict(args[0] if args else self.env.context, **kwargs) self.env = self.env(context=context) return self def _chart_of_accounts_create(self, company, chart): _logger.debug("Creating chart of account") self.env.user.write( {"company_ids": [Command.link(company.id)], "company_id": company.id} ) self.with_context(company_id=company.id, force_company=company.id) wizard = self.env["wizard.multi.charts.accounts"].create( { "company_id": company.id, "chart_template_id": chart.id, "code_digits": 6, "currency_id": self.env.ref("base.EUR").id, "transfer_account_id": chart.transfer_account_id.id, } ) wizard.onchange_chart_template_id() wizard.execute() return True def setUp(self): super(TestAccountMoveTemplate, self).setUp() employees_group = self.env.ref("base.group_user") multi_company_group = self.env.ref("base.group_multi_company") account_user_group = self.env.ref("account.group_account_user") account_manager_group = self.env.ref("account.group_account_manager") self.company = self.env["res.company"].create({"name": "Test company"}) self.company_2 = self.env["res.company"].create( {"name": "Test company 2", "parent_id": self.company.id} ) self.env.user.company_ids += self.company self.env.user.company_ids += self.company_2 self.user = ( self.env["res.users"] .with_user(self.env.user) .with_context(no_reset_password=True) .create( { "name": "Test User", "login": "test_user", "email": "test@oca.com", "groups_id": [ ( 6, 0, [ employees_group.id, account_user_group.id, account_manager_group.id, multi_company_group.id, ], ) ], "company_id": self.company.id, "company_ids": [Command.link(self.company.id)], } ) ) self.user_type = self.env.ref("account.data_account_type_liquidity") self.chart = self.env["account.chart.template"].search([], limit=1) self._chart_of_accounts_create(self.company, self.chart) account_template = self.env["account.account.template"].create( {"name": "Test 1", "code": "Code_test", "user_type_id": self.user_type.id} ) self.env["ir.model.data"].create( { "name": account_template.name, "module": "account", "model": "account.account.template", "res_id": account_template.id, "noupdate": 0, } ) self.chart_2 = self.env["account.chart.template"].create( { "name": "Test Chart", "currency_id": self.env.ref("base.EUR").id, "transfer_account_id": account_template.id, } ) account_template.chart_template_id = self.chart_2 self.chart_2.tax_template_ids |= self.chart.tax_template_ids self._chart_of_accounts_create(self.company_2, self.chart_2) self.chart.company_id = self.company self.chart_2.company_id = self.company_2 self.account_company_1 = self.env["account.account"].search( [("company_id", "=", self.company.id)], limit=1 ) self.account_journal_1 = self.env["account.journal"].create( { "name": "Journal Company 1", "company_id": self.company.id, "code": "TST", "type": "general", } ) self.partner = self.env["res.partner"].create( {"name": "Test partner", "company_id": False} ) self.partner2 = self.env["res.partner"].create( {"name": "Test partner 2", "company_id": False} ) self.account_type = self.env["account.account.type"].create( {"name": "Test Tax Account Type"} ) self.tax_account_id = self.env["account.account"].create( { "name": "tax account", "code": "TAX", "user_type_id": self.account_type.id, "company_id": self.company.id, } ) self.tax = self.env["account.tax"].create( { "name": "Tax 10.0%", "amount": 10.0, "amount_type": "percent", "account_id": self.tax_account_id.id, } ) def test_create_template(self): """Test that I can create a template""" template = ( self.env["account.move.template"] .with_user(self.user) .create( { "name": "Test Move Template", "company_id": self.company.id, "journal_id": self.account_journal_1.id, "template_line_ids": [ ( 0, 0, { "name": "L1", "sequence": 1, "account_id": self.account_company_1.id, "partner_id": self.partner.id, "tax_line_id": self.tax.id, "move_line_type": "dr", "type": "input", }, ), ( 0, 0, { "name": "L2", "sequence": 2, "account_id": self.account_company_1.id, "move_line_type": "cr", "tax_ids": [Command.link(self.tax.id)], "type": "input", }, ), ], } ) ) self.assertEqual(template.company_id, self.user.company_id) template_2 = template.copy() self.assertEqual(template_2.name, "%s (copy)" % template.name) wiz = ( self.env["wizard.select.move.template"] .with_user(self.user) .create( { "company_id": self.company.id, "template_id": template.id, "partner_id": self.partner2.id, "date": fields.Date.today(), } ) ) wiz.load_lines() res = wiz.load_template() aml = self.env["account.move.line"].search( [("account_id", "=", self.account_company_1.id)], limit=1 ) self.assertEqual(res["domain"], ([("id", "in", aml.move_id.ids)])) aml = self.env["account.move.line"].search([("name", "=", "L1")], limit=1) self.assertEqual(aml.tax_line_id, self.tax) self.assertEqual(aml.partner_id, self.partner) aml = self.env["account.move.line"].search([("name", "=", "L2")], limit=1) self.assertEqual(aml.tax_ids[0], self.tax) with self.assertRaises(IntegrityError), mute_logger("odoo.sql_db"): template_2.name = template.name
37.722727
8,299
10,896
py
PYTHON
15.0
# Copyright 2020 Ecosoft (http://ecosoft.co.th) # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import Command from odoo.exceptions import UserError, ValidationError from odoo.tests.common import Form, TransactionCase class TestAccountMoveTemplateEnhanced(TransactionCase): def setUp(self): super(TestAccountMoveTemplateEnhanced, self).setUp() self.Move = self.env["account.move"] self.Journal = self.env["account.journal"] self.Account = self.env["account.account"] self.Template = self.env["account.move.template"] self.Partner = self.env["res.partner"] self.journal = self.Journal.search([("type", "=", "general")], limit=1) self.ar_account_id = self.Account.search( [("user_type_id.type", "=", "receivable")], limit=1 ) self.ap_account_id = self.Account.search( [("user_type_id.type", "=", "payable")], limit=1 ) self.income_account_id = self.Account.search( [ ("user_type_id.type", "=", "other"), ("user_type_id.internal_group", "=", "income"), ], limit=1, ) self.expense_account_id = self.Account.search( [ ("user_type_id.type", "=", "other"), ("user_type_id.internal_group", "=", "expense"), ], limit=1, ) self.partners = self.Partner.search([], limit=3) # Create a simple move tempalte ar_line = { "sequence": 0, "name": "AR Line 1", "account_id": self.ar_account_id.id, "opt_account_id": self.ap_account_id.id, "move_line_type": "dr", "type": "input", } income_line1 = { "sequence": 1, "name": "Income Line 2", "account_id": self.income_account_id.id, "opt_account_id": self.expense_account_id.id, "move_line_type": "cr", "type": "computed", "python_code": "L0*1/3", } income_line2 = { "sequence": 2, "name": "Income Line 2", "account_id": self.income_account_id.id, "opt_account_id": self.expense_account_id.id, "move_line_type": "cr", "type": "computed", "python_code": "L0*2/3", } self.move_template = self.Template.create( { "name": "Test Template", "journal_id": self.journal.id, "line_ids": [ Command.create(ar_line), Command.create(income_line1), Command.create(income_line2), ], } ) def test_move_template_normal(self): """Test normal case, input amount 300""" with Form(self.env["account.move.template.run"]) as f: f.template_id = self.move_template template_run = f.save() template_run.load_lines() template_run.line_ids[0].amount = 300 res = template_run.generate_move() move = self.Move.browse(res["res_id"]) self.assertRecordValues( move.line_ids.sorted("credit"), [ {"account_id": self.ar_account_id.id, "credit": 0.0, "debit": 300.0}, { "account_id": self.income_account_id.id, "credit": 100.0, "debit": 0.0, }, { "account_id": self.income_account_id.id, "credit": 200.0, "debit": 0.0, }, ], ) def test_move_template_optional(self): """Test optional case, input amount -300, expect optional account""" with Form(self.env["account.move.template.run"]) as f: f.template_id = self.move_template template_run = f.save() template_run.load_lines() template_run.line_ids[0].amount = -300 # Negative amount res = template_run.generate_move() move = self.Move.browse(res["res_id"]) self.assertRecordValues( move.line_ids.sorted("debit"), [ {"account_id": self.ap_account_id.id, "credit": 300.0, "debit": 0.0}, { "account_id": self.expense_account_id.id, "credit": 0.0, "debit": 100.0, }, { "account_id": self.expense_account_id.id, "credit": 0.0, "debit": 200.0, }, ], ) def test_move_template_overwrite(self): """Test case overwrite, amount = 3000, no need to manual input""" # Test for error when debit is not a valid field with Form(self.env["account.move.template.run"]) as f: f.template_id = self.move_template f.overwrite = str( { "L0": { "partner_id": self.partners[0].id, "amount": 3000, "debit": 3000, }, } ) template_run = f.save() msg_error = "overwrite are .'partner_id', 'amount', 'name', 'date_maturity'" with self.assertRaisesRegex(ValidationError, msg_error): template_run.load_lines() # Assign only on valid fields, and load_lines again with Form(self.env["account.move.template.run"]) as f: f.template_id = self.move_template f.overwrite = str( { "L0": {"partner_id": self.partners[0].id, "amount": 3000}, "L1": {"partner_id": self.partners[1].id}, "L2": {"partner_id": self.partners[2].id}, } ) template_run = f.save() res = template_run.load_lines() self.assertEqual(template_run.line_ids[0].partner_id, self.partners[0]) self.assertEqual(template_run.line_ids[0].amount, 3000) res = template_run.with_context(**res["context"]).generate_move() move = self.Move.browse(res["res_id"]) self.assertRecordValues( move.line_ids.sorted("credit"), [ { "partner_id": self.partners[0].id, "account_id": self.ar_account_id.id, "credit": 0.0, "debit": 3000.0, }, { "partner_id": self.partners[1].id, "account_id": self.income_account_id.id, "credit": 1000.0, "debit": 0.0, }, { "partner_id": self.partners[2].id, "account_id": self.income_account_id.id, "credit": 2000.0, "debit": 0.0, }, ], ) def test_move_copy(self): template_copy = self.move_template.copy() self.assertEqual(template_copy.name, "Test Template (copy)") def test_move_generate_from_action_button(self): # `Generate Journal Entry` action button res = self.move_template.generate_journal_entry() self.assertEqual(res["name"], "Create Entry from Template") self.assertEqual(res["res_model"], "account.move.template.run") def test_move_template_exceptions(self): msg_error = "Python Code must be set for computed line with sequence 1." with self.assertRaisesRegex(ValidationError, msg_error): self.move_template.line_ids[1].python_code = "" self.move_template.line_ids[1].python_code = "P0*1/3" with Form(self.env["account.move.template.run"]) as f: f.template_id = self.move_template template_run = f.save() template_run.load_lines() msg_error = "really exists and have a lower sequence than the current line." with self.assertRaisesRegex(UserError, msg_error): template_run.generate_move() self.move_template.line_ids[1].python_code = "L0*" with Form(self.env["account.move.template.run"]) as f: f.template_id = self.move_template template_run = f.save() template_run.load_lines() msg_error = "the syntax of the formula is wrong." with self.assertRaisesRegex(UserError, msg_error): template_run.generate_move() self.move_template.line_ids[1].python_code = "L0*1/3" with Form(self.env["account.move.template.run"]) as f: f.template_id = self.move_template template_run = f.save() template_run.load_lines() template_run.line_ids[0].amount = 0 msg_error = "Debit and credit of all lines are null." with self.assertRaisesRegex(UserError, msg_error): template_run.generate_move() with Form(self.env["account.move.template.run"]) as f: f.template_id = self.move_template f.overwrite = [] template_run = f.save() msg_error = "Overwrite value must be a valid python dict" with self.assertRaisesRegex(ValidationError, msg_error): template_run.load_lines() with Form(self.env["account.move.template.run"]) as f: f.template_id = self.move_template f.overwrite = str({"P0": {"amount": 100}}) template_run = f.save() msg_error = "Keys must be line sequence, i..e, L1, L2, ..." with self.assertRaisesRegex(ValidationError, msg_error): template_run.load_lines() with Form(self.env["account.move.template.run"]) as f: f.template_id = self.move_template f.overwrite = str({"L0": []}) template_run = f.save() msg_error = "Invalid dictionary: 'list' object has no attribute 'keys'" with self.assertRaisesRegex(ValidationError, msg_error): template_run.load_lines() with Form(self.env["account.move.template.run"]) as f: f.template_id = self.move_template f.overwrite = str({"L0": {"test": 100}}) template_run = f.save() msg_error = "overwrite are .'partner_id', 'amount', 'name', 'date_maturity'" with self.assertRaisesRegex(ValidationError, msg_error): template_run.load_lines() with Form(self.env["account.move.template.run"]) as f: f.template_id = self.move_template template_run = f.save() template_run.line_ids.unlink() msg_error = "You deleted a line in the wizard. This is not allowed:" with self.assertRaisesRegex(UserError, msg_error): template_run.generate_move()
40.206642
10,896
12,136
py
PYTHON
15.0
# Copyright 2015-2019 See manifest # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from ast import literal_eval from odoo import Command, _, fields, models from odoo.exceptions import UserError, ValidationError class AccountMoveTemplateRun(models.TransientModel): _name = "account.move.template.run" _description = "Wizard to generate move from template" template_id = fields.Many2one("account.move.template", required=True) company_id = fields.Many2one( "res.company", required=True, readonly=True, default=lambda self: self.env.company, ) partner_id = fields.Many2one( "res.partner", "Override Partner", domain=["|", ("parent_id", "=", False), ("is_company", "=", True)], ) date = fields.Date(required=True, default=fields.Date.context_today) journal_id = fields.Many2one("account.journal", string="Journal", readonly=True) ref = fields.Char(string="Reference") line_ids = fields.One2many( "account.move.template.line.run", "wizard_id", string="Lines" ) state = fields.Selection( [("select_template", "Select Template"), ("set_lines", "Set Lines")], readonly=True, default="select_template", ) overwrite = fields.Text( help=""" Valid dictionary to overwrite template lines: {'L1': {'partner_id': 1, 'amount': 100, 'name': 'some label'}, 'L2': {'partner_id': 2, 'amount': 200, 'name': 'some label 2'}, } """ ) def _prepare_wizard_line(self, tmpl_line): vals = { "wizard_id": self.id, "sequence": tmpl_line.sequence, "name": tmpl_line.name, "amount": 0.0, "account_id": tmpl_line.account_id.id, "partner_id": tmpl_line.partner_id.id or False, "move_line_type": tmpl_line.move_line_type, "tax_line_id": tmpl_line.tax_line_id.id, "tax_ids": [Command.set(tmpl_line.tax_ids.ids)], "analytic_account_id": tmpl_line.analytic_account_id.id, "analytic_tag_ids": [Command.set(tmpl_line.analytic_tag_ids.ids)], "note": tmpl_line.note, "payment_term_id": tmpl_line.payment_term_id.id or False, "is_refund": tmpl_line.is_refund, "tax_repartition_line_id": tmpl_line.tax_repartition_line_id.id or False, } return vals # STEP 1 def load_lines(self): self.ensure_one() # Verify and get overwrite dict overwrite_vals = self._get_overwrite_vals() amtlro = self.env["account.move.template.line.run"] if self.company_id != self.template_id.company_id: raise UserError( _( "The selected template (%(template)s) is not in the same company " "(%(company)s) as the current user (%(user_company)s).", template=self.template_id.name, company=self.template_id.company_id.display_name, user_company=self.company_id.display_name, ) ) tmpl_lines = self.template_id.line_ids for tmpl_line in tmpl_lines.filtered(lambda l: l.type == "input"): vals = self._prepare_wizard_line(tmpl_line) amtlro.create(vals) self.write( { "journal_id": self.template_id.journal_id.id, "ref": self.template_id.ref, "state": "set_lines", } ) if not self.line_ids: return self.generate_move() action = self.env.ref("account_move_template.account_move_template_run_action") result = action.sudo().read()[0] result.update({"res_id": self.id, "context": self.env.context}) # Overwrite self.line_ids to show overwrite values self._overwrite_line(overwrite_vals) # Pass context furtner to generate_move function, only readonly field for key in overwrite_vals.keys(): overwrite_vals[key].pop("amount", None) context = result.get("context", {}).copy() context.update({"overwrite": overwrite_vals}) result["context"] = context return result def _get_valid_keys(self): return ["partner_id", "amount", "name", "date_maturity"] def _get_overwrite_vals(self): """valid_dict = { 'L1': {'partner_id': 1, 'amount': 10}, 'L2': {'partner_id': 2, 'amount': 20}, } """ self.ensure_one() valid_keys = self._get_valid_keys() overwrite_vals = self.overwrite or "{}" try: overwrite_vals = literal_eval(overwrite_vals) assert isinstance(overwrite_vals, dict) except (SyntaxError, ValueError, AssertionError) as err: raise ValidationError( _("Overwrite value must be a valid python dict") ) from err # First level keys must be L1, L2, ... keys = overwrite_vals.keys() if list(filter(lambda x: x[:1] != "L" or not x[1:].isdigit(), keys)): raise ValidationError(_("Keys must be line sequence, i..e, L1, L2, ...")) # Second level keys must be a valid keys try: if dict( filter(lambda x: set(overwrite_vals[x].keys()) - set(valid_keys), keys) ): raise ValidationError( _("Valid fields to overwrite are %s") % valid_keys ) except ValidationError as e: raise e except Exception as e: msg = """ valid_dict = { 'L1': {'partner_id': 1, 'amount': 10}, 'L2': {'partner_id': 2, 'amount': 20}, } """ raise ValidationError( _( "Invalid dictionary: %(exception)s\n%(msg)s", exception=e, msg=msg, ) ) from e return overwrite_vals def _safe_vals(self, model, vals): obj = self.env[model] copy_vals = vals.copy() invalid_keys = list( set(list(vals.keys())) - set(list(dict(obj._fields).keys())) ) for key in invalid_keys: copy_vals.pop(key) return copy_vals def _overwrite_line(self, overwrite_vals): self.ensure_one() for line in self.line_ids: vals = overwrite_vals.get("L{}".format(line.sequence), {}) safe_vals = self._safe_vals(line._name, vals) line.write(safe_vals) # STEP 2 def generate_move(self): self.ensure_one() sequence2amount = {} for wizard_line in self.line_ids: sequence2amount[wizard_line.sequence] = wizard_line.amount company_cur = self.company_id.currency_id self.template_id.compute_lines(sequence2amount) if all([company_cur.is_zero(x) for x in sequence2amount.values()]): raise UserError(_("Debit and credit of all lines are null.")) move_vals = self._prepare_move() for line in self.template_id.line_ids: amount = sequence2amount[line.sequence] if not company_cur.is_zero(amount): move_vals["line_ids"].append( Command.create(self._prepare_move_line(line, amount)) ) move = self.env["account.move"].create(move_vals) action = self.env.ref("account.action_move_journal_line") result = action.sudo().read()[0] result.update( { "name": _("Entry from template %s") % self.template_id.name, "res_id": move.id, "views": False, "view_id": False, "view_mode": "form,tree,kanban", "context": self.env.context, } ) return result def _prepare_move(self): move_vals = { "ref": self.ref, "journal_id": self.journal_id.id, "date": self.date, "company_id": self.company_id.id, "line_ids": [], } return move_vals def _prepare_move_line(self, line, amount): date_maturity = False if line.payment_term_id: pterm_list = line.payment_term_id.compute(value=1, date_ref=self.date) date_maturity = max(line[0] for line in pterm_list) debit = line.move_line_type == "dr" values = { "name": line.name, "analytic_account_id": line.analytic_account_id.id, "account_id": line.account_id.id, "credit": not debit and amount or 0.0, "debit": debit and amount or 0.0, "partner_id": self.partner_id.id or line.partner_id.id, "date_maturity": date_maturity or self.date, "tax_repartition_line_id": line.tax_repartition_line_id.id or False, } if line.analytic_tag_ids: values["analytic_tag_ids"] = [Command.set(line.analytic_tag_ids.ids)] if line.tax_ids: values["tax_ids"] = [Command.set(line.tax_ids.ids)] tax_repartition = "refund_tax_id" if line.is_refund else "invoice_tax_id" atrl_ids = self.env["account.tax.repartition.line"].search( [ (tax_repartition, "in", line.tax_ids.ids), ("repartition_type", "=", "base"), ] ) values["tax_tag_ids"] = [Command.set(atrl_ids.mapped("tag_ids").ids)] if line.tax_repartition_line_id: values["tax_tag_ids"] = [ Command.set(line.tax_repartition_line_id.tag_ids.ids) ] # With overwrite options overwrite = self._context.get("overwrite", {}) move_line_vals = overwrite.get("L{}".format(line.sequence), {}) values.update(move_line_vals) # Use optional account, when amount is negative self._update_account_on_negative(line, values) return values def _update_account_on_negative(self, line, vals): if not line.opt_account_id: return for key in ["debit", "credit"]: if vals[key] < 0: ikey = (key == "debit") and "credit" or "debit" vals["account_id"] = line.opt_account_id.id vals[ikey] = abs(vals[key]) vals[key] = 0 class AccountMoveTemplateLineRun(models.TransientModel): _name = "account.move.template.line.run" _description = "Wizard Lines to generate move from template" wizard_id = fields.Many2one("account.move.template.run", ondelete="cascade") company_id = fields.Many2one(related="wizard_id.company_id") company_currency_id = fields.Many2one( related="wizard_id.company_id.currency_id", string="Company Currency" ) sequence = fields.Integer(required=True) name = fields.Char(readonly=True) account_id = fields.Many2one("account.account", required=True, readonly=True) analytic_account_id = fields.Many2one("account.analytic.account", readonly=True) analytic_tag_ids = fields.Many2many( "account.analytic.tag", string="Analytic Tags", readonly=True ) tax_ids = fields.Many2many("account.tax", string="Taxes", readonly=True) tax_line_id = fields.Many2one( "account.tax", string="Originator Tax", ondelete="restrict", readonly=True ) partner_id = fields.Many2one("res.partner", readonly=True, string="Partner") payment_term_id = fields.Many2one( "account.payment.term", string="Payment Terms", readonly=True ) move_line_type = fields.Selection( [("cr", "Credit"), ("dr", "Debit")], required=True, readonly=True, string="Direction", ) amount = fields.Monetary(required=True, currency_field="company_currency_id") note = fields.Char(readonly=True) is_refund = fields.Boolean(string="Is a refund?", readonly=True) tax_repartition_line_id = fields.Many2one( "account.tax.repartition.line", string="Tax Repartition Line", readonly=True, )
40.052805
12,136
7,491
py
PYTHON
15.0
# Copyright 2015-2019 See manifest # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError from odoo.tools.safe_eval import safe_eval class AccountMoveTemplate(models.Model): _name = "account.move.template" _description = "Journal Entry Template" name = fields.Char(required=True) company_id = fields.Many2one( "res.company", string="Company", required=True, ondelete="cascade", default=lambda self: self.env.company, ) journal_id = fields.Many2one("account.journal", string="Journal", required=True) ref = fields.Char(string="Reference", copy=False) line_ids = fields.One2many( "account.move.template.line", inverse_name="template_id", string="Lines" ) active = fields.Boolean(default=True) _sql_constraints = [ ( "name_company_unique", "unique(name, company_id)", "This name is already used by another template!", ) ] def copy(self, default=None): self.ensure_one() default = dict(default or {}, name=_("%s (copy)") % self.name) return super().copy(default) def eval_computed_line(self, line, sequence2amount): safe_eval_dict = {} for seq, amount in sequence2amount.items(): safe_eval_dict["L%d" % seq] = amount try: val = safe_eval(line.python_code, safe_eval_dict) sequence2amount[line.sequence] = val except ValueError as err: raise UserError( _( "Impossible to compute the formula of line with sequence %(sequence)s " "(formula: %(code)s). Check that the lines used in the formula " "really exists and have a lower sequence than the current " "line.", sequence=line.sequence, code=line.python_code, ) ) from err except SyntaxError as err: raise UserError( _( "Impossible to compute the formula of line with sequence %(sequence)s " "(formula: %(code)s): the syntax of the formula is wrong.", sequence=line.sequence, code=line.python_code, ) ) from err def compute_lines(self, sequence2amount): company_cur = self.company_id.currency_id input_sequence2amount = sequence2amount.copy() for line in self.line_ids.filtered(lambda x: x.type == "input"): if line.sequence not in sequence2amount: raise UserError( _( "You deleted a line in the wizard. This is not allowed: " "you should either update the template or modify the " "journal entry that will be generated by this wizard." ) ) input_sequence2amount.pop(line.sequence) if input_sequence2amount: raise UserError( _( "You added a line in the wizard. This is not allowed: " "you should either update the template or modify " "the journal entry that will be generated by this wizard." ) ) for line in self.line_ids.filtered(lambda x: x.type == "computed"): self.eval_computed_line(line, sequence2amount) sequence2amount[line.sequence] = company_cur.round( sequence2amount[line.sequence] ) return sequence2amount def generate_journal_entry(self): """Called by the button on the form view""" self.ensure_one() wiz = self.env["account.move.template.run"].create({"template_id": self.id}) action = wiz.load_lines() return action class AccountMoveTemplateLine(models.Model): _name = "account.move.template.line" _description = "Journal Item Template" _order = "sequence, id" template_id = fields.Many2one( "account.move.template", string="Move Template", ondelete="cascade" ) name = fields.Char(string="Label", required=True) sequence = fields.Integer(required=True) account_id = fields.Many2one( "account.account", string="Account", required=True, domain=[("deprecated", "=", False)], ) partner_id = fields.Many2one( "res.partner", string="Partner", domain=["|", ("parent_id", "=", False), ("is_company", "=", True)], ) analytic_account_id = fields.Many2one( "account.analytic.account", string="Analytic Account" ) analytic_tag_ids = fields.Many2many("account.analytic.tag", string="Analytic Tags") tax_ids = fields.Many2many("account.tax", string="Taxes") tax_line_id = fields.Many2one( "account.tax", string="Originator Tax", ondelete="restrict" ) company_id = fields.Many2one(related="template_id.company_id", store=True) company_currency_id = fields.Many2one( related="template_id.company_id.currency_id", string="Company Currency", store=True, ) note = fields.Char() type = fields.Selection( [("computed", "Computed"), ("input", "User input")], required=True, default="input", ) python_code = fields.Text() move_line_type = fields.Selection( [("cr", "Credit"), ("dr", "Debit")], required=True, string="Direction" ) payment_term_id = fields.Many2one( "account.payment.term", string="Payment Terms", help="Used to compute the due date of the journal item.", ) is_refund = fields.Boolean( default=False, string="Is a refund?", ) tax_repartition_line_id = fields.Many2one( "account.tax.repartition.line", string="Tax Repartition Line", compute="_compute_tax_repartition_line_id", store=True, readonly=True, ) opt_account_id = fields.Many2one( "account.account", string="Account Opt.", domain=[("deprecated", "=", False)], help="When amount is negative, use this account instead", ) @api.depends("is_refund", "account_id", "tax_line_id") def _compute_tax_repartition_line_id(self): for record in self.filtered(lambda x: x.account_id and x.tax_line_id): tax_repartition = "refund_tax_id" if record.is_refund else "invoice_tax_id" record.tax_repartition_line_id = self.env[ "account.tax.repartition.line" ].search( [ ("account_id", "=", record.account_id.id), (tax_repartition, "=", record.tax_line_id.id), ], limit=1, ) _sql_constraints = [ ( "sequence_template_uniq", "unique(template_id, sequence)", "The sequence of the line must be unique per template!", ) ] @api.constrains("type", "python_code") def check_python_code(self): for line in self: if line.type == "computed" and not line.python_code: raise ValidationError( _("Python Code must be set for computed line with " "sequence %d.") % line.sequence )
37.084158
7,491
561
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Dauden # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Residual amount on journal items", "summary": "Display residual amount in move line view", "version": "15.0.1.0.1", "category": "Accounting", "website": "https://github.com/OCA/account-financial-tools", "author": "Tecnativa," "Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["account"], "data": ["views/account_move_line_view.xml"], }
37.4
561
480
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": "Account Maturity Date Default", "version": "15.0.1.0.0", "category": "Accounting", "author": "Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "license": "AGPL-3", "depends": ["account"], "data": [], "installable": True, "maintainers": ["victoralmau"], }
34.142857
478
3,960
py
PYTHON
15.0
# Copyright 2021-2022 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl) from odoo import fields from odoo.tests import Form, common class TestAccountMove(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.account_tax = cls.env["account.tax"].create( {"name": "0%", "amount_type": "fixed", "type_tax_use": "sale", "amount": 0} ) cls.partner = cls.env["res.partner"].create({"name": "Partner test"}) cls.product = cls.env["product.product"].create( { "name": "Product Test", "list_price": 10, "taxes_id": [(6, 0, [cls.account_tax.id])], } ) cls.account = cls.env["account.account"].create( { "name": "Test Account", "code": "TEST", "user_type_id": cls.env.ref("account.data_account_type_receivable").id, "reconcile": True, } ) cls.other_account = cls.env["account.account"].create( { "name": "Test Account", "code": "ACC", "user_type_id": cls.env.ref( "account.data_account_type_other_income" ).id, "reconcile": True, } ) cls.journal_sale = cls.env["account.journal"].create( {"name": "Test sale journal", "type": "sale", "code": "T-SALE"} ) cls.journal_bank = cls.env["account.journal"].create( {"name": "Test bank journal", "type": "bank", "code": "T-BANK"} ) def _create_invoice(self): move_form = Form( self.env["account.move"].with_context(default_move_type="out_invoice") ) move_form.partner_id = self.partner move_form.invoice_date = fields.Date.from_string("2000-01-01") with move_form.invoice_line_ids.new() as line_form: line_form.product_id = self.product invoice = move_form.save() return invoice def test_invoice_move_update(self): invoice = self._create_invoice() invoice.line_ids.write({"date_maturity": False}) invoice.write({"date": "1999-12-31"}) invoice_line = invoice.line_ids.filtered( lambda x: x.account_id.internal_type == "receivable" ) self.assertEqual( invoice_line.date_maturity, fields.Date.from_string("1999-12-31") ) def test_invoice_reconciliation(self): invoice = self._create_invoice() invoice.action_post() invoice_line = invoice.line_ids.filtered( lambda x: x.account_id.internal_type == "receivable" ) statement = self.env["account.bank.statement"].create( { "journal_id": self.journal_bank.id, "name": "Test", "date": "2000-01-01", "balance_end_real": 10.0, "line_ids": [ ( 0, 0, { "date": "2000-01-01", "partner_id": self.partner.id, "payment_ref": invoice.name, "amount": 10.0, }, ) ], } ) statement.button_post() statement_line = statement.line_ids.filtered( lambda x: x.payment_ref == invoice.name ) statement_line.reconcile(lines_vals_list=[{"id": invoice_line.id}]) self.assertEqual(invoice.payment_state, "paid") line_receivable = statement_line.move_id.line_ids.filtered( lambda x: x.account_id.internal_type == "receivable" ) self.assertEqual(line_receivable.date_maturity, line_receivable.move_id.date)
37.695238
3,958
573
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models class AccountMove(models.Model): _inherit = "account.move" def write(self, vals): res = super().write(vals) if vals.get("date"): self.mapped("line_ids").filtered( lambda x: ( not x.date_maturity and x.account_internal_type in {"receivable", "payable"} ) ).write({"date_maturity": vals["date"]}) return res
31.722222
571
685
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class AccountMoveLine(models.Model): _inherit = "account.move.line" @api.model_create_multi def create(self, vals_list): for vals in vals_list: if not vals.get("date_maturity"): account = self.env["account.account"].browse(vals.get("account_id")) if account.internal_type in {"receivable", "payable"}: move = self.env["account.move"].browse(vals.get("move_id")) vals["date_maturity"] = move.date return super().create(vals_list)
40.176471
683
674
py
PYTHON
15.0
# Copyright 2019-2020 ForgeFlow S.L. # (https://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Account Move Line Purchase Info", "summary": "Introduces the purchase order line to the journal items", "version": "15.0.1.1.1", "author": "ForgeFlow, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "category": "Generic", "depends": ["purchase_stock"], "license": "AGPL-3", "data": [ "security/account_security.xml", "views/account_move_view.xml", "views/purchase_order_view.xml", ], "installable": True, }
33.7
674
9,254
py
PYTHON
15.0
# Copyright 2021 ForgeFlow S.L. # (https://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields from odoo.tests import Form, common class TestAccountMoveLinePurchaseInfo(common.TransactionCase): @classmethod def setUpClass(cls): super(TestAccountMoveLinePurchaseInfo, cls).setUpClass() cls.purchase_model = cls.env["purchase.order"] cls.purchase_line_model = cls.env["purchase.order.line"] cls.product_model = cls.env["product.product"] cls.product_ctg_model = cls.env["product.category"] cls.acc_type_model = cls.env["account.account.type"] cls.account_model = cls.env["account.account"] cls.am_model = cls.env["account.move"] cls.aml_model = cls.env["account.move.line"] cls.res_users_model = cls.env["res.users"] cls.partner1 = cls.env.ref("base.res_partner_1") cls.location_stock = cls.env.ref("stock.stock_location_stock") cls.company = cls.env.ref("base.main_company") cls.group_purchase_user = cls.env.ref("purchase.group_purchase_user") cls.group_account_invoice = cls.env.ref("account.group_account_invoice") cls.group_account_manager = cls.env.ref("account.group_account_manager") # Create account for Goods Received Not Invoiced acc_type = cls._create_account_type(cls, "equity", "other") name = "Goods Received Not Invoiced" code = "grni" cls.account_grni = cls._create_account(cls, acc_type, name, code, cls.company) # Create account for Cost of Goods Sold acc_type = cls._create_account_type(cls, "expense", "other") name = "Cost of Goods Sold" code = "cogs" cls.account_cogs = cls._create_account(cls, acc_type, name, code, cls.company) # Create account for Inventory acc_type = cls._create_account_type(cls, "asset", "other") name = "Inventory" code = "inventory" cls.account_inventory = cls._create_account( cls, acc_type, name, code, cls.company ) # Create Product cls.product = cls._create_product(cls) # Create users cls.purchase_user = cls._create_user( cls, "purchase_user", [cls.group_purchase_user, cls.group_account_invoice], cls.company, ) cls.account_invoice = cls._create_user( cls, "account_invoice", [cls.group_account_invoice], cls.company ) cls.account_manager = cls._create_user( cls, "account_manager", [cls.group_account_manager], cls.company ) def _create_user(self, login, groups, company): """Create a user.""" group_ids = [group.id for group in groups] user = self.res_users_model.with_context(**{"no_reset_password": True}).create( { "name": "Test User", "login": login, "password": "demo", "email": "test@yourcompany.com", "company_id": company.id, "company_ids": [(4, company.id)], "groups_id": [(6, 0, group_ids)], } ) return user.id def _create_account_type(self, name, a_type): acc_type = self.acc_type_model.create( {"name": name, "type": a_type, "internal_group": name} ) return acc_type def _create_account(self, acc_type, name, code, company): """Create an account.""" account = self.account_model.create( { "name": name, "code": code, "user_type_id": acc_type.id, "company_id": company.id, "reconcile": True, } ) return account def _create_product(self): """Create a Product.""" # group_ids = [group.id for group in groups] product_ctg = self.product_ctg_model.create( { "name": "test_product_ctg", "property_stock_valuation_account_id": self.account_inventory.id, "property_valuation": "real_time", "property_stock_account_input_categ_id": self.account_grni.id, "property_stock_account_output_categ_id": self.account_cogs.id, } ) product = self.product_model.create( { "name": "test_product", "categ_id": product_ctg.id, "type": "product", "standard_price": 1.0, "list_price": 1.0, } ) return product def _create_purchase(self, line_products): """Create a purchase order. ``line_products`` is a list of tuple [(product, qty)] """ lines = [] for product, qty in line_products: line_values = { "name": product.name, "product_id": product.id, "product_qty": qty, "product_uom": product.uom_id.id, "price_unit": 500, "date_planned": fields.datetime.now(), } lines.append((0, 0, line_values)) return self.purchase_model.create( {"partner_id": self.partner1.id, "order_line": lines} ) def _get_balance(self, domain): """ Call read_group method and return the balance of particular account. """ aml_rec = self.aml_model.read_group( domain, ["debit", "credit", "account_id"], ["account_id"] ) if aml_rec: return aml_rec[0].get("debit", 0) - aml_rec[0].get("credit", 0) else: return 0.0 def _check_account_balance( self, account_id, purchase_line=None, expected_balance=0.0 ): """ Check the balance of the account """ domain = [("account_id", "=", account_id)] if purchase_line: domain.extend([("purchase_line_id", "=", purchase_line.id)]) balance = self._get_balance(domain) if purchase_line: self.assertEqual( balance, expected_balance, "Balance is not %s for Purchase Line %s." % (str(expected_balance), purchase_line.name), ) def test_purchase_invoice(self): """Test that the po line moves from the purchase order to the account move line and to the invoice line. """ purchase = self._create_purchase([(self.product, 1)]) po_line = False for line in purchase.order_line: po_line = line break purchase.button_confirm() picking = purchase.picking_ids[0] picking.action_confirm() picking.move_lines.write({"quantity_done": 1.0}) picking.button_validate() expected_balance = 1.0 self._check_account_balance( self.account_inventory.id, purchase_line=po_line, expected_balance=expected_balance, ) f = Form(self.am_model.with_context(default_type="in_invoice")) f.partner_id = purchase.partner_id f.purchase_id = purchase invoice = f.save() invoice._post() purchase.flush() for aml in invoice.invoice_line_ids: if aml.product_id == po_line.product_id and aml.move_id: self.assertEqual( aml.purchase_line_id, po_line, "Purchase Order line has not been copied " "from the invoice to the account move line.", ) def test_name_get(self): purchase = self._create_purchase([(self.product, 1)]) po_line = purchase.order_line[0] name_get = po_line.with_context(**{"po_line_info": True}).name_get() self.assertEqual( name_get, [ ( po_line.id, "[%s] %s (%s)" % (po_line.order_id.name, po_line.name, po_line.order_id.state), ) ], ) name_get_no_ctx = po_line.name_get() self.assertEqual(name_get_no_ctx, [(po_line.id, po_line.name)]) def test_purchase_order_with_journal_entries_and_vendor_bills(self): purchase = self._create_purchase([(self.product, 1)]) purchase.button_confirm() purchase._compute_invoice() purchase._compute_journal_entries() self.assertEqual(purchase.journal_entry_ids.id, False) self.assertEqual(purchase.invoice_ids.id, False) self.assertEqual(purchase.journal_entries_count, 0) self.assertEqual(purchase.invoice_count, 0) purchase.picking_ids.move_ids_without_package.quantity_done = 1 purchase.picking_ids.button_validate() self.assertEqual(purchase.journal_entries_count, 1) self.assertEqual(purchase.invoice_count, 0) purchase.action_create_invoice() self.assertEqual(purchase.journal_entries_count, 1) self.assertEqual(purchase.invoice_count, 1) self.assertNotEqual(purchase.action_view_journal_entries(), None)
37.771429
9,254
368
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. # (https://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class AccountMoveLine(models.Model): _inherit = "account.move.line" purchase_order_id = fields.Many2one( comodel_name="purchase.order", store=True, index=True, )
24.533333
368
673
py
PYTHON
15.0
# Copyright 2019-2020 ForgeFlow S.L. # (https://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import models class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" def name_get(self): result = [] orig_name = dict(super(PurchaseOrderLine, self).name_get()) for line in self: name = orig_name[line.id] if self.env.context.get("po_line_info", False): name = "[{}] {} ({})".format( line.order_id.name, name, line.order_id.state ) result.append((line.id, name)) return result
33.65
673
2,482
py
PYTHON
15.0
from odoo import api, fields, models class PurchaseOrder(models.Model): _inherit = "purchase.order" @api.depends("order_line.invoice_lines.move_id") def _compute_journal_entries(self): for order in self: journal_entries = order.mapped("order_line.invoice_lines.move_id").filtered( lambda r: r.move_type == "entry" ) order.journal_entry_ids = journal_entries order.journal_entries_count = len(journal_entries) journal_entries_count = fields.Integer(compute="_compute_journal_entries") journal_entry_ids = fields.Many2many( comodel_name="account.move", relation="journal_entries_ids_purchase_order", compute="_compute_journal_entries", string="Journal Entries", ) @api.depends("order_line.invoice_lines.move_id") def _compute_invoice(self): """Overwritten compute to avoid show all Journal Entries with purchase_order_line as invoice_lines One2many would take them into account.""" for order in self: invoices = order.order_line.invoice_lines.move_id.filtered( lambda m: m.is_invoice(include_receipts=True) ) order.invoice_ids = invoices order.invoice_count = len(invoices) def action_view_journal_entries(self, invoices=False): """This function returns an action that display existing journal entries of given purchase order ids. When only one found, show the journal entry immediately. """ if not invoices: self.sudo()._read(["journal_entry_ids"]) invoices = self.journal_entry_ids result = self.env["ir.actions.act_window"]._for_xml_id( "account.action_move_journal_line" ) # choose the view_mode accordingly if len(invoices) > 1: result["domain"] = [("id", "in", invoices.ids)] elif len(invoices) == 1: res = self.env.ref("account.view_move_form", False) form_view = [(res and res.id or False, "form")] if "views" in result: result["views"] = form_view + [ (state, view) for state, view in result["views"] if view != "form" ] else: result["views"] = form_view result["res_id"] = invoices.id else: result = {"type": "ir.actions.act_window_close"} return result
39.396825
2,482
616
py
PYTHON
15.0
# Copyright 2019 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 class StockMove(models.Model): _inherit = "stock.move" @api.model def _prepare_account_move_line( self, qty, cost, credit_account_id, debit_account_id, description ): res = super(StockMove, self)._prepare_account_move_line( qty, cost, credit_account_id, debit_account_id, description ) for line in res: line[2]["purchase_line_id"] = self.purchase_line_id.id return res
30.8
616
670
py
PYTHON
15.0
# Copyright 2013-2020 Akretion France (https://akretion.com/) # @author: Alexis de Lattre <alexis.delattre@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Account Fiscal Position VAT Check", "version": "15.0.1.0.1", "category": "Invoices & Payments", "license": "AGPL-3", "summary": "Check VAT on invoice validation", "author": "Akretion,Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "depends": ["account", "base_vat"], "data": [ "views/account_fiscal_position.xml", "views/res_partner.xml", ], "installable": True, }
35.263158
670
1,459
py
PYTHON
15.0
# Copyright 2013-2020 Akretion France (https://akretion.com/) # @author: Alexis de Lattre <alexis.delattre@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, models from odoo.exceptions import UserError class AccountMove(models.Model): _inherit = "account.move" def _post(self, soft=True): """Check that the customer has VAT set if required by the fiscal position""" for move in self: if ( move.move_type in ("out_invoice", "out_refund") and move.fiscal_position_id.vat_required and not move.commercial_partner_id.vat ): raise UserError( _( "You are trying to validate a customer " "invoice/refund with the fiscal position '%(fp)s' " "that require the customer to have a VAT number. " "But the Customer '%(rp)s' " "doesn't have a VAT number in Odoo. " "Please add the VAT number of this Customer in Odoo " "and try to validate again." ) % { "fp": move.fiscal_position_id.display_name, "rp": move.commercial_partner_id.display_name, } ) return super()._post(soft=soft)
40.527778
1,459
785
py
PYTHON
15.0
# Copyright 2013-2022 Akretion France (https://akretion.com/) # @author: Alexis de Lattre <alexis.delattre@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class ResPartner(models.Model): _inherit = "res.partner" show_warning_vat_required = fields.Boolean( compute="_compute_show_warning_vat_required" ) @api.depends("property_account_position_id", "vat") @api.depends_context("company") def _compute_show_warning_vat_required(self): for partner in self: show = False fp = partner.property_account_position_id if fp and fp.vat_required and not partner.vat: show = True partner.show_warning_vat_required = show
34.130435
785
535
py
PYTHON
15.0
# Copyright 2018 Simone Rubino - Agile Business Group # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Sale Order Priority", "summary": "Define priority on sale orders", "version": "15.0.1.0.1", "category": "Sale Workflow", "website": "https://github.com/OCA/sale-workflow", "author": "Agile Business Group, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["sale_stock"], "data": ["views/sale.xml"], }
35.666667
535
2,586
py
PYTHON
15.0
# Copyright 2018 Simone Rubino - Agile Business Group # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.addons.sale.tests.common import TestSaleCommonBase class TestSaleStock(TestSaleCommonBase): @classmethod def setUpClass(cls): super().setUpClass() cls.company = cls.env["res.company"].create( { "name": "Test Company", "currency_id": cls.env.ref("base.EUR").id, } ) cls.company_data = cls.setup_sale_configuration_for_company(cls.company) cls.partner = cls.env["res.partner"].create( { "name": "partner1", "company_id": False, } ) def test_sale_order_priority(self): sale_order_priority = "1" self.sale_order = self.env["sale.order"].create( { "partner_id": self.partner.id, "priority": sale_order_priority, "order_line": [ ( 0, 0, { "name": self.company_data["product_order_cost"].name, "product_id": self.company_data["product_order_cost"].id, "product_uom_qty": 2, "qty_delivered": 1, "product_uom": self.company_data[ "product_order_cost" ].uom_id.id, "price_unit": self.company_data[ "product_order_cost" ].list_price, }, ), ], } ) sale_order_line_priority = "0" for sol in self.sale_order.order_line: # Test that the order's priority has been # correctly assigned to the order lines self.assertEqual( sol.priority, sale_order_priority, "Priority of order lines does not match", ) sol.priority = sale_order_line_priority # Confirm the order and check the picking self.sale_order.action_confirm() # Test that the lines' priority has been # correctly assigned to the generated pickings self.assertEqual( max(self.sale_order.picking_ids.mapped("priority")), sale_order_line_priority, "Priority of generated picking does not match", )
36.422535
2,586