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
3,929
py
PYTHON
15.0
# Copyright 2017-2018 Vauxoo # 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" custom_rate = fields.Float( digits=(12, 6), default=1, store=True, readonly=False, compute="_compute_currency_change_rate", help="Set new currency rate to apply on the invoice.\n" "This rate will be taken in order to convert amounts between the " "currency on the invoice and last currency", ) original_currency_id = fields.Many2one( "res.currency", help="Store the original currency when the invoice is created or the " "conversion is called for the first time. " "This is used to calculate conversion from this currency.", ) is_original_currency = fields.Boolean( compute="_compute_is_original_currency", help="Check if current currency is the original currency. " "This is used to hide custom rate field in the form view.", ) @api.model def create(self, values): values.setdefault("original_currency_id", values.get("currency_id")) return super().create(values) def action_account_change_currency(self): """ This method convert the original price unit from the original currency when the invoice was created to the current currency using the custom rate and recompute all taxes. """ today = fields.Date.context_today(self) invoices = self.filtered(lambda x: x.state == "draft").with_context( check_move_validity=False, ) for invoice in invoices: if not invoice.original_currency_id: invoice.write({"original_currency_id": invoice.currency_id}) invoice.invoice_line_ids._set_original_price_unit() invoice_date = invoice.invoice_date or today to_currency = invoice.currency_id context = {"custom_rate": invoice.custom_rate, "to_currency": to_currency} original_currency = invoice.original_currency_id.with_context(**context) for line in invoice.invoice_line_ids: line.price_unit = original_currency._convert( line.original_price_unit, to_currency, invoice.company_id, invoice_date, ) invoice._recompute_dynamic_lines(recompute_all_taxes=True) @api.depends("company_id", "currency_id", "invoice_date") def _compute_currency_change_rate(self): """ Compute the custom rate from the original currency when the invoice was created to the current currency. The custom rate field is editable, but it will not change if custom rate is zero or the current currency and the original currency are the same """ for invoice in self: if not invoice.currency_id or not invoice.company_id: invoice.custom_rate = 1.0 continue date = invoice.invoice_date or fields.Date.context_today(invoice) from_currency = invoice.original_currency_id or invoice.currency_id invoice.custom_rate = from_currency._get_conversion_rate( from_currency, invoice.currency_id, invoice.company_id, date, ) @api.depends("currency_id", "original_currency_id") def _compute_is_original_currency(self): """ Compute if the current currency and the original currency are the same. The is_original_currency field is used in the view to hide the custom_rate field. """ for invoice in self: invoice.is_original_currency = ( invoice.currency_id == invoice.original_currency_id )
41.797872
3,929
805
py
PYTHON
15.0
# Copyright 2017-2018 Vauxoo # 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" original_price_unit = fields.Monetary( help="Store price unit from every line when the " "invoice is created or the conversion is called " "for the first time to use it to convert the " "amount in the new currency.", ) @api.model_create_multi def create(self, vals_list): for vals in vals_list: vals.setdefault("original_price_unit", vals.get("price_unit")) return super().create(vals_list) def _set_original_price_unit(self): for line in self: line.write({"original_price_unit": line.price_unit})
33.541667
805
701
py
PYTHON
15.0
# Copyright 2017-2018 Vauxoo # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class ResCurrency(models.Model): _inherit = "res.currency" def _get_rates(self, company, date): """ Inheritance to use the provided custom rate by user instead of the rate from odoo. """ custom_rate = self.env.context.get("custom_rate") to_currency = self.env.context.get("to_currency") if custom_rate and to_currency: return { currency.id: custom_rate if currency == to_currency else 1.0 for currency in self } return super()._get_rates(company, date)
33.380952
701
532
py
PYTHON
15.0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Update Invoice's Due Date", "version": "15.0.1.0.2", "author": "Vauxoo,Odoo Community Association (OCA)", "maintainers": ["luisg123v", "joao-p-marques"], "category": "Accounting", "website": "https://github.com/OCA/account-invoicing", "license": "AGPL-3", "depends": ["account"], "demo": [], "data": ["security/security.xml", "views/account_move_date_due.xml"], "installable": True, "auto_install": False, }
33.25
532
7,935
py
PYTHON
15.0
# Copyright 2021 Tecnativa - João Marques # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from datetime import datetime, timedelta from odoo import fields from odoo.tests import Form, common class TestAccountInvoiceDateDue(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env( context=dict(cls.env.context, tracking_disable=True, no_reset_password=True) ) # Create new user allowed to change invoice due date group = cls.env.ref("account_invoice_date_due.allow_to_change_due_date") acc_group = cls.env.ref("account.group_account_manager") # Loose dependency on stock to avoid perm issues. # We don't really care about such permissions in this context! # Eg: # odoo.exceptions.AccessError: # You are not allowed to access 'Stock Valuation Layer' (stock.valuation.layer) records. stock_group = ( cls.env.ref("stock.group_stock_manager", False) or cls.env["res.groups"] ) cls.user_w_access = cls.env["res.users"].create( { "name": "Test User w/ access", "login": "user_w_access", "email": "somebody@somewhere.com", "groups_id": [(6, 0, (group + acc_group + stock_group).ids)], } ) # Create new user not allowed to change invoice due date cls.user_wo_access = cls.env["res.users"].create( { "name": "Test User wo/ access", "login": "user_wo_access", "groups_id": [(6, 0, (acc_group + stock_group).ids)], } ) account100 = cls.env["account.account"].create( { "code": "100", "name": "Account 100", "user_type_id": cls.env.ref("account.data_account_type_receivable").id, "reconcile": True, } ) account300 = cls.env["account.account"].create( { "code": "300", "name": "Account 300", "user_type_id": cls.env.ref( "account.data_account_type_other_income" ).id, } ) move_form = Form(cls.env["account.move"]) move_form.date = fields.Date.today() with move_form.invoice_line_ids.new() as line_form: line_form.name = "move test" line_form.debit = 0.0 line_form.credit = 1000.0 line_form.account_id = account300 with move_form.invoice_line_ids.new() as line_form: line_form.name = "move test" line_form.debit = 1000.0 line_form.credit = 0.0 line_form.account_id = account100 cls.move = move_form.save() def _compare_records(self, rec1, rec2, ignore=None): diff_fields = [] for field in rec1: if field in ignore: continue if rec1[field] != rec2[field]: diff_fields.append(field) return set(diff_fields) def test_invoice_date_due_is_editable(self): old_move_state = self.move.read()[0] move_edit_form = Form(self.move.with_user(self.user_w_access)) ten_days_from_now = fields.Date.to_string(datetime.today() + timedelta(days=10)) move_edit_form.invoice_date_due = ten_days_from_now self.move = move_edit_form.save() # Read all fields as sudo to get them independently of the user. # Other modules can add security groups in account.move fields self.assertEqual( self._compare_records( old_move_state, self.move.sudo().read()[0], ignore={"write_uid", "message_is_follower"}, ), # Assert only this field is changed {"invoice_date_due_payment_term", "invoice_date_due"}, ) self.assertEqual( fields.Date.to_string(self.move.invoice_date_due), ten_days_from_now ) # Post and should remain editable self.move.action_post() old_move_state = self.move.read()[0] move_edit_form = Form(self.move.with_user(self.user_w_access)) twenty_days_from_now = fields.Date.to_string( datetime.today() + timedelta(days=20) ) move_edit_form.invoice_date_due = twenty_days_from_now self.move = move_edit_form.save() self.assertEqual( fields.Date.to_string(self.move.invoice_date_due), twenty_days_from_now ) # Check that the change has been propagated to the corresponding invoice line self.assertEqual( len( self.move.line_ids.filtered( lambda l: fields.Date.to_string(l.date_maturity) == twenty_days_from_now and l.account_id.user_type_id.type in ("receivable", "payable") ) ), 1, ) self.assertEqual( self._compare_records( old_move_state, self.move.sudo().read()[0], ignore={"write_uid", "message_is_follower", "message_ids"}, ), # Assert only this field is changed {"invoice_date_due_payment_term", "invoice_date_due"}, ) def test_invoice_date_due_is_editable_w_payment_term(self): move_edit_form = Form(self.move.with_user(self.user_w_access)) move_edit_form.invoice_payment_term_id = self.env.ref( "account.account_payment_term_15days" ) self.move = move_edit_form.save() self.assertFalse(self.move.invoice_date_due) # Post and should remain editable even w/ payment term twenty_days_from_now = fields.Date.to_string( datetime.today() + timedelta(days=20) ) self.move.action_post() old_move_state = self.move.read()[0] move_edit_form = Form(self.move.with_user(self.user_w_access)) move_edit_form.invoice_date_due_payment_term = twenty_days_from_now self.move = move_edit_form.save() # Check that the change has been propagated to the corresponding invoice line self.assertEqual( len( self.move.line_ids.filtered( lambda l: fields.Date.to_string(l.date_maturity) == twenty_days_from_now and l.account_id.user_type_id.type in ("receivable", "payable") ) ), 1, ) self.assertEqual( self._compare_records( old_move_state, self.move.sudo().read()[0], ignore={"write_uid", "message_is_follower", "message_ids"}, ), # Assert only this field is changed {"invoice_date_due_payment_term", "invoice_date_due"}, ) def test_invoice_date_due_is_not_editable_for_user_wo_access(self): move_edit_form = Form(self.move.with_user(self.user_wo_access)) ten_days_from_now = fields.Date.to_string(datetime.today() + timedelta(days=10)) move_edit_form.invoice_date_due = ten_days_from_now self.move = move_edit_form.save() self.assertEqual( fields.Date.to_string(self.move.invoice_date_due), ten_days_from_now ) # Should be editable while in draft # Post and should not be editable for this user self.move.action_post() move_edit_form = Form(self.move.with_user(self.user_wo_access)) twenty_days_from_now = fields.Date.to_string( datetime.today() + timedelta(days=20) ) with self.assertRaisesRegex( AssertionError, r"can't\swrite\son\sreadonly\sfield.*" ): move_edit_form.invoice_date_due = twenty_days_from_now
41.539267
7,934
1,942
py
PYTHON
15.0
# 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" # Show invoice date due even when payment term is defined invoice_date_due_payment_term = fields.Date( related="invoice_date_due", string="Due Date Payment Term" ) @api.onchange("invoice_date_due_payment_term") def _onchange_invoice_date_due_payment_term(self): """Propagate from Payment term due date to original field""" if self.invoice_date_due_payment_term: self.invoice_date_due = self.invoice_date_due_payment_term def _compute_amount(self): # Avoid recomputation of amount fields when we are only changing the # invoice's due date if self.env.context.get("bypass_compute_amount"): return return super()._compute_amount() def onchange(self, values, field_name, field_onchange): obj = self if field_name == "invoice_date_due" and self.state == "posted": # A change in the invoice date due would trigger a recompute of the # amount fields. We want to avoid that to prevent inconsistencies with # the payment state. obj = self.with_context(bypass_compute_amount=True) return super(AccountMove, obj).onchange(values, field_name, field_onchange) def write(self, vals): res = super().write(vals) # Propagate due date to move lines # that correspont to the receivable/payable account if "invoice_date_due" in vals: payment_term_lines = self.filtered( lambda r: r.state == "posted" ).line_ids.filtered( lambda line: line.account_id.user_type_id.type in ("receivable", "payable") ) payment_term_lines.date_maturity = vals["invoice_date_due"] return res
40.458333
1,942
515
py
PYTHON
15.0
# Copyright 2023 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Account Portal Invoice Search By Lot", "version": "15.0.1.0.0", "category": "Accounting", "website": "https://github.com/OCA/account-invoicing", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "development_status": "Beta", "application": False, "installable": True, "depends": ["account_portal_invoice_search", "sale_stock"], }
36.785714
515
1,679
py
PYTHON
15.0
# Copyright 2023 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models from odoo.osv import expression class AccountMove(models.Model): _inherit = "account.move" lot_name_search = fields.Char( compute="_compute_lot_name_search", search="_search_lot_name_search" ) def _compute_lot_name_search(self): """We just need the field to use the search""" def _search_lot_name_search(self, operator, value): """Used for portal search. We force equality as we handle millions of records. A fuzzy search could lead to a huge performance drop. So we force a exact match. """ if operator != "=": return lot_ids = ( self.env["stock.production.lot"].sudo()._search([("name", "=ilike", value)]) ) sml_ids = ( self.env["stock.move.line"] .sudo() ._search([("lot_id", "in", lot_ids), ("state", "=", "done")]) ) sm = ( self.env["stock.move"] .sudo() .search_read([("move_line_ids", "in", sml_ids)], ["sale_line_id"]) ) return [ ( "line_ids.sale_line_ids", "in", list({x["sale_line_id"][:1] for x in sm if x["sale_line_id"]}), ) ] @api.model def _get_portal_search_domain(self, portal_invoice_filter): domain = super()._get_portal_search_domain(portal_invoice_filter) domain = expression.OR( [domain, [("lot_name_search", "=", portal_invoice_filter)]] ) return domain
32.921569
1,679
733
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. (https://www.forgeflow.com) # Copyright 2017-2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Purchase Stock Picking Return Invoicing", "summary": "Add an option to refund returned pickings", "version": "15.0.1.0.0", "category": "Purchases", "website": "https://github.com/OCA/account-invoicing", "author": "ForgeFlow, Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "development_status": "Mature", "depends": ["purchase_stock"], "data": ["views/account_invoice_view.xml", "views/purchase_view.xml"], "maintainers": ["pedrobaeza", "MiquelRForgeFlow"], }
40.722222
733
7,034
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. (https://www.forgeflow.com) # Copyright 2017-2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields from odoo.tests.common import TransactionCase, tagged @tagged("post_install", "-at_install") class TestPurchaseStockPickingReturnInvoicing(TransactionCase): @classmethod def setUpClass(cls): """Add some defaults to let the test run without an accounts chart.""" super(TestPurchaseStockPickingReturnInvoicing, cls).setUpClass() cls.journal = cls.env["account.journal"].create( {"name": "Test journal", "type": "purchase", "code": "TEST_J"} ) cls.account_payable_type = cls.env["account.account.type"].create( { "name": "Payable account type", "type": "payable", "internal_group": "liability", } ) cls.account_expense_type = cls.env["account.account.type"].create( { "name": "Expense account type", "type": "other", "internal_group": "expense", } ) cls.payable_account = cls.env["account.account"].create( { "name": "Payable Account", "code": "PAY", "user_type_id": cls.account_payable_type.id, "reconcile": True, } ) cls.expense_account = cls.env["account.account"].create( { "name": "Expense Account", "code": "EXP", "user_type_id": cls.account_expense_type.id, "reconcile": False, } ) cls.partner = cls.env["res.partner"].create( {"name": "Test partner", "is_company": True} ) cls.partner.property_account_payable_id = cls.payable_account cls.product_categ = cls.env["product.category"].create( {"name": "Test category"} ) cls.product = cls.env["product.product"].create( { "name": "test product", "categ_id": cls.product_categ.id, "uom_id": cls.env.ref("uom.product_uom_unit").id, "uom_po_id": cls.env.ref("uom.product_uom_unit").id, "default_code": "tpr1", } ) cls.product.property_account_expense_id = cls.expense_account cls.po = cls.env["purchase.order"].create( { "partner_id": cls.partner.id, "order_line": [ ( 0, 0, { "name": cls.product.name, "product_id": cls.product.id, "product_qty": 5.0, "product_uom": cls.product.uom_id.id, "price_unit": 10, "date_planned": fields.Datetime.now(), }, ) ], } ) cls.po_line = cls.po.order_line cls.po.button_confirm() cls.po.button_approve() def check_values( self, po_line, qty_returned, qty_received, qty_refunded, qty_invoiced, invoice_status, ): self.assertAlmostEqual(po_line.qty_returned, qty_returned, 2) self.assertAlmostEqual(po_line.qty_received, qty_received, 2) self.assertAlmostEqual(po_line.qty_refunded, qty_refunded, 2) self.assertAlmostEqual(po_line.qty_invoiced, qty_invoiced, 2) self.assertEqual(po_line.order_id.invoice_status, invoice_status) def test_initial_state(self): self.check_values(self.po_line, 0, 0, 0, 0, "no") def test_purchase_stock_return_1(self): """Test a PO with received, invoiced, returned and refunded qty. Receive and invoice the PO, then do a return of the picking. Check that the invoicing status of the purchase, and quantities received and billed are correct throughout the process. """ # receive completely pick = self.po.picking_ids pick.move_lines.write({"quantity_done": 5}) pick.button_validate() self.check_values(self.po_line, 0, 5, 0, 0, "to invoice") # Make invoice action = self.po.action_create_invoice() inv_1 = self.env["account.move"].browse(action["res_id"]) self.check_values(self.po_line, 0, 5, 0, 5, "invoiced") self.assertAlmostEqual(inv_1.amount_untaxed_signed, -50, 2) # Return some items, after PO was invoiced return_wizard = self.env["stock.return.picking"].create({"picking_id": pick.id}) return_wizard._onchange_picking_id() return_wizard.product_return_moves.write({"quantity": 2, "to_refund": True}) return_pick = pick.browse(return_wizard.create_returns()["res_id"]) return_pick.move_lines.write({"quantity_done": 2}) return_pick.button_validate() self.check_values(self.po_line, 2, 3, 0, 5, "to invoice") # Make refund action2 = self.po.with_context( default_move_type="in_refund" ).action_create_invoice_refund() inv_2 = self.env["account.move"].browse(action2["res_id"]) self.check_values(self.po_line, 2, 3, 2, 3, "invoiced") self.assertAlmostEqual(inv_2.amount_untaxed_signed, 20, 2) action = self.po.action_view_invoice() self.assertEqual(action["res_id"], inv_1.id) action2 = self.po.action_view_invoice_refund() self.assertEqual(action2["res_id"], inv_2.id) def test_purchase_stock_return_2(self): """Test a PO with received and returned qty, and invoiced after. Receive the PO, then do a partial return of the picking. Create a new invoice to get the bill for the remaining qty. Check that the invoicing status of the purchase, and quantities received and billed are correct throughout the process. """ pick = self.po.picking_ids pick.move_lines.write({"quantity_done": 5}) pick.button_validate() # Return some items before PO was invoiced return_wizard = self.env["stock.return.picking"].create({"picking_id": pick.id}) return_wizard._onchange_picking_id() return_wizard.product_return_moves.write({"quantity": 2, "to_refund": True}) return_pick = pick.browse(return_wizard.create_returns()["res_id"]) return_pick.move_lines.write({"quantity_done": 2}) return_pick.button_validate() self.check_values(self.po_line, 2, 3, 0, 0, "to invoice") # Make invoice action = self.po.action_create_invoice() inv_1 = self.env["account.move"].browse(action["res_id"]) self.check_values(self.po_line, 2, 3, 0, 3, "invoiced") self.assertAlmostEqual(inv_1.amount_untaxed_signed, -30, 2)
41.621302
7,034
10,595
py
PYTHON
15.0
# Copyright 2017 ForgeFlow S.L. (https://www.forgeflow.com) # Copyright 2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import collections from itertools import groupby from odoo import _, api, fields, models from odoo.exceptions import UserError from odoo.tools.float_utils import float_compare, float_is_zero class PurchaseOrder(models.Model): _inherit = "purchase.order" invoice_refund_count = fields.Integer( compute="_compute_invoice_refund_count", string="# of Invoice Refunds" ) def _check_invoice_status_to_invoice(self): precision = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) return any( float_compare( line.qty_invoiced, line.product_qty if line.product_id.purchase_method == "purchase" else line.qty_received, precision_digits=precision, ) for line in self.order_line ) def _get_invoiced(self): """Modify invoice_status for taking into account returned/refunded qty, as the comparison qty_received vs qty_invoiced can be negative. It's only needed to modify the method for resetting state to "to invoice", as the rest of the states are already handled by super. """ res = super(PurchaseOrder, self)._get_invoiced() for order in self.filtered(lambda x: x.state in ("purchase", "done")): if order._check_invoice_status_to_invoice(): order.invoice_status = "to invoice" return res @api.depends("order_line.invoice_lines.move_id.state") def _compute_invoice_refund_count(self): for order in self: invoices = order.mapped("order_line.invoice_lines.move_id").filtered( lambda x: x.move_type == "in_refund" ) order.invoice_refund_count = len(invoices) @api.depends("invoice_refund_count") def _compute_invoice(self): """Change computation for excluding refund invoices. Make this compatible with other extensions, only subtracting refunds from the number obtained in super. """ res = super()._compute_invoice() for order in self: order.invoice_count -= order.invoice_refund_count return res def action_create_invoice_refund(self): """Create the refund associated to the PO.""" precision = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) # 1) Prepare refund vals and clean-up the section lines invoice_vals_list = [] for order in self: if order.invoice_status != "to invoice": continue order = order.with_company(order.company_id) pending_section = None # Invoice values. invoice_vals = order._prepare_invoice() # Invoice line values (keep only necessary sections). for line in order.order_line: if line.display_type == "line_section": pending_section = line continue if not float_is_zero(line.qty_to_invoice, precision_digits=precision): if pending_section: invoice_vals["invoice_line_ids"].append( (0, 0, pending_section._prepare_account_move_line()) ) pending_section = None invoice_vals["invoice_line_ids"].append( (0, 0, line._prepare_account_move_line()) ) invoice_vals_list.append(invoice_vals) if not invoice_vals_list: raise UserError( _( "There is no invoiceable line. " "If a product has a control policy based on received quantity, " "please make sure that a quantity has been received." ) ) # 2) group by (company_id, partner_id, currency_id) for batch creation new_invoice_vals_list = [] for _grouping_keys, invoices in groupby( invoice_vals_list, key=lambda x: ( x.get("company_id"), x.get("partner_id"), x.get("currency_id"), ), ): origins = set() payment_refs = set() refs = set() ref_invoice_vals = None for invoice_vals in invoices: if not ref_invoice_vals: ref_invoice_vals = invoice_vals else: ref_invoice_vals["invoice_line_ids"] += invoice_vals[ "invoice_line_ids" ] origins.add(invoice_vals["invoice_origin"]) payment_refs.add(invoice_vals["payment_reference"]) refs.add(invoice_vals["ref"]) ref_invoice_vals.update( { "ref": ", ".join(refs)[:2000], "invoice_origin": ", ".join(origins), "payment_reference": len(payment_refs) == 1 and payment_refs.pop() or False, } ) new_invoice_vals_list.append(ref_invoice_vals) invoice_vals_list = new_invoice_vals_list # 3) Create refunds. moves = self.env["account.move"] AccountMove = self.env["account.move"].with_context( default_move_type="in_refund" ) for vals in invoice_vals_list: moves |= AccountMove.with_company(vals["company_id"]).create(vals) return self.action_view_invoice_refund(moves) def action_view_invoice_refund(self, invoices=False): """This function returns an action that display existing vendor refund bills of given purchase order ids. When only one found, show the vendor bill immediately. """ if not invoices: # Invoice_ids may be filtered depending on the user. To ensure we get all # invoices related to the purchase order, we read them in sudo to fill the # cache. self.sudo()._read(["invoice_ids"]) invoices = self.invoice_ids refunds = invoices.filtered(lambda x: x.move_type == "in_refund") result = self.env["ir.actions.act_window"]._for_xml_id( "account.action_move_in_refund_type" ) # choose the view_mode accordingly if len(refunds) > 1: result["domain"] = [("id", "in", refunds.ids)] elif len(refunds) == 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"] = refunds.id else: result = {"type": "ir.actions.act_window_close"} return result def action_view_invoice(self, invoices=False): """Change super action for displaying only normal invoices.""" if not invoices: # Invoice_ids may be filtered depending on the user. To ensure we get all # invoices related to the purchase order, we read them in sudo to fill the # cache. self.sudo()._read(["invoice_ids"]) invoices = self.invoice_ids invoices = invoices.filtered(lambda x: x.move_type == "in_invoice") result = super(PurchaseOrder, self).action_view_invoice(invoices) return result class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" qty_refunded = fields.Float(compute="_compute_qty_refunded", string="Refunded Qty") qty_returned = fields.Float( compute="_compute_qty_returned", string="Returned* Qty", help="This is ONLY the returned quantity that is refundable.", store=True, ) @api.depends("invoice_lines.move_id.state", "invoice_lines.quantity") def _compute_qty_refunded(self): for line in self: inv_lines = line.invoice_lines.filtered( lambda x: ( (x.move_id.move_type == "in_invoice" and x.quantity < 0.0) or (x.move_id.move_type == "in_refund" and x.quantity > 0.0) ) ) line.qty_refunded = sum( inv_lines.mapped( lambda x: ( x.product_uom_id._compute_quantity(x.quantity, line.product_uom) ) ) ) @api.depends("move_ids.state", "move_ids.returned_move_ids.state") def _compute_qty_returned(self): """Made through read_group for not impacting in performance.""" ProductUom = self.env["uom.uom"] groups = self.env["stock.move"].read_group( [ ("purchase_line_id", "in", self.ids), ("state", "=", "done"), ("to_refund", "=", True), ("location_id.usage", "!=", "supplier"), ], ["purchase_line_id", "product_uom_qty", "product_uom"], ["purchase_line_id", "product_uom"], lazy=False, ) # load all UoM records at once on first access uom_ids = {g["product_uom"][0] for g in groups} ProductUom.browse(list(uom_ids)) # Prefetching line_qtys = collections.defaultdict(lambda: 0) for g in groups: uom = ProductUom.browse(g["product_uom"][0]) line = self.browse(g["purchase_line_id"][0]) if uom == line.product_uom: qty = g["product_uom_qty"] else: qty = uom._compute_quantity(g["product_uom_qty"], line.product_uom) line_qtys[line.id] += qty for line in self: line.qty_returned = line_qtys.get(line.id, 0) def _prepare_account_move_line(self, move=None): data = super()._prepare_account_move_line(move) move_type = self.env.context.get("default_move_type", False) if (move and move.move_type == "in_refund") or ( not move and move_type and move_type == "in_refund" ): data["quantity"] *= -1.0 return data
41.065891
10,595
802
py
PYTHON
15.0
# Copyright 2017 ForgeFlow S.L. (https://www.forgeflow.com) # Copyright 2017-2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, models from odoo.tools import float_is_zero class AccountMove(models.Model): _inherit = "account.move" @api.onchange("purchase_vendor_bill_id", "purchase_id") def _onchange_purchase_auto_complete(self): """Remove lines with qty=0 when making refunds.""" res = super()._onchange_purchase_auto_complete() if self.move_type == "in_refund": self.line_ids -= self.invoice_line_ids.filtered( lambda x: float_is_zero( x.quantity, precision_rounding=x.product_uom_id.rounding ) ) return res
36.454545
802
668
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Stock Picking Return Refund Option", "summary": "Update the refund options in pickings", "version": "15.0.1.0.1", "development_status": "Production/Stable", "category": "Sales", "website": "https://github.com/OCA/account-invoicing", "author": "Tecnativa, " "Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["stock_account", "purchase_stock", "sale_stock"], "data": ["views/stock_picking_view.xml"], "maintainers": ["sergio-teruel"], }
39.294118
668
5,111
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests.common import Form, TransactionCase, tagged @tagged("post_install", "-at_install") class TestSaleOrderLineInput(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.partner = cls.env["res.partner"].create( {"name": "Test", "customer_rank": 1, "supplier_rank": 1} ) cls.product = cls.env["product.product"].create( {"name": "test_product", "type": "product", "invoice_policy": "delivery"} ) cls.product2 = cls.env["product.product"].create( {"name": "test_product_2", "type": "product", "invoice_policy": "delivery"} ) with Form(cls.env["sale.order"]) as order_form: order_form.partner_id = cls.partner with order_form.order_line.new() as line_form: line_form.product_id = cls.product line_form.product_uom_qty = 1 with order_form.order_line.new() as line_form: line_form.product_id = cls.product2 line_form.product_uom_qty = 1 cls.order = order_form.save() cls.order.action_confirm() cls.picking = cls.order.picking_ids move_line_vals_list = [] for move in cls.picking.move_lines: move_line_vals = move._prepare_move_line_vals() move_line_vals["qty_done"] = 1 move_line_vals_list.append(move_line_vals) cls.env["stock.move.line"].create(move_line_vals_list) cls.picking.button_validate() cls.order._create_invoices() def get_return_picking_wizard(self, picking): stock_return_picking_form = Form( self.env["stock.return.picking"].with_context( active_ids=picking.ids, active_id=picking.ids[0], active_model="stock.picking", ) ) return stock_return_picking_form.save() def return_picking_wiz(self, picking): wizard = self.get_return_picking_wizard(picking) wizard.product_return_moves.write({"quantity": 1.0, "to_refund": False}) return wizard def test_return_to_refund_values(self): return_wizard = self.return_picking_wiz(self.picking) return_pick = self.picking.browse(return_wizard.create_returns()["res_id"]) return_pick.move_line_ids.write({"qty_done": 1.0}) return_pick.button_validate() self.assertEqual(return_pick.to_refund_lines, "no_refund") return_pick.move_lines.write({"to_refund": True}) self.assertEqual(return_pick.to_refund_lines, "to_refund") return_pick.move_lines[:1].write({"to_refund": False}) self.assertFalse(return_pick.to_refund_lines) def test_return_so_wo_to_refund(self): # Return some items, after SO was invoiced return_wizard = self.return_picking_wiz(self.picking) return_pick = self.picking.browse(return_wizard.create_returns()["res_id"]) return_pick.move_line_ids.write({"qty_done": 1.0}) return_pick.button_validate() self.assertEqual(self.order.invoice_status, "invoiced") return_pick.to_refund_lines = "to_refund" self.assertEqual(self.order.invoice_status, "to invoice") return_pick.to_refund_lines = "no_refund" self.assertEqual(self.order.invoice_status, "invoiced") return_pick.to_refund_lines = False self.assertEqual(self.order.invoice_status, "invoiced") self.assertTrue(return_pick.is_return) self.assertFalse(self.picking.is_return) def test_return_po_wo_to_refund(self): if not self.env.registry.models.get("purchase.order", False): return True order_form = Form(self.env["purchase.order"]) order_form.partner_id = self.partner with order_form.order_line.new() as line_form: line_form.product_id = self.product line_form.product_qty = 1 po_order = order_form.save() po_order.button_confirm() picking = po_order.picking_ids[:] move_line_vals = picking.move_lines._prepare_move_line_vals() move_line_vals["qty_done"] = 1 self.env["stock.move.line"].create(move_line_vals) picking.button_validate() self.assertEqual(po_order.invoice_status, "to invoice") # Return the picking without refund return_wizard = self.return_picking_wiz(picking) return_pick = self.picking.browse(return_wizard.create_returns()["res_id"]) move_line_vals = return_pick.move_lines._prepare_move_line_vals() move_line_vals["qty_done"] = 1 self.env["stock.move.line"].create(move_line_vals) return_pick.button_validate() # Now set to be refunded return_pick.to_refund_lines = "to_refund" self.assertEqual(po_order.invoice_status, "no") # And again to not be refunded return_pick.to_refund_lines = "no_refund" self.assertEqual(po_order.invoice_status, "to invoice")
45.230088
5,111
483
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models class StockMove(models.Model): _inherit = "stock.move" def write(self, vals): res = super().write(vals) if "to_refund" in vals: for move in self: if move.picking_id: move.picking_id.set_delivered_qty() move.picking_id.set_received_qty() return res
30.1875
483
3,386
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models class StockPicking(models.Model): _inherit = "stock.picking" to_refund_lines = fields.Selection( selection=[("to_refund", "To Refund"), ("no_refund", "No Refund")], compute="_compute_to_refund_lines", inverse="_inverse_to_refund_lines", string="Refund Options", help="This field allow modify 'to_refund' field value in all " "stock moves from this picking after it has been confirmed." "to_refund: set all stock moves to True value and recompute " "delivered quantities in sale order.\n" "no_refund: set all stock moves to False value and recompute " "delivered quantities in sale/purchase order.", ) is_return = fields.Boolean(compute="_compute_is_return") @api.depends("move_lines.to_refund") def _compute_to_refund_lines(self): for picking in self: moves_to_refund = picking.move_lines.filtered(lambda mv: mv.to_refund) if not moves_to_refund: picking.to_refund_lines = "no_refund" elif len(moves_to_refund) == len(picking.move_lines): picking.to_refund_lines = "to_refund" else: picking.to_refund_lines = False def _inverse_to_refund_lines(self): """ Set to_refund stock_move field: All lines to True. All lines to False. Each line to original value selected in return wizard by user. """ for picking in self: picking._update_stock_moves() picking.set_delivered_qty() picking.set_received_qty() def _compute_is_return(self): for picking in self: picking.is_return = any( x.origin_returned_move_id for x in picking.move_lines ) def _update_stock_moves(self): for pick in self.filtered("to_refund_lines"): pick.move_lines.write({"to_refund": pick.to_refund_lines == "to_refund"}) def set_delivered_qty(self): """ Check if exists sale_line_id field in stock.move model that has been added by sale_stock module, this module has not dependency of this, Update sale order line qty_delivered for allow do a refund invoice """ if hasattr(self.env["stock.move"], "sale_line_id") and self.sale_id: # The sale_stock module is installed so_lines = self.mapped("move_lines.sale_line_id").filtered( lambda x: x.product_id.invoice_policy in ("order", "delivery") ) so_lines._compute_qty_delivered() def set_received_qty(self): """ Check if exists purchase_line_id field in stock.move model that has been added by purchase module, this module has not dependency of this, Update purchase order line qty_received for allow do a refund invoice. """ if hasattr(self.env["stock.move"], "purchase_line_id") and self.purchase_id: # The purchase module is installed po_lines = self.mapped("move_lines.purchase_line_id").filtered( lambda x: x.product_id.invoice_policy in ("order", "delivery") ) po_lines._compute_qty_received()
42.325
3,386
858
py
PYTHON
15.0
# Copyright 2022 Lorenzo Battistini - TAKOBI # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). { "name": "Receipts Journals", "summary": "Define and use journals dedicated to receipts", "version": "15.0.1.0.1", "development_status": "Beta", "category": "Accounting & Finance", "website": "https://github.com/OCA/account-invoicing", "author": "TAKOBI, Odoo Community Association (OCA)", "maintainers": ["eLBati"], "license": "LGPL-3", "application": False, "installable": True, "preloadable": True, "depends": [ "account", ], "data": [ "views/account_journal_views.xml", "data/account_journal_data.xml", ], "pre_init_hook": "rename_old_italian_data", "external_dependencies": { "python": [ "openupgradelib", ], }, }
29.586207
858
2,345
py
PYTHON
15.0
from odoo.exceptions import ValidationError from odoo.tests import tagged from odoo.addons.account.tests.common import AccountTestInvoicingCommon @tagged("post_install", "-at_install") class TestReceipts(AccountTestInvoicingCommon): def setUp(self): super().setUp() self.out_receipt_journal = self.env["account.journal"].create( { "name": "Sale Receipts Journal", "code": "S-REC", "type": "sale", "receipts": True, "sequence": 99, } ) self.in_receipt_journal = self.env["account.journal"].create( { "name": "Purchase Receipts Journal", "code": "P-REC", "type": "purchase", "receipts": True, "sequence": 99, } ) def test_receipt_journal_sequence(self): with self.assertRaises(ValidationError): self.out_receipt_journal.write({"sequence": 1}) with self.assertRaises(ValidationError): self.in_receipt_journal.write({"sequence": 1}) def test_receipt_default_journal(self): """Test default values for receipt.""" for move_type in {"out_receipt", "in_receipt"}: with self.subTest(move_type=move_type): receipt = self.init_invoice( move_type, products=self.product_a + self.product_b ) self.assertTrue(receipt.journal_id.receipts) def test_receipt_exclusive_journal(self): """Test exclusivity constraint for receipt journals.""" for move_type in {"out_receipt", "in_receipt"}: with self.subTest(move_type=move_type): receipt = self.init_invoice( move_type, products=self.product_a + self.product_b ) non_receipt_journals = self.env["account.journal"].search( [ ("type", "=", receipt.journal_id.type), ("company_id", "=", receipt.journal_id.company_id.id), ("receipts", "=", False), ] ) with self.assertRaises(ValidationError): receipt.write({"journal_id": non_receipt_journals.ids[0]})
39.083333
2,345
5,096
py
PYTHON
15.0
from odoo import _, api, exceptions, models class AccountMove(models.Model): _inherit = "account.move" @api.depends("company_id", "invoice_filter_type_domain", "move_type") def _compute_suitable_journal_ids(self): res = super()._compute_suitable_journal_ids() for m in self: dedicated_journals = m.suitable_journal_ids.filtered( lambda j: j.receipts == m.move_type in {"out_receipt", "in_receipt"} ) # Suitable journals dedicated to receipts if exists m.suitable_journal_ids = dedicated_journals or m.suitable_journal_ids return res @api.model def _search_default_receipt_journal(self, journal_types): company_id = self.env.context.get("default_company_id", self.env.company.id) currency_id = self.env.context.get("default_currency_id") domain = [ ("company_id", "=", company_id), ("type", "in", journal_types), ("receipts", "=", True), ] journal = None if currency_id: journal = self.env["account.journal"].search( domain + [("currency_id", "=", currency_id)], limit=1 ) if not journal: journal = self.env["account.journal"].search(domain, limit=1) return journal @api.model def _search_default_journal(self, journal_types): journal = super()._search_default_journal(journal_types) move_type = self.env.context.get("default_move_type") # We can assume that if move_type is not in receipts, a journal without # receipts it's coming because of the Journal constraint if move_type not in {"in_receipt", "out_receipt"} or journal.receipts: return journal return self._search_default_receipt_journal(journal_types) or journal def _get_journal_types(self, move_type): if move_type in self.get_sale_types(include_receipts=True): journal_types = ["sale"] elif move_type in self.get_purchase_types(include_receipts=True): journal_types = ["purchase"] else: journal_types = self.env.context.get( "default_move_journal_types", ["general"] ) return journal_types @api.model def _update_receipts_journal(self, vals_list): """ Update `vals_list` in place to set journal_id to the receipt journal when move_type is receipt. Model defaults are also considered it move_type or journal_id are not in a `vals_list`. """ defaults = self.default_get(["journal_id", "move_type"]) default_journal = defaults.get("journal_id") default_move_type = defaults.get("move_type") for vals in vals_list: move_type = vals.get("move_type", default_move_type) if move_type in ("in_receipt", "out_receipt"): selected_journal_id = vals.get("journal_id", default_journal) selected_journal = self.env["account.journal"].browse( selected_journal_id ) if not selected_journal.receipts: journal_types = self._get_journal_types(move_type) receipt_journal = self._search_default_receipt_journal( journal_types ) if receipt_journal: vals["journal_id"] = receipt_journal.id @api.model_create_multi def create(self, vals_list): self._update_receipts_journal(vals_list) return super().create(vals_list) @api.constrains("move_type", "journal_id") def _check_receipts_journal(self): """Ensure that Receipt Journal is only used in Receipts if exists Receipt Journals for its type""" aj_model = self.env["account.journal"] receipt_domain = [("receipts", "=", True)] has_in_rjournals = aj_model.search([("type", "=", "purchase")] + receipt_domain) has_out_rjournals = aj_model.search([("type", "=", "sale")] + receipt_domain) for move in self: is_rj = move.journal_id.receipts if move.move_type not in {"in_receipt", "out_receipt"} and is_rj: raise exceptions.ValidationError( _("Receipt Journal is restricted to Receipts") ) elif move.move_type == "in_receipt" and not is_rj and has_in_rjournals: raise exceptions.ValidationError( _( "Purchase Receipt must use a Receipt Journal because " "there is already a Receipt Journal for Purchases" ) ) elif move.move_type == "out_receipt" and not is_rj and has_out_rjournals: raise exceptions.ValidationError( _( "Sale Receipt must use a Receipt Journal because " "there is already a Receipt Journal for Sales" ) )
43.931034
5,096
1,993
py
PYTHON
15.0
from odoo import _, api, exceptions, fields, models class AccountJournal(models.Model): _inherit = "account.journal" receipts = fields.Boolean( string="Exclusive to Receipts", help="If checked, this journal will be used by default for receipts " "and only can be used for receipts.", ) def action_create_new(self): """Create a new Receipt from the Dashboard""" res = super().action_create_new() if not self.receipts: return res res["name"] = _("Create receipt") if self.type == "sale": res["context"]["default_move_type"] = "out_receipt" elif self.type == "purchase": res["context"]["default_move_type"] = "in_receipt" return res @api.constrains("sequence", "type", "receipts", "company_id") def _check_receipts_sequence(self): """Ensure that journals with receipts checked, are on a higher sequence that the rest of journals of the same type""" for receipt_journal in self.filtered("receipts"): journals = self.search( [ ("type", "=", receipt_journal.type), ("receipts", "=", False), # ("sequence", "<", journal.sequence), ("id", "!=", receipt_journal.id), ("company_id", "=", receipt_journal.company_id.id), ] ) if not journals: continue previous_sequence_journals = journals.filtered( lambda j: j.sequence < receipt_journal.sequence ) if not previous_sequence_journals: raise exceptions.ValidationError( _( "The sequence of the journal '%s' must be higher than " "the sequence of the other journals of the same type." ) % receipt_journal.name )
39.078431
1,993
692
py
PYTHON
15.0
# Copyright 2021 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Account Tax Group Widget Base Amount", "summary": "Adds base to tax group widget as it's put in the report", "version": "15.0.1.0.0", "development_status": "Beta", "category": "Accounting & Finance", "website": "https://github.com/OCA/account-invoicing", "author": "Tecnativa, Odoo Community Association (OCA)", "maintainers": ["chienandalu"], "license": "AGPL-3", "depends": ["account"], "assets": { "web.assets_qweb": [ "account_tax_group_widget_base_amount/static/src/xml/tax_group.xml", ], }, }
36.421053
692
697
py
PYTHON
15.0
# Copyright 2019 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import SUPERUSER_ID, api def post_init_hook(cr, registry, vals=None): """Archive the ir.rules we want to override""" env = api.Environment(cr, SUPERUSER_ID, {}) env.ref("account.account_invoice_rule_portal").active = False env.ref("account.account_invoice_line_rule_portal").active = False def uninstall_hook(cr, registry, vals=None): """Unarchive the overriden ir.rules""" env = api.Environment(cr, SUPERUSER_ID, {}) env.ref("account.account_invoice_rule_portal").active = True env.ref("account.account_invoice_line_rule_portal").active = True
41
697
601
py
PYTHON
15.0
# Copyright 2018-19 Tecnativa S.L. - David Vidal # Copyright 2022 Moduon Team SL # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Portal Accounting Personal Data Only", "version": "15.0.1.0.0", "category": "Accounting/Accounting", "author": "Moduon, Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-invoicing", "license": "AGPL-3", "depends": ["account"], "data": ["security/security.xml"], "installable": True, "post_init_hook": "post_init_hook", "uninstall_hook": "uninstall_hook", }
37.5625
601
2,523
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.tests.common import tagged from odoo.addons.account.tests.common import TestAccountReconciliationCommon @tagged("post_install", "-at_install") class TestPartnerAccess(TestAccountReconciliationCommon): @classmethod def setUpClass(cls): super().setUpClass() cls.group_portal = cls.env.ref("base.group_portal") cls.user_a = cls._create_user(cls, "A") cls.user_b = cls._create_user(cls, "B") cls.user_c = cls._create_user(cls, "C") cls.partner_a = cls._create_partner(cls, cls.user_a) cls.partner_b = cls._create_partner(cls, cls.user_b) cls.partner_c = cls._create_partner(cls, cls.user_c) def _create_user(self, letter): return self.env["res.users"].create( { "name": "User %s" % letter, "login": "user_%s" % letter, "groups_id": [(6, 0, [self.group_portal.id])], } ) def _create_partner(self, user): return self.env["res.partner"].create( { "name": user.name, "user_ids": [(6, 0, [user.id])], } ) def test_access_invoice(self): invoice_a = self.create_invoice_partner(partner_id=self.partner_a.id) invoice_b = self.create_invoice_partner(partner_id=self.partner_b.id) invoice_c = self.create_invoice_partner(partner_id=self.partner_c.id) found_a = self.env["account.move"].with_user(self.user_a).search([]) self.assertTrue(invoice_a in found_a) self.assertTrue(invoice_b not in found_a) self.assertTrue(invoice_c not in found_a) found_b = self.env["account.move"].with_user(self.user_b).search([]) self.assertTrue(invoice_a not in found_b) self.assertTrue(invoice_b in found_b) self.assertTrue(invoice_c not in found_b) found_c = self.env["account.move"].with_user(self.user_c).search([]) self.assertTrue(invoice_a not in found_c) self.assertTrue(invoice_b not in found_c) self.assertTrue(invoice_c in found_c) def test_access_invoice_followers(self): invoice_a = self.create_invoice_partner(partner_id=self.partner_a.id) invoice_a.message_subscribe(partner_ids=self.partner_b.ids) invoices_b = self.env["account.move"].with_user(self.user_b).search([]) self.assertTrue(invoice_a in invoices_b)
42.016667
2,521
632
py
PYTHON
15.0
# Copyright 2016 Tecnativa - Carlos Dauden # Copyright 2017 Tecnativa - Pedro M. Baeza # Copyright 2020 Tecnativa - Manuel Calero # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Timesheet details invoice", "summary": "Add timesheet details in invoice line", "version": "15.0.1.0.2", "category": "Sales Management", "license": "AGPL-3", "author": "Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-invoicing", "depends": ["sale_timesheet"], "data": ["views/sale_view.xml", "views/res_config_view.xml"], "installable": True, }
37.176471
632
9,699
py
PYTHON
15.0
# Copyright 2016 Tecnativa - Carlos Dauden # Copyright 2017 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from datetime import datetime from odoo.tests import common from odoo.tools.float_utils import float_compare class TestSaleTimesheetDescription(common.TransactionCase): @classmethod def setUpClass(cls): super(TestSaleTimesheetDescription, cls).setUpClass() # Make sure user is in English cls.env.user.lang = "en_US" cls.partner = cls.env["res.partner"].create({"name": "Test partner"}) cls.analytic_account = cls.env["account.analytic.account"].create( {"name": "Test analytic account"} ) cls.project = cls.env["project.project"].create( { "name": "Test project", "analytic_account_id": cls.analytic_account.id, "allow_timesheets": True, "allow_billable": True, } ) cls.product_uom_hour = cls.env.ref("uom.product_uom_hour") cls.product_uom_day = cls.env.ref("uom.product_uom_day") cls.product = cls.env["product.product"].create( { "name": "Test product", "type": "service", "uom_id": cls.product_uom_hour.id, "uom_po_id": cls.product_uom_hour.id, "service_type": "timesheet", "invoice_policy": "delivery", # Task created on cls.project when the cls.product is ordered "service_tracking": "task_global_project", "project_id": cls.project.id, } ) cls.sale_order = cls.env["sale.order"].create( { "partner_id": cls.partner.id, "partner_invoice_id": cls.partner.id, "partner_shipping_id": cls.partner.id, "pricelist_id": cls.partner.property_product_pricelist.id, "analytic_account_id": cls.analytic_account.id, } ) cls.sale_order.timesheet_invoice_split = False cls.so_line = cls.env["sale.order.line"].create( { "name": cls.product.name, "product_id": cls.product.id, "product_uom_qty": 10.5, "product_uom": cls.product_uom_hour.id, "price_unit": cls.product.list_price, "order_id": cls.sale_order.id, }, ) cls.so_line.product_id_change() # confirm SO, task is created cls.sale_order.action_confirm() cls.task = cls.env["project.task"].search( [("sale_line_id", "=", cls.so_line.id)] ) # Add cls.timesheet to this task cls.timesheet = cls.env["account.analytic.line"].create( { "project_id": cls.project.id, "task_id": cls.task.id, "date": datetime.strptime("2017-08-04", "%Y-%m-%d"), "name": "Test description 1234567890", "product_uom_id": cls.product_uom_hour.id, "unit_amount": 10.5, "user_id": cls.env.user.id, } ) def _test_sale_time_description(self, desc_option, expected): self.sale_order.timesheet_invoice_description = desc_option invoice = self.sale_order.with_context( test_timesheet_description=True )._create_invoices() self.assertEqual(invoice.line_ids[0].name, expected) # Add a new timesheet to the same invoiced sale.order.line self.timesheet2 = self.timesheet.copy() invoice2 = self.sale_order.with_context( test_timesheet_description=True )._create_invoices() self.assertEqual(invoice2.line_ids[0].name, expected) def test_sale_timesheet_description_000(self): self._test_sale_time_description("000", "Test product") def test_sale_timesheet_description_111(self): self._test_sale_time_description( "111", "Test product\n2017-08-04 - 10.5 Hours - Test description 1234567890", ) def test_sale_timesheet_description_101(self): self._test_sale_time_description( "101", "Test product\n2017-08-04 - Test description 1234567890" ) def test_sale_timesheet_description_001(self): self._test_sale_time_description( "001", "Test product\nTest description 1234567890" ) def test_sale_timesheet_description_011(self): self._test_sale_time_description( "011", "Test product\n10.5 Hours - Test description 1234567890" ) def test_settings(self): settings = self.env["res.config.settings"].create({}) settings.default_timesheet_invoice_description = "101" settings.execute() sale_order = self.env["sale.order"].create( { "partner_id": self.partner.id, "partner_invoice_id": self.partner.id, "partner_shipping_id": self.partner.id, "pricelist_id": self.partner.property_product_pricelist.id, } ) self.assertEqual(sale_order.timesheet_invoice_description, "101") def test_two_timesheets_different_dates(self): self.sale_order.timesheet_invoice_description = "111" expected = "Test product\n2017-08-04 - 10.5 Hours - Test description 1234567890" # Add a new timesheet to the same invoiced sale.order.line (i.e. with the same # task and projet) but with different date self.env["account.analytic.line"].create( { "project_id": self.project.id, "task_id": self.task.id, "date": datetime.strptime("2018-08-04", "%Y-%m-%d"), "name": "Timesheet 2", "product_uom_id": self.product_uom_hour.id, "unit_amount": 10.5, "user_id": self.env.user.id, } ) invoice = self.sale_order.with_context( test_timesheet_description=True )._create_invoices(start_date="2017-01-01", end_date="2018-01-01") self.assertEqual(invoice.invoice_line_ids[0].name, expected) def test_two_timesheets_same_date_join(self): self.sale_order.timesheet_invoice_description = "111" description = "2017-08-04 - 10.5 Hours - Test description 1234567890" expected = "Test product" + 2 * ("\n" + description) # Add a new timesheet with the same date to the same invoiced sale.order.line self.timesheet2 = self.timesheet.copy() invoice = self.sale_order.with_context( test_timesheet_description=True )._create_invoices(start_date="2017-01-01", end_date="2018-01-01") self.assertEqual(invoice.invoice_line_ids[0].name, expected) def test_three_timesheets_same_date_split(self): self.sale_order.timesheet_invoice_split = True self.sale_order.timesheet_invoice_description = "001" # Set a different UoM on SO line/Invoice line from Timesheets UoM self.so_line.write({"product_uom": self.product_uom_day.id}) # Add a new timesheets with the same date to the same invoiced sale.order.line self.timesheet.write({"name": "Description 1"}) self.timesheet2 = self.timesheet.copy( { "name": "Description 2", "date": datetime.strptime("2017-08-05", "%Y-%m-%d"), } ) self.timesheet3 = self.timesheet.copy( { "name": "Description 3", "date": datetime.strptime("2017-08-06", "%Y-%m-%d"), } ) invoice = self.sale_order.with_context( test_timesheet_description=True )._create_invoices(start_date="2017-01-01", end_date="2018-01-01") self.assertEqual(len(invoice.invoice_line_ids), 4) # Initially this test was added in order to adapt to this # change in Odoo: # https://github.com/odoo/odoo/pull/115907 # self.assertEqual( # sum(self.sale_order.mapped("order_line.qty_delivered")), 3.93) # However, the change was reverted, because unknown reason: # https://github.com/odoo/odoo/pull/122431 # Decide to comment the test just for the record. # First line is a section with product's name aml_ids = invoice.invoice_line_ids.sorted(key=lambda aml: aml.sequence) first_aml = aml_ids[0] self.assertEqual(first_aml.display_type, "line_section") self.assertEqual(first_aml.name, "Test product") # 2 first aml refer to timesheet and timesheet2 self.assertEqual(aml_ids[1].name, "Description 1") self.assertEqual(aml_ids[1].quantity, 1.32) self.assertEqual(aml_ids[2].name, "Description 2") self.assertEqual(aml_ids[2].quantity, 1.32) # Last aml quantity is calculated as the rest to equal the original aml quantity self.assertEqual(aml_ids[-1].name, "Description 3") # Reason of change above self.assertEqual(aml_ids[-1].quantity, 1.3) # Invoice lines total must equal the expected order line's delivered and # invoiced quantities aml_sum = sum(aml.quantity for aml in aml_ids[1:]) pr = self.so_line.product_uom.rounding self.assertTrue( float_compare(aml_sum, self.so_line.qty_delivered, precision_rounding=pr) == 0 ) self.assertTrue( float_compare(aml_sum, self.so_line.qty_invoiced, precision_rounding=pr) == 0 )
40.58159
9,699
2,215
py
PYTHON
15.0
# Copyright 2020 Akretion - Clément Mombereau # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models from odoo.osv import expression class AccountMove(models.Model): _inherit = "account.move" def _link_timesheets_to_invoice_line(self, start_date=None, end_date=None): """Search timesheets from given period and link each timesheet to its related invoice line. Mimic '_link_timesheets_to_invoice' in native module 'sale_timesheet' """ move_ids = self.filtered( lambda i: i.move_type == "out_invoice" and i.state == "draft" ) for aml in move_ids.invoice_line_ids: sale_line_delivery = aml._get_sale_line_delivery() if sale_line_delivery: domain = [ ("so_line", "in", sale_line_delivery.ids), ("project_id", "!=", False), ("timesheet_invoice_id", "=", aml.move_id.id), ] if start_date: domain = expression.AND([domain, [("date", ">=", start_date)]]) if end_date: domain = expression.AND([domain, [("date", "<=", end_date)]]) timesheets = self.env["account.analytic.line"].sudo().search(domain) timesheets.write({"timesheet_invoice_line_id": aml.id}) def _check_balanced(self): if self.env.context.get("split_aml_by_timesheets"): return return super()._check_balanced() class AccountMoveLine(models.Model): _inherit = "account.move.line" timesheet_ids = fields.One2many( "account.analytic.line", "timesheet_invoice_line_id", string="Timesheets", readonly=True, copy=False, ) # Filled by sale order line's _prepare_invoice_line() timesheet_invoice_description = fields.Char() timesheet_invoice_split = fields.Boolean("Split Order lines by timesheets") def _get_sale_line_delivery(self): return self.sale_line_ids.filtered( lambda sol: sol.product_id.invoice_policy == "delivery" and sol.product_id.service_type == "timesheet" )
35.142857
2,214
539
py
PYTHON
15.0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" default_timesheet_invoice_description = fields.Selection( selection="_get_timesheet_invoice_description", string="Timesheet Invoice Description", default_model="sale.order", ) @api.model def _get_timesheet_invoice_description(self): return self.env["sale.order"]._get_timesheet_invoice_description()
31.705882
539
441
py
PYTHON
15.0
# Copyright 2020 Akretion - Clément Mombereau # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class AccountAnalyticLine(models.Model): _inherit = "account.analytic.line" timesheet_invoice_line_id = fields.Many2one( "account.move.line", string="Invoice Line", readonly=True, copy=False, help="Invoice line created from the timesheet", )
27.5
440
6,111
py
PYTHON
15.0
# Copyright 2016 Carlos Dauden <carlos.dauden@tecnativa.com> # Copyright 2020 Tecnativa - Manuel Calero # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.tools import config class SaleOrder(models.Model): _inherit = "sale.order" timesheet_invoice_description = fields.Selection( "_get_timesheet_invoice_description", default="000" ) timesheet_invoice_split = fields.Boolean("Split Order lines by timesheets") @api.model def _get_timesheet_invoice_description(self): return [ ("000", _("None")), ("111", _("Date - Time spent - Description")), ("101", _("Date - Description")), ("001", _("Description")), ("011", _("Time spent - Description")), ] def _get_timesheet_details(self, timesheet, desc_rule): details = [] if desc_rule[0] == "1": details.append(fields.Date.to_string(timesheet.date)) if desc_rule[1] == "1": details.append( "{} {}".format(timesheet.unit_amount, timesheet.product_uom_id.name) ) if desc_rule[2] == "1": details.append(timesheet.name) return details def _get_timesheet_description_list(self, timesheet_ids, desc_rule): """Returns a list of timesheets description""" desc_list = [] for timesheet_id in timesheet_ids.sorted(lambda t: t.date): details = self._get_timesheet_details(timesheet_id, desc_rule) desc_list.append(" - ".join(map(lambda x: str(x) or "", details))) return desc_list def _split_aml_by_timesheets(self, aml, ts_ids, desc_list): """Split an invoice line in as many lines as there is related timesheets, taking care to convert timesheets quantities in the invoice line's UoM""" aml_total = aml.quantity aml_uom_id = aml.product_uom_id aml_seq = aml.sequence aml_sum = 0 ts_ids = ts_ids.sorted(lambda t: t.date) # Add a line section on top before the original aml self.env["account.move.line"].create( { "name": aml.name, "sequence": aml_seq - 1, "display_type": "line_section", "move_id": aml.move_id.id, } ) # Override the original aml values with first timesheet init_ts_uom_id = ts_ids[0].product_uom_id init_ts_qty = ts_ids[0].unit_amount init_qty = init_ts_uom_id._compute_quantity(init_ts_qty, aml_uom_id) aml_sum += init_qty aml.with_context(split_aml_by_timesheets=True).write( { "name": desc_list[0], "quantity": init_qty, } ) # Create one invoice line for each timesheet except the last one for index, ts_id in enumerate(ts_ids[1:-1]): ts_uom_id = ts_id.product_uom_id ts_qty = ts_id.unit_amount qty = ts_uom_id._compute_quantity(ts_qty, aml_uom_id) new_aml = aml.with_context(split_aml_by_timesheets=True).copy() new_aml.with_context(split_aml_by_timesheets=True).write( { "name": desc_list[index + 1], "sequence": aml_seq + index + 1, "quantity": qty, "sale_line_ids": aml.sale_line_ids.ids, } ) aml_sum += qty # Last new invoice line get the rest if ts_ids[-1] != ts_ids[0]: last_qty = aml_total - aml_sum last_aml = aml.with_context(split_aml_by_timesheets=True).copy() last_aml.write( { "name": desc_list[-1], "sequence": aml_seq + len(ts_ids) - 1, "quantity": last_qty, "sale_line_ids": aml.sale_line_ids.ids, } ) def _create_invoices( self, grouped=False, final=False, start_date=None, end_date=None ): """Override the native _create_invoice method in order to : 1. link the new invoices lines with their related timesheets 2. change their names consequently """ # Additional condition to avoid beaking third party tests expecting to create # invoices lines the standard way is_third_party_test = config["test_enable"] and not self.env.context.get( "test_timesheet_description" ) moves = super()._create_invoices(grouped=grouped, final=final) moves._link_timesheets_to_invoice_line(start_date=start_date, end_date=end_date) for move_id in moves: for aml in move_id.invoice_line_ids: ts_ids = aml.timesheet_ids desc_rule = aml.timesheet_invoice_description inv_split = aml.timesheet_invoice_split desc_list = self._get_timesheet_description_list(ts_ids, desc_rule) if ( desc_list and desc_rule and desc_rule != "000" and not is_third_party_test ): if inv_split: self._split_aml_by_timesheets(aml, ts_ids, desc_list) else: desc = "\n".join(map(lambda x: str(x) or "", desc_list)) new_name = aml.name + "\n" + desc aml.write({"name": new_name}) return moves class SaleOrderLine(models.Model): _inherit = "sale.order.line" def _prepare_invoice_line(self, **optional_values): res = super(SaleOrderLine, self)._prepare_invoice_line(**optional_values) desc_rule = self.order_id.timesheet_invoice_description inv_split = self.order_id.timesheet_invoice_split res.update( { "timesheet_invoice_description": desc_rule, "timesheet_invoice_split": inv_split, } ) return res
38.677215
6,111
592
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV (https://acsone.eu) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) { "name": "Account invoice tax note", "version": "15.0.1.0.1", "author": "ACSONE SA/NV,Odoo Community Association (OCA)", "development_status": "Production/Stable", "summary": "Print tax notes on customer invoices", "website": "https://github.com/OCA/account-invoicing", "category": "Localization / Accounting", "license": "AGPL-3", "depends": ["account"], "data": ["reports/report_invoice_document.xml"], "installable": True, }
39.466667
592
6,715
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from uuid import uuid4 from odoo import fields from odoo.tests.common import TransactionCase class TestAccountInvoice(TransactionCase): """ Tests for account.invoice """ def setUp(self): super(TestAccountInvoice, self).setUp() tax_group_obj = self.env["account.tax.group"] tax_obj = self.env["account.tax"] invoice_obj = self.env["account.move"] self.product1 = self.env.ref("product.product_product_7") self.product2 = self.env.ref("product.product_product_8") account_type = self.env.ref("account.data_account_type_revenue") customer = self.env.ref("base.res_partner_2") self.tax_group1 = tax_group_obj.create( {"name": "Secret Taxes", "sequence": 20, "report_note": str(uuid4())} ) self.tax_group2 = tax_group_obj.create( {"name": "Public taxes", "sequence": 30, "report_note": str(uuid4())} ) self.tax1 = tax_obj.create( { "name": "TVA 1", "type_tax_use": "sale", "amount_type": "percent", "amount": "35", "description": "Top secret", "tax_group_id": self.tax_group1.id, } ) self.tax2 = tax_obj.create( { "name": "TVA 2", "type_tax_use": "sale", "amount_type": "percent", "amount": "22", "description": "Hello", "tax_group_id": self.tax_group2.id, } ) taxes = self.tax1 | self.tax2 self.product1.write({"taxes_id": [(6, False, self.tax1.ids)]}) self.product2.write({"taxes_id": [(6, False, self.tax2.ids)]}) account = self.env["account.account"].search( [("user_type_id", "=", account_type.id)], limit=1 ) account.write({"tax_ids": [(4, self.tax1.id, False), (4, self.tax2.id, False)]}) journal = self.env["account.journal"].create( {"name": "Sale journal - Test", "code": "SJ-TT", "type": "sale"} ) invoice_lines1 = [ ( 0, False, { "name": self.product1.display_name, "product_id": self.product1.id, "quantity": 3, "product_uom_id": self.product1.uom_id.id, "price_unit": self.product1.standard_price, "account_id": account.id, "tax_ids": self.tax1.ids, }, ) ] # Invoice 1 must have 1 tax group only self.invoice1 = invoice_obj.create( { "partner_id": customer.id, "move_type": "out_invoice", "invoice_date": fields.Date.today(), "invoice_line_ids": invoice_lines1, "invoice_origin": "Unit test", "journal_id": journal.id, } ) invoice_lines2 = [ ( 0, False, { "name": self.product1.display_name, "product_id": self.product1.id, "quantity": 3, "product_uom_id": self.product1.uom_id.id, "price_unit": self.product1.standard_price, "account_id": account.id, "tax_ids": self.tax1.ids, }, ), ( 0, False, { "name": self.product1.display_name, "product_id": self.product2.id, "quantity": 3, "product_uom_id": self.product2.uom_id.id, "price_unit": self.product2.standard_price, "account_id": account.id, "tax_ids": taxes.ids, }, ), ] # Invoice 2 must have more than 1 tax group self.invoice2 = invoice_obj.create( { "partner_id": customer.id, "move_type": "out_invoice", "invoice_date": fields.Date.today(), "invoice_line_ids": invoice_lines2, "invoice_origin": "Unit test", "journal_id": journal.id, } ) def test_get_account_tax_groups_with_notes1(self): """ Test the function _get_account_tax_groups_with_notes() This function should return every account.tax.group used on the invoice (by invoice_line_ids.tax_ids) For this test, we use an invoice with only 1 tax group :return: bool """ tax_group = self.invoice1.mapped("invoice_line_ids.tax_ids.tax_group_id") # We need only 1 tax group for this test self.assertEqual(len(tax_group), 1) tax_group_result = self.invoice1._get_account_tax_groups_with_notes() self.assertEqual(set(tax_group.ids), set(tax_group_result.ids)) return True def test_get_account_tax_groups_with_notes2(self): """ Test the function _get_account_tax_groups_with_notes() This function should return every account.tax.group used on the invoice (by invoice_line_ids.tax_ids) For this test, we use an invoice with more than 1 tax group :return: bool """ tax_group = self.invoice2.mapped("invoice_line_ids.tax_ids.tax_group_id") # We need more than 1 tax group for this test self.assertGreater(len(tax_group), 1) tax_group_result = self.invoice2._get_account_tax_groups_with_notes() self.assertEqual(set(tax_group.ids), set(tax_group_result.ids)) return True def test_get_account_tax_groups_with_notes3(self): """ Test the function _get_account_tax_groups_with_notes() This function should return every account.tax.group used on the invoice (by invoice_line_ids.tax_ids) For this test, we use the function on a multi invoice without any taxes. So the result should be empty :return: bool """ self.invoice1.invoice_line_ids.write({"tax_ids": [(6, False, [])]}) tax_group = self.invoice1.mapped("invoice_line_ids.tax_ids.tax_group_id") # We need 0 tax group for this test self.assertFalse(bool(tax_group)) tax_group_result = self.invoice1._get_account_tax_groups_with_notes() self.assertFalse(bool(tax_group_result)) return True
39.5
6,715
486
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV (https://acsone.eu) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import models class AccountMove(models.Model): _inherit = "account.move" def _get_account_tax_groups_with_notes(self): self.ensure_one() for line in self: tax_groups = line.mapped("invoice_line_ids.tax_ids.tax_group_id") tax_groups = tax_groups.filtered(lambda g: g.report_note) return tax_groups
32.4
486
363
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV (https://acsone.eu) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import fields, models class AccountTaxGroup(models.Model): _inherit = "account.tax.group" report_note = fields.Text( translate=True, help="Note to insert on Invoice Report if the tax group is used.", )
27.923077
363
1,268
py
PYTHON
15.0
# Copyright 2016 Antonio Espinosa <antonio.espinosa@tecnativa.com> # Copyright 2017-2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import SUPERUSER_ID, api def match_origin_lines(refund): """Try to match lines by product or by description.""" invoice = refund.reversed_entry_id invoice_lines = invoice.invoice_line_ids for refund_line in refund.invoice_line_ids: for invoice_line in invoice_lines: match = ( refund_line.product_id and refund_line.product_id == invoice_line.product_id or refund_line.name == invoice_line.name ) if match: invoice_lines -= invoice_line refund_line.origin_line_id = invoice_line.id break if not invoice_lines: break def post_init_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) # Linking all refund invoices to its original invoices refunds = env["account.move"].search( [ ("move_type", "in", ("out_refund", "in_refund")), ("reversed_entry_id", "!=", False), ] ) for refund in refunds: match_origin_lines(refund)
34.27027
1,268
788
py
PYTHON
15.0
# Copyright 2004-2011 Pexego Sistemas Informáticos. (http://pexego.es) # Copyright 2016 Antonio Espinosa <antonio.espinosa@tecnativa.com> # Copyright 2014-2017 Pedro M. Baeza <pedro.baeza@tecnativa.com> # Copyright 2021 Tecnativa - João Marques # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Show links between refunds and their originator invoices.", "version": "15.0.1.0.1", "development_status": "Mature", "category": "Accounting & Finance", "website": "https://github.com/OCA/account-invoicing", "author": "Pexego, Tecnativa, Odoo Community Association (OCA)", "installable": True, "post_init_hook": "post_init_hook", "depends": ["account"], "license": "AGPL-3", "data": ["views/account_invoice_view.xml"], }
41.368421
786
4,709
py
PYTHON
15.0
# Copyright 2016 Antonio Espinosa <antonio.espinosa@tecnativa.com> # Copyright 2014-2017 Pedro M. Baeza <pedro.baeza@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase from .. import post_init_hook class TestInvoiceRefundLinkBase(TransactionCase): refund_method = "refund" @classmethod def setUpClass(cls): super().setUpClass() cls.partner = cls.env["res.partner"].create({"name": "Test partner"}) default_line_account = cls.env["account.account"].create( { "name": "TESTACC", "code": "TESTACC", "user_type_id": cls.env.ref( "account.data_account_type_other_income" ).id, "deprecated": False, "company_id": cls.env.user.company_id.id, } ) cls.journal = cls.env["account.journal"].create( { "name": "Journal 1", "code": "J1", "type": "sale", "company_id": cls.env.user.company_id.id, } ) cls.invoice_lines = [ ( 0, False, { "name": "Test description #1", "account_id": default_line_account.id, "quantity": 1.0, "price_unit": 100.0, }, ), ( 0, False, { "name": "Test description #2", "account_id": default_line_account.id, "quantity": 2.0, "price_unit": 25.0, }, ), ] cls.invoice = cls.env["account.move"].create( { "partner_id": cls.partner.id, "move_type": "out_invoice", "invoice_line_ids": cls.invoice_lines, } ) cls.invoice.action_post() cls.refund_reason = "The refund reason" cls.env["account.move.reversal"].with_context( active_ids=cls.invoice.ids, active_model="account.move" ).create( { "refund_method": cls.refund_method, "reason": cls.refund_reason, "journal_id": cls.journal.id, } ).reverse_moves() def _test_refund_link(self): self.assertTrue(self.invoice.refund_invoice_ids) refund = self.invoice.refund_invoice_ids[0] ref = "Reversal of: {}, {}".format(self.invoice.name, self.refund_reason) self.assertEqual(refund.ref, ref) self.assertEqual(len(self.invoice.invoice_line_ids), len(self.invoice_lines)) self.assertEqual(len(refund.invoice_line_ids), len(self.invoice_lines)) self.assertTrue(refund.invoice_line_ids[0].origin_line_id) self.assertEqual( self.invoice.invoice_line_ids[0], refund.invoice_line_ids[0].origin_line_id ) self.assertTrue(refund.invoice_line_ids[1].origin_line_id) self.assertEqual( self.invoice.invoice_line_ids[1], refund.invoice_line_ids[1].origin_line_id ) class TestInvoiceRefundLink(TestInvoiceRefundLinkBase): @classmethod def setUpClass(cls): super(TestInvoiceRefundLink, cls).setUpClass() def test_post_init_hook(self): self.assertTrue(self.invoice.refund_invoice_ids) refund = self.invoice.refund_invoice_ids[0] refund.invoice_line_ids.write({"origin_line_id": False}) self.assertFalse(refund.mapped("invoice_line_ids.origin_line_id")) post_init_hook(self.env.cr, None) self.refund_reason = "The refund reason" self._test_refund_link() def test_refund_link(self): self._test_refund_link() def test_invoice_copy(self): refund = self.invoice.refund_invoice_ids[0] self.invoice.copy() self.assertEqual( refund.invoice_line_ids.mapped("origin_line_id"), self.invoice.invoice_line_ids, ) def test_refund_copy(self): refund = self.invoice.refund_invoice_ids[0] refund.copy() self.assertEqual( self.invoice.invoice_line_ids.mapped("refund_line_ids"), refund.invoice_line_ids, ) class TestInvoiceRefundCancelLink(TestInvoiceRefundLinkBase): refund_method = "cancel" def test_refund_link(self): self._test_refund_link() class TestInvoiceRefundModifyLink(TestInvoiceRefundLinkBase): refund_method = "modify" def test_refund_link(self): self._test_refund_link()
33.877698
4,709
1,222
py
PYTHON
15.0
# Copyright 2004-2011 Pexego Sistemas Informáticos. (http://pexego.es) # Copyright 2016 Antonio Espinosa <antonio.espinosa@tecnativa.com> # Copyright 2014-2022 Pedro M. Baeza <pedro.baeza@tecnativa.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" refund_invoice_ids = fields.One2many( "account.move", "reversed_entry_id", string="Refund Invoices", readonly=True ) @api.model def _reverse_move_vals(self, default_values, cancel=True): move_vals = super()._reverse_move_vals(default_values, cancel) if self.env.context.get("link_origin_line", False) and move_vals[ "move_type" ] in ( "out_refund", "in_refund", ): refund_lines_vals = [ x[2] for x in move_vals.get("line_ids", []) if not x[2].get("exclude_from_invoice_tab", True) ] for i, line in enumerate(self.invoice_line_ids): if i < len(refund_lines_vals): refund_lines_vals[i]["origin_line_id"] = line.id return move_vals
37
1,221
896
py
PYTHON
15.0
# Copyright 2004-2011 Pexego Sistemas Informáticos. (http://pexego.es) # Copyright 2016 Antonio Espinosa <antonio.espinosa@tecnativa.com> # Copyright 2014-2018 Pedro M. Baeza <pedro.baeza@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class AccountInvoiceLine(models.Model): _inherit = "account.move.line" origin_line_id = fields.Many2one( comodel_name="account.move.line", string="Original invoice line", help="Original invoice line to which this refund invoice line " "is referred to", copy=False, index=True, ) refund_line_ids = fields.One2many( comodel_name="account.move.line", inverse_name="origin_line_id", string="Refund invoice lines", help="Refund invoice lines created from this invoice line", copy=False, )
34.423077
895
526
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models class AccountMoveReversal(models.TransientModel): _inherit = "account.move.reversal" def reverse_moves(self): """ Only link invoice lines with theirs original lines when the reversal move has been done from reversal wizard. """ return super( AccountMoveReversal, self.with_context(link_origin_line=True) ).reverse_moves()
30.941176
526
799
py
PYTHON
15.0
# Copyright 2011-2020 Julius Network Solutions SARL <contact@julius.fr> # Copyright 2014-2020 Akretion France (http://www.akretion.com/) # @author: Alexis de Lattre <alexis.delattre@akretion.com> # Copyright 2018-2020 Roel Adriaans <roel@road-support.nl> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Invoice Fiscal Position Update", "version": "15.0.1.0.2", "category": "Accounting", "license": "AGPL-3", "summary": "Changing the fiscal position of an invoice will auto-update " "invoice lines", "website": "https://github.com/OCA/account-invoicing", "author": "Julius Network Solutions," "Akretion," "Odoo Community Association (OCA)", "maintainers": ["alexis-via"], "depends": ["account"], "installable": True, }
36.318182
799
6,888
py
PYTHON
15.0
# Copyright 2014 ToDay Akretion (http://www.akretion.com) # @author Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import time from odoo.tests import tagged from odoo.addons.account.tests.common import AccountTestInvoicingCommon @tagged("post_install", "-at_install") class TestProductIdChange(AccountTestInvoicingCommon): """Test that when an included tax is mapped by a fiscal position, when position fiscal change taxes and account wil be update on invoice lines. """ def setUp(self): super(TestProductIdChange, self).setUp() self.invoice_model = self.env["account.move"] self.fiscal_position_model = self.env["account.fiscal.position"] self.fiscal_position_tax_model = self.env["account.fiscal.position.tax"] self.fiscal_position_account_model = self.env["account.fiscal.position.account"] self.tax_model = self.env["account.tax"] self.account_model = self.env["account.account"] self.pricelist_model = self.env["product.pricelist"] self.res_partner_model = self.env["res.partner"] self.product_tmpl_model = self.env["product.template"] self.product_model = self.env["product.product"] self.invoice_line_model = self.env["account.move.line"] self.account_user_type = self.env.ref("account.data_account_type_revenue") self.account_receivable = self.env["account.account"].search( [ ( "user_type_id", "=", self.env.ref("account.data_account_type_receivable").id, ) ], limit=1, ) self.account_revenue = self.env["account.account"].search( [("user_type_id", "=", self.account_user_type.id)], limit=1 ) def test_fiscal_position_id_change(self): partner = self.res_partner_model.create(dict(name="George")) account_export_id = self.account_model.sudo().create( { "code": "710000-account_invoice_fiscal_position_update", "name": "customer export account", "user_type_id": self.account_user_type.id, "reconcile": True, } ) tax_sale = self.tax_model.create( {"name": "Sale tax", "type_tax_use": "sale", "amount": "20.00"} ) tax_export_sale = self.tax_model.create( {"name": "Export tax", "type_tax_use": "sale", "amount": "0.00"} ) product_tmpl = self.product_tmpl_model.create( { "name": "Car", "list_price": "15000", "taxes_id": [(6, 0, [tax_sale.id])], "property_account_income_id": self.account_revenue.id, } ) product = product_tmpl.product_variant_id product.standard_price = 12000 fp = self.fiscal_position_model.create( {"name": "fiscal position export", "sequence": 1} ) fp2 = self.fiscal_position_model.create( {"name": "fiscal position import", "sequence": 1} ) partner.write({"property_account_position_id": fp.id}) fp_tax_sale = self.fiscal_position_tax_model.create( { "position_id": fp.id, "tax_src_id": tax_sale.id, "tax_dest_id": tax_export_sale.id, } ) fp_account = self.fiscal_position_account_model.create( { "position_id": fp.id, "account_src_id": self.account_revenue.id, "account_dest_id": account_export_id.id, } ) out_invoice = self.invoice_model.create( { "partner_id": partner.id, "ref": "invoice to client", "move_type": "out_invoice", "invoice_date": time.strftime("%Y") + "-04-01", } ) out_line = self.invoice_line_model.with_context( check_move_validity=False ).create( { "product_id": product.id, "price_unit": 15000, "quantity": 1, "move_id": out_invoice.id, "name": "Car", "account_id": self.account_revenue.id, } ) out_line._onchange_product_id() self.assertEqual( out_line.tax_ids[0], tax_sale, "The sale tax off invoice line must be the same of product", ) out_invoice.fiscal_position_id = fp2 # change the partner with other FP out_invoice.with_context(check_move_validity=False)._onchange_partner_id() self.assertEqual( out_line.tax_ids[0], fp_tax_sale.tax_dest_id, "The sale tax of invoice line must be changed by fiscal position", ) self.assertEqual( out_line.account_id, fp_account.account_dest_id, "The account revenue of invoice line must be changed by fiscal position", ) # Test warning due to lines without product self.invoice_line_model.with_context(check_move_validity=False).create( { "name": "Line without product", "price_unit": 100, "quantity": 1, "move_id": out_invoice.id, "account_id": self.account_revenue.id, } ) onchange_result = out_invoice.with_context( check_move_validity=False )._onchange_fiscal_position_id_account_invoice_fiscal_position_invoice() self.assertTrue(type(onchange_result) == dict) self.assertEqual(list(onchange_result.keys()), ["warning"]) # for all lines without product out_invoice_without_prd = self.invoice_model.create( { "partner_id": partner.id, "ref": "invoice to client", "move_type": "out_invoice", "invoice_date": time.strftime("%Y") + "-04-01", } ) # Test warning due to lines without product self.invoice_line_model.with_context(check_move_validity=False).create( { "name": "Line without product", "price_unit": 100, "quantity": 1, "move_id": out_invoice_without_prd.id, "account_id": self.account_revenue.id, } ) onchange_result = out_invoice_without_prd.with_context( check_move_validity=False )._onchange_fiscal_position_id_account_invoice_fiscal_position_invoice() self.assertTrue(type(onchange_result) == dict) self.assertEqual(list(onchange_result.keys()), ["warning"])
38.696629
6,888
2,531
py
PYTHON
15.0
# Copyright 2011-2020 Julius Network Solutions SARL <contact@julius.fr> # Copyright 2014-2020 Akretion France (http://www.akretion.com) # @author Mathieu Vatel <mathieu _at_ julius.fr> # @author Alexis de Lattre <alexis.delattre@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, models class AccountMove(models.Model): _inherit = "account.move" @api.onchange("partner_id") def _onchange_partner_id(self): fiscal_position = self.fiscal_position_id res = super()._onchange_partner_id() if fiscal_position != self.fiscal_position_id: self._onchange_fiscal_position_id_account_invoice_fiscal_position_invoice() return res @api.onchange("fiscal_position_id") def _onchange_fiscal_position_id_account_invoice_fiscal_position_invoice(self): """Updates taxes and accounts on all invoice lines""" res = {} lines_without_product = [] invoice_lines = self.invoice_line_ids.filtered(lambda l: not l.display_type) for line in invoice_lines: if line.product_id: line.account_id = line._get_computed_account() taxes = line._get_computed_taxes() if taxes and line.move_id.fiscal_position_id: taxes = line.move_id.fiscal_position_id.map_tax(taxes) line.tax_ids = taxes line._onchange_price_subtotal() line._onchange_mark_recompute_taxes() else: lines_without_product.append(line.name) self._onchange_invoice_line_ids() if lines_without_product: res["warning"] = {"title": _("Warning")} if len(lines_without_product) == len(invoice_lines): res["warning"]["message"] = _( "The invoice lines were not updated to the new " "Fiscal Position because they don't have products. " "You should update the Account and the Taxes of each " "invoice line manually." ) else: res["warning"]["message"] = _( "The following invoice lines were not updated " "to the new Fiscal Position because they don't have a " "Product:\n - %s\nYou should update the Account and the " "Taxes of these invoice lines manually." ) % ("\n- ".join(lines_without_product)) return res
46.018182
2,531
678
py
PYTHON
15.0
# Copyright 2023 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Product From Account Move Line Link", "summary": """ Adds a button on product forms to access Journal Items""", "version": "15.0.1.0.0", "author": "ForgeFlow, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-invoicing", "category": "Account", "license": "AGPL-3", "depends": ["account"], "data": [ "views/account_move_line_views.xml", "views/product_product_views.xml", "views/product_template_views.xml", ], "installable": True, }
33.9
678
702
py
PYTHON
15.0
# Copyright 2023 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class ProductTemplate(models.Model): _inherit = "product.template" account_move_lines_count = fields.Float( compute="_compute_account_move_lines_count", string="Invoiced" ) @api.depends("product_variant_ids.account_move_lines_count") def _compute_account_move_lines_count(self): for product in self: product.account_move_lines_count = sum( p.account_move_lines_count for p in product.with_context(active_test=False).product_variant_ids )
33.428571
702
1,049
py
PYTHON
15.0
# Copyright 2023 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ProductProduct(models.Model): _inherit = "product.product" account_move_lines_count = fields.Float( compute="_compute_account_move_lines_count", string="Invoiced" ) def _compute_account_move_lines_count(self): if not self.user_has_groups("account.group_account_invoice") or not self.ids: self.purchase_lines_count = 0.0 return domain = [ ("product_id", "in", self.ids), ("company_id", "in", self.env.companies.ids), ] account_move_line_data = self.env["account.move.line"].read_group( domain, ["product_id"], ["product_id"] ) mapped_data = { m["product_id"][0]: m["product_id_count"] for m in account_move_line_data } for product in self: product.account_move_lines_count = mapped_data.get(product.id, 0)
36.172414
1,049
744
py
PYTHON
15.0
# Copyright 2019-2020 Tecnativa - Pedro M. Baeza # Copyright 2020 Tecnativa - Manuel Calero # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Enqueue account invoice validation", "version": "15.0.1.0.0", "category": "Accounting", "license": "AGPL-3", "author": "Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-invoicing", "depends": ["account", "queue_job"], "data": [ "data/queue_job.xml", "views/queue_job_views.xml", "views/account_invoice_views.xml", "wizards/validate_account_move_view.xml", ], "installable": True, "development_status": "Production/Stable", "maintainers": ["pedrobaeza"], }
33.818182
744
2,412
py
PYTHON
15.0
# Copyright 2019 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import exceptions from odoo.tests import TransactionCase class TestAccountInvoiceValidationQueued(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.wizard_obj = cls.env["validate.account.move"] cls.queue_obj = cls.env["queue.job"] cls.partner = cls.env["res.partner"].create({"name": "Test partner"}) cls.account_type = cls.env["account.account.type"].create( {"name": "Test account type", "internal_group": "equity"} ) cls.account = cls.env["account.account"].create( { "name": "Test account", "code": "TEST_AIVQ", "user_type_id": cls.account_type.id, } ) cls.invoice = cls.env["account.move"].create( { "partner_id": cls.partner.id, "move_type": "out_invoice", "invoice_line_ids": [ ( 0, 0, { "name": "Test product", "account_id": cls.account.id, "price_unit": 20.0, "quantity": 1.0, }, ), ], } ) def test_queue_validation(self): wizard = self.wizard_obj.with_context( active_ids=self.invoice.ids, ).create({}) prev_jobs = self.queue_obj.search([]) wizard.enqueue_invoice_confirm() current_jobs = self.queue_obj.search([]) jobs = current_jobs - prev_jobs self.assertEqual(len(jobs), 1) self.assertTrue(self.invoice.validation_job_ids) def test_queue_validation_several_dates(self): invoice2 = self.invoice.copy({"date": "2019-01-01"}) wizard = self.wizard_obj.with_context( active_ids=(self.invoice + invoice2).ids, ).create({}) with self.assertRaises(exceptions.UserError): wizard.enqueue_invoice_confirm() def test_validation(self): # Execute method directly for checking if validation is done self.invoice.action_invoice_open_job() self.assertEqual(self.invoice.state, "posted")
36
2,412
654
py
PYTHON
15.0
# Copyright 2019-2020 Tecnativa - Pedro M. Baeza # Copyright 2020 Tecnativa - Manuel Calero # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class AccountMove(models.Model): _inherit = "account.move" validation_job_ids = fields.Many2many( comodel_name="queue.job", column1="invoice_id", column2="job_id", string="Validation Jobs", relation="account_move_validation_job_rel", copy=False, ) def action_invoice_open_job(self): self.ensure_one() if self.state not in {"draft", "sent"}: return self._post()
27.25
654
1,249
py
PYTHON
15.0
# Copyright 2019 Tecnativa - Pedro M. Baeza # Copyright 2020 Tecnativa - Manuel Calero # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, exceptions, models from odoo.addons.queue_job.job import identity_exact class ValidateAccountMove(models.TransientModel): _inherit = "validate.account.move" def enqueue_invoice_confirm(self): queue_obj = self.env["queue.job"] active_ids = self.env.context.get("active_ids", []) moves = self.env["account.move"].browse(active_ids) move_to_post = moves.filtered(lambda m: m.state == "draft").sorted( lambda m: (m.date, m.ref or "", m.id) ) # Check if all invoices are for the same date inv_date = move_to_post[:1].date if any(move_to_post.filtered(lambda x: x.date != inv_date)): raise exceptions.UserError( _("You can't enqueue invoices with different dates.") ) for move in move_to_post: new_delay = move.with_delay( identity_key=identity_exact, ).action_invoice_open_job() job = queue_obj.search([("uuid", "=", new_delay.uuid)]) move.sudo().validation_job_ids = [(4, job.id)]
40.290323
1,249
664
py
PYTHON
15.0
# Copyright (C) 2021 Open Source Integrators # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Restrict Invoice created from SO", "summary": "Restricts editing the Product, Quantity and Unit Price " "columns for invoice lines that originated in Sales Orders.", "version": "15.0.1.0.1", "category": "Accounting", "author": "Open Source Integrators, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-invoicing", "license": "AGPL-3", "depends": ["sale_management"], "data": [ "views/account_move.xml", ], "installable": True, "maintainer": "dreispt", }
34.947368
664
469
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). { "name": "Account invoice search by reference", "version": "15.0.1.0.0", "author": "ForgeFlow, Odoo Community Association (OCA)", "category": "Invoicing", "website": "https://github.com/OCA/account-invoicing", "license": "AGPL-3", "depends": ["account"], "installable": True, "auto_install": False, }
33.5
469
2,728
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.tests.common import TransactionCase class TestAccountInvoiceSearchByReference(TransactionCase): def setUp(self): super(TestAccountInvoiceSearchByReference, self).setUp() self.par_model = self.env["res.partner"] self.acc_model = self.env["account.account"] self.inv_model = self.env["account.move"] self.inv_line_model = self.env["account.move.line"] self.partner1 = self._create_partner() self.invoice_account = self.acc_model.search( [ ( "user_type_id", "=", self.env.ref("account.data_account_type_receivable").id, ) ], limit=1, ) self.invoice1 = self._create_invoice(self.partner1) self.invoice_name_get = self._create_invoice(self.partner1) self.invoice_name_get.name = "/" self.invoice_line1 = self._create_inv_line( self.invoice_account.id, self.invoice1.id ) def _create_partner(self): partner = self.par_model.create( {"name": "Test Partner", "supplier_rank": 1, "company_type": "company"} ) return partner def _create_invoice(self, partner): invoice = self.inv_model.create( {"partner_id": partner.id, "ref": "Test reference"} ) return invoice def _create_inv_line(self, account_id, move_id): inv_line = self.inv_line_model.create( { "name": "test invoice line", "account_id": account_id, "quantity": 1.0, "price_unit": 3.0, "product_id": self.env.ref("product.product_product_8").id, "move_id": move_id, } ) return inv_line def test_account_invoice_method(self): self.assertEqual(self.invoice_name_get.name_get()[0][1], self.invoice1.ref) self.invoice_name_get.ref = False self.assertEqual( self.invoice_name_get.name_get()[0][1], "Draft Entry (* %s)" % self.invoice_name_get.id, ) check_method1 = self.invoice1.name_search( name="TEST", operator="ilike", args=[("id", "in", self.invoice1.ids)] ) self.assertEqual(check_method1[0][0], self.invoice1.id) self.invoice1.action_post() check_method2 = self.invoice1.name_search( name="MISC", operator="ilike", args=[("id", "in", self.invoice1.ids)] ) self.assertEqual(check_method2[0][0], self.invoice1.id)
36.373333
2,728
965
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 AccountMove(models.Model): _inherit = "account.move" @api.model def name_search(self, name, args=None, operator="ilike", limit=100): args = args or [] domain = [] if name: domain = ["|", ("ref", operator, name), ("name", operator, name)] invoices = self.search(domain + args, limit=limit) return invoices.name_get() @api.depends("ref", "name") def name_get(self): res = [] for inv in self: if inv.ref and inv.name != "/": res.append((inv.id, "{} {}".format(inv.name, inv.ref))) elif inv.ref and inv.name == "/": res.append((inv.id, "{}".format(inv.ref))) else: return super(AccountMove, self).name_get() return res
33.275862
965
738
py
PYTHON
15.0
# Copyright 2019 Tecnativa S.L. - David Vidal # Copyright 2020-2021 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Account Global Discount", "version": "15.0.1.0.1", "category": "Accounting", "author": "Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-invoicing", "license": "AGPL-3", "depends": ["account", "base_global_discount"], "data": [ "security/ir.model.access.csv", "security/security.xml", "views/account_invoice_views.xml", "views/global_discount_views.xml", "views/report_account_invoice.xml", ], "application": False, "installable": True, }
35.142857
738
20,927
py
PYTHON
15.0
# Copyright 2019 Tecnativa - David Vidal # Copyright 2020 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 exceptions from odoo.tests import Form, common class TestGlobalDiscount(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.account_type = cls.env["account.account.type"].create( {"name": "Test", "type": "other", "internal_group": "income"} ) cls.account = cls.env["account.account"].create( { "name": "Test account", "code": "TEST", "user_type_id": cls.account_type.id, "reconcile": True, } ) cls.account_type_receivable = cls.env["account.account.type"].create( {"name": "Test", "type": "receivable", "internal_group": "income"} ) cls.account_receivable = cls.env["account.account"].create( { "name": "Test receivable account", "code": "ACCRV", "user_type_id": cls.account_type_receivable.id, "reconcile": True, } ) cls.account_type_payable = cls.env["account.account.type"].create( {"name": "Test", "type": "payable", "internal_group": "income"} ) cls.account_payable = cls.env["account.account"].create( { "name": "Test receivable account", "code": "ACCPAY", "user_type_id": cls.account_type_payable.id, "reconcile": True, } ) cls.global_discount_obj = cls.env["global.discount"] cls.global_discount_1 = cls.global_discount_obj.create( { "name": "Test Discount 1", "discount_scope": "sale", "discount": 20, "account_id": cls.account.id, "sequence": 3, } ) cls.global_discount_2 = cls.global_discount_obj.create( { "name": "Test Discount 2", "discount_scope": "purchase", "discount": 30, "account_id": cls.account.id, "sequence": 2, } ) cls.global_discount_3 = cls.global_discount_obj.create( { "name": "Test Discount 3", "discount_scope": "purchase", "discount": 50, "account_id": cls.account.id, "sequence": 1, } ) cls.partner_1 = cls.env["res.partner"].create( { "name": "Mr. Odoo", "property_account_receivable_id": cls.account_receivable.id, "property_account_payable_id": cls.account_payable.id, } ) cls.partner_2 = cls.env["res.partner"].create( { "name": "Mrs. Odoo", "property_account_receivable_id": cls.account_receivable.id, "property_account_payable_id": cls.account_payable.id, } ) cls.partner_2.supplier_global_discount_ids = cls.global_discount_2 cls.tax = cls.env["account.tax"].create( { "name": "TAX 15%", "amount_type": "percent", "type_tax_use": "purchase", "amount": 15.0, } ) cls.tax_0 = cls.env["account.tax"].create( { "name": "TAX 0%", "amount_type": "percent", "type_tax_use": "purchase", "amount": 0.0, } ) cls.journal = cls.env["account.journal"].create( {"name": "Test purchase journal", "code": "TPUR", "type": "purchase"} ) cls.invoice_line = cls.env["account.move.line"] invoice_form = Form( cls.env["account.move"].with_context( default_move_type="in_invoice", test_account_global_discount=True, ) ) invoice_form.partner_id = cls.partner_1 invoice_form.ref = "Test global discount" with invoice_form.invoice_line_ids.new() as line_form: line_form.name = "Line 1" line_form.price_unit = 200.0 line_form.quantity = 1 line_form.tax_ids.clear() line_form.tax_ids.add(cls.tax) cls.invoice = invoice_form.save() def test_01_global_invoice_succesive_discounts(self): """Add global discounts to the invoice""" invoice_tax_line = self.invoice.line_ids.filtered("tax_line_id") self.assertAlmostEqual(self.invoice.amount_total, 230) self.assertAlmostEqual(invoice_tax_line.tax_base_amount, 200.0) self.assertAlmostEqual(invoice_tax_line.balance, 30.0) # Global discounts are applied to the base and taxes are recomputed: # 200 - 50% (global disc. 1) = 100 with Form(self.invoice) as invoice_form: invoice_form.global_discount_ids.clear() invoice_form.global_discount_ids.add(self.global_discount_3) self.assertEqual(len(self.invoice.invoice_global_discount_ids), 1) precision = self.env["decimal.precision"].precision_get("Discount") self.assertEqual( self.invoice.invoice_global_discount_ids.discount_display, "-50.{}%".format("0" * precision), ) invoice_tax_line = self.invoice.line_ids.filtered("tax_line_id") self.assertAlmostEqual(invoice_tax_line.tax_base_amount, 100.0) self.assertAlmostEqual(invoice_tax_line.balance, 15.0) self.assertAlmostEqual(self.invoice.amount_untaxed, 100.0) self.assertAlmostEqual(self.invoice.amount_total, 115.0) self.assertAlmostEqual(self.invoice.amount_global_discount, -100.0) # Global discounts are computed succecively: # 200 - 50% (global disc. 1) = 100 # 100 - 30% (global disc. 2) = 70 # The global discounts amount is then 200 - 70 = 130 with Form(self.invoice) as invoice_form: invoice_form.global_discount_ids.add(self.global_discount_2) self.assertEqual(len(self.invoice.invoice_global_discount_ids), 2) invoice_tax_line = self.invoice.line_ids.filtered("tax_line_id") self.assertAlmostEqual(invoice_tax_line.tax_base_amount, 70.0) self.assertAlmostEqual(invoice_tax_line.balance, 10.5) self.assertAlmostEqual(self.invoice.amount_untaxed, 70.0) self.assertAlmostEqual(self.invoice.amount_total, 80.5) self.assertAlmostEqual(self.invoice.amount_global_discount, -130.0) # Line discounts apply before global ones so: # 200 - 20% (line discount) = 160 # 160 - 50% (global disc. 1) = 80 # 80 - 30% (global disc. 2) = 56 # The global discounts amount is then 160 - 56 = 104 with Form(self.invoice) as invoice_form: with invoice_form.invoice_line_ids.edit(0) as line_form: line_form.discount = 20 self.assertEqual(len(self.invoice.invoice_global_discount_ids), 2) invoice_tax_line = self.invoice.line_ids.filtered("tax_line_id") self.assertAlmostEqual(invoice_tax_line.tax_base_amount, 56.0) self.assertAlmostEqual(invoice_tax_line.balance, 8.4) self.assertAlmostEqual(self.invoice.amount_untaxed, 56.0) self.assertAlmostEqual(self.invoice.amount_total, 64.4) self.assertAlmostEqual(self.invoice.amount_global_discount, -104.0) def test_02_global_invoice_discounts_from_partner(self): """Change the partner and his global discounts go to the invoice""" invoice_tax_line = self.invoice.line_ids.filtered("tax_line_id") self.assertAlmostEqual(self.invoice.amount_total, 230) self.assertAlmostEqual(invoice_tax_line.tax_base_amount, 200.0) self.assertAlmostEqual(invoice_tax_line.balance, 30.0) # When we change the parter, his global discounts are fetched depending # on the type of the invoice. In this case, we fetch the supplier # global discounts with Form(self.invoice) as invoice_form: invoice_form.partner_id = self.partner_2 self.assertAlmostEqual(invoice_tax_line.tax_base_amount, 140.0) self.assertAlmostEqual(invoice_tax_line.balance, 21.0) self.assertAlmostEqual(self.invoice.amount_untaxed, 140.0) self.assertAlmostEqual(self.invoice.amount_total, 161.0) self.assertAlmostEqual(self.invoice.amount_global_discount, -60.0) def test_03_multiple_taxes_multi_line(self): tax2 = self.env["account.tax"].create( { "name": "TAX 20% 2", "amount_type": "percent", "type_tax_use": "purchase", "amount": 20.0, } ) with Form(self.invoice) as invoice_form: invoice_form.global_discount_ids.add(self.global_discount_1) with invoice_form.invoice_line_ids.new() as line_form: line_form.name = "Line 2" line_form.price_unit = 100.0 line_form.quantity = 1 line_form.tax_ids.clear() line_form.tax_ids.add(tax2) self.assertEqual(len(self.invoice.invoice_global_discount_ids), 2) discount_tax_15 = self.invoice.invoice_global_discount_ids.filtered( lambda x: x.tax_ids == self.tax ) discount_tax_20 = self.invoice.invoice_global_discount_ids.filtered( lambda x: x.tax_ids == tax2 ) self.assertAlmostEqual(discount_tax_15.discount_amount, 40) self.assertAlmostEqual(discount_tax_20.discount_amount, 20) tax_line_15 = self.invoice.line_ids.filtered( lambda x: x.tax_line_id == self.tax ) tax_line_20 = self.invoice.line_ids.filtered(lambda x: x.tax_line_id == tax2) self.assertAlmostEqual(tax_line_15.tax_base_amount, 160) self.assertAlmostEqual(tax_line_15.balance, 24) self.assertAlmostEqual(tax_line_20.tax_base_amount, 80.0) self.assertAlmostEqual(tax_line_20.balance, 16) self.assertAlmostEqual(self.invoice.amount_untaxed, 240.0) self.assertAlmostEqual(self.invoice.amount_total, 280) self.assertAlmostEqual(self.invoice.amount_global_discount, -60.0) # Check journal items validity lines = self.invoice.line_ids line_15 = lines.filtered( lambda x: x.global_discount_item and x.tax_ids == self.tax ) self.assertAlmostEqual(line_15.credit, 40) line_20 = lines.filtered(lambda x: x.global_discount_item and x.tax_ids == tax2) self.assertAlmostEqual(line_20.credit, 20) def test_04_multiple_taxes_same_line(self): tax2 = self.env["account.tax"].create( { "name": "Retention 20%", "amount_type": "percent", "type_tax_use": "purchase", "amount": -20.0, # negative for testing more use cases } ) with Form(self.invoice.with_context(check_move_validity=False)) as invoice_form: invoice_form.global_discount_ids.add(self.global_discount_1) with invoice_form.invoice_line_ids.edit(0) as line_form: line_form.tax_ids.add(tax2) # Global discounts are applied to the base and taxes are recomputed: # 300 - 20% (global disc. 1) = 240 self.assertEqual(len(self.invoice.invoice_global_discount_ids), 1) self.assertAlmostEqual( self.invoice.invoice_global_discount_ids.discount_amount, 40 ) self.assertEqual( self.invoice.invoice_global_discount_ids.tax_ids, self.tax + tax2 ) tax_line_15 = self.invoice.line_ids.filtered( lambda x: x.tax_line_id == self.tax ) tax_line_20 = self.invoice.line_ids.filtered(lambda x: x.tax_line_id == tax2) self.assertAlmostEqual(tax_line_15.tax_base_amount, 160) self.assertAlmostEqual(tax_line_15.balance, 24) self.assertAlmostEqual(tax_line_20.tax_base_amount, 160.0) self.assertAlmostEqual(tax_line_20.balance, -32) self.assertAlmostEqual(self.invoice.amount_untaxed, 160.0) self.assertAlmostEqual(self.invoice.amount_total, 152) self.assertAlmostEqual(self.invoice.amount_global_discount, -40.0) def test_05_incompatible_taxes(self): # Line 1 with tax and tax2 # Line 2 with only tax2 tax2 = self.env["account.tax"].create( { "name": "Retention 20%", "amount_type": "percent", "type_tax_use": "purchase", "amount": -20.0, # negative for testing more use cases } ) with self.assertRaises(exceptions.UserError): with Form(self.invoice) as invoice_form: invoice_form.global_discount_ids.add(self.global_discount_1) with invoice_form.invoice_line_ids.new() as line_form: line_form.name = "Line 2" line_form.price_unit = 100.0 line_form.quantity = 1 line_form.tax_ids.clear() line_form.tax_ids.add(self.tax) line_form.tax_ids.add(tax2) def test_06_no_taxes(self): with self.assertRaises(exceptions.UserError): with Form(self.invoice) as invoice_form: invoice_form.global_discount_ids.add(self.global_discount_1) with invoice_form.invoice_line_ids.edit(0) as line_form: line_form.tax_ids.clear() def test_07_line_with_tax_0(self): with Form(self.invoice) as invoice_form: invoice_form.global_discount_ids.add(self.global_discount_1) with invoice_form.invoice_line_ids.edit(0) as line_form: line_form.tax_ids.clear() line_form.tax_ids.add(self.tax_0) discounts = self.invoice.invoice_global_discount_ids self.assertEqual(len(discounts), 1) self.assertAlmostEqual(discounts.discount_amount, 40) def test_08_line2_with_tax_0(self): with Form(self.invoice) as invoice_form: invoice_form.global_discount_ids.add(self.global_discount_1) with invoice_form.invoice_line_ids.new() as line_form: line_form.name = "Line 2" line_form.price_unit = 100.0 line_form.quantity = 1 line_form.tax_ids.clear() line_form.tax_ids.add(self.tax_0) self.assertEqual(len(self.invoice.invoice_global_discount_ids), 2) discount_tax_15 = self.invoice.invoice_global_discount_ids.filtered( lambda x: x.tax_ids == self.tax ) self.assertAlmostEqual(discount_tax_15.discount_amount, 40) discount_tax_0 = self.invoice.invoice_global_discount_ids.filtered( lambda x: x.tax_ids == self.tax_0 ) self.assertAlmostEqual(discount_tax_0.discount_amount, 20) def test_09_customer_invoice(self): global_discount = self.global_discount_obj.create( { "name": "Test Discount Sales", "discount_scope": "sale", "discount": 50, "account_id": self.account.id, "sequence": 1, } ) tax = self.env["account.tax"].create( { "name": "TAX 15% Sales", "amount_type": "percent", "type_tax_use": "sale", "amount": 15.0, } ) invoice_form = Form( self.env["account.move"].with_context( default_move_type="out_invoice", test_account_global_discount=True, ) ) invoice_form.partner_id = self.partner_1 invoice_form.global_discount_ids.add(global_discount) with invoice_form.invoice_line_ids.new() as line_form: line_form.name = "Line 1" line_form.price_unit = 200.0 line_form.quantity = 1 line_form.tax_ids.clear() line_form.tax_ids.add(tax) invoice = invoice_form.save() self.assertEqual(len(invoice.invoice_global_discount_ids), 1) invoice_tax_line = invoice.line_ids.filtered("tax_line_id") self.assertAlmostEqual(invoice_tax_line.tax_base_amount, 100.0) self.assertAlmostEqual(invoice_tax_line.balance, -15.0) self.assertAlmostEqual(invoice.amount_untaxed, 100.0) self.assertAlmostEqual(invoice.amount_total, 115.0) self.assertAlmostEqual(invoice.amount_global_discount, -100.0) # Check journal item validity lines = invoice.line_ids line_15 = lines.filtered(lambda x: x.global_discount_item and x.tax_ids == tax) self.assertAlmostEqual(line_15.debit, 100) def test_10_customer_invoice_currency(self): """Multi-currency""" eur = self.env.ref("base.EUR") usd = self.env.ref("base.USD") self.assertEqual(self.env.user.company_id.currency_id, usd) with Form(self.invoice) as invoice_form: invoice_form.currency_id = eur invoice = invoice_form.save() self.assertAlmostEqual(invoice.amount_total, 230.0) self.assertAlmostEqual(invoice.amount_untaxed, 200.0) self.assertAlmostEqual(invoice.amount_global_discount, 0) base_line = invoice.line_ids.filtered( lambda l: l.tax_ids and not l.global_discount_item ) self.assertEqual(len(base_line), 1) self.assertAlmostEqual( base_line.balance, eur._convert( invoice.amount_untaxed, usd, self.env.user.company_id, invoice.date ), ) tax_line = invoice.line_ids.filtered( lambda l: l.tax_line_id and not l.global_discount_item ) self.assertEqual(len(tax_line), 1) tax_line_balance_before_discount = tax_line.balance self.assertAlmostEqual( tax_line_balance_before_discount, eur._convert( invoice.amount_untaxed * (self.tax.amount / 100), usd, self.env.user.company_id, invoice.date, ), ) self.assertAlmostEqual( tax_line.tax_base_amount, eur._convert( invoice.amount_untaxed, usd, self.env.user.company_id, invoice.date, ), ) discount_line = invoice.line_ids.filtered("global_discount_item") self.assertFalse(discount_line) with Form(self.invoice) as invoice_form: invoice_form.global_discount_ids.add(self.global_discount_1) invoice = invoice_form.save() # Check that when we add a global discount it will be based on the # correct currency self.assertAlmostEqual(invoice.amount_total, 184) self.assertAlmostEqual(invoice.amount_untaxed, 160.0) self.assertAlmostEqual(invoice.amount_global_discount, -40.0) base_line = invoice.line_ids.filtered( lambda l: l.tax_ids and not l.global_discount_item ) self.assertEqual(len(base_line), 1) self.assertAlmostEqual( base_line.balance, eur._convert( invoice.amount_untaxed_before_global_discounts, usd, self.env.user.company_id, invoice.date, ), ) tax_line = invoice.line_ids.filtered( lambda l: l.tax_line_id and not l.global_discount_item ) self.assertEqual(len(tax_line), 1) self.assertAlmostEqual( tax_line.tax_base_amount, eur._convert( invoice.amount_untaxed, usd, self.env.user.company_id, invoice.date, ), ) self.assertAlmostEqual( tax_line.balance, eur._convert( invoice.amount_untaxed * (self.tax.amount / 100), usd, self.env.user.company_id, invoice.date, ), ) self.assertLess(tax_line.balance, tax_line_balance_before_discount) discount_line = invoice.line_ids.filtered("global_discount_item") self.assertEqual(len(discount_line), 1) self.assertAlmostEqual( discount_line.balance, eur._convert( invoice.amount_global_discount, usd, self.env.user.company_id, invoice.date, ), )
43.867925
20,925
19,003
py
PYTHON
15.0
# Copyright 2019 Tecnativa - David Vidal # Copyright 2020-2021 Tecnativa - Pedro M. Baeza # Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, api, exceptions, fields, models from odoo.tools import config class AccountMove(models.Model): _inherit = "account.move" # HACK: Looks like UI doesn't behave well with Many2many fields and # negative groups when the same field is shown. In this case, we want to # show the readonly version to any not in the global discount group. # TODO: Check if it's fixed in future versions global_discount_ids_readonly = fields.Many2many( string="Invoice Global Discounts (readonly)", related="global_discount_ids", readonly=True, ) global_discount_ids = fields.Many2many( comodel_name="global.discount", column1="invoice_id", column2="global_discount_id", string="Invoice Global Discounts", domain="[('discount_scope', 'in', {" " 'out_invoice': ['sale'], " " 'out_refund': ['sale'], " " 'in_refund': ['purchase'], " " 'in_invoice': ['purchase']" "}.get(move_type, [])), ('account_id', '!=', False), '|', " "('company_id', '=', company_id), ('company_id', '=', False)]", readonly=True, states={"draft": [("readonly", False)]}, ) amount_global_discount = fields.Monetary( string="Total Global Discounts", compute="_compute_amount", currency_field="currency_id", readonly=True, compute_sudo=True, store=True, ) amount_untaxed_before_global_discounts = fields.Monetary( string="Amount Untaxed Before Discounts", compute="_compute_amount", currency_field="currency_id", readonly=True, compute_sudo=True, store=True, ) invoice_global_discount_ids = fields.One2many( comodel_name="account.invoice.global.discount", inverse_name="invoice_id", readonly=True, ) def _recompute_tax_lines( self, recompute_tax_base_amount=False, tax_rep_lines_to_recompute=None ): """Inject the global discounts recomputation if recompute_tax_base_amount is false, as on contrary, only the tax_base_amount field is recalculated, not affecting global discount computation. """ # Remove first existing previous global discount move lines for not altering # tax computation if not recompute_tax_base_amount: # TODO: To be changed to invoice_global_discount_id when properly filled self.line_ids -= self.line_ids.filtered("global_discount_item") res = super()._recompute_tax_lines( recompute_tax_base_amount, tax_rep_lines_to_recompute=tax_rep_lines_to_recompute, ) if not recompute_tax_base_amount: self._update_tax_lines_for_global_discount() self._set_global_discounts_by_tax() self._recompute_global_discount_lines() return res def _update_tax_lines_for_global_discount(self): """Update tax_base_amount and taxes debits on tax move lines using global discounts. We are altering the recently recreated tax move lines got calling super on ``_recompute_tax_lines``. """ round_curr = self.currency_id.round tax_lines = self.line_ids.filtered( lambda r: r.tax_line_id.amount_type in ("percent", "division") ) for tax_line in tax_lines: base = tax_line.tax_base_amount if tax_line.currency_id != tax_line.company_currency_id: tax_line.base_before_global_discounts = ( tax_line.company_currency_id._convert( base, tax_line.currency_id, tax_line.company_id, tax_line.date or fields.Date.context_today(self), ) ) else: tax_line.base_before_global_discounts = base amount = tax_line.balance for discount in self.global_discount_ids: base = discount._get_global_discount_vals(base)["base_discounted"] amount = discount._get_global_discount_vals(amount)["base_discounted"] tax_line.tax_base_amount = round_curr(base) tax_line.debit = amount > 0.0 and amount or 0.0 tax_line.credit = amount < 0.0 and -amount or 0.0 # Apply onchanges tax_line._onchange_balance() if tax_line.currency_id != tax_line.company_currency_id: tax_line.amount_currency = tax_line.company_currency_id._convert( tax_line.balance, tax_line.currency_id, tax_line.company_id, tax_line.date or fields.Date.context_today(self), ) tax_line._onchange_amount_currency() def _prepare_global_discount_vals(self, global_discount, base, tax_ids): """Prepare the dictionary values for an invoice global discount line. """ self.ensure_one() discount = global_discount._get_global_discount_vals(base) return { "name": global_discount.display_name, "invoice_id": self.id, "global_discount_id": global_discount.id, "discount": global_discount.discount, "base": base, "base_discounted": discount["base_discounted"], "account_id": global_discount.account_id.id, "tax_ids": [(4, tax_id) for tax_id in tax_ids], } def _set_global_discounts_by_tax(self): """Create invoice global discount lines by taxes combinations and discounts. This also resets previous global discounts in case they existed. """ self.ensure_one() if not self.is_invoice(): return in_draft_mode = self != self._origin taxes_keys = {} # Perform a sanity check for discarding cases that will lead to # incorrect data in discounts _self = self.filtered("global_discount_ids") for inv_line in _self.invoice_line_ids.filtered(lambda l: not l.display_type): for key in taxes_keys: if key == tuple(inv_line.tax_ids.ids): break else: taxes_keys[tuple(inv_line.tax_ids.ids)] = True # Reset previous global discounts self.invoice_global_discount_ids -= self.invoice_global_discount_ids model = "account.invoice.global.discount" create_method = in_draft_mode and self.env[model].new or self.env[model].create account_tax_obj = self.env["account.tax"] for tax_line in _self.line_ids.filtered("tax_line_id"): key = [] to_create = True for key in taxes_keys: if tax_line.tax_line_id.id in key: to_create = taxes_keys[key] taxes_keys[key] = False # mark for not duplicating break # we leave in key variable the proper taxes value # didn't break, then we check if the tax computation is 'group' for tax_id in key: tax = account_tax_obj.browse(tax_id) if ( tax.amount_type == "group" and tax_line.tax_line_id.id in tax.children_tax_ids.ids ): to_create = taxes_keys[key] taxes_keys[key] = False # mark for not duplicating break if not to_create: continue base = tax_line.base_before_global_discounts or tax_line.tax_base_amount for global_discount in self.global_discount_ids: vals = self._prepare_global_discount_vals(global_discount, base, key) create_method(vals) base = vals["base_discounted"] # Check all moves with defined taxes to check if there's any discount not # created (tax amount is zero and only one tax is applied) for line in _self.line_ids.filtered("tax_ids"): key = tuple(line.tax_ids.ids) if taxes_keys.get(key): base = line.price_subtotal for global_discount in self.global_discount_ids: vals = self._prepare_global_discount_vals( global_discount, base, key ) create_method(vals) base = vals["base_discounted"] def _recompute_global_discount_lines(self): """Append global discounts move lines. This is called when recomputing dynamic lines before calling `_recompute_payment_terms_lines`, but after calling `_recompute_tax_lines`. """ self.ensure_one() in_draft_mode = self != self._origin model = "account.move.line" create_method = in_draft_mode and self.env[model].new or self.env[model].create for discount in self.invoice_global_discount_ids.filtered("discount"): sign = -1 if self.move_type in {"in_invoice", "out_refund"} else 1 disc_amount = sign * discount.discount_amount disc_amount_company_currency = disc_amount if self.currency_id != self.company_id.currency_id: disc_amount_company_currency = self.currency_id._convert( disc_amount, self.company_id.currency_id, self.company_id, self.date or fields.Date.context_today(self), ) create_method( { "global_discount_item": True, # TODO: This field is not properly saved, probably due to ORM glitch "invoice_global_discount_id": discount.id, "move_id": self.id, "name": "%s - %s" % (discount.name, ", ".join(discount.tax_ids.mapped("name"))), "debit": disc_amount_company_currency > 0.0 and disc_amount_company_currency or 0.0, "credit": disc_amount_company_currency < 0.0 and -disc_amount_company_currency or 0.0, "amount_currency": (disc_amount > 0.0 and disc_amount or 0.0) - (disc_amount < 0.0 and -disc_amount or 0.0), "account_id": discount.account_id.id, "analytic_account_id": discount.account_analytic_id.id, "exclude_from_invoice_tab": True, "tax_ids": [(4, x.id) for x in discount.tax_ids], "partner_id": self.commercial_partner_id.id, "currency_id": self.currency_id.id, } ) @api.onchange("partner_id", "company_id") def _onchange_partner_id(self): res = super()._onchange_partner_id() discounts = False if ( self.move_type in ["out_invoice", "out_refund"] and self.partner_id.customer_global_discount_ids ): discounts = self.partner_id.customer_global_discount_ids.filtered( lambda d: d.company_id == self.company_id ) elif ( self.move_type in ["in_refund", "in_invoice"] and self.partner_id.supplier_global_discount_ids ): discounts = self.partner_id.supplier_global_discount_ids.filtered( lambda d: d.company_id == self.company_id ) if discounts: self.global_discount_ids = discounts # We need to manually launch the onchange, as the recursivity is explicitly # disabled in this model: # https://github.com/odoo/odoo/blob/a8d3f466dfffca08214acecf08ec298e3ace6272 # /addons/account/models/account_move.py#L1021-L1025 self._onchange_global_discount_ids() return res @api.onchange("global_discount_ids") def _onchange_global_discount_ids(self): """Trigger move lines recomputation.""" return self._recompute_dynamic_lines(recompute_all_taxes=True) def _compute_amount_one(self): """Perform totals computation of a move with global discounts.""" if not self.invoice_global_discount_ids: self.amount_global_discount = 0.0 self.amount_untaxed_before_global_discounts = 0.0 return round_curr = self.currency_id.round self.amount_global_discount = sum( round_curr(discount.discount_amount) * -1 for discount in self.invoice_global_discount_ids ) self.amount_untaxed_before_global_discounts = self.amount_untaxed self.amount_untaxed = self.amount_untaxed + self.amount_global_discount self.amount_total = self.amount_untaxed + self.amount_tax amount_untaxed_signed = self.amount_untaxed if ( self.currency_id and self.company_id and self.currency_id != self.company_id.currency_id ): date = self.invoice_date or fields.Date.today() amount_untaxed_signed = self.currency_id._convert( self.amount_untaxed, self.company_id.currency_id, self.company_id, date ) sign = self.move_type in ["in_invoice", "out_refund"] and -1 or 1 self.amount_total_signed = self.amount_total * sign self.amount_untaxed_signed = amount_untaxed_signed * sign @api.depends( "line_ids.debit", "line_ids.credit", "line_ids.currency_id", "line_ids.amount_currency", "line_ids.amount_residual", "line_ids.amount_residual_currency", "line_ids.payment_id.state", "invoice_global_discount_ids", "global_discount_ids", ) def _compute_amount(self): """Modify totals computation for including global discounts.""" res = super()._compute_amount() for record in self: record._compute_amount_one() return res @api.model_create_multi def create(self, vals_list): """If we create the invoice with the discounts already set like from a sales order, we must compute the global discounts as well, as some data like ``tax_ids`` is not set until the final step. """ moves = super().create(vals_list) move_with_global_discounts = moves.filtered("global_discount_ids") for move in move_with_global_discounts: move.with_context(check_move_validity=False)._onchange_global_discount_ids() return moves def _check_balanced(self): """Add the check of proper taxes for global discounts.""" res = super()._check_balanced() test_condition = not config["test_enable"] or self.env.context.get( "test_account_global_discount" ) for move in self.filtered(lambda x: x.is_invoice() and x.global_discount_ids): taxes_keys = {} for inv_line in move.invoice_line_ids.filtered( lambda l: not l.display_type ): if not inv_line.tax_ids and test_condition: raise exceptions.UserError( _("With global discounts, taxes in lines are required.") ) for key in taxes_keys: if key == tuple(inv_line.tax_ids.ids): break elif set(key) & set(inv_line.tax_ids.ids) and test_condition: raise exceptions.UserError( _("Incompatible taxes found for global discounts.") ) else: taxes_keys[tuple(inv_line.tax_ids.ids)] = True return res class AccountMoveLine(models.Model): _inherit = "account.move.line" invoice_global_discount_id = fields.Many2one( comodel_name="account.invoice.global.discount", string="Invoice Global Discount", ) base_before_global_discounts = fields.Monetary( string="Amount Untaxed Before Discounts", readonly=True, ) # TODO: To be removed on future versions if invoice_global_discount_id is properly filled # Provided for compatibility in stable branch global_discount_item = fields.Boolean() class AccountInvoiceGlobalDiscount(models.Model): _name = "account.invoice.global.discount" _description = "Invoice Global Discount" name = fields.Char(string="Discount Name", required=True) invoice_id = fields.Many2one( "account.move", string="Invoice", ondelete="cascade", index=True, readonly=True, domain=[ ( "move_type", "in", ["out_invoice", "out_refund", "in_invoice", "in_refund"], ) ], ) global_discount_id = fields.Many2one( comodel_name="global.discount", string="Global Discount", ) discount = fields.Float(string="Discount (number)") discount_display = fields.Char( compute="_compute_discount_display", string="Discount", ) base = fields.Float(string="Base before discount", digits="Product Price") base_discounted = fields.Float(string="Base after discount", digits="Product Price") currency_id = fields.Many2one(related="invoice_id.currency_id", readonly=True) discount_amount = fields.Monetary( string="Discounted Amount", compute="_compute_discount_amount", currency_field="currency_id", compute_sudo=True, ) tax_ids = fields.Many2many(comodel_name="account.tax", string="Taxes") account_id = fields.Many2one( comodel_name="account.account", required=True, string="Account", domain="[('user_type_id.type', 'not in', ['receivable', 'payable'])]", ) account_analytic_id = fields.Many2one( comodel_name="account.analytic.account", string="Analytic account", ) company_id = fields.Many2one(related="invoice_id.company_id", readonly=True) def _compute_discount_display(self): """Given a discount type, we need to render a different symbol""" for one in self: precision = self.env["decimal.precision"].precision_get("Discount") one.discount_display = "{0:.{1}f}%".format(one.discount * -1, precision) @api.depends("base", "base_discounted") def _compute_discount_amount(self): """Compute the amount discounted""" for one in self: one.discount_amount = one.base - one.base_discounted
42.988688
19,001
885
py
PYTHON
15.0
# Copyright 2019 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class GlobalDiscount(models.Model): _inherit = "global.discount" _check_company_auto = True account_id = fields.Many2one( comodel_name="account.account", string="Account", domain="[('user_type_id.type', 'not in', ['receivable', 'payable'])]", check_company=True, ) account_analytic_id = fields.Many2one( comodel_name="account.analytic.account", string="Analytic account", check_company=True, ) def _get_global_discount_vals(self, base, account_id=False, **kwargs): """Return account as well if passed""" res = super()._get_global_discount_vals(base) if account_id: res.update({"account_id": account_id}) return res
32.777778
885
363
py
PYTHON
15.0
from odoo import api, models class AccountInvoiceReport(models.Model): _inherit = "account.invoice.report" @api.model def _where(self): where_str = super()._where() return where_str.replace( "NOT line.exclude_from_invoice_tab", "(NOT line.exclude_from_invoice_tab OR global_discount_item = true)", )
27.923077
363
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
4,183
py
PYTHON
15.0
import setuptools with open('VERSION.txt', 'r') as f: version = f.read().strip() setuptools.setup( name="odoo-addons-oca-account-invoicing", description="Meta package for oca-account-invoicing Odoo addons", version=version, install_requires=[ 'odoo-addon-account_global_discount>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_analytic_search>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_block_payment>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_blocking>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_change_currency>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_check_picking_date>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_check_total>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_clearing>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_date_due>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_fiscal_position_update>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_fixed_discount>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_force_number>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_merge>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_payment_term_date_due>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_pricelist>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_pricelist_sale>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_refund_link>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_refund_reason>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_restrict_linked_so>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_search_by_reference>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_section_sale_order>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_supplier_ref_unique>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_supplier_self_invoice>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_tax_note>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_tax_required>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_transmit_method>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_tree_currency>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_triple_discount>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_validation_queued>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_view_payment>=15.0dev,<15.1dev', 'odoo-addon-account_move_exception>=15.0dev,<15.1dev', 'odoo-addon-account_move_post_block>=15.0dev,<15.1dev', 'odoo-addon-account_move_tier_validation>=15.0dev,<15.1dev', 'odoo-addon-account_move_tier_validation_forward>=15.0dev,<15.1dev', 'odoo-addon-account_portal_invoice_search>=15.0dev,<15.1dev', 'odoo-addon-account_portal_invoice_search_by_lot>=15.0dev,<15.1dev', 'odoo-addon-account_receipt_journal>=15.0dev,<15.1dev', 'odoo-addon-account_receipt_send>=15.0dev,<15.1dev', 'odoo-addon-account_tax_group_widget_base_amount>=15.0dev,<15.1dev', 'odoo-addon-partner_invoicing_mode>=15.0dev,<15.1dev', 'odoo-addon-partner_invoicing_mode_at_shipping>=15.0dev,<15.1dev', 'odoo-addon-portal_account_personal_data_only>=15.0dev,<15.1dev', 'odoo-addon-product_form_account_move_line_link>=15.0dev,<15.1dev', 'odoo-addon-product_supplierinfo_for_customer_invoice>=15.0dev,<15.1dev', 'odoo-addon-purchase_stock_picking_return_invoicing>=15.0dev,<15.1dev', 'odoo-addon-sale_invoicing_date_selection>=15.0dev,<15.1dev', 'odoo-addon-sale_line_refund_to_invoice_qty>=15.0dev,<15.1dev', 'odoo-addon-sale_order_invoicing_grouping_criteria>=15.0dev,<15.1dev', 'odoo-addon-sale_order_invoicing_qty_percentage>=15.0dev,<15.1dev', 'odoo-addon-sale_timesheet_invoice_description>=15.0dev,<15.1dev', 'odoo-addon-stock_picking_invoicing>=15.0dev,<15.1dev', 'odoo-addon-stock_picking_invoicing_incoterm>=15.0dev,<15.1dev', 'odoo-addon-stock_picking_return_refund_option>=15.0dev,<15.1dev', ], classifiers=[ 'Programming Language :: Python', 'Framework :: Odoo', 'Framework :: Odoo :: 15.0', ] )
59.757143
4,183
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
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