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,589
py
PYTHON
15.0
# © 2009 EduSense BV (<http://www.edusense.nl>) # © 2011-2013 Therp BV (<https://therp.nl>) # © 2014-2016 Serv. Tecnol. Avanzados - Pedro M. Baeza # © 2016 Akretion (Alexis de Lattre <[email protected]>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class AccountPaymentMode(models.Model): """This corresponds to the object payment.mode of v8 with some important changes""" _inherit = "account.payment.mode" payment_order_ok = fields.Boolean( string="Selectable in Payment Orders", default=True ) no_debit_before_maturity = fields.Boolean( string="Disallow Debit Before Maturity Date", help="If you activate this option on an Inbound payment mode, " "you will have an error message when you confirm a debit order " "that has a payment line with a payment date before the maturity " "date.", ) # Default options for the "payment.order.create" wizard default_payment_mode = fields.Selection( selection=[("same", "Same"), ("same_or_null", "Same or empty"), ("any", "Any")], string="Payment Mode on Invoice", default="same", ) default_journal_ids = fields.Many2many( comodel_name="account.journal", string="Journals Filter", domain="[('company_id', '=', company_id)]", ) default_invoice = fields.Boolean( string="Linked to an Invoice or Refund", default=False ) default_target_move = fields.Selection( selection=[("posted", "All Posted Entries"), ("all", "All Entries")], string="Target Moves", default="posted", ) default_date_type = fields.Selection( selection=[("due", "Due"), ("move", "Move")], default="due", string="Type of Date Filter", ) # default option for account.payment.order default_date_prefered = fields.Selection( selection=[ ("now", "Immediately"), ("due", "Due Date"), ("fixed", "Fixed Date"), ], string="Default Payment Execution Date", ) group_lines = fields.Boolean( string="Group Transactions in Payment Orders", default=True, help="If this mark is checked, the transaction lines of the " "payment order will be grouped upon confirmation of the payment " "order.The grouping will be done only if the following " "fields matches:\n" "* Partner\n" "* Currency\n" "* Destination Bank Account\n" "* Payment Date\n" "and if the 'Communication Type' is 'Free'\n" "(other modules can set additional fields to restrict the " "grouping.)", ) @api.onchange("payment_method_id") def payment_method_id_change(self): if self.payment_method_id: ajo = self.env["account.journal"] aj_ids = [] if self.payment_method_id.payment_type == "outbound": aj_ids = ajo.search( [ ("type", "in", ("purchase_refund", "purchase")), ("company_id", "=", self.company_id.id), ] ).ids elif self.payment_method_id.payment_type == "inbound": aj_ids = ajo.search( [ ("type", "in", ("sale_refund", "sale")), ("company_id", "=", self.company_id.id), ] ).ids self.default_journal_ids = [(6, 0, aj_ids)]
38.138298
3,585
1,516
py
PYTHON
15.0
# © 2017 Acsone SA/NV (<https://www.acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, models from odoo.tools.misc import formatLang class AccountPaymentOrderReport(models.AbstractModel): _name = "report.account_payment_order.print_account_payment_order_main" _description = "Technical model for printing payment order" @api.model def _get_report_values(self, docids, data=None): AccountPaymentOrderObj = self.env["account.payment.order"] docs = AccountPaymentOrderObj.browse(docids) return { "doc_ids": docids, "doc_model": "account.payment.order", "docs": docs, "data": data, "env": self.env, "get_bank_account_name": self.get_bank_account_name, "formatLang": formatLang, } @api.model def get_bank_account_name(self, partner_bank): """ :param partner_bank: :return: """ if partner_bank: name = "" if partner_bank.bank_name: name = "%s: " % partner_bank.bank_id.name if partner_bank.acc_number: name = "{} {}".format(name, partner_bank.acc_number) if partner_bank.bank_bic: name = "%s - " % (name) if partner_bank.bank_bic: name = "{} BIC {}".format(name, partner_bank.bank_bic) return name else: return False
32.934783
1,515
752
py
PYTHON
15.0
# Copyright 2010-2020 Akretion (www.akretion.com) # Copyright 2016 Tecnativa - Antonio Espinosa # Copyright 2016-2022 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) { "name": "Account Banking SEPA Credit Transfer", "summary": "Create SEPA XML files for Credit Transfers", "version": "15.0.2.0.1", "license": "AGPL-3", "author": "Akretion, Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/bank-payment", "category": "Banking addons", "conflicts": ["account_sepa"], "depends": ["account_banking_pain_base"], "data": ["data/account_payment_method.xml"], "demo": ["demo/sepa_credit_transfer_demo.xml"], "installable": True, }
39.578947
752
15,183
py
PYTHON
15.0
# Copyright 2016 Akretion (Alexis de Lattre <[email protected]>) # Copyright 2020 Sygel Technology - Valentin Vinagre # Copyright 2018-2022 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). import base64 import time from lxml import etree from odoo.exceptions import UserError from odoo.tests.common import TransactionCase class TestSCT(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.account_model = cls.env["account.account"] cls.move_model = cls.env["account.move"] cls.journal_model = cls.env["account.journal"] cls.payment_order_model = cls.env["account.payment.order"] cls.payment_line_model = cls.env["account.payment.line"] cls.partner_bank_model = cls.env["res.partner.bank"] cls.attachment_model = cls.env["ir.attachment"] cls.invoice_model = cls.env["account.move"] cls.invoice_line_model = cls.env["account.move.line"] cls.partner_agrolait = cls.env.ref("base.res_partner_2") cls.partner_asus = cls.env.ref("base.res_partner_1") cls.partner_c2c = cls.env.ref("base.res_partner_12") cls.eur_currency = cls.env.ref("base.EUR") cls.eur_currency.active = True cls.usd_currency = cls.env.ref("base.USD") cls.usd_currency.active = True cls.main_company = cls.env["res.company"].create( {"name": "Test EUR company", "currency_id": cls.eur_currency.id} ) cls.partner_agrolait.company_id = cls.main_company.id cls.partner_asus.company_id = cls.main_company.id cls.partner_c2c.company_id = cls.main_company.id cls.env.user.write( { "company_ids": [(6, 0, cls.main_company.ids)], "company_id": cls.main_company.id, } ) cls.account_expense = cls.account_model.create( { "user_type_id": cls.env.ref("account.data_account_type_expenses").id, "name": "Test expense account", "code": "TEA", "company_id": cls.main_company.id, } ) cls.account_payable = cls.account_model.create( { "user_type_id": cls.env.ref("account.data_account_type_payable").id, "name": "Test payable account", "code": "TTA", "company_id": cls.main_company.id, "reconcile": True, } ) (cls.partner_asus + cls.partner_c2c + cls.partner_agrolait).with_company( cls.main_company.id ).write({"property_account_payable_id": cls.account_payable.id}) cls.general_journal = cls.journal_model.create( { "name": "General journal", "type": "general", "code": "GEN", "company_id": cls.main_company.id, } ) cls.purchase_journal = cls.journal_model.create( { "name": "Purchase journal", "type": "purchase", "code": "PUR", "company_id": cls.main_company.id, } ) cls.partner_bank = cls.env.ref("account_payment_mode.main_company_iban").copy( { "company_id": cls.main_company.id, "partner_id": cls.main_company.partner_id.id, "bank_id": ( cls.env.ref("account_payment_mode.bank_la_banque_postale").id ), } ) cls.bank_journal = cls.journal_model.create( { "name": "Company Bank journal", "type": "bank", "code": "BNKFB", "bank_account_id": cls.partner_bank.id, "bank_id": cls.partner_bank.bank_id.id, "company_id": cls.main_company.id, "outbound_payment_method_line_ids": [ ( 0, 0, { "payment_method_id": cls.env.ref( "account_banking_sepa_credit_transfer.sepa_credit_transfer" ).id, "payment_account_id": cls.account_expense.id, }, ) ], } ) # update payment mode cls.payment_mode = cls.env.ref( "account_banking_sepa_credit_transfer.payment_mode_outbound_sepa_ct1" ).copy({"company_id": cls.main_company.id}) cls.payment_mode.write( {"bank_account_link": "fixed", "fixed_journal_id": cls.bank_journal.id} ) # Trigger the recompute of account type on res.partner.bank cls.partner_bank_model.search([])._compute_acc_type() def test_no_pain(self): self.payment_mode.payment_method_id.pain_version = False with self.assertRaises(UserError): self.check_eur_currency_sct() def test_pain_001_03(self): self.payment_mode.payment_method_id.pain_version = "pain.001.001.03" self.check_eur_currency_sct() def test_pain_001_04(self): self.payment_mode.payment_method_id.pain_version = "pain.001.001.04" self.check_eur_currency_sct() def test_pain_001_05(self): self.payment_mode.payment_method_id.pain_version = "pain.001.001.05" self.check_eur_currency_sct() def test_pain_003_03(self): self.payment_mode.payment_method_id.pain_version = "pain.001.003.03" self.check_eur_currency_sct() def check_eur_currency_sct(self): invoice1 = self.create_invoice( self.partner_agrolait.id, "account_payment_mode.res_partner_2_iban", self.eur_currency.id, 42.0, "F1341", ) invoice2 = self.create_invoice( self.partner_agrolait.id, "account_payment_mode.res_partner_2_iban", self.eur_currency.id, 12.0, "F1342", ) invoice3 = self.create_invoice( self.partner_agrolait.id, "account_payment_mode.res_partner_2_iban", self.eur_currency.id, 5.0, "A1301", "in_refund", ) invoice4 = self.create_invoice( self.partner_c2c.id, "account_payment_mode.res_partner_12_iban", self.eur_currency.id, 11.0, "I1642", ) invoice5 = self.create_invoice( self.partner_c2c.id, "account_payment_mode.res_partner_12_iban", self.eur_currency.id, 41.0, "I1643", ) for inv in [invoice1, invoice2, invoice3, invoice4, invoice5]: action = inv.create_account_payment_line() self.assertEqual(action["res_model"], "account.payment.order") self.payment_order = self.payment_order_model.browse(action["res_id"]) self.assertEqual(self.payment_order.payment_type, "outbound") self.assertEqual(self.payment_order.payment_mode_id, self.payment_mode) self.assertEqual(self.payment_order.journal_id, self.bank_journal) pay_lines = self.payment_line_model.search( [ ("partner_id", "=", self.partner_agrolait.id), ("order_id", "=", self.payment_order.id), ] ) self.assertEqual(len(pay_lines), 3) agrolait_pay_line1 = pay_lines[0] self.assertEqual(agrolait_pay_line1.currency_id, self.eur_currency) self.assertEqual(agrolait_pay_line1.partner_bank_id, invoice1.partner_bank_id) self.assertEqual( agrolait_pay_line1.currency_id.compare_amounts( agrolait_pay_line1.amount_currency, 42 ), 0, ) self.assertEqual(agrolait_pay_line1.communication_type, "normal") self.assertEqual(agrolait_pay_line1.communication, "F1341") self.payment_order.draft2open() self.assertEqual(self.payment_order.state, "open") self.assertEqual(self.payment_order.sepa, True) self.assertTrue(self.payment_order.payment_ids) agrolait_bank_line = self.payment_order.payment_ids[0] self.assertEqual(agrolait_bank_line.currency_id, self.eur_currency) self.assertEqual( agrolait_bank_line.currency_id.compare_amounts( agrolait_bank_line.amount, 49.0 ), 0, ) self.assertEqual(agrolait_bank_line.payment_reference, "F1341-F1342-A1301") self.assertEqual(agrolait_bank_line.partner_bank_id, invoice1.partner_bank_id) action = self.payment_order.open2generated() self.assertEqual(self.payment_order.state, "generated") self.assertEqual(action["res_model"], "ir.attachment") attachment = self.attachment_model.browse(action["res_id"]) self.assertEqual(attachment.name[-4:], ".xml") xml_file = base64.b64decode(attachment.datas) xml_root = etree.fromstring(xml_file) namespaces = xml_root.nsmap namespaces["p"] = xml_root.nsmap[None] namespaces.pop(None) pay_method_xpath = xml_root.xpath("//p:PmtInf/p:PmtMtd", namespaces=namespaces) self.assertEqual(pay_method_xpath[0].text, "TRF") sepa_xpath = xml_root.xpath( "//p:PmtInf/p:PmtTpInf/p:SvcLvl/p:Cd", namespaces=namespaces ) self.assertEqual(sepa_xpath[0].text, "SEPA") debtor_acc_xpath = xml_root.xpath( "//p:PmtInf/p:DbtrAcct/p:Id/p:IBAN", namespaces=namespaces ) self.assertEqual( debtor_acc_xpath[0].text, self.payment_order.company_partner_bank_id.sanitized_acc_number, ) self.payment_order.generated2uploaded() self.assertEqual(self.payment_order.state, "uploaded") for inv in [invoice1, invoice2, invoice3, invoice4, invoice5]: self.assertEqual(inv.state, "posted") self.assertEqual( inv.currency_id.compare_amounts(inv.amount_residual, 0.0), 0, ) return def test_usd_currency_sct(self): invoice1 = self.create_invoice( self.partner_asus.id, "account_payment_mode.res_partner_2_iban", self.usd_currency.id, 2042.0, "Inv9032", ) invoice2 = self.create_invoice( self.partner_asus.id, "account_payment_mode.res_partner_2_iban", self.usd_currency.id, 1012.0, "Inv9033", ) for inv in [invoice1, invoice2]: action = inv.create_account_payment_line() self.assertEqual(action["res_model"], "account.payment.order") self.payment_order = self.payment_order_model.browse(action["res_id"]) self.assertEqual(self.payment_order.payment_type, "outbound") self.assertEqual(self.payment_order.payment_mode_id, self.payment_mode) self.assertEqual(self.payment_order.journal_id, self.bank_journal) pay_lines = self.payment_line_model.search( [ ("partner_id", "=", self.partner_asus.id), ("order_id", "=", self.payment_order.id), ] ) self.assertEqual(len(pay_lines), 2) asus_pay_line1 = pay_lines[0] self.assertEqual(asus_pay_line1.currency_id, self.usd_currency) self.assertEqual(asus_pay_line1.partner_bank_id, invoice1.partner_bank_id) self.assertEqual( asus_pay_line1.currency_id.compare_amounts( asus_pay_line1.amount_currency, 2042 ), 0, ) self.assertEqual(asus_pay_line1.communication_type, "normal") self.assertEqual(asus_pay_line1.communication, "Inv9032") self.payment_order.draft2open() self.assertEqual(self.payment_order.state, "open") self.assertEqual(self.payment_order.sepa, False) self.assertEqual(self.payment_order.payment_count, 1) asus_bank_line = self.payment_order.payment_ids[0] self.assertEqual(asus_bank_line.currency_id, self.usd_currency) self.assertEqual( asus_bank_line.currency_id.compare_amounts(asus_bank_line.amount, 3054.0), 0, ) self.assertEqual(asus_bank_line.payment_reference, "Inv9032-Inv9033") self.assertEqual(asus_bank_line.partner_bank_id, invoice1.partner_bank_id) action = self.payment_order.open2generated() self.assertEqual(self.payment_order.state, "generated") self.assertEqual(action["res_model"], "ir.attachment") attachment = self.attachment_model.browse(action["res_id"]) self.assertEqual(attachment.name[-4:], ".xml") xml_file = base64.b64decode(attachment.datas) xml_root = etree.fromstring(xml_file) namespaces = xml_root.nsmap namespaces["p"] = xml_root.nsmap[None] namespaces.pop(None) pay_method_xpath = xml_root.xpath("//p:PmtInf/p:PmtMtd", namespaces=namespaces) self.assertEqual(pay_method_xpath[0].text, "TRF") sepa_xpath = xml_root.xpath( "//p:PmtInf/p:PmtTpInf/p:SvcLvl/p:Cd", namespaces=namespaces ) self.assertEqual(len(sepa_xpath), 0) debtor_acc_xpath = xml_root.xpath( "//p:PmtInf/p:DbtrAcct/p:Id/p:IBAN", namespaces=namespaces ) self.assertEqual( debtor_acc_xpath[0].text, self.payment_order.company_partner_bank_id.sanitized_acc_number, ) self.payment_order.generated2uploaded() self.assertEqual(self.payment_order.state, "uploaded") for inv in [invoice1, invoice2]: self.assertEqual(inv.state, "posted") self.assertEqual( inv.currency_id.compare_amounts(inv.amount_residual, 0.0), 0, ) return @classmethod def create_invoice( cls, partner_id, partner_bank_xmlid, currency_id, price_unit, reference, move_type="in_invoice", ): partner_bank = cls.env.ref(partner_bank_xmlid) partner_bank.write({"company_id": False}) data = { "partner_id": partner_id, "reference_type": "none", "ref": reference, "currency_id": currency_id, "invoice_date": time.strftime("%Y-%m-%d"), "move_type": move_type, "payment_mode_id": cls.payment_mode.id, "partner_bank_id": partner_bank.id, "company_id": cls.main_company.id, "invoice_line_ids": [], } line_data = { "name": "Great service", "account_id": cls.account_expense.id, "price_unit": price_unit, "quantity": 1, } data["invoice_line_ids"].append((0, 0, line_data)) inv = cls.env["account.move"].create(data) inv.action_post() return inv
40.488
15,183
639
py
PYTHON
15.0
# Copyright 2017-2020 Akretion - Alexis de Lattre <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class AccountPaymentLine(models.Model): _inherit = "account.payment.line" # Local_instrument 'INST' used for instant credit transfers # which will begin on November 21st 2017, cf # https://www.europeanpaymentscouncil.eu/document-library/ # rulebooks/2017-sepa-instant-credit-transfer-rulebook local_instrument = fields.Selection( selection_add=[("INST", "Instant Transfer")], ondelete={"INST": "set null"}, )
37.588235
639
9,364
py
PYTHON
15.0
# Copyright 2010-2020 Akretion (www.akretion.com) # Copyright 2014-2022 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from lxml import etree from odoo import _, fields, models from odoo.exceptions import UserError class AccountPaymentOrder(models.Model): _inherit = "account.payment.order" def generate_payment_file(self): # noqa: C901 """Creates the SEPA Credit Transfer file. That's the important code!""" self.ensure_one() if self.payment_method_id.code != "sepa_credit_transfer": return super().generate_payment_file() pain_flavor = self.payment_method_id.pain_version # We use pain_flavor.startswith('pain.001.001.xx') # to support country-specific extensions such as # pain.001.001.03.ch.02 (cf l10n_ch_sepa) if not pain_flavor: raise UserError(_("PAIN version '%s' is not supported.") % pain_flavor) if pain_flavor.startswith("pain.001.001.02"): bic_xml_tag = "BIC" name_maxsize = 70 root_xml_tag = "pain.001.001.02" elif pain_flavor.startswith("pain.001.001.03"): bic_xml_tag = "BIC" # size 70 -> 140 for <Nm> with pain.001.001.03 # BUT the European Payment Council, in the document # "SEPA Credit Transfer Scheme Customer-to-bank # Implementation guidelines" v6.0 available on # http://www.europeanpaymentscouncil.eu/knowledge_bank.cfm # says that 'Nm' should be limited to 70 # so we follow the "European Payment Council" # and we put 70 and not 140 name_maxsize = 70 root_xml_tag = "CstmrCdtTrfInitn" elif pain_flavor.startswith("pain.001.001.04"): bic_xml_tag = "BICFI" name_maxsize = 140 root_xml_tag = "CstmrCdtTrfInitn" elif pain_flavor.startswith("pain.001.001.05"): bic_xml_tag = "BICFI" name_maxsize = 140 root_xml_tag = "CstmrCdtTrfInitn" # added pain.001.003.03 for German Banks # it is not in the offical ISO 20022 documentations, but nearly all # german banks are working with this instead 001.001.03 elif pain_flavor == "pain.001.003.03": bic_xml_tag = "BIC" name_maxsize = 70 root_xml_tag = "CstmrCdtTrfInitn" else: raise UserError(_("PAIN version '%s' is not supported.") % pain_flavor) xsd_file = self.payment_method_id.get_xsd_file_path() gen_args = { "bic_xml_tag": bic_xml_tag, "name_maxsize": name_maxsize, "convert_to_ascii": self.payment_method_id.convert_to_ascii, "payment_method": "TRF", "file_prefix": "sct_", "pain_flavor": pain_flavor, "pain_xsd_file": xsd_file, } nsmap = self.generate_pain_nsmap() attrib = self.generate_pain_attrib() xml_root = etree.Element("Document", nsmap=nsmap, attrib=attrib) pain_root = etree.SubElement(xml_root, root_xml_tag) # A. Group header header = self.generate_group_header_block(pain_root, gen_args) group_header, nb_of_transactions_a, control_sum_a = header transactions_count_a = 0 amount_control_sum_a = 0.0 lines_per_group = {} # key = (requested_date, priority, local_instrument, categ_purpose) # values = list of lines as object for line in self.payment_ids: payment_line = line.payment_line_ids[:1] priority = payment_line.priority local_instrument = payment_line.local_instrument categ_purpose = payment_line.category_purpose # The field line.date is the requested payment date # taking into account the 'date_prefered' setting # cf account_banking_payment_export/models/account_payment.py # in the inherit of action_open() key = (line.date, priority, local_instrument, categ_purpose) if key in lines_per_group: lines_per_group[key].append(line) else: lines_per_group[key] = [line] for (requested_date, priority, local_instrument, categ_purpose), lines in list( lines_per_group.items() ): # B. Payment info requested_date = fields.Date.to_string(requested_date) ( payment_info, nb_of_transactions_b, control_sum_b, ) = self.generate_start_payment_info_block( pain_root, "self.name + '-' " "+ requested_date.replace('-', '') + '-' + priority + " "'-' + local_instrument + '-' + category_purpose", priority, local_instrument, categ_purpose, False, requested_date, { "self": self, "priority": priority, "requested_date": requested_date, "local_instrument": local_instrument or "NOinstr", "category_purpose": categ_purpose or "NOcateg", }, gen_args, ) self.generate_party_block( payment_info, "Dbtr", "B", self.company_partner_bank_id, gen_args ) charge_bearer = etree.SubElement(payment_info, "ChrgBr") if self.sepa: charge_bearer_text = "SLEV" else: charge_bearer_text = self.charge_bearer charge_bearer.text = charge_bearer_text transactions_count_b = 0 amount_control_sum_b = 0.0 for line in lines: transactions_count_a += 1 transactions_count_b += 1 # C. Credit Transfer Transaction Info credit_transfer_transaction_info = etree.SubElement( payment_info, "CdtTrfTxInf" ) payment_identification = etree.SubElement( credit_transfer_transaction_info, "PmtId" ) instruction_identification = etree.SubElement( payment_identification, "InstrId" ) instruction_identification.text = self._prepare_field( "Instruction Identification", "str(line.move_id.id)", {"line": line}, 35, gen_args=gen_args, ) end2end_identification = etree.SubElement( payment_identification, "EndToEndId" ) end2end_identification.text = self._prepare_field( "End to End Identification", "str(line.move_id.id)", {"line": line}, 35, gen_args=gen_args, ) currency_name = self._prepare_field( "Currency Code", "line.currency_id.name", {"line": line}, 3, gen_args=gen_args, ) amount = etree.SubElement(credit_transfer_transaction_info, "Amt") instructed_amount = etree.SubElement( amount, "InstdAmt", Ccy=currency_name ) instructed_amount.text = "%.2f" % line.amount amount_control_sum_a += line.amount amount_control_sum_b += line.amount if not line.partner_bank_id: raise UserError( _( "Bank account is missing on the bank payment line " "of partner '{partner}' (reference '{reference}')." ).format(partner=line.partner_id.name, reference=line.name) ) self.generate_party_block( credit_transfer_transaction_info, "Cdtr", "C", line.partner_bank_id, gen_args, line, ) line_purpose = line.payment_line_ids[:1].purpose if line_purpose: purpose = etree.SubElement(credit_transfer_transaction_info, "Purp") etree.SubElement(purpose, "Cd").text = line_purpose self.generate_remittance_info_block( credit_transfer_transaction_info, line, gen_args ) if not pain_flavor.startswith("pain.001.001.02"): nb_of_transactions_b.text = str(transactions_count_b) control_sum_b.text = "%.2f" % amount_control_sum_b if not pain_flavor.startswith("pain.001.001.02"): nb_of_transactions_a.text = str(transactions_count_a) control_sum_a.text = "%.2f" % amount_control_sum_a else: nb_of_transactions_a.text = str(transactions_count_a) control_sum_a.text = "%.2f" % amount_control_sum_a return self.finalize_sepa_file_creation(xml_root, gen_args)
44.590476
9,364
1,604
py
PYTHON
15.0
# Copyright 2016-2020 Akretion (Alexis de Lattre <[email protected]>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class AccountPaymentMethod(models.Model): _inherit = "account.payment.method" pain_version = fields.Selection( selection_add=[ ("pain.001.001.02", "pain.001.001.02"), ("pain.001.001.03", "pain.001.001.03 (recommended for credit transfer)"), ("pain.001.001.04", "pain.001.001.04"), ("pain.001.001.05", "pain.001.001.05"), ("pain.001.003.03", "pain.001.003.03"), ], ondelete={ "pain.001.001.02": "set null", "pain.001.001.03": "set null", "pain.001.001.04": "set null", "pain.001.001.05": "set null", "pain.001.003.03": "set null", }, ) def get_xsd_file_path(self): self.ensure_one() if self.pain_version in [ "pain.001.001.02", "pain.001.001.03", "pain.001.001.04", "pain.001.001.05", "pain.001.003.03", ]: path = ( "account_banking_sepa_credit_transfer/data/%s.xsd" % self.pain_version ) return path return super().get_xsd_file_path() @api.model def _get_payment_method_information(self): res = super()._get_payment_method_information() res["sepa_credit_transfer"] = { "mode": "multi", "domain": [("type", "=", "bank")], } return res
32.734694
1,604
787
py
PYTHON
15.0
import logging from odoo.tools import sql logger = logging.getLogger(__name__) def pre_init_hook(cr): """Prepare new payment_mode fields. Add columns to avoid Memory error on an existing Odoo instance with lots of data. The payment_mode_id fields are introduced by this module and computed only from each other or the also newly introduced supplier_payment_mode_id and customer_payment_mode_id on res.partner, so they can stay NULL, nothing to compute. """ if not sql.column_exists(cr, "account_move", "payment_mode_id"): sql.create_column(cr, "account_move", "payment_mode_id", "int4") if not sql.column_exists(cr, "account_move_line", "payment_mode_id"): sql.create_column(cr, "account_move_line", "payment_mode_id", "int4")
39.35
787
1,042
py
PYTHON
15.0
# Copyright 2014 Akretion - Alexis de Lattre <[email protected]> # Copyright 2014 Tecnativa - Pedro M. Baeza # Copyright 2018 Tecnativa - Carlos Dauden # Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Account Payment Partner", "version": "15.0.1.3.1", "category": "Banking addons", "license": "AGPL-3", "summary": "Adds payment mode on partners and invoices", "author": "Akretion, Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/bank-payment", "development_status": "Mature", "depends": ["account_payment_mode"], "data": [ "views/res_partner_view.xml", "views/account_move_view.xml", "views/account_move_line.xml", "views/account_payment_mode.xml", "views/report_invoice.xml", "reports/account_invoice_report_view.xml", ], "demo": ["demo/partner_demo.xml"], "installable": True, "pre_init_hook": "pre_init_hook", }
37.142857
1,040
22,832
py
PYTHON
15.0
# Copyright 2017 ForgeFlow S.L. # Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import _, fields from odoo.exceptions import UserError, ValidationError from odoo.fields import Date from odoo.tests.common import Form, TransactionCase class TestAccountPaymentPartner(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) cls.res_users_model = cls.env["res.users"] cls.move_model = cls.env["account.move"] cls.journal_model = cls.env["account.journal"] cls.payment_mode_model = cls.env["account.payment.mode"] cls.partner_bank_model = cls.env["res.partner.bank"] # Refs cls.company = cls.env.ref("base.main_company") cls.acct_type_payable = cls.env.ref("account.data_account_type_payable") cls.acct_type_receivable = cls.env.ref("account.data_account_type_receivable") cls.acct_type_expenses = cls.env.ref("account.data_account_type_expenses") cls.company_2 = cls.env["res.company"].create({"name": "Company 2"}) charts = cls.env["account.chart.template"].search([]) if charts: cls.chart = charts[0] else: raise ValidationError(_("No Chart of Account Template has been defined !")) old_company = cls.env.user.company_id cls.env.user.company_id = cls.company_2.id cls.env.ref("base.user_admin").company_ids = [(4, cls.company_2.id)] cls.chart.try_loading() cls.env.user.company_id = old_company.id # refs cls.manual_out = cls.env.ref("account.account_payment_method_manual_out") cls.manual_out.bank_account_required = True cls.manual_in = cls.env.ref("account.account_payment_method_manual_in") cls.journal_sale = cls.env["account.journal"].create( { "name": "Test Sales Journal", "code": "tSAL", "type": "sale", "company_id": cls.company.id, } ) cls.journal_purchase = cls.env["account.journal"].create( { "name": "Test Purchases Journal", "code": "tPUR", "type": "purchase", "company_id": cls.company.id, } ) cls.journal_c1 = cls.journal_model.create( { "name": "J1", "code": "J1", "type": "bank", "company_id": cls.company.id, "bank_acc_number": "123456", } ) cls.journal_c2 = cls.journal_model.create( { "name": "J2", "code": "J2", "type": "bank", "company_id": cls.company_2.id, "bank_acc_number": "552344", } ) cls.supplier_payment_mode = cls.payment_mode_model.create( { "name": "Suppliers Bank 1", "bank_account_link": "variable", "payment_method_id": cls.manual_out.id, "show_bank_account_from_journal": True, "company_id": cls.company.id, "fixed_journal_id": cls.journal_c1.id, "variable_journal_ids": [(6, 0, [cls.journal_c1.id])], } ) cls.supplier_payment_mode_c2 = cls.payment_mode_model.create( { "name": "Suppliers Bank 2", "bank_account_link": "variable", "payment_method_id": cls.manual_out.id, "company_id": cls.company_2.id, "fixed_journal_id": cls.journal_c2.id, "variable_journal_ids": [(6, 0, [cls.journal_c2.id])], } ) cls.customer_payment_mode = cls.payment_mode_model.create( { "name": "Customers to Bank 1", "bank_account_link": "variable", "payment_method_id": cls.manual_in.id, "company_id": cls.company.id, "fixed_journal_id": cls.journal_c1.id, "refund_payment_mode_id": cls.supplier_payment_mode.id, "variable_journal_ids": [(6, 0, [cls.journal_c1.id])], } ) cls.supplier_payment_mode.write( {"refund_payment_mode_id": cls.customer_payment_mode.id} ) cls.customer = ( cls.env["res.partner"] .with_company(cls.company.id) .create( { "name": "Test customer", "customer_payment_mode_id": cls.customer_payment_mode, } ) ) cls.supplier = ( cls.env["res.partner"] .with_company(cls.company.id) .create( { "name": "Test supplier", "supplier_payment_mode_id": cls.supplier_payment_mode, } ) ) cls.supplier_bank = cls.env["res.partner.bank"].create( { "acc_number": "5345345", "partner_id": cls.supplier.id, "company_id": cls.company.id, } ) cls.supplier_bank_2 = cls.env["res.partner.bank"].create( { "acc_number": "3452342", "partner_id": cls.supplier.id, "company_id": cls.company_2.id, } ) cls.supplier.with_company( cls.company_2.id ).supplier_payment_mode_id = cls.supplier_payment_mode_c2 cls.invoice_account = cls.env["account.account"].search( [ ("user_type_id", "=", cls.acct_type_payable.id), ("company_id", "=", cls.company.id), ], limit=1, ) cls.invoice_line_account = cls.env["account.account"].search( [ ("user_type_id", "=", cls.acct_type_expenses.id), ("company_id", "=", cls.company.id), ], limit=1, ) cls.journal_bank = cls.env["res.partner.bank"].create( { "acc_number": "GB95LOYD87430237296288", "partner_id": cls.env.user.company_id.partner_id.id, } ) cls.journal = cls.env["account.journal"].create( { "name": "BANK TEST", "code": "TEST", "type": "bank", "bank_account_id": cls.journal_bank.id, } ) cls.supplier_invoice = cls.move_model.create( { "partner_id": cls.supplier.id, "invoice_date": fields.Date.today(), "move_type": "in_invoice", "journal_id": cls.journal_purchase.id, } ) def _create_invoice(self, default_move_type, partner): move_form = Form( self.env["account.move"].with_context(default_move_type=default_move_type) ) move_form.partner_id = partner move_form.invoice_date = Date.today() with move_form.invoice_line_ids.new() as line_form: line_form.product_id = self.env.ref("product.product_product_4") line_form.name = "product that cost 100" line_form.quantity = 1.0 line_form.price_unit = 100.0 line_form.account_id = self.invoice_line_account return move_form.save() def test_create_partner(self): customer = ( self.env["res.partner"] .with_company(self.company.id) .create( { "name": "Test customer", "customer_payment_mode_id": self.customer_payment_mode, } ) ) self.assertEqual( customer.with_company(self.company.id).customer_payment_mode_id, self.customer_payment_mode, ) self.assertEqual( customer.with_company(self.company_2.id).customer_payment_mode_id, self.payment_mode_model, ) def test_partner_id_changes_compute_partner_bank(self): # Test _compute_partner_bank is executed when partner_id changes move_form = Form( self.env["account.move"].with_context(default_move_type="out_invoice") ) self.assertFalse(move_form.partner_bank_id) move_form.partner_id = self.customer self.assertEqual(move_form.payment_mode_id, self.customer_payment_mode) self.assertFalse(move_form.partner_bank_id) def test_out_invoice_onchange(self): # Test the onchange methods in invoice invoice = self.move_model.new( { "partner_id": self.customer.id, "move_type": "out_invoice", "company_id": self.company.id, } ) self.assertEqual(invoice.payment_mode_id, self.customer_payment_mode) invoice.company_id = self.company_2 self.assertEqual(invoice.payment_mode_id, self.payment_mode_model) invoice.payment_mode_id = False self.assertFalse(invoice.partner_bank_id) def test_in_invoice_onchange(self): # Test the onchange methods in invoice self.manual_out.bank_account_required = True invoice = self.move_model.new( { "partner_id": self.supplier.id, "move_type": "in_invoice", "invoice_date": fields.Date.today(), "company_id": self.company.id, } ) self.assertEqual(invoice.payment_mode_id, self.supplier_payment_mode) self.assertEqual(invoice.partner_bank_id, self.supplier_bank) invoice.company_id = self.company_2 self.assertEqual(invoice.payment_mode_id, self.supplier_payment_mode_c2) self.assertEqual(invoice.partner_bank_id, self.supplier_bank_2) invoice.payment_mode_id = self.supplier_payment_mode self.assertTrue(invoice.partner_bank_id) self.manual_out.bank_account_required = False invoice.payment_mode_id = self.supplier_payment_mode_c2 self.assertFalse(invoice.partner_bank_id) invoice.partner_id = False self.assertEqual(invoice.payment_mode_id, self.supplier_payment_mode_c2) self.assertEqual(invoice.partner_bank_id, self.partner_bank_model) def test_invoice_create_in_invoice(self): invoice = self._create_invoice( default_move_type="in_invoice", partner=self.supplier ) invoice.action_post() aml = invoice.line_ids.filtered( lambda l: l.account_id.user_type_id == self.acct_type_payable ) self.assertEqual(invoice.payment_mode_id, aml[0].payment_mode_id) # Test payment mode change on aml mode = self.supplier_payment_mode.copy() aml.payment_mode_id = mode self.assertEqual(invoice.payment_mode_id, mode) # Test payment mode editability on account move self.assertFalse(invoice.has_reconciled_items) invoice.payment_mode_id = self.supplier_payment_mode self.assertEqual(aml.payment_mode_id, self.supplier_payment_mode) def test_invoice_create_out_invoice(self): invoice = self._create_invoice( default_move_type="out_invoice", partner=self.customer ) invoice.action_post() aml = invoice.line_ids.filtered( lambda l: l.account_id.user_type_id == self.acct_type_receivable ) self.assertEqual(invoice.payment_mode_id, aml[0].payment_mode_id) def test_invoice_create_out_refund(self): self.manual_out.bank_account_required = False invoice = self._create_invoice( default_move_type="out_refund", partner=self.customer ) invoice.action_post() self.assertEqual( invoice.payment_mode_id, self.customer.customer_payment_mode_id.refund_payment_mode_id, ) def test_invoice_create_in_refund(self): self.manual_in.bank_account_required = False invoice = self._create_invoice( default_move_type="in_refund", partner=self.supplier ) invoice.action_post() self.assertEqual( invoice.payment_mode_id, self.supplier.supplier_payment_mode_id.refund_payment_mode_id, ) def test_invoice_constrains(self): with self.assertRaises(UserError): self.move_model.create( { "partner_id": self.supplier.id, "move_type": "in_invoice", "invoice_date": fields.Date.today(), "company_id": self.company.id, "payment_mode_id": self.supplier_payment_mode_c2.id, } ) def test_payment_mode_constrains_01(self): self.move_model.create( { "partner_id": self.supplier.id, "move_type": "in_invoice", "invoice_date": fields.Date.today(), "company_id": self.company.id, } ) with self.assertRaises(UserError): self.supplier_payment_mode.company_id = self.company_2 def test_payment_mode_constrains_02(self): self.move_model.create( { "date": fields.Date.today(), "journal_id": self.journal_sale.id, "name": "/", "ref": "reference", "state": "draft", "invoice_line_ids": [ ( 0, 0, { "account_id": self.invoice_account.id, "credit": 1000, "debit": 0, "name": "Test", "ref": "reference", }, ), ( 0, 0, { "account_id": self.invoice_line_account.id, "credit": 0, "debit": 1000, "name": "Test", "ref": "reference", }, ), ], } ) with self.assertRaises(UserError): self.supplier_payment_mode.company_id = self.company_2 def test_invoice_in_refund(self): invoice = self._create_invoice( default_move_type="in_invoice", partner=self.supplier ) invoice.partner_bank_id = False invoice.action_post() # Lets create a refund invoice for invoice_1. # I refund the invoice Using Refund Button. refund_invoice_wizard = ( self.env["account.move.reversal"] .with_context( **{ "active_ids": [invoice.id], "active_id": invoice.id, "active_model": "account.move", } ) .create( { "refund_method": "refund", "reason": "reason test create", "journal_id": invoice.journal_id.id, } ) ) refund_invoice = self.move_model.browse( refund_invoice_wizard.reverse_moves()["res_id"] ) self.assertEqual( refund_invoice.payment_mode_id, invoice.payment_mode_id.refund_payment_mode_id, ) self.assertEqual(refund_invoice.partner_bank_id, invoice.partner_bank_id) def test_invoice_out_refund(self): invoice = self._create_invoice( default_move_type="out_invoice", partner=self.customer ) invoice.partner_bank_id = False invoice.action_post() # Lets create a refund invoice for invoice_1. # I refund the invoice Using Refund Button. refund_invoice_wizard = ( self.env["account.move.reversal"] .with_context( **{ "active_ids": [invoice.id], "active_id": invoice.id, "active_model": "account.move", } ) .create( { "refund_method": "refund", "reason": "reason test create", "journal_id": invoice.journal_id.id, } ) ) refund_invoice = self.move_model.browse( refund_invoice_wizard.reverse_moves()["res_id"] ) self.assertEqual( refund_invoice.payment_mode_id, invoice.payment_mode_id.refund_payment_mode_id, ) self.assertEqual(refund_invoice.partner_bank_id, invoice.partner_bank_id) def test_partner(self): self.customer.write({"customer_payment_mode_id": self.customer_payment_mode.id}) self.assertEqual( self.customer.customer_payment_mode_id, self.customer_payment_mode ) def test_partner_onchange(self): customer_invoice = self.move_model.create( {"partner_id": self.customer.id, "move_type": "out_invoice"} ) self.assertEqual(customer_invoice.payment_mode_id, self.customer_payment_mode) self.assertEqual(self.supplier_invoice.partner_bank_id, self.supplier_bank) vals = {"partner_id": self.customer.id, "move_type": "out_refund"} invoice = self.move_model.new(vals) self.assertEqual(invoice.payment_mode_id, self.supplier_payment_mode) vals = {"partner_id": self.supplier.id, "move_type": "in_refund"} invoice = self.move_model.new(vals) self.assertEqual(invoice.payment_mode_id, self.customer_payment_mode) vals = {"partner_id": False, "move_type": "out_invoice"} invoice = self.move_model.new(vals) self.assertFalse(invoice.payment_mode_id) vals = {"partner_id": False, "move_type": "out_refund"} invoice = self.move_model.new(vals) self.assertFalse(invoice.partner_bank_id) vals = {"partner_id": False, "move_type": "in_invoice"} invoice = self.move_model.new(vals) self.assertFalse(invoice.partner_bank_id) vals = {"partner_id": False, "move_type": "in_refund"} invoice = self.move_model.new(vals) self.assertFalse(invoice.partner_bank_id) def test_onchange_payment_mode_id(self): mode = self.supplier_payment_mode mode.payment_method_id.bank_account_required = True self.supplier_invoice.partner_bank_id = self.supplier_bank.id self.supplier_invoice.payment_mode_id = mode.id self.assertEqual(self.supplier_invoice.partner_bank_id, self.supplier_bank) mode.payment_method_id.bank_account_required = False self.assertEqual(self.supplier_invoice.partner_bank_id, self.supplier_bank) self.supplier_invoice.payment_mode_id = False self.assertFalse(self.supplier_invoice.partner_bank_id) def test_print_report(self): self.supplier_invoice.partner_bank_id = self.supplier_bank.id report = self.env.ref("account.account_invoices") res = str(report._render_qweb_html(self.supplier_invoice.ids)[0]) self.assertIn(self.supplier_bank.acc_number, res) payment_mode = self.supplier_payment_mode payment_mode.show_bank_account_from_journal = True self.supplier_invoice.payment_mode_id = payment_mode.id self.supplier_invoice.partner_bank_id = False res = str(report._render_qweb_html(self.supplier_invoice.ids)[0]) self.assertIn(self.journal_c1.bank_acc_number, res) payment_mode.bank_account_link = "variable" payment_mode.variable_journal_ids = [(6, 0, self.journal.ids)] res = str(report._render_qweb_html(self.supplier_invoice.ids)[0]) self.assertIn(self.journal_bank.acc_number, res) def test_filter_type_domain(self): in_invoice = self.move_model.create( { "partner_id": self.supplier.id, "move_type": "in_invoice", "invoice_date": fields.Date.today(), "journal_id": self.journal_purchase.id, } ) self.assertEqual(in_invoice.payment_mode_filter_type_domain, "outbound") self.assertEqual( in_invoice.partner_bank_filter_type_domain, in_invoice.commercial_partner_id ) out_refund = self.move_model.create( { "partner_id": self.customer.id, "move_type": "out_refund", "journal_id": self.journal_sale.id, } ) self.assertEqual(out_refund.payment_mode_filter_type_domain, "outbound") self.assertEqual( out_refund.partner_bank_filter_type_domain, out_refund.commercial_partner_id ) in_refund = self.move_model.create( { "partner_id": self.supplier.id, "move_type": "in_refund", "journal_id": self.journal_purchase.id, } ) self.assertEqual(in_refund.payment_mode_filter_type_domain, "inbound") self.assertEqual( in_refund.partner_bank_filter_type_domain, in_refund.bank_partner_id ) out_invoice = self.move_model.create( { "partner_id": self.customer.id, "move_type": "out_invoice", "journal_id": self.journal_sale.id, } ) self.assertEqual(out_invoice.payment_mode_filter_type_domain, "inbound") self.assertEqual( out_invoice.partner_bank_filter_type_domain, out_invoice.bank_partner_id ) def test_account_move_payment_mode_id_default(self): payment_mode = self.env.ref("account_payment_mode.payment_mode_inbound_dd1") field = self.env["ir.model.fields"].search( [ ("model_id.model", "=", self.move_model._name), ("name", "=", "payment_mode_id"), ] ) move_form = Form(self.move_model.with_context(default_type="out_invoice")) self.assertFalse(move_form.payment_mode_id) self.env["ir.default"].create( {"field_id": field.id, "json_value": payment_mode.id} ) move_form = Form(self.move_model.with_context(default_type="out_invoice")) self.assertEqual(move_form.payment_mode_id, payment_mode)
38.694915
22,830
7,268
py
PYTHON
15.0
# Copyright 2014-16 Akretion - Alexis de Lattre <[email protected]> # Copyright 2014 Serv. Tecnol. Avanzados - Pedro M. Baeza # Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class AccountMove(models.Model): _inherit = "account.move" payment_mode_filter_type_domain = fields.Char( compute="_compute_payment_mode_filter_type_domain" ) partner_bank_filter_type_domain = fields.Many2one( comodel_name="res.partner", compute="_compute_partner_bank_filter_type_domain" ) payment_mode_id = fields.Many2one( comodel_name="account.payment.mode", compute="_compute_payment_mode_id", store=True, ondelete="restrict", readonly=False, check_company=True, tracking=True, ) bank_account_required = fields.Boolean( related="payment_mode_id.payment_method_id.bank_account_required", readonly=True ) partner_bank_id = fields.Many2one( compute="_compute_partner_bank_id", store=True, ondelete="restrict", readonly=False, ) has_reconciled_items = fields.Boolean( help="Technical field for supporting the editability of the payment mode", compute="_compute_has_reconciled_items", ) @api.depends("move_type") def _compute_payment_mode_filter_type_domain(self): for move in self: if move.move_type in ("out_invoice", "in_refund"): move.payment_mode_filter_type_domain = "inbound" elif move.move_type in ("in_invoice", "out_refund"): move.payment_mode_filter_type_domain = "outbound" else: move.payment_mode_filter_type_domain = False @api.depends("partner_id", "move_type") def _compute_partner_bank_filter_type_domain(self): for move in self: if move.move_type in ("out_invoice", "in_refund"): move.partner_bank_filter_type_domain = move.bank_partner_id elif move.move_type in ("in_invoice", "out_refund"): move.partner_bank_filter_type_domain = move.commercial_partner_id else: move.partner_bank_filter_type_domain = False @api.depends("partner_id", "company_id") def _compute_payment_mode_id(self): for move in self: if move.company_id and move.payment_mode_id.company_id != move.company_id: move.payment_mode_id = False if move.partner_id: partner = move.with_company(move.company_id.id).partner_id if move.move_type == "in_invoice": move.payment_mode_id = partner.supplier_payment_mode_id elif move.move_type == "out_invoice": move.payment_mode_id = partner.customer_payment_mode_id elif ( move.move_type in ["out_refund", "in_refund"] and move.reversed_entry_id ): move.payment_mode_id = ( move.reversed_entry_id.payment_mode_id.refund_payment_mode_id ) elif not move.reversed_entry_id: if move.move_type == "out_refund": move.payment_mode_id = ( partner.customer_payment_mode_id.refund_payment_mode_id ) elif move.move_type == "in_refund": move.payment_mode_id = ( partner.supplier_payment_mode_id.refund_payment_mode_id ) @api.depends("line_ids.matched_credit_ids", "line_ids.matched_debit_ids") def _compute_has_reconciled_items(self): for record in self: lines_to_consider = record.line_ids.filtered( lambda x: x.account_id.internal_type in ("receivable", "payable") ) record.has_reconciled_items = bool( lines_to_consider.matched_credit_ids + lines_to_consider.matched_debit_ids ) @api.onchange("partner_id") def _onchange_partner_id(self): """Force compute because the onchange chain doesn't call ``_compute_partner_bank``. """ res = super()._onchange_partner_id() self._compute_partner_bank_id() return res @api.depends("partner_id", "payment_mode_id") def _compute_partner_bank_id(self): for move in self: # No bank account assignation is done for out_invoice as this is only # needed for printing purposes and it can conflict with # SEPA direct debit payments. Current report prints it. def get_bank_id(): return fields.first( move.commercial_partner_id.bank_ids.filtered( lambda b: b.company_id == move.company_id or not b.company_id ) ) bank_id = False if move.partner_id: pay_mode = move.payment_mode_id if move.move_type == "in_invoice": if ( pay_mode and pay_mode.payment_type == "outbound" and pay_mode.payment_method_id.bank_account_required and move.commercial_partner_id.bank_ids ): bank_id = get_bank_id() move.partner_bank_id = bank_id def _reverse_move_vals(self, default_values, cancel=True): move_vals = super()._reverse_move_vals(default_values, cancel=cancel) move_vals["payment_mode_id"] = self.payment_mode_id.refund_payment_mode_id.id if self.move_type == "in_invoice": move_vals["partner_bank_id"] = self.partner_bank_id.id return move_vals def partner_banks_to_show(self): self.ensure_one() if self.partner_bank_id: return self.partner_bank_id if self.payment_mode_id.show_bank_account_from_journal: if self.payment_mode_id.bank_account_link == "fixed": return self.payment_mode_id.fixed_journal_id.bank_account_id else: return self.payment_mode_id.variable_journal_ids.mapped( "bank_account_id" ) if ( self.payment_mode_id.payment_method_id.code == "sepa_direct_debit" ): # pragma: no cover return ( self.mandate_id.partner_bank_id or self.partner_id.valid_mandate_id.partner_bank_id ) # Return this as empty recordset return self.partner_bank_id @api.model def create(self, vals): # Force compute partner_bank_id when invoice is created from SO # to avoid that odoo _prepare_invoice method value will be set. if self.env.context.get("active_model") == "sale.order": # pragma: no cover virtual_move = self.new(vals) virtual_move._compute_partner_bank_id() vals["partner_bank_id"] = virtual_move.partner_bank_id.id return super().create(vals)
42.491228
7,266
1,436
py
PYTHON
15.0
# Copyright 2016 Akretion (http://www.akretion.com/) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class AccountMoveLine(models.Model): _inherit = "account.move.line" payment_mode_id = fields.Many2one( comodel_name="account.payment.mode", compute="_compute_payment_mode", store=True, ondelete="restrict", index=True, readonly=False, ) @api.depends("move_id", "move_id.payment_mode_id") def _compute_payment_mode(self): for line in self: if line.move_id.is_invoice() and line.account_internal_type in ( "receivable", "payable", ): line.payment_mode_id = line.move_id.payment_mode_id else: line.payment_mode_id = False def write(self, vals): """Propagate up to the move the payment mode if applies.""" if "payment_mode_id" in vals: for record in self: move = ( self.env["account.move"].browse(vals.get("move_id", 0)) or record.move_id ) if ( move.payment_mode_id.id != vals["payment_mode_id"] and move.is_invoice() ): move.payment_mode_id = vals["payment_mode_id"] return super().write(vals)
33.395349
1,436
2,706
py
PYTHON
15.0
# Copyright 2017 ForgeFlow S.L. # Copyright 2018 Tecnativa - Carlos Dauden # Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class AccountPaymentMode(models.Model): _inherit = "account.payment.mode" show_bank_account = fields.Selection( selection=[ ("full", "Full"), ("first", "First n chars"), ("last", "Last n chars"), ("no", "No"), ], default="full", help="Show in invoices partial or full bank account number", ) show_bank_account_from_journal = fields.Boolean(string="Bank account from journals") show_bank_account_chars = fields.Integer( string="# of digits for customer bank account" ) refund_payment_mode_id = fields.Many2one( comodel_name="account.payment.mode", domain="[('payment_type', '!=', payment_type)]", string="Payment mode for refunds", help="This payment mode will be used when doing " "refunds coming from the current payment mode.", ) @api.constrains("company_id") def account_invoice_company_constrains(self): for mode in self: if ( self.env["account.move"] .sudo() .search( [ ("payment_mode_id", "=", mode.id), ("company_id", "!=", mode.company_id.id), ], limit=1, ) ): raise ValidationError( _( "You cannot change the Company. There exists " "at least one Journal Entry with this Payment Mode, " "already assigned to another Company." ) ) @api.constrains("company_id") def account_move_line_company_constrains(self): for mode in self: if ( self.env["account.move.line"] .sudo() .search( [ ("payment_mode_id", "=", mode.id), ("company_id", "!=", mode.company_id.id), ], limit=1, ) ): raise ValidationError( _( "You cannot change the Company. There exists " "at least one Journal Item with this Payment Mode, " "already assigned to another Company." ) )
35.116883
2,704
1,136
py
PYTHON
15.0
# Copyright 2014 Akretion - Alexis de Lattre <[email protected]> # Copyright 2014 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class ResPartner(models.Model): _inherit = "res.partner" supplier_payment_mode_id = fields.Many2one( comodel_name="account.payment.mode", company_dependent=True, check_company=True, domain="[('payment_type', '=', 'outbound')," "('company_id', '=', current_company_id)]", help="Select the default payment mode for this supplier.", ) customer_payment_mode_id = fields.Many2one( comodel_name="account.payment.mode", company_dependent=True, check_company=True, domain="[('payment_type', '=', 'inbound')," "('company_id', '=', current_company_id)]", help="Select the default payment mode for this customer.", ) @api.model def _commercial_fields(self): res = super()._commercial_fields() res += ["supplier_payment_mode_id", "customer_payment_mode_id"] return res
35.5
1,136
510
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class AccountInvoiceReport(models.Model): _inherit = "account.invoice.report" payment_mode_id = fields.Many2one( comodel_name="account.payment.mode", string="Payment mode", readonly=True, ) def _select(self): select_str = super()._select() return "%s, move.payment_mode_id AS payment_mode_id" % select_str
28.222222
508
652
py
PYTHON
15.0
# Copyright 2016 Akretion (<http://www.akretion.com>). # Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Account Payment Purchase", "version": "15.0.1.0.0", "category": "Banking addons", "license": "AGPL-3", "summary": "Adds Bank Account and Payment Mode on Purchase Orders", "author": "Akretion, Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/bank-payment", "depends": ["account_payment_partner", "purchase"], "data": ["views/purchase_order_view.xml"], "installable": True, "auto_install": True, }
38.352941
652
5,262
py
PYTHON
15.0
# Copyright 2013-2015 Tecnativa - Pedro M. Baeza # Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import fields from odoo.tests import Form, TransactionCase, tagged @tagged("-at_install", "post_install") class TestAccountPaymentPurchase(TransactionCase): @classmethod def setUpClass(cls): super(TestAccountPaymentPurchase, cls).setUpClass() cls.journal = cls.env["account.journal"].create( {"name": "Test journal", "code": "TEST", "type": "general"} ) cls.payment_method_out = cls.env.ref( "account.account_payment_method_manual_out" ) cls.payment_method_out.bank_account_required = True cls.payment_mode = cls.env["account.payment.mode"].create( { "name": "Test payment mode", "fixed_journal_id": cls.journal.id, "bank_account_link": "variable", "payment_method_id": cls.payment_method_out.id, } ) cls.partner = cls.env["res.partner"].create( {"name": "Test partner", "supplier_payment_mode_id": cls.payment_mode.id} ) cls.bank = cls.env["res.partner.bank"].create( { "bank_name": "Test bank", "acc_number": "1234567890", "partner_id": cls.partner.id, } ) cls.bank2 = cls.env["res.partner.bank"].create( { "bank_name": "Test bank #2", "acc_number": "0123456789", "partner_id": cls.partner.id, } ) cls.uom_id = cls.env.ref("uom.product_uom_unit").id cls.mto_product = cls.env["product.product"].create( { "name": "Test buy product", "uom_id": cls.uom_id, "uom_po_id": cls.uom_id, "seller_ids": [(0, 0, {"name": cls.partner.id})], } ) cls.purchase = cls.env["purchase.order"].create( { "partner_id": cls.partner.id, "payment_mode_id": cls.payment_mode.id, "order_line": [ ( 0, 0, { "name": "Test line", "product_qty": 1.0, "product_id": cls.mto_product.id, "product_uom": cls.uom_id, "date_planned": fields.Datetime.today(), "price_unit": 1.0, }, ) ], } ) def test_onchange_partner_id_purchase_order(self): self.purchase.onchange_partner_id() self.assertEqual(self.purchase.payment_mode_id, self.payment_mode) def test_purchase_order_invoicing(self): self.purchase.onchange_partner_id() self.purchase.button_confirm() invoice = self.env["account.move"].create( {"partner_id": self.partner.id, "move_type": "in_invoice"} ) with Form(invoice) as inv: inv.purchase_id = self.purchase self.assertEqual( self.purchase.invoice_ids[0].payment_mode_id, self.payment_mode ) def test_from_purchase_order_invoicing(self): # Test payment mode product = self.env["product.product"].create({"name": "Test product"}) self.purchase.order_line[0].product_id = product self.purchase.button_confirm() invoice = self.env["account.move"].create( {"partner_id": self.partner.id, "move_type": "in_invoice"} ) invoice.purchase_id = self.purchase invoice._onchange_purchase_auto_complete() self.assertEqual(invoice.payment_mode_id, self.payment_mode) purchase2 = self.purchase.copy() payment_mode2 = self.payment_mode.copy() purchase2.payment_mode_id = payment_mode2 purchase2.button_confirm() invoice.purchase_id = purchase2 result = invoice._onchange_purchase_auto_complete() self.assertEqual( result and result.get("warning", {}).get("title", False), "Warning" ) def test_from_purchase_order_invoicing_bank(self): # Test partner_bank product = self.env["product.product"].create({"name": "Test product"}) self.purchase.order_line[0].product_id = product self.purchase.supplier_partner_bank_id = self.bank self.purchase.button_confirm() invoice = self.env["account.move"].create( {"partner_id": self.partner.id, "move_type": "in_invoice"} ) invoice.purchase_id = self.purchase invoice._onchange_purchase_auto_complete() self.assertEqual(invoice.partner_bank_id, self.bank) purchase2 = self.purchase.copy() purchase2.supplier_partner_bank_id = self.bank2 purchase2.button_confirm() invoice.purchase_id = purchase2 result = invoice._onchange_purchase_auto_complete() self.assertEqual( result and result.get("warning", {}).get("title", False), "Warning" )
38.691176
5,262
1,545
py
PYTHON
15.0
# Copyright 2016 Akretion (<http://www.akretion.com>). # Copyright 2017 Tecnativa - Vicent Cubells. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import _, api, models class AccountMove(models.Model): _inherit = "account.move" @api.onchange("purchase_vendor_bill_id", "purchase_id") def _onchange_purchase_auto_complete(self): new_mode = ( self.purchase_vendor_bill_id.purchase_order_id.payment_mode_id.id or self.purchase_id.payment_mode_id.id ) new_bank = ( self.purchase_vendor_bill_id.purchase_order_id.supplier_partner_bank_id.id or self.purchase_id.supplier_partner_bank_id.id ) res = super()._onchange_purchase_auto_complete() or {} if self.payment_mode_id and new_mode and self.payment_mode_id.id != new_mode: res["warning"] = { "title": _("Warning"), "message": _("Selected purchase order have different payment mode."), } return res elif self.payment_mode_id.id != new_mode: self.payment_mode_id = new_mode if self.partner_bank_id and new_bank and self.partner_bank_id.id != new_bank: res["warning"] = { "title": _("Warning"), "message": _("Selected purchase order have different supplier bank."), } return res elif self.partner_bank_id.id != new_bank: self.partner_bank_id = new_bank return res
38.625
1,545
1,550
py
PYTHON
15.0
# Copyright 2016 Akretion (<http://www.akretion.com>). # Copyright 2017 Tecnativa - Vicent Cubells. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class PurchaseOrder(models.Model): _inherit = "purchase.order" supplier_partner_bank_id = fields.Many2one( comodel_name="res.partner.bank", string="Supplier Bank Account", domain="[('partner_id', '=', partner_id)]", help="Select the bank account of your supplier on which your company " "should send the payment. This field is copied from the partner " "and will be copied to the supplier invoice.", ) payment_mode_id = fields.Many2one( comodel_name="account.payment.mode", string="Payment Mode", domain="[('payment_type', '=', 'outbound')]", ) @api.model def _get_default_supplier_partner_bank(self, partner): """This function is designed to be inherited""" return partner.bank_ids and partner.bank_ids[0].id or False @api.onchange("partner_id", "company_id") def onchange_partner_id(self): ret = super(PurchaseOrder, self).onchange_partner_id() if self.partner_id: self.supplier_partner_bank_id = self._get_default_supplier_partner_bank( self.partner_id ) self.payment_mode_id = self.partner_id.supplier_payment_mode_id else: self.supplier_partner_bank_id = False self.payment_mode_id = False return ret
37.804878
1,550
610
py
PYTHON
15.0
# Copyright 2016 Akretion (<http://www.akretion.com>). # Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Account Payment Purchase Stock", "version": "15.0.1.0.0", "category": "Banking addons", "license": "AGPL-3", "summary": "Integrate Account Payment Purchase with Stock", "author": "Akretion, Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/bank-payment", "depends": ["account_payment_purchase", "purchase_stock"], "installable": True, "auto_install": True, }
38.125
610
4,828
py
PYTHON
15.0
# Copyright 2013-2015 Tecnativa - Pedro M. Baeza # Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import fields from odoo.tests import Form from odoo.addons.account_payment_purchase.tests.test_account_payment_purchase import ( TestAccountPaymentPurchase, ) class TestAccountPaymentPurchaseStock(TestAccountPaymentPurchase): def test_purchase_stock_order_invoicing(self): self.purchase.onchange_partner_id() self.purchase.button_confirm() picking = self.purchase.picking_ids[0] picking.action_confirm() picking.move_lines.write({"quantity_done": 1.0}) picking.button_validate() invoice = self.env["account.move"].create( {"partner_id": self.partner.id, "move_type": "in_invoice"} ) with Form(invoice) as inv: inv.purchase_id = self.purchase self.assertEqual( self.purchase.invoice_ids[0].payment_mode_id, self.payment_mode ) def test_picking_from_purchase_order_invoicing(self): # Test payment mode stockable_product = self.env["product.product"].create( {"name": "Test stockable product", "type": "product"} ) self.purchase.order_line[0].product_id = stockable_product self.purchase.button_confirm() picking = self.purchase.picking_ids[0] picking.action_confirm() picking.move_lines.write({"quantity_done": 1.0}) picking.button_validate() invoice = self.env["account.move"].create( {"partner_id": self.partner.id, "move_type": "in_invoice"} ) invoice.purchase_id = self.purchase invoice._onchange_purchase_auto_complete() self.assertEqual(invoice.payment_mode_id, self.payment_mode) purchase2 = self.purchase.copy() payment_mode2 = self.payment_mode.copy() purchase2.payment_mode_id = payment_mode2 purchase2.button_confirm() picking = purchase2.picking_ids[0] picking.action_confirm() picking.move_lines.write({"quantity_done": 1.0}) picking.button_validate() invoice.purchase_id = purchase2 result = invoice._onchange_purchase_auto_complete() self.assertEqual( result and result.get("warning", {}).get("title", False), "Warning" ) def test_picking_from_purchase_order_invoicing_bank(self): # Test partner_bank stockable_product = self.env["product.product"].create( {"name": "Test stockable product", "type": "product"} ) self.purchase.order_line[0].product_id = stockable_product self.purchase.supplier_partner_bank_id = self.bank self.purchase.button_confirm() picking = self.purchase.picking_ids[0] picking.action_confirm() picking.move_lines.write({"quantity_done": 1.0}) picking.button_validate() invoice = self.env["account.move"].create( {"partner_id": self.partner.id, "move_type": "in_invoice"} ) invoice.purchase_id = self.purchase invoice._onchange_purchase_auto_complete() self.assertEqual(invoice.partner_bank_id, self.bank) purchase2 = self.purchase.copy() purchase2.supplier_partner_bank_id = self.bank2 purchase2.button_confirm() picking = purchase2.picking_ids[0] picking.action_confirm() picking.move_lines.write({"quantity_done": 1.0}) picking.button_validate() invoice.purchase_id = purchase2 result = invoice._onchange_purchase_auto_complete() self.assertEqual( result and result.get("warning", {}).get("title", False), "Warning" ) def test_stock_rule_buy_payment_mode(self): route = self.env.ref("purchase_stock.route_warehouse0_buy") rule = self.env["stock.rule"].search([("route_id", "=", route.id)], limit=1) rule._run_buy( procurements=[ ( self.env["procurement.group"].Procurement( self.mto_product, 1, self.mto_product.uom_id, self.env["stock.location"].search([], limit=1), "Procurement order test", "Test", rule.company_id, { "company_id": rule.company_id, "date_planned": fields.Datetime.now(), }, ), rule, ) ] ) purchase = self.env["purchase.order"].search([("origin", "=", "Test")]) self.assertEqual(purchase.payment_mode_id, self.payment_mode)
40.571429
4,828
789
py
PYTHON
15.0
# Copyright 2015 Tecnativa - Pedro M. Baeza # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import models class StockRule(models.Model): _inherit = "stock.rule" def _prepare_purchase_order(self, company_id, origins, values): """Propagate payment mode on MTO/drop shipping.""" res = super()._prepare_purchase_order(company_id, origins, values) values = values[0] partner = values["supplier"].name if partner: res["payment_mode_id"] = partner.with_company( self.company_id.id ).supplier_payment_mode_id.id res["supplier_partner_bank_id"] = self.env[ "purchase.order" ]._get_default_supplier_partner_bank(partner) return res
35.863636
789
582
py
PYTHON
15.0
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Account Payment Order - Generate grouped moves", "version": "15.0.1.0.1", "license": "AGPL-3", "author": "ACSONE SA/NV, Therp BV, Tecnativa, Akretion, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/bank-payment", "category": "Banking addons", "depends": ["account_payment_order"], "data": [ "views/account_payment_mode_views.xml", "views/account_payment_order_views.xml", ], "demo": [], "installable": True, }
32.333333
582
783
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests.common import tagged from odoo.addons.account_payment_order.tests.test_payment_order_inbound import ( TestPaymentOrderInboundBase, ) @tagged("post_install", "-at_install") class TestPaymentOrderInbound(TestPaymentOrderInboundBase): def test_grouped_output(self): self.inbound_mode.generate_move = True self.inbound_mode.post_move = True self.inbound_order.draft2open() self.inbound_order.open2generated() self.inbound_order.generated2uploaded() grouped_moves = self.inbound_order.grouped_move_ids self.assertTrue(grouped_moves) self.assertTrue(grouped_moves.line_ids[0].reconciled)
37.285714
783
8,033
py
PYTHON
15.0
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models class AccountPaymentOrder(models.Model): _inherit = "account.payment.order" grouped_move_ids = fields.One2many( comodel_name="account.move", inverse_name="grouped_payment_order_id", string="Journal Entries (Grouped)", readonly=True, ) grouped_move_count = fields.Integer( compute="_compute_grouped_move_count", string="Number of Grouped Journal Entries", ) @api.depends("grouped_move_ids") def _compute_grouped_move_count(self): rg_res = self.env["account.move"].read_group( [("grouped_payment_order_id", "in", self.ids)], ["grouped_payment_order_id"], ["grouped_payment_order_id"], ) mapped_data = { x["grouped_payment_order_id"][0]: x["grouped_payment_order_id_count"] for x in rg_res } for order in self: order.grouped_move_count = mapped_data.get(order.id, 0) def action_uploaded_cancel(self): """Unreconcile and remove grouped moves.""" for move in self.grouped_move_ids: move.button_cancel() for move_line in move.line_ids: move_line.remove_move_reconcile() move.with_context(force_delete=True).unlink() return super().action_uploaded_cancel() def generated2uploaded(self): """Generate grouped moves if configured that way.""" res = super().generated2uploaded() for order in self: if order.payment_mode_id.generate_move: order.generate_move() return res def generate_move(self): """Create the moves that pay off the move lines from the payment/debit order.""" self.ensure_one() trfmoves = self._prepare_trf_moves() for hashcode, plines in trfmoves.items(): self._create_reconcile_move(hashcode, plines) def _prepare_trf_moves(self): """Prepare a dict "trfmoves" grouped by date.""" self.ensure_one() trfmoves = {} for pline in self.payment_ids: hashcode = fields.Date.to_string(pline.date) trfmoves.setdefault(hashcode, self.env["account.payment"]) trfmoves[hashcode] += pline return trfmoves def _create_reconcile_move(self, hashcode, payments): self.ensure_one() post_move = self.payment_mode_id.post_move am_obj = self.env["account.move"] mvals = self._prepare_move(payments) move = am_obj.create(mvals) if post_move: move.action_post() self.reconcile_grouped_payments(move, payments) def reconcile_grouped_payments(self, move, payments): lines_to_rec = move.line_ids[:-1] for payment in payments: journal = payment.journal_id lines_to_rec += payment.move_id.line_ids.filtered( lambda x: x.account_id in ( journal._get_journal_inbound_outstanding_payment_accounts() + journal._get_journal_outbound_outstanding_payment_accounts() ) ) lines_to_rec.reconcile() def _prepare_move(self, payments=None): if self.payment_type == "outbound": ref = _("Payment order %s") % self.name else: ref = _("Debit order %s") % self.name if payments and len(payments) == 1: ref += " - " + payments.name vals = { "date": payments[0].date, "journal_id": self.journal_id.id, "ref": ref, "grouped_payment_order_id": self.id, "line_ids": [], } total_company_currency = total_payment_currency = 0 for pline in payments: amount_company_currency = abs(pline.move_id.line_ids[0].balance) total_company_currency += amount_company_currency total_payment_currency += pline.amount partner_ml_vals = self._prepare_move_line_partner_account(pline) vals["line_ids"].append((0, 0, partner_ml_vals)) trf_ml_vals = self._prepare_move_line_offsetting_account( total_company_currency, total_payment_currency, payments ) vals["line_ids"].append((0, 0, trf_ml_vals)) return vals def _get_grouped_output_liquidity_account(self, payment): domain = [ ("journal_id", "=", self.journal_id.id), ("payment_method_id", "=", payment.payment_method_id.id), ("payment_type", "=", self.payment_type), ] apml = self.env["account.payment.method.line"].search(domain) if apml.payment_account_id: return apml.payment_account_id elif self.payment_type == "inbound": return payment.company_id.account_journal_payment_debit_account_id else: return payment.company_id.account_journal_payment_credit_account_id def _prepare_move_line_partner_account(self, payment): if self.payment_type == "outbound": name = _("Payment bank line %s") % payment.name else: name = _("Debit bank line %s") % payment.name account = self._get_grouped_output_liquidity_account(payment) sign = self.payment_type == "inbound" and -1 or 1 amount_company_currency = abs(payment.move_id.line_ids[0].balance) vals = { "name": name, "partner_id": payment.partner_id.id, "account_id": account.id, "credit": ( self.payment_type == "inbound" and amount_company_currency or 0.0 ), "debit": ( self.payment_type == "outbound" and amount_company_currency or 0.0 ), "currency_id": payment.currency_id.id, "amount_currency": payment.amount * sign, } return vals def _prepare_move_line_offsetting_account( self, amount_company_currency, amount_payment_currency, payments ): if self.payment_type == "outbound": name = _("Payment order %s") % self.name else: name = _("Debit order %s") % self.name partner = self.env["res.partner"] for index, payment in enumerate(payments): account = self._get_grouped_output_liquidity_account(payment) if index == 0: partner = payment.payment_line_ids[0].partner_id elif payment.payment_line_ids[0].partner_id != partner: # we have different partners in the grouped move partner = self.env["res.partner"] break sign = self.payment_type == "outbound" and -1 or 1 vals = { "name": name, "partner_id": partner.id, "account_id": account.id, "credit": ( self.payment_type == "outbound" and amount_company_currency or 0.0 ), "debit": ( self.payment_type == "inbound" and amount_company_currency or 0.0 ), "currency_id": payments[0].currency_id.id, "amount_currency": amount_payment_currency * sign, } return vals def action_grouped_moves(self): self.ensure_one() action = self.env["ir.actions.act_window"]._for_xml_id( "account.action_move_journal_line" ) if self.grouped_move_count == 1: action.update( { "view_mode": "form,tree,kanban", "views": False, "view_id": False, "res_id": self.grouped_move_ids.id, } ) else: action["domain"] = [("id", "in", self.grouped_move_ids.ids)] ctx = self.env.context.copy() ctx.update({"search_default_misc_filter": 0}) action["context"] = ctx return action
38.995146
8,033
426
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class AccountMove(models.Model): _inherit = "account.move" grouped_payment_order_id = fields.Many2one( comodel_name="account.payment.order", string="Payment Order (Grouped)", copy=False, readonly=True, check_company=True, )
26.625
426
353
py
PYTHON
15.0
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class AccountPaymentMode(models.Model): _inherit = "account.payment.mode" generate_move = fields.Boolean( string="Generate Grouped Accounting Entries On File Upload", default=True ) post_move = fields.Boolean(default=True)
29.416667
353
586
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Luis M. Ontalba # Copyright 2021 Tecnativa - João Marques # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { "name": "Account Payment Order Return", "version": "15.0.1.0.0", "category": "Banking addons", "author": "Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/bank-payment", "depends": ["account_payment_return", "account_payment_order"], "data": ["wizards/account_payment_line_create_view.xml"], "license": "AGPL-3", "installable": True, "auto_install": True, }
36.5625
585
4,237
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Luis M. Ontalba # Copyright 2021 Tecnativa - João Marques # Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0 from datetime import timedelta from odoo import fields from odoo.tests import common from odoo.tests.common import Form class TestAccountPaymentOrderReturn(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.a_income = cls.env["account.account"].create( { "code": "TIA", "name": "Test Income Account", "user_type_id": cls.env.ref("account.data_account_type_revenue").id, } ) cls.partner = cls.env["res.partner"].create({"name": "Test Partner 2"}) cls.sale_journal = cls.env["account.journal"].create( {"name": "Test Sale Journal", "type": "sale", "code": "Test"} ) cls.bank_journal = cls.env["account.journal"].create( {"name": "Test Bank Journal", "type": "bank"} ) move_form = Form( cls.env["account.move"].with_context( default_move_type="out_invoice", default_journal_id=cls.sale_journal.id ) ) move_form.partner_id = cls.partner with move_form.invoice_line_ids.new() as line_form: line_form.name = "Test line" line_form.account_id = cls.a_income line_form.quantity = 1.0 line_form.price_unit = 100.00 cls.invoice = move_form.save() cls.payment_mode = cls.env["account.payment.mode"].create( { "name": "Test payment mode", "fixed_journal_id": cls.bank_journal.id, "bank_account_link": "fixed", "payment_method_id": cls.env.ref( "account.account_payment_method_manual_in" ).id, } ) cls.payment_order = cls.env["account.payment.order"].create( { "payment_mode_id": cls.payment_mode.id, "date_prefered": "due", "payment_type": "inbound", } ) def test_global(self): self.invoice.action_post() wizard_o = self.env["account.payment.line.create"] context = wizard_o._context.copy() context.update( { "active_model": "account.payment.order", "active_id": self.payment_order.id, } ) wizard = wizard_o.with_context(**context).create( { "order_id": self.payment_order.id, "journal_ids": [ (4, self.bank_journal.id), (4, self.invoice.journal_id.id), ], "partner_ids": [(4, self.partner.id)], "allow_blocked": True, "date_type": "move", "move_date": fields.Date.today() + timedelta(days=1), "payment_mode": "any", "invoice": True, "include_returned": True, } ) wizard.populate() self.assertEqual(len(wizard.move_line_ids), 1) payment_register = Form( self.env["account.payment.register"].with_context( active_model="account.move", active_ids=self.invoice.ids ) ) self.payment = payment_register.save()._create_payments() if self.payment.state != "posted": self.payment.action_post() wizard.populate() # Create payment return payment_return_form = Form(self.env["payment.return"]) payment_return_form.journal_id = self.bank_journal with payment_return_form.line_ids.new() as line_form: line_form.move_line_ids.add( self.payment.move_id.line_ids.filtered( lambda x: x.account_id.internal_type == "receivable" ) ) self.payment_return = payment_return_form.save() self.payment_return.action_confirm() wizard.include_returned = False wizard.populate() self.assertEqual(len(wizard.move_line_ids), 0)
38.144144
4,234
620
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Luis M. Ontalba # Copyright 2021 Tecnativa - João Marques # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import fields, models class AccountPaymentLineCreate(models.TransientModel): _inherit = "account.payment.line.create" include_returned = fields.Boolean(string="Include move lines from returns") def _prepare_move_line_domain(self): domain = super()._prepare_move_line_domain() if not self.include_returned: domain += [ ("move_id.returned_payment", "=", False), ] return domain
32.578947
619
504
py
PYTHON
15.0
# © 2019 Today Akretion # @author Pierrick Brun <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Base Product Mass Addition", "version": "15.0.1.0.0", "author": "Akretion, Odoo Community Association (OCA)", "website": "https://github.com/OCA/product-attribute", "license": "AGPL-3", "category": "Product", "depends": ["stock", "onchange_helper"], "data": ["views/product_view.xml"], "installable": True, }
33.533333
503
3,676
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA (https://www.camptocamp.com). # @author Iván Todorovich <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo_test_helper import FakeModelLoader from odoo.tests.common import TransactionCase class TestProductMassAddition(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() # Setup Fake Models cls.loader = FakeModelLoader(cls.env, cls.__module__) cls.loader.backup_registry() from .models.order import ModelOrder, ModelOrderLine cls.loader.update_registry((ModelOrder, ModelOrderLine)) # Setup data cls.order = cls.env["model.order"].create({}) cls.quick_ctx = dict(parent_model=cls.order._name, parent_id=cls.order.id) cls.product = cls.env.ref("product.product_product_8").with_context( **cls.quick_ctx ) @classmethod def tearDownClass(cls): cls.loader.restore_registry() super().tearDownClass() def test_quick_line_add(self): """Test quick lines are added, updated and removed""" # Case 1: Create new line self.assertFalse(self.order.line_ids) self.product.qty_to_process = 5.0 self.assertEqual(len(self.order.line_ids), 1, "A new line should be created") self.assertAlmostEqual(self.order.line_ids.product_qty, 5.0) # Case 2: Update existing line self.product.qty_to_process = 2.0 self.assertEqual(len(self.order.line_ids), 1) self.assertAlmostEqual(self.order.line_ids.product_qty, 2.0) # Case 3: Set to 0 should remove the line self.product.qty_to_process = 0.0 self.assertFalse(self.order.line_ids) def test_quick_should_not_write_on_product(self): """Using quick magic fields shouldn't write on product's metadata""" user_demo = self.env.ref("base.user_demo") self.product.write_uid = user_demo self.env["base"].flush() self.assertEqual(self.product.write_uid, user_demo) # Case 1: Updating qty_to_process shouldn't write on products self.product.qty_to_process = 1.0 self.env["base"].flush() self.assertEqual(self.product.write_uid, user_demo) # Case 2: Updating quick_uom_id shouldn't write on products self.product.quick_uom_id = self.env.ref("uom.product_uom_categ_unit").uom_ids[ 1 ] self.env["base"].flush() self.assertEqual(self.product.write_uid, user_demo) def test_quick_should_write_on_product(self): """Updating fields that are not magic fields should update product metadata""" # Change the product write_uid for testing user_demo = self.env.ref("base.user_demo") self.product.write_uid = user_demo self.env["base"].flush() self.assertEqual(self.product.write_uid, user_demo) # Case 1: Updating name field should write on product's metadata self.product.name = "Testing" self.env["base"].flush() self.assertEqual(self.product.write_uid, self.env.user) # Change the product write_uid for testing user_demo = self.env.ref("base.user_demo") self.product.write_uid = user_demo self.env["base"].flush() self.assertEqual(self.product.write_uid, user_demo) # Case 2: Updating qty_to_process and name before flush should # write on product's metadata self.product.qty_to_process = 2.0 self.product.name = "Testing 2" self.env["base"].flush() self.assertEqual(self.product.write_uid, self.env.user)
42.241379
3,675
1,245
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA (https://www.camptocamp.com). # @author Iván Todorovich <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class ModelOrder(models.Model): _name = "model.order" _description = "Test Model Order (base_product_mass_addition)" _inherit = "product.mass.addition" line_ids = fields.One2many("model.order.line", "order_id") def _get_quick_line(self, product): return fields.first( self.line_ids.filtered(lambda rec: rec.product_id == product) ) def _get_quick_line_qty_vals(self, product): return {"product_qty": product.qty_to_process} def _complete_quick_line_vals(self, vals, lines_key=""): return super()._complete_quick_line_vals(vals, lines_key="line_ids") def _add_quick_line(self, product, lines_key=""): return super()._add_quick_line(product, lines_key="line_ids") class ModelOrderLine(models.Model): _name = "model.order.line" _description = "Test Model Order Line (base_product_mass_addition)" order_id = fields.Many2one("model.order") product_id = fields.Many2one("product.product") product_qty = fields.Float()
34.555556
1,244
4,400
py
PYTHON
15.0
# © 2014 Today Akretion # @author Sébastien BEAU <[email protected]> # @author Mourad EL HADJ MIMOUNE <[email protected]> # @author Pierrick Brun <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models from odoo.models import LOG_ACCESS_COLUMNS class ProductProduct(models.Model): _inherit = "product.product" qty_to_process = fields.Float( compute="_compute_process_qty", inverse="_inverse_set_process_qty", help="Set this quantity to create a new line " "for this product or update the existing one.", ) quick_uom_category_id = fields.Many2one( "uom.category", related="quick_uom_id.category_id" ) quick_uom_id = fields.Many2one( "uom.uom", domain="[('category_id', '=', quick_uom_category_id)]", compute="_compute_quick_uom_id", inverse="_inverse_set_process_qty", ) def _inverse_set_process_qty(self): parent = self.pma_parent if parent: for product in self: quick_line = parent._get_quick_line(product) if quick_line: parent._update_quick_line(product, quick_line) else: parent._add_quick_line(product, quick_line._name) def modified(self, fnames, create=False, before=False): # OVERRIDE to supress LOG_ACCESS_COLUMNS writes if we're only writing on quick # magic fields, as they could lead to concurrency issues. # # Moreover, from a functional perspective, these magic fields aren't really # modifying the product's data so it doesn't make sense to update its metadata. # # We achieve it by reverting the changes made by ``write`` [^1], before [^2] # reaching any explicit flush [^3] or inverse computation [^4]. # # [^1]: # https://github.com/odoo/odoo/blob/3991737a53e75398fcf70b1924525783b54d256b/odoo/models.py#L3778-L3787 # noqa: B950 # [^2]: # https://github.com/odoo/odoo/blob/3991737a53e75398fcf70b1924525783b54d256b/odoo/models.py#L3882 # noqa: B950 # [^3]: # https://github.com/odoo/odoo/blob/3991737a53e75398fcf70b1924525783b54d256b/odoo/models.py#L3885 # noqa: B950 # [^4]: # https://github.com/odoo/odoo/blob/f74434c6f4303650e886d99fb950c763f2d4cc6e/odoo/models.py#L3703 # noqa: B950 # # Basically, if all we're modifying are quick magic fields, and we don't have # any other column to flush besides the LOG_ACCESS_COLUMNS, clear it. quick_fnames = ("qty_to_process", "quick_uom_id") if ( self and fnames and any(quick_fname in fnames for quick_fname in quick_fnames) ): for record in self.filtered("id"): towrite = self.env.all.towrite[self._name] vals = towrite[record.id] if not vals: # pragma: no cover continue if all(fname in LOG_ACCESS_COLUMNS for fname in vals.keys()): towrite.pop(record.id) return super().modified(fnames, create=create, before=before) @property def pma_parent(self): # shorthand for product_mass_addition parent parent_model = self.env.context.get("parent_model") parent_id = self.env.context.get("parent_id") if parent_model and parent_id: return self.env[parent_model].browse(parent_id) def _default_quick_uom_id(self): raise NotImplementedError def _compute_quick_uom_id(self): parent = self.pma_parent if parent: for rec in self: quick_line = parent._get_quick_line(rec) if quick_line: rec.quick_uom_id = quick_line.product_uom else: rec.quick_uom_id = rec._default_quick_uom_id() def _compute_process_qty(self): if not self.pma_parent: return def button_quick_open_product(self): self.ensure_one() return { "name": self.display_name, "type": "ir.actions.act_window", "res_model": self._name, "view_mode": "form", "res_id": self.id, "target": "current", }
39.621622
4,398
2,417
py
PYTHON
15.0
# © 2019 Today Akretion # @author Pierrick Brun <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import logging from odoo import api, models _logger = logging.getLogger(__name__) class ProductMassAddition(models.AbstractModel): _name = "product.mass.addition" _description = "inherit this to add a mass product addition function\ to your model" @api.model def _common_action_keys(self): """Call it in your own child module""" return { "type": "ir.actions.act_window", "res_model": "product.product", "target": "current", "context": { "parent_id": self.id, "parent_model": self._name, }, "view_mode": "tree", } def _prepare_quick_line(self, product): res = self._get_quick_line_qty_vals(product) res.update({"product_id": product.id}) return res def _get_quick_line(self, product): raise NotImplementedError def _add_quick_line(self, product, lines_key=""): if not lines_key: raise NotImplementedError vals = self._prepare_quick_line(product) vals = self._complete_quick_line_vals(vals) self.write({lines_key: [(0, 0, vals)]}) def _update_quick_line(self, product, line): if product.qty_to_process: # apply the on change to update price unit if depends on qty vals = self._get_quick_line_qty_vals(product) vals["id"] = line.id vals = self._complete_quick_line_vals(vals) line.write(vals) else: line.unlink() def _get_quick_line_qty_vals(self, product): raise NotImplementedError def _complete_quick_line_vals(self, vals, lines_key=""): if not lines_key: raise NotImplementedError init_keys = ["product_id"] update_vals = {key: val for key, val in vals.items() if key not in init_keys} lines = getattr(self, lines_key) if "id" in vals: line = lines.filtered(lambda x: x.id == vals["id"]) return line.play_onchanges(update_vals, list(update_vals.keys())) else: line = lines if len(lines) > 1: line = lines[0] return line.play_onchanges(vals, list(vals.keys()))
33.09589
2,416
503
py
PYTHON
15.0
# Copyright 2004 Tiny SPRL # Copyright 2016 Sodexis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). def pre_init_hook(cr): """ Updates existing codes matching the default '/' or empty. Primarily this ensures installation does not fail for demo data. :param cr: database cursor :return: void """ cr.execute( "UPDATE product_product " "SET default_code = '!!mig!!' || id " "WHERE default_code IS NULL OR default_code = '/';" )
27.944444
503
665
py
PYTHON
15.0
# Copyright 2004 Tiny SPRL # Copyright 2016 Sodexis # Copyright 2018 ForgeFlow S.L. # (http://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Product Sequence", "version": "15.0.2.1.0", "author": "Zikzakmedia SL, Sodexis, Odoo Community Association (OCA)", "website": "https://github.com/OCA/product-attribute", "license": "AGPL-3", "category": "Product", "depends": ["product"], "data": [ "data/product_sequence.xml", "views/product_category.xml", "views/res_config_settings_views.xml", ], "pre_init_hook": "pre_init_hook", "installable": True, }
30.227273
665
6,800
py
PYTHON
15.0
# Copyright 2016 Sodexis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.exceptions import ValidationError from odoo.tests.common import TransactionCase, tagged from ..hooks import pre_init_hook @tagged("post_install", "-at_install") class TestProductSequence(TransactionCase): """Tests for creating product with and without Product Sequence""" def setUp(self): super(TestProductSequence, self).setUp() self.product_product = self.env["product.product"] self.product_category = self.env["product.category"] self.product_template = self.env["product.template"].create( {"name": "Demo Product"} ) def test_product_create_with_default_code(self): product = self.product_product.create(dict(name="Apple", default_code="PROD01")) self.assertEqual(product.default_code, "PROD01") product_new = self.product_product.create( dict(name="Demo Apple", product_tmpl_id=self.product_template.id) ) self.assertTrue(product_new.default_code) def test_product_create_without_default_code(self): product_1 = self.product_product.create(dict(name="Orange", default_code="/")) self.assertRegex(str(product_1.default_code), r"PR/*") def test_product_copy(self): product_2 = self.product_template.create( dict(name="Apple", default_code="PROD02") ) product_2.flush() copy_product_2 = product_2.product_variant_id.copy() self.assertEqual(copy_product_2.default_code, "PROD02-copy") def test_pre_init_hook(self): product_3 = self.product_product.create( dict(name="Apple", default_code="PROD03") ) self.cr.execute( "update product_product set default_code='/' where id=%s", (tuple(product_3.ids),), ) product_3.invalidate_cache() self.assertEqual(product_3.default_code, "/") pre_init_hook(self.cr) product_3.invalidate_cache() self.assertEqual(product_3.default_code, "!!mig!!{}".format(product_3.id)) def test_product_category_sequence(self): categ_grocery = self.product_category.create( dict(name="Grocery", code_prefix="GRO") ) self.assertTrue(categ_grocery.sequence_id) self.assertEqual(categ_grocery.sequence_id.prefix, "GRO") self.assertFalse(categ_grocery.sequence_id.company_id) product_3 = self.product_product.create( dict(name="Apple", categ_id=categ_grocery.id) ) self.assertEqual(product_3.default_code[:3], "GRO") self.assertEqual(product_3.product_tmpl_id.default_code[:3], "GRO") categ_electronics = self.product_category.create( dict(name="Electronics", code_prefix="ELE") ) product_3.write({"default_code": "/", "categ_id": categ_electronics.id}) self.assertEqual(product_3.default_code[:3], "ELE") self.assertEqual(product_3.product_tmpl_id.default_code[:3], "ELE") product_4 = self.product_product.create( dict(name="Truck", default_code="PROD04") ) product_4.write({"default_code": "/"}) self.assertTrue(product_4.categ_id, "Category is not set.") categ_car = self.product_category.create(dict(name="Car", code_prefix="CAR")) product_3.product_tmpl_id.categ_id = categ_car product_3.product_tmpl_id.default_code = "/" product_3.refresh() self.assertEqual(product_3.default_code[:3], "CAR") self.assertEqual(product_3.product_tmpl_id.default_code[:3], "CAR") categ_car.write(dict(name="Bike", code_prefix="BIK")) self.assertEqual(categ_car.sequence_id.prefix, "BIK") categ_car.sequence_id = False categ_car.write({"code_prefix": "KIA"}) self.assertEqual(categ_car.sequence_id.prefix, "KIA") def test_product_parent_category_sequence(self): parent_categ = self.product_category.create( dict( name="Parents", code_prefix="PAR", ) ) categ = self.product_category.create( dict( name="Child", parent_id=parent_categ.id, ) ) product_anna = self.product_product.create( dict( name="Anna", categ_id=categ.id, ) ) self.assertEqual(product_anna.default_code[:2], "PR") self.assertEqual(product_anna.product_tmpl_id.default_code[:2], "PR") self.env.user.company_id.use_parent_categories_to_determine_prefix = True product_claudia = self.product_product.create( dict( name="Claudia", categ_id=categ.id, ) ) self.assertEqual(product_claudia.default_code[:3], "PAR") self.assertEqual(product_claudia.product_tmpl_id.default_code[:3], "PAR") def test_product_copy_with_default_values(self): product_2 = self.product_template.create( dict(name="Apple", default_code="PROD02") ) product_2.flush() copy_product_2 = product_2.product_variant_id.copy( {"default_code": "product test sequence"} ) self.assertEqual(copy_product_2.default_code, "product test sequence") def test_remove_and_reuse_sequence(self): prefix = "TEST" category = self.product_category.create({"name": "Test", "code_prefix": prefix}) test_sequence = category.sequence_id self.assertTrue(test_sequence) self.assertEqual(test_sequence.prefix, prefix) category.write({"code_prefix": ""}) self.assertFalse(category.sequence_id) category.write({"code_prefix": prefix}) self.assertEqual(category.sequence_id, test_sequence) category_2 = self.product_category.create( {"name": "Test reuse", "code_prefix": prefix} ) self.assertEqual(category_2.sequence_id, test_sequence) def test_sequence_prefix_discrepancies(self): prefix_test = "TEST" category_test = self.product_category.create( {"name": "Test", "code_prefix": prefix_test} ) sequence_test = category_test.sequence_id prefix_demo = "DEMO" category_demo = self.product_category.create( {"name": "Demo", "code_prefix": prefix_demo} ) with self.assertRaisesRegex( ValidationError, "prefix defined on product category" ): category_demo.sequence_id = sequence_test with self.assertRaisesRegex( ValidationError, "used on following product categories" ): sequence_test.prefix = prefix_demo
40.236686
6,800
3,230
py
PYTHON
15.0
# Copyright 2018 ForgeFlow S.L. # (http://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class ProductCategory(models.Model): _inherit = "product.category" code_prefix = fields.Char( string="Prefix for Product Internal Reference", help="Prefix used to generate the internal reference for products " "created with this category. If blank the " "default sequence will be used.", ) sequence_id = fields.Many2one( comodel_name="ir.sequence", string="Product Sequence", help="This field contains the information related to the numbering " "of the journal entries of this journal.", copy=False, ) @api.model def _prepare_ir_sequence(self, prefix): """Prepare the vals for creating the sequence :param prefix: a string with the prefix of the sequence. :return: a dict with the values. """ vals = { "name": "Product " + prefix, "code": "product.product - " + prefix, "padding": 5, "prefix": prefix, "company_id": False, } return vals def _get_or_create_sequence(self, prefix): seq_vals = self._prepare_ir_sequence(prefix) sequence = self.env["ir.sequence"].search( [("code", "=", seq_vals.get("code")), ("prefix", "=", prefix)] ) if not sequence: sequence = self.env["ir.sequence"].create(seq_vals) return sequence def write(self, vals): sequence_ids_to_check = set() if "code_prefix" in vals: prefix = vals.get("code_prefix") if prefix: for rec in self: if rec.sequence_id: sequence_sudo = rec.sudo() sequence_ids_to_check.add(sequence_sudo.id) sequence_sudo.with_context( _no_sequence_prefix_check=True ).sequence_id.prefix = prefix else: vals["sequence_id"] = self._get_or_create_sequence(prefix).id else: vals["sequence_id"] = False res = super().write(vals) if sequence_ids_to_check: self.env["ir.sequence"].sudo().browse( sequence_ids_to_check )._check_prefix_product_category() return res @api.model def create(self, vals): prefix = vals.get("code_prefix", False) if prefix: vals["sequence_id"] = self._get_or_create_sequence(prefix).id return super().create(vals) @api.constrains("code_prefix", "sequence_id") def _check_prefix_sequence_id(self): for rec in self: if rec.sequence_id and rec.code_prefix != rec.sequence_id.prefix: raise ValidationError( _( "The prefix defined on product category %s does not match " "the prefix of linked sequence" ) % rec.name )
35.888889
3,230
2,594
py
PYTHON
15.0
# Copyright 2004 Tiny SPRL # Copyright 2016 Sodexis # Copyright 2018 ForgeFlow S.L. # (http://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models class ProductProduct(models.Model): _inherit = "product.product" default_code = fields.Char( required=True, default="/", tracking=True, help="Set to '/' and save if you want a new internal reference " "to be proposed.", ) @api.model def create(self, vals): if "default_code" not in vals or vals["default_code"] == "/": categ_id = vals.get("categ_id", False) template_id = vals.get("product_tmpl_id", False) category = self.env["product.category"] if categ_id: # Created as a product.product category = category.browse(categ_id) elif template_id: # Created from a product.template template = self.env["product.template"].browse(template_id) category = template.categ_id sequence = self.env["ir.sequence"].get_category_sequence_id(category) vals["default_code"] = sequence.next_by_id() return super().create(vals) def write(self, vals): """To assign a new internal reference, just write '/' on the field. Note this is up to the user, if the product category is changed, she/he will need to write '/' on the internal reference to force the re-assignment.""" if vals.get("default_code", "") == "/": product_category_obj = self.env["product.category"] for product in self: category_id = vals.get("categ_id", product.categ_id.id) category = product_category_obj.browse(category_id) sequence = self.env["ir.sequence"].get_category_sequence_id(category) ref = sequence.next_by_id() vals["default_code"] = ref if len(product.product_tmpl_id.product_variant_ids) == 1: product.product_tmpl_id.write({"default_code": ref}) super(ProductProduct, product).write(vals) return True return super().write(vals) @api.returns("self", lambda value: value.id) def copy(self, default=None): if default is None: default = {} if self.default_code and "default_code" not in default: default.update({"default_code": self.default_code + _("-copy")}) return super().copy(default)
41.174603
2,594
1,510
py
PYTHON
15.0
# Copyright 2018 Eficent Business and IT Consulting Services S.L. # (http://www.eficent.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, models from odoo.exceptions import ValidationError class IrSequence(models.Model): _inherit = "ir.sequence" @api.model def get_category_sequence_id(self, category=False): if self.env.user.company_id.use_parent_categories_to_determine_prefix: while not category.sequence_id and category.parent_id: category = category.parent_id return category.sequence_id or self.env.ref("product_sequence.seq_product_auto") @api.constrains("prefix") def _check_prefix_product_category(self): if self.env.context.get("_no_sequence_prefix_check"): return for rec in self: categs = self.env["product.category"].search([("sequence_id", "=", rec.id)]) if not categs: continue if any(categ.code_prefix != rec.prefix for categ in categs): raise ValidationError( _( "Sequence %(seq_name)s is used on following product " "categories and prefix cannot be changed here:" "\n%(categ_names)s" ) % dict( seq_name=rec.name, categ_names="\n -".join(categs.mapped("name")), ) )
39.736842
1,510
560
py
PYTHON
15.0
# Copyright 2004 Tiny SPRL # Copyright 2016 Sodexis # Copyright 2018 Eficent Business and IT Consulting Services S.L. # (http://www.eficent.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class Company(models.Model): _inherit = "res.company" use_parent_categories_to_determine_prefix = fields.Boolean( string="Use parent categories to determine the prefix", help="Use parent categories to determine the prefix " "if the category has no settings for the prefix.", )
32.941176
560
498
py
PYTHON
15.0
# Copyright 2004 Tiny SPRL # Copyright 2016 Sodexis # Copyright 2018 Eficent Business and IT Consulting Services S.L. # (http://www.eficent.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" use_parent_categories_to_determine_prefix = fields.Boolean( related="company_id.use_parent_categories_to_determine_prefix", readonly=False, )
31.125
498
584
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Product Pricelist Direct Print Company Group", "summary": "Print Pricelist items using the company group model", "version": "15.0.1.0.0", "category": "Product", "website": "https://github.com/OCA/product-attribute", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "depends": ["product_pricelist_direct_print", "partner_company_group"], "data": [], "installable": True, "auto-install": True, }
38.933333
584
772
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class ProductPricelistPrintCompanyGroup(models.TransientModel): _inherit = "product.pricelist.print" @api.model def _get_sale_order_domain(self, partner): domain = super()._get_sale_order_domain(partner) if partner.company_group_member_ids: origin_domain = ("partner_id", "child_of", partner.id) pos = 0 if origin_domain in domain: pos = domain.index(origin_domain) domain.remove(origin_domain) domain.insert( pos, ("partner_id", "in", partner.company_group_member_ids.ids) ) return domain
36.761905
772
534
py
PYTHON
15.0
{ "name": "Product Variant Attribute Name Manager", "summary": "Manage how to display the attributes on the product variant name.", "author": "ForgeFlow, Odoo Community Association (OCA)", "website": "https://github.com/OCA/product-attribute", "category": "Product", "version": "15.0.1.0.0", "depends": ["product"], "data": ["views/product_variant_attribute_name_manager_view.xml"], "license": "AGPL-3", "auto_install": False, "installable": True, "maintainers": ["oriolvforgeflow"], }
38.142857
534
4,318
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import tagged from odoo.tests.common import TransactionCase @tagged("post_install", "-at_install") class TestProductTemplateAttributeValue(TransactionCase): def setUp(self): super(TestProductTemplateAttributeValue, self).setUp() self.computer = self.env["product.template"].create( {"name": "Super Computer", "price": 2000} ) self._add_ssd_attribute() self._add_ram_attribute() self._add_hdd_attribute() def _add_ssd_attribute(self): self.ssd_attribute = self.env["product.attribute"].create( { "name": "Memory", "short_name": "Mem", "display_attribute_name": True, "sequence": 1, } ) self.ssd_256 = self.env["product.attribute.value"].create( {"name": "256 GB", "attribute_id": self.ssd_attribute.id, "sequence": 1} ) self.ssd_512 = self.env["product.attribute.value"].create( {"name": "512 GB", "attribute_id": self.ssd_attribute.id, "sequence": 2} ) self.computer_ssd_attribute_lines = self.env[ "product.template.attribute.line" ].create( { "product_tmpl_id": self.computer.id, "attribute_id": self.ssd_attribute.id, "value_ids": [(6, 0, [self.ssd_256.id, self.ssd_512.id])], "sequence": 2, } ) def _add_ram_attribute(self): self.ram_attribute = self.env["product.attribute"].create( {"name": "RAM", "display_attribute_name": True, "sequence": 2} ) self.ram_8 = self.env["product.attribute.value"].create( {"name": "8 GB", "attribute_id": self.ram_attribute.id, "sequence": 1} ) self.ram_16 = self.env["product.attribute.value"].create( {"name": "16 GB", "attribute_id": self.ram_attribute.id, "sequence": 2} ) self.ram_32 = self.env["product.attribute.value"].create( {"name": "32 GB", "attribute_id": self.ram_attribute.id, "sequence": 3} ) self.computer_ram_attribute_lines = self.env[ "product.template.attribute.line" ].create( { "product_tmpl_id": self.computer.id, "attribute_id": self.ram_attribute.id, "value_ids": [(6, 0, [self.ram_8.id, self.ram_16.id, self.ram_32.id])], "sequence": 3, } ) def _add_hdd_attribute(self): self.hdd_attribute = self.env["product.attribute"].create( {"name": "HDD", "sequence": 3} ) self.hdd_1 = self.env["product.attribute.value"].create( {"name": "1 To", "attribute_id": self.hdd_attribute.id, "sequence": 1} ) self.hdd_2 = self.env["product.attribute.value"].create( {"name": "2 To", "attribute_id": self.hdd_attribute.id, "sequence": 2} ) self.computer_hdd_attribute_lines = self.env[ "product.template.attribute.line" ].create( { "product_tmpl_id": self.computer.id, "attribute_id": self.hdd_attribute.id, "value_ids": [(6, 0, [self.hdd_1.id, self.hdd_2.id])], "sequence": 1, } ) def test_get_combination_name(self): variant_names = [ variant.product_template_attribute_value_ids._get_combination_name() for variant in self.env["product.product"].search( [("product_tmpl_id", "=", self.computer.id)] ) ] self.assertIn( "1 To, Mem: 256 GB, RAM: 8 GB", variant_names, "Variant name extension not found", ) self.assertIn( "2 To, Mem: 512 GB, RAM: 16 GB", variant_names, "Variant name extension not found", ) self.assertNotIn( "1 To, 256 GB, 8 GB", variant_names, "Variant name extension not correct" ) self.assertNotIn( "Mem: 256 GB, 1 To, RAM: 8 GB", variant_names, "Variant name extension not correct", )
36.285714
4,318
1,634
py
PYTHON
15.0
from odoo import fields, models class ProductAttribute(models.Model): _inherit = "product.attribute" short_name = fields.Char(help="Displayed as the variant attribute name.") display_attribute_name = fields.Boolean( "Display Attribute Name on Product Variant", help="If checked, it will display the variant attribute name before its value.", ) class ProductTemplateAttributeLine(models.Model): _inherit = "product.template.attribute.line" sequence = fields.Integer(help="Determine the display order", index=True) class ProductTemplateAttributeValue(models.Model): _inherit = "product.template.attribute.value" def _get_combination_name(self): """Gets the combination name of all the attributes. If active, it will display the name or short name before its value. The order of the attributes is defined by the user""" display_ptav_list = [] for ptav in sorted( self._without_no_variant_attributes()._filter_single_value_lines(), key=lambda seq: seq.attribute_line_id.sequence, ): if ptav.attribute_id.display_attribute_name: if ptav.attribute_id.short_name: display_ptav_list.append( "%s: %s" % (ptav.attribute_id.short_name, ptav.name) ) else: display_ptav_list.append( "%s: %s" % (ptav.attribute_id.name, ptav.name) ) else: display_ptav_list.append(ptav.name) return ", ".join(display_ptav_list)
38
1,634
580
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Products - Drained Weight", "summary": "Add 'Drained Weight' on product models", "version": "15.0.1.0.0", "category": "Product", "author": "Tecnativa,Odoo Community Association (OCA)", "website": "https://github.com/OCA/product-attribute", "license": "AGPL-3", "depends": ["product_net_weight"], "data": [ "views/view_product_product.xml", "views/view_product_template.xml", ], "installable": True, }
34.117647
580
2,730
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.exceptions import ValidationError from odoo.tests.common import Form, TransactionCase class TestProductDrainedWeight(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.attribute = cls.env["product.attribute"].create( { "name": "test attribute", "display_type": "select", } ) def test_create_product_template(self): product_form = Form(self.env["product.template"]) product_form.name = "Test drained weight" product_form.drained_weight = 25.0 product = product_form.save() self.assertEqual(product.drained_weight, 25.0) self.assertEqual(product.product_variant_id.drained_weight, 25.0) product.write( { "attribute_line_ids": [ ( 0, 0, { "attribute_id": self.attribute.id, "value_ids": [ ( 0, 0, { "attribute_id": self.attribute.id, "name": "test value 1", }, ), ( 0, 0, { "attribute_id": self.attribute.id, "name": "test value 2", }, ), ], }, ) ] } ) self.assertEqual(product.drained_weight, 0.0) def test_create_product_product(self): product_form = Form(self.env["product.product"]) product_form.name = "Test drained weight" product_form.drained_weight = 25.0 product = product_form.save() self.assertEqual(product.drained_weight, 25.0) self.assertEqual(product.product_variant_id.drained_weight, 25.0) def test_product_constraint(self): product_form = Form(self.env["product.product"]) product_form.name = "Test drained weight" product_form.drained_weight = 25.0 product_form.net_weight = 22.0 with self.assertRaises(ValidationError): product_form.save()
37.916667
2,730
1,596
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models class ProductTemplate(models.Model): _inherit = "product.template" drained_weight = fields.Float( compute="_compute_drained_weight", inverse="_inverse_drained_weight", digits="Stock Weight", help="Drained Weight of the product, fluid excluded.", store=True, ) @api.depends("product_variant_ids", "product_variant_ids.drained_weight") def _compute_drained_weight(self): unique_variants = self.filtered(lambda tmpl: tmpl.product_variant_count == 1) for template in unique_variants: template.drained_weight = template.product_variant_ids.drained_weight for template in self - unique_variants: template.drained_weight = 0.0 def _inverse_drained_weight(self): for template in self: if len(template.product_variant_ids) == 1: template.product_variant_ids.drained_weight = template.drained_weight @api.model_create_multi def create(self, vals_list): templates = super(ProductTemplate, self).create(vals_list) # This is needed to set given values to first variant after creation for template, vals in zip(templates, vals_list): related_vals = {} if vals.get("drained_weight"): related_vals["drained_weight"] = vals["drained_weight"] if related_vals: template.write(related_vals) return templates
38.926829
1,596
745
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class ProductProduct(models.Model): _inherit = "product.product" drained_weight = fields.Float( digits="Stock Weight", help="Drained Weight of the product, fluid excluded.", ) @api.constrains("drained_weight", "net_weight") def _check_drained_weight(self): for product in self: if product.net_weight and product.drained_weight > product.net_weight: raise ValidationError( _("The drained weight of product must be lower than net_weight.") )
33.863636
745
687
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Vicent Cubells # Copyright 2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Supplier info prices in sales pricelists", "summary": "Allows to create priceslists based on supplier info", "version": "15.0.1.0.2", "category": "Sales", "website": "https://github.com/OCA/product-attribute", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "depends": ["product"], "data": [ "security/res_groups.xml", "views/product_pricelist_item_views.xml", "views/product_supplierinfo_view.xml", ], "installable": True, }
36.157895
687
11,774
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Vicent Cubells # Copyright 2018 Tecnativa - Pedro M. Baeza # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from datetime import date from odoo.tests import common class TestProductSupplierinfo(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.partner_obj = cls.env["res.partner"] cls.currency_rate_obj = cls.env["res.currency.rate"] cls.partner = cls.partner_obj.create({"name": "Partner Test"}) cls.supplier1 = cls.partner_obj.create({"name": "Supplier #1"}) cls.supplier2 = cls.partner_obj.create({"name": "Supplier #2"}) cls.product = cls.env["product.product"].create( { "name": "Product Test", "seller_ids": [ (0, 0, {"name": cls.supplier1.id, "min_qty": 5, "price": 50}), (0, 0, {"name": cls.supplier2.id, "min_qty": 1, "price": 10}), ], } ) cls.product_with_diff_uom = cls.env["product.product"].create( { "name": "Product UOM Test", "uom_id": cls.env.ref("uom.product_uom_unit").id, "uom_po_id": cls.env.ref("uom.product_uom_dozen").id, "seller_ids": [ (0, 0, {"name": cls.supplier1.id, "min_qty": 1, "price": 1200}), ], } ) cls.pricelist = cls.env["product.pricelist"].create( { "name": "Supplierinfo Pricelist", "item_ids": [ ( 0, 0, { "compute_price": "formula", "base": "supplierinfo", "price_discount": 0, "min_quantity": 1.0, }, ), ], } ) @classmethod def _update_rate(cls, currency_id, rate): currency_rate = cls.currency_rate_obj.search( [("name", "=", date.today()), ("currency_id", "=", currency_id.id)], limit=1 ) if not currency_rate: cls.currency_rate_obj.create( {"currency_id": currency_id.id, "rate": rate, "name": date.today()} ) else: currency_rate.write({"rate": rate}) def test_pricelist_based_on_product_category(self): self.pricelist.item_ids[0].write( { "price_discount": 50, "applied_on": "2_product_category", "categ_id": self.env.ref("product.product_category_all").id, } ) self.assertAlmostEqual( self.pricelist.get_product_price(self.product, 1, False), 5.0, ) def test_pricelist_based_on_product(self): self.pricelist.item_ids[0].write( { "applied_on": "1_product", "product_tmpl_id": self.product.product_tmpl_id.id, } ) self.assertAlmostEqual( self.pricelist.get_product_price(self.product, 1, False), 10.0, ) self.assertAlmostEqual( self.product.product_tmpl_id.with_context( pricelist=self.pricelist.id ).price, 10.0, ) def test_pricelist_based_on_product_variant(self): self.pricelist.item_ids[0].write( { "price_discount": -25, "applied_on": "0_product_variant", "product_id": self.product.id, } ) self.assertAlmostEqual( self.pricelist.get_product_price(self.product, 1, False), 12.5, ) self.assertAlmostEqual( self.product.with_context(pricelist=self.pricelist.id).price, 12.5, ) def test_pricelist_min_quantity(self): self.assertAlmostEqual( self.pricelist.get_product_price(self.product, 1, False), 10, ) self.assertAlmostEqual( self.pricelist.get_product_price(self.product, 5, False), 50, ) self.assertAlmostEqual( self.pricelist.get_product_price(self.product, 10, False), 50, ) self.pricelist.item_ids[0].no_supplierinfo_min_quantity = True self.assertAlmostEqual( self.pricelist.get_product_price(self.product, 5, False), 10, ) def test_pricelist_supplier_filter(self): self.assertAlmostEqual( self.pricelist.get_product_price(self.product, 5, False), 50, ) self.pricelist.item_ids[0].filter_supplier_id = self.supplier2.id self.assertAlmostEqual( self.pricelist.get_product_price(self.product, 5, False), 10, ) def test_pricelist_dates(self): """Test pricelist and supplierinfo dates""" self.product.seller_ids.filtered(lambda x: x.min_qty == 5)[ 0 ].date_start = "2018-12-31" self.assertAlmostEqual( self.pricelist.get_product_price( self.product, 5, False, date=date(2019, 1, 1), ), 50, ) def test_pricelist_based_price_round(self): self.pricelist.item_ids[0].write( { "price_discount": 50, "applied_on": "2_product_category", "categ_id": self.product.categ_id.id, "price_round": 1, "price_surcharge": 5, "price_min_margin": 10, "price_max_margin": 100, } ) self.assertAlmostEqual( self.pricelist.get_product_price(self.product, 1, False), 20.0, ) def test_pricelist_based_on_sale_margin(self): self.pricelist.item_ids[0].write( { "applied_on": "1_product", "product_tmpl_id": self.product.product_tmpl_id.id, } ) seller = self.product.seller_ids[0] seller.sale_margin = 50 self.assertAlmostEqual( seller._get_supplierinfo_pricelist_price(), 75.0, ) self.assertAlmostEqual( self.pricelist.get_product_price(self.product, 6, False), 75.0, ) self.assertAlmostEqual( self.product.product_tmpl_id.with_context( pricelist=self.pricelist.id, quantity=6 ).price, 75.0, ) def test_supplierinfo_per_variant(self): tmpl = self.env["product.template"].create( { "name": "Test Product", "attribute_line_ids": [ [ 0, 0, { "attribute_id": self.env.ref( "product.product_attribute_1" ).id, "value_ids": [ ( 4, self.env.ref( "product.product_attribute_value_1" ).id, ), ( 4, self.env.ref( "product.product_attribute_value_2" ).id, ), ], }, ] ], } ) variant1 = tmpl.product_variant_ids[0] variant2 = tmpl.product_variant_ids[1] tmpl.write( { "seller_ids": [ ( 0, 0, { "name": self.supplier1.id, "product_id": variant1.id, "price": 15, }, ), ( 0, 0, { "name": self.supplier1.id, "product_id": variant2.id, "price": 25, }, ), ] } ) self.assertAlmostEqual( self.pricelist.get_product_price(variant1, 1, False), 15.0, ) self.assertAlmostEqual( self.pricelist.get_product_price(variant2, 1, False), 25.0, ) def test_pricelist_and_supplierinfo_currencies(self): """Test when we have 2 records of supplierinfo in two currencies, on a same pricelist as pricelist items, the currency on the supplier that have a different currency will be converted to the pricelist's currency. """ # Setting the currencies and rates for the test, so we can have a supplierinfo # and pricelist with different currencies currency_usd = self.env.ref("base.USD") currency_mxn = self.env.ref("base.MXN") self._update_rate(currency_usd, 1) self._update_rate(currency_mxn, 20) # Setting the item with the product self.pricelist.item_ids[0].write( {"applied_on": "0_product_variant", "product_id": self.product.id} ) self.product.seller_ids[0].currency_id = currency_mxn self.pricelist.currency_id = currency_usd product_seller_price = self.product.seller_ids[0].price product_pricelist_price = self.pricelist.get_product_price( self.product, 5, False ) # The price with MXN Currency will be 50 as is set in the setup self.assertEqual(product_seller_price, 50) # And the price with the pricelist (USD Currency) will be 2.5 self.assertEqual(product_pricelist_price, 2.5) def test_line_uom_and_supplierinfo_uom(self): """Test when we have a product is sold in a different uom from the one on set for purchase. """ # Setting the item with the product self.pricelist.item_ids[0].write( { "applied_on": "0_product_variant", "product_id": self.product_with_diff_uom.id, "price_discount": -20, } ) product_seller_price = self.product_with_diff_uom.seller_ids[0].price uom_dozen = self.env.ref("uom.product_uom_dozen") product_pricelist_price_dozen = self.pricelist.get_product_price( self.product_with_diff_uom.with_context(uom=uom_dozen.id), 1, False ) uom_unit = self.env.ref("uom.product_uom_unit") product_pricelist_price_unit = self.pricelist.get_product_price( self.product_with_diff_uom.with_context(uom=uom_unit.id), 1, False ) # The price with the will be 1200 on the seller (1 Dozen) self.assertEqual(product_seller_price, 1200) # The price with the will be 1200 plus the increment of the 20% which will # give us a total of 1440 (1 Dozen) self.assertEqual(product_pricelist_price_dozen, 1440) # And the price with the pricelist and the uom of Units (Instead of Dozen) # will be 100, plus the 20% the total will be 120 per Unit self.assertEqual(product_pricelist_price_unit, 120)
36.006116
11,774
1,892
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Vicent Cubells # Copyright 2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ProductPricelist(models.Model): _inherit = "product.pricelist" def _compute_price_rule(self, products_qty_partner, date=False, uom_id=False): """Recompute price after calling the atomic super method for getting proper prices when based on supplier info. """ rule_obj = self.env["product.pricelist.item"] result = super()._compute_price_rule(products_qty_partner, date, uom_id) # Make sure all rule records are fetched at once at put in cache rule_obj.browse(x[1] for x in result.values()).mapped("price_discount") context = self.env.context for product, qty, _partner in products_qty_partner: rule = rule_obj.browse(result[product.id][1]) if rule.compute_price == "formula" and rule.base == "supplierinfo": result[product.id] = ( product.sudo()._get_supplierinfo_pricelist_price( rule, date=date or context.get("date", fields.Date.today()), quantity=qty, ), rule.id, ) return result class ProductPricelistItem(models.Model): _inherit = "product.pricelist.item" base = fields.Selection( selection_add=[("supplierinfo", "Prices based on supplier info")], ondelete={"supplierinfo": "set default"}, ) no_supplierinfo_min_quantity = fields.Boolean( string="Ignore Supplier Info Min. Quantity", ) filter_supplier_id = fields.Many2one( comodel_name="res.partner", string="Supplier filter", help="Only match prices from the selected supplier", )
39.416667
1,892
628
py
PYTHON
15.0
# Copyright 2020 Akretion - Mourad EL HADJ MIMOUNE # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ProductSupplierinfo(models.Model): _inherit = "product.supplierinfo" sale_margin = fields.Float( default=0, digits=(16, 2), help="Margin to apply on price to obtain sale price", ) def _get_supplierinfo_pricelist_price(self): self.ensure_one() sale_price = self.price if self.sale_margin: sale_price = (self.price + (self.price * (self.sale_margin / 100))) or 0.0 return sale_price
29.904762
628
4,208
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Vicent Cubells # Copyright 2018 Tecnativa - Pedro M. Baeza # Copyright 2019 Tecnativa - Carlos Dauden # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from datetime import datetime from odoo import fields, models, tools class ProductTemplate(models.Model): _inherit = "product.template" def _get_supplierinfo_pricelist_price( self, rule, date=None, quantity=None, product_id=None ): """Method for getting the price from supplier info.""" self.ensure_one() price = 0.0 product = self.product_variant_id if product_id: product = product.browse(product_id) if rule.no_supplierinfo_min_quantity: # No matter which minimum qty, we'll get every seller. We set a # number absurdidly high quantity = 1e9 # The product_variant_id returns empty recordset if template is not # active, so we must ensure variant exists or _select_seller fails. if product: if type(date) == datetime: date = date.date() seller = product.with_context( override_min_qty=rule.no_supplierinfo_min_quantity )._select_seller( # For a public user this record could be not accessible, but we # need to get the price anyway partner_id=self.env.context.get( "force_filter_supplier_id", rule.sudo().filter_supplier_id ), quantity=quantity, date=date, ) if seller: price = seller._get_supplierinfo_pricelist_price() if price: # We need to convert the price if the pricelist and seller have # different currencies so the price have the pricelist currency if rule.currency_id != seller.currency_id: convert_date = date or self.env.context.get("date", fields.Date.today()) price = seller.currency_id._convert( price, rule.currency_id, seller.company_id, convert_date ) # We have to replicate this logic in this method as pricelist # method are atomic and we can't hack inside. # Verbatim copy of part of product.pricelist._compute_price_rule. qty_uom_id = self._context.get("uom") or self.uom_id.id price_uom = self.env["uom.uom"].browse([qty_uom_id]) # We need to convert the price to the uom used on the sale, if the # uom on the seller is a different one that the one used there. if seller and seller.product_uom != price_uom: price = seller.product_uom._compute_price(price, price_uom) price_limit = price price = (price - (price * (rule.price_discount / 100))) or 0.0 if rule.price_round: price = tools.float_round(price, precision_rounding=rule.price_round) if rule.price_surcharge: price_surcharge = self.uom_id._compute_price( rule.price_surcharge, price_uom ) price += price_surcharge if rule.price_min_margin: price_min_margin = self.uom_id._compute_price( rule.price_min_margin, price_uom ) price = max(price, price_limit + price_min_margin) if rule.price_max_margin: price_max_margin = self.uom_id._compute_price( rule.price_max_margin, price_uom ) price = min(price, price_limit + price_max_margin) return price def price_compute(self, price_type, uom=False, currency=False, company=False): """Return dummy not falsy prices when computation is done from supplier info for avoiding error on super method. We will later fill these with correct values. """ if price_type == "supplierinfo": return dict.fromkeys(self.ids, 1.0) return super().price_compute( price_type, uom=uom, currency=currency, company=company )
44.765957
4,208
1,558
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Vicent Cubells # Copyright 2018 Tecnativa - Pedro M. Baeza # Copyright 2019 Tecnativa - Carlos Dauden # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import models class ProductProduct(models.Model): _inherit = "product.product" def _prepare_sellers(self, params=False): """When we override min qty we want that _select_sellers gives us the first possible seller for every other criteria ignoring the quantity. As supplierinfos are sorted by min_qty descending, we want to revert such order so we get the very first one, which is probably the one to go. """ sellers = super()._prepare_sellers(params) if self.env.context.get("override_min_qty"): sellers = sellers.sorted("min_qty") return sellers def _get_supplierinfo_pricelist_price(self, rule, date=None, quantity=None): return self.product_tmpl_id._get_supplierinfo_pricelist_price( rule, date=date, quantity=quantity, product_id=self.id ) def price_compute(self, price_type, uom=False, currency=False, company=None): """Return dummy not falsy prices when computation is done from supplier info for avoiding error on super method. We will later fill these with correct values. """ if price_type == "supplierinfo": return dict.fromkeys(self.ids, 1.0) return super().price_compute( price_type, uom=uom, currency=currency, company=company )
42.108108
1,558
591
py
PYTHON
15.0
# Copyright 2021 Camptocamp SA # @author Iván Todorovich <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Sale Product Template Tags", "summary": "Show product tags menu in Sale app", "version": "15.0.1.0.1", "license": "AGPL-3", "author": "Camptocamp SA, Odoo Community Association (OCA)", "website": "https://github.com/OCA/product-attribute", "depends": ["product_template_tags", "sale"], "data": ["views/product_template_tag.xml"], "maintainers": ["ivantodorovich"], "auto_install": True, }
36.875
590
528
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import SUPERUSER_ID, api def post_init_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) group_id = env.ref("product_multi_price.group_show_multi_prices").id default_user = env.ref("base.default_user") user = ( env["res.users"].with_context(active_test=False).search([("share", "=", False)]) ) (user - default_user).write({"groups_id": [(4, group_id, None)]})
37.714286
528
769
py
PYTHON
15.0
# Copyright 2020 Tecnativa - David Vidal # Copyright 2020 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Product Multi Price", "version": "15.0.1.0.1", "author": "Tecnativa," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/product-attribute", "category": "Product Management", "license": "AGPL-3", "depends": ["product"], "data": [ "security/ir.model.access.csv", "security/multi_price_security.xml", "views/multi_price_views.xml", "views/product_pricelist_views.xml", "views/product_views.xml", ], "demo": ["demo/multi_price_demo_data.xml"], "post_init_hook": "post_init_hook", "installable": True, }
34.954545
769
3,692
py
PYTHON
15.0
# Copyright 2020 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase class TestProductMultiPrice(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.price_name_obj = cls.env["product.multi.price.name"] cls.price_field_1 = cls.price_name_obj.create({"name": "test_field_1"}) cls.price_field_2 = cls.price_name_obj.create({"name": "test_field_2"}) prod_tmpl_obj = cls.env["product.template"] cls.prod_1 = prod_tmpl_obj.create( { "name": "Test Product Template", "price_ids": [ (0, 0, {"name": cls.price_field_1.id, "price": 5.5}), ( 0, 0, {"name": cls.price_field_2.id, "price": 20.0}, ), ], } ) cls.prod_att_1 = cls.env["product.attribute"].create({"name": "Color"}) cls.prod_attr1_v1 = cls.env["product.attribute.value"].create( {"name": "red", "attribute_id": cls.prod_att_1.id} ) cls.prod_attr1_v2 = cls.env["product.attribute.value"].create( {"name": "blue", "attribute_id": cls.prod_att_1.id} ) cls.prod_2 = prod_tmpl_obj.create( { "name": "Test Product 2 With Variants", "attribute_line_ids": [ ( 0, 0, { "attribute_id": cls.prod_att_1.id, "value_ids": [ (6, 0, [cls.prod_attr1_v1.id, cls.prod_attr1_v2.id]) ], }, ) ], } ) cls.prod_prod_2_1 = cls.prod_2.product_variant_ids[0] cls.prod_prod_2_2 = cls.prod_2.product_variant_ids[1] cls.prod_prod_2_1.write( { "price_ids": [ (0, 0, {"name": cls.price_field_1.id, "price": 6.6}), (0, 0, {"name": cls.price_field_2.id, "price": 7.7}), ], } ) cls.prod_prod_2_2.write( { "price_ids": [ (0, 0, {"name": cls.price_field_1.id, "price": 8.8}), (0, 0, {"name": cls.price_field_2.id, "price": 9.9}), ], } ) cls.pricelist = cls.env["product.pricelist"].create( { "name": "Test pricelist", "item_ids": [ ( 0, 0, { "compute_price": "formula", "base": "multi_price", "multi_price_name": cls.price_field_1.id, "price_discount": 10, "applied_on": "3_global", }, ) ], } ) def test_product_multi_price_pricelist(self): """Pricelists based on multi prices for templates or variants""" price = self.prod_1.with_context(pricelist=self.pricelist.id).price self.assertAlmostEqual(price, 4.95) price = self.prod_prod_2_1.with_context(pricelist=self.pricelist.id).price self.assertAlmostEqual(price, 5.94) price = self.prod_prod_2_2.with_context(pricelist=self.pricelist.id).price self.assertAlmostEqual(price, 7.92)
38.863158
3,692
1,452
py
PYTHON
15.0
# Copyright 2020 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class ProductPricelist(models.Model): _inherit = "product.pricelist" def _compute_price_rule(self, products_qty_partner, date=False, uom_id=False): """Recompute price after calling the atomic super method for getting proper prices when based on multi price. """ rule_obj = self.env["product.pricelist.item"] result = super()._compute_price_rule(products_qty_partner, date, uom_id) # Make sure all rule records are fetched at once and put in cache rule_obj.browse(x[1] for x in result.values()).mapped("price_discount") for product, _qty, _partner in products_qty_partner: rule = rule_obj.browse(result[product.id][1]) if rule.compute_price == "formula" and rule.base == "multi_price": result[product.id] = ( product._get_multiprice_pricelist_price(rule), rule.id, ) return result class ProductPricelistItem(models.Model): _inherit = "product.pricelist.item" base = fields.Selection( selection_add=[("multi_price", "Other Price")], ondelete={"multi_price": "set default"}, ) multi_price_name = fields.Many2one( comodel_name="product.multi.price.name", string="Other Price Name", )
39.243243
1,452
1,924
py
PYTHON
15.0
# Copyright 2020 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models class ProductTemplate(models.Model): _inherit = "product.template" price_ids = fields.One2many( comodel_name="product.multi.price", compute="_compute_price_ids", inverse="_inverse_price_ids", string="Other Prices", ) @api.depends("product_variant_ids", "product_variant_ids.price_ids") def _compute_price_ids(self): for p in self: if len(p.product_variant_ids) == 1: p.price_ids = p.product_variant_ids.price_ids else: p.price_ids = False def _inverse_price_ids(self): for p in self: if len(p.product_variant_ids) == 1: p.product_variant_ids.price_ids = p.price_ids def _get_multiprice_pricelist_price(self, rule): if len(self.product_variant_ids) == 1: return self.product_variant_ids._get_multiprice_pricelist_price(rule) return 0 @api.model def create(self, vals): """Overwrite creation for rewriting the prices (if set and having only one variant), after the variant creation, that is performed in super. """ template = super().create(vals) if vals.get("price_ids"): template.write({"price_ids": vals.get("price_ids")}) return template def price_compute(self, price_type, uom=False, currency=False, company=False): """Return temporary prices when computation is done for multi price for avoiding error on super method. We will later fill these with the correct values. """ if price_type == "multi_price": return dict.fromkeys(self.ids, 1.0) return super().price_compute( price_type, uom=uom, currency=currency, company=company )
36.301887
1,924
2,656
py
PYTHON
15.0
# Copyright 2020 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models, tools class ProductProduct(models.Model): _inherit = "product.product" price_ids = fields.One2many( comodel_name="product.multi.price", inverse_name="product_id", string="Other Prices", ) def _convert_to_price_uom(self, price): qty_uom_id = self._context.get("uom") or self.uom_id.id price_uom = self.env["uom.uom"].browse([qty_uom_id]) return self.uom_id._compute_price(price, price_uom) def _get_multiprice_pricelist_price(self, rule): """Method for getting the price from multi price.""" self.ensure_one() company = rule.company_id or self.env.user.company_id price = ( self.env["product.multi.price"] .sudo() .search( [ ("company_id", "=", company.id), ("name", "=", rule.multi_price_name.id), ("product_id", "=", self.id), ] ) .price or 0 ) if price: # We have to replicate this logic in this method as pricelist # method are atomic and we can't hack inside. # Verbatim copy of part of product.pricelist._compute_price_rule. price_limit = price price = (price - (price * (rule.price_discount / 100))) or 0.0 if rule.price_round: price = tools.float_round(price, precision_rounding=rule.price_round) if rule.price_surcharge: price_surcharge = self._convert_to_price_uom(rule.price_surcharge) price += price_surcharge if rule.price_min_margin: price_min_margin = self._convert_to_price_uom(rule.price_min_margin) price = max(price, price_limit + price_min_margin) if rule.price_max_margin: price_max_margin = self._convert_to_price_uom(rule.price_max_margin) price = min(price, price_limit + price_max_margin) return price def price_compute(self, price_type, uom=False, currency=False, company=False): """Return temporary prices when computation is done for multi price for avoiding error on super method. We will later fill these with the correct values. """ if price_type == "multi_price": return dict.fromkeys(self.ids, 1.0) return super().price_compute( price_type, uom=uom, currency=currency, company=company )
40.861538
2,656
1,640
py
PYTHON
15.0
# Copyright 2020 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models class ProductMultiPrice(models.Model): _name = "product.multi.price" _rec_name = "name_text" _description = "Product Multiple Prices" name = fields.Many2one("product.multi.price.name", required=True) name_text = fields.Char(related="name.name") product_id = fields.Many2one( comodel_name="product.product", required=True, ondelete="cascade", ) price = fields.Float( digits="Product Price", ) company_id = fields.Many2one( comodel_name="res.company", related="name.company_id", store=True, readonly=True, ) _sql_constraints = [ ( "multi_price_uniq", "unique(name, product_id, company_id)", "A field name cannot be assigned to a product twice for the same " "company", ), ] class ProductMultiPriceName(models.Model): _name = "product.multi.price.name" _description = "Multi Price Record Options" @api.model def _get_company(self): return self._context.get("company_id", self.env.company) name = fields.Char(required=True, string="Price Field Name") company_id = fields.Many2one( comodel_name="res.company", required=True, default=lambda self: self._get_company(), ) _sql_constraints = [ ( "multi_price_name_uniq", "unique(name, company_id)", "Prices Names must be unique per company", ), ]
27.79661
1,640
762
py
PYTHON
15.0
# © 2015 David BEAL @ Akretion # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Product Profile", "version": "15.0.1.0.0", "author": "Akretion, Odoo Community Association (OCA)", "summary": "Allow to configure a product in 1 click", "category": "product", "development_status": "Production/Stable", "depends": ["sale_management"], "website": "https://github.com/OCA/product-attribute", "data": [ "security/group.xml", "views/product_view.xml", "views/config_view.xml", "security/ir.model.access.csv", ], "demo": ["demo/profile_demo.xml"], "installable": True, "license": "AGPL-3", "maintainers": ["bealdav", "sebastienbeau", "kevinkhao"], }
33.086957
761
529
py
PYTHON
15.0
# Copyright 2023 bosd # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openupgradelib import openupgrade def rename_type_to_detailed_type(env): if openupgrade.column_exists(env.cr, "product_profile", "type"): openupgrade.rename_columns( env.cr, { "product_profile": [ ("type", "detailed_type"), ], }, ) @openupgrade.migrate() def migrate(env, version): rename_type_to_detailed_type(env)
25.190476
529
566
py
PYTHON
15.0
# © 2015 David BEAL @ Akretion # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" group_product_profile = fields.Boolean( string="Display Product Profile fields", implied_group="product_profile.group_product_profile_user", help="Display fields computed by product profile " "module.\nFor debugging purpose see menu\nSales > Configuration \n> Products" "\n> Product Profiles", )
35.3125
565
11,024
py
PYTHON
15.0
# © 2015 David BEAL @ Akretion # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import logging from copy import deepcopy from lxml import etree from odoo import _, api, fields, models from odoo.exceptions import UserError # Prefix name of profile fields setting a default value, # not an immutable value according to profile PROF_DEFAULT_STR = "profile_default_" LEN_DEF_STR = len(PROF_DEFAULT_STR) _logger = logging.getLogger(__name__) def format_except_message(error, field, self): value = self.profile_id[field] model = type(self)._name message = _( "Issue\n------\n" "%(error)s\n %(value)s value can't be applied to %(field)s field." "\nThere is no matching value between 'Product Profiles' " "\nand %(model)s models for this field.\n\n" "Resolution\n----------\n" "Check your settings on Profile model:\n Sales > Configuration \n> Products" "\n> Product Profiles" ) % { "error": error, "value": value, "field": field, "model": model, } return message def get_profile_fields_to_exclude(): # These fields must not be synchronized between product.profile # and product.template/product return models.MAGIC_COLUMNS + [ "name", "explanation", "sequence", "id", "display_name", "__last_update", ] class ProductProfile(models.Model): _name = "product.profile" _order = "sequence, name" _description = "Product Profile" name = fields.Char( required=True, help="Profile name displayed on product template\n" "(not synchronized with product.template fields)", ) sequence = fields.Integer( help="Defines the order of the entries of profile_id field\n" "(not synchronized with product.template fields)" ) explanation = fields.Text( required=True, help="An explanation on the selected profile\n" "(not synchronized with product.template fields)", ) detailed_type = fields.Selection( selection=[("consu", "Consumable"), ("service", "Service")], required=True, default="consu", help="See 'detailed_type' field in product.template", ) def write(self, vals): """Profile update can impact products: we take care to propagate ad hoc changes. If on the profile at least one field has changed, re-apply its values on relevant products""" excludable_fields = get_profile_fields_to_exclude() values_to_keep = deepcopy(vals) for key in vals: discard_value = ( key.startswith(PROF_DEFAULT_STR) or key in excludable_fields or self.check_useless_key_in_vals(vals, key) ) if discard_value: values_to_keep.pop(key) if values_to_keep: self._refresh_products_vals() res = super().write(vals) return res def _refresh_products_vals(self): """Reapply profile values on products""" for rec in self: products = self.env["product.product"].search([("profile_id", "=", rec.id)]) if products: _logger.info( " >>> %s Products updating after updated '%s' pro" "duct profile" % (len(products), rec.name) ) data = products._get_vals_from_profile( {"profile_id": rec.id}, ignore_defaults=True ) products.write(data) @api.model def check_useless_key_in_vals(self, vals, key): """If replacing values are the same than in db, we remove them. Use cases: 1/ if in edition mode you switch a field from value A to value B and then go back to value A then save form, field is in vals whereas it shouldn't. 2/ if profile data are in csv file there are processed each time module containing csv is loaded we remove field from vals to minimize impact on products """ comparison_value = self[key] if self._fields[key].type == "many2one": comparison_value = self[key].id elif self._fields[key].type == "many2many": comparison_value = [ (6, False, self[key].ids), ] return vals[key] == comparison_value @api.model def fields_view_get( self, view_id=None, view_type="form", toolbar=False, submenu=False ): """Display a warning for end user if edit record""" res = super().fields_view_get( view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu, ) if view_type == "form": style = "alert alert-warning oe_text_center oe_edit_only" alert = etree.Element("h2", {"class": style}) alert.text = _( "If you update this profile, all products " "using this profile could also be updated. " "Changes can take a while." ) doc = etree.XML(res["arch"]) doc[0].addprevious(alert) res["arch"] = etree.tostring(doc, pretty_print=True) return res class ProductMixinProfile(models.AbstractModel): _name = "product.mixin.profile" _description = "Product Profile Mixin" @api.model def _get_profile_fields(self): fields_to_exclude = set(get_profile_fields_to_exclude()) return [ field for field in self.env["product.profile"]._fields.keys() if field not in fields_to_exclude ] @api.model def _get_vals_from_profile(self, product_values, ignore_defaults=False): res = {} profile_obj = self.env["product.profile"] fields = self._get_profile_fields() profile_vals = profile_obj.browse(product_values["profile_id"]).read(fields)[0] profile_vals.pop("id") profile_vals = self._reformat_relationals(profile_vals) for key, val in profile_vals.items(): if key[:LEN_DEF_STR] == PROF_DEFAULT_STR: if not ignore_defaults: destination_field = key[LEN_DEF_STR:] res[destination_field] = val else: res[key] = val return res def _reformat_relationals(self, profile_vals): res = deepcopy(profile_vals) profile_obj = self.env["product.profile"] for key, value in profile_vals.items(): if value and profile_obj._fields[key].type == "many2one": # m2o value is a tuple res[key] = value[0] if profile_obj._fields[key].type == "many2many": res[key] = [(6, 0, value)] return res @api.onchange("profile_id") def _onchange_from_profile(self): """Update product fields with product.profile corresponding fields""" self.ensure_one() if self.profile_id: ignore_defaults = True if self._origin.profile_id else False values = self._get_vals_from_profile( {"profile_id": self.profile_id.id}, ignore_defaults=ignore_defaults, ) for field, value in values.items(): try: self[field] = value except Exception as e: raise UserError(format_except_message(e, field, self)) from e @api.model def create(self, vals): if vals.get("profile_id"): vals.update(self._get_vals_from_profile(vals, ignore_defaults=False)) return super().create(vals) def write(self, vals): profile_changed = vals.get("profile_id") if profile_changed: recs_has_profile = self.filtered(lambda r: r.profile_id) recs_no_profile = self - recs_has_profile recs_has_profile.write( self._get_vals_from_profile(vals, ignore_defaults=True) ) recs_no_profile.write( self._get_vals_from_profile(vals, ignore_defaults=False) ) return super().write(vals) @api.model def _get_default_profile_fields(self): "Get profile fields with prefix PROF_DEFAULT_STR" return [ x for x in self.env["product.profile"]._fields.keys() if x[:LEN_DEF_STR] == PROF_DEFAULT_STR ] @api.model def _customize_view(self, res, view_type, profile_domain=None): profile_group = self.env.ref("product_profile.group_product_profile_user") users_in_profile_group = [user.id for user in profile_group.users] default_fields = self._get_default_profile_fields() if view_type == "form": doc = etree.XML(res["arch"]) fields = self._get_profile_fields() if self.env.uid not in users_in_profile_group: attrs = {"invisible": [("profile_id", "!=", False)]} else: attrs = {"readonly": [("profile_id", "!=", False)]} paths = ["//field[@name='%s']", "//label[@for='%s']"] for field in fields: if field not in default_fields: # default fields shouldn't be modified for path in paths: node = doc.xpath(path % field) if node: for current_node in node: current_node.set("attrs", str(attrs)) res["arch"] = etree.tostring(doc, pretty_print=True) elif view_type == "search": # Allow to dynamically create search filters for each profile filters_to_create = self._get_profiles_to_filter(profile_domain) doc = etree.XML(res["arch"]) node = doc.xpath("//filter[1]") if node: for my_filter in filters_to_create: elm = etree.Element( "filter", **self._customize_profile_filters(my_filter) ) node[0].addprevious(elm) node[0].addprevious(etree.Element("separator")) res["arch"] = etree.tostring(doc, pretty_print=True) return res def _get_profiles_to_filter(self, profile_domain=None): """Inherit if you want that some profiles doesn't have a filter""" if profile_domain is None: profile_domain = [] return [ (x.id, x.name) for x in self.env["product.profile"].search(profile_domain) ] @api.model def _customize_profile_filters(self, my_filter): """Inherit if you to customize search filter display""" return { "string": "%s" % my_filter[1], "help": "Filtering by Product Profile", "domain": "[('profile_id','=', %s)]" % my_filter[0], }
37.493197
11,023
1,538
py
PYTHON
15.0
# © 2015 David BEAL @ Akretion # 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", "product.mixin.profile"] _name = "product.template" profile_id = fields.Many2one(comodel_name="product.profile", string="Profile") profile_explanation = fields.Text(related="profile_id.explanation", readonly=True) @api.model def _fields_view_get( self, view_id=None, view_type="form", toolbar=False, submenu=False ): """fields_view_get comes from Model (not AbstractModel)""" res = super()._fields_view_get( view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu, ) return self._customize_view(res, view_type) class ProductProduct(models.Model): _inherit = ["product.product", "product.mixin.profile"] _name = "product.product" @api.model def fields_view_get( self, view_id=None, view_type="form", toolbar=False, submenu=False ): view = self.env["ir.ui.view"].browse(view_id) res = super().fields_view_get( view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu, ) # This is a simplified view for which the customization do not apply if view.name == "product.product.view.form.easy": return res return self._customize_view(res, view_type)
33.413043
1,537
808
py
PYTHON
15.0
# Copyright (C) 2021 - Today: GRAP (http://www.grap.coop) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Products - Net Weight", "summary": "Add 'Net Weight' on product models", "version": "15.0.2.0.0", "category": "Product", "author": "GRAP,Odoo Community Association (OCA)", "maintainers": ["legalsylvain"], "website": "https://github.com/OCA/product-attribute", "license": "AGPL-3", "depends": ["product"], "data": [ "views/view_product_product.xml", "views/view_product_template.xml", ], "demo": [ "demo/product_product.xml", ], "images": [ "static/description/product_product_form.png", ], "installable": True, }
32.32
808
2,678
py
PYTHON
15.0
# Copyright 2023 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.exceptions import ValidationError from odoo.tests.common import Form, TransactionCase class TestProductNetWeight(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.attribute = cls.env["product.attribute"].create( { "name": "test attribute", "display_type": "select", } ) def test_create_product_template(self): product_form = Form(self.env["product.template"]) product_form.name = "Test net weight" product_form.net_weight = 25.0 product = product_form.save() self.assertEqual(product.net_weight, 25.0) self.assertEqual(product.product_variant_id.net_weight, 25.0) product.write( { "attribute_line_ids": [ ( 0, 0, { "attribute_id": self.attribute.id, "value_ids": [ ( 0, 0, { "attribute_id": self.attribute.id, "name": "test value 1", }, ), ( 0, 0, { "attribute_id": self.attribute.id, "name": "test value 2", }, ), ], }, ) ] } ) self.assertEqual(product.net_weight, 0.0) def test_create_product_product(self): product_form = Form(self.env["product.product"]) product_form.name = "Test net weight" product_form.net_weight = 25.0 product = product_form.save() self.assertEqual(product.net_weight, 25.0) self.assertEqual(product.product_variant_id.net_weight, 25.0) def test_product_constraint(self): product_form = Form(self.env["product.product"]) product_form.name = "Test net weight" product_form.net_weight = 25.0 product_form.weight = 22.0 with self.assertRaises(ValidationError): product_form.save()
37.194444
2,678
1,647
py
PYTHON
15.0
# Copyright (C) 2021 - Today: GRAP (http://www.grap.coop) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # Copyright 2023 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class ProductTemplate(models.Model): _inherit = "product.template" net_weight = fields.Float( compute="_compute_net_weight", inverse="_inverse_net_weight", digits="Stock Weight", help="Net Weight of the product, container excluded.", store=True, ) # Explicit field, renaming it weight = fields.Float(string="Gross Weight") @api.depends("product_variant_ids", "product_variant_ids.net_weight") def _compute_net_weight(self): unique_variants = self.filtered(lambda tmpl: tmpl.product_variant_count == 1) for template in unique_variants: template.net_weight = template.product_variant_ids.net_weight for template in self - unique_variants: template.net_weight = 0.0 def _inverse_net_weight(self): for template in self: if len(template.product_variant_ids) == 1: template.product_variant_ids.net_weight = template.net_weight @api.model_create_multi def create(self, vals_list): templates = super(ProductTemplate, self).create(vals_list) # This is needed to set given values to first variant after creation for template, vals in zip(templates, vals_list): if vals.get("net_weight"): template.write({"net_weight": vals["net_weight"]}) return templates
38.302326
1,647
879
py
PYTHON
15.0
# Copyright (C) 2021 - Today: GRAP (http://www.grap.coop) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class ProductProduct(models.Model): _inherit = "product.product" net_weight = fields.Float( digits="Stock Weight", help="Net Weight of the product, container excluded.", ) # Explicit field, renaming it weight = fields.Float(string="Gross Weight") @api.constrains("net_weight", "weight") def _check_net_weight(self): for product in self: if product.weight and product.net_weight > product.weight: raise ValidationError( _("The net weight of product must be lower than gross weight.") )
33.807692
879
555
py
PYTHON
15.0
{ "name": "Product Attribute Value Menu", "summary": """Product attributes values tree and form. Import attribute values.""", "version": "15.0.1.1.1", "website": "https://github.com/OCA/product-attribute", "author": "Ilyas, Ooops404, Odoo Community Association (OCA)", "license": "LGPL-3", "category": "Stock", "depends": ["sale_stock"], "data": [ "views/product_template_attribute_value_views.xml", "views/product_attribute_value_views.xml", ], "installable": True, "application": False, }
34.6875
555
1,313
py
PYTHON
15.0
# Copyright 2022 ForgeFlow, S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class ProductAttributeValue(models.Model): _inherit = "product.attribute.value" product_count = fields.Integer(string="Product", compute="_compute_product_count") @api.depends("pav_attribute_line_ids") def _compute_product_count(self): for value in self: value.product_count = len(value.pav_attribute_line_ids) def action_view_product(self): action = self.env["ir.actions.act_window"]._for_xml_id( "product.product_template_action" ) products = self.pav_attribute_line_ids.mapped("product_tmpl_id") if len(products) > 1: action["domain"] = [("id", "in", products.ids)] elif products: form_view = [ (self.env.ref("product.product_template_only_form_view").id, "form") ] if "views" in action: action["views"] = form_view + [ (state, view) for state, view in action["views"] if view != "form" ] else: action["views"] = form_view action["res_id"] = products.id action["context"] = self.env.context return action
35.486486
1,313
603
py
PYTHON
15.0
# Copyright 2021 Camptocamp SA # @author Iván Todorovich <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Purchase Product Template Tags", "summary": "Show product tags menu in Purchase app", "version": "15.0.1.0.0", "license": "AGPL-3", "author": "Camptocamp SA, Odoo Community Association (OCA)", "website": "https://github.com/OCA/product-attribute", "depends": ["product_template_tags", "purchase"], "data": ["views/product_template_tag.xml"], "maintainers": ["ivantodorovich"], "auto_install": True, }
37.625
602
682
py
PYTHON
15.0
# Copyright 2023 Moduon Team S.L. <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Product Sticker", "version": "15.0.1.1.0", "author": "Moduon, Odoo Community Association (OCA)", "license": "AGPL-3", "website": "https://github.com/OCA/product-attribute", "category": "Sales Management", "depends": [ "product", ], "data": [ "security/ir.model.access.csv", "views/product_sticker_views.xml", "views/product_attribute_views.xml", "views/product_template_views.xml", "data/menus.xml", ], "maintainers": ["Shide"], "installable": True, }
29.652174
682
1,739
py
PYTHON
15.0
from .common import ProductStickerCommon class TestStickersOnProducts(ProductStickerCommon): def test_global_stickers(self): stickers = self.product_as500.get_product_stickers() self.assertEqual(len(stickers), 1, "Global sticker must be present") def test_product_template_stickers(self): stickers = self.product_as400.get_product_stickers() self.assertEqual( len(stickers), 1, "Attribute that create variants has been generated" ) # Add a new attribute value to the template self.product_as400.attribute_line_ids.filtered( lambda al: al.attribute_id == self.att_license ).write( { "value_ids": [(4, self.att_license_freemium.id)], } ) new_stickers = self.product_as400.get_product_stickers() self.assertEqual( len(new_stickers), 2, "Attribute Value sticker must be present" ) def test_product_product_stickers(self): stickers = self.product_as400.product_variant_ids[0].get_product_stickers() self.assertEqual( len(stickers), 2, "Attribute that create variants has been generated" ) # Add a new attribute value to the template self.product_as400.attribute_line_ids.filtered( lambda al: al.attribute_id == self.att_license ).write( { "value_ids": [(4, self.att_license_freemium.id)], } ) new_stickers = self.product_as400.product_variant_ids[0].get_product_stickers() self.assertEqual( len(new_stickers), 3, "Sticker for Attribute with no create variants not present", )
38.644444
1,739
4,430
py
PYTHON
15.0
import base64 import io from PIL import Image from odoo.tests import common, tagged @tagged("post_install", "-at_install") class ProductStickerCommon(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() pa_model = cls.env["product.attribute"] pav_model = cls.env["product.attribute.value"] ps_model = cls.env["product.sticker"] pt_model = cls.env["product.template"] # No Variant Attribute cls.att_platform = pa_model.create( {"name": "Platform", "create_variant": "always"} ) cls.att_platform_linux = pav_model.create( {"attribute_id": cls.att_platform.id, "name": "Linux"} ) cls.att_platform_windows = pav_model.create( {"attribute_id": cls.att_platform.id, "name": "Windows"} ) # Create Variant Attribute cls.att_license = pa_model.create( {"name": "License", "create_variant": "no_variant"} ) cls.att_license_otp = pav_model.create( {"attribute_id": cls.att_license.id, "name": "One-time Payment"} ) cls.att_license_subscription = pav_model.create( {"attribute_id": cls.att_license.id, "name": "Subscription"} ) cls.att_license_freemium = pav_model.create( {"attribute_id": cls.att_license.id, "name": "Freemium"} ) # Products cls.product_as400 = pt_model.create( { "name": "Amazing Software 400 - Diskette", "default_code": "AS400", "attribute_line_ids": [ ( 0, 0, { "attribute_id": cls.att_platform.id, "value_ids": [ ( 6, 0, [ cls.att_platform_linux.id, cls.att_platform_windows.id, ], ) ], }, ), ( 0, 0, { "attribute_id": cls.att_license.id, "value_ids": [ ( 6, 0, [ cls.att_license_otp.id, cls.att_license_subscription.id, ], ) ], }, ), ], } ) cls.product_as500 = pt_model.create( { "name": "Awful Software 500", "default_code": "AS500", } ) # Product Stickers f_img = io.BytesIO() Image.new("RGB", (500, 500), "#FFFFFF").save(f_img, "PNG") f_img.seek(0) f_img_b64 = base64.b64encode(f_img.read()) cls.ps_global = ps_model.create( { "name": "global_sticker", "image_1920": f_img_b64, "company_id": False, } ) cls.ps_att_cc = ps_model.create( { "name": "attribute_platform_cross_company_sticker", "image_1920": f_img_b64, "company_id": False, "product_category_id": False, "product_attribute_id": cls.att_platform.id, "product_attribute_value_id": False, "show_sticker_note": False, } ) cls.ps_attv_cc = ps_model.create( { "name": "attribute_license_freemium_value_cross_company_sticker", "image_1920": f_img_b64, "company_id": False, "product_category_id": False, "product_attribute_id": cls.att_license.id, "product_attribute_value_id": cls.att_license_freemium.id, "show_sticker_note": True, } )
36.01626
4,430
276
py
PYTHON
15.0
from odoo import fields, models class ProductAttributeValue(models.Model): _name = "product.attribute.value" _inherit = ["product.attribute.value", "product.sticker.mixin"] sticker_ids = fields.One2many( inverse_name="product_attribute_value_id", )
27.6
276
1,084
py
PYTHON
15.0
from odoo import api, models class ProductTemplate(models.Model): _inherit = "product.template" def action_view_stickers(self): """Action to open the Stickers related to this Product Template""" stickers = self.get_product_stickers() action = self.env.ref("product_sticker.action_product_sticker").read()[0] action["domain"] = [("id", "in", stickers.ids)] return action def _get_sticker_arguments(self): no_variant_attribute_lines = self.attribute_line_ids.filtered( lambda al: al.attribute_id.create_variant == "no_variant" ) return { "categories": self.categ_id, "attributes": no_variant_attribute_lines.attribute_id, "attribute_values": no_variant_attribute_lines.value_ids, } @api.returns("product.sticker") def get_product_stickers(self): """Attribute Stickers related to this Product Template and its variants""" return self.env["product.sticker"]._get_stickers( **self._get_sticker_arguments() )
37.37931
1,084
1,150
py
PYTHON
15.0
from odoo import api, models class ProductProduct(models.Model): _inherit = "product.product" def action_view_stickers(self): """Action to open the Stickers related to this Product""" stickers = self.get_product_stickers() action = self.env.ref("product_sticker.action_product_sticker").read()[0] action["domain"] = [("id", "in", stickers.ids)] return action def _get_sticker_arguments(self): pavs = self.product_template_variant_value_ids.product_attribute_value_id return { "categories": self.categ_id, "attributes": pavs.attribute_id, "attribute_values": pavs, } @api.returns("product.sticker") def get_product_stickers(self): """Product Stickers related to this Product Variant and its Template""" # Product Template: Common stickers pt_stickers = self.product_tmpl_id.get_product_stickers() # Product Product: Specific stickers pp_stickers = self.env["product.sticker"]._get_stickers( **self._get_sticker_arguments() ) return pt_stickers | pp_stickers
37.096774
1,150
877
py
PYTHON
15.0
from odoo import api, fields, models class ProductStickerMixin(models.AbstractModel): _name = "product.sticker.mixin" _description = "Product Sticker Mixin" sticker_ids = fields.One2many( comodel_name="product.sticker", # `inverse_name` will be needed in every _inherit string="Product Stickers", domain=lambda s: s.env["product.sticker"]._build_sticker_domain_company(), ) sticker_count = fields.Integer( compute="_compute_sticker_count", store=True, ) @api.depends("sticker_ids") @api.depends_context("company") def _compute_sticker_count(self): company_domain = self.env["product.sticker"]._build_sticker_domain_company() for record in self: record.sticker_count = len( record.sudo().sticker_ids.filtered_domain(company_domain) )
33.730769
877
253
py
PYTHON
15.0
from odoo import fields, models class ProductAttribute(models.Model): _name = "product.attribute" _inherit = ["product.attribute", "product.sticker.mixin"] sticker_ids = fields.One2many( inverse_name="product_attribute_id", )
25.3
253
6,496
py
PYTHON
15.0
from odoo import api, fields, models from odoo.osv import expression class ProductSticker(models.Model): _name = "product.sticker" _description = "Product Sticker" _inherit = ["image.mixin"] _order = "sequence, id" company_id = fields.Many2one( comodel_name="res.company", string="Company", default=lambda s: s.env.company, ) sequence = fields.Integer(default=10, index=True) name = fields.Char(required=True, translate=True) image_1920 = fields.Image(required=True) image_64 = fields.Image( related="image_1920", max_width=64, max_height=64, store=True, ) product_category_id = fields.Many2one( comodel_name="product.category", string="Category", ondelete="cascade", ) product_attribute_id = fields.Many2one( comodel_name="product.attribute", string="Attribute", ondelete="cascade", ) product_attribute_value_id = fields.Many2one( comodel_name="product.attribute.value", string="Attribute value", ondelete="cascade", domain="[('attribute_id', '=', product_attribute_id)]", ) show_sticker_note = fields.Boolean( string="Sticker Note", help="If checked, the note will be displayed with the sticker", ) # You can use <t-esc="sticker.note" style="white-space: pre;" /> to display # break lines in reports note = fields.Text( translate=True, help="Used to display a note with the sticker", ) @api.onchange("product_attribute_id") def _onchange_product_attribute_id(self): pav_dom = [] if self.product_attribute_id: pav_dom = [("attribute_id", "=", self.product_attribute_id.id)] pav_value = False if self.product_attribute_value_id in self.product_attribute_id.value_ids: pav_value = self.product_attribute_value_id.id return { "domain": {"product_attribute_value_id": pav_dom}, "value": {"product_attribute_value_id": pav_value}, } @api.onchange("product_attribute_value_id") def _onchange_product_attribute_value_id(self): if self.product_attribute_value_id: return { "value": { "product_attribute_id": self.product_attribute_value_id.attribute_id.id }, } return {} @api.model def _build_sticker_domain_company(self): """Build domain for companies""" return expression.OR( [ [("company_id", "=", False)], [ ( "company_id", "in", self.env.context.get( "allowed_company_ids", self.env.company.ids ), ) ], ] ) @api.model def _build_sticker_domain_category(self, categories=None): """Build domain for categories""" category_domain = [("product_category_id", "=", False)] if categories: category_domain = expression.OR( [ category_domain, [("product_category_id", "child_of", categories.ids)], ] ) return category_domain @api.model def _build_sticker_domain_attributes(self, attributes=None, attribute_values=None): """Build domain for attributes and attribute values""" attribute_domain = [ ("product_attribute_id", "=", False), ("product_attribute_value_id", "=", False), ] if attribute_values: full_attributes = attributes | attribute_values.mapped("attribute_id") attribute_domain = expression.OR( [ attribute_domain, expression.OR( [ [ ( "product_attribute_value_id", "in", attribute_values.ids, ) ], expression.AND( [ [("product_attribute_value_id", "=", False)], [ ( "product_attribute_id", "in", full_attributes.ids, ) ], ] ), ] ), ] ) elif attributes: attribute_domain = expression.OR( [ attribute_domain, expression.AND( [ [("product_attribute_value_id", "=", False)], expression.OR( [ [("product_attribute_id", "in", attributes.ids)], [("product_attribute_id", "=", False)], ] ), ] ), ] ) return attribute_domain def _get_sticker_domains( self, categories=None, attributes=None, attribute_values=None ): company_domain = self._build_sticker_domain_company() category_domain = self._build_sticker_domain_category(categories) attribute_domain = self._build_sticker_domain_attributes( attributes, attribute_values ) return [company_domain, category_domain, attribute_domain] @api.model def _get_stickers(self, categories=None, attributes=None, attribute_values=None): """Get stickers for given categories, attributes and attribute values""" sticker_domain = expression.AND( self._get_sticker_domains( categories=categories, attributes=attributes, attribute_values=attribute_values, ) ) return self.sudo().search(sticker_domain)
35.497268
6,496
469
py
PYTHON
15.0
# Copyright 2021 Akretion # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Product Attribute Archive", "summary": """ Add an active field on product attributes""", "version": "15.0.1.0.1", "license": "AGPL-3", "author": "Akretion,Odoo Community Association (OCA)", "depends": ["product"], "data": [ "views/product_attribute.xml", ], "website": "https://github.com/OCA/product-attribute", }
29.3125
469
252
py
PYTHON
15.0
# Copyright 2021 Akretion # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class ProductAttributeValue(models.Model): _inherit = "product.attribute.value" active = fields.Boolean(default=True)
25.2
252
241
py
PYTHON
15.0
# Copyright 2021 Akretion # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class ProductAttribute(models.Model): _inherit = "product.attribute" active = fields.Boolean(default=True)
24.1
241
879
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Carlos Dauden # Copyright 2020 Tecnativa - João Marques # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Product Pricelist Direct Print", "summary": "Print price list from menu option, product templates, " "products variants or price lists", "version": "15.0.1.1.1", "category": "Product", "website": "https://github.com/OCA/product-attribute", "author": "Tecnativa, " "Odoo Community Association (OCA)", "license": "AGPL-3", "depends": ["sale", "report_xlsx"], "data": [ "security/ir.model.access.csv", "views/report_product_pricelist.xml", # 'mail_template_data' has to be after 'report_product_pricelist' "data/mail_template_data.xml", "report/product_pricelist_xlsx.xml", "wizards/product_pricelist_print_view.xml", ], }
39.909091
878
497
py
PYTHON
15.0
# Copyright 2023 Tecnativa - Carlos Roca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openupgradelib import openupgrade @openupgrade.migrate() def migrate(env, version): openupgrade.load_data( env.cr, "product_pricelist_direct_print", "migrations/15.0.1.1.1/noupdate_changes.xml", ) openupgrade.delete_record_translations( env.cr, "product_pricelist_direct_print", ["email_template_edi_pricelist"], )
27.611111
497
8,368
py
PYTHON
15.0
# Copyright 2017 Carlos Dauden <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo.exceptions import ValidationError from odoo.tests.common import TransactionCase, tagged @tagged("post_install", "-at_install") class TestProductPricelistDirectPrint(TransactionCase): @classmethod def setUpClass(cls): super(TestProductPricelistDirectPrint, cls).setUpClass() # Set report layout to void to wizard selection layout crashes the test report_layout = cls.env.ref("web.report_layout_standard") main_company = cls.env.ref("base.main_company") main_company.external_report_layout_id = report_layout.view_id.id cls.pricelist = cls.env["product.pricelist"].create( { "name": "Pricelist for test", "item_ids": [ ( 0, 0, { "applied_on": "3_global", "percent_price": 5.00, "compute_price": "percentage", }, ) ], } ) cls.category = cls.env["product.category"].create({"name": "Test category"}) cls.category_child = cls.env["product.category"].create( {"name": "Test category child", "parent_id": cls.category.id} ) cls.product = cls.env["product.product"].create( { "name": "Product for test", "categ_id": cls.category.id, "default_code": "TESTPROD01", } ) cls.partner = cls.env["res.partner"].create( { "name": "Partner for test", "property_product_pricelist": cls.pricelist.id, "email": "[email protected]", } ) cls.wiz_obj = cls.env["product.pricelist.print"] def test_defaults(self): wiz = self.wiz_obj.new() res = wiz.with_context( active_model="product.pricelist", active_id=self.pricelist.id ).default_get([]) self.assertEqual(res["pricelist_id"], self.pricelist.id) res = wiz.with_context( active_model="product.pricelist.item", active_ids=self.pricelist.item_ids.ids, ).default_get([]) self.assertEqual(res["pricelist_id"], self.pricelist.id) res = wiz.with_context( active_model="res.partner", active_id=self.partner.id, active_ids=[self.partner.id], ).default_get([]) self.assertEqual( res["pricelist_id"], self.partner.property_product_pricelist.id ) res = wiz.with_context( active_model="product.template", active_ids=self.product.product_tmpl_id.ids ).default_get([]) self.assertEqual( res["product_tmpl_ids"][0][2], self.product.product_tmpl_id.ids ) res = wiz.with_context( active_model="product.product", active_ids=self.product.ids ).default_get([]) self.assertEqual(res["product_ids"][0][2], self.product.ids) self.assertTrue(res["show_variants"]) with self.assertRaises(ValidationError): wiz.print_report() wiz.show_sale_price = True res = wiz.print_report() self.assertIn("report_name", res) def test_action_pricelist_send_multiple_partner(self): partner_2 = self.env["res.partner"].create( { "name": "Partner for test 2", "property_product_pricelist": self.pricelist.id, "email": "[email protected]", } ) wiz = self.wiz_obj.with_context( active_model="res.partner", active_ids=[self.partner.id, partner_2.id] ).create({}) wiz.action_pricelist_send() def test_last_ordered_products(self): SaleOrder = self.env["sale.order"] product2 = self.env["product.product"].create( { "name": "Product2 for test", "categ_id": self.category.id, "default_code": "TESTPROD02", } ) so = self.env["sale.order"].new( { "partner_id": self.partner.id, "order_line": [ ( 0, 0, { "name": self.product.name, "product_id": self.product.id, "product_uom_qty": 10.0, "product_uom": self.product.uom_id.id, "price_unit": 1000.00, }, ), ( 0, 0, { "name": product2.name, "product_id": product2.id, "product_uom_qty": 10.0, "product_uom": product2.uom_id.id, "price_unit": 300.00, }, ), ], } ) so.onchange_partner_id() sale_order = SaleOrder.create(so._convert_to_write(so._cache)) sale_order.action_confirm() wiz = self.wiz_obj.with_context( active_model="res.partner", active_ids=self.partner.ids ).create({"last_ordered_products": 2}) products = wiz.get_last_ordered_products_to_print() self.assertEqual(len(products), 2) wiz = self.wiz_obj.with_context( active_model="res.partner", active_ids=self.partner.ids ).create({"last_ordered_products": 1}) products = wiz.get_last_ordered_products_to_print() self.assertEqual(len(products), 1) def test_show_only_defined_products(self): self.pricelist.item_ids.write( {"applied_on": "0_product_variant", "product_id": self.product.id} ) wiz = self.wiz_obj.with_context( active_model="product.pricelist", active_id=self.pricelist.id, ).create({}) wiz.show_only_defined_products = True wiz.show_variants = True products = wiz.get_products_to_print() self.assertIn(products, self.pricelist.item_ids.mapped("product_id")) self.pricelist.item_ids.write( {"applied_on": "2_product_category", "categ_id": self.category.id} ) wiz.show_only_defined_products = True wiz.show_variants = True products = wiz.get_products_to_print() self.assertIn(self.product, products) def test_parent_categories(self): product_category_child = self.env["product.template"].create( { "name": "Product for test 2", "categ_id": self.category_child.id, "default_code": "TESTPROD02", } ) self.pricelist.item_ids.write( {"applied_on": "2_product_category", "categ_id": self.category_child.id} ) wiz = self.wiz_obj.with_context( active_model="product.pricelist", active_id=self.pricelist.id, ).create({}) wiz.max_categ_level = 1 groups = wiz.get_groups_to_print() product_ids = False for group in groups: if group["group_name"] == "Test category": product_ids = group["products"] self.assertTrue(product_ids) self.assertIn(product_category_child.id, product_ids.ids) def test_reports(self): wiz = self.wiz_obj.with_context( active_model="product.pricelist", active_id=self.pricelist.id, ).create({}) # Print PDF report_name = "product_pricelist_direct_print.action_report_product_pricelist" report_pdf = self.env.ref(report_name)._render(wiz.ids) self.assertGreaterEqual(len(report_pdf[0]), 1) # Export XLSX report_name = "product_pricelist_direct_print.product_pricelist_xlsx" report_xlsx = self.env.ref(report_name)._render(wiz.ids) self.assertGreaterEqual(len(report_xlsx[0]), 1) self.assertEqual(report_xlsx[1], "xlsx")
38.92093
8,368
5,783
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, fields, models class ProductPricelistXlsx(models.AbstractModel): _name = "report.product_pricelist_direct_print.product_pricelist_xlsx" _inherit = "report.report_xlsx.abstract" _description = "Abstract model to export as xlsx the product pricelist" def _get_lang(self, user_id, lang_code=False): if not lang_code: lang_code = self.env["res.users"].browse(user_id).lang return self.env["res.lang"]._lang_get(lang_code) def _create_product_pricelist_sheet(self, workbook, book, pricelist): title_format = workbook.add_format( {"bold": 1, "border": 1, "align": "left", "valign": "vjustify"} ) header_format = workbook.add_format( { "bold": 1, "border": 1, "align": "center", "valign": "vjustify", "fg_color": "#F2F2F2", } ) lang = self._get_lang(book.create_uid.id, lang_code=book.lang) date_format = lang.date_format.replace("%d", "dd") date_format = date_format.replace("%m", "mm") date_format = date_format.replace("%Y", "YYYY") date_format = date_format.replace("/", "-") date_format = workbook.add_format({"num_format": date_format}) sheet = workbook.add_worksheet(_("PRODUCTS")) sheet.set_column("A:A", 45) sheet.set_column("B:H", 15) # Title construction sheet.write("A1", _("Price List Name:"), title_format) if not book.hide_pricelist_name: sheet.write("A2", pricelist.name) else: sheet.write("A2", _("Special Pricelist")) sheet.write("B1", _("Currency:"), title_format) sheet.write("B2", pricelist.currency_id.name) sheet.write("D1", _("Date:"), title_format) if book.date: sheet.write("D2", book.date, date_format) else: sheet.write("D2", book.create_date, date_format) # Header construction if book.partner_id: sheet.write(4, 0, book.partner_id.name, header_format) elif book.partner_ids: sheet.write(4, 0, book.partner_ids[0].name, header_format) next_col = 0 sheet.write(5, next_col, _("Description"), header_format) next_col = self._add_extra_header(sheet, book, next_col, header_format) if book.show_internal_category: next_col += 1 sheet.write(5, next_col, _("Internal Category"), header_format) if book.show_standard_price: next_col += 1 sheet.write(5, next_col, _("Cost Price"), header_format) if book.show_sale_price: next_col += 1 sheet.write(5, next_col, _("Sale Price"), header_format) next_col += 1 sheet.write(5, next_col, _("List Price"), header_format) return sheet def _add_extra_header(self, sheet, book, next_col, header_format): return next_col def _fill_data(self, workbook, sheet, book, pricelist): bold_format = workbook.add_format({"bold": 1}) decimal_format = workbook.add_format({"num_format": "0.00"}) decimal_bold_format = workbook.add_format({"num_format": "0.00", "bold": 1}) row = 6 # We should avoid sending a date as a False object as it will crash if a # submethod tries to make comparisons with other date. print_date = book.date or fields.Date.today() formats = { "bold_format": bold_format, "decimal_format": decimal_format, "decimal_bold_format": decimal_bold_format, } for group in book.get_groups_to_print(): if book.breakage_per_category: sheet.write(row, 0, group["group_name"], bold_format) row += 1 for product in group["products"]: next_col = 0 sheet.write(row, next_col, product.display_name) next_col = self._add_extra_info( sheet, book, product, row, next_col, **formats ) if book.show_internal_category: next_col += 1 sheet.write(row, next_col, product.categ_id.display_name) if book.show_standard_price: next_col += 1 sheet.write(row, next_col, product.standard_price, decimal_format) if book.show_sale_price: next_col += 1 sheet.write(row, next_col, product.list_price, decimal_format) next_col += 1 sheet.write( row, next_col, product.with_context(pricelist=pricelist.id, date=print_date).price, decimal_bold_format, ) row += 1 if book.summary: sheet.write(row, 0, _("Summary:"), bold_format) sheet.write(row + 1, 0, book.summary) return sheet def _add_extra_info(self, sheet, book, product, row, next_col, **kw): return next_col def generate_xlsx_report(self, workbook, data, objects): book = objects[0].with_context( lang=objects[0].lang or self.env["res.users"].browse(objects[0].create_uid.id).lang ) self = self.with_context( lang=book.lang or self.env["res.users"].browse(book.create_uid.id).lang ) pricelist = book.get_pricelist_to_print() sheet = self._create_product_pricelist_sheet(workbook, book, pricelist) sheet = self._fill_data(workbook, sheet, book, pricelist)
43.481203
5,783
13,961
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Carlos Dauden # Copyright 2018 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from collections import defaultdict from odoo import _, api, fields, models from odoo.exceptions import ValidationError from odoo.osv import expression @api.model def _lang_get(self): return self.env["res.lang"].get_installed() class ProductPricelistPrint(models.TransientModel): _name = "product.pricelist.print" _description = "Product Pricelist Print" context_active_model = fields.Char( store=False, compute="_compute_context_active_model" ) pricelist_id = fields.Many2one(comodel_name="product.pricelist", string="Pricelist") partner_id = fields.Many2one(comodel_name="res.partner", string="Customer") partner_ids = fields.Many2many(comodel_name="res.partner", string="Customers") categ_ids = fields.Many2many(comodel_name="product.category", string="Categories") show_only_defined_products = fields.Boolean( string="Show the products defined on pricelist", help="Check this field to print only the products defined in the pricelist. " "The entries in the list referring to all products will not be displayed.", ) show_variants = fields.Boolean() product_tmpl_ids = fields.Many2many( comodel_name="product.template", string="Product Templates", help="Keep empty for all products", ) product_ids = fields.Many2many( comodel_name="product.product", string="Products", help="Keep empty for all products", ) show_standard_price = fields.Boolean(string="Show Cost Price") show_sale_price = fields.Boolean() hide_pricelist_name = fields.Boolean() order_field = fields.Selection( [("name", "Name"), ("default_code", "Internal Reference")], string="Order" ) partner_count = fields.Integer(compute="_compute_partner_count") date = fields.Date() last_ordered_products = fields.Integer( help="If you enter an X number here, then, for each selected customer," " the last X ordered products will be obtained for the report." ) summary = fields.Text() max_categ_level = fields.Integer( string="Max category level", help="If this field is not 0, products are grouped at max level " "of category tree.", ) # Excel export options breakage_per_category = fields.Boolean(default=True) show_internal_category = fields.Boolean(string="Show internal categories") lang = fields.Selection( _lang_get, string="Language", default=lambda self: self.env.user.lang ) @api.depends("partner_ids") def _compute_partner_count(self): for record in self: self.partner_count = len(record.partner_ids) @api.onchange("partner_ids") def _onchange_partner_ids(self): if not self.partner_count: self.last_ordered_products = False @api.model def default_get(self, fields): res = super().default_get(fields) if self.env.context.get("active_model") == "product.template": res["product_tmpl_ids"] = [(6, 0, self.env.context.get("active_ids", []))] elif self.env.context.get("active_model") == "product.product": res["show_variants"] = True res["product_ids"] = [(6, 0, self.env.context.get("active_ids", []))] elif self.env.context.get("active_model") == "product.pricelist": res["pricelist_id"] = self.env.context.get("active_id", False) elif self.env.context.get("active_model") == "res.partner": active_ids = self.env.context.get("active_ids", []) res["partner_ids"] = [(6, 0, active_ids)] if len(active_ids) == 1: partner = self.env["res.partner"].browse(active_ids[0]) res["pricelist_id"] = partner.property_product_pricelist.id elif self.env.context.get("active_model") == "product.pricelist.item": active_ids = self.env.context.get("active_ids", []) items = self.env["product.pricelist.item"].browse(active_ids) # Set pricelist if all the items belong to the same one if len(items.mapped("pricelist_id")) == 1: res["pricelist_id"] = items[0].pricelist_id.id product_items = items.filtered( lambda x: x.applied_on == "0_product_variant" ) template_items = items.filtered(lambda x: x.applied_on == "1_product") category_items = items.filtered( lambda x: x.applied_on == "2_product_category" ) # Convert all pricelist items to their affected variants if product_items: res["show_variants"] = True product_ids = product_items.mapped("product_id") product_ids |= template_items.mapped( "product_tmpl_id.product_variant_ids" ) product_ids |= product_ids.search( [ ("sale_ok", "=", True), ("categ_id", "in", category_items.mapped("categ_id").ids), ] ) res["product_ids"] = [(6, 0, product_ids.ids)] # Convert all pricelist items to their affected templates if template_items and not product_items: product_tmpl_ids = template_items.mapped("product_tmpl_id") product_tmpl_ids |= product_tmpl_ids.search( [ ("sale_ok", "=", True), ("categ_id", "in", category_items.mapped("categ_id").ids), ] ) res["product_tmpl_ids"] = [(6, 0, product_tmpl_ids.ids)] # Only category items, we just set the categories if category_items and not product_items and not template_items: res["categ_ids"] = [(6, 0, category_items.mapped("categ_id").ids)] return res def print_report(self): if not ( self.pricelist_id or self.partner_count or self.show_standard_price or self.show_sale_price ): raise ValidationError( _( "You must set price list or any customer " "or any show price option." ) ) return self.env.ref( "product_pricelist_direct_print." "action_report_product_pricelist" ).report_action(self) def action_pricelist_send(self): self.ensure_one() if self.partner_count > 1: self.send_batch() return if self.partner_count == 1: partner = self.partner_ids[0] self.write( { "partner_id": partner.id, "pricelist_id": partner.property_product_pricelist.id, } ) return self.message_composer_action() def message_composer_action(self): self.ensure_one() template_id = self.env.ref( "product_pricelist_direct_print.email_template_edi_pricelist" ).id compose_form_id = self.env.ref("mail.email_compose_message_wizard_form").id ctx = { "default_composition_mode": "comment", "default_res_id": self.id, "default_model": "product.pricelist.print", "default_use_template": bool(template_id), "default_template_id": template_id, } return { "type": "ir.actions.act_window", "view_mode": "form", "res_model": "mail.compose.message", "view_id": compose_form_id, "target": "new", "context": ctx, } def send_batch(self): self.ensure_one() for partner in self.partner_ids.filtered(lambda x: not x.parent_id): self.write( { "partner_id": partner.id, "pricelist_id": partner.property_product_pricelist.id, } ) self.force_pricelist_send() def force_pricelist_send(self): template_id = self.env.ref( "product_pricelist_direct_print.email_template_edi_pricelist" ).id composer = ( self.env["mail.compose.message"] .with_context( default_composition_mode="mass_mail", default_notify=True, default_res_id=self.id, default_model="product.pricelist.print", default_template_id=template_id, active_ids=self.ids, ) .create({}) ) values = composer._onchange_template_id( template_id, "mass_mail", "product.pricelist.print", self.id )["value"] composer.write(values) composer.action_send_mail() @api.model def _get_sale_order_domain(self, partner): return [ ("state", "not in", ["draft", "sent", "cancel"]), ("partner_id", "child_of", partner.id), ] def get_last_ordered_products_to_print(self): self.ensure_one() partner = self.partner_id if not partner and self.partner_count == 1: partner = self.partner_ids[0] orders = self.env["sale.order"].search( self._get_sale_order_domain(partner), order="date_order desc" ) orders = orders.sorted(key=lambda r: r.date_order, reverse=True) products = orders.mapped("order_line").mapped("product_id") return products[: self.last_ordered_products] def get_pricelist_to_print(self): self.ensure_one() pricelist = self.pricelist_id if not pricelist and self.partner_count == 1: pricelist = self.partner_ids[0].property_product_pricelist return pricelist def _compute_context_active_model(self): self.context_active_model = self.env.context.get("active_model") def get_products_domain(self): domain = [("sale_ok", "=", True)] if self.show_only_defined_products: aux_domain = [] items_dic = {"categ_ids": [], "product_ids": [], "variant_ids": []} for item in self.pricelist_id.item_ids: if item.applied_on == "0_product_variant": items_dic["variant_ids"].append(item.product_id.id) if item.applied_on == "1_product": items_dic["product_ids"].append(item.product_tmpl_id.id) if item.applied_on == "2_product_category" and item.categ_id.parent_id: items_dic["categ_ids"].append(item.categ_id.id) if items_dic["categ_ids"]: aux_domain = expression.OR( [aux_domain, [("categ_id", "in", items_dic["categ_ids"])]] ) if items_dic["product_ids"]: if self.show_variants: aux_domain = expression.OR( [ aux_domain, [("product_tmpl_id", "in", items_dic["product_ids"])], ] ) else: aux_domain = expression.OR( [aux_domain, [("id", "in", items_dic["product_ids"])]] ) if items_dic["variant_ids"]: if self.show_variants: aux_domain = expression.OR( [aux_domain, [("id", "in", items_dic["variant_ids"])]] ) else: aux_domain = expression.OR( [ aux_domain, [("product_variant_ids", "in", items_dic["variant_ids"])], ] ) domain = expression.AND([domain, aux_domain]) if self.categ_ids: domain = expression.AND([domain, [("categ_id", "in", self.categ_ids.ids)]]) return domain def get_products_to_print(self): self.ensure_one() if self.last_ordered_products: products = self.get_last_ordered_products_to_print() else: if self.show_variants: products = self.product_ids or self.product_tmpl_ids.mapped( "product_variant_ids" ) else: products = self.product_tmpl_ids if not products: products = products.search(self.get_products_domain()) return products def get_group_key(self, product): max_level = self.max_categ_level or 99 return " / ".join(product.categ_id.complete_name.split(" / ")[:max_level]) def get_sorted_products(self, products): if self.order_field: # Using "or ''" to avoid issues with None type return products.sorted(lambda x: getattr(x, self.order_field) or "") return products def get_groups_to_print(self): self.ensure_one() products = self.get_products_to_print() if not products: return [] group_dict = defaultdict(lambda: products.browse()) for product in products: key = self.get_group_key(product) group_dict[key] |= product group_list = [] for key in sorted(group_dict.keys()): group_list.append( { "group_name": key, "products": self.get_sorted_products(group_dict[key]), } ) return group_list def export_xlsx(self): self.ensure_one() return self.env.ref( "product_pricelist_direct_print.product_pricelist_xlsx" ).report_action(self)
40.233429
13,961
592
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Product ABC Classification", "summary": "Includes ABC classification for inventory management", "version": "15.0.1.0.1", "author": "Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/product-attribute", "category": "Inventory Management", "license": "AGPL-3", "maintainers": ["CarlosRoca13"], "depends": ["product_abc_classification"], "data": ["views/product_views.xml"], "installable": True, }
39.466667
592
3,901
py
PYTHON
15.0
# Copyright 2021 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from freezegun import freeze_time from odoo.tests import Form, common @freeze_time("2021-04-01 00:00:00") class TestSaleProductClassificationCase(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.partner = cls.env["res.partner"].create({"name": "Mr. Odoo"}) cls.profile = cls.env["abc.classification.profile"].create( { "name": "Test Profile", "classification_type": "fixed", "data_source": "sale_report", "value_criteria": "sold_delivered_value", } ) cls.a = cls.env["abc.classification.profile.level"].create( {"profile_id": cls.profile.id, "fixed": 10000} ) cls.b = cls.env["abc.classification.profile.level"].create( {"profile_id": cls.profile.id, "fixed": 5000} ) cls.c = cls.env["abc.classification.profile.level"].create( {"profile_id": cls.profile.id, "fixed": 2500} ) cls.d = cls.env["abc.classification.profile.level"].create( {"profile_id": cls.profile.id, "fixed": 0} ) # Quickly generate 5 products with a different price each cls.products = cls.env["product.product"].create( [ { "name": "Test product {}".format(i + 1), "type": "service", "list_price": i + 1, } for i in range(5) ] ) (cls.prod_1, cls.prod_2, cls.prod_3, cls.prod_4, cls.prod_5) = cls.products cls.products.write( { "create_date": "2021-03-01", "abc_classification_profile_id": cls.profile.id, } ) # Let's prepare some sales for them. This will be the final calendar: # +-------------+-------+------+------+------+------+ # | date | p1 | p2 | p3 | p4 | p5 | # +-------------+-------+------+------+------+------+ # | 2021-01-01 | 1000 | 2000 | | | 5000 | # | 2021-02-01 | 1000 | | 3000 | 4000 | | # | 2021-03-01 | 1000 | | | 4000 | | # | 2021-04-01 | 1000 | | 3000 | | | # | TOTALS: | 4000 | 2000 | 6000 | 8000 | 5000 | # +-------------+-------+------+------+------+------+ cls.sales_calendar = { "2021-01-01": cls.prod_1 | cls.prod_2 | cls.prod_5, "2021-02-01": cls.prod_1 | cls.prod_3 | cls.prod_4, "2021-03-01": cls.prod_1 | cls.prod_4, "2021-04-01": cls.prod_1 | cls.prod_3, } for date, products in cls.sales_calendar.items(): cls._create_sale(date, cls.partner, products) @classmethod def _create_sale(cls, date, partner, products, qty=1000): """Simple sale creation""" sale_form = Form(cls.env["sale.order"]) sale_form.partner_id = partner for product in products: with sale_form.order_line.new() as line_form: line_form.product_id = product line_form.product_uom_qty = qty line_form.qty_delivered = qty sale_order = sale_form.save() sale_order.action_done() # Force the date so to reproduce the calendar sale_order.date_order = date return sale_order def _test_product_classification(self, classifications): """Helper to assert classifications in batch. It's expected to come as dict of key product record and value string classification""" for product, classification in classifications.items(): self.assertEqual(product.abc_classification_level_id, classification)
42.402174
3,901
3,051
py
PYTHON
15.0
# Copyright 2021 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from freezegun import freeze_time from .test_sale_product_classification_common import TestSaleProductClassificationCase @freeze_time("2021-04-01 00:00:00") class TestSaleProductClassification(TestSaleProductClassificationCase): @classmethod def setUpClass(cls): super().setUpClass() def test_sale_order_classification(self): """Generate classifications for diferent period slices""" # This is the table of expected classifications according to the # generated sales depending on the evaluated period: # +------------+------+---+------+---+------+---+------+---+------+---+ # | From date | p1 | C | p2 | C | p3 | C | p4 | c | p5 | C | # +------------+------+---+------+---+------+---+------+---+------+---+ # | 2021-01-01 | 4000 | C | 2000 | D | 6000 | B | 8000 | B | 5000 | B | # | 2021-02-01 | 3000 | C | 0 | D | 6000 | B | 8000 | B | 0 | D | # | 2021-03-01 | 2000 | D | 0 | D | 3000 | C | 4000 | C | 0 | D | # | 2021-04-01 | 1000 | D | 0 | D | 3000 | C | 4000 | C | 0 | D | # +------------+------+---+------+---+------+---+------+---+------+---+ cron_classify = self.env[ "abc.classification.profile" ]._compute_abc_classification # We forced the products create date to 2021-03-01, so they won't be # evaluated by the cron if set the days to ignore to 365 self.profile.days_to_ignore = 365 cron_classify() self.assertFalse(any(self.products.mapped("abc_classification_level_id"))) # Let's reset and now evaluate the a year from now to get all the sales # which is the default for sale_classification_days_to_evaluate self.profile.days_to_ignore = 0 cron_classify() product_classification = { self.prod_1: self.c, self.prod_2: self.d, self.prod_3: self.b, self.prod_4: self.b, self.prod_5: self.b, } self._test_product_classification(product_classification) # 70 from now to get sales from february self.profile.past_period = 70 cron_classify() product_classification.update({self.prod_5: self.d}) self._test_product_classification(product_classification) # 40 from now to get sales from march self.profile.past_period = 40 cron_classify() product_classification.update( {self.prod_1: self.d, self.prod_4: self.c, self.prod_3: self.c} ) self._test_product_classification(product_classification) # Product 1 gets an A! order = self._create_sale("2021-04-01", self.partner, self.prod_1, 20000) order.flush() # make sure data are dumped to DB cron_classify() product_classification.update({self.prod_1: self.a}) self._test_product_classification(product_classification)
47.671875
3,051
1,688
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models class ProductTemplate(models.Model): _inherit = "product.template" seasonality_classification = fields.Selection( selection=[ ("very high", "Very high"), ("high", "High"), ("medium", "Medium"), ("low", "Low"), ], compute="_compute_seasonality_classification", inverse="_inverse_seasonality_classification", search="_search_seasonality_classification", readonly=False, ) @api.depends( "product_variant_ids", "product_variant_ids.seasonality_classification" ) def _compute_seasonality_classification(self): unique_variants = self.filtered( lambda template: len(template.product_variant_ids) == 1 ) for template in unique_variants: template.seasonality_classification = ( template.product_variant_ids.seasonality_classification ) for template in self - unique_variants: template.seasonality_classification = False def _inverse_seasonality_classification(self): if len(self.product_variant_ids) == 1: self.product_variant_ids.seasonality_classification = ( self.seasonality_classification ) def _search_seasonality_classification(self, operator, value): products = self.env["product.product"].search( [("seasonality_classification", operator, value)], limit=None ) return [("id", "in", products.mapped("product_tmpl_id").ids)]
36.695652
1,688
641
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class ProductProduct(models.Model): _inherit = "product.product" seasonality_classification = fields.Selection( selection=[ ("very high", "Very high"), ("high", "High"), ("medium", "Medium"), ("low", "Low"), ], string="Seasonility", help="Whether this product is selled during very short periods of time " "or steadily across the whole year", default="low", company_dependent=True, )
30.52381
641