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
778
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Purchase Order Secondary Unit", "summary": "Purchase product in a secondary unit", "version": "15.0.1.1.0", "development_status": "Beta", "category": "Purchase", "website": "https://github.com/OCA/purchase-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "auto_install": True, "depends": ["purchase", "product_secondary_unit"], "data": [ "views/product_views.xml", "views/purchase_order_views.xml", "reports/purchase_order_templates.xml", "reports/purchase_quotation_templates.xml", ], }
35.363636
778
3,380
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields from odoo.tests.common import Form, TransactionCase, tagged @tagged("-at_install", "post_install") class TestPurchaseOrderSecondaryUnit(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() # Active multiple units of measure security group for user cls.env.user.groups_id = [(4, cls.env.ref("uom.group_uom").id)] cls.product_uom_kg = cls.env.ref("uom.product_uom_kgm") cls.product_uom_gram = cls.env.ref("uom.product_uom_gram") cls.product_uom_unit = cls.env.ref("uom.product_uom_unit") # Create a product product_form = Form(cls.env["product.product"]) product_form.name = "Test" product_form.uom_id = cls.product_uom_kg product_form.uom_po_id = cls.product_uom_kg cls.product = product_form.save() # Set a secondary unit on the template of the previously created product with Form(cls.product.product_tmpl_id) as template_form: with template_form.secondary_uom_ids.new() as secondary_uom_form: secondary_uom_form.name = "unit-700" secondary_uom_form.uom_id = cls.product_uom_unit secondary_uom_form.factor = 0.7 cls.secondary_unit = cls.product.product_tmpl_id.secondary_uom_ids cls.product.purchase_secondary_uom_id = cls.secondary_unit.id cls.partner = cls.env["res.partner"].create({"name": "test - partner"}) cls.purchase_order_obj = cls.env["purchase.order"] po_val = { "partner_id": cls.partner.id, "company_id": cls.env.company.id, "order_line": [ ( 0, 0, { "name": cls.product.name, "product_id": cls.product.id, "product_qty": 1, "product_uom": cls.product.uom_id.id, "price_unit": 1000.00, "date_planned": fields.Datetime.now(), }, ) ], } po = cls.purchase_order_obj.new(po_val) po.onchange_partner_id() cls.order = cls.purchase_order_obj.create(po._convert_to_write(po._cache)) def test_purchase_order_01(self): purchase_order = Form(self.order) with purchase_order.order_line.edit(0) as line: # Test _compute product_qty line.secondary_uom_id = self.secondary_unit line.secondary_uom_qty = 10.0 self.assertEqual(line.product_qty, 7.0) # Test onchange product uom line.secondary_uom_qty = 3500.0 line.product_uom = self.product_uom_gram self.assertEqual(line.secondary_uom_qty, 3.5) def test_purchase_order_02(self): purchase_order = Form(self.order) with purchase_order.order_line.new() as line_new: # Test default purchase order line secondary uom line_new.product_id = self.product self.assertEqual(line_new.secondary_uom_id, self.secondary_unit) self.assertEqual(line_new.secondary_uom_qty, 1.0) self.assertAlmostEqual(line_new.product_qty, 0.7, places=2)
45.675676
3,380
1,665
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models class PurchaseOrderLine(models.Model): _inherit = ["purchase.order.line", "product.secondary.unit.mixin"] _name = "purchase.order.line" _secondary_unit_fields = { "qty_field": "product_qty", "uom_field": "product_uom", } product_qty = fields.Float( store=True, readonly=False, compute="_compute_product_qty", copy=True ) @api.depends("secondary_uom_qty", "secondary_uom_id") def _compute_product_qty(self): if hasattr(super(), "_compute_product_qty"): return super()._compute_product_qty() return self._compute_helper_target_field_qty() @api.onchange("product_uom") def onchange_product_uom_for_secondary(self): self._onchange_helper_product_uom_for_secondary() @api.onchange("product_id") def onchange_product_id(self): """If default purchases secondary unit set on product, put on secondary quantity 1 for being the default quantity. We override this method, that is the one that sets by default 1 on the other quantity with that purpose. """ res = super().onchange_product_id() # Check to avoid executing onchange unnecessarily, # which can sometimes cause tests of other modules to fail if self.secondary_uom_id != self.product_id.purchase_secondary_uom_id: self.secondary_uom_id = self.product_id.purchase_secondary_uom_id if self.secondary_uom_id: self.secondary_uom_qty = 1.0 return res
39.642857
1,665
448
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class ProductTemplate(models.Model): _inherit = "product.template" purchase_secondary_uom_id = fields.Many2one( comodel_name="product.secondary.unit", string="Default secondary unit for purchases", domain="[('product_tmpl_id', '=', id), ('product_id', '=', False)]", )
34.461538
448
640
py
PYTHON
15.0
# Copyright 2023 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class ProductProduct(models.Model): _inherit = "product.product" purchase_secondary_uom_id = fields.Many2one( comodel_name="product.secondary.unit", string="Default secondary unit for purchases", help="In order to set a value, please first add at least one record" " in 'Secondary Unit of Measure'", domain="['|', ('product_id', '=', id)," "'&', ('product_tmpl_id', '=', product_tmpl_id)," " ('product_id', '=', False)]", )
37.647059
640
706
py
PYTHON
15.0
# Copyright 2019-2020 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Purchase Request Tier Validation", "summary": "Extends the functionality of Purchase Requests to " "support a tier validation process.", "version": "15.0.1.0.0", "category": "Purchase Management", "website": "https://github.com/OCA/purchase-workflow", "author": "ForgeFlow, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["purchase_request", "base_tier_validation"], "data": [ "data/purchase_request_tier_definition.xml", "views/purchase_request_view.xml", ], }
37.157895
706
745
py
PYTHON
15.0
# Copyright 2017-2020 ForgeFlow S.L. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl-3.0). from odoo.tests import common class TestPurchaseRequest(common.TransactionCase): def setUp(self): super(TestPurchaseRequest, self).setUp() # common models self.purchase_request = self.env["purchase.request"] self.tier_definition = self.env["tier.definition"] def test_get_under_validation_exceptions(self): self.assertIn( "route_id", self.purchase_request._get_under_validation_exceptions() ) def test_get_tier_validation_model_names(self): self.assertIn( "purchase.request", self.tier_definition._get_tier_validation_model_names() )
32.391304
745
549
py
PYTHON
15.0
# Copyright 2019-2020 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class PurchaseRequest(models.Model): _name = "purchase.request" _inherit = ["purchase.request", "tier.validation"] _state_from = ["draft"] _state_to = ["approved"] _tier_validation_manual_config = False @api.model def _get_under_validation_exceptions(self): res = super(PurchaseRequest, self)._get_under_validation_exceptions() res.append("route_id") return res
30.5
549
401
py
PYTHON
15.0
# Copyright 2019-2020 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class TierDefinition(models.Model): _inherit = "tier.definition" @api.model def _get_tier_validation_model_names(self): res = super(TierDefinition, self)._get_tier_validation_model_names() res.append("purchase.request") return res
30.846154
401
596
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Sale Purchase Force Vendor", "version": "15.0.1.0.1", "category": "Purchase Management", "website": "https://github.com/OCA/purchase-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "depends": ["sale_purchase_stock", "web_domain_field"], "installable": True, "data": [ "views/res_config_settings_view.xml", "views/sale_order_view.xml", ], "maintainers": ["victoralmau"], }
34.941176
594
1,426
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import json from .common import TestSalePurchaseForceVendorBase class TestSalePurchaseForceVendor(TestSalePurchaseForceVendorBase): def test_misc(self): self.sale_order.action_confirm() purchase_orders = self.sale_order._get_purchase_orders() self.assertEqual(len(purchase_orders), 1) self.assertEqual(purchase_orders.partner_id, self.vendor_b) self.assertEqual(len(self.product_a.seller_ids), 2) self.assertNotIn(self.vendor_a, self.product_b.seller_ids.mapped("name")) self.assertIn(self.vendor_b, self.product_b.seller_ids.mapped("name")) def test_misc_force_vendor_restrict(self): self.env.company.sale_purchase_force_vendor_restrict = True self.sale_order.action_confirm() line_0 = self.sale_order.order_line[0] partners = self.env["res.partner"].search(json.loads(line_0.vendor_id_domain)) self.assertNotIn(self.partner, partners) self.assertIn(self.vendor_a, partners) self.assertIn(self.vendor_b, partners) def test_misc_not_force_vendor_restrict(self): self.env.company.sale_purchase_force_vendor_restrict = False self.sale_order.action_confirm() line_0 = self.sale_order.order_line[0] self.assertEqual(json.loads(line_0.vendor_id_domain), [])
44.5
1,424
1,820
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import Form, common class TestSalePurchaseForceVendorBase(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.partner = cls.env["res.partner"].create({"name": "Test partner"}) cls.vendor_a = cls.env["res.partner"].create({"name": "Test vendor A"}) cls.vendor_b = cls.env["res.partner"].create({"name": "Test vendor B"}) cls.mto = cls.env.ref("stock.route_warehouse0_mto") cls.mto.active = True cls.buy = cls.env.ref("purchase_stock.route_warehouse0_buy") cls.buy.sale_selectable = True cls.product_a = cls.env["product.product"].create( { "name": "Test product A", "seller_ids": [ (0, 0, {"name": cls.vendor_a.id, "min_qty": 1, "price": 10}), (0, 0, {"name": cls.vendor_b.id, "min_qty": 1, "price": 20}), ], "route_ids": [(6, 0, [cls.mto.id, cls.buy.id])], } ) cls.product_b = cls.env["product.product"].create( { "name": "Test product B", "route_ids": [(6, 0, [cls.mto.id, cls.buy.id])], } ) cls.sale_order = cls._create_sale_order(cls) def _create_sale_order(self): order_form = Form(self.env["sale.order"]) order_form.partner_id = self.partner for product in [self.product_a, self.product_b]: with order_form.order_line.new() as line_form: line_form.product_id = product line_form.route_id = self.buy line_form.vendor_id = self.vendor_b return order_form.save()
41.318182
1,818
2,032
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import json from odoo import api, fields, models class SaleOrder(models.Model): _inherit = "sale.order" sale_purchase_force_vendor_restrict = fields.Boolean( related="company_id.sale_purchase_force_vendor_restrict" ) class SaleOrderLine(models.Model): _inherit = "sale.order.line" vendor_id = fields.Many2one( comodel_name="res.partner", string="Vendor", ) vendor_id_domain = fields.Char( compute="_compute_vendor_id_domain", readonly=True, store=False, ) @api.depends("product_id") def _compute_vendor_id_domain(self): for item in self: domain = ( [("id", "in", item.product_id.variant_seller_ids.name.ids)] if item.order_id.sale_purchase_force_vendor_restrict else [] ) item.vendor_id_domain = json.dumps(domain) def _prepare_procurement_values(self, group_id=False): """Inject in the procurement values the preferred vendor if any, and create supplierinfo record for it if it doesn't exist. """ res = super()._prepare_procurement_values(group_id=group_id) if self.vendor_id: product = self.product_id suppinfo = product.with_company(self.company_id.id)._select_seller( partner_id=self.vendor_id, quantity=self.product_uom_qty, uom_id=self.product_uom, ) if not suppinfo: suppinfo = self.env["product.supplierinfo"].create( { "product_tmpl_id": product.product_tmpl_id.id, "name": self.vendor_id.id, "min_qty": 0, "company_id": self.company_id.id, } ) res["supplierinfo_id"] = suppinfo return res
33.278689
2,030
862
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import models class StockMove(models.Model): _inherit = "stock.move" def _prepare_procurement_values(self): """Inject the preferred vendor in case of a MTO that first creates the OUT move. """ res = super()._prepare_procurement_values() # Get all chained moves to get sale line moves = self.browse(list(self._rollup_move_dests({self.id}))) move_sale = moves.filtered("sale_line_id")[:1] if move_sale.sale_line_id.vendor_id: res_order_line = move_sale.sale_line_id._prepare_procurement_values( group_id=move_sale.group_id ) res.update({"supplierinfo_id": res_order_line["supplierinfo_id"]}) return res
39.090909
860
356
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ResCompany(models.Model): _inherit = "res.company" sale_purchase_force_vendor_restrict = fields.Boolean( string="Restrict allowed vendors in sale orders", default=True, )
29.5
354
448
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Víctor Martínez # 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" sale_purchase_force_vendor_restrict = fields.Boolean( string="Restrict allowed vendors in sale orders", related="company_id.sale_purchase_force_vendor_restrict", readonly=False, )
34.307692
446
838
py
PYTHON
15.0
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) { "name": "Purchase Invoice Plan", "summary": "Add to purchases order, ability to manage future invoice plan", "version": "15.0.1.0.2", "author": "Ecosoft,Odoo Community Association (OCA)", "license": "AGPL-3", "website": "https://github.com/OCA/purchase-workflow", "category": "Purchase", "depends": ["purchase_open_qty", "purchase_stock"], "data": [ "security/ir.model.access.csv", "data/purchase_data.xml", "wizard/purchase_create_invoice_plan_view.xml", "wizard/purchase_make_planned_invoice_view.xml", "views/purchase_view.xml", ], "installable": True, "maintainers": ["kittiu"], "development_status": "Alpha", }
36.434783
838
9,857
py
PYTHON
15.0
# Copyright 2019 Ecosoft (http://ecosoft.co.th) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) from freezegun import freeze_time from odoo import fields from odoo.exceptions import UserError, ValidationError from odoo.tests.common import Form, TransactionCase class TestPurchaseInvoicePlan(TransactionCase): def setUp(self): super(TestPurchaseInvoicePlan, self).setUp() # Create a PO self.PurchaseOrder = self.env["purchase.order"] self.PurchaseInvoicePlan = self.env["purchase.create.invoice.plan"] self.StockBackorderConfirm = self.env["stock.backorder.confirmation"] self.StockPicking = self.env["stock.picking"] self.test_partner = self.env.ref("base.res_partner_12") self.test_service = self.env.ref("product.product_product_2") self.test_product = self.env.ref("product.product_product_7") self.test_po_service = self.env["purchase.order"].create( { "partner_id": self.test_partner.id, "use_invoice_plan": True, "order_line": [ ( 0, 0, { "name": "PO-Service", "product_id": self.test_service.id, "date_planned": fields.Datetime.now(), "product_qty": 1, "product_uom": self.test_service.uom_id.id, "price_unit": 500, }, ) ], } ) self.test_po_product = self.env["purchase.order"].create( { "partner_id": self.test_partner.id, "use_invoice_plan": True, "order_line": [ ( 0, 0, { "name": "PO-Product", "product_id": self.test_product.id, "date_planned": fields.Datetime.now(), "product_qty": 10, "product_uom": self.test_product.uom_id.id, "price_unit": 1000, }, ) ], } ) def test_invoice_plan(self): ctx = { "active_id": self.test_po_product.id, "active_ids": [self.test_po_product.id], "all_remain_invoices": True, } # Create purchase plan with Form(self.PurchaseInvoicePlan) as p: p.num_installment = 5 purchase_plan = p.save() purchase_plan.with_context(**ctx).purchase_create_invoice_plan() # Change plan, so that the 1st installment is 1000 and 5th is 3000 self.assertEqual(len(self.test_po_product.invoice_plan_ids), 5) self.test_po_product.invoice_plan_ids[0].amount = 1000 self.test_po_product.invoice_plan_ids[4].amount = 3000 self.test_po_product.button_confirm() self.assertEqual(self.test_po_product.state, "purchase") # Receive all products receive = self.test_po_product.picking_ids.filtered(lambda l: l.state != "done") receive.move_ids_without_package.quantity_done = 10.0 receive._action_done() purchase_create = self.env["purchase.make.planned.invoice"].create({}) purchase_create.with_context(**ctx).create_invoices_by_plan() self.assertEqual( self.test_po_product.amount_total, sum(self.test_po_product.invoice_ids.mapped("amount_total")), ) def test_unlink_invoice_plan(self): ctx = { "active_id": self.test_po_product.id, "active_ids": [self.test_po_product.id], } with Form(self.PurchaseInvoicePlan) as p: p.num_installment = 5 plan = p.save() plan.with_context(**ctx).purchase_create_invoice_plan() # Remove it self.test_po_product.remove_invoice_plan() self.assertFalse(self.test_po_product.invoice_plan_ids) def test_error(self): ctx = { "active_id": self.test_po_product.id, "active_ids": [self.test_po_product.id], "all_remain_invoices": True, } # UserError Use Invoice Plan selected, but no plan created with self.assertRaises(UserError): self.test_po_product.button_confirm() # ValidationError Number of Installment <= 1 with self.assertRaises(ValidationError) as e: with Form(self.PurchaseInvoicePlan) as p: p.num_installment = 0 p.save() error_message = "Number Installment must greater than 1" self.assertEqual(e.exception.args[0], error_message) # Create purchase plan with Form(self.PurchaseInvoicePlan) as p: p.num_installment = 5 purchase_plan = p.save() purchase_plan.with_context(**ctx).purchase_create_invoice_plan() # Test exceed percent with self.assertRaises(UserError): self.test_po_product.invoice_plan_ids[0].percent = 99 self.test_po_product._check_ip_total_percent() self.test_po_product.button_confirm() self.assertEqual(self.test_po_product.state, "purchase") # UserError Please fill percentage for all invoice plan lines with self.assertRaises(UserError): for per in self.test_po_product.invoice_plan_ids: per.percent = 0 self.test_po_product._check_invoice_plan() # Receive product 1 unit receive = self.test_po_product.picking_ids.filtered(lambda l: l.state != "done") receive.move_ids_without_package.quantity_done = 1.0 receive._action_done() # ValidationError Create all invoice plan - Receive < Invoice require purchase_create = self.env["purchase.make.planned.invoice"].create({}) with self.assertRaises(ValidationError) as e: purchase_create.with_context(**ctx).create_invoices_by_plan() error_message = ( "Plan quantity: 2.0, exceed invoiceable quantity: 1.0" "\nProduct should be delivered before invoice" ) self.assertEqual(e.exception.args[0], error_message) def test_invoice_plan_po_edit(self): """Case when some installment already invoiced, but then, the PO line added. Test to ensure that the invoiced amount of the done installment is fixed""" ctx = { "active_id": self.test_po_product.id, "active_ids": [self.test_po_product.id], "all_remain_invoices": False, } # Create purchase plan with Form(self.PurchaseInvoicePlan) as p: p.num_installment = 5 purchase_plan = p.save() purchase_plan.with_context(**ctx).purchase_create_invoice_plan() # Change plan, so that the 1st installment is 1000 and 5th is 3000 self.assertEqual(len(self.test_po_product.invoice_plan_ids), 5) first_install = self.test_po_product.invoice_plan_ids[0] first_install.amount = 1000 self.test_po_product.invoice_plan_ids[4].amount = 3000 self.test_po_product.button_confirm() self.assertEqual(self.test_po_product.state, "purchase") # Receive all products receive = self.test_po_product.picking_ids.filtered(lambda l: l.state != "done") receive.move_ids_without_package.quantity_done = 10.0 receive._action_done() purchase_create = self.env["purchase.make.planned.invoice"].create({}) # Create only the 1st invoice, amount should be 1000, and percent is 10 purchase_create.with_context(**ctx).create_invoices_by_plan() self.assertEqual(first_install.amount, 1000) self.assertEqual(first_install.percent, 10) # Add new PO line with amount = 1000, check that only percent is changed self.test_po_product.write( { "order_line": [ ( 0, 0, { "name": "PO-Product-NEW", "product_id": self.test_product.id, "date_planned": fields.Datetime.now(), "product_qty": 1, "product_uom": self.test_product.uom_id.id, "price_unit": 1000, }, ) ], } ) # Overall amount changed to 11000, install amount not changed, only percent changed. self.assertEqual(self.test_po_product.amount_total, 11000) self.test_po_product.invoice_plan_ids._compute_amount() self.assertEqual(first_install.amount, 1000) self.assertEqual(first_install.percent, 9.090909) with self.assertRaises(UserError): self.test_po_product.remove_invoice_plan() @freeze_time("2022-01-01") def test_next_date(self): ctx = { "active_id": self.test_po_product.id, "active_ids": [self.test_po_product.id], "all_remain_invoices": False, } # Create purchase plan for item in ["day", "month", "year"]: with Form(self.PurchaseInvoicePlan) as p: p.num_installment = 5 p.interval = 5 p.interval_type = item purchase_plan = p.save() purchase_plan.with_context(**ctx).purchase_create_invoice_plan() self.assertEqual(len(self.test_po_product.invoice_plan_ids), 5) self.test_po_product.remove_invoice_plan()
43.808889
9,857
1,419
py
PYTHON
15.0
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import _, api, fields, models from odoo.exceptions import ValidationError class PurchaseCreateInvoicePlan(models.TransientModel): _name = "purchase.create.invoice.plan" _description = "Fillig invoice planning criteria" num_installment = fields.Integer( string="Number of Installment", default=0, required=True, ) installment_date = fields.Date( default=fields.Date.context_today, required=True, ) interval = fields.Integer( default=1, required=True, ) interval_type = fields.Selection( [("day", "Day"), ("month", "Month"), ("year", "Year")], default="month", required=True, ) @api.constrains("num_installment") def _check_num_installment(self): if self.num_installment <= 1: raise ValidationError(_("Number Installment must greater than 1")) def purchase_create_invoice_plan(self): purchase = self.env["purchase.order"].browse(self._context.get("active_id")) self.ensure_one() purchase.create_invoice_plan( self.num_installment, self.installment_date, self.interval, self.interval_type, ) return {"type": "ir.actions.act_window_close"}
31.533333
1,419
927
py
PYTHON
15.0
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import models class PurchaseAdvancePaymentInv(models.TransientModel): _name = "purchase.make.planned.invoice" _description = "Wizard when create invoice by plan" def create_invoices_by_plan(self): purchase = self.env["purchase.order"].browse(self._context.get("active_id")) purchase.ensure_one() invoice_plans = ( self._context.get("all_remain_invoices") and purchase.invoice_plan_ids.filtered(lambda l: not l.invoiced) or purchase.invoice_plan_ids.filtered("to_invoice") ) for plan in invoice_plans.sorted("installment"): purchase.sudo().with_context( invoice_plan_id=plan.id ).action_create_invoice() return {"type": "ir.actions.act_window_close"}
40.304348
927
11,831
py
PYTHON
15.0
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from dateutil.relativedelta import relativedelta from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError from odoo.tools.float_utils import float_compare, float_round class PurchaseOrder(models.Model): _inherit = "purchase.order" invoice_plan_ids = fields.One2many( comodel_name="purchase.invoice.plan", inverse_name="purchase_id", string="Invoice Plan", copy=False, ) use_invoice_plan = fields.Boolean( default=False, copy=False, ) ip_invoice_plan = fields.Boolean( string="Invoice Plan In Process", compute="_compute_ip_invoice_plan", help="At least one invoice plan line pending to create invoice", ) ip_total_percent = fields.Float( compute="_compute_ip_total", string="Percent", ) ip_total_amount = fields.Monetary( compute="_compute_ip_total", string="Total Amount", ) @api.depends("invoice_plan_ids") def _compute_ip_total(self): for rec in self: installments = rec.invoice_plan_ids.filtered("installment") rec.ip_total_percent = sum(installments.mapped("percent")) rec.ip_total_amount = sum(installments.mapped("amount")) def _compute_ip_invoice_plan(self): for rec in self: rec.ip_invoice_plan = ( rec.use_invoice_plan and rec.invoice_plan_ids and len(rec.invoice_plan_ids.filtered(lambda l: not l.invoiced)) ) @api.constrains("invoice_plan_ids") def _check_ip_total_percent(self): for rec in self: installments = rec.invoice_plan_ids.filtered("installment") ip_total_percent = sum(installments.mapped("percent")) if float_round(ip_total_percent, 0) > 100: raise UserError(_("Invoice plan total percentage must not exceed 100%")) @api.constrains("state") def _check_invoice_plan(self): for rec in self: if rec.state != "draft": if rec.invoice_plan_ids.filtered(lambda l: not l.percent): raise ValidationError( _("Please fill percentage for all invoice plan lines") ) def button_confirm(self): if self.filtered(lambda r: r.use_invoice_plan and not r.invoice_plan_ids): raise UserError(_("Use Invoice Plan selected, but no plan created")) return super().button_confirm() def create_invoice_plan( self, num_installment, installment_date, interval, interval_type ): self.ensure_one() self.invoice_plan_ids.unlink() invoice_plans = [] Decimal = self.env["decimal.precision"] prec = Decimal.precision_get("Purchase Invoice Plan Percent") percent = float_round(1.0 / num_installment * 100, prec) percent_last = 100 - (percent * (num_installment - 1)) for i in range(num_installment): this_installment = i + 1 if num_installment == this_installment: percent = percent_last vals = { "installment": this_installment, "plan_date": installment_date, "invoice_type": "installment", "percent": percent, } invoice_plans.append((0, 0, vals)) installment_date = self._next_date( installment_date, interval, interval_type ) self.write({"invoice_plan_ids": invoice_plans}) return True def remove_invoice_plan(self): self.ensure_one() self.invoice_plan_ids.unlink() return True @api.model def _next_date(self, installment_date, interval, interval_type): installment_date = fields.Date.from_string(installment_date) if interval_type == "month": next_date = installment_date + relativedelta(months=+interval) elif interval_type == "year": next_date = installment_date + relativedelta(years=+interval) else: next_date = installment_date + relativedelta(days=+interval) next_date = fields.Date.to_string(next_date) return next_date def action_view_invoice(self, invoices=False): invoice_plan_id = self._context.get("invoice_plan_id") if invoice_plan_id and invoices: plan = self.env["purchase.invoice.plan"].browse(invoice_plan_id) for invoice in invoices: plan._compute_new_invoice_quantity(invoice) invoice.write( { "date": plan.plan_date, "invoice_date": plan.plan_date, } ) plan.invoice_ids += invoice return super().action_view_invoice(invoices=invoices) class PurchaseInvoicePlan(models.Model): _name = "purchase.invoice.plan" _description = "Invoice Planning Detail" _order = "installment" purchase_id = fields.Many2one( comodel_name="purchase.order", string="Purchases Order", index=True, readonly=True, ondelete="cascade", ) partner_id = fields.Many2one( comodel_name="res.partner", string="Supplier", related="purchase_id.partner_id", store=True, index=True, ) state = fields.Selection( string="Status", related="purchase_id.state", store=True, index=True, ) installment = fields.Integer() plan_date = fields.Date( required=True, ) invoice_type = fields.Selection( selection=[("installment", "Installment")], string="Type", required=True, default="installment", ) last = fields.Boolean( string="Last Installment", compute="_compute_last", help="Last installment will create invoice use remaining amount", ) percent = fields.Float( digits="Purchase Invoice Plan Percent", help="This percent will be used to calculate new quantity", ) amount = fields.Float( digits="Product Price", compute="_compute_amount", inverse="_inverse_amount", help="This amount will be used to calculate the percent", ) invoice_ids = fields.Many2many( comodel_name="account.move", relation="purchase_invoice_plan_invoice_rel", column1="plan_id", column2="move_id", string="Invoices", readonly=True, ) amount_invoiced = fields.Float( compute="_compute_invoiced", store=True, readonly=False, ) to_invoice = fields.Boolean( string="Next Invoice", compute="_compute_to_invoice", help="If this line is ready to create new invoice", store=True, ) invoiced = fields.Boolean( string="Invoice Created", compute="_compute_invoiced", help="If this line already invoiced", store=True, ) no_edit = fields.Boolean( compute="_compute_no_edit", ) @api.depends("percent") def _compute_amount(self): for rec in self: amount_untaxed = rec.purchase_id._origin.amount_untaxed # With invoice already created, no recompute if rec.invoiced: rec.amount = rec.amount_invoiced rec.percent = rec.amount / amount_untaxed * 100 continue # For last line, amount is the left over if rec.last: installments = rec.purchase_id.invoice_plan_ids.filtered( lambda l: l.invoice_type == "installment" ) prev_amount = sum((installments - rec).mapped("amount")) rec.amount = amount_untaxed - prev_amount continue rec.amount = rec.percent * amount_untaxed / 100 @api.onchange("amount", "percent") def _inverse_amount(self): for rec in self: if rec.purchase_id.amount_untaxed != 0: if rec.last: installments = rec.purchase_id.invoice_plan_ids.filtered( lambda l: l.invoice_type == "installment" ) prev_percent = sum((installments - rec).mapped("percent")) rec.percent = 100 - prev_percent continue rec.percent = rec.amount / rec.purchase_id.amount_untaxed * 100 continue rec.percent = 0 @api.depends("purchase_id.state", "purchase_id.invoice_plan_ids.invoiced") def _compute_to_invoice(self): """If any invoice is in draft/open/paid do not allow to create inv Only if previous to_invoice is False, it is eligible to_invoice """ for rec in self: rec.to_invoice = False for rec in self.sorted("installment"): if rec.purchase_id.state != "purchase": continue if not rec.invoiced: rec.to_invoice = True break def _get_amount_invoice(self, invoices): """Hook function""" return sum(invoices.mapped("amount_untaxed")) @api.depends("invoice_ids.state") def _compute_invoiced(self): for rec in self: invoiced = rec.invoice_ids.filtered( lambda l: l.state in ("draft", "posted") ) rec.invoiced = invoiced and True or False rec.amount_invoiced = rec._get_amount_invoice(invoiced[:1]) def _compute_last(self): for rec in self: last = max(rec.purchase_id.invoice_plan_ids.mapped("installment")) rec.last = rec.installment == last def _no_edit(self): self.ensure_one() return self.invoiced def _compute_no_edit(self): for rec in self: rec.no_edit = rec._no_edit() def _compute_new_invoice_quantity(self, invoice_move): self.ensure_one() if self.last: # For last install, let the system do the calc. return percent = self.percent move = invoice_move.with_context(**{"check_move_validity": False}) for line in move.invoice_line_ids: self._update_new_quantity(line, percent) move.line_ids.filtered("exclude_from_invoice_tab").unlink() move._move_autocomplete_invoice_lines_values() # recompute dr/cr def _update_new_quantity(self, line, percent): """Hook function""" plan_qty = self._get_plan_qty(line.purchase_line_id, percent) prec = line.purchase_line_id.product_uom.rounding if float_compare(abs(plan_qty), abs(line.quantity), prec) == 1: raise ValidationError( _( "Plan quantity: %(plan)s, exceed invoiceable quantity: %(qty)s" "\nProduct should be delivered before invoice" ) % {"plan": plan_qty, "qty": line.quantity} ) line.write({"quantity": plan_qty}) @api.model def _get_plan_qty(self, order_line, percent): plan_qty = order_line.product_qty * (percent / 100) return plan_qty def unlink(self): lines = self.filtered("no_edit") if lines: installments = [str(x) for x in lines.mapped("installment")] raise UserError( _( "Installment %s: already used and not allowed to delete.\n" "Please discard changes." ) % ", ".join(installments) ) return super().unlink()
35.960486
11,831
585
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. # Copyright 2019 Aleph Objects, Inc. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) { "name": "Purchase Force Invoiced", "summary": "Allows to force the billing status of the purchase order to " '"Invoiced"', "version": "15.0.1.0.1", "author": "Forgeflow, Odoo Community Association (OCA)", "category": "Purchase Management", "license": "AGPL-3", "website": "https://github.com/OCA/purchase-workflow", "depends": ["purchase"], "data": ["view/purchase_view.xml"], "installable": True, }
34.411765
585
5,334
py
PYTHON
15.0
# Copyright 2019 Eficent Business and IT Consulting Services S.L. # Copyright 2019 Aleph Objects, Inc. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import fields from odoo.tests.common import TransactionCase class TestPurchaseForceInvoiced(TransactionCase): def setUp(self): super(TestPurchaseForceInvoiced, self).setUp() self.purchase_order_model = self.env["purchase.order"] self.purchase_order_line_model = self.env["purchase.order.line"] self.account_invoice_model = self.env["account.move"] self.account_invoice_line = self.env["account.move.line"] self.invoice_account = self.env["account.account"].search( [ ( "user_type_id", "=", self.env.ref("account.data_account_type_revenue").id, ), ("company_id", "=", self.env.company.id), ], limit=1, ) # Data product_ctg = self._create_product_category() self.service_1 = self._create_product("test_product1", product_ctg) self.service_2 = self._create_product("test_product2", product_ctg) self.customer = self._create_supplier("Test Supplier") def _create_supplier(self, name): """Create a Partner.""" return self.env["res.partner"].create( {"name": name, "email": "example@yourcompany.com", "phone": 123456} ) def _create_product_category(self): product_ctg = self.env["product.category"].create({"name": "test_product_ctg"}) return product_ctg def _create_product(self, name, product_ctg): product = self.env["product.product"].create( { "name": name, "categ_id": product_ctg.id, "type": "service", "purchase_method": "receive", } ) return product def _create_invoice_from_purchase(self, purchase): invoice = self.account_invoice_model.create( {"partner_id": purchase.partner_id.id, "move_type": "in_invoice"} ) invoice.write({"purchase_id": purchase.id}) invoice._onchange_purchase_auto_complete() return invoice def create_invoice_line(self, line, invoice): vals = [ ( 0, 0, { "name": line.name, "product_id": line.product_id.id, "quantity": line.qty_received - line.qty_invoiced, "price_unit": line.price_unit, "account_id": self.invoice_account.id, "purchase_line_id": line.id, }, ) ] return invoice.update({"invoice_line_ids": vals}) def test_purchase_order(self): po = self.purchase_order_model.create({"partner_id": self.customer.id}) pol1 = self.purchase_order_line_model.create( { "name": self.service_1.name, "product_id": self.service_1.id, "product_qty": 1, "product_uom": self.service_1.uom_po_id.id, "price_unit": 500.0, "date_planned": fields.Date.today(), "order_id": po.id, } ) pol2 = self.purchase_order_line_model.create( { "name": self.service_2.name, "product_id": self.service_2.id, "product_qty": 2, "product_uom": self.service_2.uom_po_id.id, "price_unit": 500.0, "date_planned": fields.Date.today(), "order_id": po.id, } ) # confirm quotation po.button_confirm() # update quantities delivered pol1.qty_received = 1 pol2.qty_received = 2 self.assertEqual( po.invoice_status, "to invoice", "The invoice status should be To Invoice" ) invoice = self._create_invoice_from_purchase(po) self.create_invoice_line(pol1, invoice) self.create_invoice_line(pol2, invoice) self.assertEqual( po.invoice_status, "invoiced", "The invoice status should be Invoiced" ) # Reduce the invoiced qty for line in pol2.invoice_lines: line.with_context(check_move_validity=False).unlink() self.assertEqual( po.invoice_status, "to invoice", "The invoice status should be To Invoice" ) # We set the force invoiced. po.button_done() po.force_invoiced = True self.assertEqual( po.invoice_status, "invoiced", "The invoice status should be Invoiced" ) invoice = self._create_invoice_from_purchase(po) invoice_qty = sum(invoice.mapped("invoice_line_ids.quantity")) self.assertEqual(invoice_qty, 0.0) # We remove the force invoiced. po.force_invoiced = False self.assertEqual( po.invoice_status, "to invoice", "The invoice status should be To Invoice" ) self.create_invoice_line(pol2, invoice) invoice_qty = sum(invoice.mapped("invoice_line_ids.quantity")) self.assertEqual(invoice_qty, 2.0)
36.786207
5,334
880
py
PYTHON
15.0
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import api, fields, models class PurchaseOrder(models.Model): _inherit = "purchase.order" force_invoiced = fields.Boolean( readonly=True, states={"done": [("readonly", False)]}, copy=False, help="When you set this field, the purchase order will be " "considered as fully billed, even when there may be ordered " "or delivered quantities pending to bill. To use this field, " "the order must be in 'Locked' state", ) @api.depends("force_invoiced") def _get_invoiced(self): res = super(PurchaseOrder, self)._get_invoiced() for order in self.filtered( lambda po: po.force_invoiced and po.invoice_status == "to invoice" ): order.invoice_status = "invoiced" return res
33.846154
880
709
py
PYTHON
15.0
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) # Copyright 2022 Tecnativa - Pedro M. Baeza from odoo import models class PurchaseReport(models.Model): _inherit = "purchase.report" def _select(self): """Put quantity to be billed as 0 if it has been forced.""" select_str = super()._select() select_str = select_str.replace( "case when t.purchase_method = 'purchase'", "case when po.force_invoiced then 0.0 " "else (case when t.purchase_method = 'purchase' ", ) select_str = select_str.replace( "end as qty_to_be_billed", "end) end as qty_to_be_billed" ) return select_str
33.761905
709
686
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Roca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Purchase Order Product Recommendation XLSX", "summary": "Add a way to print recommended products for supplier", "version": "15.0.1.0.0", "category": "Purchases", "website": "https://github.com/OCA/purchase-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["purchase_order_product_recommendation", "report_xlsx"], "data": [ "wizards/purchase_order_recommendation_view.xml", "report/recommendation_xlsx.xml", ], }
38.111111
686
612
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Roca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.addons.purchase_order_product_recommendation.tests import test_recommendation class RecommendationCase(test_recommendation.RecommendationCase): def test_export_wizard(self): """Recommendations are OK.""" wizard = self.wizard() report_xlsx = self.env.ref( "purchase_order_product_recommendation_xlsx.recommendation_xlsx" )._render(wizard.ids) self.assertGreaterEqual(len(report_xlsx[0]), 1) self.assertEqual(report_xlsx[1], "xlsx")
43.714286
612
4,726
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, models class RecommendationXlsx(models.AbstractModel): _name = "report.purchase_order_product_recommendation_xlsx.summary" _inherit = "report.report_xlsx.abstract" _description = "Abstract model to export as xlsx the product recommendation" def _get_lang(self, user_id): 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, field_names): title_format = workbook.add_format( {"bold": 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) 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", _("Recommended products for supplier:"), title_format) sheet.write("B1", book.order_id.partner_id.name) sheet.write("A3", _("Date begin:"), title_format) sheet.write("B3", book.date_begin, date_format) sheet.write("D3", _("Date end:"), title_format) sheet.write("E3", book.date_end, date_format) # Header construction sheet.write(5, 0, _("Product"), header_format) next_col = 1 line_obj = self.env["purchase.order.recommendation.line"] for name in field_names: sheet.write(5, next_col, line_obj._fields[name].string, header_format) next_col += 1 sheet.write(5, next_col, _("Qty"), header_format) return sheet def _fill_data(self, workbook, sheet, book, field_names): decimal_format = workbook.add_format({"num_format": "0.00"}) lang = self._get_lang(book.create_uid.id) 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}) next_row = 6 line_obj = self.env["purchase.order.recommendation.line"] for line in book.line_ids: if line.currency_id.position == "after": monetary_format = workbook.add_format( {"num_format": "0.00 %s" % line.currency_id.symbol} ) else: monetary_format = workbook.add_format( {"num_format": "%s 0.00" % line.currency_id.symbol} ) sheet.write(next_row, 0, line.product_id.display_name) next_col = 1 for name in field_names: if line_obj._fields[name].type == "monetary": sheet.write(next_row, next_col, line[name], monetary_format) elif line_obj._fields[name].type in ["date", "datetime"]: sheet.write(next_row, next_col, line[name], date_format) else: sheet.write(next_row, next_col, line[name], decimal_format) next_col += 1 sheet.write(next_row, next_col, line.units_included, decimal_format) next_row += 1 return sheet def generate_xlsx_report(self, workbook, data, objects): book = objects[0] field_names = sorted( book.line_ids.fields_get().keys() - self.get_restricted_fields() ) sheet = self._create_product_pricelist_sheet(workbook, book, field_names) sheet = self._fill_data(workbook, sheet, book, field_names) def get_restricted_fields(self): return { "currency_id", "partner_id", "product_id", "units_included", "times_delivered", "times_received", "wizard_id", "purchase_line_id", "is_modified", "id", "display_name", "create_uid", "create_date", "write_uid", "write_date", "__last_update", }
41.823009
4,726
952
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Roca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class PurchaseOrderRecommendation(models.TransientModel): _inherit = "purchase.order.recommendation" def export_xlsx(self): self.ensure_one() return self.env.ref( "purchase_order_product_recommendation_xlsx.recommendation_xlsx" ).report_action(self) class PurchaseOrderRecommendationLine(models.TransientModel): _inherit = "purchase.order.recommendation.line" price_unit = fields.Monetary(string="Price") units_received = fields.Float(string="Qty Received") units_delivered = fields.Float(string="Qty delivered") units_avg_delivered = fields.Float(string="Qty Dlvd./day") units_available = fields.Float(string="Qty On Hand") units_virtual_available = fields.Float(string="Forecasted Qty") units_included = fields.Float(string="Qty")
38.08
952
493
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Purchase Receipt Expectation", "version": "15.0.1.0.0", "category": "Purchase Management", "author": "Camptocamp SA, Odoo Community Association (OCA)", "website": "https://github.com/OCA/purchase-workflow", "license": "AGPL-3", "data": [ "views/purchase_order.xml", ], "depends": [ "purchase_stock", ], "installable": True, }
27.388889
493
4,092
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from datetime import datetime from odoo import fields, models from odoo.tests.common import TransactionCase class TestPurchaseReceiptExpectation(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.po_partner = cls.env["res.partner"].create({"name": "Partner"}) cls.po_product = cls.env["product.product"].create( {"name": "Product", "detailed_type": "product"} ) cls.po_vals = { "partner_id": cls.po_partner.id, "order_line": [ ( 0, 0, { "name": cls.po_product.name, "product_id": cls.po_product.id, "product_qty": 1.0, "product_uom": cls.po_product.uom_po_id.id, "price_unit": 10.0, "date_planned": datetime.today(), }, ) ], } def test_00_automatic_receipt(self): """Tests normal workflow when `receipt_expectation == "automatic"` Steps: - Create a standard purchase order - Confirm it Expect: - `receipt_expectation` must be "automatic" (as default value) - At least one picking should have been created """ order = self.env["purchase.order"].create(self.po_vals) self.assertEqual(order.receipt_expectation, "automatic") order.button_confirm() self.assertTrue(order.picking_ids) def test_01_custom_receipt(self): """Tests workflows with custom receipt expectation values Steps: - Extend `purchase.order` with a mock-up model - Extend `receipt_expectation` with 2 mock-up values, "succeeding" and "failing" - Create a method related to "succeeding" that simply creates a picking (call `_create_picking` with shortcut context key), don't create a method for "failing" - Create a purchase order with `receipt_expectation = "succeeding"` - Create a purchase order with `receipt_expectation = "failing"` - Confirm both, one at a time Expect: - A picking should be created for succeeding order - NotImplementedError must be raised when confirming failing order """ class PurchaseOrderMockUp(models.Model): _inherit = "purchase.order" receipt_expectation = fields.Selection( selection_add=[ ("succeeding", "Succeeding"), ("failing", "Failing"), ], ondelete={ "succeeding": "set default", "failing": "set default", }, ) def _create_picking_for_succeeding_receipt_expectation(self): """Standard picking creation workflow""" orders = self.with_context(skip_custom_receipt_expectation=1) return orders._create_picking() PurchaseOrderMockUp._build_model(self.registry, self.cr) self.registry.setup_models(self.cr) succeeding_order = self.env["purchase.order"].create( dict(self.po_vals, receipt_expectation="succeeding") ) self.assertEqual(succeeding_order.receipt_expectation, "succeeding") succeeding_order.button_confirm() self.assertTrue(succeeding_order.picking_ids) failing_order = self.env["purchase.order"].create( dict(self.po_vals, receipt_expectation="failing") ) with self.assertRaises(NotImplementedError) as error: failing_order.button_confirm() method = "_create_picking_for_failing_receipt_expectation" msg = "Method `purchase.order.%s()` not implemented" % method self.assertEqual(error.exception.args[0], msg)
38.242991
4,092
1,804
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from collections import defaultdict from odoo import fields, models class PurchaseOrder(models.Model): _inherit = "purchase.order" # New values added to this selection also require the definition # of methods that manage such values. These methods must be named # `_create_picking_for_<value>_receipt_expectation()`. # See `_create_picking()` override. receipt_expectation = fields.Selection( [("automatic", "Automatic")], help="Defines how reception pickings are managed when the order is" " approved.\nDefault value is 'automatic', which means the" " picking will be created following the standard Odoo workflow.", default="automatic", required=True, ) def _create_picking(self): if self.env.context.get("skip_custom_receipt_expectation"): # Shortcut; also avoids recursion errors return super()._create_picking() groups = defaultdict(list) for order in self: groups[order.receipt_expectation].append(order.id) for exp, order_ids in groups.items(): orders = self.browse(order_ids) method = "_create_picking_for_%s_receipt_expectation" % exp if hasattr(orders, method): getattr(orders, method)() else: msg = "Method `%s.%s()` not implemented" % (self._name, method) raise NotImplementedError(msg) return True def _create_picking_for_automatic_receipt_expectation(self): """Automatic => standard picking creation workflow""" orders = self.with_context(skip_custom_receipt_expectation=True) return orders._create_picking()
40.088889
1,804
743
py
PYTHON
15.0
# Copyright 2019 David Vidal <david.vidal@tecnativa.com> # Copyright 2020 Manuel Calero - Tecnativa # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Purchase Order Product Recommendation", "summary": "Recommend products to buy to supplier based on history", "version": "15.0.1.0.1", "category": "Purchases", "website": "https://github.com/OCA/purchase-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["purchase_stock"], "data": [ "security/ir.model.access.csv", "wizards/purchase_order_recommendation_view.xml", "views/purchase_order_view.xml", ], }
37.15
743
14,163
py
PYTHON
15.0
# Copyright 2019 David Vidal <david.vidal@tecnativa.com> # Copyright 2020 Manuel Calero - Tecnativa # Copyright 2020 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields from odoo.tests.common import TransactionCase class RecommendationCase(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.partner = cls.env["res.partner"].create({"name": "Mr. Odoo"}) cls.category_obj = cls.env["product.category"] cls.categ1 = cls.category_obj.create({"name": "Test Cat 1"}) cls.categ2 = cls.category_obj.create({"name": "Test Cat 2"}) cls.product_obj = cls.env["product.product"] cls.prod_1 = cls.product_obj.create( { "default_code": "product-1", "name": "Test Product 1", "categ_id": cls.categ1.id, "type": "product", "seller_ids": [(0, 0, {"name": cls.partner.id, "price": 5})], } ) cls.prod_2 = cls.product_obj.create( { "default_code": "product-2", "name": "Test Product 2", "categ_id": cls.categ2.id, "type": "product", "seller_ids": [(0, 0, {"name": cls.partner.id, "price": 10})], } ) cls.prod_3 = cls.product_obj.create( { "default_code": "product-3", "name": "Test Product 3", "categ_id": cls.categ2.id, "type": "product", "seller_ids": [(0, 0, {"name": cls.partner.id, "price": 7})], } ) # Warehouses cls.wh1 = cls.env["stock.warehouse"].create( {"name": "TEST WH1", "code": "TST1"} ) cls.wh2 = cls.env["stock.warehouse"].create( {"name": "TEST WH2", "code": "TST2"} ) # Locations location_obj = cls.env["stock.location"] cls.supplier_loc = location_obj.create( {"name": "Test supplier location", "usage": "supplier"} ) cls.customer_loc = location_obj.create( {"name": "Test customer location", "usage": "customer"} ) # Create deliveries and receipts orders to have a history cls.picking_obj = cls.env["stock.picking"] cls.picking_1 = cls.picking_obj.create( { "location_id": cls.wh1.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, "partner_id": cls.partner.id, "picking_type_id": cls.wh1.out_type_id.id, } ) cls.picking_2 = cls.picking_obj.create( { "location_id": cls.wh2.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, "partner_id": cls.partner.id, "picking_type_id": cls.wh2.out_type_id.id, } ) cls.picking_3 = cls.picking_obj.create( { "location_id": cls.supplier_loc.id, "location_dest_id": cls.wh1.lot_stock_id.id, "partner_id": cls.partner.id, "picking_type_id": cls.wh1.in_type_id.id, } ) cls.move_line = cls.env["stock.move.line"] cls.move_line |= cls.move_line.create( { "product_id": cls.prod_1.id, "product_uom_id": cls.prod_1.uom_id.id, "qty_done": 1, "date": fields.Datetime.from_string("2018-01-11 15:05:00"), "location_id": cls.wh1.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, "picking_id": cls.picking_1.id, } ) cls.move_line |= cls.move_line.create( { "product_id": cls.prod_2.id, "product_uom_id": cls.prod_2.uom_id.id, "qty_done": 38, "date": fields.Datetime.from_string("2019-02-01 00:05:00"), "location_id": cls.wh1.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, "picking_id": cls.picking_1.id, } ) cls.move_line |= cls.move_line.create( { "product_id": cls.prod_2.id, "product_uom_id": cls.prod_2.uom_id.id, "qty_done": 4, "date": fields.Datetime.from_string("2019-02-01 00:05:00"), "location_id": cls.wh2.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, "picking_id": cls.picking_2.id, } ) cls.move_line |= cls.move_line.create( { "product_id": cls.prod_3.id, "product_uom_id": cls.prod_3.uom_id.id, "qty_done": 13, "date": fields.Datetime.from_string("2019-02-01 00:06:00"), "location_id": cls.wh2.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, "picking_id": cls.picking_2.id, } ) cls.move_line |= cls.move_line.create( { "product_id": cls.prod_3.id, "product_uom_id": cls.prod_3.uom_id.id, "qty_done": 7, "date": fields.Datetime.from_string("2019-02-01 00:00:00"), "location_id": cls.supplier_loc.id, "location_dest_id": cls.wh1.lot_stock_id.id, "picking_id": cls.picking_3.id, } ) cls.move_line.write({"state": "done"}) # Total stock available for prod3 is 5 units split in two warehouses quant_obj = cls.env["stock.quant"] quant_obj.create( { "product_id": cls.prod_3.id, "location_id": cls.wh1.lot_stock_id.id, "quantity": 2.0, } ) quant_obj.create( { "product_id": cls.prod_3.id, "location_id": cls.wh2.lot_stock_id.id, "quantity": 3.0, } ) # Create a purchase order for the same customer cls.new_po = cls.env["purchase.order"].create({"partner_id": cls.partner.id}) def wizard(self): """Get a wizard.""" wizard = ( self.env["purchase.order.recommendation"] .with_context(active_id=self.new_po.id, active_model="purchase.order") .create({}) ) wizard._generate_recommendations() return wizard class RecommendationCaseTests(RecommendationCase): def test_recommendations(self): """Recommendations are OK.""" wizard = self.wizard() # Order came in from context self.assertEqual(wizard.order_id, self.new_po) # All our moves are in the past self.assertFalse(wizard.line_ids) wizard.date_begin = wizard.date_end = fields.Date.from_string("2019-02-01") wizard._generate_recommendations() line_prod_2 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_2) self.assertEqual(line_prod_2.times_delivered, 2) self.assertEqual(line_prod_2.units_delivered, 42) self.assertEqual(line_prod_2.units_included, 42) line_prod_3 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_3) self.assertEqual(line_prod_3.times_delivered, 1) self.assertEqual(line_prod_3.units_delivered, 13) self.assertEqual(line_prod_3.units_included, 8) self.assertEqual(line_prod_3.units_available, 5) self.assertEqual(line_prod_3.units_virtual_available, 5) # Only 1 product if limited as such wizard.line_amount = 1 wizard._generate_recommendations() self.assertEqual(len(wizard.line_ids), 1) def test_recommendations_by_warehouse(self): """We can split recommendations by delivery warehouse""" wizard = self.wizard() wizard.date_begin = wizard.date_end = fields.Date.from_string("2019-02-01") # Just delivered to WH2 wizard.warehouse_ids = self.wh2 wizard._generate_recommendations() line_prod_2 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_2) self.assertEqual(line_prod_2.times_delivered, 1) self.assertEqual(line_prod_2.units_delivered, 4) self.assertEqual(line_prod_2.units_included, 4) line_prod_3 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_3) self.assertEqual(line_prod_3.times_delivered, 1) self.assertEqual(line_prod_3.units_delivered, 13) self.assertEqual(line_prod_3.units_included, 10) self.assertEqual(line_prod_3.units_available, 3) self.assertEqual(line_prod_3.units_virtual_available, 3) # Just delivered to WH1 wizard.warehouse_ids = self.wh1 wizard._generate_recommendations() self.assertEqual(len(wizard.line_ids), 2) line_prod_2 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_2) self.assertEqual(line_prod_2.times_delivered, 1) self.assertEqual(line_prod_2.units_delivered, 38) self.assertEqual(line_prod_2.units_included, 38) line_prod_3 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_3) self.assertEqual(line_prod_3.times_delivered, 0) self.assertEqual(line_prod_3.units_delivered, 0) self.assertEqual(line_prod_3.units_received, 7) self.assertEqual(line_prod_3.units_included, 0) self.assertEqual(line_prod_3.units_available, 2) self.assertEqual(line_prod_3.units_virtual_available, 2) # Delivered to both warehouses wizard.warehouse_ids |= self.wh2 wizard._generate_recommendations() line_prod_2 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_2) self.assertEqual(line_prod_2.times_delivered, 2) self.assertEqual(line_prod_2.units_delivered, 42) self.assertEqual(line_prod_2.units_included, 42) line_prod_3 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_3) self.assertEqual(line_prod_3.times_delivered, 1) self.assertEqual(line_prod_3.units_delivered, 13) self.assertEqual(line_prod_3.units_included, 8) self.assertEqual(line_prod_3.units_available, 5) self.assertEqual(line_prod_3.units_virtual_available, 5) def test_action_accept(self): """Open wizard when there are PO Lines and click on Accept""" po_line = self.env["purchase.order.line"].new( {"sequence": 1, "order_id": self.new_po.id, "product_id": self.prod_2.id} ) po_line.onchange_product_id() po_line.product_qty = 10 po_line._onchange_quantity() self.new_po.order_line = po_line # Create wizard and set dates wizard = self.wizard() wizard.date_begin = wizard.date_end = fields.Date.from_string("2019-02-01") wizard._generate_recommendations() # After change dates, in the recommendation line corresponding to the # self.prod_2 Units Included must be 10 line_prod_2 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_2) self.assertEqual(line_prod_2.units_included, 10) line_prod_3 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_3) self.assertEqual(line_prod_3.units_included, 8) # Change Units Included amount to 20 and accept, then the product_qty # of the PO Line corresponding to the self.prod_2 must change to 20 line_prod_2.units_included = 20 wizard.action_accept() self.assertEqual(len(self.new_po.order_line), 2) po_line_prod_2 = self.new_po.order_line.filtered( lambda x: x.product_id == self.prod_2 ) self.assertEqual(po_line_prod_2.product_qty, 20) po_line_prod_3 = self.new_po.order_line.filtered( lambda x: x.product_id == self.prod_3 ) self.assertEqual(po_line_prod_3.product_qty, 8) def test_recommendations_by_category(self): """We can split recommendations by delivery warehouse""" wizard = self.wizard() wizard.date_begin = wizard.date_end = fields.Date.from_string( "2019-02-01" ) # "2019-02-01" # Just delivered from category 1 wizard.product_category_ids = self.categ1 wizard.show_all_partner_products = True wizard._generate_recommendations() # Just one line with products from category 1 self.assertEqual(wizard.line_ids.product_id, self.prod_1) # Just delivered from category 2 wizard.product_category_ids = self.categ2 wizard._generate_recommendations() self.assertEqual(len(wizard.line_ids), 2) # All categorys wizard.product_category_ids += self.categ1 wizard._generate_recommendations() self.assertEqual(len(wizard.line_ids), 3) # No category set wizard.product_category_ids = False wizard._generate_recommendations() self.assertEqual(len(wizard.line_ids), 3) # All products wizard.show_all_products = True wizard.line_amount = 0 wizard._generate_recommendations() purchase_products_number = self.product_obj.search_count( [("purchase_ok", "!=", False)] ) self.assertEqual(len(wizard.line_ids), purchase_products_number) def test_recommendations_inactive_product(self): """Recommendations are OK.""" self.prod_2.active = False wizard = self.wizard() wizard.date_begin = wizard.date_end = fields.Date.from_string("2019-02-01") wizard._generate_recommendations() # The first recommendation line is the prod_3, as prod_2 is archived self.assertEqual(wizard.line_ids[0].product_id, self.prod_3) self.prod_3.purchase_ok = False wizard._generate_recommendations() # No recommendations as both elegible products are excluded self.assertFalse(wizard.line_ids)
44.121495
14,163
15,224
py
PYTHON
15.0
# Copyright 2019 David Vidal <david.vidal@tecnativa.com> # Copyright 2020 Manuel Calero - Tecnativa # Copyright 2020 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from datetime import datetime, timedelta from odoo import _, api, fields, models from odoo.exceptions import UserError class PurchaseOrderRecommendation(models.TransientModel): _name = "purchase.order.recommendation" _description = "Recommended products for current purchase order" order_id = fields.Many2one( comodel_name="purchase.order", string="Purchase Order", default=lambda self: self._default_order_id(), required=True, readonly=True, ondelete="cascade", ) date_begin = fields.Date( default=fields.Date.context_today, required=True, help="Initial date to compute recommendations.", ) date_end = fields.Date( default=fields.Date.context_today, required=True, help="Final date to compute recommendations.", ) line_ids = fields.One2many( comodel_name="purchase.order.recommendation.line", inverse_name="wizard_id", string="Products", ) line_amount = fields.Integer( string="Number of recommendations", default=15, required=True, help="Stablish a limit on how many recommendations you want to get." "Leave it as 0 to set no limit", ) show_all_partner_products = fields.Boolean( string="Show all supplier products", default=False, help="Show all products with supplier infos for this supplier", ) show_all_products = fields.Boolean( string="Show all purchasable products", default=False, help="Useful if a product hasn't been selled by the partner yet", ) product_category_ids = fields.Many2many( comodel_name="product.category", string="Product Categories", help="Filter by product internal category", ) warehouse_ids = fields.Many2many( comodel_name="stock.warehouse", string="Warehouse", help="Constrain search to an specific warehouse", ) warehouse_count = fields.Integer( default=lambda self: len(self.env["stock.warehouse"].search([])), ) @api.model def _default_order_id(self): if self.env.context.get("active_model", False) != "purchase.order": raise UserError(_("This wizard is only valid for purchases")) return self.env.context.get("active_id", False) def _get_total_days(self): """Compute days between the initial and the end date""" day = (self.date_end + timedelta(days=1) - self.date_begin).days return day def _get_supplier_products(self): """Common method to be used for field domain filters""" supplierinfo_obj = self.env["product.supplierinfo"].with_context( prefetch_fields=False ) partner = self.order_id.partner_id.commercial_partner_id supplierinfos = supplierinfo_obj.search([("name", "=", partner.id)]) product_tmpls = supplierinfos.mapped("product_tmpl_id").filtered( lambda x: x.active and x.purchase_ok ) products = supplierinfos.mapped("product_id").filtered( lambda x: x.active and x.purchase_ok ) products += product_tmpls.mapped("product_variant_ids") return products def _get_products(self): """Override to filter products show_all_partner_products is set""" products = self._get_supplier_products() # Filter products by category if set. # It will apply to show_all_partner_products as well if self.product_category_ids: products = products.filtered( lambda x: x.categ_id in self.product_category_ids ) return products def _get_move_line_domain(self, products, src, dst): """Allows to easily extend the domain by third modules""" combine = datetime.combine # We can receive a context to be able to get different dates with # the same wizard attributes, for example comparing periods date_begin = self.env.context.get("period_date_begin", self.date_begin) date_end = self.env.context.get("period_date_end", self.date_end) domain = [ ("product_id", "in", products.ids), ("date", ">=", combine(date_begin, datetime.min.time())), ("date", "<=", combine(date_end, datetime.max.time())), ("location_id.usage", "=", src), ("location_dest_id.usage", "=", dst), ("state", "=", "done"), ] if self.warehouse_ids: domain += [ ( "picking_id.picking_type_id.warehouse_id", "in", self.warehouse_ids.ids, ) ] return domain def _get_all_products_domain(self): """Override to add more product filters if show_all_products is set""" domain = [ ("purchase_ok", "=", True), ] if self.product_category_ids: domain += [("categ_id", "in", self.product_category_ids.ids)] return domain def _find_move_line(self, src="internal", dst="customer"): """ "Returns a dictionary from the move lines in a range of dates from and to given location types""" products = self._get_products() domain = self._get_move_line_domain(products, src, dst) found_lines = self.env["stock.move.line"].read_group( domain, ["product_id", "qty_done"], ["product_id"] ) # Manual ordering that circumvents ORM limitations found_lines = sorted( found_lines, key=lambda res: ( res["product_id_count"], res["qty_done"], ), reverse=True, ) product_dict = {p.id: p for p in products} found_lines = [ { "id": x["product_id"][0], "product_id": product_dict[x["product_id"][0]], "product_id_count": x["product_id_count"], "qty_done": x["qty_done"], } for x in found_lines ] found_lines = {line["id"]: line for line in found_lines} # Show every purchaseable product if self.show_all_products: products += self.env["product.product"].search( self._get_all_products_domain() ) # Show all products with supplier infos belonging to a partner if self.show_all_partner_products or self.show_all_products: for product in products.filtered(lambda p: p.id not in found_lines.keys()): found_lines.update({product.id: {"product_id": product}}) return found_lines def _prepare_wizard_line_from_seller(self, vals, seller): """Allow to add values coming from the selected seller, which will have more priority than existing prepared values. :param vals: Existing wizard line dictionary vals. :param seller: Selected seller for this line. """ self.ensure_one() return { "price_unit": seller.price, } def _prepare_wizard_line(self, vals, order_line=False): """Used to create the wizard line""" self.ensure_one() product_id = order_line and order_line.product_id or vals["product_id"] if self.warehouse_ids: units_available = sum( product_id.with_context(warehouse=wh).qty_available for wh in self.warehouse_ids.ids ) units_virtual_available = sum( product_id.with_context(warehouse=wh).virtual_available for wh in self.warehouse_ids.ids ) else: units_available = product_id.qty_available units_virtual_available = product_id.virtual_available qty_to_order = abs( min(0, units_virtual_available - vals.get("qty_delivered", 0)) ) vals["is_modified"] = bool(qty_to_order) units_included = order_line and order_line.product_qty or qty_to_order seller = product_id._select_seller( partner_id=self.order_id.partner_id, date=fields.Date.today(), quantity=units_included, uom_id=product_id.uom_po_id, ) res = { "purchase_line_id": order_line and order_line.id, "product_id": product_id.id, "product_name": product_id.name, "product_code": product_id.code, "times_delivered": vals.get("times_delivered", 0), "times_received": vals.get("times_received", 0), "units_received": vals.get("qty_received", 0), "units_available": units_available, "units_virtual_available": units_virtual_available, "units_avg_delivered": ( vals.get("qty_delivered", 0) / self._get_total_days() ), "units_delivered": vals.get("qty_delivered", 0), "units_included": units_included, "is_modified": vals.get("is_modified", False), } res.update(self._prepare_wizard_line_from_seller(res, seller)) return res @api.onchange( "order_id", "date_begin", "date_end", "line_amount", "show_all_partner_products", "show_all_products", "product_category_ids", "warehouse_ids", ) def _generate_recommendations(self): """Generate lines according to received and delivered items""" self.line_ids = False # Get quantities received from suppliers found_dict = self._find_move_line(src="supplier", dst="internal") for product, line in found_dict.items(): found_dict[product]["qty_received"] = line.get("qty_done", 0) found_dict[product]["times_received"] = line.get("product_id_count", 0) # Get quantities delivered to customers found_delivered_dict = self._find_move_line(src="internal", dst="customer") # Merge the two dicts for product, line in found_delivered_dict.items(): if not found_dict.get(product): found_dict[product] = line found_dict[product]["qty_delivered"] = line.get("qty_done", 0) found_dict[product]["times_delivered"] = line.get("product_id_count", 0) found_dict[product].update( {k: v for k, v in line.items() if k not in found_dict[product].keys()} ) RecomendationLine = self.env["purchase.order.recommendation.line"] existing_product_ids = [] # Add products from purchase order lines for order_line in self.order_id.order_line: found_line = found_dict.get(order_line.product_id.id, {}) new_line = RecomendationLine.new( self._prepare_wizard_line(found_line, order_line) ) self.line_ids += new_line existing_product_ids.append(order_line.product_id.id) # Add those recommendations too i = 0 for product, line in found_dict.items(): if product in existing_product_ids: continue new_line = RecomendationLine.new(self._prepare_wizard_line(line)) self.line_ids += new_line # Limit number of results. It has to be done here, as we need to # populate all results first, for being able to select best matches i += 1 if i == self.line_amount: break self.line_ids = self.line_ids.sorted(key=lambda x: x.product_id.name) def action_accept(self): """Propagate recommendations to purchase order.""" po_lines = self.env["purchase.order.line"] sequence = max(self.order_id.mapped("order_line.sequence") or [0]) for wiz_line in self.line_ids.filtered("is_modified"): # Use preexisting line if any if wiz_line.purchase_line_id: if wiz_line.units_included: wiz_line.purchase_line_id.update(wiz_line._prepare_update_po_line()) wiz_line.purchase_line_id._onchange_quantity() else: wiz_line.purchase_line_id.unlink() continue sequence += 1 # Use a new in-memory line otherwise po_line = po_lines.new(wiz_line._prepare_new_po_line(sequence)) po_line.onchange_product_id() po_line.product_qty = wiz_line.units_included po_line._onchange_quantity() po_lines |= po_line self.order_id.order_line |= po_lines class PurchaseOrderRecommendationLine(models.TransientModel): _name = "purchase.order.recommendation.line" _description = "Recommended product for current purchase order" _order = "id" currency_id = fields.Many2one( related="product_id.currency_id", readonly=True, ) partner_id = fields.Many2one( related="wizard_id.order_id.partner_id", readonly=True, ) product_id = fields.Many2one( comodel_name="product.product", string="Product", ) product_name = fields.Char() product_code = fields.Char(string="Product reference") price_unit = fields.Monetary( readonly=True, ) times_delivered = fields.Integer( readonly=True, ) times_received = fields.Integer( readonly=True, ) units_received = fields.Float( readonly=True, ) units_delivered = fields.Float( readonly=True, ) units_avg_delivered = fields.Float( digits="Product Unit of Measure", readonly=True, ) units_available = fields.Float( readonly=True, ) units_virtual_available = fields.Float( readonly=True, ) units_included = fields.Float() wizard_id = fields.Many2one( comodel_name="purchase.order.recommendation", string="Wizard", ondelete="cascade", required=True, readonly=True, ) purchase_line_id = fields.Many2one( comodel_name="purchase.order.line", ) is_modified = fields.Boolean() @api.onchange("units_included") def _onchange_units_included(self): self.is_modified = bool(self.purchase_line_id or self.units_included) self.price_unit = self.product_id._select_seller( partner_id=self.partner_id, date=fields.Date.today(), quantity=self.units_included, uom_id=self.product_id.uom_po_id, ).price def _prepare_update_po_line(self): """So we can extend PO update""" return { "product_qty": self.units_included, } def _prepare_new_po_line(self, sequence): """So we can extend PO create""" return { "order_id": self.wizard_id.order_id.id, "product_id": self.product_id.id, "sequence": sequence, }
38.541772
15,224
527
py
PYTHON
15.0
# Copyright 2020 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Purchase Representative", "summary": "Purchase Representatives will be the point of contact for " "RFQ's and PO's", "version": "15.0.1.0.0", "category": "Purchases", "website": "https://github.com/OCA/purchase-workflow", "author": "ForgeFlow, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["purchase_stock"], }
35.133333
527
756
py
PYTHON
15.0
# Copyright 2020-21 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models class StockRule(models.Model): _inherit = "stock.rule" def _run_buy(self, procurements): for procurement, _rule in procurements: procurement.values["propagate_create_uid"] = self.env.uid return super()._run_buy(procurements) def _prepare_purchase_order(self, company_id, origins, values): vals = super()._prepare_purchase_order(company_id, origins, values) create_uids = [v.get("propagate_create_uid") for v in values] create_uids = list(set(create_uids)) if len(create_uids) == 1: vals.update({"user_id": create_uids[0]}) return vals
36
756
502
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Purchase Partner Selectable Option", "version": "15.0.1.0.1", "category": "Purchase", "website": "https://github.com/OCA/purchase-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "depends": ["purchase"], "data": ["views/res_partner_view.xml"], "installable": True, "maintainers": ["victoralmau"], }
35.714286
500
717
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from lxml import etree from odoo.tests import common class TestPurchasePartnerSelectableOption(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() def test_sale_order(self): result = self.env["purchase.order"].fields_view_get( view_id=self.env.ref("purchase.purchase_order_form").id, view_type="form", ) doc = etree.XML(result["arch"]) field = doc.xpath("//field[@name='partner_id']") domain = field[0].get("domain") self.assertTrue("('purchase_selectable', '=', True)" in domain)
34.047619
715
1,062
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from lxml import etree from odoo import api, models class PurchaseOrder(models.Model): _inherit = "purchase.order" @api.model def fields_view_get( self, view_id=None, view_type="form", toolbar=False, submenu=False ): res = super().fields_view_get( view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu, ) if view_type == "form": order_xml = etree.XML(res["arch"]) partner_id_fields = order_xml.xpath("//field[@name='partner_id']") if partner_id_fields: partner_id_field = partner_id_fields[0] domain = partner_id_field.get("domain", "[]").replace( "[", "[('purchase_selectable', '=', True)," ) partner_id_field.attrib["domain"] = domain res["arch"] = etree.tostring(order_xml) return res
33.125
1,060
315
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class Partner(models.Model): _inherit = "res.partner" purchase_selectable = fields.Boolean( string="Selectable in purchase orders", default=True )
26.083333
313
657
py
PYTHON
15.0
# © 2017 Akretion (http://www.akretion.com) Payment # @author Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Purchase Free-Of-Payment shipping", "version": "15.0.1.0.0", "author": "Akretion,Odoo Community Association (OCA)", "website": "https://github.com/OCA/purchase-workflow", "maintainer": "Akretion", "license": "AGPL-3", "category": "Purchase", "depends": ["purchase"], "data": [ "security/res_groups.xml", "views/purchase_order.xml", "views/res_partner.xml", ], "installable": True, }
32.8
656
2,267
py
PYTHON
15.0
# © 2017 Akretion (http://www.akretion.com) # @author Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields from odoo.exceptions import UserError from odoo.tests.common import TransactionCase class TestPurchaseOrder(TransactionCase): @classmethod def setUpClass(cls): super(TestPurchaseOrder, cls).setUpClass() cls.Product = cls.env["product.product"] cls.Purchase = cls.env["purchase.order"] cls.PurchaseLine = cls.env["purchase.order.line"] cls.product_1 = cls.Product.create({"name": "Product", "type": "consu"}) cls.partner_3 = cls.env.ref("base.res_partner_3") cls.partner_3.fop_shipping = 250 def test_fop_shipping_reached1(self): po = self.Purchase.create({"partner_id": self.partner_3.id}) self.PurchaseLine.create( { "order_id": po.id, "product_id": self.product_1.id, "date_planned": fields.Datetime.now(), "name": "Test", "product_qty": 1.0, "product_uom": self.product_1.uom_id.id, "price_unit": 100.0, } ) self.assertFalse(po.fop_reached) with self.assertRaises(UserError) as e, self.env.cr.savepoint(): po.button_approve() self.assertTrue( "You cannot confirm a purchase order with amount under " "FOP shipping" in e.exception.name ) po.force_order_under_fop = True po.button_approve() self.assertEqual(po.state, "purchase") def test_fop_shipping_reached2(self): po = self.Purchase.create({"partner_id": self.partner_3.id}) self.PurchaseLine.create( { "order_id": po.id, "product_id": self.product_1.id, "date_planned": fields.Datetime.now(), "name": "Test", "product_qty": 10, "product_uom": self.product_1.uom_id.id, "price_unit": 45, } ) self.assertTrue(po.fop_reached) po.button_approve() self.assertEqual(po.state, "purchase")
34.333333
2,266
476
py
PYTHON
15.0
# © 2014-2016 Akretion (http://www.akretion.com) # @author Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ResPartner(models.Model): _inherit = "res.partner" fop_shipping = fields.Float( string="FOP shipping", help="Min purchase order amount for FOP shipping", company_dependent=True, digits="Account", )
27.941176
475
2,036
py
PYTHON
15.0
# Copyright 2017 Akretion (http://www.akretion.com) # @author Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.exceptions import UserError from odoo.tools import float_compare class PurchaseOrder(models.Model): _inherit = "purchase.order" fop_reached = fields.Boolean( string="FOP reached", help="Free-Of-Payment shipping reached", compute="_compute_fop_shipping_reached", ) force_order_under_fop = fields.Boolean( string="Confirm under FOP", help="Force confirm purchase order under Free-Of-Payment shipping", ) fop_shipping = fields.Float( string="FOP shipping", related="partner_id.fop_shipping", related_sudo=False, readonly=True, help="Min purchase order amount for Free-Of-Payment shipping", ) @api.depends( "amount_total", "partner_id.fop_shipping", ) def _compute_fop_shipping_reached(self): digit_precision = self.env["decimal.precision"].precision_get("Account") for record in self: record.fop_reached = ( float_compare( record.amount_total, record.partner_id.fop_shipping, precision_digits=digit_precision, ) >= 0 ) def button_approve(self, force=False): self._check_fop_shipping() result = super().button_approve(force=force) return result def _check_fop_shipping(self): for po in self: if not po.force_order_under_fop and not po.fop_reached: raise UserError( _( "You cannot confirm a purchase order with amount under " 'FOP shipping. To force confirm you must belongs to "FOP' ' shipping Manager".' ) )
33.377049
2,036
686
py
PYTHON
15.0
# Copyright 2019 David Vidal <david.vidal@tecnativa.com> # Copyright 2020 Manuel Calero - Tecnativa # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Purchase Order Product Recommendation Brand Filter", "summary": "Allow to filter recommendations by brand", "version": "15.0.1.0.0", "category": "Purchases", "website": "https://github.com/OCA/purchase-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["purchase_order_product_recommendation", "product_brand"], "data": ["wizards/purchase_order_recommendation_view.xml"], }
42.875
686
2,360
py
PYTHON
15.0
# Copyright 2019 Tecnativa # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.addons.purchase_order_product_recommendation.tests import test_recommendation class BrandRecommendationCase(test_recommendation.RecommendationCase): @classmethod def setUpClass(cls): super().setUpClass() cls.brand_obj = cls.env["product.brand"] cls.brand_1 = cls.brand_obj.create({"name": "OCA Cola"}) cls.brand_2 = cls.brand_obj.create({"name": "Play-Odoo"}) cls.prod_1.product_brand_id = cls.brand_1 cls.prod_2.product_brand_id = cls.brand_2 cls.prod_3.product_brand_id = cls.brand_2 def test_recommendations_by_brand(self): """We can filter by brand""" wizard = self.wizard() wizard.date_begin = wizard.date_end = "2019-02-01" # Just delivered from brand 1 wizard.product_brand_ids = self.brand_1 wizard.show_all_partner_products = True wizard._generate_recommendations() # Just one line with products from brand 1 self.assertEqual(wizard.line_ids.product_id, self.prod_1) # Just delivered from brand 2 wizard.product_brand_ids = self.brand_2 wizard._generate_recommendations() self.assertEqual(len(wizard.line_ids), 2) # All brands wizard.product_brand_ids += self.brand_1 wizard._generate_recommendations() self.assertEqual(len(wizard.line_ids), 3) # No brand set wizard.product_brand_ids = False wizard._generate_recommendations() self.assertEqual(len(wizard.line_ids), 3) def test_recommendations_by_brand_all_products(self): """Brand filters also apply to all products filter""" wizard = self.wizard() wizard.date_begin = wizard.date_end = "2019-02-01" # First we show all purchasable products wizard.show_all_products = True wizard.line_amount = 0 wizard._generate_recommendations() purchase_products_number = self.product_obj.search_count( [("purchase_ok", "!=", False)] ) self.assertEqual(len(wizard.line_ids), purchase_products_number) # Then we filter by brand wizard.product_brand_ids = self.brand_2 wizard._generate_recommendations() self.assertEqual(len(wizard.line_ids), 2)
42.909091
2,360
2,340
py
PYTHON
15.0
# Copyright 2019 Tecnativa # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class PurchaseOrderRecommendation(models.TransientModel): _inherit = "purchase.order.recommendation" product_brand_ids = fields.Many2many(comodel_name="product.brand", string="Brands") def _get_products(self): """Filter products of the given brands""" products = super()._get_products() # Filter products by brand if set. # It will apply to show_all_partner_products as well if self.product_brand_ids: # We are in onchange context, so to avoid to compare records with # new_id instances we use self.product_brand_ids.ids, # self.product_brand_ids = newid but self.product_brand_ids.ids is a real id products = products.filtered( lambda x: x.product_brand_id.id in self.product_brand_ids.ids ) return products def _get_all_products_domain(self): """Filter products of the given brands""" domain = super()._get_all_products_domain() if self.product_brand_ids and not self.env.context.get("no_brands_filter"): domain += [("product_brand_id", "in", self.product_brand_ids.ids)] return domain @api.onchange( "order_id", "date_begin", "date_end", "line_amount", "show_all_partner_products", "show_all_products", "product_category_ids", "warehouse_ids", "product_brand_ids", ) def _generate_recommendations(self): """Just to add field to the onchange method""" return super()._generate_recommendations() @api.onchange("show_all_partner_products", "show_all_products") def _onchange_products(self): """Restrict available brands domain""" products = self._get_supplier_products() # Gets all products avoiding to filter them by brand again if self.show_all_products: products += ( self.with_context(no_brands_filter=True) .env["product.product"] .search(self._get_all_products_domain()) ) brands = products.mapped("product_brand_id") return {"domain": {"product_brand_ids": [("id", "in", brands.ids)]}}
39.661017
2,340
892
py
PYTHON
15.0
# Copyright 2019-22 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Purchase Blanket Orders", "category": "Purchase", "license": "AGPL-3", "author": "ForgeFlow, Odoo Community Association (OCA)", "version": "15.0.1.3.1", "website": "https://github.com/OCA/purchase-workflow", "summary": "Purchase Blanket Orders", "depends": ["purchase", "web_action_conditionable"], "data": [ "security/ir.model.access.csv", "security/security.xml", "data/sequence.xml", "data/ir_cron.xml", "wizard/create_purchase_orders.xml", "views/purchase_config_settings.xml", "views/purchase_blanket_order_views.xml", "views/purchase_order_views.xml", "report/templates.xml", "report/report.xml", ], "installable": True, }
35.68
892
9,089
py
PYTHON
15.0
# Copyright (C) 2018 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from datetime import date, timedelta from odoo import fields from odoo.exceptions import UserError from odoo.tests import common class TestPurchaseBlanketOrders(common.TransactionCase): def setUp(self): super().setUp() self.blanket_order_obj = self.env["purchase.blanket.order"] self.blanket_order_line_obj = self.env["purchase.blanket.order.line"] self.blanket_order_wiz_obj = self.env["purchase.blanket.order.wizard"] self.partner = self.env["res.partner"].create( {"name": "TEST SUPPLIER", "supplier_rank": 1} ) self.payment_term = self.env.ref("account.account_payment_term_30days") # Seller IDS seller = self.env["product.supplierinfo"].create( {"name": self.partner.id, "price": 30.0} ) self.product = self.env["product.product"].create( { "name": "Demo", "categ_id": self.env.ref("product.product_category_1").id, "standard_price": 35.0, "seller_ids": [(6, 0, [seller.id])], "type": "consu", "uom_id": self.env.ref("uom.product_uom_unit").id, "default_code": "PROD_DEL01", } ) self.product2 = self.env["product.product"].create( { "name": "Demo 2", "categ_id": self.env.ref("product.product_category_1").id, "standard_price": 50.0, "type": "consu", "uom_id": self.env.ref("uom.product_uom_unit").id, "default_code": "PROD_DEL02", } ) self.yesterday = date.today() - timedelta(days=1) self.tomorrow = date.today() + timedelta(days=1) def _get_po_from_wizard(self, res): return self.env[res["res_model"]].search(res["domain"]) def test_01_create_blanket_order_flow(self): """We create a blanket order and check constrains to confirm BO""" blanket_order = self.blanket_order_obj.create( { "partner_id": self.partner.id, "validity_date": fields.Date.to_string(self.yesterday), "payment_term_id": self.payment_term.id, "line_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom": self.product.uom_id.id, "original_uom_qty": 20.0, "price_unit": 0.0, # will be updated later }, ) ], } ) blanket_order.sudo().onchange_partner_id() blanket_order.line_ids[0].sudo().onchange_product() blanket_order._compute_line_count() blanket_order._compute_uom_qty() self.assertEqual(blanket_order.state, "draft") self.assertEqual(blanket_order.line_ids[0].price_unit, 30.0) self.assertEqual(blanket_order.original_uom_qty, 20.0) self.assertEqual(blanket_order.ordered_uom_qty, 0.0) self.assertEqual(blanket_order.remaining_uom_qty, 20.0) # date in the past with self.assertRaises(UserError): blanket_order.sudo().action_confirm() blanket_order.validity_date = fields.Date.to_string(self.tomorrow) initial_name = blanket_order.name blanket_order.sudo().action_confirm() self.assertNotEqual(initial_name, blanket_order.name) blanket_order.sudo().action_cancel() self.assertEqual(blanket_order.state, "expired") blanket_order.sudo().set_to_draft() self.assertEqual(blanket_order.state, "draft") previous_name = blanket_order.name blanket_order.sudo().action_confirm() self.assertEqual(previous_name, blanket_order.name) self.assertEqual(blanket_order.state, "open") blanket_order.action_view_purchase_blanket_order_line() # Search view check blanket_order._search_original_uom_qty(">=", 0.0) blanket_order._search_ordered_uom_qty(">=", 0.0) blanket_order._search_invoiced_uom_qty(">=", 0.0) blanket_order._search_received_uom_qty(">=", 0.0) blanket_order._search_remaining_uom_qty(">=", 0.0) def test__02_create_purchase_orders_from_blanket_order(self): """We create a blanket order and create two purchase orders""" blanket_order = self.blanket_order_obj.create( { "partner_id": self.partner.id, "partner_ref": "REF", "validity_date": fields.Date.to_string(self.tomorrow), "payment_term_id": self.payment_term.id, "line_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom": self.product.uom_id.id, "original_uom_qty": 20.0, "price_unit": 30.0, }, ) ], } ) blanket_order.sudo().onchange_partner_id() with self.assertRaises(UserError): # Blanket order is not confirmed self.blanket_order_wiz_obj.with_context( active_id=blanket_order.id, active_model="purchase.blanket.order" ).create({}) blanket_order.sudo().action_confirm() wizard1 = self.blanket_order_wiz_obj.with_context( active_id=blanket_order.id, active_model="purchase.blanket.order" ).create({}) wizard1.line_ids[0].write({"qty": 30.0}) with self.assertRaises(UserError): # Wizard quantity greater than remaining quantity wizard1.sudo().create_purchase_order() wizard1.line_ids[0].write({"qty": 10.0}) res = wizard1.sudo().create_purchase_order() po = self._get_po_from_wizard(res) self.assertEqual(po.partner_ref, "REF") wizard2 = self.blanket_order_wiz_obj.with_context( active_id=blanket_order.id, active_model="purchase.blanket.order" ).create({}) wizard2.line_ids[0].write({"qty": 10.0}) res = wizard2.sudo().create_purchase_order() po = self._get_po_from_wizard(res) self.assertEqual(po.partner_ref, "REF") with self.assertRaises(UserError): # Blanket order already completed self.blanket_order_wiz_obj.with_context( active_id=blanket_order.id, active_model="purchase.blanket.order" ).create({}) self.assertEqual(blanket_order.state, "done") self.assertEqual(blanket_order.purchase_count, 2) view_action = blanket_order.action_view_purchase_orders() domain_ids = view_action["domain"][0][2] self.assertEqual(len(domain_ids), 2) def test_03_create_purchase_orders_from_blanket_order_line(self): """We create a blanket order and create two purchase orders from the blanket order lines""" blanket_order = self.blanket_order_obj.create( { "partner_id": self.partner.id, "partner_ref": "REF", "validity_date": fields.Date.to_string(self.tomorrow), "payment_term_id": self.payment_term.id, "line_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom": self.product.uom_id.id, "original_uom_qty": 20.0, "price_unit": 30.0, }, ), ( 0, 0, { "product_id": self.product2.id, "product_uom": self.product2.uom_id.id, "original_uom_qty": 50.0, "price_unit": 60.0, }, ), ], } ) blanket_order.sudo().onchange_partner_id() blanket_order.sudo().action_confirm() bo_lines = blanket_order.line_ids self.assertEqual(blanket_order.line_count, 2) wizard1 = self.blanket_order_wiz_obj.with_context( active_ids=[bo_lines[0].id, bo_lines[1].id] ).create({}) self.assertEqual(len(wizard1.line_ids), 2) wizard1.line_ids[0].write({"qty": 10.0}) wizard1.line_ids[1].write({"qty": 20.0}) wizard1.sudo().create_purchase_order() self.assertEqual(bo_lines[0].remaining_uom_qty, 10.0) self.assertEqual(bo_lines[1].remaining_uom_qty, 30.0)
39.864035
9,089
7,730
py
PYTHON
15.0
# Copyright (C) 2018 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from datetime import date, timedelta from odoo import fields from odoo.tests import common class TestPurchaseOrder(common.TransactionCase): def setUp(self): super().setUp() self.blanket_order_obj = self.env["purchase.blanket.order"] self.blanket_order_line_obj = self.env["purchase.blanket.order.line"] self.purchase_order_obj = self.env["purchase.order"] self.purchase_order_line_obj = self.env["purchase.order.line"] self.partner = self.env["res.partner"].create( {"name": "TEST SUPPLIER", "supplier_rank": 1} ) self.payment_term = self.env.ref("account.account_payment_term_30days") # Seller IDS seller = self.env["product.supplierinfo"].create( {"name": self.partner.id, "price": 30.0} ) self.product = self.env["product.product"].create( { "name": "Demo", "categ_id": self.env.ref("product.product_category_1").id, "standard_price": 35.0, "seller_ids": [(6, 0, [seller.id])], "type": "consu", "uom_id": self.env.ref("uom.product_uom_unit").id, "default_code": "PROD_DEL01", } ) self.product_2 = self.env["product.product"].create( { "name": "Demo 2", "categ_id": self.env.ref("product.product_category_1").id, "standard_price": 35.0, "seller_ids": [(6, 0, [seller.id])], "type": "consu", "uom_id": self.env.ref("uom.product_uom_unit").id, "default_code": "PROD_DEL02", } ) self.validity = date.today() + timedelta(days=365) self.date_schedule_1 = date.today() + timedelta(days=10) self.date_schedule_2 = date.today() + timedelta(days=20) def create_blanket_order_01(self): blanket_order = self.blanket_order_obj.create( { "partner_id": self.partner.id, "validity_date": fields.Date.to_string(self.validity), "payment_term_id": self.payment_term.id, "line_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom": self.product.uom_id.id, "date_schedule": fields.Date.to_string( self.date_schedule_1 ), "original_uom_qty": 20.0, "price_unit": 30.0, }, ), ( 0, 0, { "product_id": self.product.id, "product_uom": self.product.uom_id.id, "date_schedule": fields.Date.to_string( self.date_schedule_2 ), "original_uom_qty": 20.0, "price_unit": 30.0, }, ), ], } ) blanket_order.sudo().onchange_partner_id() return blanket_order def create_blanket_order_02(self): blanket_order = self.blanket_order_obj.create( { "partner_id": self.partner.id, "validity_date": fields.Date.to_string(self.validity), "payment_term_id": self.payment_term.id, "line_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom": self.product.uom_id.id, "original_uom_qty": 20.0, "price_unit": 30.0, }, ), ( 0, 0, { "product_id": self.product_2.id, "product_uom": self.product.uom_id.id, "original_uom_qty": 20.0, "price_unit": 30.0, }, ), ], } ) blanket_order.sudo().onchange_partner_id() return blanket_order def test_01_create_purchase_order(self): blanket_order = self.create_blanket_order_01() blanket_order.sudo().action_confirm() bo_lines = self.blanket_order_line_obj.search( [("order_id", "=", blanket_order.id)] ) self.assertEqual(len(bo_lines), 2) po = self.purchase_order_obj.create( { "partner_id": self.partner.id, "order_line": [ ( 0, 0, { "name": self.product.name, "product_id": self.product.id, "product_qty": 5.0, "product_uom": self.product.uom_po_id.id, "date_planned": date.today(), "price_unit": 10.0, }, ) ], } ) po_line = po.order_line[0] po_line.with_context(from_purchase_order=True).name_get() po_line.onchange_product_id() self.assertEqual(po_line._get_eligible_bo_lines(), bo_lines) bo_line_assigned = self.blanket_order_line_obj.search( [("date_schedule", "=", fields.Date.to_string(self.date_schedule_1))] ) self.assertEqual(po_line.blanket_order_line, bo_line_assigned) def test_02_create_purchase_order(self): blanket_order = self.create_blanket_order_02() blanket_order.sudo().action_confirm() bo_lines = self.blanket_order_line_obj.search( [("order_id", "=", blanket_order.id)] ) self.assertEqual(len(bo_lines), 2) po = self.purchase_order_obj.create( { "partner_id": self.partner.id, "order_line": [ ( 0, 0, { "name": self.product.name, "product_id": self.product.id, "product_qty": 5.0, "product_uom": self.product.uom_po_id.id, "date_planned": date.today(), "price_unit": 10.0, }, ) ], } ) po_line = po.order_line[0] po_line.with_context(from_purchase_order=True).name_get() po_line.onchange_product_id() self.assertEqual( po_line._get_eligible_bo_lines(), bo_lines.filtered(lambda l: l.product_id == self.product), ) bo_line_assigned = self.blanket_order_line_obj.search( [ ("order_id", "=", blanket_order.id), ("product_id", "=", self.product.id), ("date_schedule", "=", False), ] ) self.assertEqual(po_line.blanket_order_line, bo_line_assigned)
38.267327
7,730
8,049
py
PYTHON
15.0
# Copyright (C) 2018 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from collections import defaultdict from odoo import _, api, fields, models from odoo.exceptions import UserError from odoo.tools import float_is_zero class BlanketOrderWizard(models.TransientModel): _name = "purchase.blanket.order.wizard" _description = "Blanket Order Wizard" @api.model def _default_order(self): # in case the cron hasn't run active_model = self.env.context.get("active_model", False) self.env["purchase.blanket.order"].expire_orders() if ( not self.env.context.get("active_id") or active_model != "purchase.blanket.order" ): return False blanket_order = self.env["purchase.blanket.order"].search( [("id", "=", self.env.context["active_id"])], limit=1 ) if blanket_order.state == "expired": raise UserError( _("You can't create a purchase order from an expired blanket order!") ) return blanket_order @api.model def _check_valid_blanket_order_line(self, bo_lines): precision = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) company_id = False if float_is_zero( sum(bo_lines.mapped("remaining_uom_qty")), precision_digits=precision ): raise UserError(_("All lines have already been completed.")) for line in bo_lines: if line.order_id.state != "open": raise UserError( _("Purchase Blanket Order %s is not open") % line.order_id.name ) line_company_id = line.company_id and line.company_id.id or False if company_id is not False and line_company_id != company_id: raise UserError(_("You have to select lines from the same company.")) else: company_id = line_company_id @api.model def _default_lines(self): blanket_order_line_obj = self.env["purchase.blanket.order.line"] blanket_order_line_ids = self.env.context.get("active_ids", False) active_model = self.env.context.get("active_model", False) if active_model == "purchase.blanket.order": bo_lines = self._default_order().line_ids else: bo_lines = blanket_order_line_obj.browse(blanket_order_line_ids) self._check_valid_blanket_order_line(bo_lines) lines = [ ( 0, 0, { "blanket_line_id": line.id, "product_id": line.product_id.id, "date_schedule": line.date_schedule, "remaining_uom_qty": line.remaining_uom_qty, "price_unit": line.price_unit, "product_uom": line.product_uom, "qty": line.remaining_uom_qty, "partner_id": line.partner_id, }, ) for line in bo_lines if line.remaining_uom_qty > 0 ] return lines blanket_order_id = fields.Many2one( "purchase.blanket.order", readonly=True, default=_default_order ) purchase_order_id = fields.Many2one( "purchase.order", string="Purchase Order", domain=[("state", "=", "draft")], ) line_ids = fields.One2many( "purchase.blanket.order.wizard.line", "wizard_id", string="Lines", default=_default_lines, ) def create_purchase_order(self): order_lines_by_supplier = defaultdict(list) currency_id = 0 payment_term_id = 0 for line in self.line_ids: if line.qty == 0.0: continue if line.qty > line.remaining_uom_qty: raise UserError(_("You can't order more than the remaining quantities")) date_planned = line.blanket_line_id.date_schedule vals = { "product_id": line.product_id.id, "name": line.product_id.name, "date_planned": date_planned if date_planned else line.blanket_line_id.order_id.date_start, "product_uom": line.product_uom.id, "sequence": line.blanket_line_id.sequence, "price_unit": line.blanket_line_id.price_unit, "blanket_order_line": line.blanket_line_id.id, "product_qty": line.qty, "taxes_id": [(6, 0, line.taxes_id.ids)], } order_lines_by_supplier[line.partner_id.id].append((0, 0, vals)) if currency_id == 0: currency_id = line.blanket_line_id.order_id.currency_id.id elif currency_id != line.blanket_line_id.order_id.currency_id.id: currency_id = False if payment_term_id == 0: payment_term_id = line.blanket_line_id.payment_term_id.id elif payment_term_id != line.blanket_line_id.payment_term_id.id: payment_term_id = False if not order_lines_by_supplier: raise UserError(_("An order can't be empty")) if not currency_id: raise UserError( _( "Can not create Purchase Order from Blanket " "Order lines with different currencies" ) ) res = [] for supplier in order_lines_by_supplier: order_vals = { "partner_id": int(supplier), } if self.blanket_order_id: order_vals.update( { "partner_ref": self.blanket_order_id.partner_ref, "origin": self.blanket_order_id.name, } ) order_vals.update( { "currency_id": currency_id if currency_id else False, "payment_term_id": (payment_term_id if payment_term_id else False), "order_line": order_lines_by_supplier[supplier], } ) purchase_order = self.env["purchase.order"].create(order_vals) res.append(purchase_order.id) return { "domain": [("id", "in", res)], "name": _("RFQ"), "view_mode": "tree,form", "res_model": "purchase.order", "view_id": False, "context": {"from_purchase_order": True}, "type": "ir.actions.act_window", } class BlanketOrderWizardLine(models.TransientModel): _name = "purchase.blanket.order.wizard.line" _description = "Purchase Blanket Order Wizard Line" wizard_id = fields.Many2one("purchase.blanket.order.wizard") blanket_line_id = fields.Many2one("purchase.blanket.order.line") product_id = fields.Many2one( "product.product", related="blanket_line_id.product_id", string="Product", readonly=True, ) product_uom = fields.Many2one( "uom.uom", related="blanket_line_id.product_uom", string="Unit of Measure", readonly=True, ) date_schedule = fields.Date(related="blanket_line_id.date_schedule", readonly=True) remaining_uom_qty = fields.Float( related="blanket_line_id.remaining_uom_qty", readonly=True ) qty = fields.Float(string="Quantity to Order", required=True) price_unit = fields.Float(related="blanket_line_id.price_unit", readonly=True) currency_id = fields.Many2one("res.currency", related="blanket_line_id.currency_id") partner_id = fields.Many2one( "res.partner", related="blanket_line_id.partner_id", string="Vendor", readonly=True, ) taxes_id = fields.Many2many( "account.tax", related="blanket_line_id.taxes_id", readonly=True )
36.420814
8,049
22,133
py
PYTHON
15.0
# Copyright (C) 2018 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from datetime import datetime from odoo import SUPERUSER_ID, _, api, fields, models from odoo.exceptions import UserError from odoo.tools import float_is_zero class BlanketOrder(models.Model): _name = "purchase.blanket.order" _inherit = ["mail.thread", "mail.activity.mixin"] _description = "Purchase Blanket Order" _order = "date_start desc, id desc" @api.model def _default_currency(self): return self.env.user.company_id.currency_id @api.model def _default_company(self): return self.env.user.company_id @api.depends("line_ids.price_total") def _compute_amount_all(self): for order in self: amount_untaxed = amount_tax = 0.0 for line in order.line_ids: amount_untaxed += line.price_subtotal amount_tax += line.price_tax order.update( { "amount_untaxed": order.currency_id.round(amount_untaxed), "amount_tax": order.currency_id.round(amount_tax), "amount_total": amount_untaxed + amount_tax, } ) name = fields.Char(default="Draft", readonly=True) partner_id = fields.Many2one( "res.partner", string="Vendor", readonly=True, tracking=True, states={"draft": [("readonly", False)]}, ) partner_ref = fields.Char(string="Vendor Reference", copy=False) line_ids = fields.One2many( "purchase.blanket.order.line", "order_id", string="Order lines", tracking=True, copy=True, ) line_count = fields.Integer( string="Purchase Blanket Order Line count", compute="_compute_line_count", readonly=True, ) product_id = fields.Many2one( "product.product", related="line_ids.product_id", string="Product", ) currency_id = fields.Many2one( "res.currency", required=True, default=lambda self: self.env.user.company_id.currency_id.id, ) payment_term_id = fields.Many2one( "account.payment.term", string="Payment Terms", readonly=True, states={"draft": [("readonly", False)]}, ) confirmed = fields.Boolean(copy=False) cancelled = fields.Boolean(copy=False) state = fields.Selection( selection=[ ("draft", "Draft"), ("open", "Open"), ("done", "Done"), ("expired", "Expired"), ], compute="_compute_state", store=True, copy=False, tracking=True, ) validity_date = fields.Date( readonly=True, states={"draft": [("readonly", False)]}, tracking=True, help="Date until which the blanket order will be valid, after this " "date the blanket order will be marked as expired", ) date_start = fields.Datetime( readonly=True, required=True, string="Start Date", default=fields.Datetime.now, states={"draft": [("readonly", False)]}, help="Blanket Order starting date.", ) note = fields.Text(readonly=True, states={"draft": [("readonly", False)]}) user_id = fields.Many2one( "res.users", string="Responsible", readonly=True, default=lambda self: self.env.uid, states={"draft": [("readonly", False)]}, ) company_id = fields.Many2one( "res.company", string="Company", default=_default_company, readonly=True, states={"draft": [("readonly", False)]}, ) purchase_count = fields.Integer(compute="_compute_purchase_count") fiscal_position_id = fields.Many2one( "account.fiscal.position", string="Fiscal Position" ) amount_untaxed = fields.Monetary( string="Untaxed Amount", store=True, readonly=True, compute="_compute_amount_all", tracking=True, ) amount_tax = fields.Monetary( string="Taxes", store=True, readonly=True, compute="_compute_amount_all" ) amount_total = fields.Monetary( string="Total", store=True, readonly=True, compute="_compute_amount_all" ) # Fields use to filter in tree view original_uom_qty = fields.Float( string="Original quantity", compute="_compute_uom_qty", search="_search_original_uom_qty", ) ordered_uom_qty = fields.Float( string="Ordered quantity", compute="_compute_uom_qty", search="_search_ordered_uom_qty", ) invoiced_uom_qty = fields.Float( string="Invoiced quantity", compute="_compute_uom_qty", search="_search_invoiced_uom_qty", ) remaining_uom_qty = fields.Float( string="Remaining quantity", compute="_compute_uom_qty", search="_search_remaining_uom_qty", ) received_uom_qty = fields.Float( string="Received quantity", compute="_compute_uom_qty", search="_search_received_uom_qty", ) def _get_purchase_orders(self): return self.mapped("line_ids.purchase_lines.order_id") @api.depends("line_ids") def _compute_line_count(self): self.line_count = len(self.mapped("line_ids")) def _compute_purchase_count(self): for blanket_order in self: blanket_order.purchase_count = len(blanket_order._get_purchase_orders()) @api.depends( "line_ids.remaining_uom_qty", "validity_date", "confirmed", "cancelled", ) def _compute_state(self): today = fields.Date.today() precision = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) for order in self: if not order.confirmed and not order.cancelled: order.state = "draft" elif order.validity_date <= today or order.cancelled: order.state = "expired" elif float_is_zero( sum(order.line_ids.mapped("remaining_uom_qty")), precision_digits=precision, ): order.state = "done" else: order.state = "open" def _compute_uom_qty(self): for bo in self: bo.original_uom_qty = sum(bo.mapped("line_ids.original_uom_qty")) bo.ordered_uom_qty = sum(bo.mapped("line_ids.ordered_uom_qty")) bo.invoiced_uom_qty = sum(bo.mapped("line_ids.invoiced_uom_qty")) bo.received_uom_qty = sum(bo.mapped("line_ids.received_uom_qty")) bo.remaining_uom_qty = sum(bo.mapped("line_ids.remaining_uom_qty")) @api.onchange("partner_id") def onchange_partner_id(self): """ Update the following fields when the partner is changed: - Payment term """ if not self.partner_id: self.payment_term_id = False self.fiscal_position_id = False return self.payment_term_id = ( self.partner_id.property_supplier_payment_term_id and self.partner_id.property_supplier_payment_term_id.id or False ) self.fiscal_position_id = ( self.env["account.fiscal.position"] .with_context(company_id=self.company_id.id) .get_fiscal_position(self.partner_id.id) ) self.currency_id = ( self.partner_id.property_purchase_currency_id.id or self.env.user.company_id.currency_id.id ) if self.partner_id.user_id: self.user_id = self.partner_id.user_id.id def unlink(self): for order in self: if order.state not in ("draft", "expired"): raise UserError( _( "You can not delete an open blanket order! " "Try to cancel it before." ) ) return super().unlink() def copy_data(self, default=None): if default is None: default = {} default.update(self.default_get(["name", "confirmed"])) return super().copy_data(default) def _validate(self): try: today = fields.Date.today() for order in self: assert order.validity_date, _("Validity date is mandatory") assert order.validity_date > today, _( "Validity date must be in the future" ) assert order.partner_id, _("Partner is mandatory") assert len(order.line_ids) > 0, _("Must have some lines") order.line_ids._validate() except AssertionError as e: raise UserError(e) from e def set_to_draft(self): for order in self: order.write({"cancelled": False}) return True def action_confirm(self): self._validate() for order in self: vals = {"confirmed": True} # Set name by sequence only if is necessary if order.name == "Draft": sequence_obj = self.env["ir.sequence"] if order.company_id: sequence_obj = sequence_obj.with_company(order.company_id) name = sequence_obj.next_by_code("purchase.blanket.order") or "Draft" vals.update({"name": name}) order.write(vals) return True def action_cancel(self): for order in self: if order.purchase_count > 0: for po in order._get_purchase_orders(): if po.state not in ("cancel"): raise UserError( _( "You can not delete a blanket order with opened " "purchase orders! " "Try to cancel them before." ) ) order.write({"cancelled": True, "confirmed": False}) return True def action_view_purchase_orders(self): purchase_orders = self._get_purchase_orders() action = self.env["ir.actions.actions"]._for_xml_id("purchase.purchase_rfq") if len(purchase_orders) > 0: action["domain"] = [("id", "in", purchase_orders.ids)] action["context"] = [("id", "in", purchase_orders.ids)] else: action = {"type": "ir.actions.act_window_close"} return action def action_view_purchase_blanket_order_line(self): action = self.env["ir.actions.actions"]._for_xml_id( "purchase_blanket_order.act_open_purchase_blanket_order_lines_view_tree" ) lines = self.mapped("line_ids") if len(lines) > 0: action["domain"] = [("id", "in", lines.ids)] return action @api.model def expire_orders(self): today = fields.Date.today() expired_orders = self.search( [("state", "=", "open"), ("validity_date", "<=", today)] ) expired_orders.modified(["validity_date"]) expired_orders.recompute() @api.model def _search_original_uom_qty(self, operator, value): bo_line_obj = self.env["purchase.blanket.order.line"] res = [] bo_lines = bo_line_obj.search([("original_uom_qty", operator, value)]) order_ids = bo_lines.mapped("order_id") res.append(("id", "in", order_ids.ids)) return res @api.model def _search_ordered_uom_qty(self, operator, value): bo_line_obj = self.env["purchase.blanket.order.line"] res = [] bo_lines = bo_line_obj.search([("ordered_uom_qty", operator, value)]) order_ids = bo_lines.mapped("order_id") res.append(("id", "in", order_ids.ids)) return res @api.model def _search_invoiced_uom_qty(self, operator, value): bo_line_obj = self.env["purchase.blanket.order.line"] res = [] bo_lines = bo_line_obj.search([("invoiced_uom_qty", operator, value)]) order_ids = bo_lines.mapped("order_id") res.append(("id", "in", order_ids.ids)) return res @api.model def _search_received_uom_qty(self, operator, value): bo_line_obj = self.env["purchase.blanket.order.line"] res = [] bo_lines = bo_line_obj.search([("received_uom_qty", operator, value)]) order_ids = bo_lines.mapped("order_id") res.append(("id", "in", order_ids.ids)) return res @api.model def _search_remaining_uom_qty(self, operator, value): bo_line_obj = self.env["purchase.blanket.order.line"] res = [] bo_lines = bo_line_obj.search([("remaining_uom_qty", operator, value)]) order_ids = bo_lines.mapped("order_id") res.append(("id", "in", order_ids.ids)) return res class BlanketOrderLine(models.Model): _name = "purchase.blanket.order.line" _description = "Purchase Blanket Order Line" _inherit = ["mail.thread", "mail.activity.mixin"] @api.depends("original_uom_qty", "price_unit", "taxes_id") def _compute_amount(self): for line in self: taxes = line.taxes_id.compute_all( line.price_unit, line.order_id.currency_id, line.original_uom_qty, product=line.product_id, partner=line.order_id.partner_id, ) line.update( { "price_tax": sum( t.get("amount", 0.0) for t in taxes.get("taxes", []) ), "price_total": taxes["total_included"], "price_subtotal": taxes["total_excluded"], } ) name = fields.Char(string="Description", tracking=True) sequence = fields.Integer() order_id = fields.Many2one( "purchase.blanket.order", required=True, ondelete="cascade" ) product_id = fields.Many2one( "product.product", string="Product", required=True, domain=[("purchase_ok", "=", True)], ) product_uom = fields.Many2one("uom.uom", string="Unit of Measure", required=True) price_unit = fields.Float(string="Price", required=True, digits=("Product Price")) taxes_id = fields.Many2many( "account.tax", string="Taxes", domain=["|", ("active", "=", False), ("active", "=", True)], ) date_schedule = fields.Date(string="Scheduled Date") original_uom_qty = fields.Float( string="Original quantity", required=True, default=1.0, digits=("Product Unit of Measure"), ) ordered_uom_qty = fields.Float( string="Ordered quantity", compute="_compute_quantities", store=True, digits=("Product Unit of Measure"), ) invoiced_uom_qty = fields.Float( string="Invoiced quantity", compute="_compute_quantities", store=True, digits=("Product Unit of Measure"), ) remaining_uom_qty = fields.Float( string="Remaining quantity", compute="_compute_quantities", store=True, digits=("Product Unit of Measure"), ) remaining_qty = fields.Float( string="Remaining quantity in base UoM", compute="_compute_quantities", store=True, digits=("Product Unit of Measure"), ) received_uom_qty = fields.Float( string="Received quantity", compute="_compute_quantities", store=True, digits=("Product Unit of Measure"), ) purchase_lines = fields.One2many( comodel_name="purchase.order.line", inverse_name="blanket_order_line", string="Purchase Order Lines", readonly=True, copy=False, ) company_id = fields.Many2one( "res.company", related="order_id.company_id", store=True, readonly=True ) currency_id = fields.Many2one( "res.currency", related="order_id.currency_id", readonly=True ) partner_id = fields.Many2one( related="order_id.partner_id", string="Vendor", readonly=True ) user_id = fields.Many2one( related="order_id.user_id", string="Responsible", readonly=True ) payment_term_id = fields.Many2one( related="order_id.payment_term_id", string="Payment Terms", readonly=True ) price_subtotal = fields.Monetary( compute="_compute_amount", string="Subtotal", store=True ) price_total = fields.Monetary(compute="_compute_amount", string="Total", store=True) price_tax = fields.Float(compute="_compute_amount", string="Tax", store=True) def _format_date(self, date): # format date following user language lang_model = self.env["res.lang"] lang = lang_model._lang_get(self.env.user.lang) date_format = lang.date_format return datetime.strftime(fields.Date.from_string(date), date_format) def name_get(self): result = [] if self.env.context.get("from_purchase_order"): for record in self: res = "[%s]" % record.order_id.name if record.date_schedule: formatted_date = self._format_date(record.date_schedule) res += " - {}: {}".format(_("Date Scheduled"), formatted_date) res += " ({}: {} {})".format( _("remaining"), record.remaining_uom_qty, record.product_uom.name, ) result.append((record.id, res)) return result return super().name_get() def _get_display_price(self, product): seller = product._select_seller( partner_id=self.order_id.partner_id, quantity=self.original_uom_qty, date=self.order_id.date_start and fields.Date.from_string(self.order_id.date_start), uom_id=self.product_uom, ) if not seller: return price_unit = ( self.env["account.tax"]._fix_tax_included_price_company( seller.price, product.supplier_taxes_id, self.purchase_lines.taxes_id, self.company_id, ) if seller else 0.0 ) if ( price_unit and seller and self.order_id.currency_id and seller.currency_id != self.order_id.currency_id ): price_unit = seller.currency_id.compute( price_unit, self.order_id.currency_id ) if seller and self.product_uom and seller.product_uom != self.product_uom: price_unit = seller.product_uom._compute_price(price_unit, self.product_uom) return price_unit @api.onchange("product_id", "original_uom_qty") def onchange_product(self): precision = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) if self.product_id: name = self.product_id.name if not self.product_uom: self.product_uom = self.product_id.uom_po_id or self.product_id.uom_id if self.order_id.partner_id and float_is_zero( self.price_unit, precision_digits=precision ): self.price_unit = self._get_display_price(self.product_id) if self.product_id.code: name = "[{}] {}".format(name, self.product_id.code) if self.product_id.description_purchase: name += "\n" + self.product_id.description_purchase self.name = name fpos = self.order_id.fiscal_position_id if self.env.uid == SUPERUSER_ID: company_id = self.env.user.company_id.id self.taxes_id = fpos.map_tax( self.product_id.supplier_taxes_id.filtered( lambda r: r.company_id.id == company_id ) ) else: self.taxes_id = fpos.map_tax(self.product_id.supplier_taxes_id) @api.depends( "purchase_lines.order_id.state", "purchase_lines.blanket_order_line", "purchase_lines.product_qty", "purchase_lines.product_uom", "purchase_lines.qty_received", "purchase_lines.qty_invoiced", "original_uom_qty", "product_uom", ) def _compute_quantities(self): for line in self: purchase_lines = line.purchase_lines line.ordered_uom_qty = sum( pol.product_uom._compute_quantity(pol.product_qty, line.product_uom) for pol in purchase_lines if pol.order_id.state != "cancel" and pol.product_id == line.product_id ) line.invoiced_uom_qty = sum( pol.product_uom._compute_quantity(pol.qty_invoiced, line.product_uom) for pol in purchase_lines if pol.order_id.state != "cancel" and pol.product_id == line.product_id ) line.received_uom_qty = sum( pol.product_uom._compute_quantity(pol.qty_received, line.product_uom) for pol in purchase_lines if pol.order_id.state != "cancel" and pol.product_id == line.product_id ) line.remaining_uom_qty = line.original_uom_qty - line.ordered_uom_qty line.remaining_qty = line.product_uom._compute_quantity( line.remaining_uom_qty, line.product_id.uom_id ) def _validate(self): try: for line in self: assert line.price_unit > 0.0, _("Price must be greater than zero") assert line.original_uom_qty > 0.0, _( "Quantity must be greater than zero" ) except AssertionError as e: raise UserError(e) from e
35.583601
22,133
481
py
PYTHON
15.0
# Copyright (C) 2018 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class PurchaseConfigSettings(models.TransientModel): _inherit = "res.config.settings" group_purchase_blanket_disable_adding_lines = fields.Boolean( string="Disable adding more lines to SOs", implied_group="purchase_blanket_order." "purchase_blanket_orders_disable_adding_lines", )
34.357143
481
6,904
py
PYTHON
15.0
# Copyright (C) 2018 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from datetime import date, timedelta from odoo import _, api, fields, models from odoo.exceptions import ValidationError class PurchaseOrder(models.Model): _inherit = "purchase.order" blanket_order_id = fields.Many2one( "purchase.blanket.order", string="Origin blanket order", related="order_line.blanket_order_line.order_id", readonly=True, ) @api.model def _check_exchausted_blanket_order_line(self): return any( line.blanket_order_line.remaining_qty < 0.0 for line in self.order_line ) def button_confirm(self): res = super().button_confirm() for order in self: if order._check_exchausted_blanket_order_line(): raise ValidationError( _( "Cannot confirm order %s as one of the lines refers " "to a blanket order that has no remaining quantity." ) % order.name ) return res @api.constrains("partner_id") def check_partner_id(self): for line in self.order_line: if line.blanket_order_line: if line.blanket_order_line.partner_id != self.partner_id: raise ValidationError( _( "The vendor must be equal to the blanket order" " lines vendor" ) ) @api.constrains("currency_id") def check_currency(self): for rec in self: if any( line.blanket_order_line.order_id.currency_id != rec.currency_id for line in rec.order_line.filtered(lambda x: x.blanket_order_line) ): raise ValidationError( _( "The currency of the blanket order must match with that " "of the purchase order." ) ) class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" blanket_order_line = fields.Many2one( comodel_name="purchase.blanket.order.line", copy=False ) def _get_assigned_bo_line(self, bo_lines): # We get the blanket order line with enough quantity and closest # scheduled date assigned_bo_line = False date_planned = fields.Date.from_string(self.date_planned) or date.today() date_delta = timedelta(days=365) for line in bo_lines.filtered(lambda l: l.date_schedule): date_schedule = fields.Date.from_string(line.date_schedule) if date_schedule and abs(date_schedule - date_planned) < date_delta: assigned_bo_line = line date_delta = abs(date_schedule - date_planned) if assigned_bo_line: return assigned_bo_line non_date_bo_lines = bo_lines.filtered(lambda l: not l.date_schedule) if non_date_bo_lines: return non_date_bo_lines[0] def _get_eligible_bo_lines_domain(self, base_qty): filters = [ ("product_id", "=", self.product_id.id), ("remaining_qty", ">=", base_qty), ("currency_id", "=", self.order_id.currency_id.id), ("order_id.state", "=", "open"), ] if self.order_id.partner_id: filters.append(("partner_id", "=", self.order_id.partner_id.id)) return filters def _get_eligible_bo_lines(self): base_qty = self.product_uom._compute_quantity( self.product_qty, self.product_id.uom_id ) filters = self._get_eligible_bo_lines_domain(base_qty) return self.env["purchase.blanket.order.line"].search(filters) def get_assigned_bo_line(self): self.ensure_one() eligible_bo_lines = self._get_eligible_bo_lines() if eligible_bo_lines: if ( not self.blanket_order_line or self.blanket_order_line not in eligible_bo_lines ): self.blanket_order_line = self._get_assigned_bo_line(eligible_bo_lines) else: self.blanket_order_line = False self.onchange_blanket_order_line() return {"domain": {"blanket_order_line": [("id", "in", eligible_bo_lines.ids)]}} @api.onchange("product_id", "partner_id") def onchange_product_id(self): res = super().onchange_product_id() # If product has changed remove the relation with blanket order line if self.product_id: return self.get_assigned_bo_line() return res @api.onchange("product_qty", "product_uom") def _onchange_quantity(self): res = super()._onchange_quantity() if self.product_id and not self.env.context.get("skip_blanket_find", False): return self.get_assigned_bo_line() return res @api.onchange("blanket_order_line") def onchange_blanket_order_line(self): bol = self.blanket_order_line if bol: self.product_id = bol.product_id if bol.date_schedule: self.date_planned = bol.date_schedule if bol.product_uom != self.product_uom: price_unit = bol.product_uom._compute_price( bol.price_unit, self.product_uom ) else: price_unit = bol.price_unit self.price_unit = price_unit if bol.taxes_id: self.taxes_id = bol.taxes_id else: self._compute_tax_id() self.with_context(skip_blanket_find=True)._onchange_quantity() @api.constrains("date_planned") def check_date_planned(self): for line in self: date_planned = fields.Date.from_string(line.date_planned) if ( line.blanket_order_line and line.blanket_order_line.date_schedule and line.blanket_order_line.date_schedule != date_planned ): raise ValidationError( _( "Schedule dates defined on the Purchase Order Line " "and on the Blanket Order Line do not match." ) ) @api.constrains("currency_id") def check_currency(self): for line in self: blanket_currency = line.blanket_order_line.order_id.currency_id if blanket_currency and line.order_id.currency_id != blanket_currency: raise ValidationError( _( "The currency of the blanket order must match with that " "of the purchase order." ) )
37.934066
6,904
695
py
PYTHON
15.0
# Copyright 2015 Camptocamp SA # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Purchase Order Type", "version": "15.0.1.0.0", "author": "Camptocamp, Odoo Community Association (OCA)", "license": "AGPL-3", "category": "Purchase Management", "depends": ["purchase"], "website": "https://github.com/OCA/purchase-workflow", "data": [ "security/ir.model.access.csv", "security/security.xml", "views/view_purchase_order_type.xml", "views/view_purchase_order.xml", "views/res_partner_view.xml", "data/purchase_order_type.xml", ], "installable": True, "auto_install": False, }
31.590909
695
3,487
py
PYTHON
15.0
# Copyright 2019 Oihane Crucelaegui - AvanzOSC # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import time from odoo.exceptions import ValidationError from odoo.tests import common, tagged from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT @tagged("post_install", "-at_install") class TestPurchaseOrderType(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.po_obj = cls.env["purchase.order"] cls.company_obj = cls.env["res.company"] # Partner cls.partner1 = cls.env.ref("base.res_partner_1") # Products cls.product1 = cls.env.ref("product.product_product_7") cls.product2 = cls.env.ref("product.product_product_9") cls.product3 = cls.env.ref("product.product_product_11") # Purchase Type cls.type1 = cls.env.ref("purchase_order_type.po_type_regular") cls.type2 = cls.env.ref("purchase_order_type.po_type_planned") # Payment Term cls.payterm = cls.env.ref("account.account_payment_term_immediate") # Incoterm cls.incoterm = cls.env.ref("account.incoterm_EXW") cls.type2.payment_term_id = cls.payterm cls.type2.incoterm_id = cls.incoterm cls.partner1.purchase_type = cls.type2 cls.company2 = cls.company_obj.create({"name": "company2"}) def test_purchase_order_type(self): purchase = self._create_purchase( [(self.product1, 1), (self.product2, 5), (self.product3, 8)] ) self.assertEqual(purchase.order_type, self.type1) self.assertFalse(purchase.incoterm_id) self.assertFalse(purchase.payment_term_id) purchase.onchange_partner_id() self.assertEqual(purchase.order_type, self.type2) purchase.onchange_order_type() self.assertEqual(purchase.incoterm_id, self.incoterm) self.assertEqual(purchase.payment_term_id, self.payterm) def _create_purchase(self, line_products): """Create a purchase order. ``line_products`` is a list of tuple [(product, qty)] """ lines = [] for product, qty in line_products: line_values = { "name": product.name, "product_id": product.id, "product_qty": qty, "product_uom": product.uom_id.id, "price_unit": 100, "date_planned": time.strftime(DEFAULT_SERVER_DATETIME_FORMAT), } lines.append((0, 0, line_values)) purchase = self.po_obj.create( { "partner_id": self.partner1.id, "order_type": self.type1.id, "order_line": lines, } ) return purchase def test_purchase_order_change_company(self): order = self.po_obj.new({"partner_id": self.partner1.id}) order.onchange_partner_id() self.assertEqual(order.order_type, self.type2) order._onchange_company() self.assertEqual(order.order_type, order._default_order_type()) def test_purchase_order_type_company_error(self): order = self.po_obj.create( {"partner_id": self.partner1.id, "order_type": self.type1.id} ) self.assertEqual(order.order_type, self.type1) self.assertEqual(order.company_id, self.type1.company_id) with self.assertRaises(ValidationError): order.write({"company_id": self.company2.id})
40.08046
3,487
2,255
py
PYTHON
15.0
# Copyright 2015 Camptocamp SA # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.exceptions import ValidationError from odoo.addons.purchase.models.purchase import PurchaseOrder as Purchase class PurchaseOrder(models.Model): _inherit = "purchase.order" order_type = fields.Many2one( comodel_name="purchase.order.type", readonly=False, states=Purchase.READONLY_STATES, string="Type", ondelete="restrict", domain="[('company_id', 'in', [False, company_id])]", ) @api.onchange("partner_id") def onchange_partner_id(self): res = super().onchange_partner_id() purchase_type = ( self.partner_id.purchase_type or self.partner_id.commercial_partner_id.purchase_type ) if purchase_type: self.order_type = purchase_type return res @api.onchange("order_type") def onchange_order_type(self): for order in self: if order.order_type.payment_term_id: order.payment_term_id = order.order_type.payment_term_id.id if order.order_type.incoterm_id: order.incoterm_id = order.order_type.incoterm_id.id @api.model def create(self, vals): if vals.get("name", "/") == "/" and vals.get("order_type"): purchase_type = self.env["purchase.order.type"].browse(vals["order_type"]) if purchase_type.sequence_id: vals["name"] = purchase_type.sequence_id.next_by_id() return super().create(vals) @api.constrains("company_id") def _check_po_type_company(self): if self.filtered( lambda r: r.order_type.company_id and r.company_id and r.order_type.company_id != r.company_id ): raise ValidationError(_("Document's company and type's company mismatch")) def _default_order_type(self): return self.env["purchase.order.type"].search( [("company_id", "in", [False, self.company_id.id])], limit=1, ) @api.onchange("company_id") def _onchange_company(self): self.order_type = self._default_order_type()
34.166667
2,255
1,468
py
PYTHON
15.0
# Copyright (C) 2015 Camptocamp SA # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class PurchaseOrderType(models.Model): _name = "purchase.order.type" _description = "Type of purchase order" _order = "sequence" @api.model def _get_domain_sequence_id(self): seq_type = self.env.ref("purchase.seq_purchase_order") return [ ("code", "=", seq_type.code), ("company_id", "in", [False, self.env.company.id]), ] @api.model def _default_sequence_id(self): seq_type = self.env.ref("purchase.seq_purchase_order") return seq_type.id name = fields.Char(required=True) active = fields.Boolean(default=True) description = fields.Text(translate=True) sequence_id = fields.Many2one( comodel_name="ir.sequence", string="Entry Sequence", copy=False, domain=lambda self: self._get_domain_sequence_id(), default=lambda self: self._default_sequence_id(), required=True, ) payment_term_id = fields.Many2one( comodel_name="account.payment.term", string="Payment Terms" ) incoterm_id = fields.Many2one(comodel_name="account.incoterms", string="Incoterm") sequence = fields.Integer(default=10) company_id = fields.Many2one( comodel_name="res.company", string="Company", default=lambda self: self.env.company, )
32.622222
1,468
314
py
PYTHON
15.0
# Copyright 2015 Camptocamp SA # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ResPartner(models.Model): _inherit = "res.partner" purchase_type = fields.Many2one( comodel_name="purchase.order.type", string="Purchase Order Type" )
26.166667
314
1,272
py
PYTHON
15.0
# Copyright 2018-2019 ForgeFlow, S.L. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl-3.0). { "name": "Purchase Request", "author": "ForgeFlow, Odoo Community Association (OCA)", "version": "15.0.1.1.1", "summary": "Use this module to have notification of requirements of " "materials and/or external services and keep track of such " "requirements.", "website": "https://github.com/OCA/purchase-workflow", "category": "Purchase Management", "depends": ["purchase", "product", "purchase_stock"], "data": [ "security/purchase_request.xml", "security/ir.model.access.csv", "data/purchase_request_sequence.xml", "data/purchase_request_data.xml", "reports/report_purchase_request.xml", "wizard/purchase_request_line_make_purchase_order_view.xml", "views/purchase_request_view.xml", "views/purchase_request_line_view.xml", "views/purchase_request_report.xml", "views/product_template.xml", "views/purchase_order_view.xml", "views/stock_move_views.xml", "views/stock_picking_views.xml", ], "demo": ["demo/purchase_request_demo.xml"], "license": "LGPL-3", "installable": True, "application": True, }
38.545455
1,272
16,799
py
PYTHON
15.0
# Copyright 2018-2019 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl-3.0) from odoo import SUPERUSER_ID from odoo.tests import common class TestPurchaseRequestToRfq(common.TransactionCase): def setUp(self): super(TestPurchaseRequestToRfq, self).setUp() self.purchase_request_obj = self.env["purchase.request"] self.purchase_request_line_obj = self.env["purchase.request.line"] self.wiz = self.env["purchase.request.line.make.purchase.order"] self.purchase_order = self.env["purchase.order"] vendor = self.env["res.partner"].create({"name": "Partner #2"}) self.service_product = self.env["product.product"].create( {"name": "Product Service Test", "type": "service"} ) self.env["product.supplierinfo"].create( { "name": vendor.id, "product_tmpl_id": self.service_product.product_tmpl_id.id, } ) self.product_product = self.env["product.product"].create( { "name": "Product Product Test", "type": "product", "description_purchase": "Test Description", } ) def test_wizard_default_get(self): # Check that correct create items by purchase.request vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, "line_ids": [ [ 0, 0, { "product_id": self.env.ref("product.product_product_13").id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 2.0, }, ] ], } purchase_request1 = self.purchase_request_obj.create(vals) purchase_request1.button_approved() vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, "line_ids": [ [ 0, 0, { "product_id": self.env.ref("product.product_product_13").id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 2.0, }, ] ], } purchase_request2 = self.purchase_request_obj.create(vals) purchase_request2.button_approved() vals = {"supplier_id": self.env.ref("base.res_partner_1").id} wiz_id = self.wiz.with_context( active_model="purchase.request.line", active_ids=[ purchase_request1.mapped("line_ids").id, purchase_request2.mapped("line_ids").id, ], ).create(vals) self.assertEqual( (purchase_request1 | purchase_request2).mapped("line_ids"), wiz_id.item_ids.mapped("line_id"), "Should have same purchase request lines", ) def test_purchase_request_to_purchase_rfq(self): vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, } purchase_request = self.purchase_request_obj.create(vals) vals = { "request_id": purchase_request.id, "product_id": self.env.ref("product.product_product_13").id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 5.0, } purchase_request_line = self.purchase_request_line_obj.create(vals) purchase_request.button_to_approve() purchase_request.button_approved() vals = {"supplier_id": self.env.ref("base.res_partner_12").id} wiz_id = self.wiz.with_context( active_model="purchase.request.line", active_ids=[purchase_request_line.id], active_id=purchase_request_line.id, ).create(vals) wiz_id.make_purchase_order() self.assertTrue( len(purchase_request_line.purchase_lines), "Should have a purchase line" ) self.assertEqual( purchase_request_line.purchase_lines.product_id.id, purchase_request_line.product_id.id, "Should have same product", ) self.assertEqual( purchase_request_line.purchase_lines.state, purchase_request_line.purchase_state, "Should have same state", ) def test_bug_is_editable_multiple_lines(self): # Check that reading multiple lines is still possible # https://github.com/OCA/purchase-workflow/pull/291 vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, } purchase_request = self.purchase_request_obj.create(vals) vals = { "request_id": purchase_request.id, "product_id": self.env.ref("product.product_product_13").id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 5.0, } purchase_request_line = self.purchase_request_line_obj.create(vals) request_lines = purchase_request_line + purchase_request_line.copy() request_lines.mapped("is_editable") # Test also for onchanges on non created lines self.purchase_request_line_obj.new({}).is_editable def test_purchase_request_to_purchase_rfq_minimum_order_qty(self): vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, } purchase_request = self.purchase_request_obj.create(vals) vals = { "request_id": purchase_request.id, "product_id": self.env.ref("product.product_product_8").id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 1.0, } purchase_request_line = self.purchase_request_line_obj.create(vals) vals = {"supplier_id": self.env.ref("base.res_partner_1").id} purchase_request.button_approved() wiz_id = self.wiz.with_context( active_model="purchase.request.line", active_ids=[purchase_request_line.id], active_id=purchase_request_line.id, ).create(vals) wiz_id.make_purchase_order() self.assertTrue( len(purchase_request_line.purchase_lines), "Should have a purchase line" ) self.assertEqual( purchase_request_line.purchase_lines.product_id.id, purchase_request_line.product_id.id, "Should have same product", ) self.assertEqual( purchase_request_line.purchase_lines.state, purchase_request_line.purchase_state, "Should have same state", ) self.assertEqual( purchase_request_line.purchase_lines.product_qty, 5, "The PO line should have the minimum order quantity.", ) self.assertEqual( purchase_request_line, purchase_request_line.purchase_lines.purchase_request_lines, "The PO should cross-reference to the purchase request.", ) def test_purchase_request_to_purchase_rfq_multiple_po(self): vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, } purchase_request1 = self.purchase_request_obj.create(vals) vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, } purchase_request2 = self.purchase_request_obj.create(vals) vals = { "request_id": purchase_request1.id, "product_id": self.env.ref("product.product_product_6").id, "product_uom_id": self.env.ref("uom.product_uom_dozen").id, "product_qty": 1.0, } purchase_request_line1 = self.purchase_request_line_obj.create(vals) vals = { "request_id": purchase_request2.id, "product_id": self.env.ref("product.product_product_6").id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 1.0, } purchase_request_line2 = self.purchase_request_line_obj.create(vals) vals = { "request_id": purchase_request2.id, "product_id": self.product_product.id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 1.0, } purchase_request_line3 = self.purchase_request_line_obj.create(vals) vals = {"supplier_id": self.env.ref("base.res_partner_1").id} purchase_request1.button_approved() purchase_request2.button_approved() wiz_id = self.wiz.with_context( active_model="purchase.request.line", active_ids=[ purchase_request_line1.id, purchase_request_line2.id, purchase_request_line3.id, ], ).create(vals) for item in wiz_id.item_ids: if item.line_id.id == purchase_request_line2.id: item.keep_description = True if item.line_id.id == purchase_request_line3.id: item.onchange_product_id() wiz_id.make_purchase_order() self.assertEqual( purchase_request_line1.purchased_qty, 1.0, "Should be a quantity of 1" ) self.assertEqual( purchase_request_line2.purchased_qty, 1.0, "Should be a quantity of 1" ) def test_purchase_request_to_purchase_rfq_multiple_PO_purchaseUoM(self): product = self.env.ref("product.product_product_6") product.uom_po_id = self.env.ref("uom.product_uom_dozen") vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, } purchase_request1 = self.purchase_request_obj.create(vals) vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, } purchase_request2 = self.purchase_request_obj.create(vals) vals = { "request_id": purchase_request1.id, "product_id": product.id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 12.0, } purchase_request_line1 = self.purchase_request_line_obj.create(vals) vals = { "request_id": purchase_request2.id, "product_id": product.id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 12.0, } purchase_request_line2 = self.purchase_request_line_obj.create(vals) vals = { "request_id": purchase_request2.id, "product_id": product.id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 1.0, } purchase_request_line3 = self.purchase_request_line_obj.create(vals) vals = {"supplier_id": self.env.ref("base.res_partner_1").id} purchase_request1.button_approved() purchase_request2.button_approved() wiz_id = self.wiz.with_context( active_model="purchase.request.line", active_ids=[ purchase_request_line1.id, purchase_request_line2.id, purchase_request_line3.id, ], ).create(vals) for item in wiz_id.item_ids: if item.line_id.id == purchase_request_line2.id: # PRL will be splitted into another POL to keep description item.keep_description = True wiz_id.make_purchase_order() po_line = purchase_request_line1.purchase_lines[0] self.assertEqual(po_line.product_qty, 1.09, "Quantity should be 1.09") self.assertEqual( po_line.product_uom, self.env.ref("uom.product_uom_dozen"), "The purchase UoM should be Dozen(s).", ) def test_purchase_request_to_rfq_minimum_order_qty_existing_po(self): # Define Supplier supplier = self.env.ref("base.res_partner_1") # Create Product Widget min_qty = 5 product = self.env["product.product"].create( { "name": "Widget", "type": "product", "seller_ids": [(0, 0, {"name": supplier.id, "min_qty": 5})], } ) # Create Purchase Order with qty = 3 throw Purchase Request vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, } purchase_request1 = self.purchase_request_obj.create(vals) vals = { "request_id": purchase_request1.id, "product_id": product.id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 3.0, } purchase_request_line1 = self.purchase_request_line_obj.create(vals) purchase_request1.button_approved() vals = {"supplier_id": supplier.id} wiz_id = self.wiz.with_context( active_model="purchase.request.line", active_ids=[purchase_request_line1.id] ).create(vals) wiz_id.make_purchase_order() po = purchase_request_line1.purchase_lines[0].order_id # Create Purchase Request vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, } purchase_request2 = self.purchase_request_obj.create(vals) # Create Purchase Request Line qty = 3 vals = { "request_id": purchase_request2.id, "product_id": product.id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 3.0, } purchase_request_line2 = self.purchase_request_line_obj.create(vals) # Validate purchase_request2.button_approved() # Create RFQ to Previous PO vals = {"supplier_id": supplier.id, "purchase_order_id": po.id} wiz_id = self.wiz.with_context( active_model="purchase.request.line", active_ids=[purchase_request_line2.id] ).create(vals) wiz_id.make_purchase_order() # Check Purchase qty should be 6 po_line = purchase_request_line2.purchase_lines[0] # Add unit price in PO Line po_line.write({"price_unit": 10}) self.assertEqual(po_line.product_qty, 6.0, "Quantity should be 6") # auto change state to done po_line.order_id.button_confirm() picking = po_line.order_id.picking_ids[0] picking.move_line_ids[0].write({"qty_done": 6.0}) picking.button_validate() def test_purchase_request_to_purchase_order_analytic_data_propagation(self): analytic_tags = self.env.ref("analytic.tag_contract") analytic_account = self.env["account.analytic.account"].create( {"name": "Test analytic account"} ) vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, "line_ids": [ ( 0, 0, { "product_id": self.env.ref("product.product_product_10").id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 5.0, "analytic_account_id": analytic_account.id, "analytic_tag_ids": [(6, 0, analytic_tags.ids)], }, ) ], } purchase_request = self.purchase_request_obj.create(vals) purchase_request.button_to_approve() purchase_request.button_approved() supplier = self.env.ref("base.res_partner_12") vals = { "supplier_id": supplier.id, } wiz_id = self.wiz.with_context( active_model="purchase.request.line", active_ids=[purchase_request["line_ids"][0].id], active_id=purchase_request["line_ids"][0].id, ).create(vals) wiz_id.make_purchase_order() po_line = purchase_request["line_ids"][0].purchase_lines[0] self.assertEqual(po_line.account_analytic_id, analytic_account) self.assertEqual(po_line.analytic_tag_ids.ids, analytic_tags.ids)
41.684864
16,799
17,281
py
PYTHON
15.0
# Copyright 2018-2019 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl-3.0) from odoo import SUPERUSER_ID from odoo.tests import common class TestPurchaseRequestToRfq(common.TransactionCase): def setUp(self): super(TestPurchaseRequestToRfq, self).setUp() self.purchase_request = self.env["purchase.request"] self.purchase_request_line = self.env["purchase.request.line"] self.wiz = self.env["purchase.request.line.make.purchase.order"] self.purchase_order = self.env["purchase.order"] vendor = self.env["res.partner"].create({"name": "Partner #2"}) self.service_product = self.env["product.product"].create( {"name": "Product Service Test", "type": "service"} ) self.product_product = self.env["product.product"].create( { "name": "Product Product Test", "type": "product", "description_purchase": "Test Description", } ) self.env["product.supplierinfo"].create( { "name": vendor.id, "product_tmpl_id": self.service_product.product_tmpl_id.id, } ) self.env["product.supplierinfo"].create( { "name": vendor.id, "product_tmpl_id": self.product_product.product_tmpl_id.id, } ) def test_purchase_request_allocation(self): vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, } purchase_request1 = self.purchase_request.create(vals) vals = { "request_id": purchase_request1.id, "product_id": self.product_product.id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 2.0, } purchase_request_line1 = self.purchase_request_line.create(vals) vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, } purchase_request2 = self.purchase_request.create(vals) vals = { "request_id": purchase_request1.id, "product_id": self.product_product.id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 2.0, } purchase_request_line2 = self.purchase_request_line.create(vals) purchase_request1.button_approved() purchase_request2.button_approved() purchase_request1.action_view_purchase_request_line() vals = {"supplier_id": self.env.ref("base.res_partner_1").id} wiz_id = self.wiz.with_context( active_model="purchase.request.line", active_ids=[purchase_request_line1.id, purchase_request_line2.id], ).create(vals) wiz_id.make_purchase_order() purchase_request1.action_view_purchase_order() po_line = purchase_request_line1.purchase_lines[0] # Add unit price in PO Line po_line.write({"price_unit": 10}) purchase = po_line.order_id purchase.order_line.action_open_request_line_tree_view() purchase.button_confirm() purchase_request1.action_view_stock_picking() self.assertEqual(purchase_request_line1.qty_in_progress, 2.0) self.assertEqual(purchase_request_line2.qty_in_progress, 2.0) picking = purchase.picking_ids[0] picking.move_line_ids[0].write({"qty_done": 2.0}) backorder_wiz_id = picking.button_validate() common.Form( self.env[backorder_wiz_id["res_model"]].with_context( **backorder_wiz_id["context"] ) ).save().process() self.assertEqual(purchase_request_line1.qty_done, 2.0) self.assertEqual(purchase_request_line2.qty_done, 0.0) backorder_picking = purchase.picking_ids.filtered(lambda p: p.id != picking.id) backorder_picking.move_line_ids[0].write({"qty_done": 1.0}) backorder_wiz_id2 = backorder_picking.button_validate() common.Form( self.env[backorder_wiz_id2["res_model"]].with_context( **backorder_wiz_id2["context"] ) ).save().process() self.assertEqual(purchase_request_line1.qty_done, 2.0) self.assertEqual(purchase_request_line2.qty_done, 1.0) for pick in purchase.picking_ids: if pick.state == "assigned": pick.action_cancel() self.assertEqual(purchase_request_line1.qty_cancelled, 0.0) self.assertEqual(purchase_request_line2.qty_cancelled, 1.0) self.assertEqual(purchase_request_line1.pending_qty_to_receive, 0.0) self.assertEqual(purchase_request_line2.pending_qty_to_receive, 1.0) def test_purchase_request_allocation_services(self): vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, "assigned_to": SUPERUSER_ID, } purchase_request1 = self.purchase_request.create(vals) vals = { "request_id": purchase_request1.id, "product_id": self.service_product.id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 2.0, } purchase_request_line1 = self.purchase_request_line.create(vals) vals = {"supplier_id": self.env.ref("base.res_partner_1").id} purchase_request1.button_approved() purchase_request1.action_view_purchase_request_line() wiz_id = self.wiz.with_context( active_model="purchase.request.line", active_ids=[purchase_request_line1.id] ).create(vals) wiz_id.make_purchase_order() purchase_request1.action_view_purchase_order() po_line = purchase_request_line1.purchase_lines[0] # Add unit price in PO Line po_line.write({"price_unit": 10}) purchase = po_line.order_id purchase.button_confirm() self.assertEqual(purchase_request_line1.qty_in_progress, 2.0) # manually set in the PO line po_line.write({"qty_received": 0.5}) self.assertEqual(purchase_request_line1.qty_done, 0.5) purchase.button_cancel() self.assertEqual(purchase_request_line1.qty_cancelled, 1.5) self.assertEqual(purchase_request_line1.pending_qty_to_receive, 1.5) # Case revieve 2 product vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, "assigned_to": SUPERUSER_ID, } purchase_request2 = self.purchase_request.create(vals) vals = { "request_id": purchase_request2.id, "product_id": self.service_product.id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 2.0, } purchase_request_line2 = self.purchase_request_line.create(vals) vals = {"supplier_id": self.env.ref("base.res_partner_1").id} purchase_request2.button_approved() purchase_request2.action_view_purchase_request_line() wiz_id = self.wiz.with_context( active_model="purchase.request.line", active_ids=[purchase_request_line2.id] ).create(vals) wiz_id.make_purchase_order() purchase_request2.action_view_purchase_order() po_line = purchase_request_line2.purchase_lines[0] purchase2 = po_line.order_id purchase2.button_confirm() self.assertEqual(purchase_request_line2.qty_in_progress, 2.0) purchase_request1.action_view_stock_picking() # manually set in the PO line po_line.write({"qty_received": 2.0}) self.assertEqual(purchase_request_line2.qty_done, 2.0) def test_purchase_request_allocation_min_qty(self): vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, } purchase_request1 = self.purchase_request.create(vals) vals = { "request_id": purchase_request1.id, "product_id": self.product_product.id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 2.0, } purchase_request_line1 = self.purchase_request_line.create(vals) # add a vendor vendor1 = self.env.ref("base.res_partner_1") self.env["product.supplierinfo"].create( { "name": vendor1.id, "product_tmpl_id": self.product_product.product_tmpl_id.id, "min_qty": 8, } ) vals = {"supplier_id": self.env.ref("base.res_partner_1").id} purchase_request1.button_approved() wiz_id = self.wiz.with_context( active_model="purchase.request.line", active_ids=[purchase_request_line1.id] ).create(vals) wiz_id.make_purchase_order() self.assertEqual( purchase_request_line1.purchase_request_allocation_ids[0].open_product_qty, 2.0, ) def test_purchase_request_stock_allocation(self): product = self.env.ref("product.product_product_6") product.uom_po_id = self.env.ref("uom.product_uom_dozen") vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, } purchase_request = self.purchase_request.create(vals) vals = { "request_id": purchase_request.id, "product_id": product.id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 12.0, } purchase_request_line1 = self.purchase_request_line.create(vals) vals = { "request_id": purchase_request.id, "product_id": product.id, "product_uom_id": self.env.ref("uom.product_uom_dozen").id, "product_qty": 1, } purchase_request_line2 = self.purchase_request_line.create(vals) vals = {"supplier_id": self.env.ref("base.res_partner_1").id} purchase_request.button_approved() wiz_id = self.wiz.with_context( active_model="purchase.request.line", active_ids=[purchase_request_line1.id, purchase_request_line2.id], ).create(vals) # Create PO wiz_id.make_purchase_order() po_line = purchase_request_line1.purchase_lines[0] self.assertEqual(po_line.product_qty, 2, "Quantity should be 2") self.assertEqual( po_line.product_uom, self.env.ref("uom.product_uom_dozen"), "The purchase UoM should be Dozen(s).", ) self.assertEqual( purchase_request_line1.purchase_request_allocation_ids[ 0 ].requested_product_uom_qty, 12.0, ) self.assertEqual( purchase_request_line2.purchase_request_allocation_ids[ 0 ].requested_product_uom_qty, 1.0, ) purchase = po_line.order_id # Cancel PO allocation requested quantity is set to 0. purchase.button_cancel() self.assertEqual( purchase_request_line1.purchase_request_allocation_ids[0].open_product_qty, 0, ) self.assertEqual( purchase_request_line2.purchase_request_allocation_ids[0].open_product_qty, 0, ) # Set to draft allocation requested quantity is set purchase.button_draft() self.assertEqual( purchase_request_line1.purchase_request_allocation_ids[0].open_product_qty, 12.0, ) self.assertEqual( purchase_request_line2.purchase_request_allocation_ids[0].open_product_qty, 1.0, ) purchase.button_confirm() picking = purchase.picking_ids[0] picking.move_line_ids[0].write({"qty_done": 24.0}) picking.button_validate() self.assertEqual( purchase_request_line1.purchase_request_allocation_ids[ 0 ].allocated_product_qty, purchase_request_line1.purchase_request_allocation_ids[ 0 ].requested_product_uom_qty, ) self.assertEqual( purchase_request_line2.purchase_request_allocation_ids[ 0 ].allocated_product_qty, purchase_request_line2.purchase_request_allocation_ids[ 0 ].requested_product_uom_qty, ) def test_purchase_request_stock_allocation_unlink(self): product = self.env.ref("product.product_product_6") product.uom_po_id = self.env.ref("uom.product_uom_dozen") vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, } purchase_request = self.purchase_request.create(vals) vals = { "request_id": purchase_request.id, "product_id": product.id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 12.0, } purchase_request_line1 = self.purchase_request_line.create(vals) vals = {"supplier_id": self.env.ref("base.res_partner_1").id} purchase_request.button_approved() wiz_id = self.wiz.with_context( active_model="purchase.request.line", active_ids=[purchase_request_line1.id] ).create(vals) # Create PO wiz_id.make_purchase_order() po_line = purchase_request_line1.purchase_lines[0] self.assertEqual( purchase_request_line1.purchase_request_allocation_ids[ 0 ].requested_product_uom_qty, 12.0, ) purchase = po_line.order_id purchase.button_cancel() # Delete PO: allocation and Purchase Order Lines are unlinked from PRL purchase.unlink() self.assertEqual(len(purchase_request_line1.purchase_lines), 0) self.assertEqual(len(purchase_request_line1.purchase_request_allocation_ids), 0) def test_onchange_product_id(self): vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, } purchase_request1 = self.purchase_request.create(vals) vals = { "request_id": purchase_request1.id, "product_id": self.product_product.id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 2.0, } purchase_request_line1 = self.purchase_request_line.create(vals) purchase_request_line1.onchange_product_id() def test_empty_records_for_company_constraint(self): self.assertFalse(self.env["stock.move"]._check_company_purchase_request()) def test_supplier_assignment(self): """Suppliers are not assigned across the company boundary""" product = self.env.ref("product.product_product_6") product.seller_ids.unlink() purchase_request = self.purchase_request.create( { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, "company_id": self.env.ref("base.main_company").id, } ) purchase_request_line = self.purchase_request_line.create( { "request_id": purchase_request.id, "product_id": product.id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 12.0, "company_id": self.env.ref("base.main_company").id, } ) # A supplier from another company is not assigned vendor3 = self.env["res.partner"].create({"name": "Partner #3"}) supinfo = self.env["product.supplierinfo"].create( { "name": vendor3.id, "product_tmpl_id": product.product_tmpl_id.id, "company_id": self.env.ref("stock.res_company_1").id, } ) self.assertFalse(purchase_request_line.supplier_id) # A supplierinfo of a matching company leads to supplier assignment vendor4 = self.env["res.partner"].create({"name": "Partner #4"}) supinfo = self.env["product.supplierinfo"].create( { "name": vendor4.id, "product_tmpl_id": product.product_tmpl_id.id, "company_id": self.env.ref("base.main_company").id, } ) self.assertEqual(purchase_request_line.supplier_id, vendor4) supinfo.unlink() self.assertFalse(purchase_request_line.supplier_id) # A supplierinfo without company leads to supplier assignment as well self.env["product.supplierinfo"].create( { "name": vendor4.id, "product_tmpl_id": product.product_tmpl_id.id, "company_id": False, } ) self.assertEqual(purchase_request_line.supplier_id, vendor4)
42.355392
17,281
3,999
py
PYTHON
15.0
# Copyright 2018-2019 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl-3.0) from odoo import SUPERUSER_ID, fields from odoo.tests import common class TestPurchaseRequestProcurement(common.TransactionCase): def setUp(self): super(TestPurchaseRequestProcurement, self).setUp() # Get required Model self.pr_model = self.env["purchase.request"] self.prl_model = self.env["purchase.request.line"] self.product_uom_model = self.env["uom.uom"] self.location = self.env.ref("stock.stock_location_stock") # Get required Model data self.uom_unit_categ = self.env.ref("uom.product_uom_categ_unit") self.product_1 = self.env.ref("product.product_product_16") self.product_1.purchase_request = True self.product_2 = self.env.ref("product.product_product_13") self.uom_unit = self.env.ref("uom.product_uom_unit") # Create UoM self.uom_ten = self.product_uom_model.create( { "name": "Ten", "category_id": self.uom_unit_categ.id, "factor_inv": 10, "uom_type": "bigger", } ) # Create Supplier self.supplier = self.env["res.partner"].create( {"name": "Supplier", "is_company": True, "company_id": False} ) # Add supplier to product_1 self.product_1.write( { "seller_ids": [ ( 0, 0, {"name": self.supplier.id, "price": 100.0, "company_id": False}, ) ] } ) def procurement_group_run(self, name, origin, product, qty): values = { "date_planned": fields.Datetime.now(), "warehouse_id": self.env.ref("stock.warehouse0"), "route_ids": self.env.ref("purchase_stock.route_warehouse0_buy"), "company_id": self.env.ref("base.main_company"), } procurements = [] procurements.append( self.env["procurement.group"].Procurement( product, qty, product.uom_id, self.location, name, origin, self.env.company, values, ) ) return self.env["procurement.group"].run(procurements) def test_procure_purchase_request(self): has_route = self.procurement_group_run( "Test Purchase Request Procurement", "Test Purchase Request Procurement", self.product_1, 10, ) self.assertTrue(has_route) self.env["procurement.group"].run_scheduler() pr = self.env["purchase.request"].search( [("origin", "=", "Test Purchase Request Procurement")] ) self.assertTrue(pr.to_approve_allowed) self.assertEqual(pr.origin, "Test Purchase Request Procurement") prl = self.env["purchase.request.line"].search([("request_id", "=", pr.id)]) self.assertEqual(prl.request_id, pr) # Test split(", ") vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, "origin": "Test Origin", "line_ids": [ [ 0, 0, { "product_id": self.env.ref("product.product_product_13").id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 2.0, }, ] ], } self.pr_model.create(vals) self.procurement_group_run( "Test Test, Split", "Test, Split", self.product_1, 10 ) self.procurement_group_run("Test Test, Split", False, self.product_1, 10)
35.705357
3,999
10,312
py
PYTHON
15.0
# Copyright 2018-2019 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl-3.0) from odoo import SUPERUSER_ID, exceptions from odoo.exceptions import UserError from odoo.tests.common import Form, TransactionCase class TestPurchaseRequest(TransactionCase): def setUp(self): super(TestPurchaseRequest, self).setUp() self.purchase_request_obj = self.env["purchase.request"] self.purchase_request_line_obj = self.env["purchase.request.line"] self.purchase_order = self.env["purchase.order"] self.wiz = self.env["purchase.request.line.make.purchase.order"] vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, } self.purchase_request = self.purchase_request_obj.create(vals) vals = { "request_id": self.purchase_request.id, "product_id": self.env.ref("product.product_product_13").id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 5.0, } self.purchase_request_line_obj.create(vals) def test_purchase_request_status(self): """Tests Purchase Request status workflow.""" purchase_request = self.purchase_request purchase_request.write({"assigned_to": SUPERUSER_ID}) self.assertEqual(purchase_request.is_editable, True, "Should be editable") self.assertEqual(purchase_request.state, "draft", "Should be in state draft") purchase_request.button_to_approve() self.assertEqual( purchase_request.state, "to_approve", "Should be in state to_approve" ) with self.assertRaises(exceptions.UserError) as e: purchase_request.unlink() msg = "You cannot delete a purchase request which is not draft." self.assertIn(msg, e.exception.args[0]) self.assertEqual(purchase_request.is_editable, False, "Should not be editable") purchase_request.button_draft() self.assertEqual(purchase_request.is_editable, True, "Should be editable") self.assertEqual(purchase_request.state, "draft", "Should be in state draft") purchase_request.button_to_approve() purchase_request.button_done() self.assertEqual(purchase_request.is_editable, False, "Should not be editable") with self.assertRaises(exceptions.UserError) as e: purchase_request.unlink() msg = "You cannot delete a purchase request which is not draft." self.assertIn(msg, e.exception.args[0]) purchase_request.button_rejected() self.assertEqual(purchase_request.is_editable, False, "Should not be editable") vals = { "request_id": purchase_request.id, "product_id": self.env.ref("product.product_product_6").id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 2.0, } purchase_request_line = self.purchase_request_line_obj.create(vals) purchase_request.button_approved() vals = {"supplier_id": self.env.ref("base.res_partner_1").id} wiz_id = self.wiz.with_context( active_model="purchase.request.line", active_ids=[purchase_request_line.id] ).create(vals) wiz_id.make_purchase_order() # Unlink purchase_lines from state approved with self.assertRaises(UserError): purchase_request_line.unlink() purchase = purchase_request_line.purchase_lines.order_id purchase.button_done() self.assertEqual(purchase.state, "done") purchase_request_line._compute_purchase_state() # Error case purchase_order in state done with self.assertRaises(UserError): purchase.button_confirm() purchase.button_cancel() self.assertEqual(purchase.state, "cancel") purchase_request_line._compute_purchase_state() with self.assertRaises(exceptions.UserError) as e: purchase_request.unlink() msg = "You cannot delete a purchase request which is not draft." self.assertIn(msg, e.exception.args[0]) purchase_request.button_draft() purchase_request.unlink() def test_auto_reject(self): """Tests if a Purchase Request is autorejected when all lines are cancelled.""" purchase_request = self.purchase_request # Add a second line to the PR: vals = { "request_id": purchase_request.id, "product_id": self.env.ref("product.product_product_16").id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 5.0, } self.purchase_request_line_obj.create(vals) lines = purchase_request.line_ids # Cancel one line: lines[0].do_cancel() self.assertNotEqual( purchase_request.state, "rejected", "Purchase Request should not have been rejected.", ) # Cancel the second one: lines[1].do_cancel() self.assertEqual( purchase_request.state, "rejected", "Purchase Request should have been auto-rejected.", ) def test_pr_line_to_approve_allowed(self): request = self.purchase_request self.assertTrue(request.to_approve_allowed) pr_lines = self.purchase_request.line_ids pr_lines.write({"product_qty": 0}) self.assertFalse(request.to_approve_allowed) pr_lines.write({"product_qty": 5}) self.assertTrue(request.to_approve_allowed) pr_lines.do_cancel() self.assertFalse(request.to_approve_allowed) # Request has been automatically rejected request.button_draft() new_line = self.purchase_request_line_obj.create( { "product_id": self.env.ref("product.product_product_16").id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 0.0, "request_id": request.id, } ) pr_lines.do_cancel() self.assertFalse(request.to_approve_allowed) new_line.write({"product_qty": 1}) self.assertTrue(request.to_approve_allowed) request.line_ids.unlink() self.assertFalse(request.to_approve_allowed) def test_empty_purchase_request(self): pr = self.purchase_request pr_lines = pr.line_ids pr_lines.write({"product_qty": 0}) with self.assertRaises(UserError): self.purchase_request.button_to_approve() pr_lines.write({"product_qty": 4}) pr.button_to_approve() self.assertEqual(pr.state, "to_approve") def test_default_picking_type(self): with Form(self.purchase_request_obj) as f: f.name = "Test Purchase" f.requested_by = self.env.user f.save() def test_copy_purchase_request(self): purchase_request = self.purchase_request # Add a second line to the PR: vals = { "request_id": purchase_request.id, "product_id": self.env.ref("product.product_product_16").id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 5.0, } self.purchase_request_line_obj.create(vals) purchase_request_copy = purchase_request.copy() self.assertEqual(purchase_request_copy.state, "draft") def test_raise_error(self): vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, } purchase_request = self.purchase_request.create(vals) vals = { "request_id": purchase_request.id, "product_id": self.env.ref("product.product_product_16").id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 2.0, } purchase_request_line = self.purchase_request_line_obj.create(vals) self.assertEqual(purchase_request.state, "draft") # create purchase order from draft state with self.assertRaises(UserError): self.wiz.with_context( active_model="purchase.request.line", active_ids=[purchase_request_line.id], ).create(vals) purchase_request.button_done() # create purchase order from done state self.assertEqual(purchase_request.state, "done") purchase_request_line._compute_is_editable() with self.assertRaises(UserError): self.wiz.with_context( active_model="purchase.request.line", active_ids=[purchase_request_line.id], ).create(vals) # Change product_qty to negative purchase_request_line.write({"product_qty": -6}) purchase_request.button_approved() self.assertEqual(purchase_request.state, "approved") vals = {"supplier_id": self.env.ref("base.res_partner_1").id} wiz_id = self.wiz.with_context( active_model="purchase.request.line", active_ids=[purchase_request_line.id] ).create(vals) with self.assertRaises(UserError): wiz_id.make_purchase_order() def test_purchase_request_unlink(self): pr = self.purchase_request pr_lines = pr.line_ids pr.button_to_approve() self.assertEqual(pr.state, "to_approve", "Should be in state to_approve") with self.assertRaises(exceptions.UserError) as e: pr_lines.unlink() msg = ( "You can only delete a purchase request line " "if the purchase request is in draft state." ) self.assertIn(msg, e.exception.args[0]) pr.button_done() self.assertEqual(pr.state, "done", "Should be in state done") with self.assertRaises(exceptions.UserError) as e: pr_lines.unlink() msg = ( "You can only delete a purchase request line " "if the purchase request is in draft state." ) self.assertIn(msg, e.exception.args[0]) pr.button_draft() self.assertEqual(pr.state, "draft", "Should be in state draft") pr_lines.unlink()
42.262295
10,312
15,608
py
PYTHON
15.0
# Copyright 2018-2019 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl-3.0). from datetime import datetime from odoo import _, api, fields, models from odoo.exceptions import UserError class PurchaseRequestLineMakePurchaseOrder(models.TransientModel): _name = "purchase.request.line.make.purchase.order" _description = "Purchase Request Line Make Purchase Order" supplier_id = fields.Many2one( comodel_name="res.partner", string="Supplier", required=True, context={"res_partner_search_mode": "supplier"}, ) item_ids = fields.One2many( comodel_name="purchase.request.line.make.purchase.order.item", inverse_name="wiz_id", string="Items", ) purchase_order_id = fields.Many2one( comodel_name="purchase.order", string="Purchase Order", domain=[("state", "=", "draft")], ) sync_data_planned = fields.Boolean( string="Merge on PO lines with equal Scheduled Date" ) @api.model def _prepare_item(self, line): return { "line_id": line.id, "request_id": line.request_id.id, "product_id": line.product_id.id, "name": line.name or line.product_id.name, "product_qty": line.pending_qty_to_receive, "product_uom_id": line.product_uom_id.id, } @api.model def _check_valid_request_line(self, request_line_ids): picking_type = False company_id = False for line in self.env["purchase.request.line"].browse(request_line_ids): if line.request_id.state == "done": raise UserError(_("The purchase has already been completed.")) if line.request_id.state != "approved": raise UserError( _("Purchase Request %s is not approved") % line.request_id.name ) if line.purchase_state == "done": raise UserError(_("The purchase has already been completed.")) line_company_id = line.company_id and line.company_id.id or False if company_id is not False and line_company_id != company_id: raise UserError(_("You have to select lines from the same company.")) else: company_id = line_company_id line_picking_type = line.request_id.picking_type_id or False if not line_picking_type: raise UserError(_("You have to enter a Picking Type.")) if picking_type is not False and line_picking_type != picking_type: raise UserError( _("You have to select lines from the same Picking Type.") ) else: picking_type = line_picking_type @api.model def check_group(self, request_lines): if len(list(set(request_lines.mapped("request_id.group_id")))) > 1: raise UserError( _( "You cannot create a single purchase order from " "purchase requests that have different procurement group." ) ) @api.model def get_items(self, request_line_ids): request_line_obj = self.env["purchase.request.line"] items = [] request_lines = request_line_obj.browse(request_line_ids) self._check_valid_request_line(request_line_ids) self.check_group(request_lines) for line in request_lines: items.append([0, 0, self._prepare_item(line)]) return items @api.model def default_get(self, fields): res = super().default_get(fields) active_model = self.env.context.get("active_model", False) request_line_ids = [] if active_model == "purchase.request.line": request_line_ids += self.env.context.get("active_ids", []) elif active_model == "purchase.request": request_ids = self.env.context.get("active_ids", False) request_line_ids += ( self.env[active_model].browse(request_ids).mapped("line_ids.id") ) if not request_line_ids: return res res["item_ids"] = self.get_items(request_line_ids) request_lines = self.env["purchase.request.line"].browse(request_line_ids) supplier_ids = request_lines.mapped("supplier_id").ids if len(supplier_ids) == 1: res["supplier_id"] = supplier_ids[0] return res @api.model def _prepare_purchase_order( self, picking_type, group_id, company, currency, origin ): if not self.supplier_id: raise UserError(_("Enter a supplier.")) supplier = self.supplier_id data = { "origin": origin, "partner_id": self.supplier_id.id, "fiscal_position_id": supplier.property_account_position_id and supplier.property_account_position_id.id or False, "picking_type_id": picking_type.id, "company_id": company.id, "currency_id": currency.id, "group_id": group_id.id, } return data @api.model def _get_purchase_line_onchange_fields(self): return ["product_uom", "price_unit", "name", "taxes_id"] @api.model def _execute_purchase_line_onchange(self, vals): cls = self.env["purchase.order.line"] onchanges_dict = { "onchange_product_id": self._get_purchase_line_onchange_fields() } for onchange_method, changed_fields in onchanges_dict.items(): if any(f not in vals for f in changed_fields): obj = cls.new(vals) getattr(obj, onchange_method)() for field in changed_fields: vals[field] = obj._fields[field].convert_to_write(obj[field], obj) def create_allocation(self, po_line, pr_line, new_qty, alloc_uom): vals = { "requested_product_uom_qty": new_qty, "product_uom_id": alloc_uom.id, "purchase_request_line_id": pr_line.id, "purchase_line_id": po_line.id, } return self.env["purchase.request.allocation"].create(vals) @api.model def _prepare_purchase_order_line(self, po, item): if not item.product_id: raise UserError(_("Please select a product for all lines")) product = item.product_id # Keep the standard product UOM for purchase order so we should # convert the product quantity to this UOM qty = item.product_uom_id._compute_quantity( item.product_qty, product.uom_po_id or product.uom_id ) # Suggest the supplier min qty as it's done in Odoo core min_qty = item.line_id._get_supplier_min_qty(product, po.partner_id) qty = max(qty, min_qty) date_required = item.line_id.date_required vals = { "name": product.name, "order_id": po.id, "product_id": product.id, "product_uom": product.uom_po_id.id or product.uom_id.id, "price_unit": 0.0, "product_qty": qty, "account_analytic_id": item.line_id.analytic_account_id.id, "purchase_request_lines": [(4, item.line_id.id)], "date_planned": datetime( date_required.year, date_required.month, date_required.day ), "move_dest_ids": [(4, x.id) for x in item.line_id.move_dest_ids], } if item.line_id.analytic_tag_ids: vals["analytic_tag_ids"] = [ (4, ati) for ati in item.line_id.analytic_tag_ids.ids ] self._execute_purchase_line_onchange(vals) return vals @api.model def _get_purchase_line_name(self, order, line): product_lang = line.product_id.with_context( lang=self.supplier_id.lang, partner_id=self.supplier_id.id ) name = product_lang.display_name if product_lang.description_purchase: name += "\n" + product_lang.description_purchase return name @api.model def _get_order_line_search_domain(self, order, item): vals = self._prepare_purchase_order_line(order, item) name = self._get_purchase_line_name(order, item) order_line_data = [ ("order_id", "=", order.id), ("name", "=", name), ("product_id", "=", item.product_id.id or False), ("product_uom", "=", vals["product_uom"]), ("account_analytic_id", "=", item.line_id.analytic_account_id.id or False), ] if self.sync_data_planned: date_required = item.line_id.date_required order_line_data += [ ( "date_planned", "=", datetime( date_required.year, date_required.month, date_required.day ), ) ] if not item.product_id: order_line_data.append(("name", "=", item.name)) return order_line_data def make_purchase_order(self): res = [] purchase_obj = self.env["purchase.order"] po_line_obj = self.env["purchase.order.line"] pr_line_obj = self.env["purchase.request.line"] purchase = False for item in self.item_ids: line = item.line_id if item.product_qty <= 0.0: raise UserError(_("Enter a positive quantity.")) if self.purchase_order_id: purchase = self.purchase_order_id if not purchase: po_data = self._prepare_purchase_order( line.request_id.picking_type_id, line.request_id.group_id, line.company_id, line.currency_id, line.origin, ) purchase = purchase_obj.create(po_data) # Look for any other PO line in the selected PO with same # product and UoM to sum quantities instead of creating a new # po line domain = self._get_order_line_search_domain(purchase, item) available_po_lines = po_line_obj.search(domain) new_pr_line = True # If Unit of Measure is not set, update from wizard. if not line.product_uom_id: line.product_uom_id = item.product_uom_id # Allocation UoM has to be the same as PR line UoM alloc_uom = line.product_uom_id wizard_uom = item.product_uom_id if available_po_lines and not item.keep_description: new_pr_line = False po_line = available_po_lines[0] po_line.purchase_request_lines = [(4, line.id)] po_line.move_dest_ids |= line.move_dest_ids po_line_product_uom_qty = po_line.product_uom._compute_quantity( po_line.product_uom_qty, alloc_uom ) wizard_product_uom_qty = wizard_uom._compute_quantity( item.product_qty, alloc_uom ) all_qty = min(po_line_product_uom_qty, wizard_product_uom_qty) self.create_allocation(po_line, line, all_qty, alloc_uom) else: po_line_data = self._prepare_purchase_order_line(purchase, item) if item.keep_description: po_line_data["name"] = item.name po_line = po_line_obj.create(po_line_data) po_line_product_uom_qty = po_line.product_uom._compute_quantity( po_line.product_uom_qty, alloc_uom ) wizard_product_uom_qty = wizard_uom._compute_quantity( item.product_qty, alloc_uom ) all_qty = min(po_line_product_uom_qty, wizard_product_uom_qty) self.create_allocation(po_line, line, all_qty, alloc_uom) # TODO: Check propagate_uom compatibility: new_qty = pr_line_obj._calc_new_qty( line, po_line=po_line, new_pr_line=new_pr_line ) po_line.product_qty = new_qty po_line._onchange_quantity() # The onchange quantity is altering the scheduled date of the PO # lines. We do not want that: date_required = item.line_id.date_required po_line.date_planned = datetime( date_required.year, date_required.month, date_required.day ) res.append(purchase.id) return { "domain": [("id", "in", res)], "name": _("RFQ"), "view_mode": "tree,form", "res_model": "purchase.order", "view_id": False, "context": False, "type": "ir.actions.act_window", } class PurchaseRequestLineMakePurchaseOrderItem(models.TransientModel): _name = "purchase.request.line.make.purchase.order.item" _description = "Purchase Request Line Make Purchase Order Item" wiz_id = fields.Many2one( comodel_name="purchase.request.line.make.purchase.order", string="Wizard", required=True, ondelete="cascade", readonly=True, ) line_id = fields.Many2one( comodel_name="purchase.request.line", string="Purchase Request Line" ) request_id = fields.Many2one( comodel_name="purchase.request", related="line_id.request_id", string="Purchase Request", readonly=False, ) product_id = fields.Many2one( comodel_name="product.product", string="Product", related="line_id.product_id", readonly=False, ) name = fields.Char(string="Description", required=True) product_qty = fields.Float( string="Quantity to purchase", digits="Product Unit of Measure" ) product_uom_id = fields.Many2one( comodel_name="uom.uom", string="UoM", required=True ) keep_description = fields.Boolean( string="Copy descriptions to new PO", help="Set true if you want to keep the " "descriptions provided in the " "wizard in the new PO.", ) @api.onchange("product_id") def onchange_product_id(self): if self.product_id: if not self.keep_description: name = self.product_id.name code = self.product_id.code sup_info_id = self.env["product.supplierinfo"].search( [ "|", ("product_id", "=", self.product_id.id), ("product_tmpl_id", "=", self.product_id.product_tmpl_id.id), ("name", "=", self.wiz_id.supplier_id.id), ] ) if sup_info_id: p_code = sup_info_id[0].product_code p_name = sup_info_id[0].product_name name = "[{}] {}".format( p_code if p_code else code, p_name if p_name else name ) else: if code: name = "[{}] {}".format( code, self.name if self.keep_description else name ) if self.product_id.description_purchase and not self.keep_description: name += "\n" + self.product_id.description_purchase self.product_uom_id = self.product_id.uom_id.id if name: self.name = name
39.816327
15,608
9,940
py
PYTHON
15.0
# Copyright 2018-2019 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl-3.0) from odoo import _, api, fields, models from odoo.exceptions import UserError _STATES = [ ("draft", "Draft"), ("to_approve", "To be approved"), ("approved", "Approved"), ("rejected", "Rejected"), ("done", "Done"), ] class PurchaseRequest(models.Model): _name = "purchase.request" _description = "Purchase Request" _inherit = ["mail.thread", "mail.activity.mixin"] _order = "id desc" @api.model def _company_get(self): return self.env["res.company"].browse(self.env.company.id) @api.model def _get_default_requested_by(self): return self.env["res.users"].browse(self.env.uid) @api.model def _get_default_name(self): return self.env["ir.sequence"].next_by_code("purchase.request") @api.model def _default_picking_type(self): type_obj = self.env["stock.picking.type"] company_id = self.env.context.get("company_id") or self.env.company.id types = type_obj.search( [("code", "=", "incoming"), ("warehouse_id.company_id", "=", company_id)] ) if not types: types = type_obj.search( [("code", "=", "incoming"), ("warehouse_id", "=", False)] ) return types[:1] @api.depends("state") def _compute_is_editable(self): for rec in self: if rec.state in ("to_approve", "approved", "rejected", "done"): rec.is_editable = False else: rec.is_editable = True name = fields.Char( string="Request Reference", required=True, default=lambda self: _("New"), tracking=True, ) is_name_editable = fields.Boolean( default=lambda self: self.env.user.has_group("base.group_no_one"), ) origin = fields.Char(string="Source Document") date_start = fields.Date( string="Creation date", help="Date when the user initiated the request.", default=fields.Date.context_today, tracking=True, ) requested_by = fields.Many2one( comodel_name="res.users", required=True, copy=False, tracking=True, default=_get_default_requested_by, index=True, ) assigned_to = fields.Many2one( comodel_name="res.users", string="Approver", tracking=True, domain=lambda self: [ ( "groups_id", "in", self.env.ref("purchase_request.group_purchase_request_manager").id, ) ], index=True, ) description = fields.Text() company_id = fields.Many2one( comodel_name="res.company", required=False, default=_company_get, tracking=True, ) line_ids = fields.One2many( comodel_name="purchase.request.line", inverse_name="request_id", string="Products to Purchase", readonly=False, copy=True, tracking=True, ) product_id = fields.Many2one( comodel_name="product.product", related="line_ids.product_id", string="Product", readonly=True, ) state = fields.Selection( selection=_STATES, string="Status", index=True, tracking=True, required=True, copy=False, default="draft", ) is_editable = fields.Boolean(compute="_compute_is_editable", readonly=True) to_approve_allowed = fields.Boolean(compute="_compute_to_approve_allowed") picking_type_id = fields.Many2one( comodel_name="stock.picking.type", string="Picking Type", required=True, default=_default_picking_type, ) group_id = fields.Many2one( comodel_name="procurement.group", string="Procurement Group", copy=False, index=True, ) line_count = fields.Integer( string="Purchase Request Line count", compute="_compute_line_count", readonly=True, ) move_count = fields.Integer( string="Stock Move count", compute="_compute_move_count", readonly=True ) purchase_count = fields.Integer( string="Purchases count", compute="_compute_purchase_count", readonly=True ) currency_id = fields.Many2one( comodel_name="res.currency", default=lambda self: self.env.user.company_id.currency_id, required=True, ) estimated_cost = fields.Monetary( compute="_compute_estimated_cost", string="Total Estimated Cost", store=True, ) @api.depends("line_ids", "line_ids.estimated_cost") def _compute_estimated_cost(self): for rec in self: rec.estimated_cost = sum(rec.line_ids.mapped("estimated_cost")) @api.depends("line_ids") def _compute_purchase_count(self): for rec in self: rec.purchase_count = len(rec.mapped("line_ids.purchase_lines.order_id")) def action_view_purchase_order(self): action = self.env["ir.actions.actions"]._for_xml_id("purchase.purchase_rfq") lines = self.mapped("line_ids.purchase_lines.order_id") if len(lines) > 1: action["domain"] = [("id", "in", lines.ids)] elif lines: action["views"] = [ (self.env.ref("purchase.purchase_order_form").id, "form") ] action["res_id"] = lines.id return action @api.depends("line_ids") def _compute_move_count(self): for rec in self: rec.move_count = len( rec.mapped("line_ids.purchase_request_allocation_ids.stock_move_id") ) def action_view_stock_picking(self): action = self.env["ir.actions.actions"]._for_xml_id( "stock.action_picking_tree_all" ) # remove default filters action["context"] = {} lines = self.mapped( "line_ids.purchase_request_allocation_ids.stock_move_id.picking_id" ) if len(lines) > 1: action["domain"] = [("id", "in", lines.ids)] elif lines: action["views"] = [(self.env.ref("stock.view_picking_form").id, "form")] action["res_id"] = lines.id return action @api.depends("line_ids") def _compute_line_count(self): for rec in self: rec.line_count = len(rec.mapped("line_ids")) def action_view_purchase_request_line(self): action = ( self.env.ref("purchase_request.purchase_request_line_form_action") .sudo() .read()[0] ) lines = self.mapped("line_ids") if len(lines) > 1: action["domain"] = [("id", "in", lines.ids)] elif lines: action["views"] = [ (self.env.ref("purchase_request.purchase_request_line_form").id, "form") ] action["res_id"] = lines.ids[0] return action @api.depends("state", "line_ids.product_qty", "line_ids.cancelled") def _compute_to_approve_allowed(self): for rec in self: rec.to_approve_allowed = rec.state == "draft" and any( not line.cancelled and line.product_qty for line in rec.line_ids ) def copy(self, default=None): default = dict(default or {}) self.ensure_one() default.update({"state": "draft", "name": self._get_default_name()}) return super(PurchaseRequest, self).copy(default) @api.model def _get_partner_id(self, request): user_id = request.assigned_to or self.env.user return user_id.partner_id.id @api.model def create(self, vals): if vals.get("name", _("New")) == _("New"): vals["name"] = self._get_default_name() request = super(PurchaseRequest, self).create(vals) if vals.get("assigned_to"): partner_id = self._get_partner_id(request) request.message_subscribe(partner_ids=[partner_id]) return request def write(self, vals): res = super(PurchaseRequest, self).write(vals) for request in self: if vals.get("assigned_to"): partner_id = self._get_partner_id(request) request.message_subscribe(partner_ids=[partner_id]) return res def _can_be_deleted(self): self.ensure_one() return self.state == "draft" def unlink(self): for request in self: if not request._can_be_deleted(): raise UserError( _("You cannot delete a purchase request which is not draft.") ) return super(PurchaseRequest, self).unlink() def button_draft(self): self.mapped("line_ids").do_uncancel() return self.write({"state": "draft"}) def button_to_approve(self): self.to_approve_allowed_check() return self.write({"state": "to_approve"}) def button_approved(self): return self.write({"state": "approved"}) def button_rejected(self): self.mapped("line_ids").do_cancel() return self.write({"state": "rejected"}) def button_done(self): return self.write({"state": "done"}) def check_auto_reject(self): """When all lines are cancelled the purchase request should be auto-rejected.""" for pr in self: if not pr.line_ids.filtered(lambda l: l.cancelled is False): pr.write({"state": "rejected"}) def to_approve_allowed_check(self): for rec in self: if not rec.to_approve_allowed: raise UserError( _( "You can't request an approval for a purchase request " "which is empty. (%s)" ) % rec.name )
32.37785
9,940
14,869
py
PYTHON
15.0
# Copyright 2018-2019 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl-3.0) from odoo import _, api, fields, models from odoo.exceptions import UserError _STATES = [ ("draft", "Draft"), ("to_approve", "To be approved"), ("approved", "Approved"), ("rejected", "Rejected"), ("done", "Done"), ] class PurchaseRequestLine(models.Model): _name = "purchase.request.line" _description = "Purchase Request Line" _inherit = ["mail.thread", "mail.activity.mixin"] _order = "id desc" name = fields.Char(string="Description", tracking=True) product_uom_id = fields.Many2one( comodel_name="uom.uom", string="UoM", tracking=True, domain="[('category_id', '=', product_uom_category_id)]", ) product_uom_category_id = fields.Many2one(related="product_id.uom_id.category_id") product_qty = fields.Float( string="Quantity", tracking=True, digits="Product Unit of Measure" ) request_id = fields.Many2one( comodel_name="purchase.request", string="Purchase Request", ondelete="cascade", readonly=True, index=True, auto_join=True, ) company_id = fields.Many2one( comodel_name="res.company", related="request_id.company_id", string="Company", store=True, ) analytic_account_id = fields.Many2one( comodel_name="account.analytic.account", string="Analytic Account", tracking=True, ) analytic_tag_ids = fields.Many2many( "account.analytic.tag", string="Analytic Tags", tracking=True ) requested_by = fields.Many2one( comodel_name="res.users", related="request_id.requested_by", string="Requested by", store=True, ) assigned_to = fields.Many2one( comodel_name="res.users", related="request_id.assigned_to", string="Assigned to", store=True, ) date_start = fields.Date(related="request_id.date_start", store=True) description = fields.Text( related="request_id.description", string="PR Description", store=True, readonly=False, ) origin = fields.Char( related="request_id.origin", string="Source Document", store=True ) date_required = fields.Date( string="Request Date", required=True, tracking=True, default=fields.Date.context_today, ) is_editable = fields.Boolean(compute="_compute_is_editable", readonly=True) specifications = fields.Text() request_state = fields.Selection( string="Request state", related="request_id.state", store=True, ) supplier_id = fields.Many2one( comodel_name="res.partner", string="Preferred supplier", compute="_compute_supplier_id", compute_sudo=True, store=True, ) cancelled = fields.Boolean(readonly=True, default=False, copy=False) purchased_qty = fields.Float( string="RFQ/PO Qty", digits="Product Unit of Measure", compute="_compute_purchased_qty", ) purchase_lines = fields.Many2many( comodel_name="purchase.order.line", relation="purchase_request_purchase_order_line_rel", column1="purchase_request_line_id", column2="purchase_order_line_id", string="Purchase Order Lines", readonly=True, copy=False, ) purchase_state = fields.Selection( compute="_compute_purchase_state", string="Purchase Status", selection=lambda self: self.env["purchase.order"]._fields["state"].selection, store=True, ) move_dest_ids = fields.One2many( comodel_name="stock.move", inverse_name="created_purchase_request_line_id", string="Downstream Moves", ) orderpoint_id = fields.Many2one( comodel_name="stock.warehouse.orderpoint", string="Orderpoint" ) purchase_request_allocation_ids = fields.One2many( comodel_name="purchase.request.allocation", inverse_name="purchase_request_line_id", string="Purchase Request Allocation", ) qty_in_progress = fields.Float( digits="Product Unit of Measure", readonly=True, compute="_compute_qty", store=True, help="Quantity in progress.", ) qty_done = fields.Float( digits="Product Unit of Measure", readonly=True, compute="_compute_qty", store=True, help="Quantity completed", ) qty_cancelled = fields.Float( digits="Product Unit of Measure", readonly=True, compute="_compute_qty_cancelled", store=True, help="Quantity cancelled", ) qty_to_buy = fields.Boolean( compute="_compute_qty_to_buy", string="There is some pending qty to buy", store=True, ) pending_qty_to_receive = fields.Float( compute="_compute_qty_to_buy", digits="Product Unit of Measure", copy=False, string="Pending Qty to Receive", store=True, ) estimated_cost = fields.Monetary( currency_field="currency_id", default=0.0, help="Estimated cost of Purchase Request Line, not propagated to PO.", ) currency_id = fields.Many2one(related="request_id.currency_id") product_id = fields.Many2one( comodel_name="product.product", string="Product", domain=[("purchase_ok", "=", True)], tracking=True, ) @api.depends( "purchase_request_allocation_ids", "purchase_request_allocation_ids.stock_move_id.state", "purchase_request_allocation_ids.stock_move_id", "purchase_request_allocation_ids.purchase_line_id", "purchase_request_allocation_ids.purchase_line_id.state", "request_id.state", "product_qty", ) def _compute_qty_to_buy(self): for pr in self: qty_to_buy = sum(pr.mapped("product_qty")) - sum(pr.mapped("qty_done")) pr.qty_to_buy = qty_to_buy > 0.0 pr.pending_qty_to_receive = qty_to_buy @api.depends( "purchase_request_allocation_ids", "purchase_request_allocation_ids.stock_move_id.state", "purchase_request_allocation_ids.stock_move_id", "purchase_request_allocation_ids.purchase_line_id.state", "purchase_request_allocation_ids.purchase_line_id", ) def _compute_qty(self): for request in self: done_qty = sum( request.purchase_request_allocation_ids.mapped("allocated_product_qty") ) open_qty = sum( request.purchase_request_allocation_ids.mapped("open_product_qty") ) request.qty_done = done_qty request.qty_in_progress = open_qty @api.depends( "purchase_request_allocation_ids", "purchase_request_allocation_ids.stock_move_id.state", "purchase_request_allocation_ids.stock_move_id", "purchase_request_allocation_ids.purchase_line_id.order_id.state", "purchase_request_allocation_ids.purchase_line_id", ) def _compute_qty_cancelled(self): for request in self: if request.product_id.type != "service": qty_cancelled = sum( request.mapped("purchase_request_allocation_ids.stock_move_id") .filtered(lambda sm: sm.state == "cancel") .mapped("product_qty") ) else: qty_cancelled = sum( request.mapped("purchase_request_allocation_ids.purchase_line_id") .filtered(lambda sm: sm.state == "cancel") .mapped("product_qty") ) # done this way as i cannot track what was received before # cancelled the purchase order qty_cancelled -= request.qty_done if request.product_uom_id: request.qty_cancelled = ( max( 0, request.product_id.uom_id._compute_quantity( qty_cancelled, request.product_uom_id ), ) if request.purchase_request_allocation_ids else 0 ) else: request.qty_cancelled = qty_cancelled @api.depends( "product_id", "name", "product_uom_id", "product_qty", "analytic_account_id", "date_required", "specifications", "purchase_lines", ) def _compute_is_editable(self): for rec in self: if rec.request_id.state in ("to_approve", "approved", "rejected", "done"): rec.is_editable = False else: rec.is_editable = True for rec in self.filtered(lambda p: p.purchase_lines): rec.is_editable = False @api.depends("product_id", "product_id.seller_ids") def _compute_supplier_id(self): for rec in self: sellers = rec.product_id.seller_ids.filtered( lambda si: not si.company_id or si.company_id == rec.company_id ) rec.supplier_id = sellers[0].name if sellers else False @api.onchange("product_id") def onchange_product_id(self): if self.product_id: name = self.product_id.name if self.product_id.code: name = "[{}] {}".format(self.product_id.code, name) if self.product_id.description_purchase: name += "\n" + self.product_id.description_purchase self.product_uom_id = self.product_id.uom_id.id self.product_qty = 1 self.name = name def do_cancel(self): """Actions to perform when cancelling a purchase request line.""" self.write({"cancelled": True}) def do_uncancel(self): """Actions to perform when uncancelling a purchase request line.""" self.write({"cancelled": False}) def write(self, vals): res = super(PurchaseRequestLine, self).write(vals) if vals.get("cancelled"): requests = self.mapped("request_id") requests.check_auto_reject() return res def _compute_purchased_qty(self): for rec in self: rec.purchased_qty = 0.0 for line in rec.purchase_lines.filtered(lambda x: x.state != "cancel"): if rec.product_uom_id and line.product_uom != rec.product_uom_id: rec.purchased_qty += line.product_uom._compute_quantity( line.product_qty, rec.product_uom_id ) else: rec.purchased_qty += line.product_qty @api.depends("purchase_lines.state", "purchase_lines.order_id.state") def _compute_purchase_state(self): for rec in self: temp_purchase_state = False if rec.purchase_lines: if any(po_line.state == "done" for po_line in rec.purchase_lines): temp_purchase_state = "done" elif all(po_line.state == "cancel" for po_line in rec.purchase_lines): temp_purchase_state = "cancel" elif any(po_line.state == "purchase" for po_line in rec.purchase_lines): temp_purchase_state = "purchase" elif any( po_line.state == "to approve" for po_line in rec.purchase_lines ): temp_purchase_state = "to approve" elif any(po_line.state == "sent" for po_line in rec.purchase_lines): temp_purchase_state = "sent" elif all( po_line.state in ("draft", "cancel") for po_line in rec.purchase_lines ): temp_purchase_state = "draft" rec.purchase_state = temp_purchase_state @api.model def _get_supplier_min_qty(self, product, partner_id=False): seller_min_qty = 0.0 if partner_id: seller = product.seller_ids.filtered(lambda r: r.name == partner_id).sorted( key=lambda r: r.min_qty ) else: seller = product.seller_ids.sorted(key=lambda r: r.min_qty) if seller: seller_min_qty = seller[0].min_qty return seller_min_qty @api.model def _calc_new_qty(self, request_line, po_line=None, new_pr_line=False): purchase_uom = po_line.product_uom or request_line.product_id.uom_po_id # TODO: Not implemented yet. # Make sure we use the minimum quantity of the partner corresponding # to the PO. This does not apply in case of dropshipping supplierinfo_min_qty = 0.0 if not po_line.order_id.dest_address_id: supplierinfo_min_qty = self._get_supplier_min_qty( po_line.product_id, po_line.order_id.partner_id ) rl_qty = 0.0 # Recompute quantity by adding existing running procurements. if new_pr_line: rl_qty = po_line.product_uom_qty else: for prl in po_line.purchase_request_lines: for alloc in prl.purchase_request_allocation_ids: rl_qty += alloc.product_uom_id._compute_quantity( alloc.requested_product_uom_qty, purchase_uom ) qty = max(rl_qty, supplierinfo_min_qty) return qty def _can_be_deleted(self): self.ensure_one() return self.request_state == "draft" def unlink(self): if self.mapped("purchase_lines"): raise UserError( _("You cannot delete a record that refers to purchase lines!") ) for line in self: if not line._can_be_deleted(): raise UserError( _( "You can only delete a purchase request line " "if the purchase request is in draft state." ) ) return super(PurchaseRequestLine, self).unlink() def action_show_details(self): self.ensure_one() view = self.env.ref("purchase_request.view_purchase_request_line_details") return { "name": _("Detailed Line"), "type": "ir.actions.act_window", "view_mode": "form", "res_model": "purchase.request.line", "views": [(view.id, "form")], "view_id": view.id, "target": "new", "res_id": self.id, "context": dict( self.env.context, ), }
36.002421
14,869
5,109
py
PYTHON
15.0
# Copyright 2017 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl-3.0) from odoo import _, api, models class StockMoveLine(models.Model): _inherit = "stock.move.line" @api.model def _purchase_request_confirm_done_message_content(self, message_data): title = _( "Receipt confirmation %(picking_name)s for your Request %(request_name)s" ) % { "picking_name": message_data["picking_name"], "request_name": message_data["request_name"], } message = "<h3>%s</h3>" % title message += _( "The following requested items from Purchase Request %(request_name)s " "have now been received in %(location_name)s using Picking %(picking_name)s:" ) % { "request_name": message_data["request_name"], "location_name": message_data["location_name"], "picking_name": message_data["picking_name"], } message += "<ul>" message += _( "<li><b>%(product_name)s</b>: " "Transferred quantity %(product_qty)s %(product_uom)s</li>" ) % { "product_name": message_data["product_name"], "product_qty": message_data["product_qty"], "product_uom": message_data["product_uom"], } message += "</ul>" return message @api.model def _picking_confirm_done_message_content(self, message_data): title = _("Receipt confirmation for Request %s") % ( message_data["request_name"] ) message = "<h3>%s</h3>" % title message += _( "The following requested items from Purchase Request %(request_name)s " "requested by %(requestor)s " "have now been received in %(location_name)s:" ) % { "request_name": message_data["request_name"], "requestor": message_data["requestor"], "location_name": message_data["location_name"], } message += "<ul>" message += _( "<li><b>%(product_name)s</b>: " "Transferred quantity %(product_qty)s %(product_uom)s</li>" ) % { "product_name": message_data["product_name"], "product_qty": message_data["product_qty"], "product_uom": message_data["product_uom"], } message += "</ul>" return message def _prepare_message_data(self, ml, request, allocated_qty): return { "request_name": request.name, "picking_name": ml.picking_id.name, "product_name": ml.product_id.name_get()[0][1], "product_qty": allocated_qty, "product_uom": ml.product_uom_id.name, "location_name": ml.location_dest_id.name_get()[0][1], "requestor": request.requested_by.partner_id.name, } def allocate(self): for ml in self.filtered( lambda m: m.exists() and m.move_id.purchase_request_allocation_ids ): # We do sudo because potentially the user that completes the move # may not have permissions for purchase.request. to_allocate_qty = ml.qty_done to_allocate_uom = ml.product_uom_id for allocation in ml.move_id.purchase_request_allocation_ids.sudo(): allocated_qty = 0.0 if allocation.open_product_qty and to_allocate_qty: to_allocate_uom_qty = to_allocate_uom._compute_quantity( to_allocate_qty, allocation.product_uom_id ) allocated_qty = min( allocation.open_product_qty, to_allocate_uom_qty ) allocation.allocated_product_qty += allocated_qty to_allocate_uom_qty -= allocated_qty to_allocate_qty = allocation.product_uom_id._compute_quantity( to_allocate_uom_qty, to_allocate_uom ) request = allocation.purchase_request_line_id.request_id if allocated_qty: message_data = self._prepare_message_data( ml, request, allocated_qty ) message = self._purchase_request_confirm_done_message_content( message_data ) request.message_post( body=message, subtype_id=self.env.ref("mail.mt_comment").id ) picking_message = self._picking_confirm_done_message_content( message_data ) ml.move_id.picking_id.message_post( body=picking_message, subtype_id=self.env.ref("mail.mt_comment").id, ) allocation._compute_open_product_qty() def _action_done(self): res = super(StockMoveLine, self)._action_done() self.allocate() return res
40.547619
5,109
792
py
PYTHON
15.0
# Copyright 2018-2019 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl-3.0) from odoo import models class Orderpoint(models.Model): _inherit = "stock.warehouse.orderpoint" def _quantity_in_progress(self): res = super(Orderpoint, self)._quantity_in_progress() for prline in self.env["purchase.request.line"].search( [ ("request_id.state", "in", ("draft", "approved", "to_approve")), ("orderpoint_id", "in", self.ids), ("purchase_state", "=", False), ] ): res[prline.orderpoint_id.id] += prline.product_uom_id._compute_quantity( prline.product_qty, prline.orderpoint_id.product_uom, round=False ) return res
36
792
9,142
py
PYTHON
15.0
# Copyright 2018-2019 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl-3.0) from odoo import _, api, exceptions, fields, models class PurchaseOrder(models.Model): _inherit = "purchase.order" def _purchase_request_confirm_message_content(self, request, request_dict=None): self.ensure_one() if not request_dict: request_dict = {} title = _("Order confirmation %(po_name)s for your Request %(pr_name)s") % { "po_name": self.name, "pr_name": request.name, } message = "<h3>%s</h3><ul>" % title message += _( "The following requested items from Purchase Request %(pr_name)s " "have now been confirmed in Purchase Order %(po_name)s:" ) % { "po_name": self.name, "pr_name": request.name, } for line in request_dict.values(): message += _( "<li><b>%(prl_name)s</b>: Ordered quantity %(prl_qty)s %(prl_uom)s, " "Planned date %(prl_date_planned)s</li>" ) % { "prl_name": line["name"], "prl_qty": line["product_qty"], "prl_uom": line["product_uom"], "prl_date_planned": line["date_planned"], } message += "</ul>" return message def _purchase_request_confirm_message(self): request_obj = self.env["purchase.request"] for po in self: requests_dict = {} for line in po.order_line: for request_line in line.sudo().purchase_request_lines: request_id = request_line.request_id.id if request_id not in requests_dict: requests_dict[request_id] = {} date_planned = "%s" % line.date_planned data = { "name": request_line.name, "product_qty": line.product_qty, "product_uom": line.product_uom.name, "date_planned": date_planned, } requests_dict[request_id][request_line.id] = data for request_id in requests_dict: request = request_obj.sudo().browse(request_id) message = po._purchase_request_confirm_message_content( request, requests_dict[request_id] ) request.message_post( body=message, subtype_id=self.env.ref("mail.mt_comment").id ) return True def _purchase_request_line_check(self): for po in self: for line in po.order_line: for request_line in line.purchase_request_lines: if request_line.sudo().purchase_state == "done": raise exceptions.UserError( _("Purchase Request %s has already been completed") % (request_line.request_id.name) ) return True def button_confirm(self): self._purchase_request_line_check() res = super(PurchaseOrder, self).button_confirm() self._purchase_request_confirm_message() return res def unlink(self): alloc_to_unlink = self.env["purchase.request.allocation"] for rec in self: for alloc in ( rec.order_line.mapped("purchase_request_lines") .mapped("purchase_request_allocation_ids") .filtered(lambda alloc: alloc.purchase_line_id.order_id.id == rec.id) ): alloc_to_unlink += alloc res = super().unlink() alloc_to_unlink.unlink() return res class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" purchase_request_lines = fields.Many2many( comodel_name="purchase.request.line", relation="purchase_request_purchase_order_line_rel", column1="purchase_order_line_id", column2="purchase_request_line_id", readonly=True, copy=False, ) purchase_request_allocation_ids = fields.One2many( comodel_name="purchase.request.allocation", inverse_name="purchase_line_id", string="Purchase Request Allocation", copy=False, ) def action_open_request_line_tree_view(self): """ :return dict: dictionary value for created view """ request_line_ids = [] for line in self: request_line_ids += line.purchase_request_lines.ids domain = [("id", "in", request_line_ids)] return { "name": _("Purchase Request Lines"), "type": "ir.actions.act_window", "res_model": "purchase.request.line", "view_mode": "tree,form", "domain": domain, } def _prepare_stock_moves(self, picking): self.ensure_one() val = super(PurchaseOrderLine, self)._prepare_stock_moves(picking) all_list = [] for v in val: all_ids = self.env["purchase.request.allocation"].search( [("purchase_line_id", "=", v["purchase_line_id"])] ) for all_id in all_ids: all_list.append((4, all_id.id)) v["purchase_request_allocation_ids"] = all_list return val def update_service_allocations(self, prev_qty_received): for rec in self: allocation = self.env["purchase.request.allocation"].search( [ ("purchase_line_id", "=", rec.id), ("purchase_line_id.product_id.type", "=", "service"), ] ) if not allocation: return qty_left = rec.qty_received - prev_qty_received for alloc in allocation: allocated_product_qty = alloc.allocated_product_qty if not qty_left: alloc.purchase_request_line_id._compute_qty() break if alloc.open_product_qty <= qty_left: allocated_product_qty += alloc.open_product_qty qty_left -= alloc.open_product_qty alloc._notify_allocation(alloc.open_product_qty) else: allocated_product_qty += qty_left alloc._notify_allocation(qty_left) qty_left = 0 alloc.write({"allocated_product_qty": allocated_product_qty}) message_data = self._prepare_request_message_data( alloc, alloc.purchase_request_line_id, allocated_product_qty ) message = self._purchase_request_confirm_done_message_content( message_data ) alloc.purchase_request_line_id.request_id.message_post( body=message, subtype_id=self.env.ref("mail.mt_comment").id ) alloc.purchase_request_line_id._compute_qty() return True @api.model def _purchase_request_confirm_done_message_content(self, message_data): title = _("Service confirmation for Request %s") % ( message_data["request_name"] ) message = "<h3>%s</h3>" % title message += _( "The following requested services from Purchase" " Request %(request_name)s requested by %(requestor)s " "have now been received:" ) % { "request_name": message_data["request_name"], "requestor": message_data["requestor"], } message += "<ul>" message += _( "<li><b>%(product_name)s</b>: " "Received quantity %(product_qty)s %(product_uom)s</li>" ) % { "product_name": message_data["product_name"], "product_qty": message_data["product_qty"], "product_uom": message_data["product_uom"], } message += "</ul>" return message def _prepare_request_message_data(self, alloc, request_line, allocated_qty): return { "request_name": request_line.request_id.name, "product_name": request_line.product_id.name_get()[0][1], "product_qty": allocated_qty, "product_uom": alloc.product_uom_id.name, "requestor": request_line.request_id.requested_by.partner_id.name, } def write(self, vals): # As services do not generate stock move this tweak is required # to allocate them. prev_qty_received = {} if vals.get("qty_received", False): service_lines = self.filtered(lambda l: l.product_id.type == "service") for line in service_lines: prev_qty_received[line.id] = line.qty_received res = super(PurchaseOrderLine, self).write(vals) if prev_qty_received: for line in service_lines: line.update_service_allocations(prev_qty_received[line.id]) return res
39.068376
9,142
424
py
PYTHON
15.0
# Copyright 2018-2019 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl-3.0) from odoo import fields, models class ProductTemplate(models.Model): _inherit = "product.template" purchase_request = fields.Boolean( help="Check this box to generate Purchase Request instead of " "generating Requests For Quotation from procurement.", company_dependent=True, )
30.285714
424
5,043
py
PYTHON
15.0
# Copyright 2018-2019 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl-3.0) from odoo import _, api, fields, models from odoo.exceptions import ValidationError class StockMove(models.Model): _inherit = "stock.move" created_purchase_request_line_id = fields.Many2one( comodel_name="purchase.request.line", string="Created Purchase Request Line", ondelete="set null", readonly=True, copy=False, index=True, ) purchase_request_allocation_ids = fields.One2many( comodel_name="purchase.request.allocation", inverse_name="stock_move_id", copy=False, string="Purchase Request Allocation", ) purchase_request_ids = fields.One2many( comodel_name="purchase.request", string="Purchase Requests", compute="_compute_purchase_request_ids", ) @api.model def _prepare_merge_moves_distinct_fields(self): distinct_fields = super(StockMove, self)._prepare_merge_moves_distinct_fields() distinct_fields += ["created_purchase_request_line_id"] return distinct_fields @api.model def _prepare_merge_move_sort_method(self, move): move.ensure_one() keys_sorted = super(StockMove, self)._prepare_merge_move_sort_method(move) keys_sorted += [ move.purchase_line_id.id, move.created_purchase_request_line_id.id, ] return keys_sorted def _action_cancel(self): for move in self: if move.created_purchase_request_line_id: try: activity_type_id = self.env.ref("mail.mail_activity_data_todo").id except ValueError: activity_type_id = False pr_line = move.created_purchase_request_line_id self.env["mail.activity"].sudo().create( { "activity_type_id": activity_type_id, "note": _( "A sale/manufacturing order that generated this " "purchase request has been cancelled/deleted. " "Check if an action is needed." ), "user_id": pr_line.product_id.responsible_id.id, "res_id": pr_line.request_id.id, "res_model_id": self.env.ref( "purchase_request.model_purchase_request" ).id, } ) return super(StockMove, self)._action_cancel() @api.depends("purchase_request_allocation_ids") def _compute_purchase_request_ids(self): for rec in self: rec.purchase_request_ids = rec.purchase_request_allocation_ids.mapped( "purchase_request_id" ) def _merge_moves_fields(self): res = super(StockMove, self)._merge_moves_fields() res["purchase_request_allocation_ids"] = [ (4, m.id) for m in self.mapped("purchase_request_allocation_ids") ] return res @api.constrains("company_id") def _check_company_purchase_request(self): if not self.ids: return self.env.cr.execute( """ SELECT 1 FROM purchase_request_allocation pra INNER JOIN stock_move sm ON sm.id=pra.stock_move_id WHERE pra.company_id != sm.company_id AND sm.id IN %s LIMIT 1 """, (tuple(self.ids),), ) if self.env.cr.fetchone(): raise ValidationError( _( "The company of the purchase request must match with " "that of the location." ) ) def copy_data(self, default=None): if not default: default = {} if "allocation_ids" not in default: default["purchase_request_allocation_ids"] = [] first_it = True for alloc in self.purchase_request_allocation_ids.filtered( lambda al: al.requested_product_uom_qty > al.allocated_product_qty ): qty_done = sum(alloc.stock_move_id.mapped("move_line_ids.qty_done")) if first_it: qty_left = qty_done first_it = False if qty_left >= alloc.open_product_qty: qty_left = qty_done - alloc.open_product_qty continue else: open_qty = alloc.open_product_qty - qty_left default["purchase_request_allocation_ids"].append( ( 0, 0, { "purchase_request_line_id": alloc.purchase_request_line_id.id, "requested_product_uom_qty": open_qty, }, ) ) return super(StockMove, self).copy_data(default)
36.021429
5,043
4,799
py
PYTHON
15.0
# Copyright 2018-2020 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl-3.0) from odoo import api, fields, models class StockRule(models.Model): _inherit = "stock.rule" @api.model def _prepare_purchase_request_line(self, request_id, procurement): procurement_uom_po_qty = procurement.product_uom._compute_quantity( procurement.product_qty, procurement.product_id.uom_po_id ) return { "product_id": procurement.product_id.id, "name": procurement.product_id.name, "date_required": "date_planned" in procurement.values and procurement.values["date_planned"] or fields.Datetime.now(), "product_uom_id": procurement.product_id.uom_po_id.id, "product_qty": procurement_uom_po_qty, "request_id": request_id.id, "move_dest_ids": [ (4, x.id) for x in procurement.values.get("move_dest_ids", []) ], "orderpoint_id": procurement.values.get("orderpoint_id", False) and procurement.values.get("orderpoint_id").id, } @api.model def _prepare_purchase_request(self, origin, values): gpo = self.group_propagation_option group_id = ( (gpo == "fixed" and self.group_id.id) or (gpo == "propagate" and values.get("group_id") and values["group_id"].id) or False ) return { "origin": origin, "company_id": values["company_id"].id, "picking_type_id": self.picking_type_id.id, "group_id": group_id or False, } @api.model def _make_pr_get_domain(self, values): """ This method is to be implemented by other modules that can provide a criteria to select the appropriate purchase request to be extended. :return: False """ domain = ( ("state", "=", "draft"), ("picking_type_id", "=", self.picking_type_id.id), ("company_id", "=", values["company_id"].id), ) gpo = self.group_propagation_option group_id = ( (gpo == "fixed" and self.group_id.id) or (gpo == "propagate" and values["group_id"].id) or False ) if group_id: domain += (("group_id", "=", group_id),) return domain def is_create_purchase_request_allowed(self, procurement): """ Tell if current procurement order should create a purchase request or not. :return: boolean """ return ( procurement[1].action == "buy" and procurement[0].product_id.purchase_request ) def _run_buy(self, procurements): indexes_to_pop = [] for i, procurement in enumerate(procurements): if self.is_create_purchase_request_allowed(procurement): self.create_purchase_request(procurement) indexes_to_pop.append(i) if indexes_to_pop: indexes_to_pop.reverse() for index in indexes_to_pop: procurements.pop(index) if not procurements: return return super(StockRule, self)._run_buy(procurements) def create_purchase_request(self, procurement_group): """ Create a purchase request containing procurement order product. """ procurement = procurement_group[0] rule = procurement_group[1] purchase_request_model = self.env["purchase.request"] purchase_request_line_model = self.env["purchase.request.line"] cache = {} pr = self.env["purchase.request"] domain = rule._make_pr_get_domain(procurement.values) if domain in cache: pr = cache[domain] elif domain: pr = self.env["purchase.request"].search([dom for dom in domain]) pr = pr[0] if pr else False cache[domain] = pr if not pr: request_data = rule._prepare_purchase_request( procurement.origin, procurement.values ) pr = purchase_request_model.create(request_data) cache[domain] = pr elif not pr.origin or procurement.origin not in pr.origin.split(", "): if pr.origin: if procurement.origin: pr.write({"origin": pr.origin + ", " + procurement.origin}) else: pr.write({"origin": pr.origin}) else: pr.write({"origin": procurement.origin}) # Create Line request_line_data = rule._prepare_purchase_request_line(pr, procurement) purchase_request_line_model.create(request_line_data)
37.787402
4,799
4,460
py
PYTHON
15.0
# Copyright 2019 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl-3.0) from odoo import _, api, fields, models class PurchaseRequestAllocation(models.Model): _name = "purchase.request.allocation" _description = "Purchase Request Allocation" purchase_request_line_id = fields.Many2one( string="Purchase Request Line", comodel_name="purchase.request.line", required=True, ondelete="cascade", copy=True, index=True, ) company_id = fields.Many2one( string="Company", comodel_name="res.company", readonly=True, related="purchase_request_line_id.request_id.company_id", store=True, index=True, ) stock_move_id = fields.Many2one( string="Stock Move", comodel_name="stock.move", ondelete="cascade", index=True, ) purchase_line_id = fields.Many2one( string="Purchase Line", comodel_name="purchase.order.line", copy=True, ondelete="cascade", help="Service Purchase Order Line", index=True, ) product_id = fields.Many2one( string="Product", comodel_name="product.product", related="purchase_request_line_id.product_id", readonly=True, ) product_uom_id = fields.Many2one( string="UoM", comodel_name="uom.uom", related="purchase_request_line_id.product_uom_id", readonly=True, required=True, ) requested_product_uom_qty = fields.Float( string="Requested Quantity", help="Quantity of the purchase request line allocated to the" "stock move, in the UoM of the Purchase Request Line", ) allocated_product_qty = fields.Float( string="Allocated Quantity", copy=False, help="Quantity of the purchase request line allocated to the stock" "move, in the default UoM of the product", ) open_product_qty = fields.Float( string="Open Quantity", compute="_compute_open_product_qty" ) purchase_state = fields.Selection(related="purchase_line_id.state") @api.depends( "requested_product_uom_qty", "allocated_product_qty", "stock_move_id", "stock_move_id.state", "stock_move_id.product_uom_qty", "stock_move_id.move_line_ids.qty_done", "purchase_line_id", "purchase_line_id.qty_received", "purchase_state", ) def _compute_open_product_qty(self): for rec in self: if rec.purchase_state in ["cancel", "done"]: rec.open_product_qty = 0.0 else: rec.open_product_qty = ( rec.requested_product_uom_qty - rec.allocated_product_qty ) if rec.open_product_qty < 0.0: rec.open_product_qty = 0.0 @api.model def _purchase_request_confirm_done_message_content(self, message_data): message = "" message += _( "From last reception this quantity has been " "allocated to this purchase request" ) message += "<ul>" message += _( "<li><b>%(product_name)s</b>: " "Received quantity %(product_qty)s %(product_uom)s</li>" ) % { "product_name": message_data["product_name"], "product_qty": message_data["product_qty"], "product_uom": message_data["product_uom"], } message += "</ul>" return message def _prepare_message_data(self, po_line, request, allocated_qty): return { "request_name": request.name, "po_name": po_line.order_id.name, "product_name": po_line.product_id.name_get()[0][1], "product_qty": allocated_qty, "product_uom": po_line.product_uom.name, } def _notify_allocation(self, allocated_qty): if not allocated_qty: return for allocation in self: request = allocation.purchase_request_line_id.request_id po_line = allocation.purchase_line_id message_data = self._prepare_message_data(po_line, request, allocated_qty) message = self._purchase_request_confirm_done_message_content(message_data) request.message_post( body=message, subtype_id=self.env.ref("mail.mt_comment").id )
33.787879
4,460
672
py
PYTHON
15.0
# Copyright 2014-2016 Numérigraphe SARL # Copyright 2017 ForgeFlow, S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Purchase Delivery Split Date", "version": "15.0.1.0.0", "summary": "Allows Purchase Order you confirm to generate one Incoming " "Shipment for each expected date indicated in the Purchase Order Lines", "author": "Numerigraphe, ForgeFlow, Camptocamp, Odoo Community Association (OCA)", "website": "https://github.com/OCA/purchase-workflow", "category": "Purchase Management", "license": "AGPL-3", "depends": ["purchase_stock"], "installable": True, "application": False, }
39.470588
671
9,258
py
PYTHON
15.0
# Copyright 2014-2016 Numérigraphe SARL # Copyright 2017 ForgeFlow, S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo.tests.common import TransactionCase class TestDeliverySingle(TransactionCase): def setUp(self): super(TestDeliverySingle, self).setUp() self.product_model = self.env["product.product"] # Create products: p1 = self.product1 = self.product_model.create( { "name": "Test Product 1", "type": "product", "default_code": "PROD1", "standard_price": 10, } ) p2 = self.product2 = self.product_model.create( { "name": "Test Product 2", "type": "product", "default_code": "PROD2", "standard_price": 10, } ) self.p3 = self.product2 = self.product_model.create( { "name": "Test Product 3", "type": "product", "default_code": "PROD3", "standard_price": 10, } ) # Two dates which we can use to test the features: self.date_sooner = "2015-01-01" self.date_later = "2015-12-13" self.date_3rd = "2015-12-31" self.po = self.env["purchase.order"].create( { "partner_id": self.ref("base.res_partner_3"), "order_line": [ ( 0, 0, { "product_id": p1.id, "product_uom": p1.uom_id.id, "name": p1.name, "price_unit": p1.standard_price, "date_planned": self.date_sooner, "product_qty": 42.0, }, ), ( 0, 0, { "product_id": p2.id, "product_uom": p2.uom_id.id, "name": p2.name, "price_unit": p2.standard_price, "date_planned": self.date_sooner, "product_qty": 12.0, }, ), ( 0, 0, { "product_id": p1.id, "product_uom": p1.uom_id.id, "name": p1.name, "price_unit": p1.standard_price, "date_planned": self.date_sooner, "product_qty": 1.0, }, ), ], } ) def test_check_single_date(self): """Tests with single date.""" self.assertEqual( len(self.po.picking_ids), 0, "There must not be pickings for the PO when draft", ) self.po.button_confirm() self.assertEqual( len(self.po.picking_ids), 1, "There must be 1 picking for the PO when confirmed", ) self.assertEqual( str(self.po.picking_ids[0].scheduled_date)[:10], self.date_sooner, "The picking must be planned at the expected date", ) def test_check_multiple_dates(self): """Tests changing the date of the first line.""" self.po.order_line[0].date_planned = self.date_later self.assertEqual( len(self.po.picking_ids), 0, "There must not be pickings for the PO when draft", ) self.po.button_confirm() self.assertEqual( len(self.po.picking_ids), 2, "There must be 2 pickings for the PO when confirmed. %s found" % len(self.po.picking_ids), ) sorted_pickings = sorted(self.po.picking_ids, key=lambda x: x.scheduled_date) self.assertEqual( str(sorted_pickings[0].scheduled_date)[:10], self.date_sooner, "The first picking must be planned at the soonest date", ) self.assertEqual( str(sorted_pickings[1].scheduled_date)[:10], self.date_later, "The second picking must be planned at the latest date", ) def test_purchase_line_date_change(self): self.po.order_line[0].date_planned = self.date_later self.po.button_confirm() moves = self.env["stock.move"].search( [("purchase_line_id", "=", self.po.order_line[0].id)] ) line = self.po.order_line[0] line.write({"date_planned": self.date_3rd}) self.assertEqual(moves.date_deadline.strftime("%Y-%m-%d"), self.date_3rd) def test_group_multiple_picking_same_date(self): """Check multiple picking with same planned date are also merged This can happen if another module changes the picking planned date before the _check_split_pickings is being called from the write method. """ self.po.order_line[0].date_planned = self.date_later self.po.button_confirm() moves = self.env["stock.move"].search( [("purchase_line_id", "in", self.po.order_line.ids)] ) pickings = moves.mapped("picking_id") self.assertEqual(len(pickings), 2) pickings[1].scheduled_date = pickings[0].scheduled_date self.po.order_line[0].date_planned = self.date_sooner self.assertEqual(len(moves.mapped("picking_id")), 1) self.assertEqual(len(pickings.filtered(lambda r: r.state == "cancel")), 1) def test_purchase_line_date_change_split_picking(self): self.po.button_confirm() line1 = self.po.order_line[0] line2 = self.po.order_line[1] move1 = self.env["stock.move"].search([("purchase_line_id", "=", line1.id)]) move2 = self.env["stock.move"].search([("purchase_line_id", "=", line2.id)]) line1.write({"date_planned": self.date_later}) self.assertEqual( len(self.po.picking_ids), 2, "There must be 2 pickings when I change the date", ) self.assertEqual(move1.date_deadline.strftime("%Y-%m-%d"), self.date_later) self.assertEqual(move2.date_deadline.strftime("%Y-%m-%d"), self.date_sooner) self.assertNotEqual(move1.picking_id, move2.picking_id) line2.write({"date_planned": self.date_later}) self.assertEqual( move1.picking_id, move2.picking_id, "If I change the other line to the same date as the first, " "both moves must be in the same picking", ) def test_purchase_line_created_afer_confirm(self): """Check new line created when order is confirmed. When a new line is added on an already `purchased` order If it is planned for a non yet existing date in the purchase, a new picking should be created. """ self.po.button_confirm() self.assertEqual(self.po.state, "purchase") new_date = "2016-01-30" moves_before = self.env["stock.move"].search( [("purchase_line_id", "in", self.po.order_line.ids)] ) self.assertEqual(len(moves_before.mapped("picking_id")), 1) self.po.order_line = [ ( 0, 0, { "product_id": self.p3.id, "product_uom": self.p3.uom_id.id, "name": self.p3.name, "price_unit": self.p3.standard_price, "date_planned": new_date, "product_qty": 2.0, }, ), ] moves_after = self.env["stock.move"].search( [("purchase_line_id", "in", self.po.order_line.ids)] ) self.assertEqual(len(moves_after.mapped("picking_id")), 2) def test_purchase_line_date_change_tz_aware(self): """Check that the grouping is time zone aware. Datetime are always stored in utc in the database. """ self.po.order_line[2].unlink() self.po.button_confirm() line1 = self.po.order_line[0] line2 = self.po.order_line[1] self.env.user.tz = "Europe/Brussels" self.assertEqual(len(self.po.picking_ids), 1) line1.write({"date_planned": "2021-05-05 03:00:00"}) self.assertEqual(len(self.po.picking_ids), 2) # Time difference of at least +1 so should be same day (1 picking) line2.write({"date_planned": "2021-05-04 23:00:00"}) self.assertEqual(len(self.po.picking_ids), 1) self.env.user.tz = "Etc/UTC" line1.write({"date_planned": "2021-05-05 03:00:00"}) self.assertEqual(len(self.po.picking_ids), 2) # No time difference so will be another day (2 pickings) line2.write({"date_planned": "2021-05-04 23:00:00"}) self.assertEqual(len(self.po.picking_ids), 2)
37.938525
9,257
6,424
py
PYTHON
15.0
# Copyright 2014-2016 Numérigraphe SARL # Copyright 2017 ForgeFlow, S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from itertools import groupby from odoo import api, fields, models class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" @api.model def _get_group_keys(self, order, line, picking=False): """Define the key that will be used to group. The key should be defined as a tuple of dictionaries, with each element containing a dictionary element with the field that you want to group by. This method is designed for extensibility, so that other modules can add additional keys or replace them by others.""" date = fields.Date.context_today(self.env.user, line.date_planned) # Split date value to obtain only the attributes year, month and day key = ({"date_planned": fields.Date.to_string(date)},) return key @api.model def _first_picking_copy_vals(self, key, lines): """The data to be copied to new pickings is updated with data from the grouping key. This method is designed for extensibility, so that other modules can store more data based on new keys.""" vals = {"move_lines": []} for key_element in key: if "date_planned" in key_element.keys(): vals["scheduled_date"] = key_element["date_planned"] return vals def _get_sorted_keys(self, line): """Return a tuple of keys to use in order to sort the order lines. This method is designed for extensibility, so that other modules can add additional keys or replace them by others.""" return (line.date_planned,) def _create_stock_moves(self, picking): """Group the receptions in one picking per group key""" moves = self.env["stock.move"] # Group the order lines by group key order_lines = sorted( self.filtered(lambda l: not l.display_type), key=lambda l: self._get_sorted_keys(l), ) date_groups = groupby( order_lines, lambda l: self._get_group_keys(l.order_id, l, picking=picking) ) first_picking = False # If a picking is provided, use it for the first group only if picking: first_picking = picking key, lines = next(date_groups) po_lines = self.env["purchase.order.line"] for line in list(lines): po_lines += line picking._update_picking_from_group_key(key) moves += super(PurchaseOrderLine, po_lines)._create_stock_moves( first_picking ) for key, lines in date_groups: # If a picking is provided, clone it for each key for modularity if picking: copy_vals = self._first_picking_copy_vals(key, lines) picking = first_picking.copy(copy_vals) po_lines = self.env["purchase.order.line"] for line in list(lines): po_lines += line moves += super(PurchaseOrderLine, po_lines)._create_stock_moves(picking) return moves def write(self, values): res = super().write(values) if "date_planned" in values: self.mapped("order_id")._check_split_pickings() return res def create(self, values): line = super().create(values) if line.order_id.state == "purchase": line.order_id._check_split_pickings() return line @api.onchange("product_qty", "product_uom") def _onchange_quantity(self): date_planned = self.date_planned res = super()._onchange_quantity() # preserve the date which was presumably set on the PO line if it is # later than the date computed from the Vendor information if date_planned and self.date_planned <= date_planned: self.date_planned = date_planned return res class PurchaseOrder(models.Model): _inherit = "purchase.order" def _check_split_pickings(self): for order in self: moves = self.env["stock.move"].search( [ ("purchase_line_id", "in", order.order_line.ids), ("state", "not in", ("cancel", "done")), ] ) pickings = moves.mapped("picking_id") pickings_by_date = {} for pick in pickings: pickings_by_date[pick.scheduled_date.date()] = pick order_lines = moves.mapped("purchase_line_id") date_groups = groupby( order_lines, lambda l: l._get_group_keys(l.order_id, l) ) for key, lines in date_groups: date_key = fields.Date.from_string(key[0]["date_planned"]) for line in lines: for move in line.move_ids: if move.state in ("cancel", "done"): continue if ( move.picking_id.scheduled_date.date() != date_key or pickings_by_date[date_key] != move.picking_id ): if date_key not in pickings_by_date: copy_vals = line._first_picking_copy_vals(key, line) new_picking = move.picking_id.copy(copy_vals) pickings_by_date[date_key] = new_picking move._do_unreserve() move.picking_id = pickings_by_date[date_key] move.date_deadline = date_key move._action_assign() for picking in pickings: if len(picking.move_lines) == 0: picking.write({"state": "cancel"}) class StockPicking(models.Model): _inherit = "stock.picking" def _update_picking_from_group_key(self, key): """The picking is updated with data from the grouping key. This method is designed for extensibility, so that other modules can store more data based on new keys.""" for rec in self: for key_element in key: if "date_planned" in key_element.keys(): rec.date = key_element["date_planned"] return False
41.43871
6,423
1,977
py
PYTHON
15.0
# Copyright 2020 Opener B.V. <https://opener.amsterdam> # Copyright 2020 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from psycopg2 import sql def pre_init_hook(cr): """Precreate financial_type and fill with appropriate values to prevent a MemoryError when the ORM attempts to call its compute method on a large amount of preexisting moves. Note that the order of the mapping is important as one move can have move lines on accounts of multiple types and the move type is set in the order of precedence.""" logger = logging.getLogger(__name__) logger.info("Add account_move.financial_type column if it does not yet exist") cr.execute( "ALTER TABLE account_move ADD COLUMN IF NOT EXISTS financial_type VARCHAR" ) MAPPING = [ ("liquidity", "liquidity", False), ("payable", "payable", "AND aml.balance < 0"), ("payable_refund", "payable", "AND aml.balance >= 0"), ("receivable", "receivable", "AND aml.balance > 0"), ("receivable_refund", "receivable", "AND aml.balance <= 0"), ("other", False, False), ] for financial_type, internal_type, extra_where in MAPPING: args = [financial_type] query = sql.SQL("UPDATE account_move am SET financial_type = %s") if internal_type: query += sql.SQL( """FROM account_move_line aml WHERE aml.account_id IN ( SELECT id FROM account_account WHERE internal_type = %s) AND aml.move_id = am.id AND am.financial_type IS NULL """ ) args.append(internal_type) else: query += sql.SQL("WHERE am.financial_type IS NULL") if extra_where: query += sql.SQL(extra_where) cr.execute(query, tuple(args)) logger.info("%s move set to type %s", financial_type, cr.rowcount)
42.978261
1,977
994
py
PYTHON
15.0
# Copyright 2016 Lorenzo Battistini - Agile Business Group # Copyright 2016 Tecnativa - Antonio Espinosa # Copyright 2016 ACSONE SA/NV - Stéphane Bidoul # Copyright 2017 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Tax Balance", "summary": "Compute tax balances based on date range", "version": "15.0.1.1.0", "development_status": "Mature", "category": "Invoices & Payments", "website": "https://github.com/OCA/account-financial-reporting", "author": "Agile Business Group, Therp BV, Tecnativa, ACSONE SA/NV, " "Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "depends": ["account", "date_range"], "data": [ "wizard/open_tax_balances_view.xml", "views/account_move_view.xml", "views/account_tax_view.xml", "security/ir.model.access.csv", ], "images": ["images/tax_balance.png"], "pre_init_hook": "pre_init_hook", }
38.192308
993
10,940
py
PYTHON
15.0
# Copyright 2016 Lorenzo Battistini - Agile Business Group # Copyright 2016 Giovanni Capalbo <giovanni@therp.nl> # Copyright 2019 Andrea Stirpe <a.stirpe@onestein.nl> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from datetime import datetime, timedelta from dateutil.rrule import MONTHLY import odoo from odoo import fields from odoo.fields import Date from odoo.tests.common import HttpCase from odoo.addons.account.tests.common import AccountTestInvoicingCommon @odoo.tests.tagged("post_install", "-at_install") class TestAccountTaxBalance(HttpCase): def setUp(self): super().setUp() self.company = self.env.user.company_id self.range_type = self.env["date.range.type"].create( {"name": "Fiscal year", "allow_overlap": False} ) self.range_generator = self.env["date.range.generator"] self.current_year = datetime.now().year self.current_month = datetime.now().month range_generator = self.range_generator.create( { "date_start": "%s-01-01" % self.current_year, "name_prefix": "%s-" % self.current_year, "type_id": self.range_type.id, "duration_count": 1, "unit_of_time": str(MONTHLY), "count": 12, } ) range_generator.action_apply() self.range = self.env["date.range"] def test_tax_balance(self): previous_taxes_ids = ( self.env["account.tax"].search([("has_moves", "=", True)]).ids ) tax_account_id = ( self.env["account.account"] .create( { "name": "Tax Paid", "code": "TAXTEST", "user_type_id": self.env.ref( "account.data_account_type_current_liabilities" ).id, } ) .id ) tax = self.env["account.tax"].create( {"name": "Tax 10.0%", "amount": 10.0, "amount_type": "percent"} ) invoice_line_account_id = ( self.env["account.account"] .create( { "user_type_id": self.env.ref( "account.data_account_type_expenses" ).id, "code": "EXPTEST", "name": "Test expense account", } ) .id ) product = self.env.ref("product.product_product_4") invoice = self.env["account.move"].create( { "partner_id": self.env.ref("base.res_partner_2").id, "move_type": "out_invoice", "invoice_line_ids": [ ( 0, None, { "product_id": product.id, "quantity": 1.0, "price_unit": 100.0, "name": "product that cost 100", "account_id": invoice_line_account_id, "tax_ids": [(6, 0, [tax.id])], }, ) ], } ) invoice._onchange_invoice_line_ids() invoice._convert_to_write(invoice._cache) self.assertEqual(invoice.state, "draft") # change the state of invoice to open by clicking Validate button invoice.action_post() self.assertEqual(tax.base_balance, 100.0) self.assertEqual(tax.balance, 10.0) self.assertEqual(tax.base_balance_regular, 100.0) self.assertEqual(tax.balance_regular, 10.0) self.assertEqual(tax.base_balance_refund, 0.0) self.assertEqual(tax.balance_refund, 0.0) # testing wizard current_range = self.range.search( [ ( "date_start", "=", "{}-{}-01".format(self.current_year, self.current_month), ) ] ) wizard = self.env["wizard.open.tax.balances"].new({}) self.assertFalse(wizard.from_date) self.assertFalse(wizard.to_date) wizard = self.env["wizard.open.tax.balances"].new( {"date_range_id": current_range[0].id} ) self.assertEqual(wizard.from_date, current_range[0].date_start) self.assertEqual(wizard.to_date, current_range[0].date_end) action = wizard.open_taxes() self.assertEqual(action["context"]["from_date"], current_range[0].date_start) self.assertEqual(action["context"]["to_date"], current_range[0].date_end) # exercise search has_moves = True taxes = self.env["account.tax"].search( [("has_moves", "=", True), ("id", "not in", previous_taxes_ids)] ) self.assertEqual(len(taxes), 1) self.assertEqual(taxes[0].name, "Tax 10.0%") # testing buttons tax_action = tax.view_tax_lines() base_action = tax.view_base_lines() tax_action_move_lines = self.env["account.move.line"].search( tax_action["domain"] ) self.assertTrue(invoice.line_ids & tax_action_move_lines) self.assertEqual(tax_action["xml_id"], "account.action_account_moves_all_tree") base_action_move_lines = self.env["account.move.line"].search( base_action["domain"] ) self.assertTrue(invoice.line_ids & base_action_move_lines) self.assertEqual(base_action["xml_id"], "account.action_account_moves_all_tree") # test specific method state_list = tax.get_target_state_list(target_move="all") self.assertEqual(state_list, ["posted", "draft"]) state_list = tax.get_target_state_list(target_move="whatever") self.assertEqual(state_list, []) product = self.env.ref("product.product_product_2") refund = self.env["account.move"].create( { "partner_id": self.env.ref("base.res_partner_2").id, "move_type": "out_refund", "invoice_line_ids": [ ( 0, None, { "product_id": product.id, "quantity": 1.0, "price_unit": 25.0, "name": "returned product that cost 25", "account_id": invoice_line_account_id, "tax_ids": [(6, 0, [tax.id])], }, ) ], } ) refund._onchange_invoice_line_ids() refund._convert_to_write(invoice._cache) self.assertEqual(refund.state, "draft") # change the state of refund to open by clicking Validate button refund.action_post() # force the _compute_balance() to be triggered tax._compute_balance() self.assertEqual(tax.base_balance, 75.0) self.assertEqual(tax.balance, 7.5) self.assertEqual(tax.base_balance_regular, 100.0) self.assertEqual(tax.balance_regular, 10.0) self.assertEqual(tax.base_balance_refund, -25.0) self.assertEqual(tax.balance_refund, -2.5) # Taxes on liquidity type moves are included tax_repartition_line = tax.invoice_repartition_line_ids.filtered( lambda line: line.repartition_type == "tax" ) liquidity_account_id = ( self.env["account.account"] .search( [ ("internal_type", "=", "liquidity"), ("company_id", "=", self.company.id), ], limit=1, ) .id ) move = self.env["account.move"].create( { "move_type": "entry", "date": Date.context_today(self.env.user), "journal_id": self.env["account.journal"] .search( [("type", "=", "bank"), ("company_id", "=", self.company.id)], limit=1, ) .id, "name": "Test move", "line_ids": [ ( 0, 0, { "account_id": liquidity_account_id, "debit": 110, "credit": 0, "name": "Bank Fees", }, ), ( 0, 0, { "account_id": invoice_line_account_id, "debit": 0, "credit": 100, "name": "Bank Fees", "tax_ids": [(4, tax.id)], }, ), ( 0, 0, { "account_id": tax_account_id, "debit": 0, "credit": 10, "name": "Bank Fees", "tax_repartition_line_id": tax_repartition_line.id, }, ), ], } ) move.action_post() tax.refresh() self.assertEqual(tax.base_balance, 175.0) self.assertEqual(tax.balance, 17.5) @odoo.tests.tagged("post_install", "-at_install") class TestInvoicingBalance(AccountTestInvoicingCommon): def test_balance_recomputation(self): """Check that balances are computed correctly for different dates.""" partner = self.partner_a tax = self.tax_sale_a today = fields.Date.today() self.init_invoice( "in_invoice", partner=partner, invoice_date=today, post=True, amounts=[100], taxes=tax, ) tomorrow = today + timedelta(days=1) self.init_invoice( "in_invoice", partner=partner, invoice_date=tomorrow, post=True, amounts=[200], taxes=tax, ) # Check today's balance self.check_date_balance(tax, today, -15) # Check tomorrow's balance self.check_date_balance(tax, tomorrow, -30) def check_date_balance(self, tax, date, balance): """Compare expected balance with tax's balance in specified date.""" tax = tax.with_context( from_date=date, to_date=date, ) self.assertEqual(tax.balance, balance)
35.868852
10,940
2,995
py
PYTHON
15.0
# Copyright 2016 Lorenzo Battistini - Agile Business Group # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models class WizardOpenTaxBalances(models.TransientModel): _name = "wizard.open.tax.balances" _description = "Wizard Open Tax Balances" company_ids = fields.Many2many( comodel_name="res.company", string="Companies", required=True, domain=lambda self: [("id", "in", self.env.companies.ids)], default=lambda self: self.env.companies.ids, ) from_date = fields.Date( required=True, store=True, readonly=False, compute="_compute_date_range" ) to_date = fields.Date( required=True, store=True, readonly=False, compute="_compute_date_range" ) date_range_id = fields.Many2one("date.range") target_move = fields.Selection( [("posted", "All Posted Entries"), ("all", "All Entries")], "Target Moves", required=True, default="posted", ) @api.depends("date_range_id") def _compute_date_range(self): for wizard in self: if wizard.date_range_id: wizard.from_date = wizard.date_range_id.date_start wizard.to_date = wizard.date_range_id.date_end else: wizard.from_date = wizard.to_date = None def open_taxes(self): self.ensure_one() action = self.env.ref("account_tax_balance.action_tax_balances_tree") act_vals = action.sudo().read()[0] # override action name doesn't work in v12 or v10 # we need to build a dynamic action on main keys vals = { x: act_vals[x] for x in act_vals if x in ( "res_model", "view_mode", "domain", "view_id", "search_view_id", "name", "type", ) } lang = self.env["res.lang"].search( [("code", "=", self.env.user.lang or "en_US")] ) date_format = lang and lang.date_format or "%m/%d/%Y" infos = { "name": vals["name"], "target": _(self.target_move), "from": self.from_date.strftime(date_format), "to": self.to_date.strftime(date_format), } # name of action which is displayed in breacrumb vals["name"] = _("%(name)s: %(target)s from %(from)s to %(to)s") % infos multi_cpny_grp = self.env.ref("base.group_multi_company") if multi_cpny_grp in self.env.user.groups_id: company_names = self.company_ids.mapped("name") vals["name"] = "{} ({})".format(vals["name"], ", ".join(company_names)) vals["context"] = { "from_date": self.from_date, "to_date": self.to_date, "target_move": self.target_move, "company_ids": self.company_ids.ids, } return vals
36.084337
2,995
7,953
py
PYTHON
15.0
# Copyright 2016 Lorenzo Battistini - Agile Business Group # Copyright 2016 Antonio Espinosa <antonio.espinosa@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models class AccountTax(models.Model): _inherit = "account.tax" balance = fields.Float(string="Total Balance", compute="_compute_balance") base_balance = fields.Float(string="Total Base Balance", compute="_compute_balance") balance_regular = fields.Float(string="Balance", compute="_compute_balance") base_balance_regular = fields.Float( string="Base Balance", compute="_compute_balance" ) balance_refund = fields.Float(compute="_compute_balance") base_balance_refund = fields.Float(compute="_compute_balance") has_moves = fields.Boolean( string="Has balance in period", compute="_compute_has_moves", search="_search_has_moves", ) def get_context_values(self): context = self.env.context actual_company_id = context.get("company_id", self.env.company.id) return ( context.get("from_date", fields.Date.context_today(self)), context.get("to_date", fields.Date.context_today(self)), context.get("company_ids", [actual_company_id]), context.get("target_move", "posted"), ) def _account_tax_ids_with_moves(self): """Return all account.tax ids for which there is at least one account.move.line in the context period for the user company. Caveat: this ignores record rules and ACL but it is good enough for filtering taxes with activity during the period. """ from_date, to_date, company_ids, _ = self.get_context_values() company_ids = tuple(company_ids) req = """ SELECT id FROM account_tax at WHERE company_id in %s AND EXISTS ( SELECT 1 FROM account_move_Line aml WHERE date >= %s AND date <= %s AND company_id in %s AND ( tax_line_id = at.id OR EXISTS ( SELECT 1 FROM account_move_line_account_tax_rel WHERE account_move_line_id = aml.id AND account_tax_id = at.id ) ) ) """ self.env.cr.execute(req, (company_ids, from_date, to_date, company_ids)) return [r[0] for r in self.env.cr.fetchall()] def _compute_has_moves(self): ids_with_moves = set(self._account_tax_ids_with_moves()) for tax in self: tax.has_moves = tax.id in ids_with_moves @api.model def _is_unsupported_search_operator(self, operator): return operator != "=" @api.model def _search_has_moves(self, operator, value): if self._is_unsupported_search_operator(operator) or not value: raise ValueError(_("Unsupported search operator")) ids_with_moves = self._account_tax_ids_with_moves() return [("id", "in", ids_with_moves)] @api.depends_context( "from_date", "to_date", "company_ids", "target_move", ) def _compute_balance(self): for tax in self: tax.balance_regular = tax.compute_balance( tax_or_base="tax", financial_type="regular" ) tax.base_balance_regular = tax.compute_balance( tax_or_base="base", financial_type="regular" ) tax.balance_refund = tax.compute_balance( tax_or_base="tax", financial_type="refund" ) tax.base_balance_refund = tax.compute_balance( tax_or_base="base", financial_type="refund" ) tax.balance = tax.balance_regular + tax.balance_refund tax.base_balance = tax.base_balance_regular + tax.base_balance_refund def get_target_type_list(self, financial_type=None): if financial_type == "refund": return ["receivable_refund", "payable_refund"] elif financial_type == "regular": return ["receivable", "payable", "liquidity", "other"] return [] def get_target_state_list(self, target_move="posted"): if target_move == "posted": state = ["posted"] elif target_move == "all": state = ["posted", "draft"] else: state = [] return state def get_move_line_partial_domain(self, from_date, to_date, company_ids): return [ ("date", "<=", to_date), ("date", ">=", from_date), ("company_id", "in", company_ids), ] def compute_balance(self, tax_or_base="tax", financial_type=None): self.ensure_one() domain = self.get_move_lines_domain( tax_or_base=tax_or_base, financial_type=financial_type ) # balance is debit - credit whereas on tax return you want to see what # vat has to be paid so: # VAT on sales (credit) - VAT on purchases (debit). balance = self.env["account.move.line"].read_group(domain, ["balance"], [])[0][ "balance" ] return balance and -balance or 0 def get_balance_domain(self, state_list, type_list): domain = [ ("move_id.state", "in", state_list), ("tax_line_id", "=", self.id), ] domain.extend(self.env["account.move.line"]._get_tax_exigible_domain()) if type_list: domain.append(("move_id.financial_type", "in", type_list)) return domain def get_base_balance_domain(self, state_list, type_list): domain = [ ("move_id.state", "in", state_list), ("tax_ids", "in", self.id), ] domain.extend(self.env["account.move.line"]._get_tax_exigible_domain()) if type_list: domain.append(("move_id.financial_type", "in", type_list)) return domain def get_move_lines_domain(self, tax_or_base="tax", financial_type=None): from_date, to_date, company_ids, target_move = self.get_context_values() state_list = self.get_target_state_list(target_move) type_list = self.get_target_type_list(financial_type) domain = self.get_move_line_partial_domain(from_date, to_date, company_ids) balance_domain = [] if tax_or_base == "tax": balance_domain = self.get_balance_domain(state_list, type_list) elif tax_or_base == "base": balance_domain = self.get_base_balance_domain(state_list, type_list) domain.extend(balance_domain) return domain def get_lines_action(self, tax_or_base="tax", financial_type=None): domain = self.get_move_lines_domain( tax_or_base=tax_or_base, financial_type=financial_type ) action = self.env.ref("account.action_account_moves_all_tree") vals = action.sudo().read()[0] vals["context"] = {} vals["domain"] = domain return vals def view_tax_lines(self): self.ensure_one() return self.get_lines_action(tax_or_base="tax") def view_base_lines(self): self.ensure_one() return self.get_lines_action(tax_or_base="base") def view_tax_regular_lines(self): self.ensure_one() return self.get_lines_action(tax_or_base="tax", financial_type="regular") def view_base_regular_lines(self): self.ensure_one() return self.get_lines_action(tax_or_base="base", financial_type="regular") def view_tax_refund_lines(self): self.ensure_one() return self.get_lines_action(tax_or_base="tax", financial_type="refund") def view_base_refund_lines(self): self.ensure_one() return self.get_lines_action(tax_or_base="base", financial_type="refund")
38.052632
7,953
1,903
py
PYTHON
15.0
# Copyright 2016 Antonio Espinosa <antonio.espinosa@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models class AccountMove(models.Model): _inherit = "account.move" @api.model def _selection_financial_type(self): return [ ("other", _("Other")), ("liquidity", _("Liquidity")), ("receivable", _("Receivable")), ("receivable_refund", _("Receivable refund")), ("payable", _("Payable")), ("payable_refund", _("Payable refund")), ] financial_type = fields.Selection( selection="_selection_financial_type", compute="_compute_financial_type", store=True, readonly=True, ) @api.depends( "line_ids.account_id.internal_type", "line_ids.balance", "line_ids.account_id.user_type_id.type", ) def _compute_financial_type(self): def _balance_get(line_ids, internal_type): return sum( line_ids.filtered( lambda x: x.account_id.internal_type == internal_type ).mapped("balance") ) for move in self: internal_types = move.line_ids.mapped("account_id.internal_type") if "liquidity" in internal_types: move.financial_type = "liquidity" elif "payable" in internal_types: balance = _balance_get(move.line_ids, "payable") move.financial_type = "payable" if balance < 0 else "payable_refund" elif "receivable" in internal_types: balance = _balance_get(move.line_ids, "receivable") move.financial_type = ( "receivable" if balance > 0 else "receivable_refund" ) else: move.financial_type = "other"
35.240741
1,903
684
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class AccountMoveLine(models.Model): _inherit = "account.move.line" def init(self): res = super().init() self._cr.execute( """ SELECT indexname FROM pg_indexes WHERE indexname = 'account_move_line_date_tax_line_id_idx' """ ) if not self._cr.fetchone(): self._cr.execute( """ CREATE INDEX account_move_line_date_tax_line_id_idx ON account_move_line (date, tax_line_id) """ ) return res
26.307692
684
2,172
py
PYTHON
15.0
# Author: Damien Crier # Author: Julien Coux # Copyright 2016 Camptocamp SA # Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com) # Copyright 2021 Tecnativa - João Marques # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Account Financial Reports", "version": "15.0.2.8.4", "category": "Reporting", "summary": "OCA Financial Reports", "author": "Camptocamp SA," "initOS GmbH," "redCOR AG," "ForgeFlow," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-reporting", "depends": ["account", "date_range", "report_xlsx"], "data": [ "security/ir.model.access.csv", "wizard/aged_partner_balance_wizard_view.xml", "wizard/general_ledger_wizard_view.xml", "wizard/journal_ledger_wizard_view.xml", "wizard/open_items_wizard_view.xml", "wizard/trial_balance_wizard_view.xml", "wizard/vat_report_wizard_view.xml", "menuitems.xml", "reports.xml", "report/templates/layouts.xml", "report/templates/aged_partner_balance.xml", "report/templates/general_ledger.xml", "report/templates/journal_ledger.xml", "report/templates/open_items.xml", "report/templates/trial_balance.xml", "report/templates/vat_report.xml", "view/account_view.xml", "view/report_general_ledger.xml", "view/report_journal_ledger.xml", "view/report_trial_balance.xml", "view/report_open_items.xml", "view/report_aged_partner_balance.xml", "view/report_vat_report.xml", ], "assets": { "web.assets_backend": [ "account_financial_report/static/src/js/action_manager_report.js", "account_financial_report/static/src/js/client_action.js", ], "web.report_assets_common": [ "account_financial_report/static/src/js/report.js" ], "web.assets_qweb": [ "account_financial_report/static/src/xml/**/*", ], }, "installable": True, "application": True, "auto_install": False, "license": "AGPL-3", }
36.183333
2,171
28,893
py
PYTHON
15.0
# Author: Julien Coux # Copyright 2016 Camptocamp SA # Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import time from datetime import date from odoo import api, fields from odoo.tests import tagged from odoo.addons.account.tests.common import AccountTestInvoicingCommon @tagged("post_install", "-at_install") class TestGeneralLedgerReport(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.before_previous_fy_year = fields.Date.from_string("2014-05-05") cls.previous_fy_date_start = fields.Date.from_string("2015-01-01") cls.previous_fy_date_end = fields.Date.from_string("2015-12-31") cls.fy_date_start = fields.Date.from_string("2016-01-01") cls.fy_date_end = fields.Date.from_string("2016-12-31") # Get accounts cls.receivable_account = cls.company_data["default_account_receivable"] cls.income_account = cls.company_data["default_account_revenue"] cls.unaffected_account = cls.env["account.account"].search( [ ( "user_type_id", "=", cls.env.ref("account.data_unaffected_earnings").id, ), ("company_id", "=", cls.env.user.company_id.id), ], limit=1, ) cls.partner = cls.env.ref("base.res_partner_12") def _add_move( self, date, receivable_debit, receivable_credit, income_debit, income_credit, unaffected_debit=0, unaffected_credit=0, ): journal = self.env["account.journal"].search( [("company_id", "=", self.env.user.company_id.id)], limit=1 ) partner = self.env.ref("base.res_partner_12") move_vals = { "journal_id": journal.id, "date": date, "line_ids": [ ( 0, 0, { "debit": receivable_debit, "credit": receivable_credit, "account_id": self.receivable_account.id, "partner_id": partner.id, }, ), ( 0, 0, { "debit": income_debit, "credit": income_credit, "account_id": self.income_account.id, "partner_id": partner.id, }, ), ( 0, 0, { "debit": unaffected_debit, "credit": unaffected_credit, "account_id": self.unaffected_account.id, "partner_id": partner.id, }, ), ], } move = self.env["account.move"].create(move_vals) move.action_post() def _get_report_lines(self, with_partners=False, account_ids=False): centralize = True if with_partners: centralize = False company = self.env.user.company_id general_ledger = self.env["general.ledger.report.wizard"].create( { "date_from": self.fy_date_start, "date_to": self.fy_date_end, "target_move": "posted", "hide_account_at_0": False, "company_id": company.id, "account_ids": account_ids, "fy_start_date": self.fy_date_start, "centralize": centralize, } ) data = general_ledger._prepare_report_general_ledger() res_data = self.env[ "report.account_financial_report.general_ledger" ]._get_report_values(general_ledger, data) return res_data @api.model def check_account_in_report(self, account_id, general_ledger): account_in_report = False for account in general_ledger: if account["id"] == account_id: account_in_report = True break return account_in_report @api.model def check_partner_in_report(self, account_id, partner_id, general_ledger): partner_in_report = False for account in general_ledger: if account["id"] == account_id and account["partners"]: for partner in account["list_grouped"]: if partner["id"] == partner_id: partner_in_report = True return partner_in_report @api.model def _get_initial_balance(self, account_id, general_ledger): initial_balance = False for account in general_ledger: if account["id"] == account_id: initial_balance = account["init_bal"] return initial_balance @api.model def _get_partner_initial_balance(self, account_id, partner_id, general_ledger): initial_balance = False for account in general_ledger: if account["id"] == account_id and account["partners"]: for partner in account["list_grouped"]: if partner["id"] == partner_id: initial_balance = partner["init_bal"] return initial_balance @api.model def _get_final_balance(self, account_id, general_ledger): final_balance = False for account in general_ledger: if account["id"] == account_id: final_balance = account["fin_bal"] return final_balance @api.model def _get_partner_final_balance(self, account_id, partner_id, general_ledger): final_balance = False for account in general_ledger: if account["id"] == account_id and account["partners"]: for partner in account["list_grouped"]: if partner["id"] == partner_id: final_balance = partner["fin_bal"] return final_balance def test_01_account_balance(self): # Generate the general ledger line res_data = self._get_report_lines() general_ledger = res_data["general_ledger"] check_receivable_account = self.check_account_in_report( self.receivable_account.id, general_ledger ) self.assertFalse(check_receivable_account) check_income_account = self.check_account_in_report( self.income_account.id, general_ledger ) self.assertFalse(check_income_account) self.assertTrue( self.check_account_in_report(self.unaffected_account.id, general_ledger) ) # Add a move at the previous day of the first day of fiscal year # to check the initial balance self._add_move( date=self.previous_fy_date_end, receivable_debit=1000, receivable_credit=0, income_debit=0, income_credit=1000, ) # Re Generate the general ledger line res_data = self._get_report_lines() general_ledger = res_data["general_ledger"] check_receivable_account = self.check_account_in_report( self.receivable_account.id, general_ledger ) self.assertTrue(check_receivable_account) check_income_account = self.check_account_in_report( self.income_account.id, general_ledger ) self.assertFalse(check_income_account) # Check the initial and final balance receivable_init_balance = self._get_initial_balance( self.receivable_account.id, general_ledger ) receivable_fin_balance = self._get_final_balance( self.receivable_account.id, general_ledger ) self.assertEqual(receivable_init_balance["debit"], 1000) self.assertEqual(receivable_init_balance["credit"], 0) self.assertEqual(receivable_init_balance["balance"], 1000) self.assertEqual(receivable_fin_balance["debit"], 1000) self.assertEqual(receivable_fin_balance["credit"], 0) self.assertEqual(receivable_fin_balance["balance"], 1000) # Add reversale move of the initial move the first day of fiscal year # to check the first day of fiscal year is not used # to compute the initial balance self._add_move( date=self.fy_date_start, receivable_debit=0, receivable_credit=1000, income_debit=1000, income_credit=0, ) # Re Generate the general ledger line res_data = self._get_report_lines() general_ledger = res_data["general_ledger"] check_receivable_account = self.check_account_in_report( self.receivable_account.id, general_ledger ) self.assertTrue(check_receivable_account) check_income_account = self.check_account_in_report( self.income_account.id, general_ledger ) self.assertTrue(check_income_account) # Check the initial and final balance receivable_init_balance = self._get_initial_balance( self.receivable_account.id, general_ledger ) receivable_fin_balance = self._get_final_balance( self.receivable_account.id, general_ledger ) income_init_balance = self._get_initial_balance( self.income_account.id, general_ledger ) income_fin_balance = self._get_final_balance( self.income_account.id, general_ledger ) self.assertEqual(receivable_init_balance["debit"], 1000) self.assertEqual(receivable_init_balance["credit"], 0) self.assertEqual(receivable_init_balance["balance"], 1000) self.assertEqual(receivable_fin_balance["debit"], 1000) self.assertEqual(receivable_fin_balance["credit"], 1000) self.assertEqual(receivable_fin_balance["balance"], 0) self.assertEqual(income_init_balance["debit"], 0) self.assertEqual(income_init_balance["credit"], 0) self.assertEqual(income_init_balance["balance"], 0) self.assertEqual(income_fin_balance["debit"], 1000) self.assertEqual(income_fin_balance["credit"], 0) self.assertEqual(income_fin_balance["balance"], 1000) # Re Generate the general ledger line res_data = self._get_report_lines( account_ids=(self.receivable_account + self.income_account).ids ) general_ledger = res_data["general_ledger"] self.assertTrue( self.check_account_in_report(self.receivable_account.id, general_ledger) ) self.assertTrue( self.check_account_in_report(self.income_account.id, general_ledger) ) self.assertFalse( self.check_account_in_report(self.unaffected_account.id, general_ledger) ) # Add another move at the end day of fiscal year # to check that it correctly used on report self._add_move( date=self.fy_date_end, receivable_debit=0, receivable_credit=1000, income_debit=1000, income_credit=0, ) # Re Generate the general ledger line res_data = self._get_report_lines() general_ledger = res_data["general_ledger"] check_receivable_account = self.check_account_in_report( self.receivable_account.id, general_ledger ) self.assertTrue(check_receivable_account) check_income_account = self.check_account_in_report( self.income_account.id, general_ledger ) self.assertTrue(check_income_account) # Check the initial and final balance receivable_init_balance = self._get_initial_balance( self.receivable_account.id, general_ledger ) receivable_fin_balance = self._get_final_balance( self.receivable_account.id, general_ledger ) income_init_balance = self._get_initial_balance( self.income_account.id, general_ledger ) income_fin_balance = self._get_final_balance( self.income_account.id, general_ledger ) self.assertEqual(receivable_init_balance["debit"], 1000) self.assertEqual(receivable_init_balance["credit"], 0) self.assertEqual(receivable_init_balance["balance"], 1000) self.assertEqual(receivable_fin_balance["debit"], 1000) self.assertEqual(receivable_fin_balance["credit"], 2000) self.assertEqual(receivable_fin_balance["balance"], -1000) self.assertEqual(income_init_balance["debit"], 0) self.assertEqual(income_init_balance["credit"], 0) self.assertEqual(income_init_balance["balance"], 0) self.assertEqual(income_fin_balance["debit"], 2000) self.assertEqual(income_fin_balance["credit"], 0) self.assertEqual(income_fin_balance["balance"], 2000) def test_02_partner_balance(self): # Generate the general ledger line res_data = self._get_report_lines(with_partners=True) general_ledger = res_data["general_ledger"] check_partner = self.check_partner_in_report( self.receivable_account.id, self.partner.id, general_ledger ) self.assertFalse(check_partner) # Add a move at the previous day of the first day of fiscal year # to check the initial balance self._add_move( date=self.previous_fy_date_end, receivable_debit=1000, receivable_credit=0, income_debit=0, income_credit=1000, ) # Re Generate the general ledger line res_data = self._get_report_lines(with_partners=True) general_ledger = res_data["general_ledger"] check_partner = self.check_partner_in_report( self.receivable_account.id, self.partner.id, general_ledger ) self.assertTrue(check_partner) # Check the initial and final balance partner_initial_balance = self._get_partner_initial_balance( self.receivable_account.id, self.partner.id, general_ledger ) partner_final_balance = self._get_partner_final_balance( self.receivable_account.id, self.partner.id, general_ledger ) self.assertEqual(partner_initial_balance["debit"], 1000) self.assertEqual(partner_initial_balance["credit"], 0) self.assertEqual(partner_initial_balance["balance"], 1000) self.assertEqual(partner_final_balance["debit"], 1000) self.assertEqual(partner_final_balance["credit"], 0) self.assertEqual(partner_final_balance["balance"], 1000) # Add reversale move of the initial move the first day of fiscal year # to check the first day of fiscal year is not used # to compute the initial balance self._add_move( date=self.fy_date_start, receivable_debit=0, receivable_credit=1000, income_debit=1000, income_credit=0, ) # Re Generate the general ledger line res_data = self._get_report_lines(with_partners=True) general_ledger = res_data["general_ledger"] check_partner = self.check_partner_in_report( self.receivable_account.id, self.partner.id, general_ledger ) self.assertTrue(check_partner) # Check the initial and final balance partner_initial_balance = self._get_partner_initial_balance( self.receivable_account.id, self.partner.id, general_ledger ) partner_final_balance = self._get_partner_final_balance( self.receivable_account.id, self.partner.id, general_ledger ) self.assertEqual(partner_initial_balance["debit"], 1000) self.assertEqual(partner_initial_balance["credit"], 0) self.assertEqual(partner_initial_balance["balance"], 1000) self.assertEqual(partner_final_balance["debit"], 1000) self.assertEqual(partner_final_balance["credit"], 1000) self.assertEqual(partner_final_balance["balance"], 0) # Add another move at the end day of fiscal year # to check that it correctly used on report self._add_move( date=self.fy_date_end, receivable_debit=0, receivable_credit=1000, income_debit=1000, income_credit=0, ) # Re Generate the general ledger line res_data = self._get_report_lines(with_partners=True) general_ledger = res_data["general_ledger"] check_partner = self.check_partner_in_report( self.receivable_account.id, self.partner.id, general_ledger ) self.assertTrue(check_partner) # Check the initial and final balance partner_initial_balance = self._get_partner_initial_balance( self.receivable_account.id, self.partner.id, general_ledger ) partner_final_balance = self._get_partner_final_balance( self.receivable_account.id, self.partner.id, general_ledger ) self.assertEqual(partner_initial_balance["debit"], 1000) self.assertEqual(partner_initial_balance["credit"], 0) self.assertEqual(partner_initial_balance["balance"], 1000) self.assertEqual(partner_final_balance["debit"], 1000) self.assertEqual(partner_final_balance["credit"], 2000) self.assertEqual(partner_final_balance["balance"], -1000) def test_03_unaffected_account_balance(self): # Generate the general ledger line res_data = self._get_report_lines() general_ledger = res_data["general_ledger"] check_unaffected_account = self.check_account_in_report( self.unaffected_account.id, general_ledger ) self.assertTrue(check_unaffected_account) # Check the initial and final balance unaffected_init_balance = self._get_initial_balance( self.unaffected_account.id, general_ledger ) unaffected_fin_balance = self._get_final_balance( self.unaffected_account.id, general_ledger ) self.assertEqual(unaffected_init_balance["debit"], 0) self.assertEqual(unaffected_init_balance["credit"], 0) self.assertEqual(unaffected_init_balance["balance"], 0) self.assertEqual(unaffected_fin_balance["debit"], 0) self.assertEqual(unaffected_fin_balance["credit"], 0) self.assertEqual(unaffected_fin_balance["balance"], 0) # Add a move at the previous day of the first day of fiscal year # to check the initial balance self._add_move( date=self.previous_fy_date_end, receivable_debit=1000, receivable_credit=0, income_debit=0, income_credit=1000, ) # Re Generate the general ledger line res_data = self._get_report_lines() general_ledger = res_data["general_ledger"] check_unaffected_account = self.check_account_in_report( self.unaffected_account.id, general_ledger ) self.assertTrue(check_unaffected_account) # Check the initial and final balance unaffected_init_balance = self._get_initial_balance( self.unaffected_account.id, general_ledger ) unaffected_fin_balance = self._get_final_balance( self.unaffected_account.id, general_ledger ) self.assertEqual(unaffected_init_balance["debit"], 0) self.assertEqual(unaffected_init_balance["credit"], 1000) self.assertEqual(unaffected_init_balance["balance"], -1000) self.assertEqual(unaffected_fin_balance["debit"], 0) self.assertEqual(unaffected_fin_balance["credit"], 1000) self.assertEqual(unaffected_fin_balance["balance"], -1000) # Add reversale move of the initial move the first day of fiscal year # to check the first day of fiscal year is not used # to compute the initial balance self._add_move( date=self.fy_date_start, receivable_debit=0, receivable_credit=0, income_debit=0, income_credit=1000, unaffected_debit=1000, unaffected_credit=0, ) # Re Generate the general ledger line res_data = self._get_report_lines() general_ledger = res_data["general_ledger"] check_unaffected_account = self.check_account_in_report( self.unaffected_account.id, general_ledger ) self.assertTrue(check_unaffected_account) # Check the initial and final balance unaffected_init_balance = self._get_initial_balance( self.unaffected_account.id, general_ledger ) unaffected_fin_balance = self._get_final_balance( self.unaffected_account.id, general_ledger ) self.assertEqual(unaffected_init_balance["debit"], 0) self.assertEqual(unaffected_init_balance["credit"], 1000) self.assertEqual(unaffected_init_balance["balance"], -1000) self.assertEqual(unaffected_fin_balance["debit"], 1000) self.assertEqual(unaffected_fin_balance["credit"], 1000) self.assertEqual(unaffected_fin_balance["balance"], 0) # Add another move at the end day of fiscal year # to check that it correctly used on report self._add_move( date=self.fy_date_end, receivable_debit=3000, receivable_credit=0, income_debit=0, income_credit=0, unaffected_debit=0, unaffected_credit=3000, ) # Re Generate the general ledger line res_data = self._get_report_lines() general_ledger = res_data["general_ledger"] check_unaffected_account = self.check_account_in_report( self.unaffected_account.id, general_ledger ) self.assertTrue(check_unaffected_account) # Check the initial and final balance unaffected_init_balance = self._get_initial_balance( self.unaffected_account.id, general_ledger ) unaffected_fin_balance = self._get_final_balance( self.unaffected_account.id, general_ledger ) self.assertEqual(unaffected_init_balance["debit"], 0) self.assertEqual(unaffected_init_balance["credit"], 1000) self.assertEqual(unaffected_init_balance["balance"], -1000) self.assertEqual(unaffected_fin_balance["debit"], 1000) self.assertEqual(unaffected_fin_balance["credit"], 4000) self.assertEqual(unaffected_fin_balance["balance"], -3000) def test_04_unaffected_account_balance_2_years(self): # Generate the general ledger line res_data = self._get_report_lines() general_ledger = res_data["general_ledger"] check_unaffected_account = self.check_account_in_report( self.unaffected_account.id, general_ledger ) self.assertTrue(check_unaffected_account) # Check the initial and final balance unaffected_init_balance = self._get_initial_balance( self.unaffected_account.id, general_ledger ) unaffected_fin_balance = self._get_final_balance( self.unaffected_account.id, general_ledger ) self.assertEqual(unaffected_init_balance["debit"], 0) self.assertEqual(unaffected_init_balance["credit"], 0) self.assertEqual(unaffected_init_balance["balance"], 0) self.assertEqual(unaffected_fin_balance["debit"], 0) self.assertEqual(unaffected_fin_balance["credit"], 0) self.assertEqual(unaffected_fin_balance["balance"], 0) # Add a move at any date 2 years before the balance # (to create an historic) self._add_move( date=self.before_previous_fy_year, receivable_debit=0, receivable_credit=1000, income_debit=1000, income_credit=0, ) # Re Generate the general ledger line res_data = self._get_report_lines() general_ledger = res_data["general_ledger"] check_unaffected_account = self.check_account_in_report( self.unaffected_account.id, general_ledger ) self.assertTrue(check_unaffected_account) # Check the initial and final balance unaffected_init_balance = self._get_initial_balance( self.unaffected_account.id, general_ledger ) unaffected_fin_balance = self._get_final_balance( self.unaffected_account.id, general_ledger ) self.assertEqual(unaffected_init_balance["debit"], 1000) self.assertEqual(unaffected_init_balance["credit"], 0) self.assertEqual(unaffected_init_balance["balance"], 1000) self.assertEqual(unaffected_fin_balance["debit"], 1000) self.assertEqual(unaffected_fin_balance["credit"], 0) self.assertEqual(unaffected_fin_balance["balance"], 1000) # Affect the company's result last year self._add_move( date=self.previous_fy_date_start, receivable_debit=1000, receivable_credit=0, income_debit=0, income_credit=0, unaffected_debit=0, unaffected_credit=1000, ) # Add another move last year to test the initial balance this year self._add_move( date=self.previous_fy_date_start, receivable_debit=0, receivable_credit=500, income_debit=500, income_credit=0, unaffected_debit=0, unaffected_credit=0, ) # Re Generate the general ledger line res_data = self._get_report_lines() general_ledger = res_data["general_ledger"] check_unaffected_account = self.check_account_in_report( self.unaffected_account.id, general_ledger ) self.assertTrue(check_unaffected_account) # Check the initial and final balance unaffected_init_balance = self._get_initial_balance( self.unaffected_account.id, general_ledger ) unaffected_fin_balance = self._get_final_balance( self.unaffected_account.id, general_ledger ) self.assertEqual(unaffected_init_balance["debit"], 1500) self.assertEqual(unaffected_init_balance["credit"], 1000) self.assertEqual(unaffected_init_balance["balance"], 500) self.assertEqual(unaffected_fin_balance["debit"], 1500) self.assertEqual(unaffected_fin_balance["credit"], 1000) self.assertEqual(unaffected_fin_balance["balance"], 500) def test_partner_filter(self): partner_1 = self.env.ref("base.res_partner_1") partner_2 = self.env.ref("base.res_partner_2") partner_3 = self.env.ref("base.res_partner_3") partner_4 = self.env.ref("base.res_partner_4") partner_1.write({"is_company": False, "parent_id": partner_2.id}) partner_3.write({"is_company": False}) expected_list = [partner_2.id, partner_3.id, partner_4.id] context = { "active_ids": [partner_1.id, partner_2.id, partner_3.id, partner_4.id], "active_model": "res.partner", } wizard = self.env["general.ledger.report.wizard"].with_context(**context) self.assertEqual(wizard._default_partners(), expected_list) def test_validate_date(self): company_id = self.env.user.company_id company_id.write({"fiscalyear_last_day": 31, "fiscalyear_last_month": "12"}) user = self.env.ref("base.user_root").with_context(company_id=company_id.id) wizard = self.env["general.ledger.report.wizard"].with_context(user=user.id) self.assertEqual(wizard._init_date_from(), time.strftime("%Y") + "-01-01") def test_validate_date_range(self): data_type = self.env["date.range.type"].create( {"name": "Fiscal year", "company_id": False, "allow_overlap": False} ) dr = self.env["date.range"].create( { "name": "FS2015", "date_start": "2018-01-01", "date_end": "2018-12-31", "type_id": data_type.id, } ) wizard = self.env["general.ledger.report.wizard"].create( {"date_range_id": dr.id} ) wizard.onchange_date_range_id() self.assertEqual(wizard.date_from, date(2018, 1, 1)) self.assertEqual(wizard.date_to, date(2018, 12, 31))
39.962656
28,893
10,844
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # Copyright 2019-20 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from datetime import datetime from dateutil.relativedelta import relativedelta from odoo.fields import Date from odoo.tests import tagged from odoo.tests.common import Form from odoo.addons.account.tests.common import AccountTestInvoicingCommon @tagged("post_install", "-at_install") class TestJournalReport(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.AccountObj = cls.env["account.account"] cls.InvoiceObj = cls.env["account.move"] cls.JournalObj = cls.env["account.journal"] cls.MoveObj = cls.env["account.move"] cls.TaxObj = cls.env["account.tax"] cls.JournalLedgerReportWizard = cls.env["journal.ledger.report.wizard"] cls.JournalLedgerReport = cls.env[ "report.account_financial_report.journal_ledger" ] cls.company = cls.company_data["company"] cls.company.account_sale_tax_id = False cls.company.account_purchase_tax_id = False today = datetime.today() last_year = today - relativedelta(years=1) cls.previous_fy_date_start = Date.to_string(last_year.replace(month=1, day=1)) cls.previous_fy_date_end = Date.to_string(last_year.replace(month=12, day=31)) cls.fy_date_start = Date.to_string(today.replace(month=1, day=1)) cls.fy_date_end = Date.to_string(today.replace(month=12, day=31)) cls.receivable_account = cls.company_data["default_account_receivable"] cls.income_account = cls.company_data["default_account_revenue"] cls.expense_account = cls.company_data["default_account_expense"] cls.payable_account = cls.company_data["default_account_payable"] cls.journal_sale = cls.company_data["default_journal_sale"] cls.journal_purchase = cls.company_data["default_journal_purchase"] cls.tax_15_s = cls.company_data["default_tax_sale"] cls.tax_15_s.sequence = 30 cls.tax_15_s.amount = 15.0 cls.tax_15_s.amount_type = "percent" cls.tax_15_s.include_base_amount = False cls.tax_15_s.type_tax_use = "sale" cls.tax_20_s = cls.tax_15_s.copy( { "sequence": 30, "name": "Tax 20.0% (Percentage of Price)", "amount": 20.0, "amount_type": "percent", "include_base_amount": False, "type_tax_use": "sale", } ) cls.tax_15_p = cls.company_data["default_tax_purchase"] cls.tax_15_p.sequence = 30 cls.tax_15_p.amount = 15.0 cls.tax_15_p.amount_type = "percent" cls.tax_15_p.include_base_amount = False cls.tax_15_p.type_tax_use = "purchase" cls.tax_20_p = cls.tax_15_p.copy( { "sequence": 30, "name": "Tax 20.0% (Percentage of Price)", "amount": 20.0, "amount_type": "percent", "include_base_amount": False, "type_tax_use": "purchase", } ) cls.partner_2 = cls.env.ref("base.res_partner_2") def _add_move( self, date, journal, receivable_debit, receivable_credit, income_debit, income_credit, ): move_name = "move name" move_vals = { "journal_id": journal.id, "date": date, "line_ids": [ ( 0, 0, { "name": move_name, "debit": receivable_debit, "credit": receivable_credit, "account_id": self.receivable_account.id, }, ), ( 0, 0, { "name": move_name, "debit": income_debit, "credit": income_credit, "account_id": self.income_account.id, }, ), ], } return self.MoveObj.create(move_vals) def check_report_journal_debit_credit( self, res_data, expected_debit, expected_credit ): self.assertEqual( expected_debit, sum(rec["debit"] for rec in res_data["Journal_Ledgers"]) ) self.assertEqual( expected_credit, sum(rec["credit"] for rec in res_data["Journal_Ledgers"]) ) def check_report_journal_debit_credit_taxes( self, res_data, expected_base_debit, expected_base_credit, expected_tax_debit, expected_tax_credit, ): for rec in res_data["Journal_Ledgers"]: self.assertEqual( expected_base_debit, sum(tax_line["base_debit"] for tax_line in rec["tax_lines"]), ) self.assertEqual( expected_base_credit, sum(tax_line["base_credit"] for tax_line in rec["tax_lines"]), ) self.assertEqual( expected_tax_debit, sum(tax_line["tax_debit"] for tax_line in rec["tax_lines"]), ) self.assertEqual( expected_tax_credit, sum(tax_line["tax_credit"] for tax_line in rec["tax_lines"]), ) def test_01_test_total(self): today_date = Date.today() last_year_date = Date.to_string(datetime.today() - relativedelta(years=1)) move1 = self._add_move(today_date, self.journal_sale, 0, 100, 100, 0) move2 = self._add_move(last_year_date, self.journal_sale, 0, 100, 100, 0) wiz = self.JournalLedgerReportWizard.create( { "date_from": self.fy_date_start, "date_to": self.fy_date_end, "company_id": self.company.id, "journal_ids": [(6, 0, self.journal_sale.ids)], "move_target": "all", } ) data = wiz._prepare_report_journal_ledger() res_data = self.JournalLedgerReport._get_report_values(wiz, data) self.check_report_journal_debit_credit(res_data, 100, 100) move3 = self._add_move(today_date, self.journal_sale, 0, 100, 100, 0) res_data = self.JournalLedgerReport._get_report_values(wiz, data) self.check_report_journal_debit_credit(res_data, 200, 200) wiz.move_target = "posted" data = wiz._prepare_report_journal_ledger() res_data = self.JournalLedgerReport._get_report_values(wiz, data) self.check_report_journal_debit_credit(res_data, 0, 0) move1.action_post() res_data = self.JournalLedgerReport._get_report_values(wiz, data) self.check_report_journal_debit_credit(res_data, 100, 100) move2.action_post() res_data = self.JournalLedgerReport._get_report_values(wiz, data) self.check_report_journal_debit_credit(res_data, 100, 100) move3.action_post() res_data = self.JournalLedgerReport._get_report_values(wiz, data) self.check_report_journal_debit_credit(res_data, 200, 200) wiz.date_from = self.previous_fy_date_start data = wiz._prepare_report_journal_ledger() res_data = self.JournalLedgerReport._get_report_values(wiz, data) self.check_report_journal_debit_credit(res_data, 300, 300) def test_02_test_taxes_out_invoice(self): move_form = Form( self.env["account.move"].with_context(default_move_type="out_invoice") ) move_form.partner_id = self.partner_2 move_form.journal_id = self.journal_sale with move_form.invoice_line_ids.new() as line_form: line_form.name = "test" line_form.quantity = 1.0 line_form.price_unit = 100 line_form.account_id = self.income_account line_form.tax_ids.add(self.tax_15_s) with move_form.invoice_line_ids.new() as line_form: line_form.name = "test" line_form.quantity = 1.0 line_form.price_unit = 100 line_form.account_id = self.income_account line_form.tax_ids.add(self.tax_15_s) line_form.tax_ids.add(self.tax_20_s) invoice = move_form.save() invoice.action_post() wiz = self.JournalLedgerReportWizard.create( { "date_from": self.fy_date_start, "date_to": self.fy_date_end, "company_id": self.company.id, "journal_ids": [(6, 0, self.journal_sale.ids)], "move_target": "all", } ) data = wiz._prepare_report_journal_ledger() res_data = self.JournalLedgerReport._get_report_values(wiz, data) self.check_report_journal_debit_credit(res_data, 250, 250) self.check_report_journal_debit_credit_taxes(res_data, 0, 300, 0, 50) def test_03_test_taxes_in_invoice(self): move_form = Form( self.env["account.move"].with_context(default_move_type="in_invoice") ) move_form.partner_id = self.partner_2 move_form.journal_id = self.journal_purchase move_form.invoice_date = Date.today() with move_form.invoice_line_ids.new() as line_form: line_form.name = "test" line_form.quantity = 1.0 line_form.price_unit = 100 line_form.account_id = self.expense_account line_form.tax_ids.add(self.tax_15_p) with move_form.invoice_line_ids.new() as line_form: line_form.name = "test" line_form.quantity = 1.0 line_form.price_unit = 100 line_form.account_id = self.expense_account line_form.tax_ids.add(self.tax_15_p) line_form.tax_ids.add(self.tax_20_p) move_form.invoice_date = move_form.date invoice = move_form.save() invoice.action_post() wiz = self.JournalLedgerReportWizard.create( { "date_from": self.fy_date_start, "date_to": self.fy_date_end, "company_id": self.company.id, "journal_ids": [(6, 0, self.journal_purchase.ids)], "move_target": "all", } ) data = wiz._prepare_report_journal_ledger() res_data = self.JournalLedgerReport._get_report_values(wiz, data) self.check_report_journal_debit_credit(res_data, 250, 250) self.check_report_journal_debit_credit_taxes(res_data, 300, 0, 50, 0)
39.721612
10,844
1,214
py
PYTHON
15.0
# Copyright 2021 Simone Rubino - Agile Business Group # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.tests import TransactionCase from odoo.tools import DEFAULT_SERVER_DATE_FORMAT, test_reports class TestAgedPartnerBalance(TransactionCase): def setUp(self): super().setUp() self.wizard_model = self.env["aged.partner.balance.report.wizard"] def test_report(self): """Check that report is produced correctly.""" wizard = self.wizard_model.create( { "show_move_line_details": True, "receivable_accounts_only": True, } ) wizard.onchange_type_accounts_only() data = wizard._prepare_report_aged_partner_balance() # Simulate web client behavior: # default value is a datetime.date but web client sends back strings data.update({"date_at": data["date_at"].strftime(DEFAULT_SERVER_DATE_FORMAT)}) result = test_reports.try_report( self.env.cr, self.env.uid, "account_financial_report.aged_partner_balance", wizard.ids, data=data, ) self.assertTrue(result)
35.705882
1,214
26,163
py
PYTHON
15.0
# Author: Julien Coux # Copyright 2016 Camptocamp SA # Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.tests import tagged from odoo.addons.account.tests.common import AccountTestInvoicingCommon @tagged("post_install", "-at_install") class TestTrialBalanceReport(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) # Remove previous account groups and related invoices to avoid conflicts group_obj = cls.env["account.group"] cls.group1 = group_obj.create({"code_prefix_start": "1", "name": "Group 1"}) cls.group11 = group_obj.create( {"code_prefix_start": "11", "name": "Group 11", "parent_id": cls.group1.id} ) cls.group2 = group_obj.create({"code_prefix_start": "2", "name": "Group 2"}) # Set accounts cls.account100 = cls.company_data["default_account_receivable"] cls.account100.group_id = cls.group1.id cls.account110 = cls.env["account.account"].search( [ ( "user_type_id", "=", cls.env.ref("account.data_unaffected_earnings").id, ), ], limit=1, ) cls.account200 = cls._create_account_account( cls, { "code": "200", "name": "Account 200", "group_id": cls.group2.id, "user_type_id": cls.env.ref( "account.data_account_type_other_income" ).id, }, ) cls.account300 = cls._create_account_account( cls, { "code": "300", "name": "Account 300", "user_type_id": cls.env.ref( "account.data_account_type_other_income" ).id, }, ) cls.account301 = cls._create_account_account( cls, { "code": "301", "name": "Account 301", "group_id": cls.group2.id, "user_type_id": cls.env.ref( "account.data_account_type_other_income" ).id, }, ) cls.previous_fy_date_start = "2015-01-01" cls.previous_fy_date_end = "2015-12-31" cls.fy_date_start = "2016-01-01" cls.fy_date_end = "2016-12-31" cls.date_start = "2016-01-01" cls.date_end = "2016-12-31" cls.partner = cls.env.ref("base.res_partner_12") cls.unaffected_account = cls.env["account.account"].search( [ ( "user_type_id", "=", cls.env.ref("account.data_unaffected_earnings").id, ), ], limit=1, ) def _create_account_account(self, vals): item = self.env["account.account"].create(vals) if "group_id" in vals: item.group_id = vals["group_id"] return item def _add_move( self, date, receivable_debit, receivable_credit, income_debit, income_credit, unaffected_debit=0, unaffected_credit=0, ): journal = self.env["account.journal"].search( [("company_id", "=", self.env.user.company_id.id)], limit=1 ) partner = self.env.ref("base.res_partner_12") move_vals = { "journal_id": journal.id, "date": date, "line_ids": [ ( 0, 0, { "debit": receivable_debit, "credit": receivable_credit, "partner_id": partner.id, "account_id": self.account100.id, }, ), ( 0, 0, { "debit": income_debit, "credit": income_credit, "partner_id": partner.id, "account_id": self.account200.id, }, ), ( 0, 0, { "debit": unaffected_debit, "credit": unaffected_credit, "partner_id": partner.id, "account_id": self.account110.id, }, ), ( 0, 0, { "debit": receivable_debit, "credit": receivable_credit, "partner_id": partner.id, "account_id": self.account300.id, }, ), ( 0, 0, { "debit": receivable_credit, "credit": receivable_debit, "partner_id": partner.id, "account_id": self.account301.id, }, ), ], } move = self.env["account.move"].create(move_vals) move.action_post() def _get_report_lines( self, with_partners=False, account_ids=False, show_hierarchy=False ): company = self.env.user.company_id trial_balance = self.env["trial.balance.report.wizard"].create( { "date_from": self.date_start, "date_to": self.date_end, "target_move": "posted", "hide_account_at_0": True, "show_hierarchy": show_hierarchy, "company_id": company.id, "account_ids": account_ids, "fy_start_date": self.fy_date_start, "show_partner_details": with_partners, } ) data = trial_balance._prepare_report_trial_balance() res_data = self.env[ "report.account_financial_report.trial_balance" ]._get_report_values(trial_balance, data) return res_data def check_account_in_report(self, account_id, trial_balance): account_in_report = False for account in trial_balance: if account["id"] == account_id and account["type"] == "account_type": account_in_report = True break return account_in_report def _get_account_lines(self, account_id, trial_balance): lines = False for account in trial_balance: if account["id"] == account_id and account["type"] == "account_type": lines = { "initial_balance": account["initial_balance"], "debit": account["debit"], "credit": account["credit"], "final_balance": account["ending_balance"], } return lines def _get_group_lines(self, group_id, trial_balance): lines = False for group in trial_balance: if group["id"] == group_id and group["type"] == "group_type": lines = { "initial_balance": group["initial_balance"], "debit": group["debit"], "credit": group["credit"], "final_balance": group["ending_balance"], } return lines def check_partner_in_report(self, account_id, partner_id, total_amount): partner_in_report = False if account_id in total_amount.keys(): if partner_id in total_amount[account_id]: partner_in_report = True return partner_in_report def _get_partner_lines(self, account_id, partner_id, total_amount): acc_id = account_id prt_id = partner_id lines = { "initial_balance": total_amount[acc_id][prt_id]["initial_balance"], "debit": total_amount[acc_id][prt_id]["debit"], "credit": total_amount[acc_id][prt_id]["credit"], "final_balance": total_amount[acc_id][prt_id]["ending_balance"], } return lines def _sum_all_accounts(self, trial_balance, feature): total = 0.0 for account in trial_balance: if account["type"] == "account_type": for key in account.keys(): if key == feature: total += account[key] return total def test_00_account_group(self): self.assertTrue(self.account100 in self.group1.compute_account_ids) self.assertTrue(self.account200 in self.group2.compute_account_ids) def test_02_account_balance_hierarchy(self): # Generate the general ledger line res_data = self._get_report_lines(show_hierarchy=True) trial_balance = res_data["trial_balance"] check_receivable_account = self.check_account_in_report( self.account100.id, trial_balance ) self.assertFalse(check_receivable_account) check_income_account = self.check_account_in_report( self.account200.id, trial_balance ) self.assertFalse(check_income_account) # Add a move at the previous day of the first day of fiscal year # to check the initial balance self._add_move( date=self.previous_fy_date_end, receivable_debit=1000, receivable_credit=0, income_debit=0, income_credit=1000, ) # Re Generate the trial balance line res_data = self._get_report_lines(show_hierarchy=True) trial_balance = res_data["trial_balance"] check_receivable_account = self.check_account_in_report( self.account100.id, trial_balance ) self.assertTrue(check_receivable_account) check_income_account = self.check_account_in_report( self.account200.id, trial_balance ) self.assertFalse(check_income_account) # Check the initial and final balance account_receivable_lines = self._get_account_lines( self.account100.id, trial_balance ) group1_lines = self._get_group_lines(self.group1.id, trial_balance) self.assertEqual(account_receivable_lines["initial_balance"], 1000) self.assertEqual(account_receivable_lines["debit"], 0) self.assertEqual(account_receivable_lines["credit"], 0) self.assertEqual(account_receivable_lines["final_balance"], 1000) self.assertEqual(group1_lines["initial_balance"], 1000) self.assertEqual(group1_lines["debit"], 0) self.assertEqual(group1_lines["credit"], 0) self.assertEqual(group1_lines["final_balance"], 1000) # Add reversale move of the initial move the first day of fiscal year # to check the first day of fiscal year is not used # to compute the initial balance self._add_move( date=self.fy_date_start, receivable_debit=0, receivable_credit=1000, income_debit=1000, income_credit=0, ) # Re Generate the trial balance line res_data = self._get_report_lines(show_hierarchy=True) trial_balance = res_data["trial_balance"] check_receivable_account = self.check_account_in_report( self.account100.id, trial_balance ) self.assertTrue(check_receivable_account) check_income_account = self.check_account_in_report( self.account200.id, trial_balance ) self.assertTrue(check_income_account) # Check the initial and final balance account_receivable_lines = self._get_account_lines( self.account100.id, trial_balance ) account_income_lines = self._get_account_lines( self.account200.id, trial_balance ) group1_lines = self._get_group_lines(self.group1.id, trial_balance) group2_lines = self._get_group_lines(self.group2.id, trial_balance) self.assertEqual(account_receivable_lines["initial_balance"], 1000) self.assertEqual(account_receivable_lines["debit"], 0) self.assertEqual(account_receivable_lines["credit"], 1000) self.assertEqual(account_receivable_lines["final_balance"], 0) self.assertEqual(account_income_lines["initial_balance"], 0) self.assertEqual(account_income_lines["debit"], 1000) self.assertEqual(account_income_lines["credit"], 0) self.assertEqual(account_income_lines["final_balance"], 1000) self.assertEqual(group1_lines["initial_balance"], 1000) self.assertEqual(group1_lines["debit"], 0) self.assertEqual(group1_lines["credit"], 1000) self.assertEqual(group1_lines["final_balance"], 0) self.assertEqual(group2_lines["initial_balance"], 0) self.assertEqual(group2_lines["debit"], 2000) self.assertEqual(group2_lines["credit"], 0) self.assertEqual(group2_lines["final_balance"], 2000) # Add another move at the end day of fiscal year # to check that it correctly used on report self._add_move( date=self.fy_date_end, receivable_debit=0, receivable_credit=1000, income_debit=1000, income_credit=0, ) # Re Generate the trial balance line res_data = self._get_report_lines(show_hierarchy=True) trial_balance = res_data["trial_balance"] check_receivable_account = self.check_account_in_report( self.account100.id, trial_balance ) self.assertTrue(check_receivable_account) check_income_account = self.check_account_in_report( self.account200.id, trial_balance ) self.assertTrue(check_income_account) # Check the initial and final balance account_receivable_lines = self._get_account_lines( self.account100.id, trial_balance ) account_income_lines = self._get_account_lines( self.account200.id, trial_balance ) group1_lines = self._get_group_lines(self.group1.id, trial_balance) group2_lines = self._get_group_lines(self.group2.id, trial_balance) self.assertEqual(account_receivable_lines["initial_balance"], 1000) self.assertEqual(account_receivable_lines["debit"], 0) self.assertEqual(account_receivable_lines["credit"], 2000) self.assertEqual(account_receivable_lines["final_balance"], -1000) self.assertEqual(account_income_lines["initial_balance"], 0) self.assertEqual(account_income_lines["debit"], 2000) self.assertEqual(account_income_lines["credit"], 0) self.assertEqual(account_income_lines["final_balance"], 2000) self.assertEqual(group1_lines["initial_balance"], 1000) self.assertEqual(group1_lines["debit"], 0) self.assertEqual(group1_lines["credit"], 2000) self.assertEqual(group1_lines["final_balance"], -1000) self.assertEqual(group2_lines["initial_balance"], 0) self.assertEqual(group2_lines["debit"], 4000) self.assertEqual(group2_lines["credit"], 0) self.assertEqual(group2_lines["final_balance"], 4000) def test_03_partner_balance(self): # Generate the trial balance line res_data = self._get_report_lines(with_partners=True) total_amount = res_data["total_amount"] check_partner_receivable = self.check_partner_in_report( self.account100.id, self.partner.id, total_amount ) self.assertFalse(check_partner_receivable) # Add a move at the previous day of the first day of fiscal year # to check the initial balance self._add_move( date=self.previous_fy_date_end, receivable_debit=1000, receivable_credit=0, income_debit=0, income_credit=1000, ) # Re Generate the trial balance line res_data = self._get_report_lines(with_partners=True) total_amount = res_data["total_amount"] check_partner_receivable = self.check_partner_in_report( self.account100.id, self.partner.id, total_amount ) self.assertTrue(check_partner_receivable) # Check the initial and final balance partner_lines = self._get_partner_lines( self.account100.id, self.partner.id, total_amount ) self.assertEqual(partner_lines["initial_balance"], 1000) self.assertEqual(partner_lines["debit"], 0) self.assertEqual(partner_lines["credit"], 0) self.assertEqual(partner_lines["final_balance"], 1000) # Add reversale move of the initial move the first day of fiscal year # to check the first day of fiscal year is not used # to compute the initial balance self._add_move( date=self.fy_date_start, receivable_debit=0, receivable_credit=1000, income_debit=1000, income_credit=0, ) # Re Generate the trial balance line res_data = self._get_report_lines(with_partners=True) total_amount = res_data["total_amount"] check_partner_receivable = self.check_partner_in_report( self.account100.id, self.partner.id, total_amount ) self.assertTrue(check_partner_receivable) # Check the initial and final balance partner_lines = self._get_partner_lines( self.account100.id, self.partner.id, total_amount ) self.assertEqual(partner_lines["initial_balance"], 1000) self.assertEqual(partner_lines["debit"], 0) self.assertEqual(partner_lines["credit"], 1000) self.assertEqual(partner_lines["final_balance"], 0) # Add another move at the end day of fiscal year # to check that it correctly used on report self._add_move( date=self.fy_date_end, receivable_debit=0, receivable_credit=1000, income_debit=1000, income_credit=0, ) # Re Generate the trial balance line res_data = self._get_report_lines(with_partners=True) total_amount = res_data["total_amount"] check_partner_receivable = self.check_partner_in_report( self.account100.id, self.partner.id, total_amount ) self.assertTrue(check_partner_receivable) # Check the initial and final balance partner_lines = self._get_partner_lines( self.account100.id, self.partner.id, total_amount ) self.assertEqual(partner_lines["initial_balance"], 1000) self.assertEqual(partner_lines["debit"], 0) self.assertEqual(partner_lines["credit"], 2000) self.assertEqual(partner_lines["final_balance"], -1000) def test_04_undistributed_pl(self): # Add a P&L Move in the previous FY journal = self.env["account.journal"].search( [("company_id", "=", self.env.user.company_id.id)], limit=1 ) move_vals = { "journal_id": journal.id, "date": self.previous_fy_date_end, "line_ids": [ ( 0, 0, {"debit": 0.0, "credit": 1000.0, "account_id": self.account300.id}, ), ( 0, 0, {"debit": 1000.0, "credit": 0.0, "account_id": self.account100.id}, ), ], } move = self.env["account.move"].create(move_vals) move.action_post() # Generate the trial balance line company = self.env.user.company_id trial_balance = self.env["trial.balance.report.wizard"].create( { "date_from": self.date_start, "date_to": self.date_end, "target_move": "posted", "hide_account_at_0": False, "show_hierarchy": False, "company_id": company.id, "fy_start_date": self.fy_date_start, } ) data = trial_balance._prepare_report_trial_balance() res_data = self.env[ "report.account_financial_report.trial_balance" ]._get_report_values(trial_balance, data) trial_balance = res_data["trial_balance"] check_unaffected_account = self.check_account_in_report( self.unaffected_account.id, trial_balance ) self.assertTrue(check_unaffected_account) unaffected_lines = self._get_account_lines( self.unaffected_account.id, trial_balance ) self.assertEqual(unaffected_lines["initial_balance"], -1000) self.assertEqual(unaffected_lines["debit"], 0) self.assertEqual(unaffected_lines["credit"], 0) self.assertEqual(unaffected_lines["final_balance"], -1000) # Add a P&L Move to the current FY journal = self.env["account.journal"].search( [("company_id", "=", self.env.user.company_id.id)], limit=1 ) move_vals = { "journal_id": journal.id, "date": self.date_start, "line_ids": [ ( 0, 0, {"debit": 0.0, "credit": 1000.0, "account_id": self.account300.id}, ), ( 0, 0, {"debit": 1000.0, "credit": 0.0, "account_id": self.account100.id}, ), ], } move = self.env["account.move"].create(move_vals) move.action_post() # Re Generate the trial balance line trial_balance = self.env["trial.balance.report.wizard"].create( { "date_from": self.date_start, "date_to": self.date_end, "target_move": "posted", "hide_account_at_0": False, "show_hierarchy": False, "company_id": company.id, "fy_start_date": self.fy_date_start, } ) data = trial_balance._prepare_report_trial_balance() res_data = self.env[ "report.account_financial_report.trial_balance" ]._get_report_values(trial_balance, data) trial_balance = res_data["trial_balance"] # The unaffected earnings account is not affected by a journal entry # made to the P&L in the current fiscal year. check_unaffected_account = self.check_account_in_report( self.unaffected_account.id, trial_balance ) self.assertTrue(check_unaffected_account) unaffected_lines = self._get_account_lines( self.unaffected_account.id, trial_balance ) self.assertEqual(unaffected_lines["initial_balance"], -1000) self.assertEqual(unaffected_lines["debit"], 0) self.assertEqual(unaffected_lines["credit"], 0) self.assertEqual(unaffected_lines["final_balance"], -1000) # Add a Move including Unaffected Earnings to the current FY journal = self.env["account.journal"].search( [("company_id", "=", self.env.user.company_id.id)], limit=1 ) move_vals = { "journal_id": journal.id, "date": self.date_start, "line_ids": [ ( 0, 0, {"debit": 0.0, "credit": 1000.0, "account_id": self.account110.id}, ), ( 0, 0, {"debit": 1000.0, "credit": 0.0, "account_id": self.account100.id}, ), ], } move = self.env["account.move"].create(move_vals) move.action_post() # Re Generate the trial balance line trial_balance = self.env["trial.balance.report.wizard"].create( { "date_from": self.date_start, "date_to": self.date_end, "target_move": "posted", "hide_account_at_0": False, "show_hierarchy": False, "company_id": company.id, "fy_start_date": self.fy_date_start, } ) data = trial_balance._prepare_report_trial_balance() res_data = self.env[ "report.account_financial_report.trial_balance" ]._get_report_values(trial_balance, data) trial_balance = res_data["trial_balance"] # The unaffected earnings account affected by a journal entry # made to the unaffected earnings in the current fiscal year. check_unaffected_account = self.check_account_in_report( self.unaffected_account.id, trial_balance ) self.assertTrue(check_unaffected_account) unaffected_lines = self._get_account_lines( self.unaffected_account.id, trial_balance ) self.assertEqual(unaffected_lines["initial_balance"], -1000) self.assertEqual(unaffected_lines["debit"], 0) self.assertEqual(unaffected_lines["credit"], 1000) self.assertEqual(unaffected_lines["final_balance"], -2000) # The totals for the Trial Balance are zero total_initial_balance = self._sum_all_accounts(trial_balance, "initial_balance") total_final_balance = self._sum_all_accounts(trial_balance, "ending_balance") total_debit = self._sum_all_accounts(trial_balance, "debit") total_credit = self._sum_all_accounts(trial_balance, "credit") self.assertEqual(total_initial_balance, 0) self.assertEqual(total_final_balance, 0) self.assertEqual(total_debit, total_credit)
38.875186
26,163
14,478
py
PYTHON
15.0
# Copyright 2018 Forest and Biomass Romania # Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import time from datetime import date from odoo import fields from odoo.tests import tagged from odoo.tests.common import Form from odoo.addons.account.tests.common import AccountTestInvoicingCommon @tagged("post_install", "-at_install") class TestVATReport(AccountTestInvoicingCommon): @classmethod def init_invoice( cls, move_type, name=None, partner=None, invoice_date=None, post=False, lines=None, taxes=None, ): move_form = Form( cls.env["account.move"].with_context(default_move_type=move_type) ) move_form.invoice_date = invoice_date or fields.Date.from_string("2019-01-01") move_form.partner_id = partner or cls.partner_a move_form.name = name or "Test" lines = lines or [] for line in lines: with move_form.invoice_line_ids.new() as line_form: line_form.product_id = line[0] line_form.name = "Test" line_form.account_id = line[1] line_form.quantity = line[2] line_form.price_unit = line[3] if taxes: line_form.tax_ids.clear() line_form.tax_ids.add(taxes) rslt = move_form.save() if post: rslt.action_post() return rslt @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.date_from = time.strftime("%Y-%m-01") cls.date_to = time.strftime("%Y-%m-28") cls.company = cls.env.user.company_id cls.company.country_id = cls.env.ref("base.us").id cls.receivable_account = cls.company_data["default_account_receivable"] cls.income_account = cls.company_data["default_account_revenue"] cls.expense_account = cls.company_data["default_account_expense"] cls.tax_account = cls.env["account.account"].search( [ ("company_id", "=", cls.company.id), ( "user_type_id", "=", cls.env.ref("account.data_account_type_non_current_liabilities").id, ), ], limit=1, ) cls.bank_journal = cls.company_data["default_journal_bank"] cls.tax_tag_01 = cls.env["account.account.tag"].create( { "name": "Tag 01", "applicability": "taxes", "country_id": cls.company.country_id.id, } ) cls.tax_tag_02 = cls.env["account.account.tag"].create( { "name": "Tag 02", "applicability": "taxes", "country_id": cls.company.country_id.id, } ) cls.tax_tag_03 = cls.env["account.account.tag"].create( { "name": "Tag 03", "applicability": "taxes", "country_id": cls.company.country_id.id, } ) cls.tax_group_10 = cls.env["account.tax.group"].create( {"name": "Tax 10%", "sequence": 1} ) cls.tax_group_20 = cls.env["account.tax.group"].create( {"name": "Tax 20%", "sequence": 2} ) cls.tax_10 = cls.env["account.tax"].create( { "name": "Tax 10.0%", "amount": 10.0, "amount_type": "percent", "type_tax_use": "sale", "company_id": cls.company.id, "tax_group_id": cls.tax_group_10.id, "invoice_repartition_line_ids": [ (0, 0, {"factor_percent": 100, "repartition_type": "base"}), ( 0, 0, { "factor_percent": 100, "repartition_type": "tax", "account_id": cls.tax_account.id, "tag_ids": [(6, 0, [cls.tax_tag_01.id, cls.tax_tag_02.id])], }, ), ], "refund_repartition_line_ids": [ (0, 0, {"factor_percent": 100, "repartition_type": "base"}), ( 0, 0, { "factor_percent": 100, "repartition_type": "tax", "account_id": cls.tax_account.id, }, ), ], } ) cls.tax_20 = cls.env["account.tax"].create( { "sequence": 30, "name": "Tax 20.0%", "amount": 20.0, "amount_type": "percent", "type_tax_use": "sale", "company_id": cls.company.id, "cash_basis_transition_account_id": cls.tax_account.id, "tax_group_id": cls.tax_group_20.id, "invoice_repartition_line_ids": [ (0, 0, {"factor_percent": 100, "repartition_type": "base"}), ( 0, 0, { "factor_percent": 100, "repartition_type": "tax", "account_id": cls.tax_account.id, "tag_ids": [(6, 0, [cls.tax_tag_02.id, cls.tax_tag_03.id])], }, ), ], "refund_repartition_line_ids": [ (0, 0, {"factor_percent": 100, "repartition_type": "base"}), ( 0, 0, { "factor_percent": 100, "repartition_type": "tax", "account_id": cls.tax_account.id, }, ), ], } ) cls.init_invoice( "out_invoice", name="Test invoice 1", partner=cls.env.ref("base.res_partner_2"), invoice_date=time.strftime("%Y-%m-03"), post=True, lines=[ (cls.env.ref("product.product_product_4"), cls.income_account, 1, 100.0) ], taxes=cls.tax_10, ) cls.init_invoice( "out_invoice", name="Test invoice 2", partner=cls.env.ref("base.res_partner_2"), invoice_date=time.strftime("%Y-%m-04"), post=True, lines=[ ( cls.env.ref("product.product_product_4"), cls.income_account, 1, 250.0, ), ], taxes=cls.tax_20, ) def _get_report_lines(self, taxgroups=False): based_on = "taxtags" if taxgroups: based_on = "taxgroups" vat_report = self.env["vat.report.wizard"].create( { "date_from": self.date_from, "date_to": self.date_to, "company_id": self.company.id, "based_on": based_on, "tax_detail": True, } ) data = vat_report._prepare_vat_report() res_data = self.env[ "report.account_financial_report.vat_report" ]._get_report_values(vat_report, data) return res_data def check_tag_or_group_in_report(self, tag_or_group_name, vat_report): tag_or_group_in_report = False for tag_or_group in vat_report: if tag_or_group["name"] == tag_or_group_name: tag_or_group_in_report = True break return tag_or_group_in_report def check_tax_in_report(self, tax_name, vat_report): tax_in_report = False for tag_or_group in vat_report: if tag_or_group["taxes"]: for tax in tag_or_group["taxes"]: if tax["name"] == tax_name: tax_in_report = True return tax_in_report def _get_tag_or_group_line(self, tag_or_group_name, vat_report): tag_or_group_net = False tag_or_group_tax = False for tag_or_group in vat_report: if tag_or_group["name"] == tag_or_group_name: tag_or_group_net = tag_or_group["net"] tag_or_group_tax = tag_or_group["tax"] return tag_or_group_net, tag_or_group_tax def _get_tax_line(self, tax_name, vat_report): tax_net = False tax_tax = False for tag_or_group in vat_report: if tag_or_group["taxes"]: for tax in tag_or_group["taxes"]: if tax["name"] == tax_name: tax_net = tax["net"] tax_tax = tax["tax"] return tax_net, tax_tax def test_01_compute(self): # Generate the vat lines res_data = self._get_report_lines() vat_report = res_data["vat_report"] # Check report based on taxtags check_tax_tag_01 = self.check_tag_or_group_in_report( self.tax_tag_01.name, vat_report ) self.assertTrue(check_tax_tag_01) check_tax_tag_02 = self.check_tag_or_group_in_report( self.tax_tag_02.name, vat_report ) self.assertTrue(check_tax_tag_02) check_tax_tag_03 = self.check_tag_or_group_in_report( self.tax_tag_03.name, vat_report ) self.assertTrue(check_tax_tag_03) check_tax_10 = self.check_tax_in_report(self.tax_10.name, vat_report) self.assertTrue(check_tax_10) check_tax_20 = self.check_tax_in_report(self.tax_20.name, vat_report) self.assertTrue(check_tax_20) tag_01_net, tag_01_tax = self._get_tag_or_group_line( self.tax_tag_01.name, vat_report ) tag_02_net, tag_02_tax = self._get_tag_or_group_line( self.tax_tag_02.name, vat_report ) tag_03_net, tag_03_tax = self._get_tag_or_group_line( self.tax_tag_03.name, vat_report ) tax_10_net, tax_10_tax = self._get_tax_line(self.tax_10.name, vat_report) tax_20_net, tax_20_tax = self._get_tax_line(self.tax_20.name, vat_report) self.assertEqual(tag_01_net, -100) self.assertEqual(tag_01_tax, -10) self.assertEqual(tag_02_net, -350) self.assertEqual(tag_02_tax, -60) self.assertEqual(tag_03_net, -250) self.assertEqual(tag_03_tax, -50) self.assertEqual(tax_10_net, -100) self.assertEqual(tax_10_tax, -10) self.assertEqual(tax_20_net, -250) self.assertEqual(tax_20_tax, -50) # Check report based on taxgroups res_data = self._get_report_lines(taxgroups=True) vat_report = res_data["vat_report"] check_group_10 = self.check_tag_or_group_in_report( self.tax_group_10.name, vat_report ) self.assertTrue(check_group_10) check_group_20 = self.check_tag_or_group_in_report( self.tax_group_20.name, vat_report ) self.assertTrue(check_group_20) check_tax_10 = self.check_tax_in_report(self.tax_10.name, vat_report) self.assertTrue(check_tax_10) check_tax_20 = self.check_tax_in_report(self.tax_20.name, vat_report) self.assertTrue(check_tax_20) group_10_net, group_10_tax = self._get_tag_or_group_line( self.tax_group_10.name, vat_report ) group_20_net, group_20_tax = self._get_tag_or_group_line( self.tax_group_20.name, vat_report ) tax_10_net, tax_10_tax = self._get_tax_line(self.tax_10.name, vat_report) tax_20_net, tax_20_tax = self._get_tax_line(self.tax_20.name, vat_report) self.assertEqual(group_10_net, -100) self.assertEqual(group_10_tax, -10) self.assertEqual(group_20_net, -250) self.assertEqual(group_20_tax, -50) self.assertEqual(tax_10_net, -100) self.assertEqual(tax_10_tax, -10) self.assertEqual(tax_20_net, -250) self.assertEqual(tax_20_tax, -50) def test_wizard_date_range(self): vat_wizard = self.env["vat.report.wizard"] date_range = self.env["date.range"] self.type = self.env["date.range.type"].create( {"name": "Month", "company_id": False, "allow_overlap": False} ) dt = date_range.create( { "name": "FS2016", "date_start": time.strftime("%Y-%m-01"), "date_end": time.strftime("%Y-%m-28"), "type_id": self.type.id, } ) wizard = vat_wizard.create( { "date_range_id": dt.id, "date_from": time.strftime("%Y-%m-28"), "date_to": time.strftime("%Y-%m-01"), "tax_detail": True, } ) wizard.onchange_date_range_id() self.assertEqual( wizard.date_from, date(date.today().year, date.today().month, 1) ) self.assertEqual( wizard.date_to, date(date.today().year, date.today().month, 28) ) wizard._export("qweb-pdf") wizard.button_export_html() wizard.button_export_pdf() wizard.button_export_xlsx() wizard = vat_wizard.create( { "date_range_id": dt.id, "date_from": time.strftime("%Y-%m-28"), "date_to": time.strftime("%Y-%m-01"), "based_on": "taxgroups", "tax_detail": True, } ) wizard.onchange_date_range_id() self.assertEqual( wizard.date_from, date(date.today().year, date.today().month, 1) ) self.assertEqual( wizard.date_to, date(date.today().year, date.today().month, 28) ) wizard._export("qweb-pdf") wizard.button_export_html() wizard.button_export_pdf() wizard.button_export_xlsx()
37.314433
14,478
1,198
py
PYTHON
15.0
# Author: Julien Coux # Copyright 2016 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.tests import tagged from odoo.addons.account.tests.common import AccountTestInvoicingCommon @tagged("post_install", "-at_install") class TestOpenItems(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) def test_partner_filter(self): partner_1 = self.env.ref("base.res_partner_1") partner_2 = self.env.ref("base.res_partner_2") partner_3 = self.env.ref("base.res_partner_3") partner_4 = self.env.ref("base.res_partner_4") partner_1.write({"is_company": False, "parent_id": partner_2.id}) partner_3.write({"is_company": False}) expected_list = [partner_2.id, partner_3.id, partner_4.id] context = { "active_ids": [partner_1.id, partner_2.id, partner_3.id, partner_4.id], "active_model": "res.partner", } wizard = self.env["open.items.report.wizard"].with_context(**context) self.assertEqual(wizard._default_partners(), expected_list)
38.645161
1,198
12,557
py
PYTHON
15.0
# Author: Damien Crier # Author: Julien Coux # Author: Jordi Ballester # Copyright 2016 Camptocamp SA # Copyright 2017 Akretion - Alexis de Lattre # Copyright 2017 ForgeFlow, S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import time from ast import literal_eval from odoo import _, api, fields, models from odoo.exceptions import ValidationError from odoo.tools import date_utils class GeneralLedgerReportWizard(models.TransientModel): """General ledger report wizard.""" _name = "general.ledger.report.wizard" _description = "General Ledger Report Wizard" _inherit = "account_financial_report_abstract_wizard" date_range_id = fields.Many2one(comodel_name="date.range", string="Date range") date_from = fields.Date(required=True, default=lambda self: self._init_date_from()) date_to = fields.Date(required=True, default=fields.Date.context_today) fy_start_date = fields.Date(compute="_compute_fy_start_date") target_move = fields.Selection( [("posted", "All Posted Entries"), ("all", "All Entries")], string="Target Moves", required=True, default="posted", ) account_ids = fields.Many2many( comodel_name="account.account", string="Filter accounts" ) centralize = fields.Boolean(string="Activate centralization", default=True) hide_account_at_0 = fields.Boolean( string="Hide account ending balance at 0", help="Use this filter to hide an account or a partner " "with an ending balance at 0. " "If partners are filtered, " "debits and credits totals will not match the trial balance.", ) show_analytic_tags = fields.Boolean() receivable_accounts_only = fields.Boolean() payable_accounts_only = fields.Boolean() partner_ids = fields.Many2many( comodel_name="res.partner", string="Filter partners", default=lambda self: self._default_partners(), ) analytic_tag_ids = fields.Many2many( comodel_name="account.analytic.tag", string="Filter analytic tags" ) account_journal_ids = fields.Many2many( comodel_name="account.journal", string="Filter journals" ) cost_center_ids = fields.Many2many( comodel_name="account.analytic.account", string="Filter cost centers" ) not_only_one_unaffected_earnings_account = fields.Boolean(readonly=True) foreign_currency = fields.Boolean( string="Show foreign currency", help="Display foreign currency for move lines, unless " "account currency is not setup through chart of accounts " "will display initial and final balance in that currency.", default=lambda self: self._default_foreign_currency(), ) account_code_from = fields.Many2one( comodel_name="account.account", help="Starting account in a range", ) account_code_to = fields.Many2one( comodel_name="account.account", help="Ending account in a range", ) grouped_by = fields.Selection( selection=[("", "None"), ("partners", "Partners"), ("taxes", "Taxes")], default="partners", ) show_cost_center = fields.Boolean( string="Show Analytic Account", default=True, ) domain = fields.Char( string="Journal Items Domain", default=[], help="This domain will be used to select specific domain for Journal " "Items", ) def _get_account_move_lines_domain(self): domain = literal_eval(self.domain) if self.domain else [] return domain @api.onchange("account_code_from", "account_code_to") def on_change_account_range(self): if ( self.account_code_from and self.account_code_from.code.isdigit() and self.account_code_to and self.account_code_to.code.isdigit() ): start_range = int(self.account_code_from.code) end_range = int(self.account_code_to.code) self.account_ids = self.env["account.account"].search( [("code", ">=", start_range), ("code", "<=", end_range)] ) if self.company_id: self.account_ids = self.account_ids.filtered( lambda a: a.company_id == self.company_id ) def _init_date_from(self): """set start date to begin of current year if fiscal year running""" today = fields.Date.context_today(self) company = self.company_id or self.env.company last_fsc_month = company.fiscalyear_last_month last_fsc_day = company.fiscalyear_last_day if ( today.month < int(last_fsc_month) or today.month == int(last_fsc_month) and today.day <= last_fsc_day ): return time.strftime("%Y-01-01") else: return False def _default_foreign_currency(self): return self.env.user.has_group("base.group_multi_currency") @api.depends("date_from") def _compute_fy_start_date(self): for wiz in self: if wiz.date_from: date_from, date_to = date_utils.get_fiscal_year( wiz.date_from, day=self.company_id.fiscalyear_last_day, month=int(self.company_id.fiscalyear_last_month), ) wiz.fy_start_date = date_from else: wiz.fy_start_date = False @api.onchange("company_id") def onchange_company_id(self): """Handle company change.""" account_type = self.env.ref("account.data_unaffected_earnings") count = self.env["account.account"].search_count( [ ("user_type_id", "=", account_type.id), ("company_id", "=", self.company_id.id), ] ) self.not_only_one_unaffected_earnings_account = count != 1 if ( self.company_id and self.date_range_id.company_id and self.date_range_id.company_id != self.company_id ): self.date_range_id = False if self.company_id and self.account_journal_ids: self.account_journal_ids = self.account_journal_ids.filtered( lambda p: p.company_id == self.company_id or not p.company_id ) if self.company_id and self.partner_ids: self.partner_ids = self.partner_ids.filtered( lambda p: p.company_id == self.company_id or not p.company_id ) if self.company_id and self.account_ids: if self.receivable_accounts_only or self.payable_accounts_only: self.onchange_type_accounts_only() else: self.account_ids = self.account_ids.filtered( lambda a: a.company_id == self.company_id ) if self.company_id and self.cost_center_ids: self.cost_center_ids = self.cost_center_ids.filtered( lambda c: c.company_id == self.company_id ) res = { "domain": { "account_ids": [], "partner_ids": [], "account_journal_ids": [], "cost_center_ids": [], "date_range_id": [], } } if not self.company_id: return res else: res["domain"]["account_ids"] += [("company_id", "=", self.company_id.id)] res["domain"]["account_journal_ids"] += [ ("company_id", "=", self.company_id.id) ] res["domain"]["partner_ids"] += self._get_partner_ids_domain() res["domain"]["cost_center_ids"] += [ ("company_id", "=", self.company_id.id) ] res["domain"]["date_range_id"] += [ "|", ("company_id", "=", self.company_id.id), ("company_id", "=", False), ] return res @api.onchange("date_range_id") def onchange_date_range_id(self): """Handle date range change.""" if self.date_range_id: self.date_from = self.date_range_id.date_start self.date_to = self.date_range_id.date_end @api.constrains("company_id", "date_range_id") def _check_company_id_date_range_id(self): for rec in self.sudo(): if ( rec.company_id and rec.date_range_id.company_id and rec.company_id != rec.date_range_id.company_id ): raise ValidationError( _( "The Company in the General Ledger Report Wizard and in " "Date Range must be the same." ) ) @api.onchange("receivable_accounts_only", "payable_accounts_only") def onchange_type_accounts_only(self): """Handle receivable/payable accounts only change.""" if self.receivable_accounts_only or self.payable_accounts_only: domain = [("company_id", "=", self.company_id.id)] if self.receivable_accounts_only and self.payable_accounts_only: domain += [("internal_type", "in", ("receivable", "payable"))] elif self.receivable_accounts_only: domain += [("internal_type", "=", "receivable")] elif self.payable_accounts_only: domain += [("internal_type", "=", "payable")] self.account_ids = self.env["account.account"].search(domain) else: self.account_ids = None @api.onchange("partner_ids") def onchange_partner_ids(self): """Handle partners change.""" if self.partner_ids: self.receivable_accounts_only = self.payable_accounts_only = True else: self.receivable_accounts_only = self.payable_accounts_only = False @api.depends("company_id") def _compute_unaffected_earnings_account(self): account_type = self.env.ref("account.data_unaffected_earnings") for record in self: record.unaffected_earnings_account = self.env["account.account"].search( [ ("user_type_id", "=", account_type.id), ("company_id", "=", record.company_id.id), ] ) unaffected_earnings_account = fields.Many2one( comodel_name="account.account", compute="_compute_unaffected_earnings_account", store=True, ) def _print_report(self, report_type): self.ensure_one() data = self._prepare_report_general_ledger() if report_type == "xlsx": report_name = "a_f_r.report_general_ledger_xlsx" else: report_name = "account_financial_report.general_ledger" return ( self.env["ir.actions.report"] .search( [("report_name", "=", report_name), ("report_type", "=", report_type)], limit=1, ) .report_action(self, data=data) ) def _prepare_report_general_ledger(self): self.ensure_one() return { "wizard_id": self.id, "date_from": self.date_from, "date_to": self.date_to, "only_posted_moves": self.target_move == "posted", "hide_account_at_0": self.hide_account_at_0, "foreign_currency": self.foreign_currency, "show_analytic_tags": self.show_analytic_tags, "company_id": self.company_id.id, "account_ids": self.account_ids.ids, "partner_ids": self.partner_ids.ids, "grouped_by": self.grouped_by, "cost_center_ids": self.cost_center_ids.ids, "show_cost_center": self.show_cost_center, "analytic_tag_ids": self.analytic_tag_ids.ids, "journal_ids": self.account_journal_ids.ids, "centralize": self.centralize, "fy_start_date": self.fy_start_date, "unaffected_earnings_account": self.unaffected_earnings_account.id, "account_financial_report_lang": self.env.lang, "domain": self._get_account_move_lines_domain(), } def _export(self, report_type): """Default export is PDF.""" return self._print_report(report_type) def _get_atr_from_dict(self, obj_id, data, key): try: return data[obj_id][key] except KeyError: return data[str(obj_id)][key]
38.996894
12,557
5,673
py
PYTHON
15.0
# Author: Damien Crier, Andrea Stirpe, Kevin Graveman, Dennis Sluijk # Author: Julien Coux # Copyright 2016 Camptocamp SA, Onestein B.V. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class AgedPartnerBalanceWizard(models.TransientModel): """Aged partner balance report wizard.""" _name = "aged.partner.balance.report.wizard" _description = "Aged Partner Balance Wizard" _inherit = "account_financial_report_abstract_wizard" date_at = fields.Date(required=True, default=fields.Date.context_today) date_from = fields.Date() target_move = fields.Selection( [("posted", "All Posted Entries"), ("all", "All Entries")], string="Target Moves", required=True, default="posted", ) account_ids = fields.Many2many( comodel_name="account.account", string="Filter accounts", domain=[("reconcile", "=", True)], required=True, ) receivable_accounts_only = fields.Boolean() payable_accounts_only = fields.Boolean() partner_ids = fields.Many2many(comodel_name="res.partner", string="Filter partners") show_move_line_details = fields.Boolean() account_code_from = fields.Many2one( comodel_name="account.account", help="Starting account in a range", ) account_code_to = fields.Many2one( comodel_name="account.account", help="Ending account in a range", ) @api.onchange("account_code_from", "account_code_to") def on_change_account_range(self): if ( self.account_code_from and self.account_code_from.code.isdigit() and self.account_code_to and self.account_code_to.code.isdigit() ): start_range = int(self.account_code_from.code) end_range = int(self.account_code_to.code) self.account_ids = self.env["account.account"].search( [ ("code", ">=", start_range), ("code", "<=", end_range), ("reconcile", "=", True), ] ) if self.company_id: self.account_ids = self.account_ids.filtered( lambda a: a.company_id == self.company_id ) return { "domain": { "account_code_from": [("reconcile", "=", True)], "account_code_to": [("reconcile", "=", True)], } } @api.onchange("company_id") def onchange_company_id(self): """Handle company change.""" if self.company_id and self.partner_ids: self.partner_ids = self.partner_ids.filtered( lambda p: p.company_id == self.company_id or not p.company_id ) if self.company_id and self.account_ids: if self.receivable_accounts_only or self.payable_accounts_only: self.onchange_type_accounts_only() else: self.account_ids = self.account_ids.filtered( lambda a: a.company_id == self.company_id ) res = {"domain": {"account_ids": [], "partner_ids": []}} if not self.company_id: return res else: res["domain"]["account_ids"] += [("company_id", "=", self.company_id.id)] res["domain"]["partner_ids"] += self._get_partner_ids_domain() return res @api.onchange("account_ids") def onchange_account_ids(self): return {"domain": {"account_ids": [("reconcile", "=", True)]}} @api.onchange("receivable_accounts_only", "payable_accounts_only") def onchange_type_accounts_only(self): """Handle receivable/payable accounts only change.""" domain = [("company_id", "=", self.company_id.id)] if self.receivable_accounts_only or self.payable_accounts_only: if self.receivable_accounts_only and self.payable_accounts_only: domain += [("internal_type", "in", ("receivable", "payable"))] elif self.receivable_accounts_only: domain += [("internal_type", "=", "receivable")] elif self.payable_accounts_only: domain += [("internal_type", "=", "payable")] self.account_ids = self.env["account.account"].search(domain) else: self.account_ids = None def _print_report(self, report_type): self.ensure_one() data = self._prepare_report_aged_partner_balance() if report_type == "xlsx": report_name = "a_f_r.report_aged_partner_balance_xlsx" else: report_name = "account_financial_report.aged_partner_balance" return ( self.env["ir.actions.report"] .search( [("report_name", "=", report_name), ("report_type", "=", report_type)], limit=1, ) .report_action(self, data=data) ) def _prepare_report_aged_partner_balance(self): self.ensure_one() return { "wizard_id": self.id, "date_at": self.date_at, "date_from": self.date_from or False, "only_posted_moves": self.target_move == "posted", "company_id": self.company_id.id, "account_ids": self.account_ids.ids, "partner_ids": self.partner_ids.ids, "show_move_line_details": self.show_move_line_details, "account_financial_report_lang": self.env.lang, } def _export(self, report_type): """Default export is PDF.""" return self._print_report(report_type)
39.124138
5,673
3,424
py
PYTHON
15.0
# Copyright 2018 Forest and Biomass Romania # 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 VATReportWizard(models.TransientModel): _name = "vat.report.wizard" _description = "VAT Report Wizard" _inherit = "account_financial_report_abstract_wizard" date_range_id = fields.Many2one(comodel_name="date.range", string="Date range") date_from = fields.Date("Start Date", required=True) date_to = fields.Date("End Date", required=True) based_on = fields.Selection( [("taxtags", "Tax Tags"), ("taxgroups", "Tax Groups")], required=True, default="taxtags", ) tax_detail = fields.Boolean("Detail Taxes") target_move = fields.Selection( [("posted", "All Posted Entries"), ("all", "All Entries")], string="Target Moves", required=True, default="posted", ) @api.onchange("company_id") def onchange_company_id(self): if ( self.company_id and self.date_range_id.company_id and self.date_range_id.company_id != self.company_id ): self.date_range_id = False res = {"domain": {"date_range_id": []}} if not self.company_id: return res else: res["domain"]["date_range_id"] += [ "|", ("company_id", "=", self.company_id.id), ("company_id", "=", False), ] return res @api.onchange("date_range_id") def onchange_date_range_id(self): """Handle date range change.""" self.date_from = self.date_range_id.date_start self.date_to = self.date_range_id.date_end @api.constrains("company_id", "date_range_id") def _check_company_id_date_range_id(self): for rec in self.sudo(): if ( rec.company_id and rec.date_range_id.company_id and rec.company_id != rec.date_range_id.company_id ): raise ValidationError( _( "The Company in the Vat Report Wizard and in " "Date Range must be the same." ) ) def _print_report(self, report_type): self.ensure_one() data = self._prepare_vat_report() if report_type == "xlsx": report_name = "a_f_r.report_vat_report_xlsx" else: report_name = "account_financial_report.vat_report" return ( self.env["ir.actions.report"] .search( [("report_name", "=", report_name), ("report_type", "=", report_type)], limit=1, ) .report_action(self, data=data) ) def _prepare_vat_report(self): self.ensure_one() return { "wizard_id": self.id, "company_id": self.company_id.id, "date_from": self.date_from, "date_to": self.date_to, "based_on": self.based_on, "only_posted_moves": self.target_move == "posted", "tax_detail": self.tax_detail, "account_financial_report_lang": self.env.lang, } def _export(self, report_type): """Default export is PDF.""" return self._print_report(report_type)
34.24
3,424
5,546
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models class JournalLedgerReportWizard(models.TransientModel): """Journal Ledger report wizard.""" _name = "journal.ledger.report.wizard" _description = "Journal Ledger Report Wizard" _inherit = "account_financial_report_abstract_wizard" date_range_id = fields.Many2one(comodel_name="date.range", string="Date range") date_from = fields.Date(string="Start date", required=True) date_to = fields.Date(string="End date", required=True) journal_ids = fields.Many2many( comodel_name="account.journal", string="Journals", required=False ) move_target = fields.Selection( selection="_get_move_targets", default="posted", required=True ) foreign_currency = fields.Boolean() sort_option = fields.Selection( selection="_get_sort_options", string="Sort entries by", default="move_name", required=True, ) group_option = fields.Selection( selection="_get_group_options", string="Group entries by", default="journal", required=True, ) with_account_name = fields.Boolean(default=False) with_auto_sequence = fields.Boolean(string="Show Auto Sequence", default=False) @api.model def _get_move_targets(self): return [("all", _("All")), ("posted", _("Posted")), ("draft", _("Not Posted"))] @api.model def _get_sort_options(self): return [("move_name", _("Entry number")), ("date", _("Date"))] @api.model def _get_group_options(self): return [("journal", _("Journal")), ("none", _("No group"))] @api.onchange("date_range_id") def onchange_date_range_id(self): self.date_from = self.date_range_id.date_start self.date_to = self.date_range_id.date_end @api.onchange("company_id") def onchange_company_id(self): """Handle company change.""" if ( self.company_id and self.date_range_id.company_id and self.date_range_id.company_id != self.company_id ): self.date_range_id = False if self.company_id and self.journal_ids: self.journal_ids = self.journal_ids.filtered( lambda p: p.company_id == self.company_id or not p.company_id ) res = {"domain": {"journal_ids": []}} if not self.company_id: return res else: res["domain"]["journal_ids"] += [("company_id", "=", self.company_id.id)] return res def _print_report(self, report_type): self.ensure_one() data = self._prepare_report_journal_ledger() if report_type == "xlsx": report_name = "a_f_r.report_journal_ledger_xlsx" else: report_name = "account_financial_report.journal_ledger" return ( self.env["ir.actions.report"] .search( [("report_name", "=", report_name), ("report_type", "=", report_type)], limit=1, ) .report_action(self, data=data) ) def _prepare_report_journal_ledger(self): self.ensure_one() journals = self.journal_ids if not journals: # Not selecting a journal means that we'll display all journals journals = self.env["account.journal"].search( [("company_id", "=", self.company_id.id)] ) return { "wizard_id": self.id, "date_from": self.date_from, "date_to": self.date_to, "move_target": self.move_target, "foreign_currency": self.foreign_currency, "company_id": self.company_id.id, "journal_ids": journals.ids, "sort_option": self.sort_option, "group_option": self.group_option, "with_account_name": self.with_account_name, "account_financial_report_lang": self.env.lang, "with_auto_sequence": self.with_auto_sequence, } def _export(self, report_type): """Default export is PDF.""" self.ensure_one() return self._print_report(report_type) @api.model def _get_ml_tax_description( self, move_line_data, tax_line_data, move_line_taxes_data ): taxes_description = "" if move_line_data["tax_line_id"]: taxes_description = tax_line_data["description"] or tax_line_data["name"] elif move_line_taxes_data: tax_names = [] for tax_key in move_line_taxes_data: tax = move_line_taxes_data[tax_key] tax_names.append(tax["description"] or tax["name"]) taxes_description = ",".join(tax_names) return taxes_description @api.model def _get_partner_name(self, partner_id, partner_data): if partner_id in partner_data.keys(): return partner_data[partner_id]["name"] else: return "" @api.model def _get_atr_from_dict(self, obj_id, data, key): try: return data[obj_id][key] except KeyError: return data[str(obj_id)][key] @api.model def _get_data_from_dict(self, obj_id, data): if data: if isinstance(list(data.keys())[0], int): return data.get(obj_id, False) else: return data.get(obj_id(obj_id), False) else: return False
35.324841
5,546
1,584
py
PYTHON
15.0
# Copyright 2019 Lorenzo Battistini @ TAKOBI # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class AbstractWizard(models.AbstractModel): _name = "account_financial_report_abstract_wizard" _description = "Abstract Wizard" def _get_partner_ids_domain(self): return [ "&", "|", ("company_id", "=", self.company_id.id), ("company_id", "=", False), "|", ("parent_id", "=", False), ("is_company", "=", True), ] def _default_partners(self): context = self.env.context if context.get("active_ids") and context.get("active_model") == "res.partner": partners = self.env["res.partner"].browse(context["active_ids"]) corp_partners = partners.filtered("parent_id") partners -= corp_partners partners |= corp_partners.mapped("commercial_partner_id") return partners.ids company_id = fields.Many2one( comodel_name="res.company", default=lambda self: self.env.company.id, required=False, string="Company", ) def button_export_html(self): self.ensure_one() report_type = "qweb-html" return self._export(report_type) def button_export_pdf(self): self.ensure_one() report_type = "qweb-pdf" return self._export(report_type) def button_export_xlsx(self): self.ensure_one() report_type = "xlsx" return self._export(report_type)
31.058824
1,584
6,537
py
PYTHON
15.0
# Author: Damien Crier # Author: Julien Coux # Copyright 2016 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class OpenItemsReportWizard(models.TransientModel): """Open items report wizard.""" _name = "open.items.report.wizard" _description = "Open Items Report Wizard" _inherit = "account_financial_report_abstract_wizard" date_at = fields.Date(required=True, default=fields.Date.context_today) date_from = fields.Date() target_move = fields.Selection( [("posted", "All Posted Entries"), ("all", "All Entries")], string="Target Moves", required=True, default="posted", ) account_ids = fields.Many2many( comodel_name="account.account", string="Filter accounts", domain=[("reconcile", "=", True)], required=True, ) hide_account_at_0 = fields.Boolean( string="Hide account ending balance at 0", default=True, help="Use this filter to hide an account or a partner " "with an ending balance at 0. " "If partners are filtered, " "debits and credits totals will not match the trial balance.", ) receivable_accounts_only = fields.Boolean() payable_accounts_only = fields.Boolean() partner_ids = fields.Many2many( comodel_name="res.partner", string="Filter partners", default=lambda self: self._default_partners(), ) foreign_currency = fields.Boolean( string="Show foreign currency", help="Display foreign currency for move lines, unless " "account currency is not setup through chart of accounts " "will display initial and final balance in that currency.", default=lambda self: self._default_foreign_currency(), ) show_partner_details = fields.Boolean( default=True, ) account_code_from = fields.Many2one( comodel_name="account.account", ) account_code_to = fields.Many2one( comodel_name="account.account", help="Ending account in a range", ) @api.onchange("account_code_from", "account_code_to") def on_change_account_range(self): if ( self.account_code_from and self.account_code_from.code.isdigit() and self.account_code_to and self.account_code_to.code.isdigit() ): start_range = int(self.account_code_from.code) end_range = int(self.account_code_to.code) self.account_ids = self.env["account.account"].search( [ ("code", ">=", start_range), ("code", "<=", end_range), ("reconcile", "=", True), ] ) if self.company_id: self.account_ids = self.account_ids.filtered( lambda a: a.company_id == self.company_id ) return { "domain": { "account_code_from": [("reconcile", "=", True)], "account_code_to": [("reconcile", "=", True)], } } def _default_foreign_currency(self): return self.env.user.has_group("base.group_multi_currency") @api.onchange("company_id") def onchange_company_id(self): """Handle company change.""" if self.company_id and self.partner_ids: self.partner_ids = self.partner_ids.filtered( lambda p: p.company_id == self.company_id or not p.company_id ) if self.company_id and self.account_ids: if self.receivable_accounts_only or self.payable_accounts_only: self.onchange_type_accounts_only() else: self.account_ids = self.account_ids.filtered( lambda a: a.company_id == self.company_id ) res = {"domain": {"account_ids": [], "partner_ids": []}} if not self.company_id: return res else: res["domain"]["account_ids"] += [("company_id", "=", self.company_id.id)] res["domain"]["partner_ids"] += self._get_partner_ids_domain() return res @api.onchange("account_ids") def onchange_account_ids(self): return {"domain": {"account_ids": [("reconcile", "=", True)]}} @api.onchange("receivable_accounts_only", "payable_accounts_only") def onchange_type_accounts_only(self): """Handle receivable/payable accounts only change.""" domain = [("company_id", "=", self.company_id.id)] if self.receivable_accounts_only or self.payable_accounts_only: if self.receivable_accounts_only and self.payable_accounts_only: domain += [("internal_type", "in", ("receivable", "payable"))] elif self.receivable_accounts_only: domain += [("internal_type", "=", "receivable")] elif self.payable_accounts_only: domain += [("internal_type", "=", "payable")] self.account_ids = self.env["account.account"].search(domain) else: self.account_ids = None def _print_report(self, report_type): self.ensure_one() data = self._prepare_report_open_items() if report_type == "xlsx": report_name = "a_f_r.report_open_items_xlsx" else: report_name = "account_financial_report.open_items" return ( self.env["ir.actions.report"] .search( [("report_name", "=", report_name), ("report_type", "=", report_type)], limit=1, ) .report_action(self, data=data) ) def _prepare_report_open_items(self): self.ensure_one() return { "wizard_id": self.id, "date_at": fields.Date.to_string(self.date_at), "date_from": self.date_from or False, "only_posted_moves": self.target_move == "posted", "hide_account_at_0": self.hide_account_at_0, "foreign_currency": self.foreign_currency, "show_partner_details": self.show_partner_details, "company_id": self.company_id.id, "target_move": self.target_move, "account_ids": self.account_ids.ids, "partner_ids": self.partner_ids.ids or [], "account_financial_report_lang": self.env.lang, } def _export(self, report_type): return self._print_report(report_type)
38.680473
6,537
10,662
py
PYTHON
15.0
# Author: Julien Coux # Copyright 2016 Camptocamp SA # Copyright 2017 Akretion - Alexis de Lattre # Copyright 2018 ForgeFlow, S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError from odoo.tools import date_utils class TrialBalanceReportWizard(models.TransientModel): """Trial balance report wizard.""" _name = "trial.balance.report.wizard" _description = "Trial Balance Report Wizard" _inherit = "account_financial_report_abstract_wizard" date_range_id = fields.Many2one(comodel_name="date.range", string="Date range") date_from = fields.Date(required=True) date_to = fields.Date(required=True) fy_start_date = fields.Date(compute="_compute_fy_start_date") target_move = fields.Selection( [("posted", "All Posted Entries"), ("all", "All Entries")], string="Target Moves", required=True, default="posted", ) show_hierarchy = fields.Boolean( string="Show hierarchy", help="Use when your account groups are hierarchical", ) limit_hierarchy_level = fields.Boolean("Limit hierarchy levels") show_hierarchy_level = fields.Integer("Hierarchy Levels to display", default=1) hide_parent_hierarchy_level = fields.Boolean( "Do not display parent levels", default=False ) account_ids = fields.Many2many( comodel_name="account.account", string="Filter accounts" ) hide_account_at_0 = fields.Boolean( string="Hide accounts at 0", default=True, help="When this option is enabled, the trial balance will " "not display accounts that have initial balance = " "debit = credit = end balance = 0", ) receivable_accounts_only = fields.Boolean() payable_accounts_only = fields.Boolean() show_partner_details = fields.Boolean() partner_ids = fields.Many2many(comodel_name="res.partner", string="Filter partners") journal_ids = fields.Many2many(comodel_name="account.journal") not_only_one_unaffected_earnings_account = fields.Boolean(readonly=True) foreign_currency = fields.Boolean( string="Show foreign currency", help="Display foreign currency for move lines, unless " "account currency is not setup through chart of accounts " "will display initial and final balance in that currency.", ) account_code_from = fields.Many2one( comodel_name="account.account", help="Starting account in a range", ) account_code_to = fields.Many2one( comodel_name="account.account", help="Ending account in a range", ) @api.onchange("account_code_from", "account_code_to") def on_change_account_range(self): if ( self.account_code_from and self.account_code_from.code.isdigit() and self.account_code_to and self.account_code_to.code.isdigit() ): start_range = int(self.account_code_from.code) end_range = int(self.account_code_to.code) self.account_ids = self.env["account.account"].search( [("code", ">=", start_range), ("code", "<=", end_range)] ) if self.company_id: self.account_ids = self.account_ids.filtered( lambda a: a.company_id == self.company_id ) @api.constrains("show_hierarchy", "show_hierarchy_level") def _check_show_hierarchy_level(self): for rec in self: if rec.show_hierarchy and rec.show_hierarchy_level <= 0: raise UserError( _("The hierarchy level to filter on must be greater than 0.") ) @api.depends("date_from") def _compute_fy_start_date(self): for wiz in self: if wiz.date_from: date_from, date_to = date_utils.get_fiscal_year( wiz.date_from, day=self.company_id.fiscalyear_last_day, month=int(self.company_id.fiscalyear_last_month), ) wiz.fy_start_date = date_from else: wiz.fy_start_date = False @api.onchange("company_id") def onchange_company_id(self): """Handle company change.""" account_type = self.env.ref("account.data_unaffected_earnings") count = self.env["account.account"].search_count( [ ("user_type_id", "=", account_type.id), ("company_id", "=", self.company_id.id), ] ) self.not_only_one_unaffected_earnings_account = count != 1 if ( self.company_id and self.date_range_id.company_id and self.date_range_id.company_id != self.company_id ): self.date_range_id = False if self.company_id and self.partner_ids: self.partner_ids = self.partner_ids.filtered( lambda p: p.company_id == self.company_id or not p.company_id ) if self.company_id and self.journal_ids: self.journal_ids = self.journal_ids.filtered( lambda a: a.company_id == self.company_id ) if self.company_id and self.account_ids: if self.receivable_accounts_only or self.payable_accounts_only: self.onchange_type_accounts_only() else: self.account_ids = self.account_ids.filtered( lambda a: a.company_id == self.company_id ) res = { "domain": { "account_ids": [], "partner_ids": [], "date_range_id": [], "journal_ids": [], } } if not self.company_id: return res else: res["domain"]["account_ids"] += [("company_id", "=", self.company_id.id)] res["domain"]["partner_ids"] += self._get_partner_ids_domain() res["domain"]["date_range_id"] += [ "|", ("company_id", "=", self.company_id.id), ("company_id", "=", False), ] res["domain"]["journal_ids"] += [("company_id", "=", self.company_id.id)] return res @api.onchange("date_range_id") def onchange_date_range_id(self): """Handle date range change.""" self.date_from = self.date_range_id.date_start self.date_to = self.date_range_id.date_end @api.constrains("company_id", "date_range_id") def _check_company_id_date_range_id(self): for rec in self.sudo(): if ( rec.company_id and rec.date_range_id.company_id and rec.company_id != rec.date_range_id.company_id ): raise ValidationError( _( "The Company in the Trial Balance Report Wizard and in " "Date Range must be the same." ) ) @api.onchange("receivable_accounts_only", "payable_accounts_only") def onchange_type_accounts_only(self): """Handle receivable/payable accounts only change.""" if self.receivable_accounts_only or self.payable_accounts_only: domain = [("company_id", "=", self.company_id.id)] if self.receivable_accounts_only and self.payable_accounts_only: domain += [("internal_type", "in", ("receivable", "payable"))] elif self.receivable_accounts_only: domain += [("internal_type", "=", "receivable")] elif self.payable_accounts_only: domain += [("internal_type", "=", "payable")] self.account_ids = self.env["account.account"].search(domain) else: self.account_ids = None @api.onchange("show_partner_details") def onchange_show_partner_details(self): """Handle partners change.""" if self.show_partner_details: self.receivable_accounts_only = self.payable_accounts_only = True else: self.receivable_accounts_only = self.payable_accounts_only = False @api.depends("company_id") def _compute_unaffected_earnings_account(self): account_type = self.env.ref("account.data_unaffected_earnings") for record in self: record.unaffected_earnings_account = self.env["account.account"].search( [ ("user_type_id", "=", account_type.id), ("company_id", "=", record.company_id.id), ] ) unaffected_earnings_account = fields.Many2one( comodel_name="account.account", compute="_compute_unaffected_earnings_account", store=True, ) def _print_report(self, report_type): self.ensure_one() data = self._prepare_report_trial_balance() if report_type == "xlsx": report_name = "a_f_r.report_trial_balance_xlsx" else: report_name = "account_financial_report.trial_balance" return ( self.env["ir.actions.report"] .search( [("report_name", "=", report_name), ("report_type", "=", report_type)], limit=1, ) .report_action(self, data=data) ) def _prepare_report_trial_balance(self): self.ensure_one() return { "wizard_id": self.id, "date_from": self.date_from, "date_to": self.date_to, "only_posted_moves": self.target_move == "posted", "hide_account_at_0": self.hide_account_at_0, "foreign_currency": self.foreign_currency, "company_id": self.company_id.id, "account_ids": self.account_ids.ids or [], "partner_ids": self.partner_ids.ids or [], "journal_ids": self.journal_ids.ids or [], "fy_start_date": self.fy_start_date, "show_hierarchy": self.show_hierarchy, "limit_hierarchy_level": self.limit_hierarchy_level, "show_hierarchy_level": self.show_hierarchy_level, "hide_parent_hierarchy_level": self.hide_parent_hierarchy_level, "show_partner_details": self.show_partner_details, "unaffected_earnings_account": self.unaffected_earnings_account.id, "account_financial_report_lang": self.env.lang, } def _export(self, report_type): """Default export is PDF.""" return self._print_report(report_type)
40.233962
10,662
989
py
PYTHON
15.0
# Copyright 2020 Onestein (<https://www.onestein.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class IrActionsReport(models.Model): _inherit = "ir.actions.report" @api.model def _prepare_account_financial_report_context(self, data): lang = data and data.get("account_financial_report_lang") or "" return dict(self.env.context or {}, lang=lang) if lang else False @api.model def _render_qweb_html(self, docids, data=None): context = self._prepare_account_financial_report_context(data) obj = self.with_context(**context) if context else self return super(IrActionsReport, obj)._render_qweb_html(docids, data) @api.model def _render_xlsx(self, docids, data): context = self._prepare_account_financial_report_context(data) obj = self.with_context(**context) if context else self return super(IrActionsReport, obj)._render_xlsx(docids, data)
39.56
989