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
|
|---|---|---|---|---|---|---|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
817
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Elico Corp, Dominique K. <dominique.k@elico-corp.com.sg>
# Copyright 2019 Ecosoft Co., Ltd., Kitti U. <kittiu@ecosoft.co.th>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Purchase Deposit",
"version": "15.0.1.0.2",
"summary": "Option to create deposit from purchase order",
"author": "Elico Corp, Ecosoft, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/purchase-workflow",
"category": "Purchase Management",
"license": "AGPL-3",
"depends": ["purchase"],
"data": [
"security/ir.model.access.csv",
"wizard/purchase_make_invoice_advance_views.xml",
"views/res_config_settings_views.xml",
"views/purchase_view.xml",
],
"installable": True,
"auto_install": False,
}
| 37.136364
| 817
|
8,166
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Elico Corp, Dominique K. <dominique.k@elico-corp.com.sg>
# Copyright 2019 Ecosoft Co., Ltd., Kitti U. <kittiu@ecosoft.co.th>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields
from odoo.exceptions import UserError
from odoo.tests.common import Form, TransactionCase
class TestPurchaseDeposit(TransactionCase):
def setUp(self):
super(TestPurchaseDeposit, self).setUp()
self.product_model = self.env["product.product"]
self.account_model = self.env["account.account"]
self.invoice_model = self.env["account.move"]
self.default_model = self.env["ir.default"]
# Create Deposit Account
self.account_deposit = self.account_model.create(
{
"name": "Purchase Deposit",
"code": "11620",
"user_type_id": self.env.ref(
"account.data_account_type_current_assets"
).id,
}
)
# Create products:
p1 = self.product1 = self.product_model.create(
{
"name": "Test Product 1",
"type": "service",
"default_code": "PROD1",
"purchase_method": "purchase",
}
)
self.po = self.env["purchase.order"].create(
{
"partner_id": self.ref("base.res_partner_3"),
"order_line": [
(
0,
0,
{
"product_id": p1.id,
"product_uom": p1.uom_id.id,
"name": p1.name,
"price_unit": 100.0,
"date_planned": fields.Datetime.now(),
"product_qty": 42.0,
},
)
],
}
)
def test_create_deposit_invoice(self):
self.assertEqual(len(self.po.order_line), 1)
# We create invoice from expense
ctx = {
"active_id": self.po.id,
"active_ids": [self.po.id],
"active_model": "purchase.order",
"create_bills": True,
}
CreateDeposit = self.env["purchase.advance.payment.inv"]
self.po.button_confirm()
with Form(CreateDeposit.with_context(**ctx)) as f:
f.advance_payment_method = "percentage"
f.deposit_account_id = self.account_deposit
wizard = f.save()
wizard.amount = 10.0 # 10%
wizard.create_invoices()
# New Purchase Deposit is created automatically
deposit_id = self.default_model.sudo().get(
"purchase.advance.payment.inv", "purchase_deposit_product_id"
)
deposit = self.product_model.browse(deposit_id)
self.assertEqual(deposit.name, "Purchase Deposit")
# 1 Deposit Invoice is created
self.assertRecordValues(
self.po.invoice_ids.invoice_line_ids,
[
{
"product_id": deposit.id,
"price_unit": 420.0,
"name": "Deposit Payment",
}
],
)
# On Purchase Order, there will be new deposit line create
self.assertRecordValues(
self.po.order_line,
[
{
"product_id": self.product1.id,
"price_unit": 100.0,
"is_deposit": False,
},
{"product_id": deposit.id, "price_unit": 420.0, "is_deposit": True},
],
)
# On Purchase Order, create normal billing
res = self.po.with_context(create_bill=True).action_create_invoice()
invoice = self.invoice_model.browse(res["res_id"])
self.assertRecordValues(
invoice.invoice_line_ids,
[
{"product_id": self.product1.id, "price_unit": 100.0, "quantity": 42},
{"product_id": deposit.id, "price_unit": 420.0, "quantity": -1},
],
)
def test_create_deposit_invoice_exception_1(self):
"""This test focus on exception cases, when create deposit invoice,
1. This action is allowed only in Purchase Order sate
2. The value of the deposit must be positive
3. For type percentage, The percentage of the deposit must <= 100
"""
self.assertEqual(len(self.po.order_line), 1)
# We create invoice from expense
ctx = {
"active_id": self.po.id,
"active_ids": [self.po.id],
"active_model": "purchase.order",
"create_bills": True,
}
CreateDeposit = self.env["purchase.advance.payment.inv"]
# 1. This action is allowed only in Purchase Order sate
with self.assertRaises(UserError):
Form(CreateDeposit.with_context(**ctx)) # Initi wizard
self.po.button_confirm()
self.assertEqual(self.po.state, "purchase")
# 2. The value of the deposit must be positive
f = Form(CreateDeposit.with_context(**ctx))
f.advance_payment_method = "fixed"
f.amount = 0.0
f.deposit_account_id = self.account_deposit
wizard = f.save()
with self.assertRaises(UserError):
wizard.create_invoices()
# 3. For type percentage, The percentage of the deposit must <= 100
wizard.advance_payment_method = "percentage"
wizard.amount = 101.0
with self.assertRaises(UserError):
wizard.create_invoices()
wizard.amount = 10
def test_create_deposit_invoice_exception_2(self):
"""This test focus on exception cases, when create deposit invoice,
4. Purchase Deposit Product's purchase_method != purchase
"""
self.assertEqual(len(self.po.order_line), 1)
# We create invoice from expense
ctx = {
"active_id": self.po.id,
"active_ids": [self.po.id],
"active_model": "purchase.order",
"create_bills": True,
}
CreateDeposit = self.env["purchase.advance.payment.inv"]
self.po.button_confirm()
self.assertEqual(self.po.state, "purchase")
f = Form(CreateDeposit.with_context(**ctx))
f.advance_payment_method = "percentage"
f.amount = 101.0
f.deposit_account_id = self.account_deposit
wizard = f.save()
# 4. Purchase Deposit Product's purchase_method != purchase
deposit_id = self.default_model.sudo().get(
"purchase.advance.payment.inv", "purchase_deposit_product_id"
)
deposit = self.product_model.browse(deposit_id)
deposit.purchase_method = "receive"
wizard.purchase_deposit_product_id = deposit
with self.assertRaises(UserError):
wizard.create_invoices()
def test_create_deposit_invoice_exception_3(self):
"""This test focus on exception cases, when create deposit invoice,
5. Purchase Deposit Product's type != service
"""
self.assertEqual(len(self.po.order_line), 1)
# We create invoice from expense
ctx = {
"active_id": self.po.id,
"active_ids": [self.po.id],
"active_model": "purchase.order",
"create_bills": True,
}
CreateDeposit = self.env["purchase.advance.payment.inv"]
self.po.button_confirm()
self.assertEqual(self.po.state, "purchase")
f = Form(CreateDeposit.with_context(**ctx))
f.advance_payment_method = "percentage"
f.amount = 101.0
f.deposit_account_id = self.account_deposit
wizard = f.save()
deposit_id = self.default_model.sudo().get(
"purchase.advance.payment.inv", "purchase_deposit_product_id"
)
deposit = self.product_model.browse(deposit_id)
# 5. Purchase Deposit Product's type != service
deposit.type = "consu"
with self.assertRaises(UserError):
wizard.create_invoices()
| 39.449275
| 8,166
|
9,117
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Elico Corp, Dominique K. <dominique.k@elico-corp.com.sg>
# Copyright 2019 Ecosoft Co., Ltd., Kitti U. <kittiu@ecosoft.co.th>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import time
from datetime import datetime
from odoo import _, api, fields, models
from odoo.exceptions import UserError
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
class PurchaseAdvancePaymentInv(models.TransientModel):
_name = "purchase.advance.payment.inv"
_description = "Purchase Advance Payment Invoice"
advance_payment_method = fields.Selection(
[
("percentage", "Down payment (percentage)"),
("fixed", "Deposit payment (fixed amount)"),
],
string="What do you want to invoice?",
default="percentage",
required=True,
)
purchase_deposit_product_id = fields.Many2one(
comodel_name="product.product",
string="Deposit Payment Product",
domain=[("type", "=", "service")],
)
amount = fields.Float(
string="Deposit Payment Amount",
required=True,
help="The amount to be invoiced in advance, taxes excluded.",
)
deposit_account_id = fields.Many2one(
comodel_name="account.account",
string="Expense Account",
domain=[("deprecated", "=", False)],
help="Account used for deposits",
)
deposit_taxes_id = fields.Many2many(
comodel_name="account.tax",
string="Vendor Taxes",
help="Taxes used for deposits",
)
@api.model
def view_init(self, fields):
active_id = self._context.get("active_id")
purchase = self.env["purchase.order"].browse(active_id)
if purchase.state not in ["purchase", "done"]:
raise UserError(
_("This action are allowed only in Purchase Order and Done state")
)
return super().view_init(fields)
@api.onchange("purchase_deposit_product_id")
def _onchagne_purchase_deposit_product_id(self):
product = self.purchase_deposit_product_id
self.deposit_account_id = product.property_account_expense_id
self.deposit_taxes_id = product.supplier_taxes_id
def _prepare_deposit_val(self, order, po_line, amount):
ir_property_obj = self.env["ir.property"]
account_id = False
product = self.purchase_deposit_product_id
if product.id:
account_id = (
product.property_account_expense_id.id
or product.categ_id.property_account_expense_categ_id.id
)
if not account_id:
inc_acc = ir_property_obj._get(
"property_account_expense_categ_id", "product.category"
)
account_id = (
order.fiscal_position_id.map_account(inc_acc).id if inc_acc else False
)
if not account_id:
raise UserError(
_(
"There is no purchase account defined for this product: %s."
"\nYou may have to install a chart of account from "
"Accounting app, settings menu."
)
% (product.name,)
)
if self.amount <= 0:
raise UserError(_("The value of the deposit must be positive."))
context = {"lang": order.partner_id.lang}
amount = self.amount
if self.advance_payment_method == "percentage": # Case percent
if self.amount > 100:
raise UserError(_("The percentage of the deposit must be not over 100"))
amount = self.amount / 100 * order.amount_untaxed
name = _("Deposit Payment")
del context
taxes = product.supplier_taxes_id.filtered(
lambda r: not order.company_id or r.company_id == order.company_id
)
if order.fiscal_position_id and taxes:
tax_ids = order.fiscal_position_id.map_tax(taxes).ids
else:
tax_ids = taxes.ids
deposit_val = {
"invoice_origin": order.name,
"move_type": "in_invoice",
"partner_id": order.partner_id.id,
"invoice_line_ids": [
(
0,
0,
{
"name": name,
"account_id": account_id,
"price_unit": amount,
"quantity": 1.0,
"product_uom_id": product.uom_id.id,
"product_id": product.id,
"purchase_line_id": po_line.id,
"tax_ids": [(6, 0, tax_ids)],
"analytic_account_id": po_line.account_analytic_id.id or False,
"analytic_tag_ids": [(6, 0, po_line.analytic_tag_ids.ids)],
},
)
],
"currency_id": order.currency_id.id,
"invoice_payment_term_id": order.payment_term_id.id,
"fiscal_position_id": order.fiscal_position_id.id
or order.partner_id.property_account_position_id.id,
"purchase_id": order.id,
"narration": order.notes,
}
return deposit_val
def _create_invoice(self, order, po_line, amount):
Invoice = self.env["account.move"]
deposit_val = self._prepare_deposit_val(order, po_line, amount)
invoice = Invoice.create(deposit_val)
invoice.message_post_with_view(
"mail.message_origin_link",
values={"self": invoice, "origin": order},
subtype_id=self.env.ref("mail.mt_note").id,
)
return invoice
def _prepare_advance_purchase_line(self, order, product, tax_ids, amount):
return {
"name": _("Advance: %s") % (time.strftime("%m %Y"),),
"price_unit": amount,
"product_qty": 0.0,
"order_id": order.id,
"product_uom": product.uom_id.id,
"product_id": product.id,
"taxes_id": [(6, 0, tax_ids)],
"date_planned": datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT),
"is_deposit": True,
}
def create_invoices(self):
Purchase = self.env["purchase.order"]
IrDefault = self.env["ir.default"].sudo()
purchases = Purchase.browse(self._context.get("active_ids", []))
# Create deposit product if necessary
product = self.purchase_deposit_product_id
if not product:
vals = self._prepare_deposit_product()
product = self.purchase_deposit_product_id = self.env[
"product.product"
].create(vals)
IrDefault.set(
"purchase.advance.payment.inv",
"purchase_deposit_product_id",
product.id,
)
PurchaseLine = self.env["purchase.order.line"]
for order in purchases:
amount = self.amount
if self.advance_payment_method == "percentage": # Case percent
amount = self.amount / 100 * order.amount_untaxed
if product.purchase_method != "purchase":
raise UserError(
_(
"The product used to invoice a down payment should have "
'an invoice policy set to "Ordered quantities". '
"Please update your deposit product to be able to "
"create a deposit invoice."
)
)
if product.type != "service":
raise UserError(
_(
"The product used to invoice a down payment should be "
'of type "Service". Please use another product or '
"update this product."
)
)
taxes = product.supplier_taxes_id.filtered(
lambda r: not order.company_id or r.company_id == order.company_id
)
if order.fiscal_position_id and taxes:
tax_ids = order.fiscal_position_id.map_tax(taxes).ids
else:
tax_ids = taxes.ids
context = {"lang": order.partner_id.lang}
adv_po_line_dict = self._prepare_advance_purchase_line(
order, product, tax_ids, amount
)
po_line = PurchaseLine.create(adv_po_line_dict)
del context
if self._context.get("create_bills", False):
self._create_invoice(order, po_line, amount)
return purchases.action_view_invoice()
return {"type": "ir.actions.act_window_close"}
def _prepare_deposit_product(self):
return {
"name": "Purchase Deposit",
"type": "service",
"purchase_method": "purchase",
"property_account_expense_id": self.deposit_account_id.id,
"supplier_taxes_id": [(6, 0, self.deposit_taxes_id.ids)],
"company_id": False,
}
| 39.986842
| 9,117
|
1,175
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Elico Corp, Dominique K. <dominique.k@elico-corp.com.sg>
# Copyright 2019 Ecosoft Co., Ltd., Kitti U. <kittiu@ecosoft.co.th>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class PurchaseOrder(models.Model):
_inherit = "purchase.order"
def copy_data(self, default=None):
if default is None:
default = {}
default["order_line"] = [
(0, 0, line.copy_data()[0])
for line in self.order_line.filtered(lambda l: not l.is_deposit)
]
return super(PurchaseOrder, self).copy_data(default)
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
is_deposit = fields.Boolean(
string="Is a deposit payment",
help="Deposit payments are made when creating bills from a purhcase"
" order. They are not copied when duplicating a purchase order.",
)
def _prepare_account_move_line(self, move=False):
res = super(PurchaseOrderLine, self)._prepare_account_move_line(move=move)
if self.is_deposit:
res["quantity"] = -1 * self.qty_invoiced
return res
| 34.558824
| 1,175
|
637
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Elico Corp, Dominique K. <dominique.k@elico-corp.com.sg>
# Copyright 2019 Ecosoft Co., Ltd., Kitti U. <kittiu@ecosoft.co.th>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
default_purchase_deposit_product_id = fields.Many2one(
comodel_name="product.product",
string="Purchase Deposit Product",
default_model="purchase.advance.payment.inv",
domain=[("type", "=", "service")],
help="Default product used for payment advances.",
)
| 37.470588
| 637
|
475
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Purchase Receipt Expectation - Manual w/ Split",
"version": "15.0.2.0.0",
"category": "Purchase Management",
"author": "Camptocamp SA, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/purchase-workflow",
"license": "AGPL-3",
"depends": [
"purchase_receipt_expectation_manual",
],
"installable": True,
}
| 31.666667
| 475
|
5,923
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from datetime import datetime, timedelta
from odoo.tests.common import Form
from odoo.addons.purchase_receipt_expectation_manual.tests.test_purchase_receipt_expectation_manual import ( # noqa: B950
TestPurchaseReceiptExpectationManual,
)
class TestPurchaseReceiptExpectationManualSplit(TestPurchaseReceiptExpectationManual):
def test_00_manual_split_receipt_total(self):
"""Tests manual workflow for total receipt
Steps:
- Create a PO with `receipt_expectation` set to "manual"
- Confirm it
- Check that no picking has been created
- Create a wizard with scheduled date = tomorrow and:
1 line where qty = 120, UoM = unit, unit price = 10
- Run checks on wizard
- Try to confirm wizard
- Check picking data
- Check that a split PO line has been created from the original line
Expect:
- No picking is created at PO confirm
- Pickings' data should match wizards' data
- Stock moves' data should match wizard lines' data
"""
self.current_order = self._create_and_check_manual_receipt_order()
pol = self.current_order.order_line[0]
wiz = self.current_order._prepare_manual_receipt_wizard()
self.assertEqual(len(wiz.line_ids), 1)
tomorrow = datetime.now() + timedelta(days=1)
with Form(wiz) as wiz_form:
# Update scheduled date to `tomorrow`
wiz_form.scheduled_date = tomorrow
# Update lines: set 1 line with 120 units
with wiz_form.line_ids.edit(0) as wiz_line:
wiz_line.qty = 120
wiz_line.uom_id = self.env.ref("uom.product_uom_unit")
wiz_line.unit_price = 10
wiz = self._button_wiz_checks_success(wiz_form.save())
picking = self._button_wiz_confirm_success(wiz)
self._check_picking(
picking,
expected_picking_data=[
("id", self.current_order.picking_ids.ids[-1]),
("state", "assigned"),
("scheduled_date", tomorrow),
],
expected_move_lines_data=[
(0, "product_id", pol.product_id),
(0, "price_unit", 10),
(0, "product_uom_qty", 120),
(0, "product_uom", self.env.ref("uom.product_uom_unit")),
],
)
self.assertEqual(len(self.current_order.order_line), 2)
self.assertEqual(
(self.current_order.order_line - pol).manually_split_from_line_id, pol
)
def test_01_manual_split_cancel_picking(self):
"""Tests picking cancellation for manual receipt
Steps:
- Execute `test_00_manual_split_receipt_total()`
- Retrieve the test's order
- Cancel its picking
- Check order lines
Expect:
- The split line shouldn't exist anymore
- The origin line should have its ordered qty reverted
"""
self.test_00_manual_split_receipt_total()
split_line = self.current_order.order_line.filtered(
"manually_split_from_line_id"
)
orig_line = split_line.manually_split_from_line_id
self.current_order.picking_ids.action_cancel()
self.assertFalse(split_line.exists())
self.assertTrue(orig_line.exists())
self.assertEqual(orig_line.product_qty, orig_line.product_qty_pre_split)
def test_02_manual_split_cancel_partial_picking_backorder(self):
"""Tests backorder picking cancellation for manual receipt
Steps:
- Execute `test_00_manual_split_receipt_total()`
- Retrieve the test's order
- Partially receive the picking (with backorder)
- Cancel the backorder picking
- Check order lines
Expect:
- The unreceived quantity should go back to the origin
"""
self.test_00_manual_split_receipt_total()
split_line = self.current_order.order_line.filtered(
"manually_split_from_line_id"
)
orig_line = split_line.manually_split_from_line_id
picking = self.current_order.picking_ids
picking.action_set_quantities_to_reservation()
picking.move_lines.move_line_ids[0].qty_done = 60.0
picking._action_done()
backorder = self.current_order.picking_ids - picking
backorder.action_cancel()
self.assertTrue(split_line.exists())
self.assertTrue(orig_line.exists())
self.assertEqual(orig_line.product_qty, 5.0)
self.assertEqual(split_line.product_qty, 60.0)
def test_03_manual_split_cancel_partial_picking(self):
"""Tests backorder picking cancellation for manual receipt
Steps:
- Execute `test_00_manual_split_receipt_total()`
- Retrieve the test's order
- Partially receive the picking (no backorder)
- Cancel the backorder picking
- Check order lines
Expect:
- The unreceived quantity should go back to the origin
"""
self.test_00_manual_split_receipt_total()
split_line = self.current_order.order_line.filtered(
"manually_split_from_line_id"
)
orig_line = split_line.manually_split_from_line_id
picking = self.current_order.picking_ids
picking.action_set_quantities_to_reservation()
picking.move_lines.move_line_ids[0].qty_done = 60.0
picking.with_context(cancel_backorder=True)._action_done()
self.assertTrue(split_line.exists())
self.assertTrue(orig_line.exists())
self.assertEqual(orig_line.product_qty, 5.0)
self.assertEqual(split_line.product_qty, 60.0)
| 41.131944
| 5,923
|
4,299
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
from odoo.tools import float_is_zero
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
product_qty_pre_split = fields.Float(
digits="Product Unit of Measure",
string="Pre-split Original Qty",
readonly=True,
)
manually_split_from_line_id = fields.Many2one(
"purchase.order.line",
ondelete="restrict",
readonly=True,
)
manually_split_into_line_ids = fields.One2many(
"purchase.order.line",
"manually_split_from_line_id",
readonly=True,
)
def _unlink_except_purchase_or_done(self):
# OVERRIDE: this method is originally decorated with `api.ondelete()`,
# which makes Odoo trigger this method whenever a line is deleted, and
# will raise an error if the line's order is either 'done' or
# 'purchase'. However, this will make it impossible to merge PO lines
# when a manual picking is cancelled.
# While merging the split line into its original line, adding
# the `manually_split` flag will make sure everything will work
# correctly.
lines = self.filtered(lambda x: x.order_id.receipt_expectation != "manual")
return super(PurchaseOrderLine, lines)._unlink_except_purchase_or_done()
def _create_or_update_picking(self):
# OVERRIDE: the `purchase_stock` module introduces this method that
# is called whenever a PO line is created in a confirmed order, or
# when line's qty is changed in a confirmed order. This means that
# splitting a PO line from the wizard will call this method, that will
# create or update a picking which is not the one we're creating from
# the manual wizard. As a result, we'll find ourselves with unwanted
# data (a stock move qty might be changed, a new picking might be
# created, etc).
# While copying the old PO line to create the split line, adding
# the `manually_split` flag will make sure everything will work
# correctly.
lines = self.filtered(lambda x: x.order_id.receipt_expectation != "manual")
return super(PurchaseOrderLine, lines)._create_or_update_picking()
@api.depends("manually_split_from_line_id")
def _compute_feasible_for_manual_receipt(self):
# OVERRIDE: original line is feasible if delivery method is via stock
# moves; here, we'll also add the condition that the line should not
# have been split from another line
split = self.filtered("manually_split_from_line_id")
split.feasible_for_manual_receipt = False
return super(
PurchaseOrderLine, self - split
)._compute_feasible_for_manual_receipt()
def _split_purchase_line(self, copy_vals=None):
"""Splits purchase line in a new line"""
self.ensure_one()
copy_vals = dict(copy_vals or [])
# Before splitting: if the line has never been split before, set its
# current ordered qty as "pre-split qty"
if not self.manually_split_into_line_ids:
self.product_qty_pre_split = self.product_qty
# Copy the original line to a new line with wizard line data
new = self.copy(copy_vals)
# Remove the new line's qty from the original line's qty
to_remove = new.product_uom._compute_quantity(new.product_qty, self.product_uom)
self.product_qty = max(0, self.product_qty - to_remove)
return new
def _merge_back_into_original_line(self, quantity):
"""Reverts quantity from split lines to their origin lines"""
if not self.manually_split_from_line_id:
return
self.ensure_one()
origin = self.manually_split_from_line_id
origin.product_qty += self.product_uom._compute_quantity(
quantity, origin.product_uom
)
self.product_qty -= quantity
# Remove empty lines with no done moves attached
if float_is_zero(
self.product_qty, precision_rounding=self.product_uom.rounding
) and not any(move.state == "done" for move in self.move_ids):
self.unlink()
| 45.734043
| 4,299
|
658
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
class StockMove(models.Model):
_inherit = "stock.move"
def _action_cancel(self):
moves_to_cancel = self.filtered(lambda m: m.state != "cancel")
res = super()._action_cancel()
for move in moves_to_cancel:
if move.purchase_line_id:
move.purchase_line_id._merge_back_into_original_line(
move.product_uom._compute_quantity(
move.product_qty, move.purchase_line_id.product_uom
)
)
return res
| 32.9
| 658
|
1,352
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
class PurchaseOrderManualReceiptLine(models.TransientModel):
_inherit = "purchase.order.manual.receipt.wizard.line"
def _get_move_vals_list(self):
# OVERRIDE: we'll split the purchase line here, assign the new line
# to field `purchase_line_id`, and then call the `super` so that method
# `_get_move_vals()` will read data from the new split line instead
# of the original line
self._split_purchase_line()
return super()._get_move_vals_list()
def _split_purchase_line(self):
"""Splits purchase line in a new line"""
# Assign the new line to the wizard
for line in self:
line.purchase_line_id = line.purchase_line_id._split_purchase_line(
line._get_split_purchase_line_vals()
)
def _get_split_purchase_line_vals(self) -> dict:
"""Returns values to be assigned to the new split PO line"""
self.ensure_one()
return {
"manually_split_from_line_id": self.purchase_line_id.id,
"product_qty": self.qty,
"product_uom": self.uom_id.id,
"price_unit": self.unit_price,
"date_planned": self.wizard_id.scheduled_date,
}
| 38.628571
| 1,352
|
647
|
py
|
PYTHON
|
15.0
|
# © 2016 ForgeFlow S.L.
# (<http://www.forgeflow.com>)
# © 2018 Hizbul Bahar <hizbul25@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Purchase Location by Line",
"summary": "Allows to define a specific destination location on each PO line",
"version": "15.0.1.0.0",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/purchase-workflow",
"category": "Purchase Management",
"depends": ["purchase_stock", "purchase_delivery_split_date"],
"license": "AGPL-3",
"data": ["views/purchase_view.xml"],
"installable": True,
}
| 37.941176
| 645
|
8,881
|
py
|
PYTHON
|
15.0
|
# © 2016 ForgeFlow S.L.
# (<http://www.forgeflow.com>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
import time
from odoo.tests.common import TransactionCase
class TestDeliverySingle(TransactionCase):
def setUp(self):
super(TestDeliverySingle, self).setUp()
# Products
p1 = self.env.ref("product.product_product_13")
p2 = self.env.ref("product.product_product_25")
# Locations
self.l1 = self.env.ref("stock.stock_location_stock")
self.l2 = self.env["stock.location"].create(
{"location_id": self.l1.id, "name": "Shelf 1", "usage": "internal"}
)
# 2 dates we can use to test the features
self.date_sooner = time.strftime("%Y") + "-01-01"
self.date_later = time.strftime("%Y") + "-12-31"
self.po = self.env["purchase.order"].create(
{
"partner_id": self.ref("base.res_partner_3"),
"order_line": [
(
0,
0,
{
"product_id": p1.id,
"product_uom": p1.uom_id.id,
"name": p1.name,
"price_unit": p1.standard_price,
"date_planned": self.date_sooner,
"product_qty": 42.0,
"location_dest_id": self.l1.id,
},
),
(
0,
0,
{
"product_id": p2.id,
"product_uom": p1.uom_id.id,
"name": p2.name,
"price_unit": p2.standard_price,
"date_planned": self.date_sooner,
"product_qty": 12.0,
"location_dest_id": self.l1.id,
},
),
(
0,
0,
{
"product_id": p1.id,
"product_uom": p1.uom_id.id,
"name": p1.name,
"price_unit": p1.standard_price,
"date_planned": self.date_sooner,
"product_qty": 1.0,
"location_dest_id": self.l1.id,
},
),
],
}
)
def test_check_single_date(self):
self.assertEqual(
len(self.po.picking_ids),
0,
"There must not be pickings for the PO when draft",
)
self.po.button_confirm()
self.assertEqual(
len(self.po.picking_ids),
1,
"There must be 1 picking for the PO when confirmed",
)
self.assertEqual(
str(self.po.picking_ids[0].scheduled_date)[:10],
self.date_sooner,
"The picking must be planned at the expected date",
)
def test_check_multiple_dates(self):
# Change the date of the first line
self.po.order_line[0].date_planned = self.date_later
self.assertEqual(
len(self.po.picking_ids),
0,
"There must not be pickings for the PO when draft",
)
self.po.button_confirm()
len_pickings = len(self.po.picking_ids)
self.assertEqual(
len_pickings,
2,
"There must be 2 pickings for the PO when confirmed. %s found"
% len_pickings,
)
sorted_pickings = sorted(self.po.picking_ids, key=lambda x: x.scheduled_date)
self.assertEqual(
str(sorted_pickings[0].scheduled_date)[:10],
self.date_sooner,
"The first picking must be planned at the soonest date",
)
self.assertEqual(
str(sorted_pickings[1].scheduled_date)[:10],
self.date_later,
"The second picking must be planned at the latest date",
)
l2_picking = self.po.picking_ids.filtered(
lambda p: p.location_dest_id == self.l2
)
self.assertEqual(
len(l2_picking), 0, "There must be 0 picking for location Shelf 1"
)
l1_picking = self.po.picking_ids.filtered(
lambda p: p.location_dest_id == self.l1
)
self.assertEqual(
len(l1_picking), 2, "There must be 2 pickings for location Stock"
)
def test_check_multiple_locations_same_date(self):
# Change the location of the first line
self.po.order_line[0].location_dest_id = self.l2
self.assertEqual(
len(self.po.picking_ids),
0,
"There must not be pickings for the PO when draft",
)
self.po.button_confirm()
l2_picking = self.po.picking_ids.filtered(
lambda p: p.location_dest_id == self.l2
)
self.assertGreaterEqual(
len(l2_picking),
1,
"There must be 1 or more pickings for location Shelf 1",
)
l1_picking = self.po.picking_ids.filtered(
lambda p: p.location_dest_id == self.l1
)
self.assertGreaterEqual(
len(l1_picking),
1,
"There must be 1 or more pickings for location Stock",
)
def test_check_multiple_locations_multiple_dates(self):
# Change the location of the first line and date of the second line
self.po.order_line[0].location_dest_id = self.l2
self.po.order_line[1].date_planned = self.date_later
self.assertEqual(
len(self.po.picking_ids),
0,
"There must not be pickings for the PO when draft",
)
self.po.button_confirm()
l2_picking = self.po.picking_ids.filtered(
lambda p: p.location_dest_id == self.l2
)
self.assertGreaterEqual(
len(l2_picking), 1, "There must be 1 picking for location Shelf 1"
)
l1_picking = self.po.picking_ids.filtered(
lambda p: p.location_dest_id == self.l1
)
self.assertGreaterEqual(
len(l1_picking), 2, "There must be 2 or more pickings for location Stock"
)
sorted_pickings = sorted(self.po.picking_ids, key=lambda x: x.scheduled_date)
self.assertEqual(
str(sorted_pickings[0].scheduled_date)[:10],
self.date_sooner,
"The first picking must be planned at the soonest date",
)
self.assertEqual(
str(sorted_pickings[2].scheduled_date)[:10],
self.date_later,
"The second picking must be planned at the latest date",
)
def test_check_multiple_locations_multiple_dates_02(self):
# Leave some locations in the PO line empty
self.po.order_line[0].location_dest_id = self.l2
self.po.order_line[1].location_dest_id = False
self.po.order_line[2].location_dest_id = False
self.po.order_line[1].date_planned = self.date_later
self.assertEqual(
len(self.po.picking_ids),
0,
"There must not be pickings for the PO when draft",
)
self.po.button_confirm()
l2_picking = self.po.picking_ids.filtered(
lambda p: p.location_dest_id == self.l2
)
self.assertGreaterEqual(
len(l2_picking), 1, "There must be 1 picking for location Shelf 1"
)
default_location_picking = self.po.picking_ids.filtered(
lambda p: p.location_dest_id
== self.po.picking_type_id.default_location_dest_id
)
self.assertGreaterEqual(
len(default_location_picking),
2,
"There must be 2 or more pickings for the default location of the PO",
)
sorted_pickings = sorted(self.po.picking_ids, key=lambda x: x.scheduled_date)
self.assertEqual(
str(sorted_pickings[0].scheduled_date)[:10],
self.date_sooner,
"The first picking must be planned at the soonest date",
)
self.assertEqual(
str(sorted_pickings[2].scheduled_date)[:10],
self.date_later,
"The second picking must be planned at the latest date",
)
def test_modify_confirmed(self):
# if all moves contain the location no need to update
self.po.button_confirm()
self.po.order_line[0].write({"product_qty": 43})
self.assertEqual(
self.po.order_line[0].move_ids.mapped("location_dest_id"), self.l1
)
| 34.552529
| 8,880
|
2,874
|
py
|
PYTHON
|
15.0
|
# © 2016 ForgeFlow S.L.
# (<http://www.forgeflow.com>)
# © 2018 Hizbul Bahar <hizbul25@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
location_dest_id = fields.Many2one(
comodel_name="stock.location",
string="Destination",
domain=[("usage", "in", ["internal", "transit"])],
)
@api.model
def _first_picking_copy_vals(self, key, lines):
"""The data to be copied to new pickings is updated with data from the
grouping key. This method is designed for extensibility, so that
other modules can store more data based on new keys."""
vals = super(PurchaseOrderLine, self)._first_picking_copy_vals(key, lines)
for key_element in key:
if "location_dest_id" in key_element.keys():
vals["location_dest_id"] = key_element["location_dest_id"].id
return vals
@api.model
def _get_group_keys(self, order, line, picking=False):
"""Define the key that will be used to group. The key should be
defined as a tuple of dictionaries, with each element containing a
dictionary element with the field that you want to group by. This
method is designed for extensibility, so that other modules can add
additional keys or replace them by others."""
key = super(PurchaseOrderLine, self)._get_group_keys(
order, line, picking=picking
)
default_picking_location_id = line.order_id._get_destination_location()
default_picking_location = self.env["stock.location"].browse(
default_picking_location_id
)
location = line.location_dest_id or default_picking_location
return key + ({"location_dest_id": location},)
def _get_sorted_keys(self, line):
"""Return a tuple of keys to use in order to sort the order lines.
This method is designed for extensibility, so that other modules can
add additional keys or replace them by others."""
keys = super(PurchaseOrderLine, self)._get_sorted_keys(line)
return keys + (line.location_dest_id.id,)
def _create_stock_moves(self, picking):
res = super(PurchaseOrderLine, self)._create_stock_moves(picking)
for line in self:
default_picking_location_id = line.order_id._get_destination_location()
default_picking_location = self.env["stock.location"].browse(
default_picking_location_id
)
location = line.location_dest_id or default_picking_location
if location:
line.move_ids.filtered(lambda m: m.state != "done").write(
{"location_dest_id": location.id}
)
return res
| 44.184615
| 2,872
|
890
|
py
|
PYTHON
|
15.0
|
# © 2016 ForgeFlow S.L.
# (<http://www.forgeflow.com>)
# © 2018 Hizbul Bahar <hizbul25@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import models
class StockPicking(models.Model):
_inherit = "stock.picking"
def _update_picking_from_group_key(self, key):
"""The picking is updated with data from the grouping key.
This method is designed for extensibility, so that other modules
can store more data based on new keys."""
super(StockPicking, self)._update_picking_from_group_key(key)
for rec in self:
for key_element in key:
if (
"location_dest_id" in key_element.keys()
and key_element["location_dest_id"]
):
rec.location_dest_id = key_element["location_dest_id"]
return False
| 37
| 888
|
628
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2021 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html)
{
"name": "Purchase Advance Payment",
"version": "15.0.1.0.0",
"author": "Forgeflow, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/purchase-workflow",
"category": "Purchase",
"license": "AGPL-3",
"summary": "Allow to add advance payments on purchase orders",
"depends": ["purchase"],
"data": [
"wizard/purchase_advance_payment_wizard_view.xml",
"views/purchase_view.xml",
"security/ir.model.access.csv",
],
"installable": True,
}
| 33.052632
| 628
|
13,693
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2021 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html)
from odoo import fields
from odoo.exceptions import ValidationError
from odoo.tests import common
class TestPurchaseAdvancePayment(common.TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
# Partners
cls.res_partner_1 = cls.env["res.partner"].create({"name": "Wood Corner"})
cls.res_partner_address_1 = cls.env["res.partner"].create(
{"name": "Willie Burke", "parent_id": cls.res_partner_1.id}
)
cls.res_partner_2 = cls.env["res.partner"].create({"name": "Partner 12"})
# Products
cls.product_1 = cls.env["product.product"].create(
{"name": "Desk Combination", "type": "consu", "purchase_method": "purchase"}
)
cls.product_2 = cls.env["product.product"].create(
{"name": "Conference Chair", "type": "consu", "purchase_method": "purchase"}
)
cls.product_3 = cls.env["product.product"].create(
{
"name": "Repair Services",
"type": "service",
"purchase_method": "purchase",
}
)
cls.tax = cls.env["account.tax"].create(
{
"name": "Tax 20",
"type_tax_use": "purchase",
"amount": 20,
}
)
# purchase Order
cls.purchase_order_1 = cls.env["purchase.order"].create(
{"partner_id": cls.res_partner_1.id}
)
cls.order_line_1 = cls.env["purchase.order.line"].create(
{
"order_id": cls.purchase_order_1.id,
"product_id": cls.product_1.id,
"product_uom": cls.product_1.uom_id.id,
"product_qty": 10.0,
"price_unit": 100.0,
"taxes_id": cls.tax,
}
)
cls.order_line_2 = cls.env["purchase.order.line"].create(
{
"order_id": cls.purchase_order_1.id,
"product_id": cls.product_2.id,
"product_uom": cls.product_2.uom_id.id,
"product_qty": 25.0,
"price_unit": 40.0,
"taxes_id": cls.tax,
}
)
cls.order_line_3 = cls.env["purchase.order.line"].create(
{
"order_id": cls.purchase_order_1.id,
"product_id": cls.product_3.id,
"product_uom": cls.product_3.uom_id.id,
"product_qty": 20.0,
"price_unit": 50.0,
"taxes_id": cls.tax,
}
)
cls.active_euro = False
cls.currency_euro = (
cls.env["res.currency"]
.with_context(active_test=False)
.search([("name", "=", "EUR")])
)
# active euro currency if inactive for test
if not cls.currency_euro.active:
cls.currency_euro.active = True
cls.active_euro = True
cls.currency_usd = cls.env["res.currency"].search([("name", "=", "USD")])
cls.currency_rate = cls.env["res.currency.rate"].create(
{
"rate": 1.20,
"currency_id": cls.currency_usd.id,
}
)
cls.journal_eur_bank = cls.env["account.journal"].create(
{
"name": "Journal Euro Bank",
"type": "bank",
"code": "111",
"currency_id": cls.currency_euro.id,
}
)
cls.journal_usd_bank = cls.env["account.journal"].create(
{
"name": "Journal USD Bank",
"type": "bank",
"code": "222",
"currency_id": cls.currency_usd.id,
}
)
cls.journal_eur_cash = cls.env["account.journal"].create(
{
"name": "Journal Euro Cash",
"type": "cash",
"code": "333",
"currency_id": cls.currency_euro.id,
}
)
cls.journal_usd_cash = cls.env["account.journal"].create(
{
"name": "Journal USD Cash",
"type": "cash",
"code": "444",
"currency_id": cls.currency_usd.id,
}
)
def test_01_purchase_advance_payment(self):
self.assertEqual(
self.purchase_order_1.amount_residual,
3600,
)
self.assertEqual(
self.purchase_order_1.amount_residual,
self.purchase_order_1.amount_total,
"Amounts should match",
)
context_payment = {
"active_ids": [self.purchase_order_1.id],
"active_id": self.purchase_order_1.id,
}
# Check residual > advance payment and the comparison takes
# into account the currency. 3001*1.2 > 3600
with self.assertRaises(ValidationError):
advance_payment_0 = (
self.env["account.voucher.wizard.purchase"]
.with_context(**context_payment)
.create(
{
"journal_id": self.journal_eur_bank.id,
"amount_advance": 3001,
"order_id": self.purchase_order_1.id,
}
)
)
advance_payment_0.make_advance_payment()
# Create Advance Payment 1 - EUR - bank
advance_payment_1 = (
self.env["account.voucher.wizard.purchase"]
.with_context(**context_payment)
.create(
{
"journal_id": self.journal_eur_bank.id,
"amount_advance": 100,
"order_id": self.purchase_order_1.id,
}
)
)
advance_payment_1.make_advance_payment()
self.assertEqual(self.purchase_order_1.amount_residual, 3480)
# Create Advance Payment 2 - USD - cash
advance_payment_2 = (
self.env["account.voucher.wizard.purchase"]
.with_context(**context_payment)
.create(
{
"journal_id": self.journal_usd_cash.id,
"amount_advance": 200,
"order_id": self.purchase_order_1.id,
}
)
)
advance_payment_2.make_advance_payment()
self.assertEqual(self.purchase_order_1.amount_residual, 3280)
# Confirm Purchase Order
self.purchase_order_1.button_confirm()
# Create Advance Payment 3 - EUR - cash
advance_payment_3 = (
self.env["account.voucher.wizard.purchase"]
.with_context(**context_payment)
.create(
{
"journal_id": self.journal_eur_cash.id,
"amount_advance": 250,
"order_id": self.purchase_order_1.id,
}
)
)
advance_payment_3.make_advance_payment()
self.assertEqual(self.purchase_order_1.amount_residual, 2980)
# Create Advance Payment 4 - USD - bank
advance_payment_4 = (
self.env["account.voucher.wizard.purchase"]
.with_context(**context_payment)
.create(
{
"journal_id": self.journal_usd_bank.id,
"amount_advance": 400,
"order_id": self.purchase_order_1.id,
}
)
)
advance_payment_4.make_advance_payment()
self.assertEqual(self.purchase_order_1.amount_residual, 2580)
def test_02_residual_amount_with_bill(self):
self.assertEqual(
self.purchase_order_1.amount_residual,
3600,
)
self.assertEqual(
self.purchase_order_1.amount_residual,
self.purchase_order_1.amount_total,
)
# Create Advance Payment 1 - EUR - bank
context_payment = {
"active_ids": [self.purchase_order_1.id],
"active_id": self.purchase_order_1.id,
}
# Create Advance Payment 2 - USD - cash
advance_payment_2 = (
self.env["account.voucher.wizard.purchase"]
.with_context(**context_payment)
.create(
{
"journal_id": self.journal_usd_cash.id,
"amount_advance": 200,
"order_id": self.purchase_order_1.id,
}
)
)
advance_payment_2.make_advance_payment()
pre_payment = self.purchase_order_1.account_payment_ids
self.assertEqual(len(pre_payment), 1)
self.assertEqual(self.purchase_order_1.amount_residual, 3400)
# generate bill, pay bill, check amount residual.
self.purchase_order_1.button_confirm()
self.assertEqual(self.purchase_order_1.invoice_status, "to invoice")
self.purchase_order_1.action_create_invoice()
self.assertEqual(self.purchase_order_1.invoice_status, "invoiced")
self.assertEqual(self.purchase_order_1.amount_residual, 3400)
invoice = self.purchase_order_1.invoice_ids
invoice.invoice_date = fields.Date.today()
invoice.action_post()
active_ids = invoice.ids
self.env["account.payment.register"].with_context(
active_model="account.move", active_ids=active_ids
).create(
{
"amount": 1200.0,
"group_payment": True,
"payment_difference_handling": "open",
}
)._create_payments()
self.assertEqual(self.purchase_order_1.amount_residual, 2200)
# Reconciling the pre-payment should not affect amount_residual in PO.
(
liquidity_lines,
counterpart_lines,
writeoff_lines,
) = pre_payment._seek_for_lines()
(
counterpart_lines
+ invoice.line_ids.filtered(
lambda line: line.account_internal_type == "payable"
)
).reconcile()
self.purchase_order_1.invalidate_cache()
self.assertEqual(self.purchase_order_1.amount_residual, 2200)
def test_03_residual_amount_big_pre_payment(self):
self.assertEqual(
self.purchase_order_1.amount_residual,
3600,
)
self.assertEqual(
self.purchase_order_1.amount_residual,
self.purchase_order_1.amount_total,
)
# Create Advance Payment 1 - EUR - bank
context_payment = {
"active_ids": [self.purchase_order_1.id],
"active_id": self.purchase_order_1.id,
}
# Create Advance Payment 2 - USD - cash
advance_payment_2 = (
self.env["account.voucher.wizard.purchase"]
.with_context(**context_payment)
.create(
{
"journal_id": self.journal_usd_cash.id,
"amount_advance": 2000,
"order_id": self.purchase_order_1.id,
}
)
)
advance_payment_2.make_advance_payment()
pre_payment = self.purchase_order_1.account_payment_ids
self.assertEqual(len(pre_payment), 1)
self.assertEqual(self.purchase_order_1.amount_residual, 1600)
# generate a partial bill, reconcile with pre payment, check amount residual.
self.purchase_order_1.button_confirm()
self.assertEqual(self.purchase_order_1.invoice_status, "to invoice")
# Adjust billing method to then do a partial bill with a total amount
# smaller than the pre-payment.
self.product_1.purchase_method = "receive"
self.order_line_1.qty_received = 10.0
self.assertEqual(self.order_line_1.qty_to_invoice, 10.0)
self.product_2.purchase_method = "receive"
self.order_line_2.qty_received = 0.0
self.assertEqual(self.order_line_2.qty_to_invoice, 0.0)
self.product_3.purchase_method = "receive"
self.order_line_3.qty_received = 0.0
self.assertEqual(self.order_line_3.qty_to_invoice, 0.0)
self.purchase_order_1.action_create_invoice()
self.assertEqual(self.purchase_order_1.invoice_status, "invoiced")
self.assertEqual(self.purchase_order_1.amount_residual, 1600)
invoice = self.purchase_order_1.invoice_ids
invoice.invoice_date = fields.Date.today()
invoice.action_post()
self.assertEqual(invoice.amount_residual, 1200)
active_ids = invoice.ids
self.env["account.payment.register"].with_context(
active_model="account.move", active_ids=active_ids
).create(
{
"amount": 300.0,
"group_payment": True,
"payment_difference_handling": "open",
}
)._create_payments()
self.assertEqual(invoice.amount_residual, 900)
self.assertEqual(self.purchase_order_1.amount_residual, 1300)
# Partially reconciling the pre-payment should not affect amount_residual in PO.
(
liquidity_lines,
counterpart_lines,
writeoff_lines,
) = pre_payment._seek_for_lines()
(
counterpart_lines
+ invoice.line_ids.filtered(
lambda line: line.account_internal_type == "payable"
)
).reconcile()
self.purchase_order_1.invalidate_cache()
self.assertEqual(self.purchase_order_1.amount_residual, 1300)
| 36.710456
| 13,693
|
4,616
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2021 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html)
from odoo import _, api, exceptions, fields, models
class AccountVoucherWizardPurchase(models.TransientModel):
_name = "account.voucher.wizard.purchase"
_description = "Account Voucher Wizard Purchase"
order_id = fields.Many2one("purchase.order", required=True)
journal_id = fields.Many2one(
"account.journal",
"Journal",
required=True,
domain=[("type", "in", ("bank", "cash"))],
)
journal_currency_id = fields.Many2one(
"res.currency",
"Journal Currency",
store=True,
readonly=False,
compute="_compute_get_journal_currency",
)
currency_id = fields.Many2one("res.currency", "Currency", readonly=True)
amount_total = fields.Monetary(readonly=True)
amount_advance = fields.Monetary(
"Amount advanced", required=True, currency_field="journal_currency_id"
)
date = fields.Date(required=True, default=fields.Date.context_today)
currency_amount = fields.Monetary(
"Curr. amount",
readonly=True,
currency_field="currency_id",
compute="_compute_currency_amount",
store=True,
)
payment_ref = fields.Char("Ref.")
@api.depends("journal_id")
def _compute_get_journal_currency(self):
for wzd in self:
wzd.journal_currency_id = (
wzd.journal_id.currency_id.id or self.env.user.company_id.currency_id.id
)
@api.constrains("amount_advance")
def check_amount(self):
if self.journal_currency_id.compare_amounts(self.amount_advance, 0.0) <= 0:
raise exceptions.ValidationError(_("Amount of advance must be positive."))
if self.env.context.get("active_id", False):
if (
self.currency_id.compare_amounts(
self.currency_amount, self.order_id.amount_residual
)
> 0
):
raise exceptions.ValidationError(
_("Amount of advance is greater than residual amount on purchase")
)
@api.model
def default_get(self, fields_list):
res = super().default_get(fields_list)
purchase_ids = self.env.context.get("active_ids", [])
if not purchase_ids:
return res
purchase_id = fields.first(purchase_ids)
purchase = self.env["purchase.order"].browse(purchase_id)
if "amount_total" in fields_list:
res.update(
{
"order_id": purchase.id,
"amount_total": purchase.amount_residual,
"currency_id": purchase.currency_id.id,
}
)
return res
@api.depends("journal_id", "date", "amount_advance")
def _compute_currency_amount(self):
if self.journal_currency_id != self.currency_id:
amount_advance = self.journal_currency_id._convert(
self.amount_advance,
self.currency_id,
self.order_id.company_id,
self.date or fields.Date.today(),
)
else:
amount_advance = self.amount_advance
self.currency_amount = amount_advance
def _prepare_payment_vals(self, purchase):
partner_id = purchase.partner_id.id
return {
"date": self.date,
"amount": self.amount_advance,
"payment_type": "outbound",
"partner_type": "supplier",
"ref": self.payment_ref or purchase.name,
"journal_id": self.journal_id.id,
"currency_id": self.journal_currency_id.id,
"partner_id": partner_id,
"payment_method_id": self.env.ref(
"account.account_payment_method_manual_out"
).id,
}
def make_advance_payment(self):
"""Create customer paylines and validates the payment"""
self.ensure_one()
payment_obj = self.env["account.payment"]
purchase_obj = self.env["purchase.order"]
purchase_ids = self.env.context.get("active_ids", [])
if purchase_ids:
purchase_id = fields.first(purchase_ids)
purchase = purchase_obj.browse(purchase_id)
payment_vals = self._prepare_payment_vals(purchase)
payment = payment_obj.create(payment_vals)
purchase.account_payment_ids |= payment
payment.action_post()
return {
"type": "ir.actions.act_window_close",
}
| 36.346457
| 4,616
|
3,818
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2021 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html)
from odoo import api, fields, models
from odoo.tools import float_compare
class PurchaseOrder(models.Model):
_inherit = "purchase.order"
account_payment_ids = fields.One2many(
"account.payment", "purchase_id", string="Pay purchase advanced", readonly=True
)
amount_residual = fields.Float(
"Residual amount",
readonly=True,
compute="_compute_purchase_advance_payment",
store=True,
)
payment_line_ids = fields.Many2many(
"account.move.line",
string="Payment move lines",
compute="_compute_purchase_advance_payment",
store=True,
)
advance_payment_status = fields.Selection(
selection=[
("not_paid", "Not Paid"),
("paid", "Paid"),
("partial", "Partially Paid"),
],
store=True,
readonly=True,
copy=False,
tracking=True,
compute="_compute_purchase_advance_payment",
)
@api.depends(
"currency_id",
"company_id",
"amount_total",
"account_payment_ids",
"account_payment_ids.state",
"account_payment_ids.move_id",
"account_payment_ids.move_id.line_ids",
"account_payment_ids.move_id.line_ids.date",
"account_payment_ids.move_id.line_ids.debit",
"account_payment_ids.move_id.line_ids.credit",
"account_payment_ids.move_id.line_ids.currency_id",
"account_payment_ids.move_id.line_ids.amount_currency",
"order_line.invoice_lines.move_id",
"order_line.invoice_lines.move_id.amount_total",
"order_line.invoice_lines.move_id.amount_residual",
)
def _compute_purchase_advance_payment(self):
for order in self:
mls = order.account_payment_ids.mapped("move_id.line_ids").filtered(
lambda x: x.account_id.internal_type == "payable"
and x.parent_state == "posted"
)
advance_amount = 0.0
for line in mls:
line_currency = line.currency_id or line.company_id.currency_id
# Exclude reconciled pre-payments amount because once reconciled
# the pre-payment will reduce bill residual amount like any
# other payment.
line_amount = (
line.amount_residual_currency
if line.currency_id
else line.amount_residual
)
if line_currency != order.currency_id:
advance_amount += line.currency_id._convert(
line_amount,
order.currency_id,
order.company_id,
line.date or fields.Date.today(),
)
else:
advance_amount += line_amount
# Consider payments in related invoices.
invoice_paid_amount = 0.0
for inv in order.invoice_ids:
invoice_paid_amount += inv.amount_total - inv.amount_residual
amount_residual = order.amount_total - advance_amount - invoice_paid_amount
payment_state = "not_paid"
if mls or order.invoice_ids:
has_due_amount = float_compare(
amount_residual, 0.0, precision_rounding=order.currency_id.rounding
)
if has_due_amount <= 0:
payment_state = "paid"
elif has_due_amount > 0:
payment_state = "partial"
order.payment_line_ids = mls
order.amount_residual = amount_residual
order.advance_payment_status = payment_state
| 38.565657
| 3,818
|
370
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2021 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html)
from odoo import fields, models
class AccountPayment(models.Model):
_inherit = "account.payment"
purchase_id = fields.Many2one(
"purchase.order",
"Purchase",
readonly=True,
states={"draft": [("readonly", False)]},
)
| 23.125
| 370
|
633
|
py
|
PYTHON
|
15.0
|
# Copyright 2015-17 ForgeFlow S.L.
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
{
"name": "Purchase Order Analytic Search",
"summary": """Search purchase orders by analytic account. New menu entry in
Purchasing to list purchase order lines.""",
"version": "15.0.1.0.0",
"website": "https://github.com/OCA/purchase-workflow",
"category": "Purchase Workflow",
"author": "ForgeFlow, Camptocamp, Odoo Community Association (OCA)",
"license": "LGPL-3",
"installable": True,
"depends": ["analytic", "purchase"],
"data": ["views/purchase_order_view.xml"],
}
| 39.5625
| 633
|
6,282
|
py
|
PYTHON
|
15.0
|
# Copyright 2015-17 ForgeFlow S.L.
# Copyright 2018 Camptocamp
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo.fields import Datetime
from odoo.tests.common import TransactionCase
class TestAnalyticSearch(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestAnalyticSearch, cls).setUpClass()
# purchase_order
cls.purchase_order_model = cls.env["purchase.order"]
partner_model = cls.env["res.partner"]
prod_model = cls.env["product.product"]
analytic_account_model = cls.env["account.analytic.account"]
pa_dict = {
"name": "Partner 1",
}
cls.partner = partner_model.create(pa_dict)
uom_id = cls.env.ref("uom.product_uom_unit").id
pr_dict = {
"name": "Product Test",
"uom_id": uom_id,
}
cls.product = prod_model.create(pr_dict)
ac_dict = {
"name": "account 1",
}
cls.analytic_account_1 = analytic_account_model.create(ac_dict)
ac_dict = {
"name": "dummyname",
}
cls.analytic_account_2 = analytic_account_model.create(ac_dict)
# PURCHASE ORDER NUM 1 => account 1
po_dict = {
"partner_id": cls.partner.id,
"order_line": [
(
0,
0,
{
"date_planned": Datetime.now(),
"name": "PO01",
"product_id": cls.product.id,
"product_uom": uom_id,
"price_unit": 1,
"product_qty": 5.0,
"account_analytic_id": cls.analytic_account_1.id,
},
),
(
0,
0,
{
"date_planned": Datetime.now(),
"name": "PO01",
"product_id": cls.product.id,
"product_uom": uom_id,
"price_unit": 1,
"product_qty": 5.0,
"account_analytic_id": cls.analytic_account_1.id,
},
),
],
}
cls.purchase_order_1 = cls.purchase_order_model.create(po_dict)
# PURCHASE ORDER NUM 2 => account 1 and 2
pa_dict2 = {
"name": "Partner 2",
}
cls.partner2 = partner_model.create(pa_dict2)
po_dict2 = {
"partner_id": cls.partner2.id,
"order_line": [
(
0,
0,
{
"date_planned": Datetime.now(),
"name": "PO01",
"product_id": cls.product.id,
"product_uom": uom_id,
"price_unit": 1,
"product_qty": 5.0,
"account_analytic_id": cls.analytic_account_1.id,
},
),
(
0,
0,
{
"date_planned": Datetime.now(),
"name": "PO01",
"product_id": cls.product.id,
"product_uom": uom_id,
"price_unit": 1,
"product_qty": 5.0,
"account_analytic_id": cls.analytic_account_2.id,
},
),
],
}
cls.purchase_order_2 = cls.purchase_order_model.create(po_dict2)
# PURCHASE ORDER NUM 3 => account 2
po_dict3 = {
"partner_id": cls.partner2.id,
"order_line": [
(
0,
0,
{
"date_planned": Datetime.now(),
"name": "PO01",
"product_id": cls.product.id,
"product_uom": uom_id,
"price_unit": 1,
"product_qty": 5.0,
"account_analytic_id": cls.analytic_account_2.id,
},
),
(
0,
0,
{
"date_planned": Datetime.now(),
"name": "PO01",
"product_id": cls.product.id,
"product_uom": uom_id,
"price_unit": 1,
"product_qty": 5.0,
"account_analytic_id": cls.analytic_account_2.id,
},
),
],
}
cls.purchase_order_3 = cls.purchase_order_model.create(po_dict3)
def test_filter_analytic_accounts(self):
found = self.purchase_order_model.search(
[("account_analytic_ids", "=", self.analytic_account_1.id)]
)
self.assertEqual(found, self.purchase_order_1 + self.purchase_order_2)
def test_filter_analytic_accounts_by_name(self):
found = self.purchase_order_model.search(
[("account_analytic_ids", "=", "nt 1")]
)
self.assertEqual(found, self.purchase_order_1 + self.purchase_order_2)
def test_filter_analytic_accounts_not_equal(self):
found = self.purchase_order_model.search(
[("account_analytic_ids", "!=", self.analytic_account_1.id)]
)
self.assertTrue(self.purchase_order_3 in found)
self.assertTrue(self.purchase_order_1 not in found)
self.assertTrue(self.purchase_order_2 not in found)
def test_compute_analytic_accounts(self):
self.assertEqual(
self.purchase_order_1.account_analytic_ids, self.analytic_account_1
)
self.assertEqual(
self.purchase_order_2.account_analytic_ids,
self.analytic_account_1 + self.analytic_account_2,
)
def test_filter_purchase_with_no_analytic_account(self):
found = self.purchase_order_model.search([("account_analytic_ids", "=", False)])
self.assertTrue(found)
| 36.736842
| 6,282
|
1,864
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 ForgeFlow S.L.
# Copyright 2018 Camptocamp
# 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.account_analytic_id")
def _compute_analytic_accounts(self):
for purchase in self:
purchase.account_analytic_ids = purchase.mapped(
"order_line.account_analytic_id"
)
@api.model
def _search_analytic_accounts(self, operator, value):
po_line_obj = self.env["purchase.order.line"].filtered(
lambda x: x.account_analytic_id == value
)
if not value:
return [("account_analytic_id", "=", False)]
if isinstance(value, (tuple, list)):
# we are searching on a list of ids
domain = [("order_id", "!=", False), ("account_analytic_id", "in", value)]
else:
if isinstance(value, int):
# we are searching on the id of the analytic_account
domain = [
("account_analytic_id", "=", value),
]
else:
# assume we are searching on the analytic account name
domain = [
("account_analytic_id.name", "ilike", value),
]
po_lines = po_line_obj.search(domain)
orders = po_lines.mapped("order_id")
if operator in ("!=", "not in"):
return [("id", "not in", orders.ids)]
else:
return [("id", "in", orders.ids)]
account_analytic_ids = fields.Many2many(
comodel_name="account.analytic.account",
string="Analytic Account(s)",
compute="_compute_analytic_accounts",
search="_search_analytic_accounts",
readonly=True,
)
| 35.169811
| 1,864
|
571
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2022 Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Purchase Order No Zero Price",
"version": "15.0.1.0.0",
"author": "Open Source Integrators, Odoo Community Association (OCA)",
"summary": "Prevent zero price lines on Purchase Orders",
"website": "https://github.com/OCA/purchase-workflow",
"license": "AGPL-3",
"depends": ["purchase"],
"category": "Purchase",
"data": [],
"installable": True,
"maintainer": ["dreispt"],
"development_status": "Beta",
}
| 33.588235
| 571
|
1,948
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2022 Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import time
from odoo.exceptions import UserError
from odoo.tests import common
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
class TestPurchaseOrderNoZeroPrice(common.TransactionCase):
def setUp(self):
super(TestPurchaseOrderNoZeroPrice, self).setUp()
self.PurchaseOrder = self.env["purchase.order"]
# Partner
self.partner1 = self.env.ref("base.res_partner_1")
# Products
self.product1 = self.env.ref("product.product_product_7")
self.purchase_order1 = self.PurchaseOrder.create(
{
"partner_id": self.partner1.id,
"order_line": [
(
0,
0,
{
"name": self.product1.name,
"product_id": self.product1.id,
"product_qty": 50,
"product_uom": self.product1.uom_id.id,
"price_unit": 10.0,
"date_planned": time.strftime(
DEFAULT_SERVER_DATETIME_FORMAT
),
},
)
],
}
)
self.purchase_order2 = self.purchase_order1.copy()
def test_check_price_unit_zero(self):
self.assertEqual(self.purchase_order1.state, "draft")
self.purchase_order1.button_confirm()
self.assertEqual(self.purchase_order1.state, "purchase")
self.assertEqual(self.purchase_order2.state, "draft")
with self.assertRaises(UserError):
self.purchase_order2.order_line.write({"price_unit": 0.0})
self.purchase_order2.button_confirm()
self.assertEqual(self.purchase_order2.state, "draft")
| 36.754717
| 1,948
|
1,132
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2022 Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, exceptions, models
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
@api.constrains("price_unit", "display_type", "state")
def _check_price_unit_zero(self):
# Prevent zero prices on confirmed POs
# to help ensure proper Stock Valuation
# when receiving the products
# Also supports `purchase_triple_discount` module
no_price_lines = self.filtered(
lambda x: not x.display_type
and x.state not in ["draft", "done", "cancel"]
and not x.price_unit
# Allow zero price for 100% discounts:
and getattr(x, "discount", 0.0) != 100.0
and getattr(x, "discount2", 0.0) != 100.0
and getattr(x, "discount3", 0.0) != 100.0
)
if no_price_lines:
raise exceptions.UserError(
_("Missing unit price for Products: %s")
% ", ".join(no_price_lines.product_id.mapped("display_name"))
)
| 39.034483
| 1,132
|
527
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Tecnativa - Carlos Dauden
# Copyright 2018 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Purchase stock price unit sync",
"summary": "Update cost price in stock moves already done",
"version": "15.0.1.0.1",
"category": "Purchase",
"website": "https://github.com/OCA/purchase-workflow",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"depends": ["purchase_stock"],
}
| 37.642857
| 527
|
2,080
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Carlos Dauden
# Copyright 2019 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields
from odoo.tests.common import TransactionCase
class TestProductCostPriceAvcoSync(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.partner = cls.env["res.partner"].create({"name": "Test Partner"})
cls.product_category = cls.env["product.category"].create(
{
"name": "Category property_cost_method average",
"property_cost_method": "average",
}
)
cls.product = cls.env["product.product"].create(
{
"name": "Product for test",
"type": "product",
"tracking": "none",
"categ_id": cls.product_category.id,
"standard_price": 1,
}
)
cls.order = cls.env["purchase.order"].create(
{
"partner_id": cls.partner.id,
"order_line": [
(
0,
0,
{
"name": "Test line",
"product_qty": 10.0,
"product_id": cls.product.id,
"product_uom": cls.product.uom_id.id,
"date_planned": fields.Date.today(),
"price_unit": 8.0,
},
),
],
}
)
def test_sync_cost_price(self):
self.order.button_confirm()
picking = self.order.picking_ids[:1]
move = picking.move_lines[:1]
move.quantity_done = move.product_uom_qty
picking._action_done()
self.assertAlmostEqual(move.stock_valuation_layer_ids[:1].unit_cost, 8.0, 2)
self.order.order_line[:1].price_unit = 6.0
self.assertAlmostEqual(move.stock_valuation_layer_ids[:1].unit_cost, 6.0, 2)
| 36.491228
| 2,080
|
1,638
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Carlos Dauden
# Copyright 2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import models
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
def write(self, vals):
res = super().write(vals)
if ("price_unit" in vals or "discount" in vals) and (
not self.env.context.get("skip_stock_price_unit_sync")
):
self.stock_price_unit_sync()
return res
def stock_price_unit_sync(self):
for line in self.filtered(lambda l: l.state in ["purchase", "done"]):
# When the affected product is a kit we do nothing, which is the
# default behavior on the standard: the move is exploded into moves
# for the components and those get the default price_unit for the
# time being. We avoid a hard dependency as well.
if hasattr(line.product_id, "bom_ids") and self.env[
"mrp.bom"
].sudo()._bom_find(
product=line.product_id,
company_id=line.company_id.id,
bom_type="phantom",
):
continue
line.move_ids.mapped("stock_valuation_layer_ids").filtered(
# Filter children SVLs (like landed cost)
lambda x: not x.stock_valuation_layer_id
).write(
{
"unit_cost": line.with_context(
skip_stock_price_unit_sync=True
)._get_stock_move_price_unit(),
}
)
| 38.952381
| 1,636
|
728
|
py
|
PYTHON
|
15.0
|
# © 2021 Solvos Consultoría Informática (<http://www.solvos.es>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Purchase Order Type Dashboard",
"version": "15.0.1.0.0",
"author": "Solvos, Odoo Community Association (OCA)",
"license": "AGPL-3",
"category": "Purchase Management",
"depends": ["purchase_order_type"],
"website": "https://github.com/OCA/purchase-workflow",
"data": [
"views/view_purchase_order.xml",
"views/view_purchase_order_type.xml",
"views/menu_purchase_order.xml",
],
"demo": ["demo/purchase_order_type_dashboard.xml"],
"maintainers": ["dalonsod"],
"installable": True,
"auto_install": False,
}
| 34.52381
| 725
|
2,428
|
py
|
PYTHON
|
15.0
|
# © 2021 Solvos Consultoría Informática (<http://www.solvos.es>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
import time
from odoo.tests import common, tagged
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
@tagged("post_install", "-at_install")
class TestPurchaseOrderTypeDashboard(common.TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.po_obj = cls.env["purchase.order"]
# Partner
cls.partner1 = cls.env.ref("base.res_partner_1")
# Products
cls.product1 = cls.env.ref("product.product_product_7")
cls.product2 = cls.env.ref("product.product_product_9")
cls.product3 = cls.env.ref("product.product_product_11")
# Purchase Type
cls.type1 = cls.env.ref("purchase_order_type.po_type_regular")
def test_purchase_order_type_dashboard(self):
po_type1_rfq_count = self.type1.state_rfq_po_count
purchase = self._create_purchase(
[(self.product1, 1), (self.product2, 5), (self.product3, 8)]
)
self.assertEqual(self.type1.state_rfq_po_count, po_type1_rfq_count + 1)
purchase.button_confirm()
po_type1_is_no_count = self.type1.invoice_status_no_po_count
po_type1_is_ti_count = self.type1.invoice_status_ti_po_count
purchase.order_line[0].qty_received = 1.0
self.assertEqual(
self.type1.invoice_status_no_po_count, po_type1_is_no_count - 1
)
self.assertEqual(
self.type1.invoice_status_ti_po_count, po_type1_is_ti_count + 1
)
def _create_purchase(self, line_products):
"""Create a purchase order.
``line_products`` is a list of tuple [(product, qty)]
"""
lines = []
for product, qty in line_products:
line_values = {
"name": product.name,
"product_id": product.id,
"product_qty": qty,
"product_uom": product.uom_id.id,
"price_unit": 100,
"date_planned": time.strftime(DEFAULT_SERVER_DATETIME_FORMAT),
}
lines.append((0, 0, line_values))
purchase = self.po_obj.create(
{
"partner_id": self.partner1.id,
"order_type": self.type1.id,
"order_line": lines,
}
)
return purchase
| 37.307692
| 2,425
|
2,024
|
py
|
PYTHON
|
15.0
|
# © 2021 Solvos Consultoría Informática (<http://www.solvos.es>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class PurchaseOrderType(models.Model):
_inherit = "purchase.order.type"
purchase_order_ids = fields.One2many(
comodel_name="purchase.order",
inverse_name="order_type",
string="Purchase Orders",
)
state_rfq_po_count = fields.Integer(string="RFQs", compute="_compute_po_counts")
invoice_status_no_po_count = fields.Integer(
string="Nothing to Bill", compute="_compute_po_counts"
)
invoice_status_ti_po_count = fields.Integer(
string="Waiting Bills", compute="_compute_po_counts"
)
@api.depends(
"purchase_order_ids",
"purchase_order_ids.state",
"purchase_order_ids.invoice_status",
)
def _compute_po_counts(self):
rfq_states = ("draft", "sent", "to approve")
po_states = ("purchase", "done")
PurchaseOrder = self.env["purchase.order"]
fetch_data = PurchaseOrder.read_group(
[("order_type", "in", self.ids)],
["order_type", "state", "invoice_status"],
["order_type", "state", "invoice_status"],
lazy=False,
)
result = [
[
data["order_type"][0],
data["state"],
data["invoice_status"],
data["__count"],
]
for data in fetch_data
]
for order in self:
order.state_rfq_po_count = sum(
r[3] for r in result if r[0] == order.id and r[1] in rfq_states
)
order.invoice_status_no_po_count = sum(
r[3]
for r in result
if r[0] == order.id and r[1] in po_states and r[2] == "no"
)
order.invoice_status_ti_po_count = sum(
r[3] for r in result if r[0] == order.id and r[2] == "to invoice"
)
| 34.844828
| 2,021
|
666
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Ecosoft (<http://ecosoft.co.th>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Purchase Request Sub State",
"version": "15.0.1.0.0",
"category": "Tools",
"author": "Ecosoft,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/purchase-workflow",
"license": "AGPL-3",
"depends": ["base_substate", "purchase_request"],
"data": [
"views/purchase_request_views.xml",
"data/purchase_substate_mail_template_data.xml",
"data/purchase_request_substate_data.xml",
],
"demo": ["demo/purchase_request_substate_demo.xml"],
"installable": True,
}
| 35.052632
| 666
|
2,462
|
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 SUPERUSER_ID
from odoo.exceptions import ValidationError
from odoo.tests.common import TransactionCase
class TestBaseSubstate(TransactionCase):
def setUp(self):
super(TestBaseSubstate, self).setUp()
# Prepare PR
self.purchase_request_obj = self.env["purchase.request"]
self.purchase_request_line_obj = self.env["purchase.request.line"]
self.wiz = self.env["purchase.request.line.make.purchase.order"]
vals = {
"picking_type_id": self.env.ref("stock.picking_type_in").id,
"requested_by": SUPERUSER_ID,
}
self.pr_test = self.purchase_request_obj.create(vals)
vals = {
"request_id": self.pr_test.id,
"product_id": self.env.ref("product.product_product_13").id,
"product_uom_id": self.env.ref("uom.product_uom_unit").id,
"product_qty": 5.0,
}
self.purchase_request_line_obj.create(vals)
# Prepare states
self.substate_to_verify = self.env.ref(
"purchase_request_substate.base_substate_to_verify"
)
self.substate_checked = self.env.ref(
"purchase_request_substate.base_substate_checked"
)
self.substate_verified = self.env.ref(
"purchase_request_substate.base_substate_verified"
)
# Active substate
(
self.substate_to_verify + self.substate_checked + self.substate_verified
).active = True
def test_purchase_request_order_substate(self):
self.assertTrue(self.pr_test.state == "draft")
self.assertTrue(not self.pr_test.substate_id)
# Block substate not corresponding to draft state
with self.assertRaises(ValidationError):
self.pr_test.substate_id = self.substate_to_verify
# Test that validation of purchase_request order change substate_id
self.pr_test.button_to_approve()
self.assertTrue(self.pr_test.state == "to_approve")
self.assertTrue(self.pr_test.substate_id == self.substate_to_verify)
# Test that substate_id is set to false if
# there is not substate corresponding to state
self.pr_test.button_approved()
self.assertTrue(self.pr_test.state == "approved")
self.assertTrue(not self.pr_test.substate_id)
| 41.728814
| 2,462
|
532
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 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.request", "Purchase request")],
ondelete={"purchase.request": "cascade"},
)
class PurchaseRequest(models.Model):
_inherit = ["purchase.request", "base.substate.mixin"]
_name = "purchase.request"
_state_field = "state"
| 28
| 532
|
497
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Carlos Dauden
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
{
"name": "Procurement Purchase Service No Grouping",
"version": "15.0.1.0.0",
"author": "Tecnativa," "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/purchase-workflow",
"category": "Procurements",
"depends": ["procurement_purchase_no_grouping", "sale_purchase"],
"installable": True,
"auto_install": True,
"license": "AGPL-3",
}
| 35.5
| 497
|
2,549
|
py
|
PYTHON
|
15.0
|
# Copyright 2015-2017 - Pedro M. Baeza <pedro.baeza@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
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.customer = cls.env["res.partner"].create({"name": "Test customer"})
cls.supplier = cls.env["res.partner"].create({"name": "Test supplier"})
cls.product = cls.env["product.product"].create(
{
"name": "Test product service",
"type": "service",
"categ_id": cls.category.id,
"service_to_purchase": True,
"seller_ids": [(0, 0, {"name": cls.supplier.id, "min_qty": 1.0})],
}
)
cls.sale_order = cls.env["sale.order"].create({"partner_id": cls.customer.id})
cls.sale_order_line = cls.env["sale.order.line"].create(
{
"order_id": cls.sale_order.id,
"name": cls.product.name,
"product_id": cls.product.id,
"product_uom_qty": 2,
"product_uom": cls.product.uom_id.id,
"price_unit": 10,
}
)
def test_procurement_no_grouping_order_purchase_service(self):
self.category.procured_purchase_grouping = "order"
self.sale_order.action_confirm()
orders = self.env["purchase.order"].search(
[("origin", "=", self.sale_order.name)]
)
self.assertEqual(
len(orders),
1,
"Procured purchase orders are the same",
)
self.assertEqual(
len(orders.mapped("order_line")),
1,
"Procured purchase orders lines are the same",
)
sale_order_2 = self.sale_order.copy()
# Duplicate line to have 2 distinct lines with the same product
sale_order_2.order_line.copy({"order_id": sale_order_2.id})
sale_order_2.action_confirm()
orders = self.env["purchase.order"].search([("origin", "=", sale_order_2.name)])
self.assertEqual(
len(orders),
2,
"Procured purchase orders are the same",
)
self.assertEqual(
len(orders.mapped("order_line")),
2,
"Procured purchase orders lines are the same",
)
| 39.215385
| 2,549
|
707
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Carlos Dauden
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
class SaleOrderLine(models.Model):
_inherit = "sale.order.line"
def _purchase_service_create(self, quantity=False):
no_grouped_lines = self.filtered(
lambda sol: (sol.product_id.categ_id.procured_purchase_grouping == "order")
)
res = super(SaleOrderLine, self - no_grouped_lines)._purchase_service_create()
res.update(
super(
SaleOrderLine,
no_grouped_lines.with_context(search_purchase_no_grouping=True),
)._purchase_service_create()
)
return res
| 33.666667
| 707
|
512
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Carlos Dauden
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo import api, models
class PurchaseOrder(models.Model):
_inherit = "purchase.order"
@api.model
def search(self, args, offset=0, limit=None, order=None, count=False):
if self.env.context.get("search_purchase_no_grouping", False):
return self.browse()
return super().search(
args, offset=offset, limit=limit, order=order, count=count
)
| 32
| 512
|
467
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Purchase - Total Ordered Qty",
"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.357143
| 467
|
2,822
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from json import dumps
from odoo.tests import TransactionCase
class TestPurchaseTotalOrderedQty(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.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,
},
{
"name": "Product 2",
"uom_id": cls.uom_dozen.id,
"uom_po_id": cls.uom_dozen.id,
},
{
"name": "Product 3",
"uom_id": cls.uom_cubic_meter.id,
"uom_po_id": cls.uom_cubic_meter.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_total_ordered_qty(self):
order = self.env["purchase.order"].create(self.order_vals)
self.assertEqual(
order.total_ordered_qty_json,
dumps({self.uom_unit.id: 22.0, self.uom_litre.id: 50.0}),
)
self.assertEqual(order.total_ordered_qty_text, "50.0 L\n22.0 Units")
| 35.275
| 2,822
|
2,621
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import json
from collections import defaultdict
from odoo import api, fields, models
class PurchaseOrder(models.Model):
_inherit = "purchase.order"
total_ordered_qty_json = fields.Char(
string="Total Quantity Json",
compute="_compute_total_ordered_qty_json",
store=True, # Used by ``total_ordered_qty_text``, store it for better performances
)
total_ordered_qty_text = fields.Text(
string="Total Quantity Text",
compute="_compute_total_ordered_qty_text",
store=False, # Depends on ctx/user lang
)
@api.depends("order_line.product_qty", "order_line.product_uom")
def _compute_total_ordered_qty_json(self):
# Map UoMs to their reference
ref_uom = defaultdict(lambda: self.env["uom.uom"])
with_lines = self.filtered("order_line")
(self - with_lines).total_ordered_qty_json = json.dumps({})
for order in with_lines:
ordered_qty_by_uom = defaultdict(float)
for line in order.order_line:
qty = line.product_qty
uom = line.product_uom
if uom.uom_type == "reference":
ref = uom
elif uom in ref_uom:
ref = ref_uom[uom]
else:
ref = self.env["uom.uom"].search(
[
("category_id", "=", uom.category_id.id),
("uom_type", "=", "reference"),
],
limit=1,
)
ref_uom[uom] = ref
ordered_qty_by_uom[ref] += uom._compute_quantity(qty, ref, round=False)
order.total_ordered_qty_json = json.dumps(
{u.id: q for u, q in ordered_qty_by_uom.items()}
)
@api.depends("total_ordered_qty_json")
@api.depends_context("lang")
def _compute_total_ordered_qty_text(self):
lang = self.env.context.get("lang") or self.env.user.lang
uom_browse = self.env["uom.uom"].with_context(lang=lang).browse
for order in self:
ordered_qty_dict = {
uom_browse(int(u_id)): qty
for u_id, qty in json.loads(order.total_ordered_qty_json).items()
}
order.total_ordered_qty_text = "\n".join(
"%s %s" % (u._compute_quantity(q, u, round=True), u.name)
for u, q in sorted(ordered_qty_dict.items(), key=lambda x: x[0].name)
)
| 39.712121
| 2,621
|
677
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Purchase Receipt Expectation From Partner",
"version": "15.0.1.0.0",
"category": "Purchase Management",
"author": "Camptocamp SA, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/purchase-workflow",
"license": "AGPL-3",
"data": [
"views/res_partner.xml",
],
"depends": [
"purchase_receipt_expectation",
],
"installable": True,
# High sequence to make sure other ``purchase_receipt_expectation*`` are
# already properly installed/upgraded before this module
"sequence": 9999,
}
| 32.238095
| 677
|
1,799
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
from odoo.tests.common import Form
from odoo.addons.purchase_receipt_expectation.tests.test_purchase_receipt_expectation import (
TestPurchaseReceiptExpectation,
)
class TestPurchaseReceiptExpectationFromPartner(TestPurchaseReceiptExpectation):
def test_00_receipt_expectation_from_partner(self):
"""Tests receipt expectation being taken from PO partner
Steps:
- Extend `purchase.order` with a mock-up model
- Extend `receipt_expectation` with a mock-up value "test"
- Check `res.partner.receipt_expectation` selection values
- Update test partner `receipt_expectation` with value "test"
- Create a new PO with given partner
- Check PO `receipt_expectation`
Expect:
- `res.partner.receipt_expectation` selection values contain "test"
- PO `receipt_expectation` is "test"
"""
class PurchaseOrderMockUp(models.Model):
_inherit = "purchase.order"
receipt_expectation = fields.Selection(
selection_add=[("test", "Test")],
ondelete={"test": "set default"},
)
PurchaseOrderMockUp._build_model(self.registry, self.cr)
self.registry.setup_models(self.cr)
self.assertIn(
"test",
self.env["res.partner"]._fields["receipt_expectation"].get_values(self.env),
)
self.po_partner.receipt_expectation = "test"
with Form(self.env["purchase.order"]) as po_form:
po_form.partner_id = self.po_partner
po = po_form.save()
self.assertEqual(po.receipt_expectation, "test")
| 37.479167
| 1,799
|
389
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, models
class PurchaseOrder(models.Model):
_inherit = "purchase.order"
@api.onchange("partner_id")
def _onchange_partner_receipt_expectation(self):
exp = self.partner_id.receipt_expectation
if exp:
self.receipt_expectation = exp
| 27.785714
| 389
|
456
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class PurchaseOrder(models.Model):
_inherit = "res.partner"
@api.model
def _get_receipt_expectation_selection(self):
po_field = self.env["purchase.order"]._fields["receipt_expectation"]
return po_field.selection
receipt_expectation = fields.Selection(_get_receipt_expectation_selection)
| 30.4
| 456
|
861
|
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 Evaluation",
"version": "15.0.1.0.0",
"category": "Purchase Management",
"author": "Ecosoft, Odoo Community Association (OCA)",
"license": "AGPL-3",
"website": "https://github.com/OCA/purchase-workflow",
"depends": ["purchase_work_acceptance"],
"data": [
"security/ir.model.access.csv",
"security/security.xml",
"views/res_config_settings_views.xml",
"views/work_acceptance_evaluation_views.xml",
"views/work_acceptance_views.xml",
"report/work_acceptance_evaluation_report.xml",
],
"demo": ["demo/evaluation_data.xml"],
"maintainers": ["kittiu"],
"installable": True,
"development_status": "Alpha",
}
| 35.875
| 861
|
3,066
|
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
from odoo.exceptions import UserError
from odoo.tests.common import Form, TransactionCase
class TestPurchaseWorkAcceptanceEvaluation(TransactionCase):
def setUp(self):
super().setUp()
self.Config = self.env["res.config.settings"]
self.WorkAcceptance = self.env["work.acceptance"]
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")
# Enable WA Evaluation
with Form(self.Config) as c:
c.group_enable_eval_on_wa = True
c.save()
self.Config.create({"group_enable_eval_on_wa": True}).execute()
def test_01_wa_check_state_required(self):
"""Creat new WA with 3 evaluation criterias, I expect that user must
fill in the evaluation based on state_requried"""
with Form(self.WorkAcceptance) as f:
f.partner_id = self.res_partner
f.responsible_id = self.employee
f.date_due = fields.Datetime.now()
f.date_receive = fields.Datetime.now()
f.company_id = self.main_company
work_acceptance = f.save()
self.assertEqual(len(work_acceptance.evaluation_result_ids), 3)
# 1st criteria state_required = accept, 2nd and 3rd state_required = draft
eval_resuls = work_acceptance.evaluation_result_ids
eval_resuls[0].case_id.state_required = "accept"
eval_resuls[1].case_id.state_required = "draft"
eval_resuls[2].case_id.state_required = "draft"
# User need to fill in 2nd and 3rd criteria
with self.assertRaises(UserError) as e:
work_acceptance.button_accept()
self.assertEqual(
e.exception.args[0],
"Please evaluate - %s"
% ", ".join([eval_resuls[1].case_id.name, eval_resuls[2].case_id.name]),
)
# Set score and accept again
eval_resuls[1].score_id = eval_resuls[1].case_id.score_ids[0]
eval_resuls[2].score_id = eval_resuls[2].case_id.score_ids[0]
work_acceptance.button_accept()
self.assertEqual(work_acceptance.state, "accept")
def test_02_wa_evaluation_score_name_get(self):
with Form(self.WorkAcceptance) as f:
f.partner_id = self.res_partner
f.responsible_id = self.employee
f.date_due = fields.Datetime.now()
f.date_receive = fields.Datetime.now()
f.company_id = self.main_company
work_acceptance = f.save()
score_resuls = work_acceptance.mapped("evaluation_result_ids.case_id.score_ids")
name = "{} ({})".format(score_resuls[0].name, score_resuls[0].score)
res = score_resuls[0].name_get()
self.assertEqual(len(res), 1)
rec_id, name_get = res[0]
self.assertEqual(score_resuls[0].id, rec_id)
self.assertIn(name, name_get)
| 44.434783
| 3,066
|
622
|
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_eval_on_wa = fields.Boolean(
string="Enable Evaluation on Work Acceptance",
implied_group="purchase_work_acceptance_evaluation.group_enable_eval_on_wa",
)
@api.onchange("group_enable_eval_on_wa")
def _onchange_group_enable_eval_on_wa(self):
if self.group_enable_eval_on_wa:
self.group_enable_wa_on_po = True
| 34.555556
| 622
|
2,443
|
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"
evaluation_result_ids = fields.One2many(
comodel_name="work.acceptance.evaluation.result",
inverse_name="wa_id",
string="Evaluation Results",
default=lambda self: self._default_evaluation_result_ids(),
)
def _default_evaluation_result_ids(self):
eval_result = self.env["work.acceptance.evaluation"].search([])
result = [(0, 0, {"case_id": rec.id}) for rec in eval_result]
return result
def button_accept(self, force=False):
for rec in self:
rec._check_evaluation()
return super().button_accept(force=force)
def _check_evaluation(self):
self.ensure_one()
if self.user_has_groups(
"purchase_work_acceptance_evaluation.group_enable_eval_on_wa"
):
missing_results = self.evaluation_result_ids.filtered(
lambda l: l.case_id.state_required == self.state and not l.score_id
)
if missing_results:
cases = missing_results.mapped("case_id")
raise UserError(
_("Please evaluate - %s") % ", ".join(cases.mapped("name"))
)
class WorkAcceptanceEvaluationResult(models.Model):
_name = "work.acceptance.evaluation.result"
_description = "Work Acceptance Evaluation Result"
wa_id = fields.Many2one(
comodel_name="work.acceptance",
string="WA Reference",
required=True,
index=True,
ondelete="cascade",
)
case_id = fields.Many2one(
comodel_name="work.acceptance.evaluation",
string="Case Name",
required=True,
)
score_id = fields.Many2one(
comodel_name="work.acceptance.evaluation.score",
string="Score",
domain="[('evaluation_id', '=', case_id)]",
)
note = fields.Char()
editable = fields.Boolean(compute="_compute_editable")
@api.depends("case_id")
def _compute_editable(self):
for rec in self:
rec.editable = (
True
if not rec.case_id.state_required
else rec.wa_id.state == rec.case_id.state_required
)
| 33.013514
| 2,443
|
1,313
|
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 WorkAcceptanceEvaluation(models.Model):
_name = "work.acceptance.evaluation"
_description = "Work Acceptance Evaluation"
name = fields.Char(
string="Case Name",
required=True,
)
active = fields.Boolean(
default=True,
)
state_required = fields.Selection(
selection=[("draft", "Draft"), ("accept", "Accepted")],
help="Status of Work Acceptance that user need to fill the evaluation",
)
score_ids = fields.One2many(
comodel_name="work.acceptance.evaluation.score",
inverse_name="evaluation_id",
string="Score",
)
class WorkAcceptanceEvaluationScore(models.Model):
_name = "work.acceptance.evaluation.score"
_description = "Work Acceptance Evaluation Score"
_order = "score"
name = fields.Char(
string="Values",
required=True,
)
evaluation_id = fields.Many2one(
comodel_name="work.acceptance.evaluation",
string="Case Name",
)
score = fields.Integer()
def name_get(self):
result = [(rec.id, "{} ({})".format(rec.name, rec.score)) for rec in self]
return result
| 28.543478
| 1,313
|
1,822
|
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 WorkAcceptanceEvaluationReport(models.Model):
_name = "work.acceptance.evaluation.report"
_description = "Work Acceptance Evaluation Report"
_order = "partner_id,date_accept"
_auto = False
partner_id = fields.Many2one(
comodel_name="res.partner",
string="Vendor",
)
wa_id = fields.Many2one(
comodel_name="work.acceptance",
string="WA Reference",
)
wa_state = fields.Selection(
[("draft", "Draft"), ("accept", "Accepted"), ("cancel", "Cancelled")],
string="Status",
)
date_accept = fields.Datetime(
string="Accepted Date",
)
case_id = fields.Many2one(
comodel_name="work.acceptance.evaluation",
string="Case Name",
)
score_id = fields.Many2one(
comodel_name="work.acceptance.evaluation.score",
string="Score ID",
)
score = fields.Integer()
note = fields.Char()
company_id = fields.Many2one(
comodel_name="res.company",
)
def _select(self):
return """
select result.id, wa.partner_id, result.wa_id,
wa.state as wa_state,
wa.date_accept, result.case_id,
result.score_id, score.score, result.note,
wa.company_id
"""
def _from(self):
return """
from work_acceptance_evaluation_result result
join work_acceptance_evaluation_score score on score.id = result.score_id
left join work_acceptance wa on result.wa_id = wa.id
"""
@property
def _table_query(self):
return "%s %s" % (self._select(), self._from())
| 30.366667
| 1,822
|
598
|
py
|
PYTHON
|
15.0
|
# Copyright 2015-20 ForgeFlow, S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Product Supplier Code in Purchase",
"summary": """This module adds to the purchase order line the supplier
code defined in the product.""",
"version": "15.0.1.0.0",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/purchase-workflow",
"category": "Purchase Management",
"license": "AGPL-3",
"depends": ["purchase"],
"data": ["views/purchase_order_view.xml"],
"installable": True,
}
| 37.375
| 598
|
3,023
|
py
|
PYTHON
|
15.0
|
# Copyright 2015-17 ForgeFlow, S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields
from odoo.tests.common import TransactionCase
class TestProductSupplierCodePurchase(TransactionCase):
def setUp(self):
super(TestProductSupplierCodePurchase, self).setUp()
self.supplierinfo_model = self.env["product.supplierinfo"]
self.supplier = self.env["res.partner"].create(
{"name": "name", "email": "example@yourcompany.com", "phone": 123456}
)
self.product = self.env["product.product"].create({"name": "Test product"})
self.seller = self.env["product.supplierinfo"].create(
{
"name": self.supplier.id,
"product_id": self.product.id,
"product_tmpl_id": self.product.product_tmpl_id.id,
"product_code": "00001",
"price": 100.0,
}
)
self.purchase_model = self.env["purchase.order"]
def test_product_supplier_code_purchase(self):
purchase_order = self.purchase_model.create(
{
"partner_id": self.supplier.id,
"order_line": [
(
0,
0,
{
"product_id": self.product.id,
"product_uom": self.product.uom_id.id,
"price_unit": self.product.standard_price,
"name": self.product.name,
"date_planned": fields.Datetime.now(),
"product_qty": 1,
},
)
],
}
)
purchase_order.order_line._onchange_product_code()
self.assertEqual(
purchase_order.order_line[0].product_supplier_code,
"00001",
"Wrong supplier code",
)
def test_supplierinfo_update(self):
new_product = self.env["product.product"].create({"name": "Test product"})
purchase_order = self.purchase_model.create(
{
"partner_id": self.supplier.id,
"order_line": [
(
0,
0,
{
"product_id": new_product.id,
"product_uom": new_product.uom_id.id,
"price_unit": new_product.standard_price,
"name": new_product.name,
"date_planned": fields.Datetime.now(),
"product_qty": 1,
"product_supplier_code": "01000",
},
)
],
}
)
purchase_order.button_confirm()
self.assertEqual(
new_product.seller_ids[0].product_code, "01000", "Wrong supplier code"
)
| 38.75641
| 3,023
|
2,175
|
py
|
PYTHON
|
15.0
|
# Copyright 2015-17 ForgeFlow, S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
from odoo.exceptions import AccessError
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
product_supplier_code = fields.Char()
@api.onchange(
"partner_id",
"product_id",
)
def _onchange_product_code(self):
for line in self:
supplier_info = line.product_id.seller_ids.filtered(
lambda s: (
s.product_id == line.product_id and s.name == line.partner_id
)
)
if supplier_info:
code = supplier_info[0].product_code or ""
line.product_supplier_code = code
else:
supplier_info = line.product_id.seller_ids.filtered(
lambda s: (
s.product_tmpl_id == line.product_id.product_tmpl_id
and s.name == line.partner_id
)
)
if supplier_info:
code = supplier_info[0].product_code or ""
line.product_supplier_code = code
class PurchaseOrder(models.Model):
_inherit = "purchase.order"
def _add_supplier_to_product(self):
res = super()._add_supplier_to_product()
for line in self.order_line:
partner = (
self.partner_id
if not self.partner_id.parent_id
else self.partner_id.parent_id
)
if partner in line.product_id.seller_ids.mapped("name"):
seller = line.product_id._select_seller(
partner_id=line.partner_id,
quantity=line.product_qty,
date=line.order_id.date_order and line.order_id.date_order.date(),
uom_id=line.product_uom,
)
if seller:
try:
seller["product_code"] = line.product_supplier_code
except AccessError:
break
return res
| 35.655738
| 2,175
|
595
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Purchase Stock Tier Validation",
"summary": "Exclude RFQs pending to validate when procuring",
"version": "15.0.1.0.0",
"category": "Purchase Management",
"website": "https://github.com/OCA/purchase-workflow",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"maintainers": ["bosd"],
"license": "AGPL-3",
"application": False,
"installable": True,
"auto_install": True,
"depends": ["purchase_stock", "purchase_tier_validation"],
}
| 37.1875
| 595
|
4,040
|
py
|
PYTHON
|
15.0
|
# Copyright 2017-2020 ForgeFlow S.L.
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl-3.0).
from odoo import fields
from odoo.tests import common
class TestPurchaseStockTierValidation(common.TransactionCase):
def setUp(self):
super(TestPurchaseStockTierValidation, self).setUp()
# Get purchase order model
self.po_model = self.env.ref("purchase.model_purchase_order").with_context(
tracking_disable=True, no_reset_password=True
)
# Create users
group_ids = self.env.ref("base.group_system").ids
self.test_user_1 = self.env["res.users"].create(
{
"name": "John",
"login": "test1",
"groups_id": [(6, 0, group_ids)],
"email": "test@examlple.com",
}
)
# Create tier definitions:
self.tier_def_obj = self.env["tier.definition"]
self.tier_def_obj.create(
{
"model_id": self.po_model.id,
"review_type": "individual",
"reviewer_id": self.test_user_1.id,
}
)
# Common models
self.test_partner = self.env["res.partner"].create({"name": "Partner for test"})
self.stock_loc = self.browse_ref("stock.stock_location_stock")
self.warehouse = self.browse_ref("stock.warehouse0")
# Create product
route_buy = self.env.ref("purchase_stock.route_warehouse0_buy").id
self.test_product = self.env["product.product"].create(
{
"name": "Test Scrap Component 1",
"type": "product",
"route_ids": [(6, 0, [route_buy])],
"seller_ids": [(0, 0, {"name": self.test_partner.id, "price": 20.0})],
}
)
def test_procurement_in_new_rfq(self):
"""
Procure a product with the same supplier as one open RFQ under validation
and check if it includes the procurement in that RFQ or in a new one.
"""
po = self.env["purchase.order"].create(
{
"partner_id": self.test_partner.id,
"order_line": [
(
0,
0,
{
"name": "PO-Product",
"product_id": self.test_product.id,
"date_planned": fields.Datetime.now(),
"product_qty": 10,
"product_uom": self.test_product.uom_id.id,
"price_unit": 1000,
},
)
],
}
)
rfq_test_partner_before = self.env["purchase.order"].search(
[("partner_id", "=", self.test_partner.id)]
)
self.assertEqual(len(po.mapped("order_line")), 1)
po.request_validation()
po.with_user(self.test_user_1).validate_tier()
date_planned = fields.Datetime.now()
group = self.env["procurement.group"].create(
{"name": "Test", "move_type": "direct"}
)
values = {
"company_id": self.warehouse.company_id,
"group_id": group,
"date_planned": date_planned,
"warehouse_id": self.warehouse,
}
procurements = [
self.env["procurement.group"].Procurement(
self.test_product,
1,
self.env.ref("uom.product_uom_unit"),
self.stock_loc,
"test",
"TEST",
self.warehouse.company_id,
values,
)
]
group.run(procurements)
self.assertEqual(len(po.mapped("order_line")), 1)
rfq_test_partner_after = self.env["purchase.order"].search(
[("partner_id", "=", self.test_partner.id)]
)
self.assertEqual(len(rfq_test_partner_after), len(rfq_test_partner_before) + 1)
| 36.727273
| 4,040
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.