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
388
py
PYTHON
15.0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase class TestPurchaseOrderApproved(TransactionCase): def test_purchase_order_approved(self): po = self.env["purchase.order"].create( {"partner_id": self.env.ref("base.res_partner_12").id} ) po.button_confirm() po.button_release()
32.333333
388
4,486
py
PYTHON
15.0
# Copyright 2020 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields from odoo.tests.common import TransactionCase class TestPurchaseOrder(TransactionCase): @classmethod def setUpClass(cls): super(TestPurchaseOrder, cls).setUpClass() cls.supplier = cls.env.ref("base.res_partner_1") vals = { "name": "PO TEST", "partner_id": cls.supplier.id, } cls.purchase_order = cls.env["purchase.order"].create(vals) product = cls.env.ref("product.product_product_4") cls.env["purchase.order.line"].create( { "order_id": cls.purchase_order.id, "product_id": product.id, "date_planned": fields.Datetime.now(), "name": "Test", "product_qty": 10.0, "product_uom": product.uom_id.id, "price_unit": 100.0, } ) cls.purchase_order.refresh() def test_01(self): """ Data: * one draft PO * supplier configured with purchase request second approval based on company policy * company configured with purchase_approve_active set to False Test Case: * confirm the PO Expected result: * PO is in state 'purchase' """ self.assertEqual(self.purchase_order.state, "draft") self.purchase_order.company_id.purchase_approve_active = False self.supplier.purchase_requires_second_approval = "based_on_company" self.purchase_order.button_approve() self.assertEqual(self.purchase_order.state, "purchase") def test_02(self): """ Data: * one draft PO * supplier configured with purchase request second approval based on company policy * company configured with purchase_approve_active set to True Test Case: * confirm the PO Expected result: * PO is in state 'approved' """ self.assertEqual(self.purchase_order.state, "draft") self.purchase_order.company_id.purchase_approve_active = True self.supplier.purchase_requires_second_approval = "based_on_company" self.purchase_order.button_approve() self.assertEqual(self.purchase_order.state, "approved") def test_03(self): """ Data: * one draft PO * supplier configured with purchase request second approval based set to 'never' * company configured with purchase_approve_active set to True Test Case: * confirm the PO Expected result: * PO is in state 'purchase' """ self.assertEqual(self.purchase_order.state, "draft") self.purchase_order.company_id.purchase_approve_active = True self.supplier.purchase_requires_second_approval = "never" self.purchase_order.button_approve() self.assertEqual(self.purchase_order.state, "purchase") def test_04(self): """ Data: * one draft PO * supplier configured with purchase request second approval based set to 'always' * company configured with purchase_approve_active set to False Test Case: * confirm the PO Expected result: * PO is in state 'approved' """ self.assertEqual(self.purchase_order.state, "draft") self.purchase_order.company_id.purchase_approve_active = False self.supplier.purchase_requires_second_approval = "always" self.purchase_order.button_approve() self.assertEqual(self.purchase_order.state, "approved") def test_05(self): """ Data: * one draft PO * supplier configured with purchase request second approval based set to 'always' * company configured with purchase_approve_active set to False Test Case: * confirm the PO Expected result: * PO is in state 'approved' """ self.assertEqual(self.purchase_order.state, "draft") self.purchase_order.company_id.purchase_approve_active = False self.supplier.purchase_requires_second_approval = "always" self.purchase_order.button_approve() self.assertEqual(self.purchase_order.state, "approved")
37.383333
4,486
2,035
py
PYTHON
15.0
# Copyright 2017 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class PurchaseOrder(models.Model): _inherit = "purchase.order" state = fields.Selection(selection_add=[("approved", "Approved"), ("purchase",)]) READONLY_STATES = { "purchase": [("readonly", True)], "done": [("readonly", True)], "cancel": [("readonly", True)], "approved": [("readonly", True)], } # Update the readonly states: origin = fields.Char(states=READONLY_STATES) date_order = fields.Datetime(states=READONLY_STATES) partner_id = fields.Many2one(states=READONLY_STATES) dest_address_id = fields.Many2one(states=READONLY_STATES) currency_id = fields.Many2one(states=READONLY_STATES) order_line = fields.One2many(states=READONLY_STATES) company_id = fields.Many2one(states=READONLY_STATES) picking_type_id = fields.Many2one(states=READONLY_STATES) def button_release(self): return super(PurchaseOrder, self).button_approve() def button_approve(self, force=False): two_steps_purchase_approval_ids = [] for rec in self: partner_requires_approve = ( rec.partner_id.purchase_requires_second_approval == "always" ) company_requires_approve = ( rec.partner_id.purchase_requires_second_approval == "based_on_company" and rec.company_id.purchase_approve_active ) if rec.state != "approved" and ( partner_requires_approve or company_requires_approve ): two_steps_purchase_approval_ids.append(rec.id) two_steps_purchase_approval = self.browse(two_steps_purchase_approval_ids) two_steps_purchase_approval.write({"state": "approved"}) one_step_purchase_approval = self - two_steps_purchase_approval return super(PurchaseOrder, one_step_purchase_approval).button_approve( force=force )
39.901961
2,035
724
py
PYTHON
15.0
# Copyright 2017 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class ResCompany(models.Model): _inherit = "res.company" purchase_approve_active = fields.Boolean( string="Use State 'Approved' in Purchase Orders", help="Adds an extra state in purchase orders previous to 'Purchase " "Order'. After confirming and approving a purchase order it will " "go to state 'Approved'. In this state the incoming shipments " "are not created yet and you still can go back to draft. You " "can release the creation of the incoming shipments moving the " "purchase order to state 'Purchase Order'.", )
40.222222
724
401
py
PYTHON
15.0
# Copyright 2018 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" purchase_approve_active = fields.Boolean( related="company_id.purchase_approve_active", string="State 'Approved' in Purchase Orders", readonly=False, )
28.642857
401
471
py
PYTHON
15.0
# Copyright 2020 ACSONE SA/NV # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class ResPartner(models.Model): _inherit = "res.partner" purchase_requires_second_approval = fields.Selection( selection=[ ("never", "Never"), ("based_on_company", "Based on company policy"), ("always", "Always"), ], default="based_on_company", copy=False, )
24.789474
471
609
py
PYTHON
15.0
# Copyright 2021 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Purchase Receipt Expectation - Manual", "version": "15.0.1.0.1", "category": "Purchase Management", "author": "Camptocamp SA, Odoo Community Association (OCA)", "website": "https://github.com/OCA/purchase-workflow", "license": "AGPL-3", "data": [ "security/ir.model.access.csv", "views/purchase_order.xml", "wizards/purchase_order_manual_receipt.xml", ], "depends": [ "purchase_receipt_expectation", ], "installable": True, }
30.45
609
10,136
py
PYTHON
15.0
# Copyright 2021 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from datetime import datetime, timedelta from odoo.tests.common import Form from odoo.addons.purchase_receipt_expectation.tests.test_purchase_receipt_expectation import ( TestPurchaseReceiptExpectation, ) class TestPurchaseReceiptExpectationManual(TestPurchaseReceiptExpectation): @classmethod def setUpClass(cls): super().setUpClass() cls.po_vals_manual = dict( cls.po_vals, receipt_expectation="manual", order_line=[ ( 0, 0, dict( cls.po_vals["order_line"][0][-1], # Update the original PO line qty: 10 dozens instead of # 1 unit, 120 as price unit product_qty=10.0, product_uom=cls.env.ref("uom.product_uom_dozen").id, price_unit=120.0, ), ) ], ) def _create_and_check_manual_receipt_order(self, vals: dict = None): vals = dict(vals or self.po_vals_manual) order = self.env["purchase.order"].create(vals) self.assertEqual(order.receipt_expectation, "manual") order.button_confirm() self.assertEqual(order.incoming_picking_count, 0) return order def _button_wiz_checks_success(self, wiz): wiz.button_check() self.assertEqual(wiz.checks_result, "success") return wiz def _button_wiz_checks_failure(self, wiz): wiz.button_check() self.assertEqual(wiz.checks_result, "failure") return wiz def _button_wiz_confirm_success(self, wiz): action = wiz.button_confirm() self.assertEqual(wiz.checks_result, "success") self.assertEqual(action.get("res_model"), "stock.picking") self.assertTrue(action.get("res_id")) return self.env["stock.picking"].browse(action["res_id"]) def _button_wiz_confirm_failure(self, wiz): action = wiz.button_confirm() self.assertEqual(wiz.checks_result, "failure") self.assertEqual( action.get("res_model"), "purchase.order.manual.receipt.wizard" ) self.assertTrue(action.get("res_id")) new_wiz = self.env["purchase.order.manual.receipt.wizard"].browse( action["res_id"] ) self.assertEqual(wiz, new_wiz) return wiz def _check_picking(self, picking, expected_picking_data, expected_move_lines_data): for fname, value in expected_picking_data: self.assertEqual(picking[fname], value) self.assertEqual( len(picking.move_lines), max(i + 1 for i, _, _ in expected_move_lines_data) ) for index, fname, value in expected_move_lines_data: self.assertEqual(picking.move_lines[index][fname], value) def test_00_manual_receipt_total(self): """Tests manual workflow for total receipt Steps: - Create a PO with `receipt_expectation` set to "manual" - Confirm it - Check that no picking has been created - Create a wizard with scheduled date = tomorrow and: 1 line where qty = 120, UoM = unit, unit price = 10 - Run checks on wizard - Try to confirm wizard - Check picking data Expect: - No picking is created at PO confirm - Pickings' data should match wizards' data - Stock moves' data should match wizard lines' data """ order = self._create_and_check_manual_receipt_order() pol = order.order_line[0] wiz = order._prepare_manual_receipt_wizard() self.assertEqual(len(wiz.line_ids), 1) tomorrow = datetime.now() + timedelta(days=1) with Form(wiz) as wiz_form: # Update scheduled date to `tomorrow` wiz_form.scheduled_date = tomorrow # Update lines: set 1 line with 120 units with wiz_form.line_ids.edit(0) as wiz_line: wiz_line.qty = 120 wiz_line.uom_id = self.env.ref("uom.product_uom_unit") wiz_line.unit_price = 10 wiz = self._button_wiz_checks_success(wiz_form.save()) picking = self._button_wiz_confirm_success(wiz) self._check_picking( picking, expected_picking_data=[ ("id", order.picking_ids.ids[-1]), ("state", "assigned"), ("scheduled_date", tomorrow), ], expected_move_lines_data=[ (0, "product_id", pol.product_id), (0, "price_unit", 10), (0, "product_uom_qty", 120), (0, "product_uom", self.env.ref("uom.product_uom_unit")), ], ) def test_01_manual_receipt_partial(self): """Tests manual workflow for partial receipt Steps: - Create a PO with `receipt_expectation` set to "manual" - Confirm it - Check that no picking has been created - Create a wizard with scheduled date = tomorrow and: 1 line where qty = 1, UoM = dozen, unit price = 120 1 line where qty = 6, UoM = unit, unit price = 15 - Run checks on wizard - Try to confirm wizard - Check picking data Expect: - No picking is created at PO confirm - Pickings' data should match wizards' data - Stock moves' data should match wizard lines' data """ order = self._create_and_check_manual_receipt_order() pol = order.order_line[0] wiz = order._prepare_manual_receipt_wizard() self.assertEqual(len(wiz.line_ids), 1) tomorrow = datetime.now() + timedelta(days=1) with Form(wiz) as wiz_form: # Update scheduled date to `tomorrow` wiz_form.scheduled_date = tomorrow # Update lines: set 1 line with 1dozen, create 1 line with 6units with wiz_form.line_ids.edit(0) as wiz_line: wiz_line.qty = 1 with wiz_form.line_ids.new() as new_wiz_line: new_wiz_line.purchase_line_id = order.order_line[0] new_wiz_line.qty = 6 new_wiz_line.uom_id = self.env.ref("uom.product_uom_unit") new_wiz_line.unit_price = 15 wiz = self._button_wiz_checks_success(wiz_form.save()) picking = self._button_wiz_confirm_success(wiz) self._check_picking( picking, expected_picking_data=[ ("id", order.picking_ids.ids[-1]), ("state", "assigned"), ("scheduled_date", tomorrow), ], expected_move_lines_data=[ (0, "product_id", pol.product_id), (0, "price_unit", 120), (0, "product_uom_qty", 1), (0, "product_uom", self.env.ref("uom.product_uom_dozen")), (1, "product_id", pol.product_id), (1, "price_unit", 15), (1, "product_uom_qty", 6), (1, "product_uom", self.env.ref("uom.product_uom_unit")), ], ) def test_02_manual_receipt_failure(self): """Tests manual workflow with failing wizard data Steps: - Create a PO with `receipt_expectation` set to "manual" - Confirm it - Check that no picking has been created - Create a wizard with scheduled date = tomorrow and: 1 line where qty = 60, UoM = dozen, unit price = 120 1 line where qty = -1, UoM = unit, unit price = 10 - Run checks on wizard - Try to confirm wizard - Remove second line - Run checks on wizard - Try to confirm wizard again - Check picking data Expect: - No picking is created at PO confirm - After first wizard check, result should be a failure - After first wizard confirm, no picking is created yet - After second wizard check, result should be a failure again - After second wizard confirm, picking is created - Pickings' data should match wizards' data - Stock moves' data should match wizard lines' data """ order = self._create_and_check_manual_receipt_order() pol = order.order_line[0] wiz = order._prepare_manual_receipt_wizard() self.assertEqual(len(wiz.line_ids), 1) tomorrow = datetime.now() + timedelta(days=1) with Form(wiz) as wiz_form: # Update scheduled date to `tomorrow` wiz_form.scheduled_date = tomorrow # Update lines: set 1 line with 60dozens, create 1 line with -1unit with wiz_form.line_ids.edit(0) as wiz_line: wiz_line.qty = 60 with wiz_form.line_ids.new() as new_wiz_line: new_wiz_line.purchase_line_id = order.order_line[0] new_wiz_line.qty = -1 new_wiz_line.uom_id = self.env.ref("uom.product_uom_unit") new_wiz_line.unit_price = 10 wiz = self._button_wiz_checks_failure(wiz_form.save()) wiz = self._button_wiz_confirm_failure(wiz) wiz.line_ids[1].unlink() wiz = self._button_wiz_checks_failure(wiz) picking = self._button_wiz_confirm_success(wiz) self._check_picking( picking, expected_picking_data=[ ("id", order.picking_ids.ids[-1]), ("state", "assigned"), ("scheduled_date", tomorrow), ], expected_move_lines_data=[ (0, "product_id", pol.product_id), (0, "price_unit", 120), (0, "product_uom_qty", 60), (0, "product_uom", self.env.ref("uom.product_uom_dozen")), ], )
41.036437
10,136
7,001
py
PYTHON
15.0
# Copyright 2021 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models from odoo.tools.float_utils import float_round class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" feasible_for_manual_receipt = fields.Boolean( compute="_compute_feasible_for_manual_receipt", store=True, ) manually_generated_move_ids = fields.One2many( "stock.move", "purchase_line_id", domain=[("manually_generated", "=", True)], ) manually_receivable_qty = fields.Float( compute="_compute_manually_receivable_qty", digits="Product Unit of Measure", help="Qty that has yet to be received for current line (in product" " PO UoM)", store=True, ) manually_receivable_qty_uom = fields.Float( compute="_compute_manually_receivable_qty", digits="Product Unit of Measure", help="Qty that has yet to be received for current line (in line UoM)", store=True, ) manually_received_qty = fields.Float( compute="_compute_manually_received_qty", digits="Product Unit of Measure", help="Qty that has been received for current line (in product" " PO UoM)", store=True, ) manually_received_qty_uom = fields.Float( compute="_compute_manually_received_qty", digits="Product Unit of Measure", help="Qty that has been received for current line (in product" " PO UoM)", store=True, ) @api.depends("qty_received_method") def _compute_feasible_for_manual_receipt(self): """Computes whether a line can be used in the manual receipt wizard By default, True if `qty_received_method` is "stock_moves" """ for line in self: line.feasible_for_manual_receipt = line.qty_received_method == "stock_moves" @api.depends( "manually_generated_move_ids.manually_received_qty", "manually_generated_move_ids.state", "product_uom", ) def _compute_manually_received_qty(self): """Computes qty that has been manually received Compute process: 1- `manually_received_qty` is the sum of manually received quantities in related stock moves (this value is already measured in product's PO UoM) 2- `manually_received_qty_uom` is equal to `manually_received_qty` converted to line's UoM """ for line in self: received = sum( m.manually_received_qty for m in line.manually_generated_move_ids if m.state != "cancel" ) received_uom = 0 if received: # No need to convert anything if `received` is 0 received_uom = line.product_id.uom_po_id._compute_quantity( received, line.product_uom, round=False ) line.update( { "manually_received_qty": received, "manually_received_qty_uom": received_uom, } ) @api.depends( "feasible_for_manual_receipt", "product_uom", "product_qty", "product_id.uom_po_id", "manually_received_qty", ) def _compute_manually_receivable_qty(self): """Computes qty that can be manually received Compute process: 1- convert `product_qty` to product PO UoM to have the ordered qty 2- get received qty from `manually_received_qty` (already in product PO UoM) 3- `manually_receivable_qty` is ordered qty minus received qty; if the result is negative, then it is considered as 0 4- `manually_receivable_qty_uom` is `manually_receivable_qty` converted to line's UoM """ prec = self.env["decimal.precision"].precision_get("Product Unit of Measure") for line in self: if not line.feasible_for_manual_receipt: line.update( { "manually_receivable_qty": 0, "manually_receivable_qty_uom": 0, } ) continue # Convert ordered qty from line UoM to product PO UoM to be able to # confront it with manually received qty (which is already in # product PO UoM) ordered = line.product_uom._compute_quantity( line.product_qty, line.product_id.uom_po_id, round=False ) received = line.manually_received_qty receivable = max(0, float_round(ordered - received, prec)) receivable_uom = 0 if receivable: # No need to convert anything if `receivable` is 0 receivable_uom = line.product_id.uom_po_id._compute_quantity( receivable, line.product_uom, round=False ) line.update( { "manually_receivable_qty": receivable, "manually_receivable_qty_uom": receivable_uom, } ) def _prepare_manual_receipt_wizard_line_vals_list(self) -> list: """Returns a list of receipt wizard lines values""" vals_list = [] for line in self.filtered("feasible_for_manual_receipt"): vals = line._prepare_manual_receipt_wizard_line_vals() if vals: vals_list.append(vals) return vals_list def _prepare_manual_receipt_wizard_line_vals(self, wizlines=None) -> dict: """Returns a values for a receipt wizard line :param wizlines: existing receipt wizard lines """ self.ensure_one() qty = self.manually_receivable_qty uom = self.product_uom if self.product_id.uom_po_id != uom: qty = self.product_id.uom_po_id._compute_quantity(qty, uom, False) # If already have wizard lines, remove their qty (this method is called # from wizard line's onchange when changing PO line) for line in wizlines if wizlines is not None else []: if line.purchase_line_id == self: qty -= line.uom_id._compute_quantity(line.qty, uom, False) # Return an empty dict if qty <= 0 and the method was not called from # wizard lines onchange; this way, we won't create a new wizard line # when opening a new wizard, but we'll still be able to correctly # update a wizard line when the onchange plays (even if it's qty is 0) qty = max(qty, 0) if not qty and wizlines is None: return {} return { "purchase_line_id": self.id, "product_id": self.product_id.id, "qty": max(qty, 0), "uom_id": uom.id, "unit_price": self.price_unit, }
38.467033
7,001
1,451
py
PYTHON
15.0
# Copyright 2021 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class PurchaseOrder(models.Model): _inherit = "purchase.order" receipt_expectation = fields.Selection( selection_add=[("manual", "Manual")], ondelete={"manual": "set default"}, ) def _create_picking_for_manual_receipt_expectation(self): """Manual => do nothing, users will create picking via the wizard""" return self def button_open_manual_receipt_wizard(self): self.ensure_one() wiz = self._prepare_manual_receipt_wizard() return wiz.open_form_view() def _prepare_manual_receipt_wizard(self): """Creates a manual receipt wizard Used to pre-fill wizard data before opening the form view """ self.ensure_one() vals = self._prepare_manual_receipt_wizard_vals() return self.env["purchase.order.manual.receipt.wizard"].create(vals) def _prepare_manual_receipt_wizard_vals(self) -> dict: self.ensure_one() line_vals = self._prepare_manual_receipt_wizard_line_vals_list() return { "purchase_order_id": self.id, "line_ids": [(0, 0, v) for v in line_vals], } def _prepare_manual_receipt_wizard_line_vals_list(self) -> list: self.ensure_one() return self.order_line._prepare_manual_receipt_wizard_line_vals_list()
33.744186
1,451
1,073
py
PYTHON
15.0
# Copyright 2021 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class StockMove(models.Model): _inherit = "stock.move" manually_generated = fields.Boolean() manually_received_qty = fields.Float( compute="_compute_manually_received_qty", digits="Product Unit of Measure", help="Qty that has been received for stock move (in product's" " PO UoM)", store=True, ) @api.depends( "manually_generated", "product_uom_qty", "product_uom", "product_id.uom_po_id", ) def _compute_manually_received_qty(self): for move in self: if not move.manually_generated: move.manually_received_qty = 0 else: from_uom = move.product_uom to_uom = move.product_id.uom_po_id qty = move.product_uom_qty move.manually_received_qty = from_uom._compute_quantity( qty, to_uom, round=False )
30.657143
1,073
2,471
py
PYTHON
15.0
# Copyright 2021 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class PurchaseOrderManualReceiptLine(models.TransientModel): _name = "purchase.order.manual.receipt.wizard.line" _description = "PO Manual Receipt Wizard Line" wizard_id = fields.Many2one( "purchase.order.manual.receipt.wizard", required=True, ) currency_id = fields.Many2one( "res.currency", related="purchase_line_id.currency_id", readonly=True, ) product_id = fields.Many2one( "product.product", related="purchase_line_id.product_id", readonly=True, store=True, ) purchase_line_id = fields.Many2one( "purchase.order.line", ondelete="cascade", required=True, ) purchase_order_id = fields.Many2one( "purchase.order", related="wizard_id.purchase_order_id", store=True, ) qty = fields.Float( digits="Product Unit of Measure", string="Quantity", ) uom_category_id = fields.Many2one( "uom.category", related="product_id.uom_id.category_id", store=True, ) uom_id = fields.Many2one( "uom.uom", ondelete="cascade", required=True, string="Unit of Measure", ) unit_price = fields.Monetary( required=True, ) @api.onchange("purchase_line_id") def _onchange_purchase_line_id(self): po_line = self.purchase_line_id if po_line: wizlines = self.wizard_id.line_ids vals = po_line._prepare_manual_receipt_wizard_line_vals(wizlines) self.update(vals) def _get_move_vals_list(self) -> list: """Returns list of `stock.move.create()` values""" return [line._get_move_vals() for line in self] def _get_move_vals(self) -> dict: """Returns `stock.move.create()` values""" self.ensure_one() # Use `purchase.order.line` utilities to create picking data properly, # then just update the picking values according to wizard line vals = self.purchase_line_id._prepare_stock_move_vals( self.env["stock.picking"], self.unit_price, self.qty, self.uom_id ) # Picking will be assigned by wizard's `_generate_picking()` method vals.pop("picking_id", False) vals["manually_generated"] = True return vals
28.732558
2,471
8,507
py
PYTHON
15.0
# Copyright 2021 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from collections import defaultdict from odoo import _, fields, models from odoo.tools.float_utils import float_compare class PurchaseOrderManualReceipt(models.TransientModel): _name = "purchase.order.manual.receipt.wizard" _description = "PO Manual Receipt Wizard" line_ids = fields.One2many( "purchase.order.manual.receipt.wizard.line", "wizard_id", ) auto_confirm_picking = fields.Boolean( default=True, help="Automatically confirms the picking after creation." ) checks_result = fields.Selection( [("success", "Success"), ("failure", "Failure")], default="success", ) checks_result_msg = fields.Text( help="Stores error messages result from executed checks" ) purchase_order_id = fields.Many2one( "purchase.order", required=True, ) scheduled_date = fields.Datetime( default=fields.Datetime.now, required=True, ) ####################### # BUTTONS AND ACTIONS # ####################### def open_form_view(self): self.ensure_one() return { "name": _("Manual Receipt"), "type": "ir.actions.act_window", "res_id": self.id, "res_model": "purchase.order.manual.receipt.wizard", "target": "new", "view_mode": "form", } def open_picking_form_view(self, picking): self.ensure_one() return { "name": _("Picking"), "type": "ir.actions.act_window", "res_id": picking.id, "res_model": "stock.picking", "view_mode": "form", } def button_check(self): """Runs checks on the wizard data, then opens the wizard again""" self.ensure_one() errs = self._execute_all_checks() self.write(self._prepare_post_check_vals(errs)) return self.open_form_view() def button_confirm(self): """Confirms wizard data and creates new picking""" self.ensure_one() # Setting `checks_result` to "success" because the user is allowed to # ignore warnings; then, we'll run pre-confirm checks and, if any of # them fails, field `checks_result` should be changed self.checks_result = "success" errs = self._execute_pre_confirm_checks() self.write(self._prepare_post_check_vals(errs)) if self.checks_result != "success": # Some pre-confirm check failed: reopen the wizard self.checks_result_msg += _("\n\nThese checks cannot be skipped!") return self.open_form_view() # Create picking and picking's open form view return self.open_picking_form_view(self._generate_picking()) #################################### # CHECKS AND CHECK-RELATED METHODS # #################################### def _execute_pre_confirm_checks(self) -> dict: """Executes pre-confirm checks on wizard data Returns a dict mapping each check to its error message (even if empty, which means the check was successful) """ self.ensure_one() return {"_check_lines_consistency": self._check_lines_consistency()} def _execute_all_checks(self) -> dict: """Executes checks on wizard data Returns a dict mapping each check to its error message (even if empty, which means the check was successful) """ self.ensure_one() return { "_check_lines_consistency": self._check_lines_consistency(), "_check_product_quantities": self._check_product_quantities(), } def _prepare_post_check_vals(self, errors: dict) -> dict: """Prepares `write` vals to update wizard after executing checks :param dict errors: dict mapping each check name to its error """ res, msg = "success", "" if any(errors.values()): res, msg = "failure", "\n\n".join(m for m in errors.values() if m) return {"checks_result": res, "checks_result_msg": msg} def _check_lines_consistency(self) -> str: """Lines consistency check""" self.ensure_one() err = "" if not self.line_ids or any(line.qty < 0 for line in self.line_ids): err = _( "Receipts must have at least 1 line and every line must have" " strictly positive quantity." ) return err def _check_product_quantities(self) -> str: """Receivable/to receive quantities check""" self.ensure_one() err = "" if self.line_ids: prec = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) mtr = [ (pid, qtr, rq) for (pid, qtr, rq) in self._get_product_quantities_info() if float_compare(qtr, rq, prec) == 1 ] if mtr: msg = [_("Qty to receive exceeds the receivable qty:")] for pid, q1, q2 in mtr: prod = self.env["product.product"].browse(pid) uom_name = prod.uom_po_id.name msg.append( _("- {p}: to receive {q1} {u}, receivable {q2} {u}").format( p=prod.name, q1=q1, q2=q2, u=uom_name ) ) err = "\n".join(msg) return err def _get_product_quantities_info(self) -> list: """Returns list of triplet (prod.id, qty to receive, receivable qty)""" self.ensure_one() receivable = self._get_product_quantities_info_receivable() to_receive = self._get_product_quantities_info_to_receive() return [ (pid, to_receive.get(pid, 0), receivable.get(pid, 0)) for pid in set(to_receive.keys()).union(receivable.keys()) ] def _get_product_quantities_info_receivable(self) -> dict: """Returns mapping {prod: receivable qty} Qty is retrieved from the purchase line's `manually_receivable_qty` field, so it's in product's PO UoM """ self.ensure_one() receivable = defaultdict(float) for po_line in self.line_ids.purchase_line_id: prod, qty = po_line.product_id, po_line.manually_receivable_qty receivable[prod.id] += qty return receivable def _get_product_quantities_info_to_receive(self) -> dict: """Returns mapping {prod: qty to receive} Qty is retrieved from the wizard line's `qty` and is converted into product's PO UoM for consistency with `_get_product_quantities_info_receivable()` (this allows comparing data faster when the two mappings are used together) """ self.ensure_one() to_receive = defaultdict(float) for line in self.line_ids: qty = line.qty from_uom = line.uom_id prod = line.product_id to_uom = prod.uom_po_id to_receive[prod.id] += from_uom._compute_quantity(qty, to_uom, round=False) return to_receive ############################## # PICKING GENERATION METHODS # ############################## def _generate_picking(self): """Creates picking Also manages confirmation and validation if related fields are flagged """ self.ensure_one() vals = self._get_picking_vals() vals["move_lines"] = [(0, 0, v) for v in self._get_move_vals_list()] picking = self.env["stock.picking"].create(vals) if self.auto_confirm_picking: picking.action_confirm() return picking def _get_picking_vals(self) -> dict: """Prepares `stock.picking.create()` vals""" self.ensure_one() order = self.purchase_order_id order = order.with_company(order.company_id) # Use `purchase.order` utilities to create picking data properly, # then just update the picking values according to wizard picking_vals = order._prepare_picking() picking_vals["scheduled_date"] = self.scheduled_date return picking_vals def _get_move_vals_list(self) -> list: """Returns list of `stock.move.create()` values""" self.ensure_one() return self.line_ids._get_move_vals_list()
36.354701
8,507
469
py
PYTHON
15.0
# Copyright 2023 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Purchase Line - Qty To Receive", "version": "15.0.1.0.0", "category": "Purchase Management", "author": "Camptocamp, Odoo Community Association (OCA), Italo Lopes", "website": "https://github.com/OCA/purchase-workflow", "license": "AGPL-3", "data": ["views/purchase_order.xml"], "depends": ["purchase"], "installable": True, }
33.5
469
1,489
py
PYTHON
15.0
# Copyright 2023 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import TransactionCase class TestPurchaseOrderLineQtyToReceive(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.partner = cls.env["res.partner"].create({"name": "Purchase Partner"}) cls.product = cls.env["product.product"].create( # Use "service" type product to be able to set receipt qty manually {"name": "Purchase Product", "type": "service"} ) cls.order = cls.env["purchase.order"].create( { "partner_id": cls.partner.id, "company_id": cls.env.user.company_id.id, } ) cls.order_line = cls.env["purchase.order.line"].create( { "order_id": cls.order.id, "name": cls.product.name, "product_id": cls.product.id, "product_qty": 10.0, } ) def test_00_nothing_received(self): self.order.order_line.qty_received_manual = 0 self.assertEqual(self.order_line.qty_to_receive, 10) def test_01_partially_received(self): self.order.order_line.qty_received_manual = 3 self.assertEqual(self.order_line.qty_to_receive, 7) def test_02_totally_received(self): self.order.order_line.qty_received_manual = 10 self.assertEqual(self.order_line.qty_to_receive, 0)
36.317073
1,489
478
py
PYTHON
15.0
# Copyright 2023 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" qty_to_receive = fields.Float(compute="_compute_qty_to_receive", store=True) @api.depends("product_qty", "qty_received") def _compute_qty_to_receive(self): for line in self: line.qty_to_receive = line.product_qty - line.qty_received
31.866667
478
543
py
PYTHON
15.0
# Copyright 2014-2019 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) { "name": "Purchase - Analytic Account Global", "version": "15.0.1.0.1", "author": "Camptocamp, Odoo Community Association (OCA)", "maintainer": "Camptocamp", "license": "AGPL-3", "category": "Purchase Management", "complexity": "easy", "depends": ["purchase"], "website": "https://github.com/OCA/purchase-workflow", "data": ["views/purchase.xml"], "installable": True, "auto_install": False, }
31.941176
543
3,239
py
PYTHON
15.0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) from datetime import date from odoo.tests.common import Form, TransactionCase class TestPurchaseAnalyticGlobal(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.purchase_order_model = cls.env["purchase.order"] cls.partner_model = cls.env["res.partner"] cls.analytic_account_model = cls.env["account.analytic.account"] cls.partner1 = cls.partner_model.create({"name": "Partner1"}) cls.partner2 = cls.partner_model.create({"name": "Partner2"}) cls.analytic_account1 = cls.analytic_account_model.create( {"name": "Analytic Account 1"} ) cls.analytic_account2 = cls.analytic_account_model.create( {"name": "Analytic Account 2"} ) cls.product = cls.env.ref("product.product_product_4") cls.purchase_order1 = cls.purchase_order_model.create( { "partner_id": cls.partner1.id, "account_analytic_id": cls.analytic_account1.id, "order_line": [ ( 0, 0, { "product_id": cls.product.id, "name": cls.product.name, "product_qty": 10, "price_unit": 50, "product_uom": cls.product.uom_id.id, "date_planned": date.today(), }, ) ], } ) cls.purchase_order2 = cls.purchase_order_model.create( { "partner_id": cls.partner2.id, "order_line": [ ( 0, 0, { "product_id": cls.product.id, "name": cls.product.name, "product_qty": 5, "price_unit": 40, "account_analytic_id": cls.analytic_account2.id, "product_uom": cls.product.uom_id.id, "date_planned": date.today(), }, ) ], } ) def test_purchase_order_check(self): self.assertEqual( self.purchase_order1.order_line[0].account_analytic_id, self.analytic_account1, ) self.assertEqual( self.purchase_order2.account_analytic_id, self.analytic_account2 ) purchase_form = Form(self.purchase_order2) with purchase_form.order_line.new() as line_form: line_form.product_id = self.product line_form.name = self.product.name line_form.product_qty = 10 line_form.price_unit = 20 line_form.account_analytic_id = self.analytic_account1 line_form.product_uom = self.product.uom_id line_form.date_planned = date.today() purchase_form.save() self.assertFalse(self.purchase_order2.account_analytic_id)
39.024096
3,239
1,082
py
PYTHON
15.0
# Copyright 2014-2019 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) from odoo import api, fields, models class PurchaseOrder(models.Model): _inherit = "purchase.order" account_analytic_id = fields.Many2one( "account.analytic.account", string="Analytic Account", compute="_compute_analytic_account", inverse="_inverse_analytic_account", help="This account will be propagated to all lines, if you need " "to use different accounts, define the account at line level.", ) @api.depends("order_line.account_analytic_id") def _compute_analytic_account(self): for rec in self: account = rec.mapped("order_line.account_analytic_id") if len(account) == 1: rec.account_analytic_id = account else: rec.account_analytic_id = False def _inverse_analytic_account(self): for rec in self: if rec.account_analytic_id: rec.order_line.account_analytic_id = rec.account_analytic_id
34.903226
1,082
668
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Product Form Purchase Link", "summary": """ Add an option to display the purchases lines from product""", "version": "15.0.1.1.0", "license": "AGPL-3", "development_status": "Beta", "maintainers": ["rousseldenis"], "author": "ACSONE SA/NV,Odoo Community Association (OCA)", "website": "https://github.com/OCA/purchase-workflow", "depends": ["purchase"], "data": [ "views/purchase_order_line.xml", "views/product_template.xml", "views/product_product.xml", ], "installable": True, }
31.809524
668
457
py
PYTHON
15.0
# Copyright Odoo S.A. # License LGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Purchase Control Menu from v12", "version": "15.0.1.0.0", "category": "Purchase", "author": "Tecnativa, Odoo S.A., Odoo Community Association (OCA)", "website": "https://github.com/OCA/purchase-workflow", "license": "LGPL-3", "depends": ["purchase_stock"], "data": ["views/purchase_views.xml"], "installable": True, }
35.153846
457
634
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Purchase Merge", "summary": "Wizard to merge purchase with required conditions", "version": "15.0.1.0.0", "author": "Camptocamp, Odoo Community Association (OCA)", "website": "https://github.com/OCA/purchase-workflow", "license": "AGPL-3", "category": "Purchase", "depends": ["purchase_order_approved"], "data": [ "security/ir.model.access.csv", "wizard/purchase_merge_views.xml", ], "external_dependencies": {"python": ["openupgradelib"]}, "installable": True, }
35.222222
634
3,236
py
PYTHON
15.0
from odoo.exceptions import UserError from odoo.tests import common class TestPurchaseMerge(common.TransactionCase): @classmethod def setUpClass(cls): super(TestPurchaseMerge, cls).setUpClass() cls.PurchaseMerge = cls.env["purchase.merge.automatic.wizard"] cls.product_1 = cls.env["product.product"].create({"name": "Product 1"}) cls.product_2 = cls.env["product.product"].create({"name": "Product 2"}) cls.partner = cls.env["res.partner"].create({"name": "Partner"}) cls.PurchaseOrder = cls.env["purchase.order"] cls.purchase_order_1 = cls.PurchaseOrder.create( { "partner_id": cls.partner.id, "order_line": [ (0, 0, {"product_id": cls.product_1.id, "price_unit": 10}) ], } ) cls.purchase_order_2 = cls.PurchaseOrder.create( { "partner_id": cls.partner.id, "order_line": [ (0, 0, {"product_id": cls.product_2.id, "price_unit": 10}) ], } ) def test_count_purchase_order_lines(self): self.purchase_merge_1 = self.PurchaseMerge.create( { "purchase_ids": [ (6, 0, [self.purchase_order_1.id, self.purchase_order_2.id]) ], "dst_purchase_id": self.purchase_order_2.id, } ) self.purchase_merge_1.action_merge() self.purchase_order_line_1 = len(self.purchase_order_2.order_line) self.assertEqual(self.purchase_order_line_1, 2) def test_purchase_ids(self): self.purchase_merge_2 = self.PurchaseMerge.create( { "dst_purchase_id": self.purchase_order_2.id, } ) self.assertEqual(self.purchase_merge_2.action_merge(), False) def test_default_purchase_ids(self): context = { "active_ids": [self.purchase_order_1.id, self.purchase_order_2.id], "active_model": self.PurchaseOrder._name, } self.purchase_merge_3 = self.PurchaseMerge.with_context(**context).create({}) self.assertEqual(len(self.purchase_merge_3.dst_purchase_id), 1) self.assertEqual(len(self.purchase_merge_3.purchase_ids), 2) def test_purchase_order_states(self): self.purchase_order_3 = self.env["purchase.order"].create( { "partner_id": self.partner.id, "order_line": [ (0, 0, {"product_id": self.product_2.id, "price_unit": 10}) ], } ) self.purchase_order_3.write({"state": "sent"}) self.purchase_merge_4 = self.PurchaseMerge.create( { "purchase_ids": [ (6, 0, [self.purchase_order_1.id, self.purchase_order_3.id]) ], "dst_purchase_id": self.purchase_order_3.id, } ) with self.assertRaisesRegex( UserError, r"You can't merge purchase orders that aren't in draft state like: .+", ): self.purchase_merge_4._check_state(self.purchase_merge_4.purchase_ids)
38.987952
3,236
8,259
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openupgradelib import openupgrade_merge_records from odoo import _, api, fields, models from odoo.exceptions import ValidationError class MergePurchaseAutomatic(models.TransientModel): """ The idea behind this wizard is to create a list of potential purchases to merge. We use two objects, the first one is the wizard for the end-user. And the second will contain the purchase list to merge. """ _name = "purchase.merge.automatic.wizard" purchase_ids = fields.Many2many("purchase.order") dst_purchase_id = fields.Many2one( comodel_name="purchase.order", string="Destination", ) @api.model def default_get(self, fields_list): res = super(MergePurchaseAutomatic, self).default_get(fields_list) active_ids = self.env.context.get("active_ids") purchase_orders = self.purchase_ids.browse(active_ids) self._check_all_values(purchase_orders) if ( self.env.context.get("active_model") == "purchase.order" and len(active_ids) >= 1 ): res["purchase_ids"] = [(6, 0, active_ids)] res["dst_purchase_id"] = self._get_ordered_purchase(active_ids)[-1].id return res # ---------------------------------------- # Check method # ---------------------------------------- def _check_all_values(self, purchase_orders): """Contain all check method""" self._check_state(purchase_orders) self._check_content(purchase_orders) def _check_state(self, purchase_orders): non_draft_po = purchase_orders.filtered(lambda p: p.state != "draft") if non_draft_po: po_names = non_draft_po.mapped("name") raise ValidationError( _( "You can't merge purchase orders that aren't in draft state like: {}" ).format(po_names) ) def _check_content(self, purchase_orders): error_messages = [] currencies = purchase_orders.currency_id if len(currencies) > 1: error_messages.append( _( "You can't merge purchase orders with different currencies: %s", ", ".join(currencies.mapped("name")), ) ) picking_types = purchase_orders.picking_type_id if len(picking_types) > 1: error_messages.append( _( "You can't merge purchase orders with different picking types: %s", ", ".join(picking_types.mapped("name")), ) ) incoterms = purchase_orders.incoterm_id if len(incoterms) > 1: error_messages.append( _( "You can't merge purchase orders with different incoterms: %s", ", ".join(incoterms.mapped("name")), ) ) payment_terms = purchase_orders.payment_term_id if len(payment_terms) > 1: error_messages.append( _( "You can't merge purchase orders with different payment terms: %s", ", ".join(payment_terms.mapped("name")), ) ) fiscal_positions = purchase_orders.fiscal_position_id if len(fiscal_positions) > 1: error_messages.append( _( "You can't merge purchase orders with different fiscal positions: %s", ", ".join(fiscal_positions.mapped("name")), ) ) suppliers = purchase_orders.partner_id if len(suppliers) > 1: error_messages.append( _( "You can't merge purchase orders with different suppliers: %s", ", ".join(suppliers.mapped("name")), ) ) if error_messages: raise ValidationError("\n".join(error_messages)) # ---------------------------------------- # Update method # ---------------------------------------- @api.model def _update_values(self, src_purchase, dst_purchase): """Update values of dst_purchase with the ones from the src_purchase. :param src_purchase : recordset of source purchase.order :param dst_purchase : record of destination purchase.order """ # merge all order lines + set origin and partner_ref dst_purchase.write(self._get_update_values(src_purchase, dst_purchase)) for po in src_purchase: self._add_message("to", [dst_purchase.name], po) po_names = src_purchase.mapped("name") self._add_message("from", po_names, dst_purchase) @api.model def _get_update_values(self, src_purchase, dst_purchase): """Generate values of dst_purchase with the ones from the src_purchase. :param src_purchase : recordset of source purchase.order :param dst_purchase : record of destination purchase.order """ # initialize destination origin and partner_ref origin = {dst_purchase.origin or ""} origin.update({x.origin for x in src_purchase if x.origin}) partner_ref = {dst_purchase.partner_ref or ""} partner_ref.update({x.partner_ref for x in src_purchase if x.partner_ref}) # Generate destination origin and partner_ref src_order_line = src_purchase.mapped("order_line") return { "order_line": [(4, line, 0) for line in src_order_line.ids], "origin": ", ".join(origin), "partner_ref": ", ".join(partner_ref), } def _add_message(self, way, po_name, po): """Send a message post with to advise the po about the merge. :param way : choice between 'from' or 'to' :param po_name : list of purchase order name to add in the body :param po_name : the po where the message will be posted """ subject = "Merge purchase order" body = _("This purchase order lines have been merged {} : {}").format( way, " ,".join(po_name) ) po.message_post(body=body, subject=subject, content_subtype="plaintext") def _merge(self, purchases, dst_purchase=None): """private implementation of merge purchase :param purchases : ids of purchase to merge :param dst_purchase : record of destination purchase.order """ if len(purchases) < 2: return record_ids = purchases - dst_purchase openupgrade_merge_records.merge_records( env=self.env, model_name=self._name, record_ids=record_ids.ids, target_record_id=dst_purchase.id, ) self._check_all_values(purchases) # remove dst_purchase from purchases to merge if dst_purchase and dst_purchase in purchases: src_purchase = purchases - dst_purchase else: dst_purchase = self.purchase_ids[-1] src_purchase = self.purchase_ids[:-1] # call sub methods to do the merge self._update_values(src_purchase, dst_purchase) # cancel source purchase, since they are merged src_purchase.button_cancel() # ---------------------------------------- # Helpers # ---------------------------------------- @api.model def _get_ordered_purchase(self, purchase_ids): """Helper returns a `purchase.order` recordset ordered by create_date :param purchase_ids : list of purchase ids to sort """ return ( self.env["purchase.order"] .browse(purchase_ids) .sorted( key=lambda p: (p.create_date or ""), reverse=True, ) ) # ---------------------------------------- # Actions # ---------------------------------------- def action_merge(self): """Merge Quotation button. Merge the selected purchases.""" if not self.purchase_ids: return False self._merge(self.purchase_ids, self.dst_purchase_id) return True
36.706667
8,259
584
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) { "name": "Purchase Fully Received", "summary": "Useful filters in Purchases to know the actual status of shipments." "and invoices", "author": "Forgeflow, Odoo Community Association (OCA)", "license": "AGPL-3", "website": "https://github.com/OCA/purchase-workflow", "category": "Purchase", "version": "15.0.1.0.0", "depends": [ "purchase_stock", ], "data": [ "views/purchase_views.xml", ], "installable": True, }
29.2
584
3,534
py
PYTHON
15.0
# Copyright 2022 ForgeFlow, S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from datetime import datetime from odoo import fields from odoo.tests import Form, common, tagged @tagged("-at_install", "post_install") class TestPurchaseOrderAutoLock(common.TransactionCase): def setUp(self): super().setUp() # ENVIRONMENTS self.purchase_order = self.env["purchase.order"] self.partner_id = self.env.ref("base.res_partner_1") self.product_id_1 = self.env.ref("product.product_product_8") self.account_model = self.env["account.account"] self.product_id_1.write({"purchase_method": "purchase"}) self.po_vals = { "partner_id": self.partner_id.id, "order_line": [ ( 0, 0, { "name": self.product_id_1.name, "product_id": self.product_id_1.id, "product_qty": 5.0, "product_uom": self.product_id_1.uom_po_id.id, "price_unit": 500.0, "date_planned": fields.Datetime.now(), }, ), ], } self.po = self.purchase_order.create(self.po_vals) self.currency_eur = self.env.ref("base.EUR") self.supplier = self.env["res.partner"].create({"name": "Test supplier"}) def test_00_purchase_order_not_received(self): """ The PO is not even received """ self.po.button_confirm() self.assertFalse(self.po.is_fully_shipped) def test_01_purchase_order_received_not_invoiced(self): """Test is marked as fully received and to invoice""" self.po.button_confirm() self.po.picking_ids[0].move_lines.write({"quantity_done": 5}) self.po.picking_ids[0].button_validate() self.assertEqual( self.po.order_line[0].product_qty, self.po.order_line[0].qty_received, "The product quantity and the product received should be the same", ) self.assertTrue(self.po.is_fully_shipped) def test_02_purchase_order_received_invoiced_not_posted(self): """If the invoice is not posted is the same thing""" self.po.button_confirm() self.po.picking_ids.move_lines.write({"quantity_done": 5}) self.po.picking_ids[0].button_validate() move_form = Form( self.env["account.move"].with_context(default_move_type="in_invoice") ) move_form.partner_id = self.supplier move_form.currency_id = self.currency_eur move_form.purchase_id = self.po move_form.save() self.assertTrue(self.po.is_fully_shipped) def test_03_purchase_order_received_invoiced_posted(self): """ The invoiced and validated """ self.po.button_confirm() self.po.picking_ids.move_lines.write({"quantity_done": 5}) self.po.picking_ids[0].button_validate() move_form = Form( self.env["account.move"].with_context(default_move_type="in_invoice") ) move_form.partner_id = self.supplier move_form.currency_id = self.currency_eur move_form.purchase_id = self.po move_form.invoice_date = datetime.now() invoice = move_form.save() invoice.action_post() # Run the action and check it is closed self.assertTrue(self.po.is_fully_shipped)
38
3,534
738
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import api, fields, models class PurchaseOrder(models.Model): _inherit = "purchase.order" # This field is more complete than the standard is_shipped is_fully_shipped = fields.Boolean( compute="_compute_is_fully_shipped", store=True, index=True ) @api.depends("order_line.qty_received") def _compute_is_fully_shipped(self): for purchase in self: if all( line.product_qty <= line.qty_received for line in purchase.order_line ): purchase.is_fully_shipped = True else: purchase.is_fully_shipped = False
33.545455
738
822
py
PYTHON
15.0
# Copyright 2020 Ecosoft Co., Ltd. (http://ecosoft.co.th) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Purchase Work Acceptance Invoice Plan", "version": "15.0.1.0.0", "category": "Purchase Management", "author": "Ecosoft, Odoo Community Association (OCA)", "license": "AGPL-3", "website": "https://github.com/OCA/purchase-workflow", "depends": ["purchase_work_acceptance", "purchase_invoice_plan"], "data": [ "security/ir.model.access.csv", "data/server_action.xml", "wizard/select_work_acceptance_invoice_plan_wizard_views.xml", "views/purchase_views.xml", "views/work_acceptance_view.xml", ], "maintainers": ["kittiu"], "installable": True, "auto_install": True, "development_status": "Alpha", }
35.73913
822
6,612
py
PYTHON
15.0
# Copyright 2020 Ecosoft (http://ecosoft.co.th) # 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 Form, TransactionCase class TestPurchaseWorkAcceptanceInvoicePlan(TransactionCase): def setUp(self): super(TestPurchaseWorkAcceptanceInvoicePlan, self).setUp() self.PurchaseInvoicePlan = self.env["purchase.create.invoice.plan"] self.PurchaseOrder = self.env["purchase.order"] self.PurchaseInvoicePlan = self.env["purchase.create.invoice.plan"] self.WaInstallmentWizard = self.env[ "select.work.acceptance.invoice.plan.wizard" ] self.WaInvoiceWizard = self.env["select.work.acceptance.wizard"] 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_product.purchase_method = "purchase" self.date_now = fields.Datetime.now() # Method create wa self.apply_all = self.env.ref( "purchase_work_acceptance_invoice_plan.apply_on_all_product_line" ) self.apply_match_amount = self.env.ref( "purchase_work_acceptance_invoice_plan.apply_on_matched_amount" ) # Enable and Config WA self.env["res.config.settings"].create( { "group_enable_wa_on_po": True, "group_enable_wa_on_in": True, "group_enable_wa_on_invoice": True, } ).execute() def _create_purchase_order(self, product): purchase_order = self.env["purchase.order"].create( { "partner_id": self.test_partner.id, "use_invoice_plan": True, "order_line": [ ( 0, 0, { "product_id": product.id, "product_uom": product.uom_id.id, "name": product.name, "price_unit": product.standard_price, "date_planned": self.date_now, "product_qty": 10, }, ) ], } ) return purchase_order def test_01_purchase_invoice_plan_to_wa(self): purchase_order = self._create_purchase_order(self.test_product) ctx = { "active_id": purchase_order.id, "active_ids": [purchase_order.id], } # Create purchase plan with Form(self.PurchaseInvoicePlan) as p: p.num_installment = 2 purchase_plan = p.save() purchase_plan.with_context(**ctx).purchase_create_invoice_plan() invoice_plan = purchase_order.invoice_plan_ids # Check invoice plan can editable self.assertFalse(invoice_plan[0].no_edit) purchase_order.button_confirm() # Check create wa with last invoice plan, it should warning wa_installment = self.WaInstallmentWizard.with_context(**ctx).create( {"installment_id": invoice_plan[1].id} ) check_installment = wa_installment._onchange_installment_id() self.assertTrue(check_installment.get("warning")) # Check select base on match amount, it not found and raise error with self.assertRaises(UserError): with Form(self.WaInstallmentWizard.with_context(**ctx)) as wa_wizard: wa_wizard.installment_id = invoice_plan[0] wa_wizard.apply_method_id = self.apply_match_amount with Form(self.WaInstallmentWizard.with_context(**ctx)) as wa_wizard: wa_wizard.installment_id = invoice_plan[0] wa_wizard.apply_method_id = self.apply_all wizard = wa_wizard.save() self.assertTrue(wizard.wa_qty_line_ids) self.assertEqual(wizard.wa_qty_line_ids.quantity, 5.0) # Check create wa with po line zero amount, it should error price_subtotal = wizard.order_line_ids.price_subtotal qty_to_accept = wizard.order_line_ids.qty_to_accept installment_amount = wizard.installment_id.amount with self.assertRaises(UserError): wizard.order_line_ids.price_subtotal = 0.0 wizard._compute_wa_qty_line_ids() wizard.order_line_ids.price_subtotal = price_subtotal # Check installment amount is zero, it wa qty should zero too (deposit) wizard.installment_id.amount = 0.0 wizard._compute_wa_qty_line_ids() self.assertEqual(wizard.wa_qty_line_ids.quantity, 0.0) wizard.installment_id.amount = installment_amount # Check add qty over po, it will change to not over qty wizard.order_line_ids.qty_to_accept = 1 wizard._compute_wa_qty_line_ids() self.assertEqual(wizard.wa_qty_line_ids.quantity, 1.0) wizard.order_line_ids.qty_to_accept = qty_to_accept wizard._compute_wa_qty_line_ids() res = wizard.button_create_wa() # Check Work Acceptance ctx_wa = res.get("context") work_acceptance = Form(self.env["work.acceptance"].with_context(**ctx_wa)) wa = work_acceptance.save() self.assertEqual(wa.state, "draft") purchase_order.action_view_wa() self.assertEqual(purchase_order.wa_count, 1) wa.button_accept() self.assertEqual(wa.state, "accept") # Check create wa duplicate, it will error wa_installment = self.WaInstallmentWizard.with_context(**ctx_wa).create( {"installment_id": invoice_plan[0].id} ) with self.assertRaises(UserError): wa_installment.button_create_wa() # Received Products picking = purchase_order.picking_ids[0] self.assertEqual(len(picking.move_ids_without_package), 1) with Form(picking) as p: p.wa_id = wa p.save() picking.move_ids_without_package[0].quantity_done = 5.0 picking.button_validate() # Create invoice following wa with Form(self.WaInvoiceWizard.with_context(**ctx)) as wa_inv_wizard: wa_inv_wizard.wa_id = wa wiz = wa_inv_wizard.save() res = wiz.button_create_vendor_bill() invoice = self.env["account.move"].browse(res["res_id"]) self.assertEqual(sum(invoice.invoice_line_ids.mapped("quantity")), 5.0) self.assertEqual(invoice.wa_id, wa)
45.287671
6,612
9,106
py
PYTHON
15.0
# Copyright 2020 Ecosoft Co., Ltd. (http://ecosoft.co.th). # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import UserError from odoo.tools import float_compare, float_round class SelectWorkAcceptanceInvoicePlanWizard(models.TransientModel): _name = "select.work.acceptance.invoice.plan.wizard" _description = "Select Work Acceptance Invoice Plan Wizard" active_installment_ids = fields.Many2many( comodel_name="purchase.invoice.plan", compute="_compute_active_installment_ids", ) installment_id = fields.Many2one( comodel_name="purchase.invoice.plan", string="Invoice Plan", required=True, domain="[('id', 'in', active_installment_ids), ('installment', '>', 0)]", help="List only installment that has not been used in WA (draft, accepted)", ) apply_method_id = fields.Many2one( comodel_name="ir.actions.server", string="Base On", domain=[ ("usage", "=", "ir_actions_server"), ("model_id.model", "=", "select.work.acceptance.invoice.plan.wizard"), ], help="Choose the method to find matcing product line for this installment", ) order_id = fields.Many2one( comodel_name="purchase.order", default=lambda self: self.env.context.get("active_id"), ) order_line_ids = fields.Many2many( comodel_name="purchase.order.line", relation="select_wa_invoice_plan_order_line_rel", column1="wizard_id", column2="order_line_id", string="Product Filter", domain="[('order_id', '=', order_id)]", compute="_compute_order_line_ids", store=True, readonly=False, help="List of product lines used to create WA. Blank means all", ) wa_qty_line_ids = fields.One2many( comodel_name="select.work.acceptance.invoice.plan.qty", inverse_name="wizard_id", compute="_compute_wa_qty_line_ids", store=True, readonly=False, ) valid_amount = fields.Boolean( compute="_compute_valid_amount", ) @api.model def default_get(self, field_list): res = super().default_get(field_list) order = self.env["purchase.order"].browse( self.env.context.get("active_ids", []) ) not_installment = order.invoice_plan_ids.filtered_domain( [("invoice_type", "!=", "installment")] ) negative_qty = order.order_line.filtered(lambda l: l.product_qty <= 0) if not_installment and not negative_qty: raise UserError(_("Please register deposit first.")) return res @api.depends("installment_id") def _compute_active_installment_ids(self): self.ensure_one() purchase = self.env["purchase.order"].browse( self.env.context.get("active_ids", []) ) installment_ids = ( purchase.wa_ids.filtered(lambda l: l.state != "cancel") .mapped("installment_id") .ids ) self.active_installment_ids = self.env["purchase.invoice.plan"].search( [ ("purchase_id", "=", purchase.id), ("id", "not in", installment_ids), ("installment", ">", 0), ] ) @api.depends("installment_id", "apply_method_id") def _compute_order_line_ids(self): self.ensure_one() self.order_line_ids = False if self.installment_id and self.apply_method_id: ctx = { "installment_id": self.installment_id.id, "purchase_id": self.env.context.get("active_id"), } order_line_ids = self.apply_method_id.with_context(**ctx).run() if not order_line_ids: raise UserError(_("No product line with matched amount!")) self.order_line_ids = order_line_ids # [1,2,3,4] @api.depends("order_line_ids") def _compute_wa_qty_line_ids(self): Decimal = self.env["decimal.precision"] prec = Decimal.precision_get("Product Unit of Measure") for rec in self: rec.wa_qty_line_ids = False expect_amount = rec.installment_id.amount order_lines = rec.order_line_ids lines_amount = sum(order_lines.mapped("price_subtotal")) order = order_lines[:1].order_id all_lines_amount = sum(order.order_line.mapped("price_subtotal")) if rec.order_line_ids and not lines_amount: raise UserError(_("Total purchase amount must not be zero!")) for order_line in rec.order_line_ids: ratio = expect_amount / lines_amount ratio_all = expect_amount / all_lines_amount quantity = float_round(order_line.product_qty * ratio, prec) if not quantity: # good for deposit case quantity = -ratio_all if float_compare(quantity, order_line.qty_to_accept, 2) == 1: quantity = order_line.qty_to_accept amount = quantity * order_line.price_unit expect_amount -= amount order_lines -= order_line lines_amount = sum(order_lines.mapped("price_subtotal")) line = self.env["select.work.acceptance.invoice.plan.qty"].new( {"order_line_id": order_line._origin.id, "quantity": quantity} ) rec.wa_qty_line_ids += line @api.depends("wa_qty_line_ids") def _compute_valid_amount(self): for rec in self: wa_amount = sum(rec.wa_qty_line_ids.mapped("amount")) installment = rec.installment_id.amount rec.valid_amount = float_compare(wa_amount, installment, 2) == 0 @api.onchange("installment_id") def _onchange_installment_id(self): if not self.installment_id: return min_installment = min(self.active_installment_ids.mapped("installment")) if self.installment_id.installment > min_installment: return { "warning": { "title": _("Installment Warning:"), "message": _( "The 1st installment is 'Invoice Plan {}' " "but you are choosing 'Invoice Plan {}'" ).format(min_installment, self.installment_id.installment), } } def button_create_wa(self): purchase = self.env["purchase.order"].browse(self.env.context.get("active_id")) if self.installment_id not in self.active_installment_ids: raise UserError( _("Installment {} is already used by other WA.").format( self.installment_id.installment ) ) res = purchase.with_context( installment_id=self.installment_id.id, wa_qty_line_ids=self.wa_qty_line_ids.ids, ).action_view_wa() res["context"]["default_installment_id"] = self.installment_id.id return res class ComputeWorkAcceptanceInvoicePlan(models.TransientModel): _name = "select.work.acceptance.invoice.plan.qty" _description = "Compute quantity of each WA lines, according to product lines" wizard_id = fields.Many2one( comodel_name="select.work.acceptance.invoice.plan.wizard", ondelete="cascade", ) currency_id = fields.Many2one( comodel_name="res.currency", related="wizard_id.order_id.currency_id", ) order_id = fields.Many2one( related="wizard_id.order_id", ) order_line_id = fields.Many2one( comodel_name="purchase.order.line", string="Product Line", required=True, index=True, domain="[('order_id', '=', order_id)]", ) account_analytic_id = fields.Many2one( comodel_name="account.analytic.account", related="order_line_id.account_analytic_id", ) analytic_tag_ids = fields.Many2many( comodel_name="account.analytic.tag", related="order_line_id.analytic_tag_ids", ) qty_not_accepted = fields.Float( string="Not Accepted", related="order_line_id.qty_to_accept", digits="Product Unit of Measure", ) quantity = fields.Float( string="To Accept", digits="Product Unit of Measure", ) amount = fields.Monetary( compute="_compute_amount", inverse="_inverse_amount", ) _sql_constraints = [ ( "order_line_unique", "unique(wizard_id, order_line_id)", "You are selecting same product line more than one.", ) ] @api.depends("quantity") def _compute_amount(self): for rec in self: rec.amount = rec.quantity * rec.order_line_id.price_unit @api.onchange("amount") def _inverse_amount(self): for rec in self: rec.quantity = rec.amount / rec.order_line_id.price_unit
38.748936
9,106
460
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). from odoo import models class SelectWorkAcceptanceWizard(models.TransientModel): _inherit = "select.work.acceptance.wizard" def _get_purchase_order_with_context(self, order_id): order = super()._get_purchase_order_with_context(order_id) return order.with_context(invoice_plan_id=self.wa_id.installment_id.id)
38.333333
460
1,860
py
PYTHON
15.0
# Copyright 2020 Ecosoft Co., Ltd. (http://ecosoft.co.th) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" def _get_product_qty(self): installment_id = self.env.context.get("installment_id", False) wa_qty_line_ids = self.env.context.get("wa_qty_line_ids", []) if installment_id: if wa_qty_line_ids: qty = self.env["select.work.acceptance.invoice.plan.qty"].search( [("id", "in", wa_qty_line_ids), ("order_line_id", "=", self.id)] ) return qty[:1].quantity else: installment = self.env["purchase.invoice.plan"].browse(installment_id) return self.product_qty * (installment.percent / 100) return super()._get_product_qty() class PurchaseInvoicePlan(models.Model): _inherit = "purchase.invoice.plan" def name_get(self): result = [] for rec in self: result.append( ( rec.id, "%s %s : %s -- %s %s" % ( "Invoice Plan", rec.installment, rec.plan_date, rec.percent, "%", ), ) ) return result def _no_edit(self): no_edit = super()._no_edit() return no_edit or self.env["work.acceptance"].search_count( [ ("installment_id", "=", self.id), ] ) def _compute_new_invoice_quantity(self, invoice_move): if self.env.context.get("wa_id"): return return super()._compute_new_invoice_quantity(invoice_move)
32.631579
1,860
420
py
PYTHON
15.0
# Copyright 2020 Ecosoft Co., Ltd. (http://ecosoft.co.th) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class WorkAcceptance(models.Model): _inherit = "work.acceptance" installment_id = fields.Many2one( comodel_name="purchase.invoice.plan", string="Invoice Plan", readonly=True, copy=False, ondelete="restrict", )
26.25
420
671
py
PYTHON
15.0
# Copyright 2021 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Purchase recommendations according to sales classification", "summary": "Extends the purchase recomendator with classification filters", "version": "15.0.1.0.0", "category": "Purchases", "website": "https://github.com/OCA/purchase-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "depends": [ "purchase_order_product_recommendation", "product_abc_classification_sale", ], "data": ["wizard/purchase_order_recommendation_view.xml"], }
39.470588
671
2,013
py
PYTHON
15.0
# Copyright 2021 Tecnativa # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.addons.purchase_order_product_recommendation.tests import test_recommendation class ClassificationRecommendationCase(test_recommendation.RecommendationCase): @classmethod def setUpClass(cls): super().setUpClass() cls.profile = cls.env["abc.classification.profile"].create( { "name": "Test Profile", "classification_type": "fixed", "data_source": "sale_report", "value_criteria": "sold_delivered_value", } ) cls.a = cls.env["abc.classification.profile.level"].create( {"profile_id": cls.profile.id, "fixed": 10000} ) cls.b = cls.env["abc.classification.profile.level"].create( {"profile_id": cls.profile.id, "fixed": 5000} ) cls.prod_1.abc_classification_profile_id = cls.profile cls.prod_2.abc_classification_profile_id = cls.profile cls.prod_3.abc_classification_profile_id = cls.profile cls.prod_1.abc_classification_level_id = cls.a cls.prod_2.abc_classification_level_id = cls.b cls.prod_3.abc_classification_level_id = cls.b cls.prod_1.seasonality_classification = "high" cls.prod_2.seasonality_classification = "high" cls.prod_3.seasonality_classification = "low" def test_recommendations_by_classification(self): """We can filter by brand""" wizard = self.wizard() wizard.date_begin = wizard.date_end = "2019-02-01" # Just delivered from brand 1 wizard.abc_classification_profile_id = self.profile wizard.abc_classification_level_id = self.b wizard.seasonality_classification = "high" 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_2)
44.733333
2,013
3,350
py
PYTHON
15.0
# Copyright 2021 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models class PurchaseOrderRecommendation(models.TransientModel): _inherit = "purchase.order.recommendation" abc_classification_profile_id = fields.Many2one( comodel_name="abc.classification.profile", string="Classification Profile", ) abc_classification_level_id = fields.Many2one( comodel_name="abc.classification.profile.level", string="Classification Level", domain="[('profile_id', '=', abc_classification_profile_id)]", ) seasonality_classification = fields.Selection( selection=[ ("very high", "Very high"), ("high", "High"), ("medium", "Medium"), ("low", "Low"), ], string="Seasonility", ) def _get_products(self): """Filter products of the given classifications""" products = super()._get_products() if self.abc_classification_profile_id and self.abc_classification_level_id: products = products.filtered( lambda x: x.abc_classification_profile_id == self.abc_classification_profile_id and x.abc_classification_level_id == self.abc_classification_level_id ) if self.seasonality_classification: products = products.filtered( lambda x: ( x.seasonality_classification == self.seasonality_classification ) ) return products def _get_all_products_domain(self): """Filter products of the given classifications""" domain = super()._get_all_products_domain() if self.abc_classification_profile_id and self.abc_classification_level_id: domain += [ ( "abc_classification_profile_id", "=", self.abc_classification_profile_id.id, ), ( "abc_classification_level_id", "=", self.abc_classification_level_id.id, ), ] if self.seasonality_classification: domain += [ ("seasonality_classification", "=", self.seasonality_classification) ] return domain @api.onchange( "abc_classification_profile_id", "abc_classification_level_id", "seasonality_classification", ) def _generate_classification_recommendations(self): """Trigger the general onchange method""" return super()._generate_recommendations() class PurchaseOrderRecommendationLine(models.TransientModel): _inherit = "purchase.order.recommendation.line" abc_classification_profile_id = fields.Many2one( comodel_name="abc.classification.profile", related="product_id.abc_classification_profile_id", readonly=True, ) abc_classification_level_id = fields.Many2one( comodel_name="abc.classification.profile.level", related="product_id.abc_classification_level_id", readonly=True, ) seasonality_classification = fields.Selection( related="product_id.seasonality_classification", readonly=True, )
36.021505
3,350
798
py
PYTHON
15.0
# Copyright 2016 Eficent Business and IT Consulting Services S.L. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl-3.0). { "name": "Purchase Request to Purchase Agreement", "version": "15.0.1.0.1", "author": "Eficent,Acsone SA/NV,Odoo Community Association (OCA)", "website": "https://github.com/OCA/purchase-workflow", "category": "Purchase Management", "depends": [ "purchase_request", "purchase_requisition_stock", ], "data": [ "security/ir.model.access.csv", "wizard/purchase_request_line_make_purchase_requisition_view.xml", "views/purchase_request_view.xml", "views/purchase_requisition_view.xml", "views/purchase_order_view.xml", ], "license": "AGPL-3", "installable": True, }
34.695652
798
8,565
py
PYTHON
15.0
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import SUPERUSER_ID from odoo.exceptions import UserError from odoo.tests import tagged from odoo.tests.common import TransactionCase @tagged("post_install", "-at_install") class TestPurchaseRequestToRequisition(TransactionCase): def setUp(self): super(TestPurchaseRequestToRequisition, 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.requisition"] self.purchase_order = self.env["purchase.order"] self.product1 = self.env.ref("product.product_product_13") self.company2 = self.env["res.company"].create({"name": "Test company"}) self.picking_type2 = self.env["stock.picking.type"].search( [("code", "=", "incoming")] ) def _create_pr(self): vals = { "picking_type_id": self.env.ref("stock.picking_type_in").id, "requested_by": SUPERUSER_ID, "line_ids": [ ( 0, 0, { "product_id": self.product1.id, "product_uom_id": self.env.ref("uom.product_uom_unit").id, "product_qty": 5.0, }, ) ], } purchase_request = self.purchase_request.create(vals) return purchase_request def test_01_purchase_request_to_purchase_requisition(self): purchase_request = self._create_pr() # Test unlink pr line purchase_request.line_ids.unlink() purchase_request = self._create_pr() purchase_request_line = purchase_request.line_ids # Test create TE from PR wiz1 = self.wiz.with_context( active_model="purchase.request", ).create({}) self.assertFalse(wiz1.item_ids) wiz1 = self.wiz.with_context( active_model="purchase.request", active_ids=[purchase_request.id], ).create({}) # Test onchange qty will change to 1 self.product1.description_purchase = "Test description purchase" wiz1.item_ids.onchange_product_id() self.assertEqual(wiz1.item_ids.product_qty, 1) self.assertEqual(len(wiz1.item_ids), 1) # Test create TE from PR Line wiz2 = self.wiz.with_context( active_model="purchase.request.line", active_ids=[purchase_request_line.id], active_id=purchase_request_line.id, ).create({}) self.assertEqual(len(wiz2.item_ids), 1) # check PR or PR Line when create TE must be equal self.assertEqual(wiz1.item_ids.request_id, wiz2.item_ids.request_id) # Test qty < 1 with self.assertRaises(UserError): wiz2.item_ids.product_qty = 0.0 wiz2.make_purchase_requisition() wiz2.make_purchase_requisition() # check PR link to TE must have 1 self.assertEqual(purchase_request.requisition_count, 1) action = purchase_request.action_view_purchase_requisition() self.assertEqual( action["res_id"], purchase_request.line_ids.mapped("requisition_lines.requisition_id").id, ) self.assertTrue( len(purchase_request_line.requisition_lines.ids) == 1, "Should have one purchase agreement line created", ) # Not edit after created TE self.assertFalse(purchase_request.line_ids.is_editable) self.assertEqual( purchase_request.line_ids.requisition_qty, purchase_request.line_ids.product_qty, ) # Test delete line PR after created TE with self.assertRaises(UserError): purchase_request.line_ids.unlink() requisition = purchase_request_line.requisition_lines.requisition_id self.assertEqual( len(purchase_request.line_ids), len(requisition.line_ids), "Should have the same lines", ) requisition_line = requisition.line_ids self.assertEqual( requisition_line.product_id.id, purchase_request_line.product_id.id, "Should have the same products", ) self.assertEqual( purchase_request.state, requisition.state, "Should have the same state" ) # check TE link to PR must have 1 self.assertEqual(requisition.purchase_request_count, 1) action = requisition.action_view_purchase_request() self.assertEqual( action["res_id"], requisition.line_ids.purchase_request_lines.request_id.id, ) self.assertTrue(requisition.line_ids.has_purchase_request_lines) # check TE Line link to PR Line action = requisition.line_ids.action_open_request_line_tree_view() self.assertEqual( action["domain"][0][2], requisition.line_ids.purchase_request_lines.ids, ) # Check state self.assertEqual(purchase_request.line_ids.requisition_state, "draft") requisition.action_cancel() self.assertEqual(purchase_request.line_ids.requisition_state, "cancel") requisition.action_in_progress() self.assertEqual(purchase_request.line_ids.requisition_state, "in_progress") requisition.action_open() # Create Purchase from Agreement purchase = self.purchase_order.create( { "partner_id": self.env.ref("base.res_partner_12").id, "requisition_id": requisition.id, } ) purchase._onchange_requisition_id() purchase.button_confirm() self.assertEqual( len(purchase.order_line.purchase_request_lines), 1, "Should have a link between order lines and request lines", ) # close TE requisition.action_done() self.assertEqual(purchase_request.line_ids.requisition_state, "done") def test_02_multi_purchase_request_to_purchase_requisition(self): purchase_request1 = self._create_pr() purchase_request2 = self._create_pr() # 2 PR Line (diff PR) create 1 TE purchase_request_line = purchase_request1.line_ids + purchase_request2.line_ids wiz = self.wiz.with_context( active_model="purchase.request.line", active_ids=purchase_request_line.ids, ).create({}) # Test multi company in 1 TE pr_line = wiz.item_ids[-1].line_id with self.assertRaises(UserError): pr_line.company_id = self.company2 wiz.make_purchase_requisition() # Test multi picking in 1 TE picking_type2 = self.picking_type2.filtered( lambda l: l != pr_line.request_id.picking_type_id ) with self.assertRaises(UserError): pr_line.request_id.picking_type_id = picking_type2[0] wiz.make_purchase_requisition() wiz.make_purchase_requisition() requisition = purchase_request_line.requisition_lines.requisition_id action = requisition.action_view_purchase_request() self.assertEqual( action["domain"][0][2], requisition.mapped("line_ids.purchase_request_lines.request_id").ids, ) # Test add old TE into new TE requisition = purchase_request1.line_ids.requisition_lines.requisition_id wiz = self.wiz.with_context( active_model="purchase.request", active_ids=purchase_request1.ids, ).create({"purchase_requisition_id": requisition.id}) wiz.make_purchase_requisition() # 1 PR create 2 TE wiz = self.wiz.with_context( active_model="purchase.request", active_ids=purchase_request1.ids, ).create({}) wiz.make_purchase_requisition() purchase_request1.action_view_purchase_requisition() def test_03_product_request_requisition(self): with self.assertRaises(UserError): self.product1.write( { "purchase_request": True, "purchase_requisition": "tenders", } ) self.product1.write( { "purchase_request": False, "purchase_requisition": "tenders", } )
41.57767
8,565
7,591
py
PYTHON
15.0
# Copyright 2016 Eficent Business and IT Consulting Services S.L. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl-3.0). from odoo import _, api, fields, models from odoo.exceptions import UserError class PurchaseRequestLineMakePurchaseRequisition(models.TransientModel): _name = "purchase.request.line.make.purchase.requisition" _description = "Purchase Request Line Make Purchase Agreement" item_ids = fields.One2many( "purchase.request.line.make.purchase.requisition.item", "wiz_id", string="Items" ) purchase_requisition_id = fields.Many2one( "purchase.requisition", string="Purchase Agreement", required=False, domain=[("state", "=", "draft")], ) @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.product_qty, "product_uom_id": line.product_uom_id.id, } @api.model def default_get(self, fields): res = super(PurchaseRequestLineMakePurchaseRequisition, self).default_get( fields ) # By default, expect called from PR Line request_line_obj = self.env["purchase.request.line"] request_line_ids = self.env.context.get("active_ids") active_model = self.env.context.get("active_model") # For case called from PR if active_model == "purchase.request": request_ids = self.env.context.get("active_ids") requests = self.env["purchase.request"].browse(request_ids) request_line_ids = requests.mapped("line_ids").ids active_model = "purchase.request.line" if not request_line_ids: return res assert active_model == "purchase.request.line", "Bad context propagation" items = [] for line in request_line_obj.browse(request_line_ids): items.append([0, 0, self._prepare_item(line)]) res["item_ids"] = items return res @api.model def _prepare_purchase_requisition(self, item, picking_type_id, company_id): data = { "origin": "", "picking_type_id": picking_type_id, "company_id": company_id, "currency_id": item.request_id.currency_id.id, } return data @api.model def _prepare_purchase_requisition_line(self, pr, item): return { "requisition_id": pr.id, "product_qty": item.product_qty, "product_id": item.product_id.id, "product_uom_id": item.product_uom_id.id, "purchase_request_lines": [(4, item.line_id.id)], "account_analytic_id": item.line_id.analytic_account_id.id or False, "analytic_tag_ids": item.line_id.analytic_tag_ids.ids or False, "product_description_variants": item.name, } @api.model def _get_requisition_line_search_domain(self, requisition, item): vals = [ ("requisition_id", "=", requisition.id), ("product_id", "=", item.product_id.id or False), ("product_uom_id", "=", item.product_uom_id.id or False), ("account_analytic_id", "=", item.line_id.analytic_account_id.id or False), ("analytic_tag_ids", "in", item.line_id.analytic_tag_ids.ids or False), ] return vals def make_purchase_requisition(self): pr_obj = self.env["purchase.requisition"] pr_line_obj = self.env["purchase.requisition.line"] company_id = False picking_type_id = False requisition = False res = [] for item in self.item_ids: line = item.line_id if item.product_qty <= 0.0: raise UserError(_("Enter a positive quantity.")) line_company_id = line.company_id and line.company_id.id or False # check company from line previous if company_id 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 # check picking_type_id from line previous if picking_type_id and line_picking_type.id != picking_type_id: raise UserError( _("You have to select lines from the same picking type.") ) else: picking_type_id = line_picking_type.id if self.purchase_requisition_id: requisition = self.purchase_requisition_id if not requisition: preq_data = self._prepare_purchase_requisition( item, picking_type_id, company_id ) requisition = pr_obj.create(preq_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_requisition_line_search_domain(requisition, item) available_pr_lines = pr_line_obj.search(domain) if available_pr_lines: pr_line = available_pr_lines[0] new_qty = pr_line.product_qty + item.product_qty pr_line.product_qty = new_qty pr_line.purchase_request_lines = [(4, line.id)] else: po_line_data = self._prepare_purchase_requisition_line( requisition, item ) pr_line_obj.create(po_line_data) res.append(requisition.id) return { "domain": "[('id','in', [" + ",".join(map(str, res)) + "])]", "name": _("Purchase Agreement"), "view_type": "form", "view_mode": "tree,form", "res_model": "purchase.requisition", "view_id": False, "context": False, "type": "ir.actions.act_window", } class PurchaseRequestLineMakePurchaseRequisitionItem(models.TransientModel): _name = "purchase.request.line.make.purchase.requisition.item" _description = "Purchase Request Line Make Purchase Agreement Item" wiz_id = fields.Many2one( "purchase.request.line.make.purchase.requisition", string="Wizard", required=True, ondelete="cascade", readonly=True, ) line_id = fields.Many2one( "purchase.request.line", string="Purchase Request Line", required=True, ) request_id = fields.Many2one( "purchase.request", related="line_id.request_id", string="Purchase Request", readonly=True, ) product_id = fields.Many2one("product.product", string="Product") name = fields.Char(string="Description", required=True) product_qty = fields.Float( string="Quantity to Bid", digits="Product Unit of Measure", ) product_uom_id = fields.Many2one("uom.uom", string="UoM") @api.onchange("product_id", "product_uom_id") def onchange_product_id(self): if self.product_id: name = self.product_id.display_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
38.532995
7,591
4,426
py
PYTHON
15.0
# Copyright 2016 Eficent Business and IT Consulting Services S.L. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl-3.0). from odoo import _, api, fields, models from odoo.exceptions import UserError class PurchaseRequest(models.Model): _inherit = "purchase.request" requisition_count = fields.Integer( compute="_compute_requisition_count", ) def _compute_requisition_count(self): for rec in self: rec.requisition_count = len( rec.mapped("line_ids.requisition_lines.requisition_id") ) def action_view_purchase_requisition(self): action = self.env["ir.actions.act_window"]._for_xml_id( "purchase_requisition.action_purchase_requisition" ) requisitions = self.mapped("line_ids.requisition_lines.requisition_id") if len(requisitions) == 1: action["res_id"] = requisitions.id action["views"] = [ ( self.env.ref( "purchase_requisition.view_purchase_requisition_form" ).id, "form", ) ] else: action["view_mode"] = "tree,form" action["domain"] = [("id", "in", requisitions.ids)] action["context"] = {} return action class PurchaseRequestLine(models.Model): _inherit = "purchase.request.line" @api.depends("purchase_lines") def _compute_is_editable(self): res = super(PurchaseRequestLine, self)._compute_is_editable() editable_records = self.filtered(lambda p: p in self and p.requisition_lines) editable_records.write({"is_editable": False}) return res def _compute_requisition_qty(self): for rec in self: requisition_qty = 0.0 req_lines = rec.requisition_lines.filtered( lambda l: l.requisition_id.state != "cancel" ) for req_line in req_lines: requisition_qty += req_line.product_qty rec.requisition_qty = requisition_qty @api.depends("requisition_lines.requisition_id.state") def _compute_requisition_state(self): for rec in self: temp_req_state = False if rec.requisition_lines: if any( [ pr_line.requisition_id.state == "done" for pr_line in rec.requisition_lines ] ): temp_req_state = "done" elif all( [ pr_line.requisition_id.state == "cancel" for pr_line in rec.requisition_lines ] ): temp_req_state = "cancel" elif any( [ pr_line.requisition_id.state == "in_progress" for pr_line in rec.requisition_lines ] ): temp_req_state = "in_progress" elif all( [ pr_line.requisition_id.state in ("draft", "cancel") for pr_line in rec.requisition_lines ] ): temp_req_state = "draft" rec.requisition_state = temp_req_state requisition_lines = fields.Many2many( "purchase.requisition.line", "purchase_request_purchase_requisition_line_rel", "purchase_request_line_id", "purchase_requisition_line_id", string="Purchase Agreement Lines", readonly=True, copy=False, ) requisition_qty = fields.Float( compute="_compute_requisition_qty", string="Quantity in a Bid" ) requisition_state = fields.Selection( compute="_compute_requisition_state", string="Bid Status", type="selection", selection=lambda self: self.env["purchase.requisition"] ._fields["state"] .selection, store=True, ) is_editable = fields.Boolean(compute="_compute_is_editable", string="Is editable") def unlink(self): if self.filtered("requisition_lines"): raise UserError( _("You cannot delete a record that refers to purchase lines!") ) return super().unlink()
34.850394
4,426
751
py
PYTHON
15.0
# Copyright 2016 Eficent Business and IT Consulting Services S.L. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl-3.0). from odoo import _, api, models from odoo.exceptions import ValidationError class ProductTemplate(models.Model): _inherit = "product.template" @api.constrains("purchase_request", "purchase_requisition") def _check_request_requisition(self): for product in self: if product.purchase_request and product.purchase_requisition == "tenders": raise ValidationError( _( "Only one selection of Purchase " "Request or Purchase Agreement allowed" ) ) return True
35.761905
751
4,834
py
PYTHON
15.0
# Copyright 2016 Eficent Business and IT Consulting Services S.L. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl-3.0). from odoo import _, api, fields, models class PurchaseRequisition(models.Model): _inherit = "purchase.requisition" purchase_request_count = fields.Integer( compute="_compute_purchase_request_count", ) @api.model def _purchase_request_confirm_message_content(self, pr, request, request_dict): if not request_dict: request_dict = {} title = _("Bid confirmation {} for your Request {}").format( pr.name, request.name ) message = "<h3>{}</h3><ul>".format(title) message += _( "The following requested items from Purchase Request {} " "have now being sent to Suppliers using Purchase Bid " "{}:" ).format(request.name, pr.name) for line in request_dict.values(): message += _("<li><b>{}</b>: Total bid quantity {} {}</li>").format( line["name"], line["product_qty"], line["product_uom_id"], ) message += "</ul>" return message def _purchase_request_confirm_message(self): request_obj = self.env["purchase.request"] for pr in self: requests_dict = {} for line in pr.line_ids: for request_line in line.purchase_request_lines: request_id = request_line.request_id.id if request_id not in requests_dict: requests_dict[request_id] = {} data = { "name": request_line.name, "product_qty": line.product_qty, "product_uom_id": line.product_uom_id.name, } requests_dict[request_id][request_line.id] = data for request_id in requests_dict.keys(): request = request_obj.browse(request_id) message = self._purchase_request_confirm_message_content( pr, request, requests_dict[request_id] ) request.message_post(body=message, subtype_xmlid="mail.mt_comment") return True def action_in_progress(self): res = super().action_in_progress() self._purchase_request_confirm_message() return res def _compute_purchase_request_count(self): for rec in self: rec.purchase_request_count = len( rec.mapped("line_ids.purchase_request_lines.request_id") ) def action_view_purchase_request(self): action = self.env["ir.actions.act_window"]._for_xml_id( "purchase_request.purchase_request_form_action" ) requests = self.mapped("line_ids.purchase_request_lines.request_id") if len(requests) == 1: action["res_id"] = requests.id action["views"] = [ (self.env.ref("purchase_request.view_purchase_request_form").id, "form") ] else: action["view_mode"] = "tree,form" action["domain"] = [("id", "in", requests.ids)] action["context"] = {} return action class PurchaseRequisitionLine(models.Model): _inherit = "purchase.requisition.line" def _compute_has_purchase_request_lines(self): for rec in self: rec.has_purchase_request_lines = bool(rec.purchase_request_lines) purchase_request_lines = fields.Many2many( comodel_name="purchase.request.line", relation="purchase_request_purchase_requisition_line_rel", column1="purchase_requisition_line_id", column2="purchase_request_line_id", readonly=True, copy=False, ) has_purchase_request_lines = fields.Boolean( compute="_compute_has_purchase_request_lines", ) def action_open_request_line_tree_view(self): """ :return dict: dictionary value for created view """ domain = [("id", "in", self.mapped("purchase_request_lines").ids)] return { "name": _("Purchase Request Lines"), "type": "ir.actions.act_window", "res_model": "purchase.request.line", "view_type": "form", "view_mode": "tree,form", "domain": domain, } def _prepare_purchase_order_line( self, name, product_qty=0.0, price_unit=0.0, taxes_ids=False ): res = super()._prepare_purchase_order_line( name, product_qty, price_unit, taxes_ids ) pr_lines = self.mapped("purchase_request_lines") res["purchase_request_lines"] = ( pr_lines and [(4, line.id) for line in pr_lines] or [] ) return res
36.900763
4,834
650
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. # (http://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Purchase Tags", "summary": "Allows to add multiple tags to purchase orders", "version": "15.0.1.0.0", "author": "ForgeFlow, Odoo Community Association (OCA)", "website": "https://github.com/OCA/purchase-workflow", "category": "Purchases", "depends": ["purchase"], "data": [ "security/ir.model.access.csv", "views/purchase_view.xml", "views/purchase_tag_view.xml", ], "license": "AGPL-3", "installable": True, "application": False, }
30.952381
650
440
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. # (http://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class PurchaseOrder(models.Model): _inherit = "purchase.order" tag_ids = fields.Many2many( comodel_name="purchase.tag", relation="purchase_order_tag_rel", column1="purchase_order_id", column2="tag_id", string="Tags", )
25.882353
440
582
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. # (http://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from random import randint from odoo import fields, models class PurchaseTag(models.Model): _name = "purchase.tag" _description = "Purchase Tag" def _get_default_color(self): return randint(1, 11) name = fields.Char("Tag Name", required=True, translate=True) color = fields.Integer(default=_get_default_color) _sql_constraints = [ ("tag_name_uniq", "unique (name)", "Tag name already exists !"), ]
26.454545
582
700
py
PYTHON
15.0
# Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Purchase Work Acceptance Tier Validation", "summary": "Extends the functionality of Work Acceptance to " "support a tier validation process.", "version": "15.0.1.0.0", "category": "Purchases", "website": "https://github.com/OCA/purchase-workflow", "author": "Ecosoft, Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "development_status": "Alpha", "maintainers": ["kittiu"], "depends": ["purchase_work_acceptance", "base_tier_validation"], "data": ["views/work_acceptance_view.xml"], }
38.888889
700
504
py
PYTHON
15.0
# Copyright 2019 Ecosoft Co., Ltd. (http://ecosoft.co.th) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import common class TestPurchaseWorkAcceptanceTierValidation(common.TransactionCase): def setUp(self): super().setUp() self.tier_definition = self.env["tier.definition"] def test_get_tier_validation_model_names(self): self.assertIn( "work.acceptance", self.tier_definition._get_tier_validation_model_names() )
33.6
504
421
py
PYTHON
15.0
# Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, 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("work.acceptance") return res
30.071429
421
368
py
PYTHON
15.0
# Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class WorkAcceptance(models.Model): _name = "work.acceptance" _inherit = ["work.acceptance", "tier.validation"] _state_from = ["draft"] _state_to = ["accept"] _tier_validation_manual_config = False
28.307692
368
513
py
PYTHON
15.0
# Copyright 2015 AvanzOSC # Copyright 2017-2019 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Purchase order line stock available", "version": "15.0.1.0.0", "license": "AGPL-3", "author": "AvanzOSC," "Tecnativa," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/purchase-workflow", "depends": ["purchase_stock"], "category": "Purchases", "data": ["views/purchase_view.xml"], "installable": True, }
36.642857
513
2,186
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) from datetime import date from odoo.tests import common class TestPurchase(common.TransactionCase): def setUp(self): super().setUp() self.company = self.env.ref("base.main_company") self.partner = self.env["res.partner"].create({"name": "Test partner"}) self.product = self.env["product.product"].create( {"name": "Test product", "detailed_type": "product"} ) self.location_stock = self.env.ref("stock.stock_location_stock") self.location_suppliers = self.env.ref("stock.stock_location_suppliers") self.purchase = self.env["purchase.order"].create( { "partner_id": self.partner.id, "order_line": [ ( 0, 0, { "product_id": self.product.id, "product_uom": self.product.uom_id.id, "name": self.product.name, "price_unit": self.product.standard_price, "date_planned": date.today(), "product_qty": 1, }, ) ], } ) self.purchase_line = self.purchase.order_line[0] self._create_stock_move(10.0) def _create_stock_move(self, qty): stock_move = self.env["stock.move"].create( { "name": self.product.display_name, "location_id": self.location_suppliers.id, "location_dest_id": self.location_stock.id, "product_id": self.product.id, "product_uom": self.product.uom_id.id, "product_uom_qty": qty, } ) stock_move._action_done() def test_purchase_line_virtual_available(self): self.assertEqual(self.purchase_line.virtual_available, 10.0) self._create_stock_move(20.0) self.assertEqual(self.purchase_line.virtual_available, 30.0)
38.315789
2,184
217
py
PYTHON
15.0
from odoo import fields, models class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" virtual_available = fields.Float( related="product_id.virtual_available", readonly=True )
24.111111
217
640
py
PYTHON
15.0
# Copyright 2019 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Purchase Order General Discount", "summary": "General discount per purchase order", "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_discount"], "data": [ "views/purchase_order_view.xml", "views/res_partner_view.xml", "views/res_config_view.xml", ], }
33.684211
640
2,620
py
PYTHON
15.0
# Copyright 2019 Tecnativa - David Vidal # Copyright 2022 Tecnativa - Pilar Vargas # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from lxml import etree from odoo.tests import TransactionCase, common class TestPurchaseOrderLineInput(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.partner = cls.env["res.partner"].create( {"name": "Test", "purchase_general_discount": 10.0} ) cls.product = cls.env["product.product"].create( {"name": "test_product", "type": "service"} ) order_form = common.Form(cls.env["purchase.order"]) order_form.partner_id = cls.partner with order_form.order_line.new() as line_form: line_form.product_id = cls.product line_form.product_uom = cls.product.uom_id line_form.product_qty = 1 line_form.price_unit = 1000.00 cls.order = order_form.save() cls.View = cls.env["ir.ui.view"] def test_01_default_partner_discount(self): self.order.onchange_partner_id() self.assertEqual( self.order.general_discount, self.partner.purchase_general_discount ) def test_02_sale_order_values(self): self.order.general_discount = 10 self.order.action_update_general_discount() self.assertEqual(self.order.order_line.price_subtotal, 900.00) def _get_ctx_from_view(self, res): order_xml = etree.XML(res["arch"]) order_line_path = "//field[@name='order_line']" order_line_field = order_xml.xpath(order_line_path)[0] return order_line_field.attrib.get("context", "{}") def test_03_default_line_discount_value(self): res = self.order.fields_view_get( view_id=self.env.ref( "purchase_order_general_discount.purchase_order_form" ).id, view_type="form", ) ctx = self._get_ctx_from_view(res) self.assertTrue("default_discount" in ctx) view = self.View.create( { "name": "test", "type": "form", "model": "purchase.order", "arch": """ <data> <field name='order_line' context="{'default_product_uom_qty': 3.0}"> </field> </data> """, } ) res = self.order.fields_view_get(view_id=view.id, view_type="form") ctx = self._get_ctx_from_view(res) self.assertTrue("default_discount" in ctx)
36.901408
2,620
2,792
py
PYTHON
15.0
# Copyright 2019 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from lxml import etree from odoo import api, fields, models class PurchaseOrder(models.Model): _inherit = "purchase.order" general_discount = fields.Float( digits="Discount", string="Gen. Disc. (%)", ) _sql_constraints = [ ( "general_discount_limit", "CHECK (general_discount <= 100.0)", "Discount must be lower than 100%.", ), ] @api.onchange("partner_id") def onchange_partner_id(self): res = super().onchange_partner_id() self.general_discount = ( self.partner_id.commercial_partner_id.purchase_general_discount ) return res def _get_general_discount_field(self): """We can set in settings another discount field to be applied For example, if we had purchase_triple_dicount, we could set the general discount in discount3 to be applied after all other discounts""" discount_field = self.company_id.purchase_general_discount_field return discount_field or "discount" @api.onchange("general_discount") def onchange_general_discount(self): discount_field = self._get_general_discount_field() self.mapped("order_line").update({discount_field: self.general_discount}) def action_update_general_discount(self): for order in self: order.onchange_general_discount() @api.model def fields_view_get( self, view_id=None, view_type="form", toolbar=False, submenu=False ): """The purpose of this is to write a context on "order_line" field respecting other contexts on this field. There is a PR (https://github.com/odoo/odoo/pull/26607) to odoo for avoiding this. If merged, remove this method and add the attribute in the field. """ res = super().fields_view_get( view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu, ) if view_type == "form": discount_field = self._get_general_discount_field() order_xml = etree.XML(res["arch"]) order_line_fields = order_xml.xpath("//field[@name='order_line']") if order_line_fields: order_line_field = order_line_fields[0] context = order_line_field.attrib.get("context", "{}").replace( "{", "{{'default_{}': general_discount, ".format(discount_field), 1, ) order_line_field.attrib["context"] = context res["arch"] = etree.tostring(order_xml) return res
35.794872
2,792
1,183
py
PYTHON
15.0
# Copyright 2019 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models class ResCompany(models.Model): _inherit = "res.company" purchase_general_discount_field = fields.Selection( selection="_get_purchase_discount_fields", string="Purchase Discount Field", default="discount", help="Set the purchase line discount field in which the " "discounts will be applied.", ) @api.model def _get_purchase_discount_fields(self): """Extensible method to add possible discounts. We offer in advance the posibility of using purchase_triple_discount so no bridge module is needed""" discount_fields = [("discount", _("Discount"))] purchase_line_fields = self.env["purchase.order.line"]._fields.keys() if "discount2" in purchase_line_fields: discount_fields += [ ("discount2", _("Discount 2")), ] if "discount3" in purchase_line_fields: discount_fields += [ ("discount3", _("Discount 3")), ] return discount_fields
36.96875
1,183
374
py
PYTHON
15.0
# Copyright 2019 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" purchase_general_discount_field = fields.Selection( related="company_id.purchase_general_discount_field", readonly=False, )
31.166667
374
362
py
PYTHON
15.0
# Copyright 2019 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class ResPartner(models.Model): _inherit = "res.partner" purchase_general_discount = fields.Float( digits="Discount", string="Purchase General Discount (%)", company_dependent=True, )
25.857143
362
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
6,335
py
PYTHON
15.0
import setuptools with open('VERSION.txt', 'r') as f: version = f.read().strip() setuptools.setup( name="odoo-addons-oca-purchase-workflow", description="Meta package for oca-purchase-workflow Odoo addons", version=version, install_requires=[ 'odoo-addon-procurement_purchase_no_grouping>=15.0dev,<15.1dev', 'odoo-addon-procurement_purchase_sale_no_grouping>=15.0dev,<15.1dev', 'odoo-addon-product_form_purchase_link>=15.0dev,<15.1dev', 'odoo-addon-product_supplier_code_purchase>=15.0dev,<15.1dev', 'odoo-addon-purchase_advance_payment>=15.0dev,<15.1dev', 'odoo-addon-purchase_allowed_product>=15.0dev,<15.1dev', 'odoo-addon-purchase_analytic_global>=15.0dev,<15.1dev', 'odoo-addon-purchase_blanket_order>=15.0dev,<15.1dev', 'odoo-addon-purchase_cancel_confirm>=15.0dev,<15.1dev', 'odoo-addon-purchase_default_terms_conditions>=15.0dev,<15.1dev', 'odoo-addon-purchase_delivery_split_date>=15.0dev,<15.1dev', 'odoo-addon-purchase_deposit>=15.0dev,<15.1dev', 'odoo-addon-purchase_discount>=15.0dev,<15.1dev', 'odoo-addon-purchase_exception>=15.0dev,<15.1dev', 'odoo-addon-purchase_fop_shipping>=15.0dev,<15.1dev', 'odoo-addon-purchase_force_invoiced>=15.0dev,<15.1dev', 'odoo-addon-purchase_fully_invoiced>=15.0dev,<15.1dev', 'odoo-addon-purchase_fully_received>=15.0dev,<15.1dev', 'odoo-addon-purchase_invoice_method>=15.0dev,<15.1dev', 'odoo-addon-purchase_invoice_plan>=15.0dev,<15.1dev', 'odoo-addon-purchase_last_price_info>=15.0dev,<15.1dev', 'odoo-addon-purchase_line_reassign>=15.0dev,<15.1dev', 'odoo-addon-purchase_location_by_line>=15.0dev,<15.1dev', 'odoo-addon-purchase_merge>=15.0dev,<15.1dev', 'odoo-addon-purchase_open_qty>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_analytic_search>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_approved>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_general_discount>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_line_deep_sort>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_line_menu>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_line_price_history>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_line_price_history_discount>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_line_qty_to_receive>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_line_stock_available>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_no_zero_price>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_product_recommendation>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_product_recommendation_brand>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_product_recommendation_classification>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_product_recommendation_forecast>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_product_recommendation_secondary_unit>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_product_recommendation_xlsx>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_qty_by_product_category>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_qty_change_no_recompute>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_secondary_unit>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_supplierinfo_update>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_type>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_type_dashboard>=15.0dev,<15.1dev', 'odoo-addon-purchase_order_uninvoiced_amount>=15.0dev,<15.1dev', 'odoo-addon-purchase_partner_incoterm>=15.0dev,<15.1dev', 'odoo-addon-purchase_partner_selectable_option>=15.0dev,<15.1dev', 'odoo-addon-purchase_quick>=15.0dev,<15.1dev', 'odoo-addon-purchase_receipt_expectation>=15.0dev,<15.1dev', 'odoo-addon-purchase_receipt_expectation_from_partner>=15.0dev,<15.1dev', 'odoo-addon-purchase_receipt_expectation_manual>=15.0dev,<15.1dev', 'odoo-addon-purchase_receipt_expectation_manual_split>=15.0dev,<15.1dev', 'odoo-addon-purchase_receipt_percentage>=15.0dev,<15.1dev', 'odoo-addon-purchase_reception_notify>=15.0dev,<15.1dev', 'odoo-addon-purchase_reception_status>=15.0dev,<15.1dev', 'odoo-addon-purchase_representative>=15.0dev,<15.1dev', 'odoo-addon-purchase_request>=15.0dev,<15.1dev', 'odoo-addon-purchase_request_department>=15.0dev,<15.1dev', 'odoo-addon-purchase_request_exception>=15.0dev,<15.1dev', 'odoo-addon-purchase_request_substate>=15.0dev,<15.1dev', 'odoo-addon-purchase_request_tier_validation>=15.0dev,<15.1dev', 'odoo-addon-purchase_request_to_requisition>=15.0dev,<15.1dev', 'odoo-addon-purchase_requisition_grouped_by_procurement>=15.0dev,<15.1dev', 'odoo-addon-purchase_requisition_order_remaining_qty>=15.0dev,<15.1dev', 'odoo-addon-purchase_requisition_tier_validation>=15.0dev,<15.1dev', 'odoo-addon-purchase_security>=15.0dev,<15.1dev', 'odoo-addon-purchase_stock_price_unit_sync>=15.0dev,<15.1dev', 'odoo-addon-purchase_stock_return_request>=15.0dev,<15.1dev', 'odoo-addon-purchase_stock_secondary_unit>=15.0dev,<15.1dev', 'odoo-addon-purchase_stock_tier_validation>=15.0dev,<15.1dev', 'odoo-addon-purchase_substate>=15.0dev,<15.1dev', 'odoo-addon-purchase_tag>=15.0dev,<15.1dev', 'odoo-addon-purchase_tier_validation>=15.0dev,<15.1dev', 'odoo-addon-purchase_total_ordered_qty>=15.0dev,<15.1dev', 'odoo-addon-purchase_triple_discount>=15.0dev,<15.1dev', 'odoo-addon-purchase_v12_control_menu>=15.0dev,<15.1dev', 'odoo-addon-purchase_work_acceptance>=15.0dev,<15.1dev', 'odoo-addon-purchase_work_acceptance_evaluation>=15.0dev,<15.1dev', 'odoo-addon-purchase_work_acceptance_invoice_plan>=15.0dev,<15.1dev', 'odoo-addon-purchase_work_acceptance_late_fines>=15.0dev,<15.1dev', 'odoo-addon-purchase_work_acceptance_tier_validation>=15.0dev,<15.1dev', 'odoo-addon-sale_purchase_force_vendor>=15.0dev,<15.1dev', ], classifiers=[ 'Programming Language :: Python', 'Framework :: Odoo', 'Framework :: Odoo :: 15.0', ] )
62.107843
6,335
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100