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
|
|---|---|---|---|---|---|---|
483
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 ForgeFlow S.L. (https://www.forgeflow.com)
# Part of ForgeFlow. See LICENSE file for full copyright and licensing details.
from odoo import models
class StockRule(models.Model):
_inherit = "stock.rule"
def _make_po_get_domain(self, company_id, values, partner):
domain = super()._make_po_get_domain(
company_id=company_id, values=values, partner=partner
)
domain += (("review_ids", "=", False),)
return domain
| 32.2
| 483
|
551
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Purchase Order Qty change no recompute",
"summary": "Prevent recompute if only quantity has changed in purchase order line",
"version": "15.0.1.0.1",
"category": "Purchases",
"website": "https://github.com/OCA/purchase-workflow",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"depends": ["purchase"],
"maintainers": ["victoralmau"],
}
| 39.214286
| 549
|
2,009
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests.common import Form, TransactionCase
class TestPurchaseOrderQtyChange(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.partner = cls.env["res.partner"].create({"name": "Test supplier"})
cls.product_1 = cls.env["product.product"].create(
{
"name": "Test Product 1",
"taxes_id": False,
"seller_ids": [
(0, False, {"name": cls.partner.id, "min_qty": 1, "price": 25.00}),
],
}
)
cls.product_2 = cls.env["product.product"].create(
{
"name": "Test Product 2",
"taxes_id": False,
"seller_ids": [
(0, False, {"name": cls.partner.id, "min_qty": 1, "price": 30.00}),
],
}
)
purchase_order_form = Form(
cls.env["purchase.order"].with_context(prevent_onchange_quantity=True)
)
purchase_order_form.partner_id = cls.partner
with purchase_order_form.order_line.new() as cls.line_form:
cls.line_form.product_id = cls.product_1
cls.line_form.product_qty = 1
def test_purchase_line_misc(self):
self.assertEqual(self.line_form.price_unit, 25)
self.assertEqual(self.line_form.price_subtotal, 25)
self.line_form.price_unit = 10
self.assertEqual(self.line_form.price_unit, 10)
self.assertEqual(self.line_form.price_subtotal, 10)
self.line_form.product_qty = 2
self.assertEqual(self.line_form.price_unit, 10)
self.assertEqual(self.line_form.price_subtotal, 20)
self.line_form.product_id = self.product_2
self.line_form.product_qty = 2
self.assertEqual(self.line_form.price_unit, 30)
self.assertEqual(self.line_form.price_subtotal, 60)
| 40.959184
| 2,007
|
1,204
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Víctor Martínez
# Copyright 2021 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import models
from odoo.tools import config
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
def _onchange_eval(self, field_name, onchange, result):
"""Remove the trigger for the undesired onchange method with this field.
We have to act at this place, as `_onchange_methods` is defined as a
property, and thus it can't be inherited due to the conflict of
inheritance between Python and Odoo ORM, so we can consider this as a HACK.
"""
ctx = self.env.context
if field_name == "product_qty" and (
not config["test_enable"]
or (config["test_enable"] and ctx.get("prevent_onchange_quantity", False))
):
cls = type(self)
for method in self._onchange_methods.get(field_name, ()):
if method == cls._onchange_quantity:
self._onchange_methods[field_name].remove(method)
break
return super()._onchange_eval(field_name, onchange, result)
| 42.928571
| 1,202
|
2,633
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 ForgeFlow S.L.
# (http://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
import logging
logger = logging.getLogger(__name__)
def pre_init_hook(cr):
"""
The objective of this hook is to speed up the installation
of the module on an existing Odoo instance.
"""
store_field_qty_to_receive_and_invoice(cr)
def store_field_qty_to_receive_and_invoice(cr):
cr.execute(
"""SELECT column_name
FROM information_schema.columns
WHERE table_name='purchase_order_line' AND
column_name='qty_to_receive'"""
)
if not cr.fetchone():
logger.info("Creating field qty_to_receive on purchase_order_line")
cr.execute(
"""
ALTER TABLE purchase_order_line ADD COLUMN qty_to_receive float;
COMMENT ON COLUMN purchase_order_line.qty_to_receive IS
'Qty to Receive';
"""
)
cr.execute(
"""SELECT column_name
FROM information_schema.columns
WHERE table_name='purchase_order_line' AND
column_name='qty_to_invoice'"""
)
if not cr.fetchone():
logger.info("Creating field qty_to_invoice on purchase_order_line")
cr.execute(
"""
ALTER TABLE purchase_order_line ADD COLUMN qty_to_invoice float;
COMMENT ON COLUMN purchase_order_line.qty_to_invoice IS
'Qty to Bill';
"""
)
logger.info(
"Computing values for fields qty_to_receive and qty_to_invoice"
" on purchase_order_line"
)
cr.execute(
"""
UPDATE purchase_order_line pol
SET qty_to_invoice = pol.qty_received - pol.qty_invoiced
FROM product_product p
JOIN product_template t ON p.product_tmpl_id = t.id
WHERE t.purchase_method = 'receive' AND pol.product_id = p.id
"""
)
cr.execute(
"""
UPDATE purchase_order_line pol
SET qty_to_invoice = pol.product_qty - pol.qty_invoiced
FROM product_product p
JOIN product_template t ON p.product_tmpl_id = t.id
WHERE t.purchase_method != 'receive' AND pol.product_id = p.id
"""
)
cr.execute(
"""
UPDATE purchase_order_line
SET qty_to_receive = pol.qty
FROM (SELECT purchase_line_id, sum(product_uom_qty) as qty
FROM stock_move
WHERE purchase_line_id IS NOT NULL AND
state not in ('cancel', 'done')
GROUP BY purchase_line_id) as pol
WHERE purchase_order_line.id = pol.purchase_line_id
"""
)
| 30.976471
| 2,633
|
658
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 ForgeFlow S.L.
# (http://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Purchase Open Qty",
"summary": "Allows to identify the purchase orders that have quantities "
"pending to invoice or to receive.",
"version": "15.0.2.0.1",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/purchase-workflow",
"category": "Purchases",
"depends": ["purchase_stock"],
"data": ["views/purchase_view.xml"],
"pre_init_hook": "pre_init_hook",
"license": "AGPL-3",
"installable": True,
"application": False,
}
| 34.631579
| 658
|
7,486
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 ForgeFlow S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.fields import Datetime
from odoo.tests.common import TransactionCase
class TestPurchaseOpenQty(TransactionCase):
def setUp(self):
super(TestPurchaseOpenQty, self).setUp()
self.purchase_order_model = self.env["purchase.order"]
purchase_order_line_model = self.env["purchase.order.line"]
partner_model = self.env["res.partner"]
prod_model = self.env["product.product"]
analytic_account_model = self.env["account.analytic.account"]
# partners
pa_dict = {"name": "Partner 1"}
self.partner = partner_model.sudo().create(pa_dict)
pa_dict2 = {"name": "Partner 2"}
self.partner2 = partner_model.sudo().create(pa_dict2)
# account
ac_dict = {"name": "analytic account 1"}
self.analytic_account_1 = analytic_account_model.sudo().create(ac_dict)
# Purchase Order Num 1
po_dict = {"partner_id": self.partner.id}
self.purchase_order_1 = self.purchase_order_model.create(po_dict)
uom_id = prod_model.uom_id.search([("name", "=", "Units")], limit=1).id
pr_dict = {
"name": "Product Test",
"uom_id": uom_id,
"purchase_method": "purchase",
}
self.product = prod_model.sudo().create(pr_dict)
pl_dict1 = {
"date_planned": Datetime.now(),
"name": "PO01",
"order_id": self.purchase_order_1.id,
"product_id": self.product.id,
"product_uom": uom_id,
"price_unit": 1.0,
"product_qty": 5.0,
"account_analytic_id": self.analytic_account_1.id,
}
self.purchase_order_line_1 = purchase_order_line_model.sudo().create(pl_dict1)
self.purchase_order_1.button_confirm()
# Purchase Order Num 2
po_dict2 = {"partner_id": self.partner2.id}
self.purchase_order_2 = self.purchase_order_model.create(po_dict2)
pr_dict2 = {
"name": "Product Test 2",
"uom_id": uom_id,
"purchase_method": "receive",
}
self.product2 = prod_model.sudo().create(pr_dict2)
pl_dict2 = {
"date_planned": Datetime.now(),
"name": "PO02",
"order_id": self.purchase_order_2.id,
"product_id": self.product2.id,
"product_uom": uom_id,
"price_unit": 1.0,
"product_qty": 5.0,
"account_analytic_id": self.analytic_account_1.id,
}
self.purchase_order_line_2 = purchase_order_line_model.sudo().create(pl_dict2)
self.purchase_order_2.button_confirm()
# Purchase Order Num 3 (service)
po_dict3 = {"partner_id": self.partner2.id}
self.purchase_order_3 = self.purchase_order_model.create(po_dict3)
pr_dict3 = {
"name": "Product Test 3",
"uom_id": uom_id,
"purchase_method": "receive",
"type": "service",
}
self.product3 = prod_model.sudo().create(pr_dict3)
pl_dict3 = {
"date_planned": Datetime.now(),
"name": "PO03",
"order_id": self.purchase_order_3.id,
"product_id": self.product3.id,
"product_uom": uom_id,
"price_unit": 10.0,
"product_qty": 5.0,
}
self.purchase_order_line_3 = purchase_order_line_model.sudo().create(pl_dict3)
self.purchase_order_3.button_confirm()
def test_compute_qty_to_invoice_and_receive(self):
self.assertEqual(
self.purchase_order_line_1.qty_to_invoice,
5.0,
"Expected 5 as qty_to_invoice in the PO line",
)
self.assertEqual(
self.purchase_order_line_1.qty_to_receive,
5.0,
"Expected 5 as qty_to_receive in the PO line",
)
self.assertEqual(
self.purchase_order_1.qty_to_invoice,
5.0,
"Expected 5 as qty_to_invoice in the PO",
)
self.assertEqual(
self.purchase_order_1.qty_to_receive,
5.0,
"Expected 5 as qty_to_receive in the PO",
)
self.assertEqual(
self.purchase_order_line_2.qty_to_invoice,
0.0,
"Expected 0 as qty_to_invoice in the PO line",
)
self.assertEqual(
self.purchase_order_line_2.qty_to_receive,
5.0,
"Expected 5 as qty_to_receive in the PO line",
)
self.assertEqual(
self.purchase_order_2.qty_to_invoice,
0.0,
"Expected 0 as qty_to_invoice in the PO",
)
self.assertEqual(
self.purchase_order_2.qty_to_receive,
5.0,
"Expected 5 as qty_to_receive in the PO",
)
# Now we receive the products
for picking in self.purchase_order_2.picking_ids:
picking.action_confirm()
picking.move_lines.write({"quantity_done": 5.0})
picking.button_validate()
# The value is computed when you run it as at user but not in the test
self.purchase_order_2._compute_qty_to_invoice()
self.purchase_order_2._compute_qty_to_receive()
self.assertEqual(
self.purchase_order_line_2.qty_to_invoice,
5.0,
"Expected 5 as qty_to_invoice in the PO line",
)
self.assertEqual(
self.purchase_order_line_2.qty_to_receive,
0.0,
"Expected 0 as qty_to_receive in the PO line",
)
self.assertEqual(
self.purchase_order_2.qty_to_invoice,
5.0,
"Expected 5 as qty_to_invoice in the PO",
)
self.assertEqual(
self.purchase_order_2.qty_to_receive,
0.0,
"Expected 0 as qty_to_receive in the PO",
)
def test_search_qty_to_invoice_and_receive(self):
found = self.purchase_order_model.search(
[
"|",
("pending_qty_to_invoice", "=", True),
("pending_qty_to_receive", "=", True),
]
)
self.assertTrue(
self.purchase_order_1.id in found.ids,
"Expected PO {} in POs {}".format(self.purchase_order_1.id, found.ids),
)
found = self.purchase_order_model.search(
[
"|",
("pending_qty_to_invoice", "=", False),
("pending_qty_to_receive", "=", False),
]
)
self.assertFalse(
self.purchase_order_2.id not in found.ids,
"Expected PO %s not to be in POs %s"
% (self.purchase_order_2.id, found.ids),
)
def test_03_po_line_with_services(self):
self.assertEqual(
self.purchase_order_line_3.qty_to_receive,
5.0,
)
self.assertEqual(
self.purchase_order_line_3.qty_received,
0.0,
)
self.purchase_order_line_3.qty_received = 3.0
self.assertEqual(
self.purchase_order_line_3.qty_to_receive,
2.0,
)
self.assertEqual(
self.purchase_order_line_3.qty_received,
3.0,
)
self.assertEqual(
self.purchase_order_line_3.qty_to_invoice,
3.0,
)
| 34.981308
| 7,486
|
3,730
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 ForgeFlow S.L.
# (http://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import _, api, fields, models
from odoo.tools import float_is_zero
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
@api.depends(
"move_ids.state",
"move_ids.product_uom",
"move_ids.product_uom_qty",
"product_qty",
"qty_received",
)
def _compute_qty_to_receive(self):
service_lines = self.filtered(lambda l: l.product_id.type == "service")
for line in self - service_lines:
total = 0.0
for move in line.move_ids.filtered(
lambda m: m.state not in ("cancel", "done")
):
if move.product_uom != line.product_uom:
total += move.product_uom._compute_quantity(
move.product_uom_qty, line.product_uom
)
else:
total += move.product_uom_qty
line.qty_to_receive = total
for line in service_lines:
line.qty_to_receive = line.product_qty - line.qty_received
qty_to_receive = fields.Float(
compute="_compute_qty_to_receive",
digits="Product Unit of Measure",
copy=False,
string="Qty to Receive",
store=True,
)
class PurchaseOrder(models.Model):
_inherit = "purchase.order"
def _compute_qty_to_invoice(self):
dp = self.env["decimal.precision"].precision_get("Product Unit of Measure")
for po in self:
qty_to_invoice = sum(po.mapped("order_line.qty_to_invoice"))
po.pending_qty_to_invoice = not float_is_zero(
qty_to_invoice, precision_digits=dp
)
po.qty_to_invoice = qty_to_invoice
def _compute_qty_to_receive(self):
for po in self:
qty_to_receive = sum(po.mapped("order_line.qty_to_receive"))
po.pending_qty_to_receive = qty_to_receive > 0.0
po.qty_to_receive = qty_to_receive
@api.model
def _search_pending_qty_to_receive(self, operator, value):
if operator != "=" or not isinstance(value, bool):
raise ValueError(_("Unsupported search operator"))
po_line_obj = self.env["purchase.order.line"]
po_lines = po_line_obj.search([("qty_to_receive", ">", 0.0)])
orders = po_lines.mapped("order_id")
if value:
return [("id", "in", orders.ids)]
else:
return [("id", "not in", orders.ids)]
@api.model
def _search_pending_qty_to_invoice(self, operator, value):
if operator != "=" or not isinstance(value, bool):
raise ValueError(_("Unsupported search operator"))
po_line_obj = self.env["purchase.order.line"]
po_lines = po_line_obj.search([("qty_to_invoice", ">", 0.0)])
orders = po_lines.mapped("order_id")
if value:
return [("id", "in", orders.ids)]
else:
return [("id", "not in", orders.ids)]
qty_to_invoice = fields.Float(
compute="_compute_qty_to_invoice",
string="Qty to Bill",
default=0.0,
)
pending_qty_to_invoice = fields.Boolean(
compute="_compute_qty_to_invoice",
search="_search_pending_qty_to_invoice",
string="Pending Qty to Bill",
)
qty_to_receive = fields.Float(
compute="_compute_qty_to_receive",
string="Qty to Receive",
default=0.0,
)
pending_qty_to_receive = fields.Boolean(
compute="_compute_qty_to_receive",
search="_search_pending_qty_to_receive",
string="Pending Qty to Receive",
)
| 35.188679
| 3,730
|
623
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 AvanzOsc (http://www.avanzosc.es)
# Copyright 2015-2017 Tecnativa - Pedro M. Baeza
# Copyright 2018 Tecnativa - Carlos Dauden
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
{
"name": "Procurement Purchase No Grouping",
"version": "15.0.1.0.1",
"author": "AvanzOSC, Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/purchase-workflow",
"category": "Procurements",
"depends": ["purchase_stock"],
"data": ["views/product_category_view.xml", "views/res_config_settings_views.xml"],
"installable": True,
"license": "AGPL-3",
}
| 38.9375
| 623
|
7,750
|
py
|
PYTHON
|
15.0
|
# Copyright 2015-2017 Tecnativa - Pedro M. Baeza
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo import fields
from odoo.tests import common
class TestProcurementPurchaseNoGrouping(common.TransactionCase):
@classmethod
def setUpClass(cls):
super(TestProcurementPurchaseNoGrouping, cls).setUpClass()
cls.category = cls.env["product.category"].create({"name": "Test category"})
cls.partner = cls.env["res.partner"].create({"name": "Test partner"})
cls.product_1 = cls._create_product(
cls, "Test product 1", cls.category, cls.partner
)
cls.product_2 = cls._create_product(
cls, "Test product 2", cls.category, cls.partner
)
cls.location = cls.env.ref("stock.stock_location_stock")
cls.picking_type = cls.env.ref("stock.picking_type_in")
cls.origin = "Manual Replenishment"
cls.prev_orders = cls.env["purchase.order"].search(
[("origin", "=", cls.origin)]
)
cls.stock_location_route = cls.env.ref("purchase_stock.route_warehouse0_buy")
cls.stock_rule = cls.stock_location_route.rule_ids[0]
cls.values = {
# FIXME: Core doesn't find correctly supplier if not recordset
"company_id": cls.env.user.company_id,
"date_planned": fields.Datetime.now(),
}
def _create_product(self, name, category, partner):
product = self.env["product.product"].create(
{
"name": name,
"categ_id": category.id,
"seller_ids": [(0, 0, {"name": partner.id, "min_qty": 1.0})],
}
)
return product
def _run_procurement(self, product):
procurement_group_obj = self.env["procurement.group"]
procurement = procurement_group_obj.Procurement(
product,
1,
product.uom_id,
self.location,
False,
self.origin,
self.env.company,
self.values,
)
rule = procurement_group_obj._get_rule(
procurement.product_id, procurement.location_id, procurement.values
)
self.stock_rule._run_buy([(procurement, rule)])
def _set_system_grouping(self, grouping):
self.env.company.procured_purchase_grouping = grouping
def _search_purchases(self):
return self.env["purchase.order"].search(
[("origin", "=", self.origin), ("id", "not in", self.prev_orders.ids)]
)
def test_procurement_grouped_purchase(self):
self.category.procured_purchase_grouping = "standard"
self._run_procurement(self.product_1)
self._run_procurement(self.product_1)
self._run_procurement(self.product_2)
orders = self._search_purchases()
self.assertEqual(
len(orders),
1,
"Procured purchase orders are not the same",
)
self.assertEqual(
len(orders.order_line),
2,
"Procured purchase orders lines are not the same",
)
def test_procurement_system_grouped_purchase(self):
self.category.procured_purchase_grouping = None
self._set_system_grouping("standard")
self._run_procurement(self.product_1)
self._run_procurement(self.product_1)
self._run_procurement(self.product_2)
orders = self._search_purchases()
self.assertEqual(len(orders), 1, "Procured purchase orders are not the same")
self.assertEqual(
len(orders.order_line),
2,
"Procured purchase orders lines are the same",
)
def test_procurement_no_grouping_line_purchase(self):
self.category.procured_purchase_grouping = "line"
self._run_procurement(self.product_1)
self._run_procurement(self.product_1)
self._run_procurement(self.product_2)
orders = self._search_purchases()
self.assertEqual(len(orders), 1, "Procured purchase orders are not the same")
self.assertEqual(
len(orders.order_line), 3, "Procured purchase orders lines are the same"
)
def test_procurement_system_no_grouping_line_purchase(self):
self.category.procured_purchase_grouping = None
self._set_system_grouping("line")
self._run_procurement(self.product_1)
self._run_procurement(self.product_1)
self._run_procurement(self.product_2)
orders = self._search_purchases()
self.assertEqual(len(orders), 1, "Procured purchase orders are not the same")
self.assertEqual(
len(orders.order_line), 3, "Procured purchase orders lines are the same"
)
def test_procurement_no_grouping_order_purchase(self):
self.category.procured_purchase_grouping = "order"
self._run_procurement(self.product_1)
self._run_procurement(self.product_1)
self._run_procurement(self.product_2)
orders = self._search_purchases()
self.assertEqual(
len(orders),
3,
"Procured purchase orders are the same",
)
self.assertEqual(
len(orders.mapped("order_line")),
3,
"Procured purchase orders lines are the same",
)
def test_procurement_system_no_grouping_order_purchase(self):
self.category.procured_purchase_grouping = None
self._set_system_grouping("order")
self._run_procurement(self.product_1)
self._run_procurement(self.product_1)
self._run_procurement(self.product_2)
orders = self._search_purchases()
self.assertEqual(len(orders), 3, "Procured purchase orders are the same")
self.assertEqual(
len(orders.mapped("order_line")),
3,
"Procured purchase orders lines are the same",
)
def test_procurement_products_same_category(self):
self.category.procured_purchase_grouping = "product_category"
self._run_procurement(self.product_1)
self._run_procurement(self.product_2)
self._run_procurement(self.product_1)
orders = self._search_purchases()
self.assertEqual(len(orders), 1)
self.assertEqual(len(orders.mapped("order_line")), 2)
def test_procurement_system_products_same_category(self):
self.category.procured_purchase_grouping = None
self._set_system_grouping("product_category")
self._run_procurement(self.product_1)
self._run_procurement(self.product_2)
self._run_procurement(self.product_1)
orders = self._search_purchases()
self.assertEqual(len(orders), 1)
self.assertEqual(len(orders.mapped("order_line")), 2)
def test_procurement_products_distinct_category(self):
self.category.procured_purchase_grouping = "product_category"
category2 = self.category.copy()
self._run_procurement(self.product_1)
self.product_2.categ_id = category2.id
self._run_procurement(self.product_2)
self._run_procurement(self.product_1)
orders = self._search_purchases()
self.assertEqual(len(orders), 2)
def test_procurement_system_products_distinct_category(self):
self.category.procured_purchase_grouping = None
self._set_system_grouping("product_category")
category2 = self.category.copy()
self._run_procurement(self.product_1)
self.product_2.categ_id = category2.id
self._run_procurement(self.product_2)
self._run_procurement(self.product_1)
orders = self._search_purchases()
self.assertEqual(len(orders), 2)
| 40.145078
| 7,748
|
1,334
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 AvanzOsc (http://www.avanzosc.es)
# Copyright 2015-2016 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo import fields, models
class ProductCategory(models.Model):
_inherit = "product.category"
procured_purchase_grouping = fields.Selection(
[
("standard", "Standard grouping"),
("line", "No line grouping"),
("order", "No order grouping"),
("product_category", "Product category grouping"),
],
default="standard",
help="Select the behaviour for grouping procured purchases for the "
"the products of this category:\n"
"* Standard grouping (default): Procurements will generate "
"purchase orders as always, grouping lines and orders when "
"possible.\n"
"* No line grouping: If there are any open purchase order for "
"the same supplier, it will be reused, but lines won't be "
"merged.\n"
"* No order grouping: This option will prevent any kind of "
"grouping.\n"
"* <empty>: If no value is selected, system-wide default will be used.\n"
"* Product category grouping: This option groups products in the "
"same purchase order that belongs to the same product category.",
)
| 41.6875
| 1,334
|
1,461
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 AvanzOsc (http://www.avanzosc.es)
# Copyright 2018 Tecnativa - Carlos Dauden
# Copyright 2015-2021 Tecnativa - Pedro M. Baeza
# 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 _find_candidate(
self,
product_id,
product_qty,
product_uom,
location_id,
name,
origin,
company_id,
values,
):
"""If not grouping by line, we should make an exception when you update an
existing sales order line, so we filter a bit more by procurement group.
NOTE: This makes that if you manually assign the same procurement group to
several different sales orders, the grouping will be done no matter the grouping
criteria, but this is the only way to do it without having to put a lot of glue
modules, and on standard operation mode, procurement groups are not reused
between sales orders.
"""
obj = self
if values.get("grouping") == "line":
obj = self.filtered(lambda x: x.order_id.group_id == values.get("group_id"))
return super(PurchaseOrderLine, obj)._find_candidate(
product_id,
product_qty,
product_uom,
location_id,
name,
origin,
company_id,
values,
)
| 33.204545
| 1,461
|
1,272
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 - Radovan Skolnik <radovan@skolnik.info>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo import fields, models
class ResCompany(models.Model):
_inherit = "res.company"
procured_purchase_grouping = fields.Selection(
[
("standard", "Standard grouping"),
("line", "No line grouping"),
("order", "No order grouping"),
("product_category", "Product category grouping"),
],
default="standard",
help="Select the behaviour for grouping procured purchases for the "
"the products of this category:\n"
"* Standard grouping: Procurements will generate "
"purchase orders as always, grouping lines and orders when "
"possible.\n"
"* No line grouping: If there are any open purchase order for "
"the same supplier, it will be reused, but lines won't be "
"merged.\n"
"* No order grouping: This option will prevent any kind of "
"grouping.\n"
"* <empty>: If no value is selected, system-wide default will be used.\n"
"* Product category grouping: This option groups products in the "
"same purchase order that belongs to the same product category.",
)
| 41.032258
| 1,272
|
1,861
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 AvanzOsc (http://www.avanzosc.es)
# Copyright 2015-2016 Tecnativa - Pedro M. Baeza
# Copyright 2018 Tecnativa - Carlos Dauden
# Copyright 2020 Radovan Skolnik
# Copyright 2020 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
import random
from odoo import models
class StockRule(models.Model):
_inherit = "stock.rule"
def _run_buy(self, procurements):
for procurement, _rule in procurements:
grouping = procurement.product_id.categ_id.procured_purchase_grouping
if not grouping:
grouping = self.env.company.procured_purchase_grouping
procurement.values["grouping"] = grouping
return super()._run_buy(procurements)
def _make_po_get_domain(self, company_id, values, partner):
"""Inject an impossible domain for not getting match in case of no order
grouping.
We try to make it the more unique possible for avoiding coincidences for not
overlapping in a batch procurement run (like a sales order with multiple MTO
lines confirmation).
"""
domain = super()._make_po_get_domain(company_id, values, partner)
if values.get("grouping") == "product_category":
if values.get("supplier"):
suppinfo = values["supplier"]
product = suppinfo.product_id or suppinfo.product_tmpl_id
domain += (
("order_line.product_id.categ_id", "=", product.categ_id.id),
)
elif values.get("grouping") == "order":
if values.get("move_dest_ids"):
domain += (("id", "=", -values["move_dest_ids"][:1].id),)
# The minimum is imposed by PG int4 limit
domain += (("id", "=", random.randint(-2147483648, 0)),)
return domain
| 41.311111
| 1,859
|
517
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 - Radovan Skolnik <radovan@skolnik.info>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
"""Configuration of default value for procurement purchase grouping."""
_inherit = "res.config.settings"
_description = "Procurement purchase grouping settings"
procured_purchase_grouping = fields.Selection(
related="company_id.procured_purchase_grouping",
readonly=False,
)
| 32.3125
| 517
|
582
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Purchase order line price history",
"version": "15.0.1.0.0",
"category": "Purchase Management",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/purchase-workflow",
"license": "AGPL-3",
"depends": ["purchase"],
"data": [
"security/ir.model.access.csv",
"wizards/purchase_order_line_price_history.xml",
"views/purchase_views.xml",
],
"installable": True,
}
| 34.235294
| 582
|
6,462
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Ernesto Tejeda
# Copyright 2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests import Form, TransactionCase
class TestPurchaseOrderLinePriceHistoryBase(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.partner_1 = cls.env["res.partner"].create({"name": "Partner 1"})
cls.partner_2 = cls.env["res.partner"].create({"name": "Partner 2"})
cls.product = cls.env["product.product"].create({"name": "Product 1"})
cls.purchase_order_model = cls.env["purchase.order"]
# Two confirmed purchase orders with the same data and
# different partners
cls.purchase_order_1 = cls._create_purchase_order(
cls, cls.partner_1, [cls.product, 2, 10]
)
cls.purchase_order_1.button_confirm()
cls.purchase_order_2 = cls._create_purchase_order(
cls, cls.partner_2, [cls.product, 2, 20]
)
# A non-confirmed purchase orders with the same partner
# of cls.purchase_order_2
cls.purchase_order_3 = cls._create_purchase_order(
cls, cls.partner_2, [cls.product, 2, 30]
)
def _create_purchase_order(self, partner, product_info):
purchase_form = Form(self.purchase_order_model)
purchase_form.partner_id = partner
with purchase_form.order_line.new() as line_form:
line_form.product_id = product_info[0]
line_form.product_qty = product_info[1]
line_form.price_unit = product_info[2]
return purchase_form.save()
def launch_wizard(self, active_id):
wizard_obj = self.env["purchase.order.line.price.history"]
wizard = wizard_obj.with_context(active_id=active_id).create({})
wizard._onchange_partner_id()
return wizard
class TestPurchaseOrderLinePriceHistory(TestPurchaseOrderLinePriceHistoryBase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.purchase_order_2.button_confirm()
def test_onchange_partner_id(self):
# Create a wizard from self.purchase_order_3 order line.
# Only one history line should be shown and should be
# associated with self.purchase_order_2 order line
wizard = self.launch_wizard(self.purchase_order_3.order_line.id)
self.assertEqual(len(wizard.line_ids), 1)
self.assertEqual(
wizard.line_ids.purchase_order_line_id,
self.purchase_order_2.order_line,
)
self.assertEqual(wizard.line_ids.price_unit, 20)
# Set partner to False. Two history lines should be shown and
# they should be associated with self.purchase_order_1 order line
# and self.purchase_order_2 order line
wizard.partner_id = False
wizard._onchange_partner_id()
self.assertEqual(len(wizard.line_ids), 2)
self.assertEqual(
set(wizard.line_ids.mapped("purchase_order_line_id.price_unit")),
set(list([10.0, 20.0])),
)
def test_onchange_partner_id_include_rfq(self):
# Another purchase orders with the same partner of cls.purchase_order_2
# and cls.purchase_order_3
self.purchase_order_4 = self._create_purchase_order(
self.partner_2, [self.product, 2, 40]
)
# Create a wizard from self.purchase_order_4 order line.
# Only one history line should be shown and should be
# associated with self.purchase_order_2 order line
wizard = self.launch_wizard(self.purchase_order_4.order_line.id)
self.assertEqual(len(wizard.line_ids), 1)
self.assertEqual(
wizard.line_ids.purchase_order_line_id,
self.purchase_order_2.order_line,
)
# If include_rfq is checked two history lines should be shown
# and they should be associated with self.purchase_order_2 order line
# and self.purchase_order_3 order line
wizard.include_rfq = True
wizard._onchange_partner_id()
self.assertEqual(len(wizard.line_ids), 2)
self.assertEqual(
wizard.line_ids.mapped("purchase_order_line_id"),
(self.purchase_order_2.order_line | self.purchase_order_3.order_line),
)
def test_onchange_partner_id_include_commercial_partner(self):
# Another purchase orders with a partner child of cls.purchase_order_2
partner_2_child = self.env["res.partner"].create(
{"name": "Child of Partner 2", "parent_id": self.partner_2.id},
)
self.purchase_order_4 = self._create_purchase_order(
partner_2_child, [self.product, 2, 40]
)
# Create a wizard from self.purchase_order_4 order line. As
# include_commercial_partner is checked by default, one history line
# should be shown and associated with self.purchase_order_2 order line
wizard = self.launch_wizard(self.purchase_order_4.order_line.id)
self.assertEqual(len(wizard.line_ids), 1)
self.assertEqual(
wizard.line_ids.purchase_order_line_id,
self.purchase_order_2.order_line,
)
# Uncheck include_commercial_partner and purchase history
# will be empty.
wizard.include_commercial_partner = False
wizard._onchange_partner_id()
self.assertFalse(wizard.line_ids)
def test_action_set_price(self):
# Create a wizard from self.purchase_order_3.order_line.
wizard = self.launch_wizard(self.purchase_order_3.order_line.id)
self.assertEqual(self.purchase_order_3.order_line.price_unit, 30)
# Set the price of the history line to the purchase order line.
wizard.line_ids.action_set_price()
self.assertEqual(self.purchase_order_3.order_line.price_unit, 20)
# Create a wizard from self.purchase_order_3 order line again.
wizard = self.launch_wizard(self.purchase_order_3.order_line.id)
wizard.partner_id = False
wizard._onchange_partner_id()
# Find the history line with price_unit == 10 and set this price
# to the purchase order line
history_line = wizard.line_ids.filtered(lambda r: r.price_unit == 10)
self.assertEqual(self.purchase_order_3.order_line.price_unit, 20)
history_line.action_set_price()
self.assertEqual(self.purchase_order_3.order_line.price_unit, 10)
| 46.142857
| 6,460
|
3,811
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class PurchaseOrderLinePriceHistory(models.TransientModel):
_name = "purchase.order.line.price.history"
_description = "Purchase order line price history"
@api.model
def _default_partner_id(self):
return (
self.env["purchase.order.line"]
.browse(self.env.context.get("active_id"))
.partner_id.id
)
purchase_order_line_id = fields.Many2one(
comodel_name="purchase.order.line",
string="Purchase order line",
default=lambda self: self.env.context.get("active_id"),
)
product_id = fields.Many2one(related="purchase_order_line_id.product_id")
partner_id = fields.Many2one(
comodel_name="res.partner",
string="Supplier",
default=_default_partner_id,
)
line_ids = fields.One2many(
comodel_name="purchase.order.line.price.history.line",
inverse_name="history_id",
string="History lines",
readonly=True,
)
include_rfq = fields.Boolean(
string="Include RFQ",
help="Include 'Requests for Quotation' lines in the purchase history",
)
include_commercial_partner = fields.Boolean(
string="Include commercial entity",
default=True,
help="Include commercial entity and its contacts in the purchase history",
)
@api.onchange("partner_id", "include_rfq", "include_commercial_partner")
def _onchange_partner_id(self):
self.line_ids = False
states = ["purchase", "done"]
if self.include_rfq:
states += ["draft", "sent", "to approve"]
domain = [
("product_id", "=", self.product_id.id),
("order_id.state", "in", states),
]
if self.partner_id:
if self.include_commercial_partner:
commercial_ids = self.partner_id.commercial_partner_id.ids
domain += [("partner_id", "child_of", commercial_ids)]
else:
domain += [("partner_id", "child_of", self.partner_id.ids)]
order_lines = self.env["purchase.order.line"].search(domain, limit=20)
order_lines -= self.purchase_order_line_id
vals = [
(0, False, {"purchase_order_line_id": order_line.id})
for order_line in order_lines
]
self.line_ids = vals
class PurchaseOrderLinePriceHistoryLine(models.TransientModel):
_name = "purchase.order.line.price.history.line"
_description = "Purchase order line price history line"
history_id = fields.Many2one(
comodel_name="purchase.order.line.price.history",
string="History",
)
purchase_order_line_id = fields.Many2one(
comodel_name="purchase.order.line",
string="Purchase order line",
)
order_id = fields.Many2one(related="purchase_order_line_id.order_id")
partner_id = fields.Many2one(related="purchase_order_line_id.partner_id")
purchase_order_date_order = fields.Datetime(
related="purchase_order_line_id.order_id.date_order",
)
product_qty = fields.Float(related="purchase_order_line_id.product_qty")
product_uom = fields.Many2one(related="purchase_order_line_id.product_uom")
price_unit = fields.Float(related="purchase_order_line_id.price_unit")
def _prepare_purchase_order_line_vals(self):
self.ensure_one()
return {"price_unit": self.price_unit}
def action_set_price(self):
self.ensure_one()
active_id = self.env.context.get("active_id")
order_line = self.env["purchase.order.line"].browse(active_id)
vals = self._prepare_purchase_order_line_vals()
order_line.write(vals)
| 38.11
| 3,811
|
672
|
py
|
PYTHON
|
15.0
|
# Copyright 2020-2022 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Default purchase incoterm per partner",
"summary": "Add a an incoterm field for supplier and use it on purchase order",
"version": "15.0.3.0.0",
"category": "Purchase",
"author": "Camptocamp, Odoo Community Association (OCA)",
"license": "AGPL-3",
"maintainers": ["TDu", "bealdav"],
"depends": [
"account",
"purchase_stock",
],
"website": "https://github.com/OCA/purchase-workflow",
"data": [
"views/partner_view.xml",
"views/purchase_view.xml",
],
"installable": True,
}
| 32
| 672
|
744
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 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"
incoterm_address_id = fields.Many2one(
comodel_name="res.partner",
string="Incoterm Address",
help="Address where goods responsibility is transferred to the buyer",
)
@api.onchange("partner_id")
def onchange_partner_id(self):
res = super().onchange_partner_id()
self.incoterm_id = self.partner_id.commercial_partner_id.purchase_incoterm_id
self.incoterm_address_id = (
self.partner_id.commercial_partner_id.purchase_incoterm_address_id
)
return res
| 33.818182
| 744
|
724
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
purchase_incoterm_id = fields.Many2one(
comodel_name="account.incoterms",
ondelete="restrict",
string="Default Purchase Incoterm",
)
purchase_incoterm_address_id = fields.Many2one(
comodel_name="res.partner",
ondelete="restrict",
string="Default Purchase Incoterm Address",
)
@api.model
def _commercial_fields(self):
return super()._commercial_fields() + [
"purchase_incoterm_address_id",
"purchase_incoterm_id",
]
| 28.96
| 724
|
619
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Akretion France (http://www.akretion.com/)
# @author: Alexis de Lattre <alexis.delattre@akretion.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Purchase Reception Status",
"version": "15.0.1.0.0",
"category": "Purchases",
"license": "AGPL-3",
"summary": "Add reception status on purchase orders",
"author": "Akretion,Odoo Community Association (OCA)",
"maintainers": ["alexis-via"],
"website": "https://github.com/OCA/purchase-workflow",
"depends": ["purchase"],
"data": ["views/purchase_order.xml"],
"installable": True,
}
| 36.411765
| 619
|
2,035
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Akretion France (http://www.akretion.com/)
# @author: Alexis de Lattre <alexis.delattre@akretion.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
from odoo.tools import float_compare
class PurchaseOrder(models.Model):
_inherit = "purchase.order"
reception_status = fields.Selection(
[
("no", "Nothing Received"),
("partial", "Partially Received"),
("received", "Fully Received"),
],
compute="_compute_reception_status",
store=True,
)
force_received = fields.Boolean(
readonly=True,
states={"done": [("readonly", False)]},
copy=False,
help="If true, the reception status will be forced to Fully Received, "
"even if some lines are not fully received. "
"To be able to modify this field, you must first lock the order.",
)
@api.depends(
"state", "force_received", "order_line.qty_received", "order_line.product_qty"
)
def _compute_reception_status(self):
prec = self.env["decimal.precision"].precision_get("Product Unit of Measure")
for order in self:
status = "no"
if order.state in ("purchase", "done"):
if order.force_received:
status = "received"
elif all(
[
float_compare(
line.qty_received, line.product_qty, precision_digits=prec
)
>= 0
for line in order.order_line
]
):
status = "received"
elif any(
[
float_compare(line.qty_received, 0, precision_digits=prec) > 0
for line in order.order_line
]
):
status = "partial"
order.reception_status = status
| 35.701754
| 2,035
|
584
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Manuel Calero
# Copyright 2020 Tecnativa - João Marques
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
{
"name": "Purchase Order Univoiced Amount",
"author": "Tecnativa, Odoo Community Association (OCA)",
"version": "15.0.1.0.0",
"development_status": "Production/Stable",
"website": "https://github.com/OCA/purchase-workflow",
"category": "Purchase",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["purchase"],
"data": ["views/purchase_order_view.xml"],
}
| 34.294118
| 583
|
5,738
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Manuel Calero
# Copyright 2020 Tecnativa - Pedro M. Baeza
# Copyright 2021 Tecnativa - Víctor Martínez
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import fields
from odoo.tests.common import Form, TransactionCase
class TestPurchaseOrderUninvoiceAmount(TransactionCase):
def setUp(self):
super().setUp()
# Environmet
self.purchase_order_model = self.env["purchase.order"]
self.purchase_order_line_model = self.env["purchase.order.line"]
self.account_move_model = self.env["account.move"]
self.res_partner_model = self.env["res.partner"]
self.product_product_model = self.env["product.product"]
self.product_category_model = self.env["product.category"]
# Company
self.company = self.env.ref("base.main_company")
# Partner
self.partner = self.res_partner_model.create(
{"name": "Partner 1", "supplier_rank": 1, "is_company": True}
)
# Category
self.product_categ = self.product_category_model.create(
{"name": "Test category"}
)
self.uom_categ = self.env["uom.category"].create({"name": "Category 1"})
self.uom1 = self.env["uom.uom"].create(
{
"name": "UOM 1",
"category_id": self.uom_categ.id,
"factor": 1,
"active": True,
"uom_type": "reference",
}
)
# Products
self.product_category = self.env["product.category"].create(
{"name": "Test Product category"}
)
self.product_1 = self.env["product.product"].create(
{
"name": "Test Sale Product",
"sale_ok": True,
"type": "consu",
"categ_id": self.product_category.id,
"description_sale": "Test Description Sale",
"purchase_method": "receive",
}
)
def _create_purchase(self, product_qty=1, product_received=1):
"""Create a purchase order."""
purchase = self.purchase_order_model.create(
{"company_id": self.company.id, "partner_id": self.partner.id}
)
purchase_line_1 = self.purchase_order_line_model.create(
{
"name": self.product_1.name,
"product_id": self.product_1.id,
"product_qty": product_qty,
"product_uom": self.product_1.uom_po_id.id,
"price_unit": 100.0,
"date_planned": fields.Date.today(),
"order_id": purchase.id,
}
)
purchase.button_confirm()
# update quantities delivered
purchase_line_1.qty_received = product_received
return purchase
def _create_invoice_from_purchase(self, purchase):
invoice_form = Form(
self.account_move_model.with_context(default_move_type="in_invoice")
)
invoice_form.partner_id = purchase.partner_id
invoice_form.purchase_id = purchase
return invoice_form.save()
def test_create_purchase_and_not_invoiced(self):
purchase = self._create_purchase(1, 1)
self.assertEqual(
purchase.invoice_status,
"to invoice",
"The purchase status should be To Invoice",
)
self.assertEqual(
purchase.amount_uninvoiced,
purchase.amount_untaxed,
"The purchase amount uninvoiced must be the amount untaxed",
)
def test_create_purchase_and_no_receive(self):
purchase = self._create_purchase(2, 0)
self.assertEqual(
purchase.amount_uninvoiced, 0, "The purchase amount uninvoiced must be 0"
)
def test_create_purchase_and_invoiced_a_part(self):
purchase = self._create_purchase(10, 5)
self.assertEqual(purchase.amount_uninvoiced, 500)
invoice = self._create_invoice_from_purchase(purchase)
with Form(invoice) as invoice_form:
with invoice_form.invoice_line_ids.edit(0) as line_form:
line_form.quantity = 3
self.assertEqual(purchase.amount_uninvoiced, 200)
def test_create_purchase_create_and_invoiced_with_all_units(self):
purchase = self._create_purchase(2, 2)
self._create_invoice_from_purchase(purchase)
self.assertEqual(
purchase.amount_uninvoiced, 0, "The purchase amount uninvoiced must be 0"
)
def test_create_purchase_qty_0(self):
purchase = self._create_purchase(0, 0)
self.assertEqual(purchase.amount_uninvoiced, 0)
def test_on_ordered_quantities_policy(self):
self.product_1.purchase_method = "purchase"
purchase = self._create_purchase(10, 0)
self.assertEqual(purchase.amount_uninvoiced, 1000)
invoice = self._create_invoice_from_purchase(purchase)
with Form(invoice) as invoice_form:
with invoice_form.invoice_line_ids.edit(0) as line_form:
line_form.quantity = 6
self.assertEqual(purchase.amount_uninvoiced, 400)
self._create_invoice_from_purchase(purchase)
self.assertEqual(purchase.amount_uninvoiced, 0)
def test_create_purchase_receive_and_invoice_more_qty(self):
purchase = self._create_purchase(10, 10)
self.assertEqual(purchase.amount_uninvoiced, 1000)
invoice = self._create_invoice_from_purchase(purchase)
with Form(invoice) as invoice_form:
with invoice_form.invoice_line_ids.edit(0) as line_form:
line_form.quantity = 20
self.assertEqual(purchase.amount_uninvoiced, -1000)
| 40.394366
| 5,736
|
1,684
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Manuel Calero
# Copyright 2020 Tecnativa - Pedro M. Baeza
# Copyright 2020 Tecnativa - João Marques
# Copyright 2021 Tecnativa - Víctor Martínez
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class PurchaseOrder(models.Model):
_inherit = "purchase.order"
@api.depends(
"order_line.product_qty",
"order_line.qty_invoiced",
"order_line.qty_received",
"order_line.product_id",
"order_line.product_uom",
"order_line.price_unit",
)
def _compute_amount_uninvoiced(self):
for order in self:
amount_uninvoiced = 0
for line in order.order_line:
# The qty to invoice depends on the invoicing policy of
# the product
if line.product_id.purchase_method == "purchase":
qty = line.product_qty - line.qty_invoiced
else:
qty = line.qty_received - line.qty_invoiced
# we use this way for being compatible with purchase_discount
price_unit = (
line.price_subtotal / line.product_qty
if line.product_qty
else line.price_unit
)
amount_uninvoiced += qty * price_unit
order.update(
{"amount_uninvoiced": order.currency_id.round(amount_uninvoiced)}
)
amount_uninvoiced = fields.Monetary(
string="Uninvoiced Amount",
readonly=True,
compute="_compute_amount_uninvoiced",
tracking=True,
store=True,
)
| 35.020833
| 1,681
|
836
|
py
|
PYTHON
|
15.0
|
# © 2004-2009 Tiny SPRL (<http://tiny.be>).
# © 2014-2017 Tecnativa - Pedro M. Baeza
# © 2016 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Purchase order lines with discounts",
"author": "Tiny, "
"Acysos S.L., "
"Tecnativa, "
"ACSONE SA/NV,"
"GRAP,"
"Odoo Community Association (OCA)",
"version": "15.0.1.2.0",
"category": "Purchase Management",
"website": "https://github.com/OCA/purchase-workflow",
"depends": ["purchase_stock"],
"data": [
"views/purchase_discount_view.xml",
"views/report_purchaseorder.xml",
"views/product_supplierinfo_view.xml",
"views/res_partner_view.xml",
],
"license": "AGPL-3",
"installable": True,
"images": ["images/purchase_discount.png"],
}
| 32.038462
| 833
|
6,095
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 GRAP - Sylvain Legal
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields
from odoo.tests.common import TransactionCase
class TestProductSupplierinfoDiscount(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.supplierinfo_model = cls.env["product.supplierinfo"]
cls.purchase_order_line_model = cls.env["purchase.order.line"]
cls.partner_1 = cls.env.ref("base.res_partner_1")
cls.partner_3 = cls.env.ref("base.res_partner_3")
cls.product = cls.env.ref("product.product_product_6")
cls.supplierinfo = cls.supplierinfo_model.create(
{
"min_qty": 0.0,
"name": cls.partner_3.id,
"product_tmpl_id": cls.product.product_tmpl_id.id,
"discount": 10,
}
)
cls.supplierinfo2 = cls.supplierinfo_model.create(
{
"min_qty": 10.0,
"name": cls.partner_3.id,
"product_tmpl_id": cls.product.product_tmpl_id.id,
"discount": 20,
}
)
cls.purchase_order = cls.env["purchase.order"].create(
{"partner_id": cls.partner_3.id}
)
cls.po_line_1 = cls.purchase_order_line_model.create(
{
"order_id": cls.purchase_order.id,
"product_id": cls.product.id,
"date_planned": fields.Datetime.now(),
"name": "Test",
"product_qty": 1.0,
"product_uom": cls.env.ref("uom.product_uom_categ_unit").id,
"price_unit": 10.0,
}
)
def test_001_purchase_order_partner_3_qty_1(self):
self.po_line_1._onchange_quantity()
self.assertEqual(
self.po_line_1.discount,
10,
"Incorrect discount for product 6 with partner 3 and qty 1: "
"Should be 10%",
)
def test_002_purchase_order_partner_3_qty_10(self):
self.po_line_1.write({"product_qty": 10})
self.po_line_1._onchange_quantity()
self.assertEqual(
self.po_line_1.discount,
20.0,
"Incorrect discount for product 6 with partner 3 and qty 10: "
"Should be 20%",
)
def test_003_purchase_order_partner_1_qty_1(self):
self.po_line_1.write({"partner_id": self.partner_1.id, "product_qty": 1})
self.po_line_1.onchange_product_id()
self.assertEqual(
self.po_line_1.discount,
0.0,
"Incorrect discount for product 6 with partner 1 and qty 1",
)
def test_004_prepare_purchase_order_line(self):
res = self.purchase_order_line_model._prepare_purchase_order_line(
self.product,
50,
self.env.ref("uom.product_uom_unit"),
self.env.ref("base.main_company"),
self.supplierinfo,
self.purchase_order,
)
self.assertTrue(res.get("discount"), "Should have a discount key")
def test_005_default_supplierinfo_discount(self):
# Create an original supplierinfo
supplierinfo = self.supplierinfo_model.create(
{
"min_qty": 0.0,
"name": self.partner_3.id,
"product_tmpl_id": self.product.product_tmpl_id.id,
"discount": 10,
}
)
# Change the partner and raise onchange function
self.partner_1.default_supplierinfo_discount = 15
supplierinfo.name = self.partner_1
supplierinfo.onchange_name()
self.assertEqual(
supplierinfo.discount,
15,
"Incorrect discount for supplierinfo "
" after changing partner that has default discount defined.",
)
def test_006_supplierinfo_from_purchaseorder(self):
"""Include discount when creating new sellers for a product"""
partner = self.env.ref("base.res_partner_3")
product = self.env.ref("product.product_product_8")
self.assertFalse(
self.supplierinfo_model.search(
[
("name", "=", partner.id),
("product_tmpl_id", "=", product.product_tmpl_id.id),
]
)
)
order = self.env["purchase.order"].create({"partner_id": partner.id})
self.purchase_order_line_model.create(
{
"date_planned": fields.Datetime.now(),
"discount": 40,
"name": product.name,
"price_unit": 10.0,
"product_id": product.id,
"product_qty": 1.0,
"product_uom": product.uom_po_id.id,
"order_id": order.id,
}
)
order.button_confirm()
seller = self.supplierinfo_model.search(
[
("name", "=", partner.id),
("product_tmpl_id", "=", product.product_tmpl_id.id),
]
)
self.assertTrue(seller)
self.assertEqual(seller.discount, 40)
def test_007_change_price_unit_autoupdate_stock_move(self):
partner = self.env.ref("base.res_partner_3")
product = self.env.ref("product.product_product_8")
order = self.env["purchase.order"].create({"partner_id": partner.id})
self.purchase_order_line_model.create(
{
"date_planned": fields.Datetime.now(),
"discount": 40,
"name": product.name,
"price_unit": 10.0,
"product_id": product.id,
"product_qty": 1.0,
"product_uom": product.uom_po_id.id,
"order_id": order.id,
}
)
order.button_confirm()
self.assertEqual(order.order_line.move_ids.price_unit, 6)
order.order_line.price_unit = 100
self.assertEqual(order.order_line.move_ids.price_unit, 60)
| 37.392638
| 6,095
|
6,840
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>)
# Copyright 2015-2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields
from odoo.tests.common import TransactionCase
class TestPurchaseOrder(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestPurchaseOrder, cls).setUpClass()
cls.categ_cost_average = cls.env["product.category"].create(
{"name": "Average cost method category", "property_cost_method": "average"}
)
product_obj = cls.env["product.product"]
cls.product_1 = product_obj.create(
{"name": "Test product 1", "categ_id": cls.categ_cost_average.id}
)
cls.product_2 = product_obj.create({"name": "Test product 2"})
po_model = cls.env["purchase.order.line"]
currency_rate_model = cls.env["res.currency.rate"]
# Set the Exchange rate for the currency of the company to 1
# to avoid issues with rates
latest_currency_rate_line = currency_rate_model.search(
[
("currency_id", "=", cls.env.user.company_id.currency_id.id),
("name", "=", fields.Date.today()),
],
limit=1,
)
if latest_currency_rate_line and latest_currency_rate_line.rate != 1.0:
latest_currency_rate_line.rate = 1.0
elif not latest_currency_rate_line:
currency_rate_model.create(
{
"currency_id": cls.env.user.company_id.currency_id.id,
"rate": 1.00,
"name": fields.Date.today(),
}
)
cls.purchase_order = cls.env["purchase.order"].create(
{"partner_id": cls.env.ref("base.res_partner_3").id}
)
cls.po_line_1 = po_model.create(
{
"order_id": cls.purchase_order.id,
"product_id": cls.product_1.id,
"date_planned": fields.Datetime.now(),
"name": "Test",
"product_qty": 1.0,
"product_uom": cls.product_1.uom_id.id,
"discount": 50.0,
"price_unit": 10.0,
"taxes_id": [],
}
)
cls.account = cls.env["account.account"].create(
{
"name": "Test account",
"code": "TEST",
"user_type_id": cls.env.ref("account.data_account_type_expenses").id,
}
)
cls.tax = cls.env["account.tax"].create(
{
"name": "Sample tax 15%",
"amount_type": "percent",
"type_tax_use": "purchase",
"amount": 15.0,
"invoice_repartition_line_ids": [
(0, 0, {"factor_percent": 100, "repartition_type": "base"}),
(
0,
0,
{
"factor_percent": 100,
"repartition_type": "tax",
"account_id": cls.account.id,
},
),
],
}
)
cls.po_line_2 = po_model.create(
{
"order_id": cls.purchase_order.id,
"product_id": cls.product_2.id,
"date_planned": fields.Datetime.now(),
"name": "Test",
"product_qty": 10.0,
"product_uom": cls.product_2.uom_id.id,
"discount": 30,
"taxes_id": [(6, 0, [cls.tax.id])],
"price_unit": 230.0,
}
)
cls.po_line_3 = po_model.create(
{
"order_id": cls.purchase_order.id,
"product_id": cls.product_2.id,
"date_planned": fields.Datetime.now(),
"name": "Test",
"product_qty": 1.0,
"product_uom": cls.product_2.uom_id.id,
"discount": 0,
"taxes_id": [(6, 0, [cls.tax.id])],
"price_unit": 10.0,
}
)
def test_purchase_order_vals(self):
self.assertEqual(self.po_line_1.price_subtotal, 5.0)
self.assertEqual(self.po_line_2.price_subtotal, 1610.0)
self.assertEqual(self.po_line_3.price_subtotal, 10.0)
self.assertEqual(self.purchase_order.amount_untaxed, 1625.0)
self.assertEqual(self.purchase_order.amount_tax, 243)
# Change price to launch a recalculation of totals
self.po_line_1.discount = 60
self.assertEqual(self.po_line_1.price_subtotal, 4.0)
self.assertEqual(self.purchase_order.amount_untaxed, 1624.0)
self.assertEqual(self.purchase_order.amount_tax, 243)
def test_move_price_unit(self):
self.purchase_order.button_confirm()
picking = self.purchase_order.picking_ids
moves = picking.move_lines
move1 = moves.filtered(lambda x: x.purchase_line_id == self.po_line_1)
self.assertEqual(move1.price_unit, 5)
move2 = moves.filtered(lambda x: x.purchase_line_id == self.po_line_2)
self.assertEqual(move2.price_unit, 161)
move3 = moves.filtered(lambda x: x.purchase_line_id == self.po_line_3)
self.assertEqual(move3.price_unit, 10)
# Confirm the picking to see the cost price
move1.move_line_ids.qty_done = 1
picking._action_done()
self.assertAlmostEqual(self.product_1.standard_price, 5.0)
# Check data in PO remains the same - This is due to the hack
self.assertAlmostEqual(self.po_line_1.price_unit, 10.0)
self.assertAlmostEqual(self.po_line_1.discount, 50.0)
def test_report_price_unit(self):
rec = self.env["purchase.report"].search(
[("product_id", "=", self.product_1.id)]
)
self.assertEqual(rec.price_total, 5)
self.assertEqual(rec.discount, 50)
def test_invoice(self):
invoice = self.env["account.move"].new(
{
"move_type": "out_invoice",
"partner_id": self.env.ref("base.res_partner_3").id,
"purchase_id": self.purchase_order.id,
}
)
invoice._onchange_purchase_auto_complete()
line = invoice.invoice_line_ids.filtered(
lambda x: x.purchase_line_id == self.po_line_1
)
self.assertEqual(line.discount, 50)
line = invoice.invoice_line_ids.filtered(
lambda x: x.purchase_line_id == self.po_line_2
)
self.assertEqual(line.discount, 30)
line = invoice.invoice_line_ids.filtered(
lambda x: x.purchase_line_id == self.po_line_3
)
self.assertEqual(line.discount, 0)
| 40.473373
| 6,840
|
1,486
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>)
# Copyright 2014-2019 Tecnativa - Pedro M. Baeza
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import api, fields, models
class ProductSupplierInfo(models.Model):
_inherit = "product.supplierinfo"
discount = fields.Float(string="Discount (%)", digits="Discount")
@api.onchange("name")
def onchange_name(self):
"""Apply the default supplier discount of the selected supplier"""
for supplierinfo in self.filtered("name"):
supplierinfo.discount = supplierinfo.name.default_supplierinfo_discount
@api.model
def _get_po_to_supplierinfo_synced_fields(self):
"""Overwrite this method for adding other fields to be synchronized
with product.supplierinfo.
"""
return ["discount"]
@api.model_create_multi
def create(self, vals_list):
"""Insert discount (or others) from context from purchase.order's
_add_supplier_to_product method"""
for vals in vals_list:
product_tmpl_id = vals["product_tmpl_id"]
po_line_map = self.env.context.get("po_line_map", {})
if product_tmpl_id in po_line_map:
po_line = po_line_map[product_tmpl_id]
for field in self._get_po_to_supplierinfo_synced_fields():
if not vals.get(field):
vals[field] = po_line[field]
return super().create(vals_list)
| 39.105263
| 1,486
|
5,172
|
py
|
PYTHON
|
15.0
|
# Copyright 2004-2009 Tiny SPRL (<http://tiny.be>).
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>)
# Copyright 2015-2019 Tecnativa - Pedro M. Baeza
# 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"
def _add_supplier_to_product(self):
"""Insert a mapping of products to PO lines to be picked up
in supplierinfo's create()"""
self.ensure_one()
po_line_map = {
line.product_id.product_tmpl_id.id: line for line in self.order_line
}
return super(
PurchaseOrder, self.with_context(po_line_map=po_line_map)
)._add_supplier_to_product()
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
# adding discount to depends
@api.depends("discount")
def _compute_amount(self):
return super()._compute_amount()
def _prepare_compute_all_values(self):
vals = super()._prepare_compute_all_values()
vals.update({"price_unit": self._get_discounted_price_unit()})
return vals
discount = fields.Float(string="Discount (%)", digits="Discount")
_sql_constraints = [
(
"discount_limit",
"CHECK (discount <= 100.0)",
"Discount must be lower than 100%.",
)
]
def _get_discounted_price_unit(self):
"""Inheritable method for getting the unit price after applying
discount(s).
:rtype: float
:return: Unit price after discount(s).
"""
self.ensure_one()
if self.discount:
return self.price_unit * (1 - self.discount / 100)
return self.price_unit
def _get_stock_move_price_unit(self):
"""Get correct price with discount replacing current price_unit
value before calling super and restoring it later for assuring
maximum inheritability.
HACK: This is needed while https://github.com/odoo/odoo/pull/29983
is not merged.
"""
# Use 'skip_update_price_unit' context key to avoid infinite
# recursion. Updating the price_unit field here triggers the
# 'write' method of 'purchase.order.line' in stock_account
# module which triggers this method again.
if self.env.context.get("skip_update_price_unit"):
return super()._get_stock_move_price_unit()
price_unit = False
price = self._get_discounted_price_unit()
if price != self.price_unit:
# Only change value if it's different
price_unit = self.price_unit
self.with_context(skip_update_price_unit=True).price_unit = price
price = super()._get_stock_move_price_unit()
if price_unit:
self.with_context(skip_update_price_unit=True).price_unit = price_unit
return price
@api.onchange("product_qty", "product_uom")
def _onchange_quantity(self):
"""
Check if a discount is defined into the supplier info and if so then
apply it to the current purchase order line
"""
res = super()._onchange_quantity()
if self.product_id:
date = None
if self.order_id.date_order:
date = self.order_id.date_order.date()
seller = self.product_id._select_seller(
partner_id=self.partner_id,
quantity=self.product_qty,
date=date,
uom_id=self.product_uom,
)
self._apply_value_from_seller(seller)
return res
@api.model
def _apply_value_from_seller(self, seller):
"""Overload this function to prepare other data from seller,
like in purchase_triple_discount module"""
if not seller:
return
self.discount = seller.discount
def _prepare_account_move_line(self, move=False):
vals = super(PurchaseOrderLine, self)._prepare_account_move_line(move)
vals["discount"] = self.discount
return vals
@api.model
def _prepare_purchase_order_line(
self, product_id, product_qty, product_uom, company_id, supplier, po
):
"""Apply the discount to the created purchase order"""
res = super()._prepare_purchase_order_line(
product_id, product_qty, product_uom, company_id, supplier, po
)
partner = supplier.name
uom_po_qty = product_uom._compute_quantity(product_qty, product_id.uom_po_id)
seller = product_id.with_company(company_id)._select_seller(
partner_id=partner,
quantity=uom_po_qty,
date=po.date_order and po.date_order.date(),
uom_id=product_id.uom_po_id,
)
res.update(self._prepare_purchase_order_line_from_seller(seller))
return res
@api.model
def _prepare_purchase_order_line_from_seller(self, seller):
"""Overload this function to prepare other data from seller,
like in purchase_triple_discount module"""
if not seller:
return {}
return {"discount": seller.discount}
| 36.167832
| 5,172
|
1,205
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
class StockMove(models.Model):
_inherit = "stock.move"
def write(self, values):
if self.env.context.get("skip_update_price_unit") and values.get("price_unit"):
values.pop("price_unit")
return super().write(values)
def _get_price_unit(self):
"""Get correct price with discount replacing current price_unit
value before calling super and restoring it later for assuring
maximum inheritability.
HACK: This is needed while https://github.com/odoo/odoo/pull/29983
is not merged.
"""
price_unit = False
po_line = self.purchase_line_id
if po_line and self.product_id == po_line.product_id:
price = po_line._get_discounted_price_unit()
if price != po_line.price_unit:
# Only change value if it's different
price_unit = po_line.price_unit
po_line.price_unit = price
res = super()._get_price_unit()
if price_unit:
po_line.price_unit = price_unit
return res
| 35.441176
| 1,205
|
527
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 GRAP (http://www.grap.coop)
# Sylvain LE GAL (https://twitter.com/legalsylvain)
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
default_supplierinfo_discount = fields.Float(
string="Default Supplier Discount (%)",
digits="Discount",
help="This value will be used as the default one, for each new"
" supplierinfo line depending on that supplier.",
)
| 32.9375
| 527
|
1,073
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 Akretion (Alexis de Lattre <alexis.delattre@akretion.com>)
# Copyright 2017-2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class PurchaseReport(models.Model):
_inherit = "purchase.report"
discount = fields.Float(
string="Discount (%)", digits="Discount", group_operator="avg"
)
def _select(self):
res = super()._select()
# There are 3 matches
res = res.replace("l.price_unit", self._get_discounted_price_unit_exp())
res += ", l.discount AS discount"
return res
def _group_by(self):
res = super()._group_by()
res += ", l.discount"
return res
def _get_discounted_price_unit_exp(self):
"""Inheritable method for getting the SQL expression used for
calculating the unit price with discount(s).
:rtype: str
:return: SQL expression for discounted unit price.
"""
return "(1.0 - COALESCE(l.discount, 0.0) / 100.0) * l.price_unit"
| 31.558824
| 1,073
|
468
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Purchase - Receipt Percentage",
"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.428571
| 468
|
2,701
|
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 TestPurchaseTotalOrderedQty(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,
}
)
def test_00_order_empty_without_lines(self):
"""Test empty order w/o lines: receipt percentage should be 100%"""
self.assertEqual(self.order.receipt_percentage, 100)
self.assertEqual(self.order.receipt_percentage_display, 1)
def test_01_order_empty_with_lines(self):
"""Test empty order w/ lines: receipt percentage should be 100%"""
self.env["purchase.order.line"].create(
{
"order_id": self.order.id,
"name": self.product.name,
"product_id": self.product.id,
"product_qty": 0.0,
}
)
self.assertEqual(self.order.order_line.receipt_percentage, 100)
self.assertEqual(self.order.receipt_percentage, 100)
self.assertEqual(self.order.receipt_percentage_display, 1)
def test_02_order_with_lines(self):
"""Test order w/ lines
Add 2 lines:
1) 20u ordered, 0u received
2) 5u ordered, 5u received
Expected percentage is 20%
"""
self.env["purchase.order.line"].create(
[
{
"order_id": self.order.id,
"name": self.product.name,
"product_id": self.product.id,
"product_qty": 20.0,
"qty_received_manual": 0.0,
},
{
"order_id": self.order.id,
"name": self.product.name,
"product_id": self.product.id,
"product_qty": 5.0,
"qty_received_manual": 5.0,
},
]
)
self.assertEqual(self.order.order_line[0].receipt_percentage, 0)
self.assertEqual(self.order.order_line[1].receipt_percentage, 100)
self.assertEqual(self.order.receipt_percentage, 20)
self.assertEqual(self.order.receipt_percentage_display, 0.20)
| 38.042254
| 2,701
|
803
|
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
from odoo.tools.float_utils import float_is_zero
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
receipt_percentage = fields.Float(compute="_compute_receipt_percentage", store=True)
@api.depends("qty_received", "product_qty")
def _compute_receipt_percentage(self):
for line in self:
perc = 100 # 100% by default, in case ordered qty is 0
if not float_is_zero(
line.product_qty, precision_rounding=line.product_uom.rounding
):
perc *= line.qty_received / line.product_qty
line.receipt_percentage = min(max(perc, 0), 100) # 0 <= % <= 100
| 38.238095
| 803
|
1,589
|
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 PurchaseOrder(models.Model):
_inherit = "purchase.order"
receipt_percentage = fields.Float(
compute="_compute_receipt_percentage",
store=True,
help="Receipt percentage between 0% and 100%",
)
receipt_percentage_display = fields.Float(
compute="_compute_receipt_percentage",
store=True,
help="Technical field to be displayed in view. Its value is between"
" 0 and 1, the percentage widget will format the value properly",
)
@api.depends("order_line.product_uom_qty", "order_line.receipt_percentage")
def _compute_receipt_percentage(self):
with_lines = self.filtered("order_line")
(self - with_lines).update(
{"receipt_percentage": 100, "receipt_percentage_display": 1}
)
for order in with_lines:
num, den = 0, 0
for line in order.order_line:
qty = line.product_uom_qty or 1
num += qty * line.receipt_percentage
den += qty
ratio = num / den
order.update(
{
"receipt_percentage": ratio,
# NB: we divide by 100 because we want this field to be in
# [0, 1], the percentage widget in the view will take care
# of displaying it correctly
"receipt_percentage_display": ratio / 100,
}
)
| 36.953488
| 1,589
|
820
|
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 - Late Delivery Fines",
"version": "15.0.1.1.0",
"category": "Purchase Management",
"author": "Ecosoft, Odoo Community Association (OCA)",
"license": "AGPL-3",
"website": "https://github.com/OCA/purchase-workflow",
"depends": ["purchase_work_acceptance"],
"data": [
"security/ir.model.access.csv",
"security/security.xml",
"wizards/work_acceptance_create_fines_views.xml",
"views/res_config_settings_views.xml",
"views/work_acceptance_views.xml",
"views/account_move_views.xml",
],
"maintainers": ["Saran440"],
"installable": True,
"development_status": "Alpha",
}
| 35.652174
| 820
|
6,745
|
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 dateutil.relativedelta import relativedelta
from odoo import fields
from odoo.exceptions import UserError
from odoo.tests.common import Form, TransactionCase
class TestWorkAcceptanceLateFine(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
account_obj = cls.env["account.account"]
cls.service_product = cls.env.ref("product.product_product_1")
cls.product_product = cls.env.ref("product.product_product_6")
cls.res_partner = cls.env.ref("base.res_partner_3")
cls.employee = cls.env.ref("base.user_demo")
cls.currency_eur = cls.env.ref("base.EUR")
cls.currency_usd = cls.env.ref("base.USD")
cls.main_company = cls.env.ref("base.main_company")
cls.env.cr.execute(
"""UPDATE res_company SET currency_id = %s
WHERE id = %s""",
(cls.main_company.id, cls.currency_eur.id),
)
cls.date_now = fields.Datetime.now()
cls.account_receivable = account_obj.create(
{
"code": "cust_acc",
"name": "customer account",
"user_type_id": cls.env.ref("account.data_account_type_receivable").id,
"reconcile": True,
}
)
cls.not_late = cls.date_now + relativedelta(days=2)
cls.late2days = cls.date_now - relativedelta(days=2)
# Enable and Config WA Delivery Late Fines
cls._config_wa_late(cls)
def _config_wa_late(self):
config = self.env["res.config.settings"]
with Form(config) as c:
c.group_enable_fines_on_wa = True
c.wa_fines_rate = 100.0
c.wa_fines_late_account_id = self.account_receivable
def _create_wa(self, due_date, currency=False, product_qty=False):
work_acceptance = self.env["work.acceptance"].create(
{
"partner_id": self.res_partner.id,
"responsible_id": self.employee.id,
"date_due": due_date,
"date_receive": self.date_now,
"company_id": self.main_company.id,
"currency_id": currency or self.currency_eur.id,
"wa_line_ids": [
(
0,
0,
{
"product_id": self.service_product.id,
"name": self.service_product.name,
"price_unit": self.service_product.standard_price,
"product_qty": product_qty or 1.0,
"product_uom": self.service_product.uom_id.id,
},
)
],
}
)
work_acceptance._onchange_late_days()
work_acceptance._onchange_fines_late()
return work_acceptance
def test_01_compute_wa_late(self):
work_acceptance = self._create_wa(self.not_late)
self.assertEqual(work_acceptance.late_days, 0)
work_acceptance = self._create_wa(self.late2days)
self.assertEqual(work_acceptance.late_days, 2)
self.assertEqual(work_acceptance.fines_rate, 100.0)
self.assertEqual(work_acceptance.fines_late, 200.0)
def test_02_wa_late_multi_currency(self):
work_acceptance = self._create_wa(
self.late2days, self.currency_usd.id, product_qty=2
)
self.assertEqual(work_acceptance.currency_id.id, self.currency_usd.id)
move = self.env["account.move"].create({"move_type": "out_invoice"})
self.assertEqual(move.currency_id.id, self.currency_eur.id)
with Form(move) as m:
m.late_wa_id = work_acceptance
m.partner_id = self.res_partner
move = m.save()
self.assertEqual(move.currency_id.id, self.currency_usd.id)
def test_03_create_fines_from_wa(self):
work_acceptance1 = self._create_wa(self.late2days)
work_acceptance2 = self._create_wa(self.not_late)
result = work_acceptance1.action_create_fines_invoice()
# Should be form view
move = self.env[result["res_model"]].browse(result["res_id"])
self.assertEqual(move.late_wa_id.id, work_acceptance1.id)
self.assertEqual(len(work_acceptance1.fines_invoice_ids.ids), 1)
self.assertEqual(work_acceptance1.fines_invoice_count, 1)
# Can create 1 time until you cancel fines invoice
with self.assertRaises(UserError):
work_acceptance1.action_create_fines_invoice()
move.button_cancel()
work_acceptance1.action_create_fines_invoice()
self.assertEqual(len(work_acceptance1.fines_invoice_ids.ids), 2)
self.assertEqual(work_acceptance1.fines_invoice_count, 2)
# Not late can't create fines
with self.assertRaises(UserError):
work_acceptance2.action_create_fines_invoice()
# Check no invoice (fines) in WA
with self.assertRaises(UserError):
work_acceptance2.action_view_invoice()
# Button from wa to fines
work_acceptance1.action_view_invoice()
def test_04_create_multi_fines_from_wa(self):
work_acceptance1 = self._create_wa(self.late2days)
work_acceptance2 = self._create_wa(self.late2days)
ctx = {"active_ids": [work_acceptance1.id, work_acceptance2.id]}
work_acceptance = work_acceptance1 + work_acceptance2
result = work_acceptance.with_context(**ctx).action_create_fines_invoice()
# Should be tree view
self.assertFalse(result.get("res_id"))
domain = result["domain"]
move_ids = self.env[result["res_model"]].browse(domain[0][2])
self.assertEqual(move_ids.mapped("late_wa_id").ids, work_acceptance.ids)
def test_05_create_fines_invoice_refund(self):
"""Test create fines as invoice and refund"""
work_acceptance1 = self._create_wa(self.late2days)
ctx = {"active_ids": [work_acceptance1.id]}
# Fines as Invoice or Refund
for move_type in ["out_invoice", "in_refund"]:
with Form(
self.env["work.acceptance.create.fines"].with_context(**ctx)
) as f:
f.move_type = move_type
create_fine = f.save()
create_fine.action_create_fines()
self.assertEqual(len(work_acceptance1.fines_invoice_ids.ids), 1)
res = work_acceptance1.action_view_invoice()
move = self.env["account.move"].browse(res["res_id"])
self.assertEqual(move.move_type, move_type)
move.unlink()
| 44.668874
| 6,745
|
2,418
|
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 api, fields, models
class AccountMove(models.Model):
_inherit = "account.move"
late_wa_id = fields.Many2one(
comodel_name="work.acceptance",
string="Late WA",
domain=lambda self: self._domain_late_wa(),
index=True,
ondelete="restrict",
help="For the supplier with late penalty (from work acceptance), "
"choosing the late WA to get the amount this partner need to pay.",
)
@api.model
def _domain_late_wa(self):
AccountMove = self.env["account.move"]
used_wa_ids = AccountMove.search([("state", "!=", "cancel")]).mapped(
"late_wa_id"
)
dom = [
("fines_late", ">", 0.0),
("state", "!=", "cancel"),
("id", "not in", used_wa_ids.ids),
]
if self.env.context.get("default_partner_id", False):
dom.append(("partner_id", "=", self.env.context["default_partner_id"]))
return dom
@api.onchange("partner_id")
def _onchange_partner_late_wa(self):
if self.late_wa_id:
self.late_wa_id = False
self.invoice_line_ids = False
self.line_ids = False
if self.partner_id:
self.with_context(
default_partner_id=self.partner_id.id
)._domain_late_wa()
def _prepare_move_wa_late(self, wa):
move_dict = {
"partner_id": wa.partner_id.id,
"currency_id": wa.currency_id,
"company_id": wa.company_id,
}
return move_dict
@api.onchange("late_wa_id")
def _onchange_late_wa_id(self):
"""Auto fill values from WA delivery late fines"""
MoveLine = self.env["account.move.line"]
if self.move_type in ("out_invoice", "in_refund") and self.late_wa_id:
self.invoice_line_ids = False
self.line_ids = False
move_dict = self._prepare_move_wa_late(self.late_wa_id)
move_line_dict = self.late_wa_id._prepare_late_wa_move_line()
move_line_dict.update(
{"move_id": self.id, "date_maturity": self.invoice_date_due}
)
self.update(move_dict)
MoveLine.new(move_line_dict)
self._onchange_currency()
| 35.558824
| 2,418
|
421
|
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 Company(models.Model):
_inherit = "res.company"
wa_fines_rate = fields.Monetary(string="Fines Rate")
wa_fines_late_account_id = fields.Many2one(
comodel_name="account.account",
string="Late Delivery Fines Revenue Account",
)
| 30.071429
| 421
|
1,003
|
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 api, fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
group_enable_fines_on_wa = fields.Boolean(
string="Enable Late Delivery Fines on Work Acceptance",
implied_group="purchase_work_acceptance_late_fines.group_enable_fines_on_wa",
)
wa_fines_late_account_id = fields.Many2one(
comodel_name="account.account",
related="company_id.wa_fines_late_account_id",
string="Late Delivery Fines Revenue Account",
readonly=False,
)
wa_fines_rate = fields.Monetary(
related="company_id.wa_fines_rate",
string="Fines Rate",
readonly=False,
)
@api.onchange("group_enable_fines_on_wa")
def _onchange_group_enable_fines_on_wa(self):
if self.group_enable_fines_on_wa:
self.group_enable_wa_on_po = True
| 34.586207
| 1,003
|
4,756
|
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 _, api, fields, models
from odoo.exceptions import UserError
class WorkAcceptance(models.Model):
_inherit = "work.acceptance"
late_days = fields.Integer(
readonly=True,
states={"draft": [("readonly", False)]},
tracking=True,
help="Late day(s) from Received Date - Due Date",
)
fines_rate = fields.Monetary(
default=lambda self: self.env.company.wa_fines_rate,
readonly=True,
states={"draft": [("readonly", False)]},
tracking=True,
help="Default fines per day. Can be overwritten",
)
fines_late = fields.Monetary(
string="Fines Amount",
readonly=True,
states={"draft": [("readonly", False)]},
tracking=True,
help="Computed amount. Can be overwritten",
)
fines_invoice_count = fields.Integer(
compute="_compute_fines_invoice_count",
)
fines_invoice_ids = fields.One2many(
comodel_name="account.move",
inverse_name="late_wa_id",
string="Fines Invoices",
)
_sql_constraints = [
("late_days", "CHECK (late_days>=0)", "Wrong Late Days, it must be positive!"),
(
"fines_rate",
"CHECK (fines_rate>=0)",
"Wrong Fines Rate, it must be positive!",
),
(
"fines_late",
"CHECK (fines_late>=0)",
"Wrong Fines Amount, it must be positive!",
),
]
@api.depends("fines_invoice_ids")
def _compute_fines_invoice_count(self):
for rec in self:
rec.fines_invoice_count = len(rec.fines_invoice_ids)
def action_view_invoice(self):
move_ids = self.env.context.get("created_move_ids", [])
if not move_ids:
active_ids = self.ids or self.env.context.get("active_ids", [])
work_acceptances = self.env["work.acceptance"].browse(active_ids)
move_ids = work_acceptances.mapped("fines_invoice_ids").ids
if not move_ids:
raise UserError(_("No fine invoices"))
result = {
"name": _("Fines Invoice/Refund"),
"type": "ir.actions.act_window",
"view_mode": "tree,kanban,form",
"res_model": "account.move",
}
if len(move_ids) > 1:
result["domain"] = [("id", "in", move_ids)]
else:
res = self.env.ref("account.view_move_form", False)
result.update(
{
"views": [(res and res.id or False, "form")],
"res_id": move_ids[0],
}
)
return result
def action_create_fines_invoice(self, move_type="out_invoice"):
AccountMove = self.env["account.move"]
active_ids = self.ids or self.env.context.get("active_ids", [])
work_acceptances = self.browse(active_ids)
if any(wa.fines_late <= 0.0 for wa in work_acceptances):
raise UserError(_("No late fines on work acceptance(s)"))
fines_invoices = AccountMove.search(
[("late_wa_id", "in", work_acceptances.ids), ("state", "!=", "cancel")]
)
if fines_invoices:
names = ", ".join(fines_invoices.mapped("late_wa_id").mapped("name"))
raise UserError(_("Invoice already created for %s") % names)
move_dict = self._prepare_late_wa_moves(move_type)
moves = AccountMove.create(move_dict)
result = self.with_context(created_move_ids=moves.ids).action_view_invoice()
return result
def _prepare_late_wa_moves(self, move_type):
return [
{
"partner_id": wa.partner_id.id,
"move_type": move_type,
"late_wa_id": wa.id,
"invoice_line_ids": [(0, 0, wa._prepare_late_wa_move_line())],
}
for wa in self
]
def _prepare_late_wa_move_line(self, name=False):
return {
"name": name or _("Work Acceptance Late Delivery Fines %s") % (self.name),
"account_id": self.env.company.wa_fines_late_account_id,
"price_unit": self.fines_late,
}
@api.onchange("date_receive", "date_due")
def _onchange_late_days(self):
late_days = 0
if self.date_receive and self.date_due:
late_days = (self.date_receive - self.date_due).days
self.late_days = late_days > 0 and late_days or 0
@api.onchange("late_days", "fines_rate")
def _onchange_fines_late(self):
fines_late = self.late_days * self.fines_rate
self.fines_late = fines_late > 0 and fines_late or 0
| 36.868217
| 4,756
|
810
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class WorkAcceptanceCreateFine(models.TransientModel):
_name = "work.acceptance.create.fines"
_description = "Create Fines Invoice/Refund from WA"
move_type = fields.Selection(
selection=[
("out_invoice", "Customer Invoice"),
("in_refund", "Vendor Refund"),
],
string="Type",
required=True,
default="out_invoice",
)
def action_create_fines(self):
active_ids = self.env.context.get("active_ids", [])
work_acceptances = self.env["work.acceptance"].browse(active_ids)
return work_acceptances.action_create_fines_invoice(move_type=self.move_type)
| 33.75
| 810
|
486
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Purchase Requisition Grouped by Procurement",
"version": "15.0.1.0.0",
"category": "Purchases",
"website": "https://github.com/OCA/purchase-workflow",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"depends": ["purchase_requisition_stock"],
"installable": True,
"maintainers": ["victoralmau"],
}
| 37.230769
| 484
|
2,514
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields
from odoo.tests import TransactionCase
class TestPurchaseRequisitionGgroupedbyProcurement(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.mto = cls.env.ref("stock.route_warehouse0_mto")
cls.buy = cls.env.ref("purchase_stock.route_warehouse0_buy")
cls.product_a = cls._create_product(cls, "Test product A")
cls.product_b = cls._create_product(cls, "Test product B")
cls.origin = "TEST"
cls.group = cls.env["procurement.group"].create({"name": "Test"})
cls.location = cls.env.ref("stock.stock_location_stock")
cls.stock_location_route = cls.env.ref("purchase_stock.route_warehouse0_buy")
cls.stock_rule = cls.stock_location_route.rule_ids[0]
cls.values = {"date_planned": fields.Datetime.now(), "group_id": cls.group}
def _create_product(self, name):
return self.env["product.product"].create(
{
"name": name,
"type": "product",
"purchase_requisition": "tenders",
"route_ids": [(6, 0, [self.buy.id, self.mto.id])],
}
)
def _set_procurement_by_product(self, group, product):
procurement = group.Procurement(
product,
1,
product.uom_id,
self.location,
False,
self.origin,
self.env.company,
self.values,
)
rule = group._get_rule(
procurement.product_id, procurement.location_id, procurement.values
)
return (procurement, rule)
def _run_procurements(self):
self.stock_rule._run_buy(
[
self._set_procurement_by_product(self.group, self.product_a),
self._set_procurement_by_product(self.group, self.product_b),
]
)
def test_purchase_requisition_grouped(self):
domain = [("state", "=", "draft")]
self.env["purchase.requisition"].search(domain).unlink()
self._run_procurements()
items = self.env["purchase.requisition"].search(domain)
self.assertEqual(len(items), 1)
self.assertEqual(items.origin, self.origin)
self.assertTrue(self.product_a in items.line_ids.mapped("product_id"))
self.assertTrue(self.product_b in items.line_ids.mapped("product_id"))
| 38.646154
| 2,512
|
395
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, models
class StockRule(models.Model):
_inherit = "stock.rule"
@api.model
def _run_buy(self, procurements):
_self = self.with_context(grouped_by_procurement=True)
return super(StockRule, _self)._run_buy(procurements=procurements)
| 30.230769
| 393
|
1,623
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class PurchaseRequisition(models.Model):
_inherit = "purchase.requisition"
group_id = fields.Many2one(comodel_name="procurement.group", string="Group")
def _prepare_tender_values(
self,
product_id,
product_qty,
product_uom,
location_id,
name,
origin,
company_id,
values,
):
res = super()._prepare_tender_values(
product_id,
product_qty,
product_uom,
location_id,
name,
origin,
company_id,
values,
)
res["group_id"] = values.get("group_id").id or False
return res
@api.model
def create(self, vals):
"""It is not possible to intercept _run_buy() to add lines instead of creating
multiple records.
This method is used to find if there is any previously created record with
the same values to add the line instead of creating a new record.
"""
if self.env.context.get("grouped_by_procurement") and vals.get("group_id"):
domain = []
for key in vals:
if key == "line_ids":
continue
domain.append((key, "=", vals.get(key)))
purchase = self.search(domain)
if purchase:
purchase.write({"line_ids": vals.get("line_ids")})
return purchase
return super().create(vals)
| 30.584906
| 1,621
|
546
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Purchase order line price history discount",
"version": "15.0.1.0.0",
"category": "Purchase Management",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/purchase-workflow",
"license": "AGPL-3",
"depends": ["purchase_order_line_price_history", "purchase_discount"],
"data": ["wizards/purchase_order_line_price_history.xml"],
"installable": True,
}
| 42
| 546
|
1,135
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Ernesto Tejeda
# Copyright 2020 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.addons.purchase_order_line_price_history.tests.test_purchase_order_line_price_history import ( # noqa: B950
TestPurchaseOrderLinePriceHistoryBase,
)
class TestPurchaseOrderLinePriceHistoryDiscount(TestPurchaseOrderLinePriceHistoryBase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.purchase_order_1.order_line.discount = 10
cls.purchase_order_2.partner_id = cls.partner_1.id
cls.purchase_order_2.order_line.discount = 20
def test_action_set_price(self):
# Create a wizard from self.purchase_order_2.order_line
wizard = self.launch_wizard(self.purchase_order_2.order_line.id)
self.assertEqual(wizard.line_ids.discount, 10)
# Set the price of the history line to the purchase order line
wizard.line_ids.action_set_price()
self.assertEqual(self.purchase_order_2.order_line.price_unit, 10)
self.assertEqual(self.purchase_order_2.order_line.discount, 10)
| 45.4
| 1,135
|
507
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class PurchaseOrderLinePriceHistoryLine(models.TransientModel):
_inherit = "purchase.order.line.price.history.line"
discount = fields.Float(related="purchase_order_line_id.discount")
def _prepare_purchase_order_line_vals(self):
vals = super()._prepare_purchase_order_line_vals()
vals.update(discount=self.discount)
return vals
| 36.214286
| 507
|
492
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 CreuBlanca
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Purchase Invoice Method",
"summary": """
Allow to force the invoice method of a purchase""",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"author": "CreuBlanca,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/purchase-workflow",
"depends": ["purchase"],
"data": [
"views/purchase_order.xml",
],
"demo": [],
}
| 28.941176
| 492
|
3,137
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 CreuBlanca
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests import Form
from odoo.tests.common import TransactionCase
class TestPurchaseInvoiceMethod(TransactionCase):
def setUp(self):
super().setUp()
self.vendor = self.env["res.partner"].create(
{
"name": "Supplier",
"email": "supplier.serv@supercompany.com",
}
)
self.product = self.env["product.product"].create(
{
"name": "Product",
"standard_price": 200.0,
"list_price": 180.0,
"type": "service",
"purchase_method": "receive",
}
)
def test_force_create_invoice_receive(self):
purchase_order_form = Form(self.env["purchase.order"])
purchase_order_form.partner_id = self.vendor
with purchase_order_form.order_line.new() as line:
line.name = self.product.name
line.product_id = self.product
line.product_qty = 4
line.price_unit = 500
purchase_order = purchase_order_form.save()
purchase_order.button_confirm()
self.assertEqual(purchase_order.invoice_status, "no")
purchase_order.invoice_method = "purchase"
self.assertEqual(purchase_order.invoice_status, "to invoice")
for line in purchase_order.order_line:
self.assertEqual(line.product_qty, 4)
self.assertEqual(line.qty_invoiced, 0.0)
purchase_order.action_create_invoice()
self.assertEqual(purchase_order.invoice_status, "invoiced")
for line in purchase_order.order_line:
self.assertEqual(line.qty_to_invoice, 0.0)
self.assertEqual(line.qty_invoiced, 4)
def test_force_create_invoice_purchase(self):
self.product.purchase_method = "purchase"
purchase_order_form = Form(self.env["purchase.order"])
purchase_order_form.partner_id = self.vendor
with purchase_order_form.order_line.new() as line:
line.name = self.product.name
line.product_id = self.product
line.product_qty = 4
line.price_unit = 500
purchase_order = purchase_order_form.save()
purchase_order.button_confirm()
self.assertEqual(purchase_order.invoice_status, "to invoice")
purchase_order.invoice_method = "receive"
self.assertEqual(purchase_order.invoice_status, "no")
def test_force_create_invoice_draft(self):
purchase_order_form = Form(self.env["purchase.order"])
purchase_order_form.partner_id = self.vendor
with purchase_order_form.order_line.new() as line:
line.name = self.product.name
line.product_id = self.product
line.product_qty = 4
line.price_unit = 500
purchase_order = purchase_order_form.save()
purchase_order.invoice_method = "purchase"
self.assertEqual(purchase_order.invoice_status, "no")
self.assertEqual(purchase_order.order_line.qty_to_invoice, 0)
| 36.057471
| 3,137
|
1,138
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 CreuBlanca
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class PurchaseOrder(models.Model):
_inherit = "purchase.order"
invoice_method = fields.Selection(
lambda r: r.env["product.template"]._fields["purchase_method"].selection
)
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
@api.depends(
"invoice_lines.move_id.state",
"invoice_lines.quantity",
"qty_received",
"product_uom_qty",
"order_id.state",
"order_id.invoice_method",
)
def _compute_qty_invoiced(self):
ret = super()._compute_qty_invoiced()
for line in self.filtered(
lambda r: r.order_id.invoice_method
and r.order_id.state in ["purchase", "done"]
):
if line.order_id.invoice_method == "purchase":
line.qty_to_invoice = line.product_qty - line.qty_invoiced
elif line.order_id.invoice_method == "receive":
line.qty_to_invoice = line.qty_received - line.qty_invoiced
return ret
| 31.611111
| 1,138
|
1,005
|
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).
{
"name": "Purchase Work Acceptance",
"version": "15.0.1.1.0",
"category": "Purchase Management",
"author": "Ecosoft, Odoo Community Association (OCA)",
"license": "AGPL-3",
"website": "https://github.com/OCA/purchase-workflow",
"depends": ["purchase_stock"],
"data": [
"data/work_acceptance_sequence.xml",
"security/ir.model.access.csv",
"security/security.xml",
"views/account_move_views.xml",
"views/purchase_views.xml",
"views/res_config_settings_views.xml",
"views/stock_picking_views.xml",
"views/stock_picking_type_views.xml",
"views/work_acceptance_views.xml",
"wizard/select_work_acceptance_wizard_views.xml",
"wizard/work_accepted_date_wizard.xml",
],
"maintainers": ["ps-tubtim"],
"installable": True,
"development_status": "Alpha",
}
| 35.892857
| 1,005
|
15,491
|
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).
import ast
from odoo import fields
from odoo.exceptions import UserError, ValidationError
from odoo.tests.common import Form, TransactionCase
class TestPurchaseWorkAcceptance(TransactionCase):
def setUp(self):
super().setUp()
self.service_product = self.env.ref("product.product_product_1")
self.service_product.purchase_method = "purchase"
self.product_product = self.env.ref("product.product_product_6")
self.res_partner = self.env.ref("base.res_partner_3")
self.employee = self.env.ref("base.user_demo")
self.main_company = self.env.ref("base.main_company")
self.date_now = fields.Datetime.now()
# Enable and Config WA
self.env["res.config.settings"].create(
{"group_enable_wa_on_po": True}
).execute()
self.picking_type_return = self.env["stock.picking.type"].search(
[
("code", "=", "incoming"),
("return_picking_type_id", "=", False),
("company_id", "=", self.main_company.id),
],
limit=1,
)
def _create_purchase_order(self, qty, product):
purchase_order = self.env["purchase.order"].create(
{
"partner_id": self.res_partner.id,
"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": qty,
},
)
],
}
)
return purchase_order
def _create_multi_purchase_order(self, qty, multi):
purchase_order = self.env["purchase.order"].create(
{
"partner_id": self.res_partner.id,
"order_line": [
(
0,
0,
{
"product_id": self.product_product.id,
"product_uom": self.product_product.uom_id.id,
"name": self.product_product.name,
"price_unit": self.product_product.standard_price,
"date_planned": self.date_now,
"product_qty": qty,
},
)
for x in range(multi)
],
}
)
return purchase_order
def _create_work_acceptance(self, qty, po=False):
work_acceptance = self.env["work.acceptance"].create(
{
"purchase_id": po and po.id or False,
"partner_id": self.res_partner.id,
"responsible_id": self.employee.id,
"date_due": self.date_now,
"date_receive": self.date_now,
"company_id": self.main_company.id,
"wa_line_ids": [
(
0,
0,
{
"purchase_line_id": po and po.order_line[0].id or False,
"product_id": po
and po.order_line[0].product_id.id
or self.service_product.id,
"name": po
and po.order_line[0].name
or self.service_product.name,
"price_unit": po
and po.order_line[0].price_unit
or self.service_product.standard_price,
"product_uom": po
and po.order_line[0].product_uom.id
or self.service_product.uom_id.id,
"product_qty": qty,
},
)
],
}
)
return work_acceptance
def _create_multi_work_acceptance(self, qty, purchase_order, multi):
work_acceptance = self.env["work.acceptance"].create(
{
"purchase_id": purchase_order.id,
"partner_id": self.res_partner.id,
"responsible_id": self.employee.id,
"date_due": self.date_now,
"date_receive": self.date_now,
"company_id": self.main_company.id,
"wa_line_ids": [
(
0,
0,
{
"purchase_line_id": purchase_order.order_line[x].id,
"product_id": purchase_order.order_line[x].product_id.id,
"name": purchase_order.order_line[x].name,
"price_unit": purchase_order.order_line[x].price_unit,
"product_uom": purchase_order.order_line[x].product_uom.id,
"product_qty": qty,
},
)
for x in range(multi)
],
}
)
return work_acceptance
def test_00_wa_button(self):
qty = 3.0
work_acceptance = self._create_work_acceptance(qty)
work_acceptance.button_accept()
self.assertEqual(work_acceptance.state, "accept")
work_acceptance.button_cancel()
self.assertEqual(work_acceptance.state, "cancel")
work_acceptance.button_draft()
self.assertEqual(work_acceptance.state, "draft")
# Test open wizard
wizard = self.env.ref("purchase_work_acceptance.view_work_accepted_date_wizard")
res = work_acceptance.with_context(manual_date_accept=True).button_accept()
self.assertEqual(res["res_model"], "work.accepted.date.wizard")
self.assertEqual(res["view_id"], wizard.id)
ctx = {
"active_ids": [work_acceptance.id],
"active_id": work_acceptance.id,
"active_model": work_acceptance._name,
}
WorkAcceptanceWizard = self.env["work.accepted.date.wizard"]
with Form(WorkAcceptanceWizard.with_context(**ctx)) as f:
f.date_accept = self.date_now
wa_wizard = f.save()
wa_wizard.button_accept()
def test_01_action_view_wa(self):
# Create Purchase Order
qty = 42.0
purchase_order = self._create_purchase_order(qty, self.product_product)
purchase_order.button_confirm()
self.assertEqual(purchase_order.state, "purchase")
res = purchase_order.with_context(create_wa=True).action_view_wa()
ctx = res.get("context")
work_acceptance = Form(self.env["work.acceptance"].with_context(**ctx))
self.assertEqual(work_acceptance.state, "draft")
# Open with 1 WA
work_acceptance1 = self._create_work_acceptance(1, purchase_order)
res = purchase_order.action_view_wa()
self.assertEqual(res["res_id"], work_acceptance1.id)
work_acceptance1.button_accept()
purchase_order._compute_wa_accepted()
# Open with 2 WA
work_acceptance2 = self._create_work_acceptance(2, purchase_order)
purchase_order._compute_wa_ids()
res = purchase_order.action_view_wa()
res_domain = ast.literal_eval(res["domain"])
wa_ids = (work_acceptance1 + work_acceptance2).ids
self.assertEqual(res_domain[0][2], wa_ids)
def test_02_flow_product(self):
# Create Purchase Order
qty = 42.0
purchase_order = self._create_purchase_order(qty, self.product_product)
purchase_order.button_confirm()
self.assertEqual(purchase_order.state, "purchase")
self.assertEqual(purchase_order.incoming_picking_count, 1)
# Create Work Acceptance
work_acceptance = self._create_work_acceptance(qty, purchase_order)
work_acceptance.button_accept()
self.assertEqual(work_acceptance.state, "accept")
self.assertEqual(purchase_order.wa_count, 1)
# 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 = work_acceptance
p.save()
with self.assertRaises(ValidationError):
picking.move_ids_without_package[0].quantity_done = 30.0
picking.button_validate()
picking.move_ids_without_package[0].quantity_done = 42.0
picking.button_validate()
# Can't set to draft wa when you validate picking
with self.assertRaises(UserError):
work_acceptance.button_draft()
# Create Vendor Bill
f = Form(self.env["account.move"].with_context(default_move_type="in_invoice"))
f.partner_id = purchase_order.partner_id
f.purchase_id = purchase_order
# f.wa_id = work_acceptance
invoice = f.save()
invoice.wa_id = work_acceptance
invoice_line = invoice.invoice_line_ids[0]
with self.assertRaises(ValidationError):
invoice_line.with_context(check_move_validity=False).write(
{"quantity": 6.0}
)
invoice.action_post() # Warn when quantity not equal to WA
invoice_line.quantity = qty
self.assertEqual(invoice.state, "draft")
invoice.invoice_date = invoice.date
invoice.action_post()
self.assertEqual(invoice.state, "posted")
def test_03_flow_service(self):
qty = 30.0
# Create Purchase Order
purchase_order = self._create_purchase_order(qty, self.service_product)
purchase_order.button_confirm()
self.assertEqual(purchase_order.state, "purchase")
# Create Work Acceptance
work_acceptance = self._create_work_acceptance(qty, purchase_order)
work_acceptance.button_accept()
self.assertEqual(work_acceptance.state, "accept")
self.assertEqual(purchase_order.wa_count, 1)
# Create Vendor Bill
f = Form(self.env["account.move"].with_context(default_move_type="in_invoice"))
f.partner_id = purchase_order.partner_id
f.purchase_id = purchase_order
# f.wa_id = work_acceptance
invoice = f.save()
invoice.wa_id = work_acceptance
self.assertEqual(invoice.state, "draft")
invoice.invoice_date = invoice.date
invoice.action_post()
self.assertEqual(invoice.state, "posted")
def test_04_enable_config_flow(self):
qty = 2.0
# Create Purchase Order
purchase_order = self._create_purchase_order(qty, self.service_product)
purchase_order.button_confirm()
# Create Work Acceptance
work_acceptance = self._create_work_acceptance(qty, purchase_order)
work_acceptance.button_accept()
self.env["res.config.settings"].create(
{"group_enable_wa_on_invoice": True}
).execute()
res = purchase_order.with_context(create_bill=True).action_create_invoice()
self.assertEqual(res.get("res_model"), "select.work.acceptance.wizard")
wizard = self.env[res.get("res_model")].create({"wa_id": work_acceptance.id})
wizard = wizard.with_context(active_id=purchase_order.id)
self.assertEqual(wizard.wa_ids, work_acceptance)
res = wizard.button_create_vendor_bill()
invoice = self.env["account.move"].browse(res["res_id"])
self.assertEqual(sum(invoice.invoice_line_ids.mapped("quantity")), qty)
# Test create wa is used
with self.assertRaises(ValidationError):
wizard.button_create_vendor_bill()
invoice = self.env["account.move"].browse(res["res_id"])
self.assertEqual(sum(invoice.invoice_line_ids.mapped("quantity")), qty)
# Create Return with required WA
self.env["res.config.settings"].create(
{"group_enforce_wa_on_in": True}
).execute()
picking = self.env["stock.picking"].create(
{
"picking_type_id": self.picking_type_return.id,
"location_id": 4,
"location_dest_id": 8,
}
)
# Set bypass reutrn not required wa
self.assertTrue(picking.require_wa)
self.picking_type_return.bypass_wa = True
picking._compute_require_wa()
self.assertFalse(picking.require_wa)
def test_05_create_multi_lines(self):
qty = 5.0
# Create Purchase Order
purchase_order = self._create_multi_purchase_order(qty, multi=2)
purchase_order.button_confirm()
# Create Work Acceptance
work_acceptance = work_acceptance = self._create_multi_work_acceptance(
qty, purchase_order, multi=2
)
work_acceptance.button_accept()
# Received Products
picking = purchase_order.picking_ids[0]
self.assertEqual(len(picking.move_ids_without_package), 2)
with Form(picking) as p:
p.wa_id = work_acceptance
p.save()
picking.button_validate()
# Create Vendor Bill
self.env["res.config.settings"].create(
{"group_enable_wa_on_invoice": True}
).execute()
res = purchase_order.with_context(create_bill=True).action_create_invoice()
self.assertEqual(res.get("res_model"), "select.work.acceptance.wizard")
wizard = self.env[res.get("res_model")].create({"wa_id": work_acceptance.id})
res = wizard.with_context(
active_id=purchase_order.id
).button_create_vendor_bill()
invoice = self.env["account.move"].browse(res["res_id"])
self.assertEqual(sum(invoice.invoice_line_ids.mapped("quantity")), qty * 2)
def test_06_check_qty_accepted(self):
qty_po = 20.0
qty_wa = 12.0
purchase_order = self._create_purchase_order(qty_po, self.product_product)
purchase_order.button_confirm()
work_acceptance = self._create_work_acceptance(qty_wa, po=purchase_order)
work_acceptance.button_accept()
self.assertEqual(purchase_order.order_line[0].qty_accepted, 12.0)
self.assertEqual(purchase_order.order_line[0].qty_to_accept, 8.0)
def test_07_hide_wa_button(self):
qty_po = 20.0
purchase_order = self._create_purchase_order(qty_po, self.product_product)
purchase_order.button_confirm()
work_acceptance = self._create_work_acceptance(qty=12, po=purchase_order)
work_acceptance.button_accept()
purchase_order._compute_wa_accepted()
self.assertEqual(purchase_order.wa_accepted, False)
work_acceptance = self._create_work_acceptance(qty=8, po=purchase_order)
work_acceptance.button_accept()
purchase_order._compute_wa_accepted()
self.assertEqual(purchase_order.wa_accepted, True)
# Search wa accepted
purchase_order._search_wa_accepted("=", True)
# Search with not `=` or `!=`
with self.assertRaises(UserError):
purchase_order._search_wa_accepted(">", True)
| 43.150418
| 15,491
|
678
|
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 fields, models
class SelectWorkAcceptanceWizard(models.TransientModel):
_name = "work.accepted.date.wizard"
_description = "Select work accepted date"
date_accept = fields.Datetime(
string="Accepted Date",
required=True,
)
def button_accept(self):
active_id = self.env.context.get("active_id")
work_acceptance = self.env["work.acceptance"].browse(active_id)
work_acceptance.with_context(manual_date_accept=False).button_accept(
force=self.date_accept
)
| 32.285714
| 678
|
1,757
|
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 _, api, fields, models
from odoo.exceptions import ValidationError
class SelectWorkAcceptanceWizard(models.TransientModel):
_name = "select.work.acceptance.wizard"
_description = "Select Work Acceptance Wizard"
require_wa = fields.Boolean(default=lambda self: self._get_require_wa())
wa_id = fields.Many2one(
comodel_name="work.acceptance",
string="Work Acceptance",
domain="[('id', 'in', wa_ids)]",
)
wa_ids = fields.Many2many(
comodel_name="work.acceptance",
compute="_compute_wa_ids",
)
def _get_require_wa(self):
return self.env.user.has_group(
"purchase_work_acceptance.group_enforce_wa_on_invoice"
)
@api.depends("require_wa")
def _compute_wa_ids(self):
self.ensure_one()
self.wa_ids = self.env["work.acceptance"]._get_valid_wa(
"invoice", self.env.context.get("active_id")
)
def _get_purchase_order_with_context(self, order_id):
return (
self.env["purchase.order"]
.browse(order_id)
.with_context(create_bill=False, wa_id=self.wa_id.id)
)
def button_create_vendor_bill(self):
self.ensure_one()
order_id = self._context.get("active_id")
wa = self.env["work.acceptance"]._get_valid_wa("invoice", order_id)
if self.wa_id not in wa:
raise ValidationError(
_("%s was already used by some bill") % self.wa_id.name
)
order = self._get_purchase_order_with_context(order_id)
return order.sudo().action_create_invoice()
| 34.45098
| 1,757
|
2,973
|
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 import _, api, fields, models
from odoo.exceptions import ValidationError
class AccountMove(models.Model):
_inherit = "account.move"
require_wa = fields.Boolean(compute="_compute_require_wa")
wa_id = fields.Many2one(
comodel_name="work.acceptance",
string="WA Reference",
copy=False,
readonly=True,
domain=lambda self: [
("state", "=", "accept"),
("purchase_id", "=", self._context.get("active_id")),
],
help="To control quantity and unit price of the vendor bill, to be "
"according to the quantity and unit price of the work acceptance.",
)
def _compute_require_wa(self):
for rec in self:
enforce_wa = self.env.user.has_group(
"purchase_work_acceptance.group_enforce_wa_on_invoice"
)
rec.require_wa = self.wa_id and enforce_wa
def action_post(self):
for rec in self:
if rec.wa_id:
wa_line = {}
for line in rec.wa_id.wa_line_ids:
qty = line.product_uom._compute_quantity(
line.product_qty, line.product_id.uom_id
)
if qty > 0.0:
if line.product_id.id in wa_line.keys():
qty_old = wa_line[line.product_id.id]
wa_line[line.product_id.id] = qty_old + qty
else:
wa_line[line.product_id.id] = qty
invoice_line = {}
for line in rec.invoice_line_ids:
qty = line.product_uom_id._compute_quantity(
line.quantity, line.product_id.uom_id
)
if qty > 0.0:
if line.product_id.id in invoice_line.keys():
qty_old = invoice_line[line.product_id.id]
invoice_line[line.product_id.id] = qty_old + qty
else:
invoice_line[line.product_id.id] = qty
if wa_line != invoice_line:
raise ValidationError(
_(
"You cannot validate a bill if Quantity not equal "
"accepted quantity"
)
)
return super().action_post()
@api.model
def create(self, vals):
if self.env.context.get("wa_id"):
# When use WA, filter for line with qty != 0, good for deposit too.
lines = vals.get("invoice_line_ids", [])
lines = filter(lambda l: len(l) == 3 and l[2].get("quantity") != 0, lines)
vals["invoice_line_ids"] = list(lines)
return super().create(vals)
| 40.726027
| 2,973
|
6,883
|
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 import _, api, fields, models
from odoo.exceptions import UserError
class PurchaseOrder(models.Model):
_inherit = "purchase.order"
wa_count = fields.Integer(compute="_compute_wa_ids", string="WA count", default=0)
wa_ids = fields.One2many(
comodel_name="work.acceptance",
compute="_compute_wa_ids",
string="Work Acceptances",
)
wa_line_ids = fields.One2many(
comodel_name="work.acceptance.line",
inverse_name="purchase_line_id",
string="WA Lines",
readonly=True,
)
wa_accepted = fields.Boolean(
string="WA Accepted",
compute="_compute_wa_accepted",
search="_search_wa_accepted",
)
def _compute_wa_ids(self):
for order in self:
order.wa_ids = (
order.mapped("order_line").mapped("wa_line_ids").mapped("wa_id")
)
order.wa_count = len(order.wa_ids)
def action_view_wa(self):
self.ensure_one()
act = self.env.ref("purchase_work_acceptance.action_work_acceptance")
result = act.sudo().read()[0]
create_wa = self.env.context.get("create_wa", False)
result["context"] = {
"default_purchase_id": self.id,
"default_partner_id": self.partner_id.id,
"default_company_id": self.company_id.id,
"default_currency_id": self.currency_id.id,
"default_date_due": self.date_planned,
"default_wa_line_ids": [
(
0,
0,
{
"purchase_line_id": line.id,
"name": line.name,
"product_uom": line.product_uom.id,
"product_id": line.product_id.id,
"price_unit": line.price_unit,
"product_qty": line._get_product_qty(),
},
)
for line in self.order_line
if line._get_product_qty() != 0
],
}
if len(self.wa_ids) > 1 and not create_wa:
result["domain"] = "[('id', 'in', " + str(self.wa_ids.ids) + ")]"
else:
res = self.env.ref(
"purchase_work_acceptance.view_work_acceptance_form", False
)
result["views"] = [(res and res.id or False, "form")]
if not create_wa:
result["res_id"] = self.wa_ids.id or False
return result
def action_create_invoice(self):
enable_wa = self.env.user.has_group(
"purchase_work_acceptance.group_enable_wa_on_invoice"
)
ctx = self.env.context.copy()
if enable_wa and ctx.get("create_bill"):
wizard = self.env.ref(
"purchase_work_acceptance.view_select_work_acceptance_wizard"
)
return {
"name": _("Select Work Acceptance"),
"type": "ir.actions.act_window",
"view_mode": "form",
"res_model": "select.work.acceptance.wizard",
"views": [(wizard.id, "form")],
"view_id": wizard.id,
"target": "new",
}
res = super().action_create_invoice()
# Set 'ref' to WA
if (
ctx.get("wa_id")
and res.get("res_model") == "account.move"
and res.get("res_id")
):
wa = self.env["work.acceptance"].browse(ctx["wa_id"])
invoice = self.env["account.move"].browse(res["res_id"])
# invoice.ref, adding "/ WA001"
invoice.ref = (
"{} / {}".format(invoice.ref, wa.name) if invoice.ref else wa.name
)
# invoice.payment_reference, adding "/ <WA's invoice_ref>"
invoice.payment_reference = (
"{} / {}".format(invoice.payment_reference, wa.invoice_ref)
if invoice.payment_reference
else wa.invoice_ref
)
return res
def _compute_wa_accepted(self):
for order in self:
lines = order.order_line.filtered(
lambda l: l.product_qty > 0 and l.qty_to_accept > 0
)
order.wa_accepted = not any(lines)
@api.model
def _search_wa_accepted(self, operator, value):
if operator not in ["=", "!="] or not isinstance(value, bool):
raise UserError(_("Operation not supported"))
recs = self.search([]).filtered(lambda l: l.wa_accepted is value)
return [("id", "in", recs.ids)]
def _prepare_invoice(self):
invoice_vals = super()._prepare_invoice()
invoice_vals["wa_id"] = self.env.context.get("wa_id")
return invoice_vals
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
wa_line_ids = fields.One2many(
comodel_name="work.acceptance.line",
inverse_name="purchase_line_id",
string="WA Lines",
readonly=True,
)
qty_accepted = fields.Float(
compute="_compute_qty_accepted",
string="Accepted Qty.",
store=True,
readonly=True,
digits="Product Unit of Measure",
)
qty_to_accept = fields.Float(
compute="_compute_qty_accepted",
string="To Accept Qty.",
store=True,
readonly=True,
digits="Product Unit of Measure",
)
def _get_product_qty(self):
return self.product_qty - sum(
wa_line.product_qty
for wa_line in self.wa_line_ids
if wa_line.wa_id.state != "cancel"
)
def _prepare_account_move_line(self, move=False):
res = super()._prepare_account_move_line(move=move)
wa_id = self.env.context.get("wa_id")
if wa_id:
wa_line = self.wa_line_ids.filtered(lambda l: l.wa_id.id == wa_id)
res["quantity"] = wa_line.product_qty
res["product_uom_id"] = wa_line.product_uom
return res
@api.depends(
"wa_line_ids.wa_id.state",
"wa_line_ids.product_qty",
"product_qty",
"product_uom_qty",
"order_id.state",
)
def _compute_qty_accepted(self):
for line in self:
# compute qty_accepted
qty_accepted = 0.0
for wa_line in line.wa_line_ids.filtered(
lambda l: l.wa_id.state == "accept"
):
qty_accepted += wa_line.product_uom._compute_quantity(
wa_line.product_qty, line.product_uom, round=False
)
line.qty_accepted = qty_accepted
# compute qty_to_accept
line.qty_to_accept = line.product_uom_qty - qty_accepted
| 35.479381
| 6,883
|
4,314
|
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 import _, api, fields, models
from odoo.exceptions import ValidationError
class Picking(models.Model):
_inherit = "stock.picking"
require_wa = fields.Boolean(compute="_compute_require_wa")
wa_id = fields.Many2one(
comodel_name="work.acceptance",
string="WA Reference",
domain="[('id', 'in', wa_ids)]",
copy=False,
)
wa_ids = fields.Many2many(
comodel_name="work.acceptance",
compute="_compute_wa_ids",
)
@api.depends("picking_type_id")
def _compute_require_wa(self):
for rec in self:
if rec.picking_type_id.bypass_wa:
rec.require_wa = False
elif rec.picking_type_code == "incoming":
rec.require_wa = self.env.user.has_group(
"purchase_work_acceptance.group_enforce_wa_on_in"
)
else:
rec.require_wa = False
@api.depends("require_wa")
def _compute_wa_ids(self):
for picking in self:
picking.wa_ids = (
self.env["work.acceptance"]
.sudo()
._get_valid_wa("picking", picking.purchase_id.id)
)
def button_validate(self):
for picking in self:
if picking.wa_id:
order_id = self._context.get("active_id")
wa = (
self.env["work.acceptance"]
.sudo()
._get_valid_wa("picking", order_id)
)
wa += picking.wa_id
if picking.wa_id not in wa:
raise ValidationError(
_("%s was used in some picking.") % picking.wa_id.name
)
wa_line = {}
for line in picking.wa_id.wa_line_ids:
qty = line.product_uom._compute_quantity(
line.product_qty, line.product_id.uom_id
)
if qty > 0.0 and line.product_id.type in ["product", "consu"]:
wa_line[line.product_id.id] = (
wa_line.get(line.product_id.id, 0) + qty
)
move_line = {}
for move in picking.move_ids_without_package:
qty = move.product_uom._compute_quantity(
move.quantity_done, move.product_id.uom_id
)
if qty > 0.0:
move_line[move.product_id.id] = (
move_line.get(move.product_id.id, 0) + qty
)
if wa_line != move_line:
raise ValidationError(
_(
"You cannot validate a transfer if done"
" quantity not equal accepted quantity"
)
)
return super(Picking, self).button_validate()
@api.onchange("wa_id")
def _onchange_wa_id(self):
if self.wa_id:
wa_line = {}
for line in self.wa_id.wa_line_ids:
qty = line.product_uom._compute_quantity(
line.product_qty, line.product_id.uom_id
)
if line.product_id.id in wa_line:
wa_line[line.product_id.id] += qty
else:
wa_line[line.product_id.id] = qty
for move_line in self.move_line_ids_without_package:
if move_line.product_id.id in wa_line:
qty = wa_line[move_line.product_id.id]
if move_line.product_uom_qty < qty:
move_line._origin.qty_done = move_line.product_uom_qty
wa_line[line.product_id.id] = qty - move_line.product_uom_qty
else:
move_line._origin.qty_done = qty
class StockPickingType(models.Model):
_inherit = "stock.picking.type"
bypass_wa = fields.Boolean(
string="WA not required",
help="When 'Enforce WA on Goods Receipt' is set, this option type can by pass it",
)
| 38.176991
| 4,314
|
1,101
|
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 import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
group_enable_wa_on_po = fields.Boolean(
string="Enable WA on Purchase Order",
implied_group="purchase_work_acceptance.group_enable_wa_on_po",
)
group_enable_wa_on_in = fields.Boolean(
string="Enable WA on Goods Receipt",
implied_group="purchase_work_acceptance.group_enable_wa_on_in",
)
group_enforce_wa_on_in = fields.Boolean(
string="Enforce WA on Goods Receipt",
implied_group="purchase_work_acceptance.group_enforce_wa_on_in",
)
group_enable_wa_on_invoice = fields.Boolean(
string="Enable WA on Vendor Bill",
implied_group="purchase_work_acceptance.group_enable_wa_on_invoice",
)
group_enforce_wa_on_invoice = fields.Boolean(
string="Enforce WA on Vendor Bill",
implied_group="purchase_work_acceptance.group_enforce_wa_on_invoice",
)
| 37.965517
| 1,101
|
7,299
|
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 import _, api, fields, models
from odoo.exceptions import UserError
class WorkAcceptance(models.Model):
_name = "work.acceptance"
_inherit = ["mail.thread", "mail.activity.mixin", "portal.mixin"]
_description = "Work Acceptance"
_order = "id desc"
name = fields.Char(required=True, index=True, copy=False, default="New")
date_due = fields.Datetime(
string="Due Date",
required=True,
readonly=True,
states={"draft": [("readonly", False)]},
)
date_receive = fields.Datetime(
string="Received Date",
default=fields.Datetime.now,
required=True,
readonly=True,
states={"draft": [("readonly", False)]},
)
date_accept = fields.Datetime(string="Accepted Date", readonly=True)
invoice_ref = fields.Char(string="Invoice Reference", copy=False)
partner_id = fields.Many2one(
comodel_name="res.partner",
string="Vendor",
required=True,
change_default=True,
tracking=True,
readonly=True,
states={"draft": [("readonly", False)]},
)
responsible_id = fields.Many2one(
comodel_name="res.users",
string="Responsible Person",
default=lambda self: self.env.user,
required=True,
change_default=True,
tracking=True,
readonly=True,
states={"draft": [("readonly", False)]},
)
currency_id = fields.Many2one(
comodel_name="res.currency",
string="Currency",
default=lambda self: self.env.company.currency_id,
required=True,
readonly=True,
)
state = fields.Selection(
[("draft", "Draft"), ("accept", "Accepted"), ("cancel", "Cancelled")],
string="Status",
readonly=True,
index=True,
copy=False,
default="draft",
tracking=True,
)
wa_line_ids = fields.One2many(
comodel_name="work.acceptance.line",
inverse_name="wa_id",
string="Work Acceptance Lines",
)
notes = fields.Text()
product_id = fields.Many2one(
comodel_name="product.product",
related="wa_line_ids.product_id",
string="Product",
readonly=False,
)
user_id = fields.Many2one(
comodel_name="res.users",
string="Work Acceptance Representative",
default=lambda self: self.env.user,
index=True,
tracking=True,
)
company_id = fields.Many2one(
comodel_name="res.company",
string="Company",
default=lambda self: self.env.company,
required=True,
index=True,
readonly=True,
states={"draft": [("readonly", False)]},
)
purchase_id = fields.Many2one(
comodel_name="purchase.order", string="Purchase Order", readonly=True
)
@api.model
def create(self, vals):
if vals.get("name", "New") == "New":
vals["name"] = (
self.env["ir.sequence"].next_by_code("work.acceptance") or "/"
)
return super(WorkAcceptance, self).create(vals)
def button_accept(self, force=False):
if self.env.context.get("manual_date_accept"):
wizard = self.env.ref(
"purchase_work_acceptance.view_work_accepted_date_wizard"
)
return {
"name": _("Select Accept Date"),
"type": "ir.actions.act_window",
"view_mode": "form",
"res_model": "work.accepted.date.wizard",
"views": [(wizard.id, "form")],
"view_id": wizard.id,
"target": "new",
}
self._unlink_zero_quantity()
date_accept = force or fields.Datetime.now()
self.write({"state": "accept", "date_accept": date_accept})
def button_draft(self):
picking_obj = self.env["stock.picking"]
wa_ids = picking_obj.search([("wa_id", "in", self.ids)])
if wa_ids:
raise UserError(
_(
"Unable set to draft this work acceptance. "
"You must first cancel the related receipts."
)
)
self.write({"state": "draft"})
def button_cancel(self):
self.write({"state": "cancel"})
def _unlink_zero_quantity(self):
wa_line_zero_quantity = self.wa_line_ids.filtered(
lambda l: l.product_qty == 0.0
)
wa_line_zero_quantity.unlink()
def _get_valid_wa(self, doctype, order_id):
"""Get unused WA when validate invoice or picking"""
order = self.env["purchase.order"].browse(order_id)
all_wa = self.env["work.acceptance"].search(
[
("state", "=", "accept"),
("purchase_id", "=", order.id),
]
)
if doctype == "invoice":
used_wa = order.invoice_ids.filtered(
lambda l: l.state in ("draft", "posted")
).mapped("wa_id")
return all_wa - used_wa
if doctype == "picking":
used_wa = order.picking_ids.mapped("wa_id")
return all_wa - used_wa
return all_wa
class WorkAcceptanceLine(models.Model):
_name = "work.acceptance.line"
_description = "Work Acceptance Line"
_order = "id"
name = fields.Text(string="Description", required=True)
product_qty = fields.Float(
string="Quantity", required=True, digits="Product Unit of Measure"
)
product_id = fields.Many2one(
comodel_name="product.product", string="Product", required=True
)
product_uom = fields.Many2one(
comodel_name="uom.uom", string="Product Unit of Measure", required=True
)
price_unit = fields.Float(string="Unit Price", required=True)
price_subtotal = fields.Monetary(compute="_compute_amount", string="Subtotal")
wa_id = fields.Many2one(
comodel_name="work.acceptance",
string="WA Reference",
index=True,
required=True,
ondelete="cascade",
)
partner_id = fields.Many2one(
comodel_name="res.partner",
related="wa_id.partner_id",
string="Partner",
readonly=True,
)
responsible_id = fields.Many2one(
comodel_name="res.users",
related="wa_id.responsible_id",
string="Responsible Person",
readonly=True,
)
currency_id = fields.Many2one(
related="wa_id.currency_id", string="Currency", readonly=True
)
date_due = fields.Datetime(
related="wa_id.date_due", string="Due Date", readonly=True
)
date_receive = fields.Datetime(
related="wa_id.date_receive", string="Received Date", readonly=True
)
date_accept = fields.Datetime(
related="wa_id.date_accept", string="Accepted Date", readonly=True
)
purchase_line_id = fields.Many2one(
comodel_name="purchase.order.line",
string="Purchase Order Line",
ondelete="set null",
index=True,
readonly=False,
)
def _compute_amount(self):
for line in self:
line.price_subtotal = line.product_qty * line.price_unit
| 32.878378
| 7,299
|
689
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Akretion (<http://www.akretion.com>)
# Copyright 2020 Ecosoft (<http://ecosoft.co.th>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Purchase Sub State",
"version": "15.0.1.0.0",
"category": "Tools",
"author": "Akretion,Ecosoft,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/purchase-workflow",
"license": "AGPL-3",
"depends": ["base_substate", "purchase"],
"data": [
"views/purchase_views.xml",
"data/purchase_substate_mail_template_data.xml",
"data/purchase_substate_data.xml",
],
"demo": ["data/purchase_substate_demo.xml"],
"installable": True,
}
| 34.45
| 689
|
2,757
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Akretion Mourad EL HADJ MIMOUNE
# Copyright 2020 Ecosoft (<http://ecosoft.co.th>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields
from odoo.exceptions import ValidationError
from odoo.tests.common import TransactionCase
class TestBaseSubstate(TransactionCase):
def setUp(self):
super(TestBaseSubstate, self).setUp()
self.substate_test_purchase = self.env["purchase.order"]
self.substate_test_purchase_line = self.env["purchase.order.line"]
self.substate_under_nego = self.env.ref(
"purchase_substate.base_substate_under_nego"
)
self.substate_won = self.env.ref("purchase_substate.base_substate_won")
self.substate_wait_docs = self.env.ref(
"purchase_substate.base_substate_wait_docs"
)
self.substate_valid_docs = self.env.ref(
"purchase_substate.base_substate_valid_docs"
)
self.substate_in_receipt = self.env.ref(
"purchase_substate.base_substate_in_receipt"
)
self.product = self.env["product.product"].create({"name": "Test"})
def test_purchase_order_substate(self):
partner = self.env.ref("base.res_partner_1")
po_test1 = self.substate_test_purchase.create(
{
"name": "Test base substate to basic purchase",
"partner_id": partner.id,
"order_line": [
(
0,
0,
{
"name": "line test",
"product_id": self.product.id,
"product_uom": self.product.uom_po_id.id,
"price_unit": 120.0,
"product_qty": 1.5,
"date_planned": fields.Date.today(),
},
)
],
}
)
self.assertTrue(po_test1.state == "draft")
self.assertTrue(po_test1.substate_id == self.substate_under_nego)
# Block substate not corresponding to draft state
with self.assertRaises(ValidationError):
po_test1.substate_id = self.substate_valid_docs
# Test that validation of purchase order change substate_id
po_test1.button_confirm()
self.assertTrue(po_test1.state == "purchase")
self.assertTrue(po_test1.substate_id == self.substate_valid_docs)
# Test that substate_id is set to false if
# there is not substate corresponding to state
po_test1.button_cancel()
self.assertTrue(po_test1.state == "cancel")
self.assertTrue(not po_test1.substate_id)
| 40.544118
| 2,757
|
546
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Akretion
# Copyright 2020 Ecosoft (<http://ecosoft.co.th>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class BaseSubstateType(models.Model):
_inherit = "base.substate.type"
model = fields.Selection(
selection_add=[("purchase.order", "Purchase order")],
ondelete={"purchase.order": "cascade"},
)
class PurchaseOrder(models.Model):
_inherit = ["purchase.order", "base.substate.mixin"]
_name = "purchase.order"
_state_field = "state"
| 27.3
| 546
|
574
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - David Vidal
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Purchase Stock Return Request",
"version": "15.0.1.0.0",
"category": "Stock",
"website": "https://github.com/OCA/purchase-workflow",
"author": "Tecnativa, " "Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["purchase", "stock_return_request"],
"data": [
"views/purchase_return_request_views.xml",
"report/stock_return_report.xml",
],
}
| 33.764706
| 574
|
4,885
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - David Vidal
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.addons.stock_return_request.tests.test_stock_return_request_common import (
StockReturnRequestCase,
)
class PurchaseReturnRequestCase(StockReturnRequestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
# TODO: Declare new supplier
cls.partner_supplier_2 = cls.env["res.partner"].create(
{
"name": "Mr. Purchase",
"property_stock_supplier": cls.supplier_loc.id,
"property_stock_customer": cls.customer_loc.id,
}
)
# TODO: Declare two purchase orders and receive their items
cls.po_1 = cls.env["purchase.order"].create(
{
"partner_id": cls.partner_supplier_2.id,
"picking_type_id": cls.wh1.in_type_id.id,
"order_line": [
(
0,
False,
{
"product_id": cls.prod_3.id,
"name": cls.prod_3.name,
"product_qty": 50.0,
"price_unit": 10.0,
"product_uom": cls.prod_3.uom_id.id,
"date_planned": "2019-10-01",
},
),
],
}
)
cls.po_2 = cls.po_1.copy()
cls.purchase_orders = cls.po_1 | cls.po_2
# Confirm all the purchase orders
for order in cls.purchase_orders:
order.button_confirm()
# Receive products. For each picking:
# 10 units of TSTPROD3LOT0001 -> 20 units +90 already existing
# 40 units of TSTPROD3LOT0002 -> 80 units +10 already existing
for picking in cls.purchase_orders.mapped("picking_ids"):
for ml in picking.move_line_ids:
ml.write({"lot_id": cls.prod_3_lot1.id, "qty_done": 10.0})
ml.copy({"lot_id": cls.prod_3_lot2.id, "qty_done": 40.0})
picking._action_done()
def test_01_return_purchase_stock_to_supplier(self):
"""Return stock to supplier and the corresponding
purchases are ready for refund"""
self.return_request_supplier.write(
{
"partner_id": self.partner_supplier_2.id,
"to_refund": True,
"line_ids": [
(
0,
0,
{
"product_id": self.prod_3.id,
"lot_id": self.prod_3_lot1.id,
"quantity": 12.0,
},
),
(
0,
0,
{
"product_id": self.prod_3.id,
"lot_id": self.prod_3_lot2.id,
"quantity": 22.0,
},
),
],
}
)
self.return_request_supplier.onchange_locations()
self.return_request_supplier.action_confirm()
purchase_orders = self.return_request_supplier.purchase_order_ids
pickings = self.return_request_supplier.returned_picking_ids
moves = self.return_request_supplier.returned_picking_ids.mapped("move_lines")
# For lot TSTPROD3LOT0001 we'll be returning:
# ==> 2 units from PO01
# ==> 10 units from PO02
# For lot TSTPROD3LOT0002 we'll be returning:
# ==> 22 units from PO01
self.assertEqual(len(purchase_orders), 2)
self.assertEqual(len(pickings), 2)
# Two moves with two move lines each
self.assertEqual(len(moves), 2)
self.assertAlmostEqual(sum(moves.mapped("product_uom_qty")), 34.0)
# Process the return to validate all the pickings
self.return_request_supplier.action_validate()
self.assertTrue(
all([True if x == "done" else False for x in pickings.mapped("state")])
)
# For lot TSTPROD3LOT0001 we had 110 units
prod_3_qty_lot_1 = self.prod_3.with_context(
location=self.wh1.lot_stock_id.id, lot_id=self.prod_3_lot1.id
).qty_available
# For lot TSTPROD3LOT0002 we had 90 units
prod_3_qty_lot_2 = self.prod_3.with_context(
location=self.wh1.lot_stock_id.id, lot_id=self.prod_3_lot2.id
).qty_available
self.assertAlmostEqual(prod_3_qty_lot_1, 98.0)
self.assertAlmostEqual(prod_3_qty_lot_2, 68.0)
# There were 100 units in the purchase orders.
self.assertAlmostEqual(
sum(purchase_orders.mapped("order_line.qty_received")), 66.0
)
| 41.752137
| 4,885
|
3,355
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - David Vidal
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class StockReturnRequest(models.Model):
_inherit = "stock.return.request"
purchase_order_ids = fields.Many2many(
comodel_name="purchase.order",
string="Involved Purchases",
readonly=True,
copy=False,
)
def _prepare_move_default_values(self, line, qty, move):
"""Extend this method to add values to return move"""
vals = super()._prepare_move_default_values(line, qty, move)
vals.update(
{
"purchase_line_id": move.purchase_line_id.id,
"to_refund": line.request_id.to_refund,
}
)
return vals
def _action_confirm(self):
res = super()._action_confirm()
if self.state == "confirmed":
self.purchase_order_ids = self.returned_picking_ids.mapped("purchase_id")
return res
def action_view_purchases(self):
"""Display returned purchases"""
action = self.env.ref("purchase.purchase_form_action")
result = action.read()[0]
result["context"] = {}
purchases = self.mapped("purchase_order_ids")
if len(purchases) != 1:
result["domain"] = "[('id', 'in', %s)]" % (purchases.ids)
else:
res = self.env.ref("purchase.purchase_order_form", False)
result["views"] = [(res and res.id or False, "form")]
result["res_id"] = purchases.id
return result
@api.model
def _get_po_price_unit(self, move_line):
"""We take the price applied in the original"""
po_line = move_line.move_id and move_line.move_id.purchase_line_id
return po_line and po_line._get_stock_move_price_unit() or 0.0
@api.model
def _get_po_line_amount(self, move_line, qty=0):
"""Computes amounts to be shown in the report"""
po_line = move_line.move_id and move_line.move_id.purchase_line_id
to_refund = move_line.move_id and move_line.move_id.to_refund
if not po_line or not to_refund:
return {
"price_tax": 0,
"price_total": 0,
"price_subtotal": 0,
}
price_unit = self._get_po_price_unit(move_line)
taxes = po_line.taxes_id.compute_all(
price_unit,
po_line.order_id.currency_id,
qty,
product=po_line.product_id,
partner=po_line.order_id.partner_id,
)
return {
"price_tax": sum(t.get("amount", 0.0) for t in taxes.get("taxes", [])),
"price_total": taxes["total_included"],
"price_subtotal": taxes["total_excluded"],
}
@api.model
def _get_po_amount_all(self, move_lines, currency):
amount_untaxed = amount_tax = 0.0
for ml in move_lines.filtered("move_id.purchase_line_id"):
line_amount = self._get_po_line_amount(ml, ml.qty_done)
amount_untaxed += line_amount["price_subtotal"]
amount_tax += line_amount["price_tax"]
return {
"amount_untaxed": currency.round(amount_untaxed),
"amount_tax": currency.round(amount_tax),
"amount_total": amount_untaxed + amount_tax,
}
| 37.696629
| 3,355
|
735
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Ecosoft (http://ecosoft.co.th)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Purchase Reqeust Exception",
"summary": "Custom exceptions on purchase request",
"version": "15.0.1.0.0",
"category": "Generic Modules/Purchase",
"author": "Ecosoft, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/purchase-workflow",
"depends": ["purchase_request", "base_exception"],
"license": "AGPL-3",
"data": [
"security/ir.model.access.csv",
"data/purchase_request_exception_data.xml",
"wizard/purchase_request_exception_confirm_view.xml",
"views/purchase_request_view.xml",
],
"installable": True,
}
| 36.75
| 735
|
4,278
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Ecosoft (http://ecosoft.co.th)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from datetime import datetime
from odoo.tests.common import TransactionCase
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
class TestPurchaseRequestException(TransactionCase):
def setUp(self):
super(TestPurchaseRequestException, self).setUp()
# Useful models
self.PurchaseRequest = self.env["purchase.request"]
self.PurchaseRequestLine = self.env["purchase.request.line"]
self.request_user_id = self.env.ref("base.user_admin")
self.date_required = datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT)
self.purchase_request_exception_confirm = self.env[
"purchase.request.exception.confirm"
]
self.exception_noapprover = self.env.ref(
"purchase_request_exception.pr_excep_no_approver"
)
self.exception_qtycheck = self.env.ref(
"purchase_request_exception.prl_excep_qty_check"
)
self.pr_vals = {
"requested_by": self.request_user_id.id,
"line_ids": [
(
0,
0,
{
"name": "Pen",
"product_qty": 5.0,
"estimated_cost": 500.0,
"date_required": self.date_required,
},
),
(
0,
0,
{
"name": "Ink",
"product_qty": 5.0,
"estimated_cost": 250.0,
"date_required": self.date_required,
},
),
],
}
def test_purchase_request_exception(self):
self.exception_noapprover.active = True
self.exception_qtycheck.active = True
self.pr = self.PurchaseRequest.create(self.pr_vals.copy())
# confirm
self.pr.button_to_approve()
self.assertEqual(self.pr.state, "draft")
# test all draft pr
self.pr2 = self.PurchaseRequest.create(self.pr_vals.copy())
self.PurchaseRequest.test_all_draft_requests()
self.assertEqual(self.pr2.state, "draft")
# Set ignore_exception flag (Done after ignore is selected at wizard)
self.pr.ignore_exception = True
self.pr.button_to_approve()
self.assertEqual(self.pr.state, "to_approve")
# Add a request line to test after PR is confirmed
# set ignore_exception = False (Done by onchange of line_ids)
field_onchange = self.PurchaseRequest._onchange_spec()
self.assertEqual(field_onchange.get("line_ids"), "1")
self.env.cache.invalidate()
self.pr3New = self.PurchaseRequest.new(self.pr_vals.copy())
self.pr3New.ignore_exception = True
self.pr3New.state = "to_approve"
self.pr3New.onchange_ignore_exception()
self.assertFalse(self.pr3New.ignore_exception)
self.pr.write(
{
"line_ids": [
(
0,
0,
{
"name": "Pencil",
"product_qty": 2.0,
"estimated_cost": 30.0,
"date_required": self.date_required,
},
)
]
}
)
# Set ignore exception True (Done manually by user)
self.pr.ignore_exception = True
self.pr.button_rejected()
self.pr.button_draft()
self.assertEqual(self.pr.state, "draft")
self.assertTrue(not self.pr.ignore_exception)
# Simulation the opening of the wizard purchase_request_exception_confirm and
# set ignore_exception to True
pr_except_confirm = self.purchase_request_exception_confirm.with_context(
active_id=self.pr.id,
active_ids=[self.pr.id],
active_model=self.pr._name,
).create({"ignore": True})
pr_except_confirm.action_confirm()
self.assertTrue(self.pr.ignore_exception)
| 37.858407
| 4,278
|
723
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Ecosoft (http://ecosoft.co.th)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class PurchaseRequestExceptionConfirm(models.TransientModel):
_name = "purchase.request.exception.confirm"
_description = "Purchase request exception wizard"
_inherit = ["exception.rule.confirm"]
related_model_id = fields.Many2one("purchase.request", "Purchase request")
def action_confirm(self):
self.ensure_one()
if self.ignore:
self.related_model_id.button_draft()
self.related_model_id.ignore_exception = True
self.related_model_id.button_to_approve()
return super().action_confirm()
| 36.15
| 723
|
1,809
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Ecosoft (http://ecosoft.co.th)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import api, models
class PurchaseRequest(models.Model):
_inherit = ["purchase.request", "base.exception"]
_name = "purchase.request"
_order = "main_exception_id asc, id desc"
@api.model
def test_all_draft_requests(self):
request_set = self.search([("state", "=", "draft")])
request_set.detect_exceptions()
return True
@api.model
def _reverse_field(self):
return "purchase_request_ids"
def detect_exceptions(self):
all_exceptions = super().detect_exceptions()
lines = self.mapped("line_ids")
all_exceptions += lines.detect_exceptions()
return all_exceptions
@api.constrains("ignore_exception", "line_ids", "state")
def purchase_request_check_exception(self):
requests = self.filtered(lambda s: s.state == "to_approve")
if requests:
requests._check_exception()
@api.onchange("line_ids")
def onchange_ignore_exception(self):
if self.state == "to_approve":
self.ignore_exception = False
def button_to_approve(self):
if self.detect_exceptions() and not self.ignore_exception:
return self._popup_exceptions()
return super().button_to_approve()
def button_draft(self):
res = super().button_draft()
for request in self:
request.exception_ids = False
request.main_exception_id = False
request.ignore_exception = False
return res
@api.model
def _get_popup_action(self):
action = self.env.ref(
"purchase_request_exception.action_purchase_request_exception_confirm"
)
return action
| 31.736842
| 1,809
|
728
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Ecosoft (http://ecosoft.co.th)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class PurchaseRequestLine(models.Model):
_inherit = ["purchase.request.line", "base.exception.method"]
_name = "purchase.request.line"
ignore_exception = fields.Boolean(
related="request_id.ignore_exception", store=True, string="Ignore Exceptions"
)
def _get_main_records(self):
return self.mapped("request_id")
@api.model
def _reverse_field(self):
return "purchase_request_ids"
def _detect_exceptions(self, rule):
records = super()._detect_exceptions(rule)
return records.mapped("request_id")
| 30.333333
| 728
|
624
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Ecosoft (http://ecosoft.co.th)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class ExceptionRule(models.Model):
_inherit = "exception.rule"
purchase_request_ids = fields.Many2many(
comodel_name="purchase.request",
string="Purchase Requests",
)
model = fields.Selection(
selection_add=[
("purchase.request", "Purchase request"),
("purchase.request.line", "Purchase request line"),
],
ondelete={"purchase.request": "cascade", "purchase.request.line": "cascade"},
)
| 31.2
| 624
|
558
|
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 Invoiced",
"summary": "Useful filters in Purchases to know the actual status of 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",
],
"data": [
"views/purchase_views.xml",
],
"installable": True,
}
| 29.368421
| 558
|
3,340
|
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.assertEqual(self.po.invoice_status_validated, "no")
self.po.button_confirm()
self.assertEqual(self.po.invoice_status_validated, "to invoice")
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].button_validate()
self.assertEqual(self.po.invoice_status_validated, "to invoice")
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.assertEqual(self.po.invoice_status_validated, "to invoice")
def test_03_purchase_order_received_invoiced_posted(self):
"""
The invoiced and validated
"""
self.po.button_confirm()
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.assertEqual(self.po.invoice_status_validated, "invoiced")
| 38.390805
| 3,340
|
1,279
|
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"
# Same as invoice_status, but excluding invoices in draft
invoice_status_validated = fields.Selection(
[
("no", "Nothing to Bill"),
("to invoice", "Waiting Bills"),
("invoiced", "Fully Billed"),
],
string="Posted Billing Status",
compute="_compute_invoice_status_validated",
store=True,
readonly=True,
copy=False,
default="no",
)
@api.depends("invoice_status", "invoice_ids.state")
def _compute_invoice_status_validated(self):
# Same as invoice status, execpt it is not invoiced unless there is no invoice
# in draft
for order in self:
if order.invoice_status in ("no", "to invoice"):
order.invoice_status_validated = order.invoice_status
else:
if not any(inv.state == "draft" for inv in order.invoice_ids):
order.invoice_status_validated = order.invoice_status
else:
order.invoice_status_validated = "to invoice"
| 36.542857
| 1,279
|
662
|
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).
{
"name": "Purchase Requisition Tier Validation",
"summary": "Extends the functionality of Purchase Agreements 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",
"application": False,
"installable": True,
"depends": ["purchase_requisition", "base_tier_validation"],
"data": ["views/purchase_requisition_view.xml"],
}
| 38.941176
| 662
|
519
|
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 TestPurchaseRequisitionTierValidation(common.TransactionCase):
def setUp(self):
super().setUp()
self.tier_definition = self.env["tier.definition"]
def test_get_tier_validation_model_names(self):
self.assertIn(
"purchase.requisition",
self.tier_definition._get_tier_validation_model_names(),
)
| 32.4375
| 519
|
407
|
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 api, models
class TierDefinition(models.Model):
_inherit = "tier.definition"
@api.model
def _get_tier_validation_model_names(self):
res = super()._get_tier_validation_model_names()
res.append("purchase.requisition")
return res
| 29.071429
| 407
|
400
|
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 PurchaseRequisition(models.Model):
_name = "purchase.requisition"
_inherit = ["purchase.requisition", "tier.validation"]
_state_from = ["draft"]
_state_to = ["ongoing", "in_progress"]
_tier_validation_manual_config = False
| 30.769231
| 400
|
506
|
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.html).
{
"name": "Purchase Cancel Confirm",
"version": "15.0.1.0.0",
"author": "Ecosoft,Odoo Community Association (OCA)",
"category": "Usability",
"license": "AGPL-3",
"website": "https://github.com/OCA/purchase-workflow",
"depends": ["base_cancel_confirm", "purchase"],
"auto_install": False,
"installable": True,
"maintainers": ["kittiu"],
}
| 33.733333
| 506
|
1,737
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Ecosoft Co., Ltd. (http://ecosoft.co.th)
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
from odoo.tests.common import Form, TransactionCase
class TestPurchaseCancelConfirm(TransactionCase):
def setUp(self):
super(TestPurchaseCancelConfirm, self).setUp()
self.purchase_order_obj = self.env["purchase.order"]
self.env["ir.config_parameter"].sudo().set_param(
"purchase.order.cancel_confirm_disable", "False"
)
self.purchase_order = self.purchase_order_obj.create(
{
"partner_id": self.env.ref("base.res_partner_12").id,
}
)
def test_01_cancel_confirm_purchase(self):
"""Cancel a document, I expect cancel_reason.
Then, set to draft, I expect cancel_reason is deleted.
"""
self.purchase_order.button_confirm()
# Click reject, cancel confirm wizard will open. Type in cancel_reason
res = self.purchase_order.button_cancel()
ctx = res.get("context")
self.assertEqual(ctx["cancel_method"], "button_cancel")
self.assertEqual(ctx["default_has_cancel_reason"], "optional")
wizard = Form(self.env["cancel.confirm"].with_context(**ctx))
wizard.cancel_reason = "Wrong information"
wiz = wizard.save()
# Confirm cancel on wizard
wiz.confirm_cancel()
self.assertEqual(self.purchase_order.cancel_reason, wizard.cancel_reason)
self.assertEqual(self.purchase_order.state, "cancel")
# Set to draft
self.purchase_order.button_draft()
self.assertEqual(self.purchase_order.cancel_reason, False)
self.assertEqual(self.purchase_order.state, "draft")
| 44.538462
| 1,737
|
623
|
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.html).
from odoo import models
class PurchaseOrder(models.Model):
_name = "purchase.order"
_inherit = ["purchase.order", "base.cancel.confirm"]
_has_cancel_reason = "optional" # ["no", "optional", "required"]
def button_cancel(self):
if not self.filtered("cancel_confirm"):
return self.open_cancel_confirm_wizard()
return super().button_cancel()
def button_draft(self):
self.clear_cancel_confirm_data()
return super().button_draft()
| 32.789474
| 623
|
1,107
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
from odoo import SUPERUSER_ID, api
_logger = logging.getLogger(__name__)
def post_init_hook(cr, registry):
"""Existing employees should be subscribed to the new subtype for all
existing purchase orders..
"""
_logger.info(
"Starting task to update internal followers for "
"existing purchase orders to assign the new subtype "
"Purchase Receptions."
)
env = api.Environment(cr, SUPERUSER_ID, {})
users = env["res.users"].search([])
followers = env["mail.followers"].search(
[
("res_model", "=", "purchase.order"),
("partner_id", "in", users.mapped("partner_id").ids),
]
)
for follower in followers:
follower.subtype_ids += env.ref(
"purchase_reception_notify.mt_purchase_reception"
)
_logger.info(
"Finalized task to update internal followers for "
"existing purchase orders to assign the new subtype "
"Purchase Receptions."
)
| 31.628571
| 1,107
|
493
|
py
|
PYTHON
|
15.0
|
# Copyright 2019-21 ForgeFlow S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl-3.0).
{
"name": "Purchase Reception Notify",
"version": "15.0.1.0.0",
"category": "Purchase Management",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/purchase-workflow",
"license": "AGPL-3",
"depends": ["purchase_stock"],
"data": ["data/mail.xml"],
"installable": True,
"post_init_hook": "post_init_hook",
}
| 32.866667
| 493
|
1,989
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 ForgeFlow S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.fields import Datetime
from odoo.tests.common import TransactionCase
class TestPurchaseReceptionNotify(TransactionCase):
def setUp(self):
super(TestPurchaseReceptionNotify, self).setUp()
self.purchase_order_model = self.env["purchase.order"]
purchase_order_line_model = self.env["purchase.order.line"]
partner_model = self.env["res.partner"]
prod_model = self.env["product.product"]
self.product_uom_model = self.env["uom.uom"]
# partners
pa_dict = {"name": "Partner 1"}
self.partner = partner_model.sudo().create(pa_dict)
# Purchase Order Num 1
po_dict = {"partner_id": self.partner.id}
self.purchase_order = self.purchase_order_model.create(po_dict)
uom_id = self.env.ref("uom.product_uom_unit").id
pr_dict = {
"name": "Product Test",
"uom_id": uom_id,
"purchase_method": "purchase",
}
self.product = prod_model.sudo().create(pr_dict)
pl_dict1 = {
"date_planned": Datetime.now(),
"name": "PO01",
"order_id": self.purchase_order.id,
"product_id": self.product.id,
"product_uom": uom_id,
"price_unit": 1.0,
"product_qty": 5.0,
}
self.purchase_order_line = purchase_order_line_model.sudo().create(pl_dict1)
self.purchase_order.button_confirm()
def test_reception_notification(self):
# Now we receive the products
for picking in self.purchase_order.picking_ids:
picking.move_lines.write({"quantity_done": 5.0})
picking.button_validate()
self.assertTrue(
"Receipt confirmation %s" % picking.name
in self.purchase_order_line.order_id.message_ids[0].body,
"PO user not notified",
)
| 38.25
| 1,989
|
2,396
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 ForgeFlow S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/lgpl-3.0).
from odoo import _, api, models
class StockPicking(models.Model):
_inherit = "stock.picking"
@api.model
def _purchase_order_picking_confirm_message_content(self, picking, purchase_dict):
if not purchase_dict:
purchase_dict = {}
title = _("Receipt confirmation %s") % (picking.name)
message = "<h3>%s</h3>" % title
message += _(
"The following items have now been received in Incoming Shipment %s:"
) % (picking.name)
message += "<ul>"
for purchase_line_id in purchase_dict.values():
display_name = purchase_line_id["purchase_line"].product_id.display_name
product_qty = purchase_line_id["stock_move"].product_qty
uom = purchase_line_id["stock_move"].product_uom.name
message += _(
"<li><b>%(display_name)s</b>: Received quantity %(product_qty)s %(uom)s</li>",
display_name=display_name,
product_qty=product_qty,
uom=uom,
)
message += "</ul>"
return message
def _action_done(self):
res = super()._action_done()
for picking in self.filtered(lambda p: p.picking_type_id.code == "incoming"):
purchase_dict = {}
for move in picking.move_lines.filtered("purchase_line_id"):
pol_id = move.purchase_line_id
if pol_id.order_id not in purchase_dict.keys():
purchase_dict[pol_id.order_id] = {}
if pol_id.id not in purchase_dict[pol_id.order_id].keys():
purchase_dict[pol_id.order_id][pol_id.id] = {}
data = {"purchase_line": pol_id, "stock_move": move}
purchase_dict[pol_id.order_id][pol_id.id] = data
for po in purchase_dict.keys():
message = self._purchase_order_picking_confirm_message_content(
picking, purchase_dict[po]
)
po.sudo().message_post(
body=message,
subtype_id=self.env.ref(
"purchase_reception_notify.mt_purchase_reception"
).id,
author_id=self.env.user.partner_id.id,
)
return res
| 42.785714
| 2,396
|
642
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Sergio Teruel <sergio.teruel@tecnativa.com>
# Copyright 2018 Carlos Dauden <carlos.dauden@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
{
"name": "Purchase Line Reassign",
"summary": "",
"version": "15.0.1.0.0",
"category": "Purchase Management",
"website": "https://github.com/OCA/purchase-workflow",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"depends": [
"purchase",
],
"data": [
"security/ir.model.access.csv",
"wizards/purchase_line_reassign_view.xml",
],
}
| 30.571429
| 642
|
1,778
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Alexandre Díaz <alexandre.diaz@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from datetime import datetime
from odoo.tests import common
class TestReassign(common.TransactionCase):
def test_reassign(self):
vendor = self.env["res.partner"].create(
{
"name": "Vendor Test",
}
)
product = self.env["product.product"].create(
{
"name": "Product Test",
}
)
purchase_from = self.env["purchase.order"].create(
{
"partner_id": vendor.id,
"order_line": [
(
0,
False,
{
"name": "Test Product",
"product_id": product.id,
"product_qty": 2,
"price_unit": 150.00,
"date_planned": datetime.now(),
"product_uom": self.env.ref("uom.product_uom_unit").id,
},
)
],
}
)
purchase_to = self.env["purchase.order"].create(
{
"partner_id": vendor.id,
}
)
pl_reassign = (
self.env["purchase.order.line.reassign.wiz"]
.with_context(active_ids=purchase_from.order_line.ids)
.create(
{
"purchase_order_id": purchase_to.id,
}
)
)
pl_reassign.action_apply()
self.assertFalse(len(purchase_from.order_line))
self.assertTrue(len(purchase_to.order_line))
| 32.309091
| 1,777
|
1,495
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Sergio Teruel <sergio.teruel@tecnativa.com>
# Copyright 2018 Carlos Dauden <carlos.dauden@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo import _, exceptions, fields, models
class PurchaseOrderLineReassignWiz(models.TransientModel):
_name = "purchase.order.line.reassign.wiz"
_description = "Wizard to reassign purchase order lines to other PO"
def _default_partner_id(self):
active_ids = self.env.context.get("active_ids")
lines = self.env["purchase.order.line"].browse(active_ids)
partner = lines[:1].order_id.partner_id
if lines.filtered(lambda l: (l.invoice_lines or l.partner_id != partner)):
raise exceptions.ValidationError(
_("Selected line/s are invoiced or they have distinct vendors")
)
return partner
purchase_order_id = fields.Many2one(
comodel_name="purchase.order",
string="Move to purchase",
)
partner_id = fields.Many2one(
comodel_name="res.partner",
string="Vendor",
default=lambda self: self._default_partner_id(),
)
allow_different_suppliers = fields.Boolean(
help="Allow selecting orders from other suppliers."
)
def action_apply(self):
active_ids = self.env.context.get("active_ids")
lines = self.env["purchase.order.line"].browse(active_ids)
lines.write({"order_id": self.purchase_order_id.id})
return lines
| 39.342105
| 1,495
|
575
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Purchase - Order Qty By Product Category",
"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": [
"security/ir.model.access.csv",
"views/purchase_order.xml",
"views/res_config_settings.xml",
],
"depends": ["purchase"],
"installable": True,
}
| 31.944444
| 575
|
10,765
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests import Form, TransactionCase
class TestPurchaseOrderQtyByProductCategory(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.uom_unit = cls.env.ref("uom.product_uom_unit")
cls.uom_dozen = cls.env.ref("uom.product_uom_dozen")
cls.uom_cubic_meter = cls.env.ref("uom.product_uom_cubic_meter")
cls.uom_litre = cls.env.ref("uom.product_uom_litre")
cls.partner = cls.env["res.partner"].create({"name": "Partner 1"})
cls.category1, cls.category2 = cls.env["product.category"].create(
[{"name": "Category 1"}, {"name": "Category 2"}]
)
cls.product1, cls.product2, cls.product3 = cls.env["product.product"].create(
[
{
"name": "Product 1",
"uom_id": cls.uom_unit.id,
"uom_po_id": cls.uom_unit.id,
"categ_id": cls.category1.id,
},
{
"name": "Product 2",
"uom_id": cls.uom_dozen.id,
"uom_po_id": cls.uom_dozen.id,
"categ_id": cls.category1.id,
},
{
"name": "Product 3",
"uom_id": cls.uom_cubic_meter.id,
"uom_po_id": cls.uom_cubic_meter.id,
"categ_id": cls.category2.id,
},
]
)
cls.order_vals = {
"partner_id": cls.partner.id,
"company_id": cls.env.user.company_id.id,
"order_line": [
(
0,
0,
{
"name": cls.product1.name,
"product_id": cls.product1.id,
"product_qty": 10.0,
"product_uom": cls.product1.uom_po_id.id,
},
),
(
0,
0,
{
"name": cls.product2.name,
"product_id": cls.product2.id,
"product_qty": 1.0,
"product_uom": cls.product2.uom_po_id.id,
},
),
(
0,
0,
{
"name": cls.product3.name,
"product_id": cls.product3.id,
"product_qty": 0.05,
"product_uom": cls.product3.uom_po_id.id,
},
),
],
}
def test_00_po_settings_from_param(self):
# Case 1: both params inactive
k, v = "purchase_ordered_qty_by_product_category.split_by_uom", "0"
self.env["ir.config_parameter"].sudo().set_param(k, v)
k, v = "purchase_ordered_qty_by_product_category.split_by_uom_reference", "0"
self.env["ir.config_parameter"].sudo().set_param(k, v)
po = self.env["purchase.order"].create(self.order_vals)
self.assertFalse(po.category_qty_split_by_uom)
self.assertFalse(po.category_qty_split_by_uom_reference)
# Case 2: split by UoM active, split by reference UoM inactive
k, v = "purchase_ordered_qty_by_product_category.split_by_uom", "1"
self.env["ir.config_parameter"].sudo().set_param(k, v)
po = self.env["purchase.order"].create(self.order_vals)
self.assertTrue(po.category_qty_split_by_uom)
self.assertFalse(po.category_qty_split_by_uom_reference)
# Case 3: split by UoM active, split by reference UoM active
k, v = "purchase_ordered_qty_by_product_category.split_by_uom_reference", "1"
self.env["ir.config_parameter"].sudo().set_param(k, v)
po = self.env["purchase.order"].create(self.order_vals)
self.assertTrue(po.category_qty_split_by_uom)
self.assertTrue(po.category_qty_split_by_uom_reference)
# Case 4: split by UoM inactive, split by reference UoM active
k, v = "purchase_ordered_qty_by_product_category.split_by_uom", "0"
self.env["ir.config_parameter"].sudo().set_param(k, v)
po = self.env["purchase.order"].create(self.order_vals)
self.assertFalse(po.category_qty_split_by_uom)
self.assertFalse(po.category_qty_split_by_uom_reference)
def test_01_po_settings_from_settings(self):
# Case 1: both params inactive
with Form(
self.env["res.config.settings"], "base.res_config_settings_view_form"
) as config_form:
config_form.po_category_qty_split_by_uom_reference = False
config_form.po_category_qty_split_by_uom = False
config = config_form.save()
config.execute()
po = self.env["purchase.order"].create(self.order_vals)
self.assertFalse(po.category_qty_split_by_uom)
self.assertFalse(po.category_qty_split_by_uom_reference)
# Case 2: split by UoM active, split by reference UoM inactive
with Form(
self.env["res.config.settings"], "base.res_config_settings_view_form"
) as config_form:
config_form.po_category_qty_split_by_uom = True
config = config_form.save()
config.execute()
po = self.env["purchase.order"].create(self.order_vals)
self.assertTrue(po.category_qty_split_by_uom)
self.assertFalse(po.category_qty_split_by_uom_reference)
# Case 3: split by UoM active, split by reference UoM active
with Form(
self.env["res.config.settings"], "base.res_config_settings_view_form"
) as config_form:
config_form.po_category_qty_split_by_uom_reference = True
config = config_form.save()
config.execute()
po = self.env["purchase.order"].create(self.order_vals)
self.assertTrue(po.category_qty_split_by_uom)
self.assertTrue(po.category_qty_split_by_uom_reference)
# Case 4: split by UoM inactive, split by reference UoM active
with Form(
self.env["res.config.settings"], "base.res_config_settings_view_form"
) as config_form:
config_form.po_category_qty_split_by_uom = False
config = config_form.save()
config.execute()
po = self.env["purchase.order"].create(self.order_vals)
self.assertFalse(po.category_qty_split_by_uom)
self.assertFalse(po.category_qty_split_by_uom_reference)
def test_02_qty_splitting_by_category(self):
po = self.env["purchase.order"].create(self.order_vals)
self.assertEqual(len(po.qty_by_product_category_ids), 2)
self.assertEqual(
po.qty_by_product_category_ids.category_id, self.category1 + self.category2
)
rec1 = po.qty_by_product_category_ids.filtered(
lambda r: r.category_id == self.category1
)
self.assertEqual(
(
rec1.qty_ordered,
rec1.qty_received,
rec1.qty_to_receive,
rec1.qty_uom_id.id,
),
(11, 0, 11, False),
)
rec2 = po.qty_by_product_category_ids.filtered(
lambda r: r.category_id == self.category2
)
self.assertEqual(
(
rec2.qty_ordered,
rec2.qty_received,
rec2.qty_to_receive,
rec2.qty_uom_id.id,
),
(0.05, 0, 0.05, False),
)
def test_02_qty_splitting_by_category_and_uom(self):
k, v = "purchase_ordered_qty_by_product_category.split_by_uom", "1"
self.env["ir.config_parameter"].sudo().set_param(k, v)
po = self.env["purchase.order"].create(self.order_vals)
self.assertEqual(len(po.qty_by_product_category_ids), 3)
self.assertEqual(
po.qty_by_product_category_ids.category_id, self.category1 + self.category2
)
rec1 = po.qty_by_product_category_ids.filtered(
lambda r: r.category_id == self.category1 and r.qty_uom_id == self.uom_unit
)
self.assertEqual(
(
rec1.qty_ordered,
rec1.qty_received,
rec1.qty_to_receive,
rec1.qty_uom_id.id,
),
(10, 0, 10, self.uom_unit.id),
)
rec2 = po.qty_by_product_category_ids.filtered(
lambda r: r.category_id == self.category1 and r.qty_uom_id == self.uom_dozen
)
self.assertEqual(
(
rec2.qty_ordered,
rec2.qty_received,
rec2.qty_to_receive,
rec2.qty_uom_id.id,
),
(1, 0, 1, self.uom_dozen.id),
)
rec3 = po.qty_by_product_category_ids.filtered(
lambda r: r.category_id == self.category2
and r.qty_uom_id == self.uom_cubic_meter
)
self.assertEqual(
(
rec3.qty_ordered,
rec3.qty_received,
rec3.qty_to_receive,
rec3.qty_uom_id.id,
),
(0.05, 0, 0.05, self.uom_cubic_meter.id),
)
def test_03_qty_splitting_by_category_and_uom_reference(self):
k, v = "purchase_ordered_qty_by_product_category.split_by_uom", "1"
self.env["ir.config_parameter"].sudo().set_param(k, v)
k, v = "purchase_ordered_qty_by_product_category.split_by_uom_reference", "1"
self.env["ir.config_parameter"].sudo().set_param(k, v)
po = self.env["purchase.order"].create(self.order_vals)
self.assertEqual(len(po.qty_by_product_category_ids), 2)
self.assertEqual(
po.qty_by_product_category_ids.category_id, self.category1 + self.category2
)
rec1 = po.qty_by_product_category_ids.filtered(
lambda r: r.category_id == self.category1 and r.qty_uom_id == self.uom_unit
)
self.assertEqual(
(
rec1.qty_ordered,
rec1.qty_received,
rec1.qty_to_receive,
rec1.qty_uom_id.id,
),
(22, 0, 22, self.uom_unit.id),
)
rec2 = po.qty_by_product_category_ids.filtered(
lambda r: r.category_id == self.category2 and r.qty_uom_id == self.uom_litre
)
self.assertEqual(
(
rec2.qty_ordered,
rec2.qty_received,
rec2.qty_to_receive,
rec2.qty_uom_id.id,
),
(50, 0, 50, self.uom_litre.id),
)
| 41.563707
| 10,765
|
2,766
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from collections import defaultdict
from odoo import api, fields, models
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
qty_by_product_category_id = fields.Many2one(
"purchase.order.qty.by.product.category",
compute="_compute_qty_by_product_category_id",
store=True,
string="Order Line Qty By Category",
)
def unlink(self):
recs = self.qty_by_product_category_id
res = super().unlink()
recs.filtered(lambda r: not r.purchase_line_ids).unlink()
return res
@api.depends(
"order_id.category_qty_split_by_uom",
"order_id.category_qty_split_by_uom_reference",
"product_id",
"product_uom",
"product_qty",
"qty_received",
)
def _compute_qty_by_product_category_id(self):
old_recs = self.qty_by_product_category_id
data = defaultdict(lambda: self.browse())
uom_reference_ids = {
u.category_id.id: u.id
for u in self.env["uom.uom"].search([("uom_type", "=", "reference")])
}
for line in self:
if isinstance(line.id, models.NewId) or not (
line.order_id._origin and line.product_id
):
# Skip lines while creating or updating them, recompute field only after saving
line.qty_by_product_category_id = False
continue
uom_id = False
if line.product_uom and line.order_id.category_qty_split_by_uom:
if line.order_id.category_qty_split_by_uom_reference:
uom_id = uom_reference_ids[line.product_uom.category_id.id]
else:
uom_id = line.product_uom.id
data[
(line.order_id._origin.id, line.product_id.categ_id.id, uom_id)
] += line
rec_obj = self.env["purchase.order.qty.by.product.category"]
for (order_id, categ_id, uom_id), lines in data.items():
rec = rec_obj.search(
[
("purchase_order_id", "=", order_id),
("category_id", "=", categ_id),
("qty_uom_id", "=", uom_id),
],
limit=1,
)
if not rec:
rec = rec_obj.create(
{
"purchase_order_id": order_id,
"category_id": categ_id,
"qty_uom_id": uom_id,
}
)
lines.qty_by_product_category_id = rec
old_recs.filtered(lambda r: not r.purchase_line_ids).unlink()
| 36.88
| 2,766
|
3,159
|
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
from odoo.exceptions import ValidationError
class PurchaseOrderQtyByProductCategory(models.Model):
_name = "purchase.order.qty.by.product.category"
_description = "PO quantities split by product category"
purchase_order_id = fields.Many2one(
"purchase.order", required=True, ondelete="cascade"
)
purchase_line_ids = fields.One2many(
"purchase.order.line", "qty_by_product_category_id"
)
category_id = fields.Many2one("product.category", required=True, ondelete="cascade")
qty_ordered = fields.Float(
digits="Product Unit of Measure", compute="_compute_quantities", store=True
)
qty_received = fields.Float(
digits="Product Unit of Measure", compute="_compute_quantities", store=True
)
qty_to_receive = fields.Float(
digits="Product Unit of Measure", compute="_compute_quantities", store=True
)
qty_uom_id = fields.Many2one("uom.uom")
@api.constrains("purchase_order_id", "category_id", "qty_uom_id")
def _check_unicity(self):
for rec in self:
if (
self.search_count(
[
("purchase_order_id", "=", rec.purchase_order_id.id),
("category_id", "=", rec.category_id.id),
("qty_uom_id", "=", rec.qty_uom_id.id),
]
)
> 1
):
raise ValidationError(
_(
"Qty group for order '%(order)s', category '%(categ)s'"
" and UoM '%(uom)s' already exists"
)
% {
"order": rec.purchase_order_id.name,
"categ": rec.category_id.name,
"uom": rec.qty_uom_id.name or _("undefined"),
}
)
@api.depends(
"purchase_line_ids.product_qty",
"purchase_line_ids.qty_received",
"purchase_line_ids.product_uom",
)
def _compute_quantities(self):
for rec in self:
ordered, received = 0, 0
for po_line in rec.purchase_line_ids:
if isinstance(po_line.id, models.NewId):
continue # Skip lines while creating them
elif rec.qty_uom_id:
ordered += po_line.product_uom._compute_quantity(
po_line.product_qty, rec.qty_uom_id, round=False
)
received += po_line.product_uom._compute_quantity(
po_line.qty_received, rec.qty_uom_id, round=False
)
else:
ordered += po_line.product_qty
received += po_line.qty_received
rec.update(
{
"qty_ordered": ordered,
"qty_received": received,
"qty_to_receive": ordered - received,
}
)
| 38.52439
| 3,159
|
2,094
|
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 PurchaseOrder(models.Model):
_inherit = "purchase.order"
@api.model
def _get_default_category_qty_split_by_uom(self):
key = "purchase_ordered_qty_by_product_category.split_by_uom"
param = self.env["ir.config_parameter"].sudo().get_param(key)
if param and param.strip().lower() in ("1", "true"):
return True
company_id = self.default_get(["company_id"]).get("company_id")
if company_id:
company = self.env["res.company"].browse(company_id)
if company.exists() and company.po_category_qty_split_by_uom:
return True
return False
@api.model
def _get_default_category_qty_split_by_uom_reference(self):
split_by_uom = self._get_default_category_qty_split_by_uom()
if not split_by_uom:
return False
key = "purchase_ordered_qty_by_product_category.split_by_uom_reference"
param = self.env["ir.config_parameter"].sudo().get_param(key)
if param and param.strip().lower() in ("1", "true"):
return True
company_id = self.default_get(["company_id"]).get("company_id")
if company_id:
company = self.env["res.company"].browse(company_id)
if (
company.exists()
and company.po_category_qty_split_by_uom
and company.po_category_qty_split_by_uom_reference
):
return True
return False
category_qty_split_by_uom = fields.Boolean(
default=lambda self: self._get_default_category_qty_split_by_uom()
)
category_qty_split_by_uom_reference = fields.Boolean(
default=lambda self: self._get_default_category_qty_split_by_uom_reference()
)
qty_by_product_category_ids = fields.One2many(
"purchase.order.qty.by.product.category",
"purchase_order_id",
readonly=True,
string="Order Qty By Category",
)
| 38.777778
| 2,094
|
306
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResCompany(models.Model):
_inherit = "res.company"
po_category_qty_split_by_uom = fields.Boolean()
po_category_qty_split_by_uom_reference = fields.Boolean()
| 27.818182
| 306
|
517
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA
# 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"
po_category_qty_split_by_uom = fields.Boolean(
related="company_id.po_category_qty_split_by_uom",
readonly=False,
)
po_category_qty_split_by_uom_reference = fields.Boolean(
related="company_id.po_category_qty_split_by_uom_reference",
readonly=False,
)
| 28.722222
| 517
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.