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
|
|---|---|---|---|---|---|---|
1,250
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Delivery Costs',
'version': '1.0',
'category': 'Inventory/Delivery',
'description': """
Allows you to add delivery methods in sale orders and picking.
==============================================================
You can define your own carrier for prices. When creating
invoices from picking, the system is able to add and compute the shipping line.
""",
'depends': ['sale_stock', 'sale_management'],
'data': [
'security/ir.model.access.csv',
'security/delivery_carrier_security.xml',
'views/product_template_view.xml',
'views/delivery_view.xml',
'views/partner_view.xml',
'views/delivery_portal_template.xml',
'data/delivery_data.xml',
'views/report_shipping.xml',
'views/report_deliveryslip.xml',
'views/report_package_barcode.xml',
'views/res_config_settings_views.xml',
'wizard/choose_delivery_package_views.xml',
'wizard/choose_delivery_carrier_views.xml',
'views/stock_package_type_views.xml',
],
'demo': ['data/delivery_demo.xml'],
'installable': True,
'license': 'LGPL-3',
}
| 34.722222
| 1,250
|
5,311
|
py
|
PYTHON
|
15.0
|
from odoo.tests import Form
from odoo.tests.common import TransactionCase
class TestCarrierPropagation(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
# For performances reasons
cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
cls.warehouse = cls.env.ref("stock.warehouse0")
# Set Warehouse as multi steps delivery
cls.warehouse.delivery_steps = "pick_pack_ship"
# Create a delivery product and its carrier
cls.ProductProduct = cls.env['product.product']
cls.SaleOrder = cls.env['sale.order']
cls.StockMove = cls.env["stock.move"]
cls.partner_propagation = cls.env['res.partner'].create({
'name': 'My Carrier Propagation Customer'})
cls.product_uom_unit = cls.env.ref('uom.product_uom_unit')
cls.product_delivery_normal = cls.env['product.product'].create({
'name': 'Normal Delivery Charges',
'invoice_policy': 'order',
'type': 'service',
'list_price': 10.0,
'categ_id': cls.env.ref('delivery.product_category_deliveries').id,
})
cls.normal_delivery = cls.env['delivery.carrier'].create({
'name': 'Normal Delivery Charges',
'fixed_price': 10,
'delivery_type': 'fixed',
'product_id': cls.product_delivery_normal.id,
})
cls.customer_location = cls.env.ref("stock.stock_location_customers")
cls.output_location = cls.env.ref("stock.stock_location_output")
cls.super_product = cls.ProductProduct.create({
'name': 'Super Product',
'invoice_policy': 'delivery',
})
mto_route = cls.env.ref('stock.route_warehouse0_mto')
mto_route.active = True
cls.warehouse.mto_pull_id.procure_method = "make_to_stock"
cls.mto_product = cls.ProductProduct.create({
'name': 'MTO Product',
'invoice_policy': 'delivery',
'route_ids': [(6, 0, mto_route.ids)],
})
cls.rule_pack = cls.env["procurement.group"]._get_rule(
cls.super_product, cls.output_location, {"warehouse_id": cls.warehouse})
def test_carrier_no_propagation(self):
"""
Set the carrier propagation to False on stock.rule
Create a Sale Order, confirm it
Check that the carrier is set on the OUT
Check that the carrier is not set on the PACK
"""
self.rule_pack.propagate_carrier = False
so = self.SaleOrder.create({
'name': 'Sale order',
'partner_id': self.partner_propagation.id,
'partner_invoice_id': self.partner_propagation.id,
'order_line': [
(0, 0, {'name': self.super_product.name, 'product_id': self.super_product.id, 'product_uom_qty': 1, 'price_unit': 1,}),
]
})
delivery_wizard = Form(self.env['choose.delivery.carrier'].with_context({
'default_order_id': so.id,
'default_carrier_id': self.normal_delivery.id,
}))
choose_delivery_carrier = delivery_wizard.save()
choose_delivery_carrier.button_confirm()
# Confirm the SO
so.action_confirm()
move_out = self.StockMove.search([("location_dest_id.usage", "=", "customer"), ("product_id", "=", self.super_product.id)])
self.assertEqual(
self.normal_delivery,
move_out.picking_id.carrier_id,
)
move_pack = self.StockMove.search([("move_dest_ids", "in", move_out.ids)])
self.assertFalse(move_pack.picking_id.carrier_id)
def test_carrier_propagation(self):
"""
Set the carrier propagation to True on stock.rule
Create a Sale Order, confirm it
Check that the carrier is set on the OUT
Check that the carrier is set on the PACK
"""
self.rule_pack.propagate_carrier = True
for product in [self.super_product, self.mto_product]:
so = self.SaleOrder.create({
'name': 'Sale order',
'partner_id': self.partner_propagation.id,
'partner_invoice_id': self.partner_propagation.id,
'order_line': [
(0, 0, {'name': product.name, 'product_id': product.id, 'product_uom_qty': 1, 'price_unit': 1,}),
]
})
delivery_wizard = Form(self.env['choose.delivery.carrier'].with_context({
'default_order_id': so.id,
'default_carrier_id': self.normal_delivery.id,
}))
choose_delivery_carrier = delivery_wizard.save()
choose_delivery_carrier.button_confirm()
# Confirm the SO
so.action_confirm()
move_out = self.StockMove.search([("location_dest_id.usage", "=", "customer"), ("product_id", "=", product.id)])
self.assertEqual(
self.normal_delivery,
move_out.picking_id.carrier_id,
)
move_pack = self.StockMove.search([("move_dest_ids", "in", move_out.ids)])
self.assertEqual(
self.normal_delivery,
move_pack.picking_id.carrier_id,
)
| 42.488
| 5,311
|
4,555
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.stock.tests.test_packing import TestPackingCommon
class TestPacking(TestPackingCommon):
@classmethod
def setUpClass(cls):
super(TestPacking, cls).setUpClass()
cls.uom_kg = cls.env.ref('uom.product_uom_kgm')
cls.product_aw = cls.env['product.product'].create({
'name': 'Product AW',
'type': 'product',
'weight': 2.4,
'uom_id': cls.uom_kg.id,
'uom_po_id': cls.uom_kg.id
})
cls.product_bw = cls.env['product.product'].create({
'name': 'Product BW',
'type': 'product',
'weight': 0.3,
'uom_id': cls.uom_kg.id,
'uom_po_id': cls.uom_kg.id
})
test_carrier_product = cls.env['product.product'].create({
'name': 'Test carrier product',
'type': 'service',
})
cls.test_carrier = cls.env['delivery.carrier'].create({
'name': 'Test carrier',
'delivery_type': 'fixed',
'product_id': test_carrier_product.id,
})
def test_put_in_pack_weight_wizard(self):
""" Check that de default weight is correctly set by default when using the 'choose.delivery.package' wizard.
This purpose of this wizard is
"""
self.env['stock.quant']._update_available_quantity(self.product_aw, self.stock_location, 20.0)
self.env['stock.quant']._update_available_quantity(self.product_bw, self.stock_location, 20.0)
picking_ship = self.env['stock.picking'].create({
'partner_id': self.env['res.partner'].create({'name': 'A partner'}).id,
'picking_type_id': self.warehouse.out_type_id.id,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'carrier_id': self.test_carrier.id
})
move_line_paw = self.env['stock.move.line'].create({
'product_id': self.product_aw.id,
'product_uom_id': self.uom_kg.id,
'picking_id': picking_ship.id,
'qty_done': 5,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id
})
move_line_pbw = self.env['stock.move.line'].create({
'product_id': self.product_bw.id,
'product_uom_id': self.uom_kg.id,
'picking_id': picking_ship.id,
'qty_done': 5,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id
})
picking_ship.action_confirm()
pack_action = picking_ship.action_put_in_pack()
pack_action_ctx = pack_action['context']
pack_action_model = pack_action['res_model']
# We make sure the correct action was returned
self.assertEqual(pack_action_model, 'choose.delivery.package')
# We instanciate the wizard with the context of the action and check that the
# default weight was set.
pack_wiz = self.env['choose.delivery.package'].with_context(pack_action_ctx).create({})
self.assertEqual(pack_wiz.shipping_weight, 13.5)
def test_send_to_shipper_without_sale_order(self):
"""
Check we can validate delivery with a delivery carrier set when it isn't linked to a sale order
"""
self.env['stock.quant']._update_available_quantity(self.product_aw, self.stock_location, 20.0)
picking_ship = self.env['stock.picking'].create({
'partner_id': self.env['res.partner'].create({'name': 'A partner'}).id,
'picking_type_id': self.warehouse.out_type_id.id,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'carrier_id': self.test_carrier.id
})
self.env['stock.move.line'].create({
'product_id': self.product_aw.id,
'product_uom_id': self.uom_kg.id,
'picking_id': picking_ship.id,
'qty_done': 5,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id
})
self.assertEqual(picking_ship.state, 'draft', 'Delivery state should be draft.')
self.assertFalse(picking_ship.sale_id.id, 'Sale order shouldn\'t be set')
picking_ship.action_confirm()
picking_ship.button_validate()
self.assertEqual(picking_ship.state, 'done')
| 42.971698
| 4,555
|
10,563
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged, Form
@tagged('post_install', '-at_install')
class StockMoveInvoice(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.ProductProduct = cls.env['product.product']
cls.SaleOrder = cls.env['sale.order']
cls.AccountJournal = cls.env['account.journal']
cls.partner_18 = cls.env['res.partner'].create({'name': 'My Test Customer'})
cls.pricelist_id = cls.env.ref('product.list0')
cls.product_11 = cls.env['product.product'].create({'name': 'A product to deliver'})
cls.product_cable_management_box = cls.env['product.product'].create({
'name': 'Another product to deliver',
'weight': 1.0,
'invoice_policy': 'order',
})
cls.product_uom_unit = cls.env.ref('uom.product_uom_unit')
cls.product_delivery_normal = cls.env['product.product'].create({
'name': 'Normal Delivery Charges',
'invoice_policy': 'order',
'type': 'service',
'list_price': 10.0,
'categ_id': cls.env.ref('delivery.product_category_deliveries').id,
})
cls.normal_delivery = cls.env['delivery.carrier'].create({
'name': 'Normal Delivery Charges',
'fixed_price': 10,
'delivery_type': 'fixed',
'product_id': cls.product_delivery_normal.id,
})
def test_01_delivery_stock_move(self):
# Test if the stored fields of stock moves are computed with invoice before delivery flow
self.sale_prepaid = self.SaleOrder.create({
'partner_id': self.partner_18.id,
'partner_invoice_id': self.partner_18.id,
'partner_shipping_id': self.partner_18.id,
'pricelist_id': self.pricelist_id.id,
'order_line': [(0, 0, {
'name': 'Cable Management Box',
'product_id': self.product_cable_management_box.id,
'product_uom_qty': 2,
'product_uom': self.product_uom_unit.id,
'price_unit': 750.00,
})],
})
# I add delivery cost in Sales order
delivery_wizard = Form(self.env['choose.delivery.carrier'].with_context({
'default_order_id': self.sale_prepaid.id,
'default_carrier_id': self.normal_delivery.id,
}))
choose_delivery_carrier = delivery_wizard.save()
choose_delivery_carrier.button_confirm()
# I confirm the SO.
self.sale_prepaid.action_confirm()
self.sale_prepaid._create_invoices()
# I check that the invoice was created
self.assertEqual(len(self.sale_prepaid.invoice_ids), 1, "Invoice not created.")
# I confirm the invoice
self.invoice = self.sale_prepaid.invoice_ids
self.invoice.action_post()
# I pay the invoice.
self.journal = self.AccountJournal.search([('type', '=', 'cash'), ('company_id', '=', self.sale_prepaid.company_id.id)], limit=1)
register_payments = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=self.invoice.ids).create({
'journal_id': self.journal.id,
})
register_payments._create_payments()
# Check the SO after paying the invoice
self.assertNotEqual(self.sale_prepaid.invoice_count, 0, 'order not invoiced')
self.assertTrue(self.sale_prepaid.invoice_status == 'invoiced', 'order is not invoiced')
self.assertEqual(len(self.sale_prepaid.picking_ids), 1, 'pickings not generated')
# Check the stock moves
moves = self.sale_prepaid.picking_ids.move_lines
self.assertEqual(moves[0].product_qty, 2, 'wrong product_qty')
self.assertEqual(moves[0].weight, 2.0, 'wrong move weight')
# Ship
moves.move_line_ids.write({'qty_done': 2})
self.picking = self.sale_prepaid.picking_ids._action_done()
self.assertEqual(moves[0].move_line_ids.sale_price, 1725.0, 'wrong shipping value')
def test_02_delivery_stock_move(self):
# Test if SN product shipment line has the correct amount
self.product_cable_management_box.write({
'tracking': 'serial'
})
serial_numbers = self.env['stock.production.lot'].create([{
'name': str(x),
'product_id': self.product_cable_management_box.id,
'company_id': self.env.company.id,
} for x in range(5)])
self.sale_prepaid = self.SaleOrder.create({
'partner_id': self.partner_18.id,
'partner_invoice_id': self.partner_18.id,
'partner_shipping_id': self.partner_18.id,
'pricelist_id': self.pricelist_id.id,
'order_line': [(0, 0, {
'name': 'Cable Management Box',
'product_id': self.product_cable_management_box.id,
'product_uom_qty': 2,
'product_uom': self.product_uom_unit.id,
'price_unit': 750.00,
})],
})
# I add delivery cost in Sales order
delivery_wizard = Form(self.env['choose.delivery.carrier'].with_context({
'default_order_id': self.sale_prepaid.id,
'default_carrier_id': self.normal_delivery.id,
}))
choose_delivery_carrier = delivery_wizard.save()
choose_delivery_carrier.button_confirm()
# I confirm the SO.
self.sale_prepaid.action_confirm()
moves = self.sale_prepaid.picking_ids.move_lines
# Ship
for ml, lot in zip(moves.move_line_ids, serial_numbers):
ml.write({'qty_done': 1, 'lot_id': lot.id})
self.picking = self.sale_prepaid.picking_ids._action_done()
self.assertEqual(moves[0].move_line_ids[0].sale_price, 862.5, 'wrong shipping value')
def test_03_invoiced_status(self):
super_product = self.env['product.product'].create({
'name': 'Super Product',
'invoice_policy': 'delivery',
})
great_product = self.env['product.product'].create({
'name': 'Great Product',
'invoice_policy': 'delivery',
})
so = self.env['sale.order'].create({
'name': 'Sale order',
'partner_id': self.partner_a.id,
'partner_invoice_id': self.partner_a.id,
'order_line': [
(0, 0, {'name': super_product.name, 'product_id': super_product.id, 'product_uom_qty': 1, 'price_unit': 1,}),
(0, 0, {'name': great_product.name, 'product_id': great_product.id, 'product_uom_qty': 1, 'price_unit': 1,}),
]
})
# Confirm the SO
so.action_confirm()
# Deliver one product and create a backorder
self.assertEqual(sum([line.quantity_done for line in so.picking_ids.move_lines]), 0)
so.picking_ids.move_lines[0].quantity_done = 1
backorder_wizard_dict = so.picking_ids.button_validate()
backorder_wizard = Form(self.env[backorder_wizard_dict['res_model']].with_context(backorder_wizard_dict['context'])).save()
backorder_wizard.process()
self.assertEqual(sum([line.quantity_done for line in so.picking_ids.move_lines]), 1)
# Invoice the delivered product
invoice = so._create_invoices()
invoice.action_post()
self.assertEqual(so.invoice_status, 'no')
# Add delivery fee
delivery_wizard = Form(self.env['choose.delivery.carrier'].with_context({
'default_order_id': so.id,
'default_carrier_id': self.normal_delivery.id
}))
choose_delivery_carrier = delivery_wizard.save()
choose_delivery_carrier.button_confirm()
self.assertEqual(so.invoice_status, 'no', 'The status should still be "Nothing To Invoice"')
def test_delivery_carrier_from_confirmed_so(self):
"""Test if adding shipping method in sale order after confirmation
will add it in pickings too"""
sale_order = self.SaleOrder.create({
"partner_id": self.partner_18.id,
"partner_invoice_id": self.partner_18.id,
"partner_shipping_id": self.partner_18.id,
"order_line": [(0, 0, {
"name": "Cable Management Box",
"product_id": self.product_cable_management_box.id,
"product_uom_qty": 2,
"product_uom": self.product_uom_unit.id,
"price_unit": 750.00,
})],
})
sale_order.action_confirm()
sale_order.picking_ids.move_lines.quantity_done = 2
sale_order.picking_ids.button_validate()
# Return picking
return_form = Form(self.env["stock.return.picking"].with_context(active_id=sale_order.picking_ids.id, active_model="stock.picking"))
return_wizard = return_form.save()
action = return_wizard.create_returns()
return_picking = self.env["stock.picking"].browse(action["res_id"])
# add new product so new picking is created
sale_order.write({
"order_line": [(0, 0, {
"name": "Another product to deliver",
"product_id": self.product_11.id,
"product_uom_qty": 2,
"product_uom": self.product_uom_unit.id,
"price_unit": 750.00,
})],
})
# Add delivery cost in Sales order
delivery_wizard = Form(self.env["choose.delivery.carrier"].with_context({
"default_order_id": sale_order.id,
"default_carrier_id": self.normal_delivery.id,
}))
choose_delivery_carrier = delivery_wizard.save()
choose_delivery_carrier.button_confirm()
# Check the carrier in picking after confirm sale order
delivery_for_product_11 = sale_order.picking_ids.filtered(lambda p: self.product_11 in p.move_lines.product_id)
self.assertEqual(delivery_for_product_11.carrier_id, self.normal_delivery, "The shipping method should be set in pending deliveries.")
done_delivery = sale_order.picking_ids.filtered(lambda p: p.state == "done")
self.assertFalse(done_delivery.carrier_id.id, "The shipping method should not be set in done deliveries.")
self.assertFalse(return_picking.carrier_id.id, "The shipping method should not set in return pickings")
| 43.829876
| 10,563
|
17,762
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.tests import common, Form
from odoo.tools import float_compare
@common.tagged('post_install', '-at_install')
class TestDeliveryCost(common.TransactionCase):
def setUp(self):
super(TestDeliveryCost, self).setUp()
self.SaleOrder = self.env['sale.order']
self.SaleOrderLine = self.env['sale.order.line']
self.AccountAccount = self.env['account.account']
self.SaleConfigSetting = self.env['res.config.settings']
self.Product = self.env['product.product']
self.partner_18 = self.env['res.partner'].create({'name': 'My Test Customer'})
self.pricelist = self.env.ref('product.list0')
self.product_4 = self.env['product.product'].create({'name': 'A product to deliver', 'weight': 1.0})
self.product_uom_unit = self.env.ref('uom.product_uom_unit')
self.product_delivery_normal = self.env['product.product'].create({
'name': 'Normal Delivery Charges',
'type': 'service',
'list_price': 10.0,
'categ_id': self.env.ref('delivery.product_category_deliveries').id,
})
self.normal_delivery = self.env['delivery.carrier'].create({
'name': 'Normal Delivery Charges',
'fixed_price': 10,
'delivery_type': 'fixed',
'product_id': self.product_delivery_normal.id,
})
self.partner_4 = self.env['res.partner'].create({'name': 'Another Customer'})
self.partner_address_13 = self.env['res.partner'].create({
'name': "Another Customer's Address",
'parent_id': self.partner_4.id,
})
self.product_uom_hour = self.env.ref('uom.product_uom_hour')
self.account_data = self.env.ref('account.data_account_type_revenue')
self.account_tag_operating = self.env.ref('account.account_tag_operating')
self.product_2 = self.env['product.product'].create({'name': 'Zizizaproduct', 'weight': 1.0})
self.product_category = self.env.ref('product.product_category_all')
self.free_delivery = self.env.ref('delivery.free_delivery_carrier')
# as the tests hereunder assume all the prices in USD, we must ensure
# that the company actually uses USD
# We do an invalidate_cache so the cache is aware of it too.
self.env.cr.execute(
"UPDATE res_company SET currency_id = %s WHERE id = %s",
[self.env.ref('base.USD').id, self.env.company.id])
self.env.company.invalidate_cache()
self.pricelist.currency_id = self.env.ref('base.USD').id
def test_00_delivery_cost(self):
# In order to test Carrier Cost
# Create sales order with Normal Delivery Charges
self.sale_normal_delivery_charges = self.SaleOrder.create({
'partner_id': self.partner_18.id,
'partner_invoice_id': self.partner_18.id,
'partner_shipping_id': self.partner_18.id,
'pricelist_id': self.pricelist.id,
'order_line': [(0, 0, {
'name': 'PC Assamble + 2GB RAM',
'product_id': self.product_4.id,
'product_uom_qty': 1,
'product_uom': self.product_uom_unit.id,
'price_unit': 750.00,
})],
})
# I add delivery cost in Sales order
self.a_sale = self.AccountAccount.create({
'code': 'X2020',
'name': 'Product Sales - (test)',
'user_type_id': self.account_data.id,
'tag_ids': [(6, 0, {
self.account_tag_operating.id
})]
})
self.product_consultant = self.Product.create({
'sale_ok': True,
'list_price': 75.0,
'standard_price': 30.0,
'uom_id': self.product_uom_hour.id,
'uom_po_id': self.product_uom_hour.id,
'name': 'Service',
'categ_id': self.product_category.id,
'type': 'service'
})
# I add delivery cost in Sales order
delivery_wizard = Form(self.env['choose.delivery.carrier'].with_context({
'default_order_id': self.sale_normal_delivery_charges.id,
'default_carrier_id': self.normal_delivery.id
}))
choose_delivery_carrier = delivery_wizard.save()
choose_delivery_carrier.button_confirm()
# I check sales order after added delivery cost
line = self.SaleOrderLine.search([('order_id', '=', self.sale_normal_delivery_charges.id),
('product_id', '=', self.normal_delivery.product_id.id)])
self.assertEqual(len(line), 1, "Delivery cost is not Added")
zin = str(delivery_wizard.display_price) + " " + str(delivery_wizard.delivery_price) + ' ' + line.company_id.country_id.code + line.company_id.name
self.assertEqual(float_compare(line.price_subtotal, 10.0, precision_digits=2), 0,
"Delivery cost does not correspond to 10.0. %s %s" % (line.price_subtotal, zin))
# I confirm the sales order
self.sale_normal_delivery_charges.action_confirm()
# Create one more sales order with Free Delivery Charges
self.delivery_sale_order_cost = self.SaleOrder.create({
'partner_id': self.partner_4.id,
'partner_invoice_id': self.partner_address_13.id,
'partner_shipping_id': self.partner_address_13.id,
'pricelist_id': self.pricelist.id,
'order_line': [(0, 0, {
'name': 'Service on demand',
'product_id': self.product_consultant.id,
'product_uom_qty': 24,
'product_uom': self.product_uom_hour.id,
'price_unit': 75.00,
}), (0, 0, {
'name': 'On Site Assistance',
'product_id': self.product_2.id,
'product_uom_qty': 30,
'product_uom': self.product_uom_unit.id,
'price_unit': 38.25,
})],
})
# I add free delivery cost in Sales order
delivery_wizard = Form(self.env['choose.delivery.carrier'].with_context({
'default_order_id': self.delivery_sale_order_cost.id,
'default_carrier_id': self.free_delivery.id
}))
choose_delivery_carrier = delivery_wizard.save()
choose_delivery_carrier.button_confirm()
# I check sales order after adding delivery cost
line = self.SaleOrderLine.search([('order_id', '=', self.delivery_sale_order_cost.id),
('product_id', '=', self.free_delivery.product_id.id)])
self.assertEqual(len(line), 1, "Delivery cost is not Added")
self.assertEqual(float_compare(line.price_subtotal, 0, precision_digits=2), 0,
"Delivery cost is not correspond.")
# I set default delivery policy
self.default_delivery_policy = self.SaleConfigSetting.create({})
self.default_delivery_policy.execute()
def test_01_delivery_cost_from_pricelist(self):
""" This test aims to validate the use of a pricelist to compute the delivery cost in the case the associated
product of the shipping method is defined in the pricelist """
# Create pricelist with a custom price for the standard shipping method
my_pricelist = self.env['product.pricelist'].create({
'name': 'shipping_cost_change',
'item_ids': [(0, 0, {
'compute_price': 'fixed',
'fixed_price': 5,
'applied_on': '0_product_variant',
'product_id': self.normal_delivery.product_id.id,
})],
})
# Create sales order with Normal Delivery Charges
sale_pricelist_based_delivery_charges = self.SaleOrder.create({
'partner_id': self.partner_18.id,
'pricelist_id': my_pricelist.id,
'order_line': [(0, 0, {
'name': 'PC Assamble + 2GB RAM',
'product_id': self.product_4.id,
'product_uom_qty': 1,
'product_uom': self.product_uom_unit.id,
'price_unit': 750.00,
})],
})
# Add of delivery cost in Sales order
delivery_wizard = Form(self.env['choose.delivery.carrier'].with_context({
'default_order_id': sale_pricelist_based_delivery_charges.id,
'default_carrier_id': self.normal_delivery.id
}))
self.assertEqual(delivery_wizard.delivery_price, 5.0, "Delivery cost does not correspond to 5.0 in wizard")
delivery_wizard.save().button_confirm()
line = self.SaleOrderLine.search([('order_id', '=', sale_pricelist_based_delivery_charges.id),
('product_id', '=', self.normal_delivery.product_id.id)])
self.assertEqual(len(line), 1, "Delivery cost hasn't been added to SO")
self.assertEqual(line.price_subtotal, 5.0, "Delivery cost does not correspond to 5.0")
def test_02_delivery_cost_from_different_currency(self):
""" This test aims to validate the use of a pricelist using a different currency to compute the delivery cost in
the case the associated product of the shipping method is defined in the pricelist """
# Create pricelist with a custom price for the standard shipping method
my_pricelist = self.env['product.pricelist'].create({
'name': 'shipping_cost_change',
'item_ids': [(0, 0, {
'compute_price': 'fixed',
'fixed_price': 5,
'applied_on': '0_product_variant',
'product_id': self.normal_delivery.product_id.id,
})],
'currency_id': self.env.ref('base.EUR').id,
})
# Create sales order with Normal Delivery Charges
sale_pricelist_based_delivery_charges = self.SaleOrder.create({
'partner_id': self.partner_18.id,
'pricelist_id': my_pricelist.id,
'order_line': [(0, 0, {
'name': 'PC Assamble + 2GB RAM',
'product_id': self.product_4.id,
'product_uom_qty': 1,
'product_uom': self.product_uom_unit.id,
'price_unit': 750.00,
})],
})
# Add of delivery cost in Sales order
delivery_wizard = Form(self.env['choose.delivery.carrier'].with_context({
'default_order_id': sale_pricelist_based_delivery_charges.id,
'default_carrier_id': self.normal_delivery.id
}))
self.assertEqual(delivery_wizard.delivery_price, 5.0, "Delivery cost does not correspond to 5.0 in wizard")
delivery_wizard.save().button_confirm()
line = self.SaleOrderLine.search([('order_id', '=', sale_pricelist_based_delivery_charges.id),
('product_id', '=', self.normal_delivery.product_id.id)])
self.assertEqual(len(line), 1, "Delivery cost hasn't been added to SO")
self.assertEqual(line.price_subtotal, 5.0, "Delivery cost does not correspond to 5.0")
def test_01_taxes_on_delivery_cost(self):
# Creating taxes and fiscal position
tax_price_include = self.env['account.tax'].create({
'name': '10% inc',
'type_tax_use': 'sale',
'amount_type': 'percent',
'amount': 10,
'price_include': True,
'include_base_amount': True,
})
tax_price_exclude = self.env['account.tax'].create({
'name': '15% exc',
'type_tax_use': 'sale',
'amount_type': 'percent',
'amount': 15,
})
fiscal_position = self.env['account.fiscal.position'].create({
'name': 'fiscal_pos_a',
'tax_ids': [
(0, None, {
'tax_src_id': tax_price_include.id,
'tax_dest_id': tax_price_exclude.id,
}),
],
})
# Setting tax on delivery product
self.normal_delivery.product_id.taxes_id = tax_price_include
# Create sales order
order_form = Form(self.env['sale.order'].with_context(tracking_disable=True))
order_form.partner_id = self.partner_18
order_form.pricelist_id = self.pricelist
order_form.fiscal_position_id = fiscal_position
# Try adding delivery product as a normal product
with order_form.order_line.new() as line:
line.product_id = self.normal_delivery.product_id
line.product_uom_qty = 1.0
line.product_uom = self.product_uom_unit
sale_order = order_form.save()
self.assertRecordValues(sale_order.order_line, [{'price_subtotal': 9.09, 'price_total': 10.45}])
# Now trying to add the delivery line using the delivery wizard, the results should be the same as before
delivery_wizard = Form(self.env['choose.delivery.carrier'].with_context(default_order_id=sale_order.id,
default_carrier_id=self.normal_delivery.id))
choose_delivery_carrier = delivery_wizard.save()
choose_delivery_carrier.button_confirm()
line = self.SaleOrderLine.search([
('order_id', '=', sale_order.id),
('product_id', '=', self.normal_delivery.product_id.id),
('is_delivery', '=', True)
])
self.assertRecordValues(line, [{'price_subtotal': 9.09, 'price_total': 10.45}])
def test_add_carrier_on_picking(self):
"""
A user confirms a SO, then adds a carrier on the picking. The invoicing
policy of the carrier is set to "Real Cost". He then confirms the
picking: a line with the carrier cost should be added to the SO
"""
self.normal_delivery.invoice_policy = 'real'
so_form = Form(self.env['sale.order'])
so_form.partner_id = self.partner_4
with so_form.order_line.new() as line:
line.product_id = self.product_2
so = so_form.save()
so.action_confirm()
picking = so.picking_ids
picking.carrier_id = self.normal_delivery
picking.move_lines.quantity_done = 1
picking.button_validate()
so.order_line.invalidate_cache(ids=so.order_line.ids)
self.assertEqual(picking.state, 'done')
self.assertRecordValues(so.order_line, [
{'product_id': self.product_2.id, 'is_delivery': False, 'product_uom_qty': 1, 'qty_delivered': 1},
{'product_id': self.normal_delivery.product_id.id, 'is_delivery': True, 'product_uom_qty': 1, 'qty_delivered': 0},
])
def test_delivery_cost_gift_card(self):
"""
A customer has a carrier with the amount greater than the one to have
free shipping cost, then uses a gift card that lowers that amount to less
than the threshold: the shipping cost should still be 0.0
"""
if "gift.card" not in self.env:
return
product_delivery_free = self.env['product.product'].create({
'name': 'Free Delivery Charges',
'type': 'service',
'list_price': 40.0,
'categ_id': self.env.ref('delivery.product_category_deliveries').id,
})
free_delivery = self.env['delivery.carrier'].create({
'name': 'Delivery Now Free Over 100',
'fixed_price': 40,
'delivery_type': 'fixed',
'product_id': product_delivery_free.id,
'free_over': True,
'amount': 100,
})
sale_normal_delivery_charges = self.SaleOrder.create({
'partner_id': self.partner_18.id,
'partner_invoice_id': self.partner_18.id,
'partner_shipping_id': self.partner_18.id,
'pricelist_id': self.pricelist.id,
'order_line': [(0, 0, {
'name': 'PC Assamble + 2GB RAM',
'product_id': self.product_4.id,
'product_uom_qty': 1,
'product_uom': self.product_uom_unit.id,
'price_unit': 120.00,
})],
})
gift_card = self.env['gift.card'].create({
'initial_amount': 40,
})
sale_normal_delivery_charges._pay_with_gift_card(gift_card)
delivery_wizard = Form(self.env['choose.delivery.carrier'].with_context({
'default_order_id': sale_normal_delivery_charges.id,
'default_carrier_id': free_delivery.id
}))
delivery_wizard.save().button_confirm()
self.assertEqual(len(sale_normal_delivery_charges.order_line), 3)
self.assertEqual(sale_normal_delivery_charges.amount_untaxed, 80.0, "Delivery cost is not Added")
def test_estimated_weight(self):
"""
Test that negative qty SO lines are not included in the estimated weight calculation
of delivery carriers (since it's used when calculating their rates).
"""
sale_order = self.SaleOrder.create({
'partner_id': self.partner_18.id,
'name': 'SO - neg qty',
'order_line': [
(0, 0, {
'product_id': self.product_4.id,
'product_uom_qty': 1,
'product_uom': self.product_uom_unit.id,
}),
(0, 0, {
'product_id': self.product_2.id,
'product_uom_qty': -1,
'product_uom': self.product_uom_unit.id,
})],
})
shipping_weight = sale_order._get_estimated_weight()
self.assertEqual(shipping_weight, self.product_4.weight, "Only positive quantity products' weights should be included in estimated weight")
| 43.748768
| 17,762
|
4,044
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api, _
from odoo.exceptions import UserError
class ChooseDeliveryCarrier(models.TransientModel):
_name = 'choose.delivery.carrier'
_description = 'Delivery Carrier Selection Wizard'
order_id = fields.Many2one('sale.order', required=True, ondelete="cascade")
partner_id = fields.Many2one('res.partner', related='order_id.partner_id', required=True)
carrier_id = fields.Many2one(
'delivery.carrier',
string="Shipping Method",
help="Choose the method to deliver your goods",
required=True,
)
delivery_type = fields.Selection(related='carrier_id.delivery_type')
delivery_price = fields.Float()
display_price = fields.Float(string='Cost', readonly=True)
currency_id = fields.Many2one('res.currency', related='order_id.currency_id')
company_id = fields.Many2one('res.company', related='order_id.company_id')
available_carrier_ids = fields.Many2many("delivery.carrier", compute='_compute_available_carrier', string="Available Carriers")
invoicing_message = fields.Text(compute='_compute_invoicing_message')
delivery_message = fields.Text(readonly=True)
@api.onchange('carrier_id')
def _onchange_carrier_id(self):
self.delivery_message = False
if self.delivery_type in ('fixed', 'base_on_rule'):
vals = self._get_shipment_rate()
if vals.get('error_message'):
return {'error': vals['error_message']}
else:
self.display_price = 0
self.delivery_price = 0
@api.onchange('order_id')
def _onchange_order_id(self):
# fixed and base_on_rule delivery price will computed on each carrier change so no need to recompute here
if self.carrier_id and self.order_id.delivery_set and self.delivery_type not in ('fixed', 'base_on_rule'):
vals = self._get_shipment_rate()
if vals.get('error_message'):
warning = {
'title': '%s Error' % self.carrier_id.name,
'message': vals.get('error_message'),
'type': 'notification',
}
return {'warning': warning}
@api.depends('carrier_id')
def _compute_invoicing_message(self):
self.ensure_one()
if self.carrier_id.invoice_policy == 'real':
self.invoicing_message = _('The shipping price will be set once the delivery is done.')
else:
self.invoicing_message = ""
@api.depends('partner_id')
def _compute_available_carrier(self):
for rec in self:
carriers = self.env['delivery.carrier'].search(['|', ('company_id', '=', False), ('company_id', '=', rec.order_id.company_id.id)])
rec.available_carrier_ids = carriers.available_carriers(rec.order_id.partner_shipping_id) if rec.partner_id else carriers
def _get_shipment_rate(self):
vals = self.carrier_id.rate_shipment(self.order_id)
if vals.get('success'):
self.delivery_message = vals.get('warning_message', False)
self.delivery_price = vals['price']
self.display_price = vals['carrier_price']
return {}
return {'error_message': vals['error_message']}
def update_price(self):
vals = self._get_shipment_rate()
if vals.get('error_message'):
raise UserError(vals.get('error_message'))
return {
'name': _('Add a shipping method'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'choose.delivery.carrier',
'res_id': self.id,
'target': 'new',
}
def button_confirm(self):
self.order_id.set_delivery_line(self.carrier_id, self.delivery_price)
self.order_id.write({
'recompute_delivery_price': False,
'delivery_message': self.delivery_message,
})
| 43.021277
| 4,044
|
3,506
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.tools.float_utils import float_compare
class ChooseDeliveryPackage(models.TransientModel):
_name = 'choose.delivery.package'
_description = 'Delivery Package Selection Wizard'
@api.model
def default_get(self, fields_list):
defaults = super().default_get(fields_list)
if 'shipping_weight' in fields_list:
picking = self.env['stock.picking'].browse(defaults.get('picking_id'))
move_line_ids = picking.move_line_ids.filtered(lambda m:
float_compare(m.qty_done, 0.0, precision_rounding=m.product_uom_id.rounding) > 0
and not m.result_package_id
)
total_weight = 0.0
for ml in move_line_ids:
qty = ml.product_uom_id._compute_quantity(ml.qty_done, ml.product_id.uom_id)
total_weight += qty * ml.product_id.weight
defaults['shipping_weight'] = total_weight
return defaults
picking_id = fields.Many2one('stock.picking', 'Picking')
delivery_package_type_id = fields.Many2one('stock.package.type', 'Delivery Package Type', check_company=True)
shipping_weight = fields.Float('Shipping Weight')
weight_uom_name = fields.Char(string='Weight unit of measure label', compute='_compute_weight_uom_name')
company_id = fields.Many2one(related='picking_id.company_id')
@api.depends('delivery_package_type_id')
def _compute_weight_uom_name(self):
weight_uom_id = self.env['product.template']._get_weight_uom_id_from_ir_config_parameter()
for package in self:
package.weight_uom_name = weight_uom_id.name
@api.onchange('delivery_package_type_id', 'shipping_weight')
def _onchange_package_type_weight(self):
if self.delivery_package_type_id.max_weight and self.shipping_weight > self.delivery_package_type_id.max_weight:
warning_mess = {
'title': _('Package too heavy!'),
'message': _('The weight of your package is higher than the maximum weight authorized for this package type. Please choose another package type.')
}
return {'warning': warning_mess}
def action_put_in_pack(self):
picking_move_lines = self.picking_id.move_line_ids
if not self.picking_id.picking_type_id.show_reserved and not self.env.context.get('barcode_view'):
picking_move_lines = self.picking_id.move_line_nosuggest_ids
move_line_ids = picking_move_lines.filtered(lambda ml:
float_compare(ml.qty_done, 0.0, precision_rounding=ml.product_uom_id.rounding) > 0
and not ml.result_package_id
)
if not move_line_ids:
move_line_ids = picking_move_lines.filtered(lambda ml: float_compare(ml.product_uom_qty, 0.0,
precision_rounding=ml.product_uom_id.rounding) > 0 and float_compare(ml.qty_done, 0.0,
precision_rounding=ml.product_uom_id.rounding) == 0)
delivery_package = self.picking_id._put_in_pack(move_line_ids)
# write shipping weight and package type on 'stock_quant_package' if needed
if self.delivery_package_type_id:
delivery_package.package_type_id = self.delivery_package_type_id
if self.shipping_weight:
delivery_package.shipping_weight = self.shipping_weight
| 51.558824
| 3,506
|
9,146
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, api, _
from odoo.exceptions import UserError
class SaleOrder(models.Model):
_inherit = 'sale.order'
carrier_id = fields.Many2one('delivery.carrier', string="Delivery Method", domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]", help="Fill this field if you plan to invoice the shipping based on picking.")
delivery_message = fields.Char(readonly=True, copy=False)
delivery_rating_success = fields.Boolean(copy=False)
delivery_set = fields.Boolean(compute='_compute_delivery_state')
recompute_delivery_price = fields.Boolean('Delivery cost should be recomputed')
is_all_service = fields.Boolean("Service Product", compute="_compute_is_service_products")
@api.depends('order_line')
def _compute_is_service_products(self):
for so in self:
so.is_all_service = all(line.product_id.type == 'service' for line in so.order_line.filtered(lambda x: not x.display_type))
def _compute_amount_total_without_delivery(self):
self.ensure_one()
delivery_cost = sum([l.price_total for l in self.order_line if l.is_delivery])
return super()._compute_amount_total_without_delivery() - delivery_cost
@api.depends('order_line')
def _compute_delivery_state(self):
for order in self:
order.delivery_set = any(line.is_delivery for line in order.order_line)
@api.onchange('order_line', 'partner_id', 'partner_shipping_id')
def onchange_order_line(self):
self.ensure_one()
delivery_line = self.order_line.filtered('is_delivery')
if delivery_line:
self.recompute_delivery_price = True
def _get_update_prices_lines(self):
""" Exclude delivery lines from price list recomputation based on product instead of carrier """
lines = super()._get_update_prices_lines()
return lines.filtered(lambda line: not line.is_delivery)
def _remove_delivery_line(self):
delivery_lines = self.env['sale.order.line'].search([('order_id', 'in', self.ids), ('is_delivery', '=', True)])
if not delivery_lines:
return
to_delete = delivery_lines.filtered(lambda x: x.qty_invoiced == 0)
if not to_delete:
raise UserError(
_('You can not update the shipping costs on an order where it was already invoiced!\n\nThe following delivery lines (product, invoiced quantity and price) have already been processed:\n\n')
+ '\n'.join(['- %s: %s x %s' % (line.product_id.with_context(display_default_code=False).display_name, line.qty_invoiced, line.price_unit) for line in delivery_lines])
)
to_delete.unlink()
def set_delivery_line(self, carrier, amount):
# Remove delivery products from the sales order
self._remove_delivery_line()
for order in self:
order.carrier_id = carrier.id
if order.state in ('sale', 'done'):
pending_deliveries = order.picking_ids.filtered(
lambda p: p.state not in ('done', 'cancel') and not any(m.origin_returned_move_id for m in p.move_lines))
pending_deliveries.carrier_id = carrier.id
order._create_delivery_line(carrier, amount)
return True
def action_open_delivery_wizard(self):
view_id = self.env.ref('delivery.choose_delivery_carrier_view_form').id
if self.env.context.get('carrier_recompute'):
name = _('Update shipping cost')
carrier = self.carrier_id
else:
name = _('Add a shipping method')
carrier = (
self.with_company(self.company_id).partner_shipping_id.property_delivery_carrier_id
or self.with_company(self.company_id).partner_shipping_id.commercial_partner_id.property_delivery_carrier_id
)
return {
'name': name,
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'choose.delivery.carrier',
'view_id': view_id,
'views': [(view_id, 'form')],
'target': 'new',
'context': {
'default_order_id': self.id,
'default_carrier_id': carrier.id,
}
}
def _create_delivery_line(self, carrier, price_unit):
SaleOrderLine = self.env['sale.order.line']
context = {}
if self.partner_id:
# set delivery detail in the customer language
context['lang'] = self.partner_id.lang
carrier = carrier.with_context(lang=self.partner_id.lang)
# Apply fiscal position
taxes = carrier.product_id.taxes_id.filtered(lambda t: t.company_id.id == self.company_id.id)
taxes_ids = taxes.ids
if self.partner_id and self.fiscal_position_id:
taxes_ids = self.fiscal_position_id.map_tax(taxes).ids
# Create the sales order line
if carrier.product_id.description_sale:
so_description = '%s: %s' % (carrier.name,
carrier.product_id.description_sale)
else:
so_description = carrier.name
values = {
'order_id': self.id,
'name': so_description,
'product_uom_qty': 1,
'product_uom': carrier.product_id.uom_id.id,
'product_id': carrier.product_id.id,
'tax_id': [(6, 0, taxes_ids)],
'is_delivery': True,
}
if carrier.invoice_policy == 'real':
values['price_unit'] = 0
values['name'] += _(' (Estimated Cost: %s )', self._format_currency_amount(price_unit))
else:
values['price_unit'] = price_unit
if carrier.free_over and self.currency_id.is_zero(price_unit) :
values['name'] += '\n' + _('Free Shipping')
if self.order_line:
values['sequence'] = self.order_line[-1].sequence + 1
sol = SaleOrderLine.sudo().create(values)
del context
return sol
def _format_currency_amount(self, amount):
pre = post = u''
if self.currency_id.position == 'before':
pre = u'{symbol}\N{NO-BREAK SPACE}'.format(symbol=self.currency_id.symbol or '')
else:
post = u'\N{NO-BREAK SPACE}{symbol}'.format(symbol=self.currency_id.symbol or '')
return u' {pre}{0}{post}'.format(amount, pre=pre, post=post)
@api.depends('order_line.is_delivery', 'order_line.is_downpayment')
def _get_invoice_status(self):
super()._get_invoice_status()
for order in self:
if order.invoice_status in ['no', 'invoiced']:
continue
order_lines = order.order_line.filtered(lambda x: not x.is_delivery and not x.is_downpayment and not x.display_type and x.invoice_status != 'invoiced')
if all(line.product_id.invoice_policy == 'delivery' and line.invoice_status == 'no' for line in order_lines):
order.invoice_status = 'no'
def _get_estimated_weight(self):
self.ensure_one()
weight = 0.0
for order_line in self.order_line.filtered(lambda l: l.product_id.type in ['product', 'consu'] and not l.is_delivery and not l.display_type and l.product_uom_qty > 0):
weight += order_line.product_qty * order_line.product_id.weight
return weight
class SaleOrderLine(models.Model):
_inherit = 'sale.order.line'
is_delivery = fields.Boolean(string="Is a Delivery", default=False)
product_qty = fields.Float(compute='_compute_product_qty', string='Product Qty', digits='Product Unit of Measure')
recompute_delivery_price = fields.Boolean(related='order_id.recompute_delivery_price')
def _is_not_sellable_line(self):
return self.is_delivery or super(SaleOrderLine, self)._is_not_sellable_line()
@api.depends('product_id', 'product_uom', 'product_uom_qty')
def _compute_product_qty(self):
for line in self:
if not line.product_id or not line.product_uom or not line.product_uom_qty:
line.product_qty = 0.0
continue
line.product_qty = line.product_uom._compute_quantity(line.product_uom_qty, line.product_id.uom_id)
def unlink(self):
for line in self:
if line.is_delivery:
line.order_id.carrier_id = False
return super(SaleOrderLine, self).unlink()
def _is_delivery(self):
self.ensure_one()
return self.is_delivery
# override to allow deletion of delivery line in a confirmed order
def _check_line_unlink(self):
"""
Extend the allowed deletion policy of SO lines.
Lines that are delivery lines can be deleted from a confirmed order.
:rtype: recordset sale.order.line
:returns: set of lines that cannot be deleted
"""
undeletable_lines = super()._check_line_unlink()
return undeletable_lines.filtered(lambda line: not line.is_delivery)
| 44.614634
| 9,146
|
371
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
property_delivery_carrier_id = fields.Many2one('delivery.carrier', company_dependent=True, string="Delivery Method", help="Default delivery method used in sales orders.")
| 37.1
| 371
|
407
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields
class ProductTemplate(models.Model):
_inherit = 'product.template'
hs_code = fields.Char(
string="HS Code",
help="Standardized code for international shipping and goods declaration. At the moment, only used for the FedEx shipping provider.",
)
| 31.307692
| 407
|
3,793
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.tools.sql import column_exists, create_column
class StockMove(models.Model):
_inherit = 'stock.move'
def _auto_init(self):
if not column_exists(self.env.cr, "stock_move", "weight"):
# In case of a big database with a lot of stock moves, the RAM gets exhausted
# To prevent a process from being killed We create the column 'weight' manually
# Then we do the computation in a query by multiplying product weight with qty
create_column(self.env.cr, "stock_move", "weight", "numeric")
self.env.cr.execute("""
UPDATE stock_move move
SET weight = move.product_qty * product.weight
FROM product_product product
WHERE move.product_id = product.id
AND move.state != 'cancel'
""")
return super()._auto_init()
weight = fields.Float(compute='_cal_move_weight', digits='Stock Weight', store=True, compute_sudo=True)
@api.depends('product_id', 'product_uom_qty', 'product_uom')
def _cal_move_weight(self):
moves_with_weight = self.filtered(lambda moves: moves.product_id.weight > 0.00)
for move in moves_with_weight:
move.weight = (move.product_qty * move.product_id.weight)
(self - moves_with_weight).weight = 0
def _get_new_picking_values(self):
vals = super(StockMove, self)._get_new_picking_values()
carrier_id = self.group_id.sale_id.carrier_id.id
vals['carrier_id'] = any(rule.propagate_carrier for rule in self.rule_id) and carrier_id
return vals
def _key_assign_picking(self):
keys = super(StockMove, self)._key_assign_picking()
return keys + (self.sale_line_id.order_id.carrier_id,)
class StockMoveLine(models.Model):
_inherit = 'stock.move.line'
sale_price = fields.Float(compute='_compute_sale_price')
destination_country_code = fields.Char(related='picking_id.destination_country_code')
carrier_id = fields.Many2one(related='picking_id.carrier_id')
@api.depends('qty_done', 'product_uom_id', 'product_id', 'move_id.sale_line_id', 'move_id.sale_line_id.price_reduce_taxinc', 'move_id.sale_line_id.product_uom')
def _compute_sale_price(self):
for move_line in self:
if move_line.move_id.sale_line_id:
unit_price = move_line.move_id.sale_line_id.price_reduce_taxinc
qty = move_line.product_uom_id._compute_quantity(move_line.qty_done, move_line.move_id.sale_line_id.product_uom)
else:
unit_price = move_line.product_id.list_price
qty = move_line.product_uom_id._compute_quantity(move_line.qty_done, move_line.product_id.uom_id)
move_line.sale_price = unit_price * qty
super(StockMoveLine, self)._compute_sale_price()
def _get_aggregated_product_quantities(self, **kwargs):
"""Returns dictionary of products and corresponding values of interest + hs_code
Unfortunately because we are working with aggregated data, we have to loop through the
aggregation to add more values to each datum. This extension adds on the hs_code value.
returns: dictionary {same_key_as_super: {same_values_as_super, hs_code}, ...}
"""
aggregated_move_lines = super()._get_aggregated_product_quantities(**kwargs)
for aggregated_move_line in aggregated_move_lines:
hs_code = aggregated_move_lines[aggregated_move_line]['product'].product_tmpl_id.hs_code
aggregated_move_lines[aggregated_move_line]['hs_code'] = hs_code
return aggregated_move_lines
| 49.907895
| 3,793
|
16,326
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
from collections import defaultdict
from odoo import models, fields, api, _
from odoo.exceptions import UserError
from odoo.tools.sql import column_exists, create_column
class StockQuantPackage(models.Model):
_inherit = "stock.quant.package"
@api.depends('quant_ids')
def _compute_weight(self):
if self.env.context.get('picking_id'):
package_weights = defaultdict(float)
# Ordering by qty_done prevents the default ordering by groupby fields that can inject multiple Left Joins in the resulting query.
res_groups = self.env['stock.move.line'].read_group(
[('result_package_id', 'in', self.ids), ('product_id', '!=', False), ('picking_id', '=', self.env.context['picking_id'])],
['id:count'],
['result_package_id', 'product_id', 'product_uom_id', 'qty_done'],
lazy=False, orderby='qty_done asc'
)
for res_group in res_groups:
product_id = self.env['product.product'].browse(res_group['product_id'][0])
product_uom_id = self.env['uom.uom'].browse(res_group['product_uom_id'][0])
package_weights[res_group['result_package_id'][0]] += (
res_group['__count']
* product_uom_id._compute_quantity(res_group['qty_done'], product_id.uom_id)
* product_id.weight
)
for package in self:
if self.env.context.get('picking_id'):
package.weight = package_weights[package.id]
else:
weight = 0.0
for quant in package.quant_ids:
weight += quant.quantity * quant.product_id.weight
package.weight = weight
def _get_default_weight_uom(self):
return self.env['product.template']._get_weight_uom_name_from_ir_config_parameter()
def _compute_weight_uom_name(self):
for package in self:
package.weight_uom_name = self.env['product.template']._get_weight_uom_name_from_ir_config_parameter()
weight = fields.Float(compute='_compute_weight', help="Total weight of all the products contained in the package.")
weight_uom_name = fields.Char(string='Weight unit of measure label', compute='_compute_weight_uom_name', readonly=True, default=_get_default_weight_uom)
shipping_weight = fields.Float(string='Shipping Weight', help="Total weight of the package.")
class StockPicking(models.Model):
_inherit = 'stock.picking'
def _auto_init(self):
if not column_exists(self.env.cr, "stock_picking", "weight"):
# In order to speed up module installation when dealing with hefty data
# We create the column weight manually, but the computation will be skipped
# Therefore we do the computation in a query by getting weight sum from stock moves
create_column(self.env.cr, "stock_picking", "weight", "numeric")
self.env.cr.execute("""
WITH computed_weight AS (
SELECT SUM(weight) AS weight_sum, picking_id
FROM stock_move
WHERE picking_id IS NOT NULL
GROUP BY picking_id
)
UPDATE stock_picking
SET weight = weight_sum
FROM computed_weight
WHERE stock_picking.id = computed_weight.picking_id;
""")
return super()._auto_init()
@api.depends('move_line_ids', 'move_line_ids.result_package_id')
def _compute_packages(self):
for package in self:
packs = set()
if self.env['stock.move.line'].search_count([('picking_id', '=', package.id), ('result_package_id', '!=', False)]):
for move_line in package.move_line_ids:
if move_line.result_package_id:
packs.add(move_line.result_package_id.id)
package.package_ids = list(packs)
@api.depends('move_line_ids', 'move_line_ids.result_package_id', 'move_line_ids.product_uom_id', 'move_line_ids.qty_done')
def _compute_bulk_weight(self):
picking_weights = defaultdict(float)
# Ordering by qty_done prevents the default ordering by groupby fields that can inject multiple Left Joins in the resulting query.
res_groups = self.env['stock.move.line'].read_group(
[('picking_id', 'in', self.ids), ('product_id', '!=', False), ('result_package_id', '=', False)],
['id:count'],
['picking_id', 'product_id', 'product_uom_id', 'qty_done'],
lazy=False, orderby='qty_done asc'
)
products_by_id = {
product_res['id']: (product_res['uom_id'][0], product_res['weight'])
for product_res in
self.env['product.product'].with_context(active_test=False).search_read(
[('id', 'in', list(set(grp["product_id"][0] for grp in res_groups)))], ['uom_id', 'weight'])
}
for res_group in res_groups:
uom_id, weight = products_by_id[res_group['product_id'][0]]
uom = self.env['uom.uom'].browse(uom_id)
product_uom_id = self.env['uom.uom'].browse(res_group['product_uom_id'][0])
picking_weights[res_group['picking_id'][0]] += (
res_group['__count']
* product_uom_id._compute_quantity(res_group['qty_done'], uom)
* weight
)
for picking in self:
picking.weight_bulk = picking_weights[picking.id]
@api.depends('move_line_ids.result_package_id', 'move_line_ids.result_package_id.shipping_weight', 'weight_bulk')
def _compute_shipping_weight(self):
for picking in self:
# if shipping weight is not assigned => default to calculated product weight
picking.shipping_weight = picking.weight_bulk + sum([pack.shipping_weight or pack.weight for pack in picking.package_ids])
def _get_default_weight_uom(self):
return self.env['product.template']._get_weight_uom_name_from_ir_config_parameter()
def _compute_weight_uom_name(self):
for package in self:
package.weight_uom_name = self.env['product.template']._get_weight_uom_name_from_ir_config_parameter()
carrier_price = fields.Float(string="Shipping Cost")
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
carrier_id = fields.Many2one("delivery.carrier", string="Carrier", check_company=True)
weight = fields.Float(compute='_cal_weight', digits='Stock Weight', store=True, help="Total weight of the products in the picking.", compute_sudo=True)
carrier_tracking_ref = fields.Char(string='Tracking Reference', copy=False)
carrier_tracking_url = fields.Char(string='Tracking URL', compute='_compute_carrier_tracking_url')
weight_uom_name = fields.Char(string='Weight unit of measure label', compute='_compute_weight_uom_name', readonly=True, default=_get_default_weight_uom)
package_ids = fields.Many2many('stock.quant.package', compute='_compute_packages', string='Packages')
weight_bulk = fields.Float('Bulk Weight', compute='_compute_bulk_weight', help="Total weight of products which are not in a package.")
shipping_weight = fields.Float("Weight for Shipping", compute='_compute_shipping_weight',
help="Total weight of packages and products not in a package. Packages with no shipping weight specified will default to their products' total weight. This is the weight used to compute the cost of the shipping.")
is_return_picking = fields.Boolean(compute='_compute_return_picking')
return_label_ids = fields.One2many('ir.attachment', compute='_compute_return_label')
destination_country_code = fields.Char(related='partner_id.country_id.code', string="Destination Country")
@api.depends('carrier_id', 'carrier_tracking_ref')
def _compute_carrier_tracking_url(self):
for picking in self:
picking.carrier_tracking_url = picking.carrier_id.get_tracking_link(picking) if picking.carrier_id and picking.carrier_tracking_ref else False
@api.depends('carrier_id', 'move_ids_without_package')
def _compute_return_picking(self):
for picking in self:
if picking.carrier_id and picking.carrier_id.can_generate_return:
picking.is_return_picking = any(m.origin_returned_move_id for m in picking.move_ids_without_package)
else:
picking.is_return_picking = False
def _compute_return_label(self):
for picking in self:
if picking.carrier_id:
picking.return_label_ids = self.env['ir.attachment'].search([('res_model', '=', 'stock.picking'), ('res_id', '=', picking.id), ('name', 'like', '%s%%' % picking.carrier_id.get_return_label_prefix())])
else:
picking.return_label_ids = False
def get_multiple_carrier_tracking(self):
self.ensure_one()
try:
return json.loads(self.carrier_tracking_url)
except (ValueError, TypeError):
return False
@api.depends('move_lines')
def _cal_weight(self):
for picking in self:
picking.weight = sum(move.weight for move in picking.move_lines if move.state != 'cancel')
def _send_confirmation_email(self):
for pick in self:
if pick.carrier_id and pick.carrier_id.integration_level == 'rate_and_ship' and pick.picking_type_code != 'incoming' and not pick.carrier_tracking_ref and pick.picking_type_id.print_label:
pick.sudo().send_to_shipper()
pick._check_carrier_details_compliance()
return super(StockPicking, self)._send_confirmation_email()
def _pre_put_in_pack_hook(self, move_line_ids):
res = super(StockPicking, self)._pre_put_in_pack_hook(move_line_ids)
if not res:
if self.carrier_id:
return self._set_delivery_package_type()
else:
return res
def _set_delivery_package_type(self):
""" This method returns an action allowing to set the package type and the shipping weight
on the stock.quant.package.
"""
self.ensure_one()
view_id = self.env.ref('delivery.choose_delivery_package_view_form').id
context = dict(
self.env.context,
current_package_carrier_type=self.carrier_id.delivery_type,
default_picking_id=self.id
)
# As we pass the `delivery_type` ('fixed' or 'base_on_rule' by default) in a key who
# correspond to the `package_carrier_type` ('none' to default), we make a conversion.
# No need conversion for other carriers as the `delivery_type` and
#`package_carrier_type` will be the same in these cases.
if context['current_package_carrier_type'] in ['fixed', 'base_on_rule']:
context['current_package_carrier_type'] = 'none'
return {
'name': _('Package Details'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'choose.delivery.package',
'view_id': view_id,
'views': [(view_id, 'form')],
'target': 'new',
'context': context,
}
def send_to_shipper(self):
self.ensure_one()
res = self.carrier_id.send_shipping(self)[0]
if self.carrier_id.free_over and self.sale_id:
amount_without_delivery = self.sale_id._compute_amount_total_without_delivery()
if self.carrier_id._compute_currency(self.sale_id, amount_without_delivery, 'pricelist_to_company') >= self.carrier_id.amount:
res['exact_price'] = 0.0
self.carrier_price = res['exact_price'] * (1.0 + (self.carrier_id.margin / 100.0))
if res['tracking_number']:
previous_pickings = self.env['stock.picking']
previous_moves = self.move_lines.move_orig_ids
while previous_moves:
previous_pickings |= previous_moves.picking_id
previous_moves = previous_moves.move_orig_ids
without_tracking = previous_pickings.filtered(lambda p: not p.carrier_tracking_ref)
(self + without_tracking).carrier_tracking_ref = res['tracking_number']
for p in previous_pickings - without_tracking:
p.carrier_tracking_ref += "," + res['tracking_number']
order_currency = self.sale_id.currency_id or self.company_id.currency_id
msg = _(
"Shipment sent to carrier %(carrier_name)s for shipping with tracking number %(ref)s<br/>Cost: %(price).2f %(currency)s",
carrier_name=self.carrier_id.name,
ref=self.carrier_tracking_ref,
price=self.carrier_price,
currency=order_currency.name
)
self.message_post(body=msg)
self._add_delivery_cost_to_so()
def _check_carrier_details_compliance(self):
"""Hook to check if a delivery is compliant in regard of the carrier.
"""
return
def print_return_label(self):
self.ensure_one()
self.carrier_id.get_return_label(self)
def _add_delivery_cost_to_so(self):
self.ensure_one()
sale_order = self.sale_id
if sale_order and self.carrier_id.invoice_policy == 'real' and self.carrier_price:
delivery_lines = sale_order.order_line.filtered(lambda l: l.is_delivery and l.currency_id.is_zero(l.price_unit) and l.product_id == self.carrier_id.product_id)
if not delivery_lines:
delivery_lines = [sale_order._create_delivery_line(self.carrier_id, self.carrier_price)]
delivery_line = delivery_lines[0]
delivery_line[0].write({
'price_unit': self.carrier_price,
# remove the estimated price from the description
'name': self.carrier_id.with_context(lang=self.partner_id.lang).name,
})
def open_website_url(self):
self.ensure_one()
if not self.carrier_tracking_url:
raise UserError(_("Your delivery method has no redirect on courier provider's website to track this order."))
carrier_trackers = []
try:
carrier_trackers = json.loads(self.carrier_tracking_url)
except ValueError:
carrier_trackers = self.carrier_tracking_url
else:
msg = "Tracking links for shipment: <br/>"
for tracker in carrier_trackers:
msg += '<a href=' + tracker[1] + '>' + tracker[0] + '</a><br/>'
self.message_post(body=msg)
return self.env["ir.actions.actions"]._for_xml_id("delivery.act_delivery_trackers_url")
client_action = {
'type': 'ir.actions.act_url',
'name': "Shipment Tracking Page",
'target': 'new',
'url': self.carrier_tracking_url,
}
return client_action
def cancel_shipment(self):
for picking in self:
picking.carrier_id.cancel_shipment(self)
msg = "Shipment %s cancelled" % picking.carrier_tracking_ref
picking.message_post(body=msg)
picking.carrier_tracking_ref = False
def _get_estimated_weight(self):
self.ensure_one()
weight = 0.0
for move in self.move_lines:
weight += move.product_qty * move.product_id.weight
return weight
def _should_generate_commercial_invoice(self):
self.ensure_one()
return self.picking_type_id.warehouse_id.partner_id.country_id != self.partner_id.country_id
class StockReturnPicking(models.TransientModel):
_inherit = 'stock.return.picking'
def _create_returns(self):
# Prevent copy of the carrier and carrier price when generating return picking
# (we have no integration of returns for now)
new_picking, pick_type_id = super(StockReturnPicking, self)._create_returns()
picking = self.env['stock.picking'].browse(new_picking)
picking.write({'carrier_id': False,
'carrier_price': 0.0})
return new_picking, pick_type_id
| 50.233846
| 16,326
|
6,960
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, api, _
from odoo.tools.safe_eval import safe_eval
from odoo.exceptions import UserError, ValidationError
class PriceRule(models.Model):
_name = "delivery.price.rule"
_description = "Delivery Price Rules"
_order = 'sequence, list_price, id'
@api.depends('variable', 'operator', 'max_value', 'list_base_price', 'list_price', 'variable_factor')
def _compute_name(self):
for rule in self:
name = 'if %s %s %.02f then' % (rule.variable, rule.operator, rule.max_value)
if rule.list_base_price and not rule.list_price:
name = '%s fixed price %.02f' % (name, rule.list_base_price)
elif rule.list_price and not rule.list_base_price:
name = '%s %.02f times %s' % (name, rule.list_price, rule.variable_factor)
else:
name = '%s fixed price %.02f plus %.02f times %s' % (name, rule.list_base_price, rule.list_price, rule.variable_factor)
rule.name = name
name = fields.Char(compute='_compute_name')
sequence = fields.Integer(required=True, default=10)
carrier_id = fields.Many2one('delivery.carrier', 'Carrier', required=True, ondelete='cascade')
variable = fields.Selection([('weight', 'Weight'), ('volume', 'Volume'), ('wv', 'Weight * Volume'), ('price', 'Price'), ('quantity', 'Quantity')], required=True, default='weight')
operator = fields.Selection([('==', '='), ('<=', '<='), ('<', '<'), ('>=', '>='), ('>', '>')], required=True, default='<=')
max_value = fields.Float('Maximum Value', required=True)
list_base_price = fields.Float(string='Sale Base Price', digits='Product Price', required=True, default=0.0)
list_price = fields.Float('Sale Price', digits='Product Price', required=True, default=0.0)
variable_factor = fields.Selection([('weight', 'Weight'), ('volume', 'Volume'), ('wv', 'Weight * Volume'), ('price', 'Price'), ('quantity', 'Quantity')], 'Variable Factor', required=True, default='weight')
class ProviderGrid(models.Model):
_inherit = 'delivery.carrier'
delivery_type = fields.Selection(selection_add=[
('base_on_rule', 'Based on Rules'),
], ondelete={'base_on_rule': lambda recs: recs.write({
'delivery_type': 'fixed', 'fixed_price': 0,
})})
price_rule_ids = fields.One2many('delivery.price.rule', 'carrier_id', 'Pricing Rules', copy=True)
def base_on_rule_rate_shipment(self, order):
carrier = self._match_address(order.partner_shipping_id)
if not carrier:
return {'success': False,
'price': 0.0,
'error_message': _('Error: this delivery method is not available for this address.'),
'warning_message': False}
try:
price_unit = self._get_price_available(order)
except UserError as e:
return {'success': False,
'price': 0.0,
'error_message': e.args[0],
'warning_message': False}
price_unit = self._compute_currency(order, price_unit, 'company_to_pricelist')
return {'success': True,
'price': price_unit,
'error_message': False,
'warning_message': False}
def _get_conversion_currencies(self, order, conversion):
if conversion == 'company_to_pricelist':
from_currency, to_currency = order.company_id.currency_id, order.pricelist_id.currency_id
elif conversion == 'pricelist_to_company':
from_currency, to_currency = order.currency_id, order.company_id.currency_id
return from_currency, to_currency
def _compute_currency(self, order, price, conversion):
from_currency, to_currency = self._get_conversion_currencies(order, conversion)
if from_currency.id == to_currency.id:
return price
return from_currency._convert(price, to_currency, order.company_id, order.date_order or fields.Date.today())
def _get_price_available(self, order):
self.ensure_one()
self = self.sudo()
order = order.sudo()
total = weight = volume = quantity = 0
total_delivery = 0.0
for line in order.order_line:
if line.state == 'cancel':
continue
if line.is_delivery:
total_delivery += line.price_total
if not line.product_id or line.is_delivery:
continue
if line.product_id.type == "service":
continue
qty = line.product_uom._compute_quantity(line.product_uom_qty, line.product_id.uom_id)
weight += (line.product_id.weight or 0.0) * qty
volume += (line.product_id.volume or 0.0) * qty
quantity += qty
total = (order.amount_total or 0.0) - total_delivery
total = self._compute_currency(order, total, 'pricelist_to_company')
return self._get_price_from_picking(total, weight, volume, quantity)
def _get_price_dict(self, total, weight, volume, quantity):
'''Hook allowing to retrieve dict to be used in _get_price_from_picking() function.
Hook to be overridden when we need to add some field to product and use it in variable factor from price rules. '''
return {
'price': total,
'volume': volume,
'weight': weight,
'wv': volume * weight,
'quantity': quantity
}
def _get_price_from_picking(self, total, weight, volume, quantity):
price = 0.0
criteria_found = False
price_dict = self._get_price_dict(total, weight, volume, quantity)
if self.free_over and total >= self.amount:
return 0
for line in self.price_rule_ids:
test = safe_eval(line.variable + line.operator + str(line.max_value), price_dict)
if test:
price = line.list_base_price + line.list_price * price_dict[line.variable_factor]
criteria_found = True
break
if not criteria_found:
raise UserError(_("No price rule matching this order; delivery cost cannot be computed."))
return price
def base_on_rule_send_shipping(self, pickings):
res = []
for p in pickings:
carrier = self._match_address(p.partner_id)
if not carrier:
raise ValidationError(_('There is no matching delivery rule.'))
res = res + [{'exact_price': p.carrier_id._get_price_available(p.sale_id) if p.sale_id else 0.0, # TODO cleanme
'tracking_number': False}]
return res
def base_on_rule_get_tracking_link(self, picking):
return False
def base_on_rule_cancel_shipment(self, pickings):
raise NotImplementedError()
| 45.789474
| 6,960
|
749
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, api
class PackageType(models.Model):
_inherit = 'stock.package.type'
shipper_package_code = fields.Char('Carrier Code')
package_carrier_type = fields.Selection([('none', 'No carrier integration')], string='Carrier', default='none')
@api.onchange('package_carrier_type')
def _onchange_carrier_type(self):
carrier_id = self.env['delivery.carrier'].search([('delivery_type', '=', self.package_carrier_type)], limit=1)
if carrier_id:
self.shipper_package_code = carrier_id._get_default_custom_package_code()
else:
self.shipper_package_code = False
| 39.421053
| 749
|
13,290
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import psycopg2
from odoo import api, fields, models, registry, SUPERUSER_ID, _
_logger = logging.getLogger(__name__)
class DeliveryCarrier(models.Model):
_name = 'delivery.carrier'
_description = "Shipping Methods"
_order = 'sequence, id'
''' A Shipping Provider
In order to add your own external provider, follow these steps:
1. Create your model MyProvider that _inherit 'delivery.carrier'
2. Extend the selection of the field "delivery_type" with a pair
('<my_provider>', 'My Provider')
3. Add your methods:
<my_provider>_rate_shipment
<my_provider>_send_shipping
<my_provider>_get_tracking_link
<my_provider>_cancel_shipment
_<my_provider>_get_default_custom_package_code
(they are documented hereunder)
'''
# -------------------------------- #
# Internals for shipping providers #
# -------------------------------- #
name = fields.Char('Delivery Method', required=True, translate=True)
active = fields.Boolean(default=True)
sequence = fields.Integer(help="Determine the display order", default=10)
# This field will be overwritten by internal shipping providers by adding their own type (ex: 'fedex')
delivery_type = fields.Selection([('fixed', 'Fixed Price')], string='Provider', default='fixed', required=True)
integration_level = fields.Selection([('rate', 'Get Rate'), ('rate_and_ship', 'Get Rate and Create Shipment')], string="Integration Level", default='rate_and_ship', help="Action while validating Delivery Orders")
prod_environment = fields.Boolean("Environment", help="Set to True if your credentials are certified for production.")
debug_logging = fields.Boolean('Debug logging', help="Log requests in order to ease debugging")
company_id = fields.Many2one('res.company', string='Company', related='product_id.company_id', store=True, readonly=False)
product_id = fields.Many2one('product.product', string='Delivery Product', required=True, ondelete='restrict')
invoice_policy = fields.Selection([
('estimated', 'Estimated cost'),
('real', 'Real cost')
], string='Invoicing Policy', default='estimated', required=True,
help="Estimated Cost: the customer will be invoiced the estimated cost of the shipping.\nReal Cost: the customer will be invoiced the real cost of the shipping, the cost of the shipping will be updated on the SO after the delivery.")
country_ids = fields.Many2many('res.country', 'delivery_carrier_country_rel', 'carrier_id', 'country_id', 'Countries')
state_ids = fields.Many2many('res.country.state', 'delivery_carrier_state_rel', 'carrier_id', 'state_id', 'States')
zip_from = fields.Char('Zip From')
zip_to = fields.Char('Zip To')
margin = fields.Float(help='This percentage will be added to the shipping price.')
free_over = fields.Boolean('Free if order amount is above', help="If the order total amount (shipping excluded) is above or equal to this value, the customer benefits from a free shipping", default=False)
amount = fields.Float(string='Amount', help="Amount of the order to benefit from a free shipping, expressed in the company currency")
can_generate_return = fields.Boolean(compute="_compute_can_generate_return")
return_label_on_delivery = fields.Boolean(string="Generate Return Label", help="The return label is automatically generated at the delivery.")
get_return_label_from_portal = fields.Boolean(string="Return Label Accessible from Customer Portal", help="The return label can be downloaded by the customer from the customer portal.")
_sql_constraints = [
('margin_not_under_100_percent', 'CHECK (margin >= -100)', 'Margin cannot be lower than -100%'),
]
@api.depends('delivery_type')
def _compute_can_generate_return(self):
for carrier in self:
carrier.can_generate_return = False
def toggle_prod_environment(self):
for c in self:
c.prod_environment = not c.prod_environment
def toggle_debug(self):
for c in self:
c.debug_logging = not c.debug_logging
def install_more_provider(self):
return {
'name': 'New Providers',
'view_mode': 'kanban,form',
'res_model': 'ir.module.module',
'domain': [['name', '=like', 'delivery_%'], ['name', '!=', 'delivery_barcode']],
'type': 'ir.actions.act_window',
'help': _('''<p class="o_view_nocontent">
Buy Odoo Enterprise now to get more providers.
</p>'''),
}
def available_carriers(self, partner):
return self.filtered(lambda c: c._match_address(partner))
def _match_address(self, partner):
self.ensure_one()
if self.country_ids and partner.country_id not in self.country_ids:
return False
if self.state_ids and partner.state_id not in self.state_ids:
return False
if self.zip_from and (partner.zip or '').upper() < self.zip_from.upper():
return False
if self.zip_to and (partner.zip or '').upper() > self.zip_to.upper():
return False
return True
@api.onchange('integration_level')
def _onchange_integration_level(self):
if self.integration_level == 'rate':
self.invoice_policy = 'estimated'
@api.onchange('can_generate_return')
def _onchange_can_generate_return(self):
if not self.can_generate_return:
self.return_label_on_delivery = False
@api.onchange('return_label_on_delivery')
def _onchange_return_label_on_delivery(self):
if not self.return_label_on_delivery:
self.get_return_label_from_portal = False
@api.onchange('state_ids')
def onchange_states(self):
self.country_ids = [(6, 0, self.country_ids.ids + self.state_ids.mapped('country_id.id'))]
@api.onchange('country_ids')
def onchange_countries(self):
self.state_ids = [(6, 0, self.state_ids.filtered(lambda state: state.id in self.country_ids.mapped('state_ids').ids).ids)]
def _get_delivery_type(self):
"""Return the delivery type.
This method needs to be overridden by a delivery carrier module if the delivery type is not
stored on the field `delivery_type`.
"""
self.ensure_one()
return self.delivery_type
# -------------------------- #
# API for external providers #
# -------------------------- #
def rate_shipment(self, order):
''' Compute the price of the order shipment
:param order: record of sale.order
:return dict: {'success': boolean,
'price': a float,
'error_message': a string containing an error message,
'warning_message': a string containing a warning message}
# TODO maybe the currency code?
'''
self.ensure_one()
if hasattr(self, '%s_rate_shipment' % self.delivery_type):
res = getattr(self, '%s_rate_shipment' % self.delivery_type)(order)
# apply fiscal position
company = self.company_id or order.company_id or self.env.company
res['price'] = self.product_id._get_tax_included_unit_price(
company,
company.currency_id,
order.date_order,
'sale',
fiscal_position=order.fiscal_position_id,
product_price_unit=res['price'],
product_currency=company.currency_id
)
# apply margin on computed price
res['price'] = float(res['price']) * (1.0 + (self.margin / 100.0))
# save the real price in case a free_over rule overide it to 0
res['carrier_price'] = res['price']
# free when order is large enough
amount_without_delivery = order._compute_amount_total_without_delivery()
if res['success'] and self.free_over and self._compute_currency(order, amount_without_delivery, 'pricelist_to_company') >= self.amount:
res['warning_message'] = _('The shipping is free since the order amount exceeds %.2f.') % (self.amount)
res['price'] = 0.0
return res
def send_shipping(self, pickings):
''' Send the package to the service provider
:param pickings: A recordset of pickings
:return list: A list of dictionaries (one per picking) containing of the form::
{ 'exact_price': price,
'tracking_number': number }
# TODO missing labels per package
# TODO missing currency
# TODO missing success, error, warnings
'''
self.ensure_one()
if hasattr(self, '%s_send_shipping' % self.delivery_type):
return getattr(self, '%s_send_shipping' % self.delivery_type)(pickings)
def get_return_label(self,pickings, tracking_number=None, origin_date=None):
self.ensure_one()
if self.can_generate_return:
return getattr(self, '%s_get_return_label' % self.delivery_type)(pickings, tracking_number, origin_date)
def get_return_label_prefix(self):
return 'ReturnLabel-%s' % self.delivery_type
def get_tracking_link(self, picking):
''' Ask the tracking link to the service provider
:param picking: record of stock.picking
:return str: an URL containing the tracking link or False
'''
self.ensure_one()
if hasattr(self, '%s_get_tracking_link' % self.delivery_type):
return getattr(self, '%s_get_tracking_link' % self.delivery_type)(picking)
def cancel_shipment(self, pickings):
''' Cancel a shipment
:param pickings: A recordset of pickings
'''
self.ensure_one()
if hasattr(self, '%s_cancel_shipment' % self.delivery_type):
return getattr(self, '%s_cancel_shipment' % self.delivery_type)(pickings)
def log_xml(self, xml_string, func):
self.ensure_one()
if self.debug_logging:
self.flush()
db_name = self._cr.dbname
# Use a new cursor to avoid rollback that could be caused by an upper method
try:
db_registry = registry(db_name)
with db_registry.cursor() as cr:
env = api.Environment(cr, SUPERUSER_ID, {})
IrLogging = env['ir.logging']
IrLogging.sudo().create({'name': 'delivery.carrier',
'type': 'server',
'dbname': db_name,
'level': 'DEBUG',
'message': xml_string,
'path': self.delivery_type,
'func': func,
'line': 1})
except psycopg2.Error:
pass
def _get_default_custom_package_code(self):
""" Some delivery carriers require a prefix to be sent in order to use custom
packages (ie not official ones). This optional method will return it as a string.
"""
self.ensure_one()
if hasattr(self, '_%s_get_default_custom_package_code' % self.delivery_type):
return getattr(self, '_%s_get_default_custom_package_code' % self.delivery_type)()
else:
return False
# ------------------------------------------------ #
# Fixed price shipping, aka a very simple provider #
# ------------------------------------------------ #
fixed_price = fields.Float(compute='_compute_fixed_price', inverse='_set_product_fixed_price', store=True, string='Fixed Price')
@api.depends('product_id.list_price', 'product_id.product_tmpl_id.list_price')
def _compute_fixed_price(self):
for carrier in self:
carrier.fixed_price = carrier.product_id.list_price
def _set_product_fixed_price(self):
for carrier in self:
carrier.product_id.list_price = carrier.fixed_price
def fixed_rate_shipment(self, order):
carrier = self._match_address(order.partner_shipping_id)
if not carrier:
return {'success': False,
'price': 0.0,
'error_message': _('Error: this delivery method is not available for this address.'),
'warning_message': False}
price = order.pricelist_id.get_product_price(self.product_id, 1.0, order.partner_id)
return {'success': True,
'price': price,
'error_message': False,
'warning_message': False}
def fixed_send_shipping(self, pickings):
res = []
for p in pickings:
res = res + [{'exact_price': p.carrier_id.fixed_price,
'tracking_number': False}]
return res
def fixed_get_tracking_link(self, picking):
return False
def fixed_cancel_shipment(self, pickings):
raise NotImplementedError()
| 44.747475
| 13,290
|
1,893
|
py
|
PYTHON
|
15.0
|
#-*- coding:utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Email Gateway',
'version': '1.0',
'depends': ['mail'],
'category': 'Hidden/Tools',
'description': """
Retrieve incoming email on POP/IMAP servers.
============================================
Enter the parameters of your POP/IMAP account(s), and any incoming emails on
these accounts will be automatically downloaded into your Odoo system. All
POP3/IMAP-compatible servers are supported, included those that require an
encrypted SSL/TLS connection.
This can be used to easily create email-based workflows for many email-enabled Odoo documents, such as:
----------------------------------------------------------------------------------------------------------
* CRM Leads/Opportunities
* CRM Claims
* Project Issues
* Project Tasks
* Human Resource Recruitments (Applicants)
Just install the relevant application, and you can assign any of these document
types (Leads, Project Issues) to your incoming email accounts. New emails will
automatically spawn new documents of the chosen type, so it's a snap to create a
mailbox-to-Odoo integration. Even better: these documents directly act as mini
conversations synchronized by email. You can reply from within Odoo, and the
answers will automatically be collected when they come back, and attached to the
same *conversation* document.
For more specific needs, you may also assign custom-defined actions
(technically: Server Actions) to be triggered for each incoming mail.
""",
'data': [
'data/fetchmail_data.xml',
'security/ir.model.access.csv',
'views/fetchmail_views.xml',
'views/mail_mail_views.xml',
'views/res_config_settings_views.xml',
],
'demo': [],
'installable': True,
'auto_install': True,
'license': 'LGPL-3',
}
| 39.4375
| 1,893
|
12,411
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import poplib
import socket
from imaplib import IMAP4, IMAP4_SSL
from poplib import POP3, POP3_SSL
from socket import gaierror, timeout
from ssl import SSLError
from odoo import api, fields, models, tools, _
from odoo.exceptions import UserError
_logger = logging.getLogger(__name__)
MAX_POP_MESSAGES = 50
MAIL_TIMEOUT = 60
# Workaround for Python 2.7.8 bug https://bugs.python.org/issue23906
poplib._MAXLINE = 65536
# Add timeout to IMAP connections
# HACK https://bugs.python.org/issue38615
# TODO: clean in Python 3.9
IMAP4._create_socket = lambda self, timeout=MAIL_TIMEOUT: socket.create_connection((self.host or None, self.port), timeout)
class FetchmailServer(models.Model):
"""Incoming POP/IMAP mail server account"""
_name = 'fetchmail.server'
_description = 'Incoming Mail Server'
_order = 'priority'
name = fields.Char('Name', required=True)
active = fields.Boolean('Active', default=True)
state = fields.Selection([
('draft', 'Not Confirmed'),
('done', 'Confirmed'),
], string='Status', index=True, readonly=True, copy=False, default='draft')
server = fields.Char(string='Server Name', readonly=True, help="Hostname or IP of the mail server", states={'draft': [('readonly', False)]})
port = fields.Integer(readonly=True, states={'draft': [('readonly', False)]})
server_type = fields.Selection([
('pop', 'POP Server'),
('imap', 'IMAP Server'),
('local', 'Local Server'),
], string='Server Type', index=True, required=True, default='pop')
is_ssl = fields.Boolean('SSL/TLS', help="Connections are encrypted with SSL/TLS through a dedicated port (default: IMAPS=993, POP3S=995)")
attach = fields.Boolean('Keep Attachments', help="Whether attachments should be downloaded. "
"If not enabled, incoming emails will be stripped of any attachments before being processed", default=True)
original = fields.Boolean('Keep Original', help="Whether a full original copy of each email should be kept for reference "
"and attached to each processed message. This will usually double the size of your message database.")
date = fields.Datetime(string='Last Fetch Date', readonly=True)
user = fields.Char(string='Username', readonly=True, states={'draft': [('readonly', False)]})
password = fields.Char(readonly=True, states={'draft': [('readonly', False)]})
object_id = fields.Many2one('ir.model', string="Create a New Record", help="Process each incoming mail as part of a conversation "
"corresponding to this document type. This will create "
"new documents for new conversations, or attach follow-up "
"emails to the existing conversations (documents).")
priority = fields.Integer(string='Server Priority', readonly=True, states={'draft': [('readonly', False)]}, help="Defines the order of processing, lower values mean higher priority", default=5)
message_ids = fields.One2many('mail.mail', 'fetchmail_server_id', string='Messages', readonly=True)
configuration = fields.Text('Configuration', readonly=True)
script = fields.Char(readonly=True, default='/mail/static/scripts/odoo-mailgate.py')
@api.onchange('server_type', 'is_ssl', 'object_id')
def onchange_server_type(self):
self.port = 0
if self.server_type == 'pop':
self.port = self.is_ssl and 995 or 110
elif self.server_type == 'imap':
self.port = self.is_ssl and 993 or 143
conf = {
'dbname': self.env.cr.dbname,
'uid': self.env.uid,
'model': self.object_id.model if self.object_id else 'MODELNAME'
}
self.configuration = """Use the below script with the following command line options with your Mail Transport Agent (MTA)
odoo-mailgate.py --host=HOSTNAME --port=PORT -u %(uid)d -p PASSWORD -d %(dbname)s
Example configuration for the postfix mta running locally:
/etc/postfix/virtual_aliases: @youdomain odoo_mailgate@localhost
/etc/aliases:
odoo_mailgate: "|/path/to/odoo-mailgate.py --host=localhost -u %(uid)d -p PASSWORD -d %(dbname)s"
""" % conf
@api.model_create_multi
def create(self, vals_list):
res = super(FetchmailServer, self).create(vals_list)
self._update_cron()
return res
def write(self, values):
res = super(FetchmailServer, self).write(values)
self._update_cron()
return res
def unlink(self):
res = super(FetchmailServer, self).unlink()
self._update_cron()
return res
def set_draft(self):
self.write({'state': 'draft'})
return True
def connect(self):
self.ensure_one()
if self.server_type == 'imap':
if self.is_ssl:
connection = IMAP4_SSL(self.server, int(self.port))
else:
connection = IMAP4(self.server, int(self.port))
self._imap_login(connection)
elif self.server_type == 'pop':
if self.is_ssl:
connection = POP3_SSL(self.server, int(self.port), timeout=MAIL_TIMEOUT)
else:
connection = POP3(self.server, int(self.port), timeout=MAIL_TIMEOUT)
#TODO: use this to remove only unread messages
#connection.user("recent:"+server.user)
connection.user(self.user)
connection.pass_(self.password)
return connection
def _imap_login(self, connection):
"""Authenticate the IMAP connection.
Can be overridden in other module for different authentication methods.
:param connection: The IMAP connection to authenticate
"""
self.ensure_one()
connection.login(self.user, self.password)
def button_confirm_login(self):
for server in self:
try:
connection = server.connect()
server.write({'state': 'done'})
except UnicodeError as e:
raise UserError(_("Invalid server name !\n %s", tools.ustr(e)))
except (gaierror, timeout, IMAP4.abort) as e:
raise UserError(_("No response received. Check server information.\n %s", tools.ustr(e)))
except (IMAP4.error, poplib.error_proto) as err:
raise UserError(_("Server replied with following exception:\n %s", tools.ustr(err)))
except SSLError as e:
raise UserError(_("An SSL exception occurred. Check SSL/TLS configuration on server port.\n %s", tools.ustr(e)))
except (OSError, Exception) as err:
_logger.info("Failed to connect to %s server %s.", server.server_type, server.name, exc_info=True)
raise UserError(_("Connection test failed: %s", tools.ustr(err)))
finally:
try:
if connection:
if server.server_type == 'imap':
connection.close()
elif server.server_type == 'pop':
connection.quit()
except Exception:
# ignored, just a consequence of the previous exception
pass
return True
@api.model
def _fetch_mails(self):
""" Method called by cron to fetch mails from servers """
return self.search([('state', '=', 'done'), ('server_type', 'in', ['pop', 'imap'])]).fetch_mail()
def fetch_mail(self):
""" WARNING: meant for cron usage only - will commit() after each email! """
additionnal_context = {
'fetchmail_cron_running': True
}
MailThread = self.env['mail.thread']
for server in self:
_logger.info('start checking for new emails on %s server %s', server.server_type, server.name)
additionnal_context['default_fetchmail_server_id'] = server.id
count, failed = 0, 0
imap_server = None
pop_server = None
if server.server_type == 'imap':
try:
imap_server = server.connect()
imap_server.select()
result, data = imap_server.search(None, '(UNSEEN)')
for num in data[0].split():
res_id = None
result, data = imap_server.fetch(num, '(RFC822)')
imap_server.store(num, '-FLAGS', '\\Seen')
try:
res_id = MailThread.with_context(**additionnal_context).message_process(server.object_id.model, data[0][1], save_original=server.original, strip_attachments=(not server.attach))
except Exception:
_logger.info('Failed to process mail from %s server %s.', server.server_type, server.name, exc_info=True)
failed += 1
imap_server.store(num, '+FLAGS', '\\Seen')
self._cr.commit()
count += 1
_logger.info("Fetched %d email(s) on %s server %s; %d succeeded, %d failed.", count, server.server_type, server.name, (count - failed), failed)
except Exception:
_logger.info("General failure when trying to fetch mail from %s server %s.", server.server_type, server.name, exc_info=True)
finally:
if imap_server:
imap_server.close()
imap_server.logout()
elif server.server_type == 'pop':
try:
while True:
failed_in_loop = 0
num = 0
pop_server = server.connect()
(num_messages, total_size) = pop_server.stat()
pop_server.list()
for num in range(1, min(MAX_POP_MESSAGES, num_messages) + 1):
(header, messages, octets) = pop_server.retr(num)
message = (b'\n').join(messages)
res_id = None
try:
res_id = MailThread.with_context(**additionnal_context).message_process(server.object_id.model, message, save_original=server.original, strip_attachments=(not server.attach))
pop_server.dele(num)
except Exception:
_logger.info('Failed to process mail from %s server %s.', server.server_type, server.name, exc_info=True)
failed += 1
failed_in_loop += 1
self.env.cr.commit()
_logger.info("Fetched %d email(s) on %s server %s; %d succeeded, %d failed.", num, server.server_type, server.name, (num - failed_in_loop), failed_in_loop)
# Stop if (1) no more message left or (2) all messages have failed
if num_messages < MAX_POP_MESSAGES or failed_in_loop == num:
break
pop_server.quit()
except Exception:
_logger.info("General failure when trying to fetch mail from %s server %s.", server.server_type, server.name, exc_info=True)
finally:
if pop_server:
pop_server.quit()
server.write({'date': fields.Datetime.now()})
return True
@api.model
def _update_cron(self):
if self.env.context.get('fetchmail_cron_running'):
return
try:
# Enabled/Disable cron based on the number of 'done' server of type pop or imap
cron = self.env.ref('fetchmail.ir_cron_mail_gateway_action')
cron.toggle(model=self._name, domain=[('state', '=', 'done'), ('server_type', 'in', ['pop', 'imap'])])
except ValueError:
pass
| 50.044355
| 12,411
|
304
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class MailMail(models.Model):
_inherit = 'mail.mail'
fetchmail_server_id = fields.Many2one('fetchmail.server', "Inbound Mail Server", readonly=True, index=True)
| 30.4
| 304
|
1,969
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Purchase',
'version': '1.2',
'category': 'Inventory/Purchase',
'sequence': 35,
'summary': 'Purchase orders, tenders and agreements',
'description': "",
'website': 'https://www.odoo.com/app/purchase',
'depends': ['account'],
'data': [
'security/purchase_security.xml',
'security/ir.model.access.csv',
'data/digest_data.xml',
'views/account_move_views.xml',
'data/purchase_data.xml',
'data/ir_cron_data.xml',
'report/purchase_reports.xml',
'views/purchase_views.xml',
'views/res_config_settings_views.xml',
'views/product_views.xml',
'views/res_partner_views.xml',
'report/purchase_bill_views.xml',
'report/purchase_report_views.xml',
'data/mail_templates.xml',
'data/mail_template_data.xml',
'views/portal_templates.xml',
'report/purchase_order_templates.xml',
'report/purchase_quotation_templates.xml',
'views/product_packaging_views.xml',
'views/analytic_account_views.xml',
],
'demo': [
'data/purchase_demo.xml',
],
'installable': True,
'auto_install': False,
'application': True,
'assets': {
'web.assets_backend': [
'purchase/static/src/scss/purchase.scss',
'purchase/static/src/js/purchase_dashboard.js',
'purchase/static/src/js/purchase_toaster_button.js',
'purchase/static/src/js/tours/purchase.js',
],
'web.assets_frontend': [
'purchase/static/src/js/purchase_datetimepicker.js',
'purchase/static/src/scss/purchase_portal.scss',
'purchase/static/src/js/purchase_portal_sidebar.js',
],
'web.assets_qweb': [
'purchase/static/src/xml/**/*',
],
},
'license': 'LGPL-3',
}
| 33.948276
| 1,969
|
1,408
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
def convert_field(cr, model, field, target_model):
table = model.replace('.', '_')
cr.execute("""SELECT 1
FROM information_schema.columns
WHERE table_name = %s
AND column_name = %s
""", (table, field))
if not cr.fetchone():
return
cr.execute("SELECT id FROM ir_model_fields WHERE model=%s AND name=%s", (model, field))
[fields_id] = cr.fetchone()
cr.execute("""
INSERT INTO ir_property(name, type, fields_id, company_id, res_id, value_reference)
SELECT %(field)s, 'many2one', %(fields_id)s, company_id, CONCAT('{model},', id),
CONCAT('{target_model},', {field})
FROM {table} t
WHERE {field} IS NOT NULL
AND NOT EXISTS(SELECT 1
FROM ir_property
WHERE fields_id=%(fields_id)s
AND company_id=t.company_id
AND res_id=CONCAT('{model},', t.id))
""".format(**locals()), locals())
cr.execute('ALTER TABLE "{0}" DROP COLUMN "{1}" CASCADE'.format(table, field))
def migrate(cr, version):
convert_field(cr, 'res.partner', 'property_purchase_currency_id', 'res.currency')
convert_field(cr, 'product.template',
'property_account_creditor_price_difference', 'account.account')
| 40.228571
| 1,408
|
3,835
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from datetime import datetime, timedelta
from odoo import models
from odoo.tools import populate, groupby
from odoo.addons.stock.populate.stock import COMPANY_NB_WITH_STOCK
_logger = logging.getLogger(__name__)
class ResCompany(models.Model):
_inherit = 'res.company'
def _populate_factories(self):
return super()._populate_factories() + [
('po_lead', populate.randint(0, 2))
]
class PurchaseOrder(models.Model):
_inherit = 'purchase.order'
_populate_sizes = {'small': 100, 'medium': 1_500, 'large': 25_000}
_populate_dependencies = ['res.partner']
def _populate_factories(self):
now = datetime.now()
company_ids = self.env.registry.populated_models['res.company'][:COMPANY_NB_WITH_STOCK]
all_partners = self.env['res.partner'].browse(self.env.registry.populated_models['res.partner'])
partners_by_company = dict(groupby(all_partners, key=lambda par: par.company_id.id))
partners_inter_company = self.env['res.partner'].concat(*partners_by_company.get(False, []))
partners_by_company = {com: self.env['res.partner'].concat(*partners) | partners_inter_company for com, partners in partners_by_company.items() if com}
def get_date_order(values, counter, random):
# 95.45 % of picking scheduled between (-5, 10) days and follow a gauss distribution (only +-15% PO is late)
delta = random.gauss(5, 5)
return now + timedelta(days=delta)
def get_date_planned(values, counter, random):
# 95 % of PO Receipt Date between (1, 16) days after the order deadline and follow a exponential distribution
delta = random.expovariate(5) + 1
return values['date_order'] + timedelta(days=delta)
def get_partner_id(values, counter, random):
return random.choice(partners_by_company[values['company_id']]).id
def get_currency_id(values, counter, random):
company = self.env['res.company'].browse(values['company_id'])
return company.currency_id.id
return [
('company_id', populate.randomize(company_ids)),
('date_order', populate.compute(get_date_order)),
('date_planned', populate.compute(get_date_planned)),
('partner_id', populate.compute(get_partner_id)),
('currency_id', populate.compute(get_currency_id)),
]
class PurchaseOrderLine(models.Model):
_inherit = 'purchase.order.line'
_populate_sizes = {'small': 500, 'medium': 7_500, 'large': 125_000}
_populate_dependencies = ['purchase.order', 'product.product']
def _populate_factories(self):
purchase_order_ids = self.env.registry.populated_models['purchase.order']
product_ids = self.env.registry.populated_models['product.product']
def get_product_uom(values, counter, random):
product = self.env['product.product'].browse(values['product_id'])
return product.uom_id.id
def get_date_planned(values, counter, random):
po = self.env['purchase.order'].browse(values['order_id'])
return po.date_planned
return [
('order_id', populate.iterate(purchase_order_ids)),
('name', populate.constant("PO-line-{counter}")),
('product_id', populate.randomize(product_ids)),
('product_uom', populate.compute(get_product_uom)),
('taxes_id', populate.constant(False)), # to avoid slow _prepare_add_missing_fields
('date_planned', populate.compute(get_date_planned)),
('product_qty', populate.randint(1, 10)),
('price_unit', populate.randint(10, 100)),
]
| 41.684783
| 3,835
|
7,354
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import Form, tagged
from odoo.exceptions import AccessError
@tagged('post_install', '-at_install')
class TestPurchaseInvoice(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
# Create a users
group_purchase_user = cls.env.ref('purchase.group_purchase_user')
group_employee = cls.env.ref('base.group_user')
group_partner_manager = cls.env.ref('base.group_partner_manager')
cls.purchase_user = cls.env['res.users'].with_context(
no_reset_password=True
).create({
'name': 'Purchase user',
'login': 'purchaseUser',
'email': 'pu@odoo.com',
'groups_id': [(6, 0, [group_purchase_user.id, group_employee.id, group_partner_manager.id])],
})
cls.vendor = cls.env['res.partner'].create({
'name': 'Supplier',
'email': 'supplier.serv@supercompany.com',
})
user_type_expense = cls.env.ref('account.data_account_type_expenses')
cls.account_expense_product = cls.env['account.account'].create({
'code': 'EXPENSE_PROD111',
'name': 'Expense - Test Account',
'user_type_id': user_type_expense.id,
})
# Create category
cls.product_category = cls.env['product.category'].create({
'name': 'Product Category with Expense account',
'property_account_expense_categ_id': cls.account_expense_product.id
})
cls.product = cls.env['product.product'].create({
'name': "Product",
'standard_price': 200.0,
'list_price': 180.0,
'type': 'service',
})
def test_create_purchase_order(self):
"""Check a purchase user can create a vendor bill from a purchase order but not post it"""
purchase_order_form = Form(self.env['purchase.order'].with_user(self.purchase_user))
purchase_order_form.partner_id = self.vendor
with purchase_order_form.order_line.new() as line:
line.name = self.product.name
line.product_id = self.product
line.product_qty = 4
line.price_unit = 5
purchase_order = purchase_order_form.save()
purchase_order.button_confirm()
purchase_order.order_line.qty_received = 4
purchase_order.action_create_invoice()
invoice = purchase_order.invoice_ids
with self.assertRaises(AccessError):
invoice.action_post()
def test_read_purchase_order(self):
""" Check that a purchase user can read all purchase order and 'in' invoices"""
purchase_user_2 = self.purchase_user.copy({
'name': 'Purchase user 2',
'login': 'purchaseUser2',
'email': 'pu2@odoo.com',
})
purchase_order_form = Form(self.env['purchase.order'].with_user(purchase_user_2))
purchase_order_form.partner_id = self.vendor
with purchase_order_form.order_line.new() as line:
line.name = self.product.name
line.product_id = self.product
line.product_qty = 4
line.price_unit = 5
purchase_order_user2 = purchase_order_form.save()
purchase_order_user2.button_confirm()
purchase_order_user2.order_line.qty_received = 4
purchase_order_user2.action_create_invoice()
vendor_bill_user2 = purchase_order_user2.invoice_ids
# open purchase_order_user2 and vendor_bill_user2 with `self.purchase_user`
purchase_order_user1 = Form(purchase_order_user2.with_user(self.purchase_user))
purchase_order_user1 = purchase_order_user1.save()
vendor_bill_user1 = Form(vendor_bill_user2.with_user(self.purchase_user))
vendor_bill_user1 = vendor_bill_user1.save()
def test_read_purchase_order_2(self):
""" Check that a 2 purchase users with open the vendor bill the same
way even with a 'own documents only' record rule. """
# edit the account.move record rule for purchase user in order to ensure
# a user can only see his own invoices
rule = self.env.ref('purchase.purchase_user_account_move_rule')
rule.domain_force = "['&', ('move_type', 'in', ('in_invoice', 'in_refund', 'in_receipt')), ('invoice_user_id', '=', user.id)]"
# create a purchase and make a vendor bill from it as purchase user 2
purchase_user_2 = self.purchase_user.copy({
'name': 'Purchase user 2',
'login': 'purchaseUser2',
'email': 'pu2@odoo.com',
})
purchase_order_form = Form(self.env['purchase.order'].with_user(purchase_user_2))
purchase_order_form.partner_id = self.vendor
with purchase_order_form.order_line.new() as line:
line.name = self.product.name
line.product_id = self.product
line.product_qty = 4
line.price_unit = 5
purchase_order_user2 = purchase_order_form.save()
purchase_order_user2.button_confirm()
purchase_order_user2.order_line.qty_received = 4
purchase_order_user2.action_create_invoice()
vendor_bill_user2 = purchase_order_user2.invoice_ids
# check user 1 cannot read the invoice
with self.assertRaises(AccessError):
Form(vendor_bill_user2.with_user(self.purchase_user))
# Check that calling 'action_view_invoice' return the same action despite the record rule
action_user_1 = purchase_order_user2.with_user(self.purchase_user).action_view_invoice()
purchase_order_user2.invalidate_cache()
action_user_2 = purchase_order_user2.with_user(purchase_user_2).action_view_invoice()
self.assertEqual(action_user_1, action_user_2)
def test_double_validation(self):
"""Only purchase managers can approve a purchase order when double
validation is enabled"""
group_purchase_manager = self.env.ref('purchase.group_purchase_manager')
order = self.env['purchase.order'].create({
"partner_id": self.vendor.id,
"order_line": [
(0, 0, {
'product_id': self.product.id,
'name': f'{self.product.name} {1:05}',
'price_unit': 79.80,
'product_qty': 15.0,
}),
]})
company = order.sudo().company_id
company.po_double_validation = 'two_step'
company.po_double_validation_amount = 0
self.purchase_user.write({
'company_ids': [(4, company.id)],
'company_id': company.id,
'groups_id': [(3, group_purchase_manager.id)],
})
order.with_user(self.purchase_user).button_confirm()
self.assertEqual(order.state, 'to approve')
order.with_user(self.purchase_user).button_approve()
self.assertEqual(order.state, 'to approve')
self.purchase_user.groups_id += group_purchase_manager
order.with_user(self.purchase_user).button_approve()
self.assertEqual(order.state, 'purchase')
| 43.514793
| 7,354
|
13,695
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged, Form
from odoo import fields
from datetime import timedelta
@tagged('-at_install', 'post_install')
class TestPurchase(AccountTestInvoicingCommon):
def test_date_planned(self):
"""Set a date planned on 2 PO lines. Check that the PO date_planned is the earliest PO line date
planned. Change one of the dates so it is even earlier and check that the date_planned is set to
this earlier date.
"""
po = Form(self.env['purchase.order'])
po.partner_id = self.partner_a
with po.order_line.new() as po_line:
po_line.product_id = self.product_a
po_line.product_qty = 1
po_line.price_unit = 100
with po.order_line.new() as po_line:
po_line.product_id = self.product_b
po_line.product_qty = 10
po_line.price_unit = 200
po = po.save()
# Check that the same date is planned on both PO lines.
self.assertNotEqual(po.order_line[0].date_planned, False)
self.assertAlmostEqual(po.order_line[0].date_planned, po.order_line[1].date_planned, delta=timedelta(seconds=10))
self.assertAlmostEqual(po.order_line[0].date_planned, po.date_planned, delta=timedelta(seconds=10))
orig_date_planned = po.order_line[0].date_planned
# Set an earlier date planned on a PO line and check that the PO expected date matches it.
new_date_planned = orig_date_planned - timedelta(hours=1)
po.order_line[0].date_planned = new_date_planned
self.assertAlmostEqual(po.order_line[0].date_planned, po.date_planned, delta=timedelta(seconds=10))
# Set an even earlier date planned on the other PO line and check that the PO expected date matches it.
new_date_planned = orig_date_planned - timedelta(hours=72)
po.order_line[1].date_planned = new_date_planned
self.assertAlmostEqual(po.order_line[1].date_planned, po.date_planned, delta=timedelta(seconds=10))
def test_purchase_order_sequence(self):
PurchaseOrder = self.env['purchase.order'].with_context(tracking_disable=True)
company = self.env.user.company_id
self.env['ir.sequence'].search([
('code', '=', 'purchase.order'),
]).write({
'use_date_range': True, 'prefix': 'PO/%(range_year)s/',
})
vals = {
'partner_id': self.partner_a.id,
'company_id': company.id,
'currency_id': company.currency_id.id,
'date_order': '2019-01-01',
}
purchase_order = PurchaseOrder.create(vals.copy())
self.assertTrue(purchase_order.name.startswith('PO/2019/'))
vals['date_order'] = '2020-01-01'
purchase_order = PurchaseOrder.create(vals.copy())
self.assertTrue(purchase_order.name.startswith('PO/2020/'))
# In EU/BXL tz, this is actually already 01/01/2020
vals['date_order'] = '2019-12-31 23:30:00'
purchase_order = PurchaseOrder.with_context(tz='Europe/Brussels').create(vals.copy())
self.assertTrue(purchase_order.name.startswith('PO/2020/'))
def test_reminder_1(self):
"""Set to send reminder today, check if a reminder can be send to the
partner.
"""
po = Form(self.env['purchase.order'])
po.partner_id = self.partner_a
with po.order_line.new() as po_line:
po_line.product_id = self.product_a
po_line.product_qty = 1
po_line.price_unit = 100
with po.order_line.new() as po_line:
po_line.product_id = self.product_b
po_line.product_qty = 10
po_line.price_unit = 200
# set to send reminder today
po.date_planned = fields.Datetime.now() + timedelta(days=1)
po.receipt_reminder_email = True
po.reminder_date_before_receipt = 1
po = po.save()
po.button_confirm()
# check vendor is a message recipient
self.assertTrue(po.partner_id in po.message_partner_ids)
old_messages = po.message_ids
po._send_reminder_mail()
messages_send = po.message_ids - old_messages
# check reminder send
self.assertTrue(messages_send)
self.assertTrue(po.partner_id in messages_send.mapped('partner_ids'))
# check confirm button
po.confirm_reminder_mail()
self.assertTrue(po.mail_reminder_confirmed)
def test_reminder_2(self):
"""Set to send reminder tomorrow, check if no reminder can be send.
"""
po = Form(self.env['purchase.order'])
po.partner_id = self.partner_a
with po.order_line.new() as po_line:
po_line.product_id = self.product_a
po_line.product_qty = 1
po_line.price_unit = 100
with po.order_line.new() as po_line:
po_line.product_id = self.product_b
po_line.product_qty = 10
po_line.price_unit = 200
# set to send reminder tomorrow
po.date_planned = fields.Datetime.now() + timedelta(days=2)
po.receipt_reminder_email = True
po.reminder_date_before_receipt = 1
po = po.save()
po.button_confirm()
# check vendor is a message recipient
self.assertTrue(po.partner_id in po.message_partner_ids)
old_messages = po.message_ids
po._send_reminder_mail()
messages_send = po.message_ids - old_messages
# check no reminder send
self.assertFalse(messages_send)
def test_update_date_planned(self):
po = Form(self.env['purchase.order'])
po.partner_id = self.partner_a
with po.order_line.new() as po_line:
po_line.product_id = self.product_a
po_line.product_qty = 1
po_line.price_unit = 100
po_line.date_planned = '2020-06-06 00:00:00'
with po.order_line.new() as po_line:
po_line.product_id = self.product_b
po_line.product_qty = 10
po_line.price_unit = 200
po_line.date_planned = '2020-06-06 00:00:00'
po = po.save()
po.button_confirm()
# update first line
po._update_date_planned_for_lines([(po.order_line[0], fields.Datetime.today())])
self.assertEqual(po.order_line[0].date_planned, fields.Datetime.today())
activity = self.env['mail.activity'].search([
('summary', '=', 'Date Updated'),
('res_model_id', '=', 'purchase.order'),
('res_id', '=', po.id),
])
self.assertTrue(activity)
self.assertIn(
'<p>partner_a modified receipt dates for the following products:</p>\n'
'<p> - product_a from 2020-06-06 to %s</p>' % fields.Date.today(),
activity.note,
)
# update second line
po._update_date_planned_for_lines([(po.order_line[1], fields.Datetime.today())])
self.assertEqual(po.order_line[1].date_planned, fields.Datetime.today())
self.assertIn(
'<p>partner_a modified receipt dates for the following products:</p>\n'
'<p> - product_a from 2020-06-06 to %(today)s</p>\n'
'<p> - product_b from 2020-06-06 to %(today)s</p>' % {'today': fields.Date.today()},
activity.note,
)
def test_onchange_packaging_00(self):
"""Create a PO and use packaging. Check we suggested suitable packaging
according to the product_qty. Also check product_qty or product_packaging
are correctly calculated when one of them changed.
"""
packaging_single = self.env['product.packaging'].create({
'name': "I'm a packaging",
'product_id': self.product_a.id,
'qty': 1.0,
})
packaging_dozen = self.env['product.packaging'].create({
'name': "I'm also a packaging",
'product_id': self.product_a.id,
'qty': 12.0,
})
po = self.env['purchase.order'].create({
'partner_id': self.partner_a.id,
})
po_form = Form(po)
with po_form.order_line.new() as line:
line.product_id = self.product_a
line.product_qty = 1.0
po_form.save()
self.assertEqual(po.order_line.product_packaging_id, packaging_single)
self.assertEqual(po.order_line.product_packaging_qty, 1.0)
with po_form.order_line.edit(0) as line:
line.product_packaging_qty = 2.0
po_form.save()
self.assertEqual(po.order_line.product_qty, 2.0)
with po_form.order_line.edit(0) as line:
line.product_qty = 24.0
po_form.save()
self.assertEqual(po.order_line.product_packaging_id, packaging_dozen)
self.assertEqual(po.order_line.product_packaging_qty, 2.0)
with po_form.order_line.edit(0) as line:
line.product_packaging_qty = 1.0
po_form.save()
self.assertEqual(po.order_line.product_qty, 12)
def test_with_different_uom(self):
""" This test ensures that the unit price is correctly computed"""
uom_units = self.env.ref('uom.product_uom_unit')
uom_dozens = self.env.ref('uom.product_uom_dozen')
uom_pairs = self.env['uom.uom'].create({
'name': 'Pairs',
'category_id': uom_units.category_id.id,
'uom_type': 'bigger',
'factor_inv': 2,
'rounding': 1,
})
product_data = {
'name': 'SuperProduct',
'type': 'consu',
'uom_id': uom_units.id,
'uom_po_id': uom_pairs.id,
'standard_price': 100
}
product_01 = self.env['product.product'].create(product_data)
product_02 = self.env['product.product'].create(product_data)
po_form = Form(self.env['purchase.order'])
po_form.partner_id = self.partner_a
with po_form.order_line.new() as po_line:
po_line.product_id = product_01
with po_form.order_line.new() as po_line:
po_line.product_id = product_02
po_line.product_uom = uom_dozens
po = po_form.save()
self.assertEqual(po.order_line[0].price_unit, 200)
self.assertEqual(po.order_line[1].price_unit, 1200)
def test_on_change_quantity_description(self):
"""
When a user changes the quantity of a product in a purchase order it
should not change the description if the descritpion was changed by
the user before
"""
self.env.user.write({'company_id': self.company_data['company'].id})
po = Form(self.env['purchase.order'])
po.partner_id = self.partner_a
with po.order_line.new() as pol:
pol.product_id = self.product_a
pol.product_qty = 1
pol.name = "New custom description"
pol.product_qty += 1
self.assertEqual(pol.name, "New custom description")
def test_tax_totals(self):
""" This test ensures the tax amount is correctly computed"""
self.env.company.tax_calculation_rounding_method = 'round_globally'
tax_21_excl = self.env['account.tax'].create({
'name': "21 exclude",
'amount': '21.00',
'amount_type': 'percent',
'price_include': False,
})
po_form = Form(self.env['purchase.order'])
po_form.partner_id = self.partner_a
with po_form.order_line.new() as po_line:
po_line.product_id = self.product_a
po_line.product_qty = 1.0
po_line.price_unit = 10.74
po_line.taxes_id.clear()
po_line.taxes_id.add(tax_21_excl)
with po_form.order_line.new() as po_line:
po_line.product_id = self.product_a
po_line.product_qty = 2.0
po_line.price_unit = 0.83
po_line.taxes_id.clear()
po_line.taxes_id.add(tax_21_excl)
po = po_form.save()
self.assertEqual(po.amount_tax, 2.60)
self.assertEqual(po.amount_total, 15.00)
self.assertEqual(po.amount_untaxed, 12.40)
def test_purchase_not_creating_useless_product_vendor(self):
""" This test ensures that the product vendor is not created when the
product is not set on the purchase order line.
"""
#create a contact of type contact
contact = self.env['res.partner'].create({
'name': 'Contact',
'type': 'contact',
})
#create a contact of type Delivery Address lnked to the contact
delivery_address = self.env['res.partner'].create({
'name': 'Delivery Address',
'type': 'delivery',
'parent_id': contact.id,
})
#create a product that use the delivery address as vendor
product = self.env['product.product'].create({
'name': 'Product',
'seller_ids': [(0, 0, {
'name': delivery_address.id,
'min_qty': 1.0,
'price': 1.0,
})]
})
#create a purchase order with the delivery address as partner
po_form = Form(self.env['purchase.order'])
po_form.partner_id = delivery_address
with po_form.order_line.new() as po_line:
po_line.product_id = product
po_line.product_qty = 1.0
po = po_form.save()
po.button_confirm()
self.assertEqual(po.order_line.product_id.seller_ids.mapped('name'), delivery_address)
| 40.517751
| 13,695
|
32,566
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged
from odoo.tests.common import Form
from odoo import Command, fields
@tagged('post_install', '-at_install')
class TestPurchaseToInvoice(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls):
super(TestPurchaseToInvoice, cls).setUpClass()
uom_unit = cls.env.ref('uom.product_uom_unit')
uom_hour = cls.env.ref('uom.product_uom_hour')
cls.product_order = cls.env['product.product'].create({
'name': "Zed+ Antivirus",
'standard_price': 235.0,
'list_price': 280.0,
'type': 'consu',
'uom_id': uom_unit.id,
'uom_po_id': uom_unit.id,
'purchase_method': 'purchase',
'default_code': 'PROD_ORDER',
'taxes_id': False,
})
cls.service_deliver = cls.env['product.product'].create({
'name': "Cost-plus Contract",
'standard_price': 200.0,
'list_price': 180.0,
'type': 'service',
'uom_id': uom_unit.id,
'uom_po_id': uom_unit.id,
'purchase_method': 'receive',
'default_code': 'SERV_DEL',
'taxes_id': False,
})
cls.service_order = cls.env['product.product'].create({
'name': "Prepaid Consulting",
'standard_price': 40.0,
'list_price': 90.0,
'type': 'service',
'uom_id': uom_hour.id,
'uom_po_id': uom_hour.id,
'purchase_method': 'purchase',
'default_code': 'PRE-PAID',
'taxes_id': False,
})
cls.product_deliver = cls.env['product.product'].create({
'name': "Switch, 24 ports",
'standard_price': 55.0,
'list_price': 70.0,
'type': 'consu',
'uom_id': uom_unit.id,
'uom_po_id': uom_unit.id,
'purchase_method': 'receive',
'default_code': 'PROD_DEL',
'taxes_id': False,
})
def test_vendor_bill_delivered(self):
"""Test if a order of product invoiced by delivered quantity can be
correctly invoiced."""
purchase_order = self.env['purchase.order'].with_context(tracking_disable=True).create({
'partner_id': self.partner_a.id,
})
PurchaseOrderLine = self.env['purchase.order.line'].with_context(tracking_disable=True)
pol_prod_deliver = PurchaseOrderLine.create({
'name': self.product_deliver.name,
'product_id': self.product_deliver.id,
'product_qty': 10.0,
'product_uom': self.product_deliver.uom_id.id,
'price_unit': self.product_deliver.list_price,
'order_id': purchase_order.id,
'taxes_id': False,
})
pol_serv_deliver = PurchaseOrderLine.create({
'name': self.service_deliver.name,
'product_id': self.service_deliver.id,
'product_qty': 10.0,
'product_uom': self.service_deliver.uom_id.id,
'price_unit': self.service_deliver.list_price,
'order_id': purchase_order.id,
'taxes_id': False,
})
purchase_order.button_confirm()
self.assertEqual(purchase_order.invoice_status, "no")
for line in purchase_order.order_line:
self.assertEqual(line.qty_to_invoice, 0.0)
self.assertEqual(line.qty_invoiced, 0.0)
purchase_order.order_line.qty_received = 5
self.assertEqual(purchase_order.invoice_status, "to invoice")
for line in purchase_order.order_line:
self.assertEqual(line.qty_to_invoice, 5)
self.assertEqual(line.qty_invoiced, 0.0)
purchase_order.action_create_invoice()
self.assertEqual(purchase_order.invoice_status, "invoiced")
for line in purchase_order.order_line:
self.assertEqual(line.qty_to_invoice, 0.0)
self.assertEqual(line.qty_invoiced, 5)
def test_vendor_bill_ordered(self):
"""Test if a order of product invoiced by ordered quantity can be
correctly invoiced."""
purchase_order = self.env['purchase.order'].with_context(tracking_disable=True).create({
'partner_id': self.partner_a.id,
})
PurchaseOrderLine = self.env['purchase.order.line'].with_context(tracking_disable=True)
pol_prod_order = PurchaseOrderLine.create({
'name': self.product_order.name,
'product_id': self.product_order.id,
'product_qty': 10.0,
'product_uom': self.product_order.uom_id.id,
'price_unit': self.product_order.list_price,
'order_id': purchase_order.id,
'taxes_id': False,
})
pol_serv_order = PurchaseOrderLine.create({
'name': self.service_order.name,
'product_id': self.service_order.id,
'product_qty': 10.0,
'product_uom': self.service_order.uom_id.id,
'price_unit': self.service_order.list_price,
'order_id': purchase_order.id,
'taxes_id': False,
})
purchase_order.button_confirm()
self.assertEqual(purchase_order.invoice_status, "to invoice")
for line in purchase_order.order_line:
self.assertEqual(line.qty_to_invoice, 10)
self.assertEqual(line.qty_invoiced, 0.0)
purchase_order.order_line.qty_received = 5
self.assertEqual(purchase_order.invoice_status, "to invoice")
for line in purchase_order.order_line:
self.assertEqual(line.qty_to_invoice, 10)
self.assertEqual(line.qty_invoiced, 0.0)
purchase_order.action_create_invoice()
self.assertEqual(purchase_order.invoice_status, "invoiced")
for line in purchase_order.order_line:
self.assertEqual(line.qty_to_invoice, 0.0)
self.assertEqual(line.qty_invoiced, 10)
def test_vendor_bill_delivered_return(self):
"""Test when return product, a order of product invoiced by delivered
quantity can be correctly invoiced."""
purchase_order = self.env['purchase.order'].with_context(tracking_disable=True).create({
'partner_id': self.partner_a.id,
})
PurchaseOrderLine = self.env['purchase.order.line'].with_context(tracking_disable=True)
pol_prod_deliver = PurchaseOrderLine.create({
'name': self.product_deliver.name,
'product_id': self.product_deliver.id,
'product_qty': 10.0,
'product_uom': self.product_deliver.uom_id.id,
'price_unit': self.product_deliver.list_price,
'order_id': purchase_order.id,
'taxes_id': False,
})
pol_serv_deliver = PurchaseOrderLine.create({
'name': self.service_deliver.name,
'product_id': self.service_deliver.id,
'product_qty': 10.0,
'product_uom': self.service_deliver.uom_id.id,
'price_unit': self.service_deliver.list_price,
'order_id': purchase_order.id,
'taxes_id': False,
})
purchase_order.button_confirm()
purchase_order.order_line.qty_received = 10
purchase_order.action_create_invoice()
self.assertEqual(purchase_order.invoice_status, "invoiced")
for line in purchase_order.order_line:
self.assertEqual(line.qty_to_invoice, 0.0)
self.assertEqual(line.qty_invoiced, 10)
purchase_order.order_line.qty_received = 5
self.assertEqual(purchase_order.invoice_status, "to invoice")
for line in purchase_order.order_line:
self.assertEqual(line.qty_to_invoice, -5)
self.assertEqual(line.qty_invoiced, 10)
purchase_order.action_create_invoice()
self.assertEqual(purchase_order.invoice_status, "invoiced")
for line in purchase_order.order_line:
self.assertEqual(line.qty_to_invoice, 0.0)
self.assertEqual(line.qty_invoiced, 5)
def test_vendor_bill_ordered_return(self):
"""Test when return product, a order of product invoiced by ordered
quantity can be correctly invoiced."""
purchase_order = self.env['purchase.order'].with_context(tracking_disable=True).create({
'partner_id': self.partner_a.id,
})
PurchaseOrderLine = self.env['purchase.order.line'].with_context(tracking_disable=True)
pol_prod_order = PurchaseOrderLine.create({
'name': self.product_order.name,
'product_id': self.product_order.id,
'product_qty': 10.0,
'product_uom': self.product_order.uom_id.id,
'price_unit': self.product_order.list_price,
'order_id': purchase_order.id,
'taxes_id': False,
})
pol_serv_order = PurchaseOrderLine.create({
'name': self.service_order.name,
'product_id': self.service_order.id,
'product_qty': 10.0,
'product_uom': self.service_order.uom_id.id,
'price_unit': self.service_order.list_price,
'order_id': purchase_order.id,
'taxes_id': False,
})
purchase_order.button_confirm()
purchase_order.order_line.qty_received = 10
purchase_order.action_create_invoice()
self.assertEqual(purchase_order.invoice_status, "invoiced")
for line in purchase_order.order_line:
self.assertEqual(line.qty_to_invoice, 0.0)
self.assertEqual(line.qty_invoiced, 10)
purchase_order.order_line.qty_received = 5
self.assertEqual(purchase_order.invoice_status, "invoiced")
for line in purchase_order.order_line:
self.assertEqual(line.qty_to_invoice, 0.0)
self.assertEqual(line.qty_invoiced, 10)
def test_vendor_severals_bills_and_multicurrency(self):
"""
This test ensures that, when adding several PO to a bill, if they are expressed with different
currency, the amount of each AML is converted to the bill's currency
"""
PurchaseOrderLine = self.env['purchase.order.line']
PurchaseBillUnion = self.env['purchase.bill.union']
ResCurrencyRate = self.env['res.currency.rate']
usd = self.env.ref('base.USD')
eur = self.env.ref('base.EUR')
purchase_orders = []
ResCurrencyRate.create({'currency_id': usd.id, 'rate': 1})
ResCurrencyRate.create({'currency_id': eur.id, 'rate': 2})
for currency in [usd, eur]:
po = self.env['purchase.order'].with_context(tracking_disable=True).create({
'partner_id': self.partner_a.id,
'currency_id': currency.id,
})
pol_prod_order = PurchaseOrderLine.create({
'name': self.product_order.name,
'product_id': self.product_order.id,
'product_qty': 1,
'product_uom': self.product_order.uom_id.id,
'price_unit': 1000,
'order_id': po.id,
'taxes_id': False,
})
po.button_confirm()
pol_prod_order.write({'qty_received': 1})
purchase_orders.append(po)
move_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice'))
move_form.purchase_vendor_bill_id = PurchaseBillUnion.browse(-purchase_orders[0].id)
move_form.purchase_vendor_bill_id = PurchaseBillUnion.browse(-purchase_orders[1].id)
move = move_form.save()
amls = move.line_ids.filtered(lambda l: l.account_internal_group == 'expense')
self.assertEqual(move.amount_total, 1500)
self.assertEqual(move.currency_id, usd)
self.assertEqual(len(amls), 2)
self.assertEqual(amls[0].amount_currency, 1000)
self.assertEqual(amls[1].amount_currency, 500)
def test_product_price_decimal_accuracy(self):
self.env.ref('product.decimal_price').digits = 3
self.env.company.currency_id.rounding = 0.01
po = self.env['purchase.order'].with_context(tracking_disable=True).create({
'partner_id': self.partner_a.id,
'order_line': [(0, 0, {
'name': self.product_a.name,
'product_id': self.product_a.id,
'product_qty': 12,
'product_uom': self.product_a.uom_id.id,
'price_unit': 0.001,
'taxes_id': False,
})]
})
po.button_confirm()
po.order_line.qty_received = 12
move_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice'))
move_form.purchase_vendor_bill_id = self.env['purchase.bill.union'].browse(-po.id)
move = move_form.save()
self.assertEqual(move.amount_total, 0.01)
def test_vendor_bill_analytic_account_default_change(self):
""" Tests whether, when an analytic account rule is set, and user changes manually the analytic account on
the po, it is the same that is mentioned in the bill.
"""
analytic_account_default = self.env['account.analytic.account'].create({'name': 'default'})
analytic_account_manual = self.env['account.analytic.account'].create({'name': 'manual'})
self.env['account.analytic.default'].create({
'analytic_id': analytic_account_default.id,
'product_id': self.product_order.id,
})
po_form = Form(self.env['purchase.order'].with_context(tracking_disable=True))
po_form.partner_id = self.partner_a
with po_form.order_line.new() as po_line_form:
po_line_form.name = self.product_order.name
po_line_form.product_id = self.product_order
po_line_form.product_qty = 1.0
po_line_form.price_unit = 10
po_line_form.account_analytic_id = analytic_account_manual
purchase_order = po_form.save()
purchase_order.button_confirm()
purchase_order.action_create_invoice()
aml = self.env['account.move.line'].search([('purchase_line_id', '=', purchase_order.order_line.id)])
self.assertRecordValues(aml, [{'analytic_account_id': analytic_account_manual.id}])
def test_vendor_bill_analytic_account_product_change(self):
analytic_account_super = self.env['account.analytic.account'].create({'name': 'Super Account'})
analytic_account_great = self.env['account.analytic.account'].create({'name': 'Great Account'})
super_product = self.env['product.product'].create({'name': 'Super Product'})
great_product = self.env['product.product'].create({'name': 'Great Product'})
self.env['account.analytic.default'].create([
{
'analytic_id': analytic_account_super.id,
'product_id': super_product.id,
},
{
'analytic_id': analytic_account_great.id,
'product_id': great_product.id,
},
])
purchase_order = self.env['purchase.order'].create({
'partner_id': self.partner_a.id,
})
purchase_order_line = self.env['purchase.order.line'].create({
'name': super_product.name,
'product_id': super_product.id,
'order_id': purchase_order.id,
})
self.assertEqual(purchase_order_line.account_analytic_id.id, analytic_account_super.id, "The analytic account should be set to 'Super Account'")
purchase_order_line.write({'product_id': great_product.id})
self.assertEqual(purchase_order_line.account_analytic_id.id, analytic_account_great.id, "The analytic account should be set to 'Great Account'")
other_analytic_account = self.env['account.analytic.account'].create({'name': 'Other Account'})
other_product = self.env['product.product'].create({'name': 'Other Product'})
other_purchase_order_line = self.env['purchase.order.line'].create({
'name': other_product.name,
'product_id': other_product.id,
'order_id': purchase_order.id,
})
other_purchase_order_line.write({'account_analytic_id': other_analytic_account})
purchase_order.write({'date_order': '2019-01-01'})
self.assertEqual(other_purchase_order_line.account_analytic_id.id, other_analytic_account.id, "The analytic account should still be set to 'Other Account'")
po_no_analytic_account = self.env['purchase.order'].create({
'partner_id': self.partner_a.id,
})
pol_no_analytic_account = self.env['purchase.order.line'].create({
'name': super_product.name,
'product_id': super_product.id,
'order_id': po_no_analytic_account.id,
'account_analytic_id': False,
})
po_no_analytic_account.button_confirm()
self.assertFalse(pol_no_analytic_account.account_analytic_id.id, "The compute should not overwrite what the user has set.")
def test_multicompany_partner_bank(self):
""" Test that in a multiple company environment, the bank account of the invoice
is the one corresponding to the active company. """
company_a = self.env.user.company_id
company_b = self.env['res.company'].create({
'name': 'Company B',
})
self.env.ref('l10n_generic_coa.configurable_chart_template')._load(15.0, 15.0, company_b)
partner = self.env['res.partner'].create({
'name': 'AAAAA',
})
partner_bank_a = self.env['res.partner.bank'].create({
'acc_number': "BE01 23456789 10",
'partner_id': partner.id,
'company_id': company_a.id,
'acc_type': 'bank'
})
partner_bank_b = self.env['res.partner.bank'].create({
'acc_number': "BE10 98765432 10",
'partner_id': partner.id,
'company_id': company_b.id,
'acc_type': 'bank'
})
partner.bank_ids = [partner_bank_a.id, partner_bank_b.id]
PurchaseOrder = self.env['purchase.order'].with_context(tracking_disable=True)
po_a = PurchaseOrder.with_company(company_a).create({
'partner_id': partner.id,
'company_id': company_a.id,
'currency_id': company_a.currency_id.id,
'date_order': '2019-01-01',
})
po_b = PurchaseOrder.with_company(company_b).create({
'partner_id': partner.id,
'company_id': company_b.id,
'currency_id': company_b.currency_id.id,
'date_order': '2019-01-01',
})
vals_pol = {
'name': self.product_deliver.name,
'product_id': self.product_deliver.id,
'product_qty': 10.0,
'product_uom': self.product_deliver.uom_id.id,
'price_unit': self.product_deliver.list_price,
'order_id': po_a.id,
'taxes_id': False,
}
PurchaseOrderLine = self.env['purchase.order.line'].with_context(tracking_disable=True)
PurchaseOrderLine.create(vals_pol)
vals_pol['order_id'] = po_b.id
PurchaseOrderLine.create(vals_pol)
po_a.button_confirm()
po_b.button_confirm()
po_a.order_line.qty_received = po_b.order_line.qty_received = 10
po_a.with_company(company_a).action_create_invoice()
po_b.with_company(company_b).action_create_invoice()
self.assertEqual(po_a.invoice_ids.company_id, company_a)
self.assertEqual(po_a.invoice_ids.partner_bank_id, partner_bank_a)
self.assertEqual(po_b.invoice_ids.company_id, company_b)
self.assertEqual(po_b.invoice_ids.partner_bank_id, partner_bank_b)
def test_sequence_invoice_lines_from_multiple_purchases(self):
"""Test if the invoice lines are sequenced by purchase order when creating an invoice
from multiple selected po's"""
purchase_orders = self.env['purchase.order']
for _ in range(3):
pol_vals = [
(0, 0, {
'name': self.product_order.name,
'product_id': self.product_order.id,
'product_qty': 10.0,
'product_uom': self.product_order.uom_id.id,
'price_unit': self.product_order.list_price,
'taxes_id': False,
'sequence': sequence_number,
}) for sequence_number in range(10, 13)]
purchase_order = self.env['purchase.order'].with_context(tracking_disable=True).create({
'partner_id': self.partner_a.id,
'order_line': pol_vals,
})
purchase_order.button_confirm()
purchase_orders |= purchase_order
action = purchase_orders.action_create_invoice()
invoice = self.env['account.move'].browse(action['res_id'])
expected_purchase = [
purchase_orders[0], purchase_orders[0], purchase_orders[0],
purchase_orders[1], purchase_orders[1], purchase_orders[1],
purchase_orders[2], purchase_orders[2], purchase_orders[2],
]
for line in invoice.invoice_line_ids.sorted('sequence'):
self.assertEqual(line.purchase_order_id, expected_purchase.pop(0))
def test_sequence_autocomplete_invoice(self):
"""Test if the invoice lines are sequenced by purchase order when using the autocomplete
feature on a bill to add lines from po's"""
purchase_orders = self.env['purchase.order']
for _ in range(3):
pol_vals = [
(0, 0, {
'name': self.product_order.name,
'product_id': self.product_order.id,
'product_qty': 10.0,
'product_uom': self.product_order.uom_id.id,
'price_unit': self.product_order.list_price,
'taxes_id': False,
'sequence': sequence_number,
}) for sequence_number in range(10, 13)]
purchase_order = self.env['purchase.order'].with_context(tracking_disable=True).create({
'partner_id': self.partner_a.id,
'order_line': pol_vals,
})
purchase_order.button_confirm()
purchase_orders |= purchase_order
move_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice'))
PurchaseBillUnion = self.env['purchase.bill.union']
move_form.purchase_vendor_bill_id = PurchaseBillUnion.browse(-purchase_orders[0].id)
move_form.purchase_vendor_bill_id = PurchaseBillUnion.browse(-purchase_orders[1].id)
move_form.purchase_vendor_bill_id = PurchaseBillUnion.browse(-purchase_orders[2].id)
invoice = move_form.save()
expected_purchase = [
purchase_orders[0], purchase_orders[0], purchase_orders[0],
purchase_orders[1], purchase_orders[1], purchase_orders[1],
purchase_orders[2], purchase_orders[2], purchase_orders[2],
]
for line in invoice.invoice_line_ids.sorted('sequence'):
self.assertEqual(line.purchase_order_id, expected_purchase.pop(0))
def test_partial_billing_interaction_with_invoicing_switch_threshold(self):
""" Let's say you create a partial bill 'B' for a given PO. Now if you change the
'Invoicing Switch Threshold' such that the bill date of 'B' is before the new threshold,
the PO should still take bill 'B' into account.
"""
if not self.env['ir.module.module'].search([('name', '=', 'account_accountant'), ('state', '=', 'installed')]):
self.skipTest("This test requires the installation of the account_account module")
purchase_order = self.env['purchase.order'].with_context(tracking_disable=True).create({
'partner_id': self.partner_a.id,
'order_line': [
Command.create({
'name': self.product_deliver.name,
'product_id': self.product_deliver.id,
'product_qty': 20.0,
'product_uom': self.product_deliver.uom_id.id,
'price_unit': self.product_deliver.list_price,
'taxes_id': False,
}),
],
})
line = purchase_order.order_line[0]
purchase_order.button_confirm()
line.qty_received = 10
purchase_order.action_create_invoice()
invoice = purchase_order.invoice_ids
invoice.invoice_date = invoice.date
invoice.action_post()
self.assertEqual(line.qty_invoiced, 10)
self.env['res.config.settings'].create({
'invoicing_switch_threshold': fields.Date.add(invoice.invoice_date, days=30),
}).execute()
invoice.invalidate_cache(fnames=['payment_state'])
self.assertEqual(line.qty_invoiced, 10)
line.qty_received = 15
self.assertEqual(line.qty_invoiced, 10)
def test_on_change_quantity_price_unit(self):
""" When a user changes the quantity of a product in a purchase order it
should only update the unit price if PO line has no invoice line. """
supplierinfo_vals = {
'name': self.partner_a.id,
'price': 10.0,
'min_qty': 1,
"product_id": self.product_order.id,
"product_tmpl_id": self.product_order.product_tmpl_id.id,
}
supplierinfo = self.env["product.supplierinfo"].create(supplierinfo_vals)
po_form = Form(self.env['purchase.order'])
po_form.partner_id = self.partner_a
with po_form.order_line.new() as po_line_form:
po_line_form.product_id = self.product_order
po_line_form.product_qty = 1
po = po_form.save()
po_line = po.order_line[0]
self.assertEqual(10.0, po_line.price_unit, "Unit price should be set to 10.0 for 1 quantity")
# Ensure price unit is updated when changing quantity on a un-confirmed PO
supplierinfo.write({'min_qty': 2, 'price': 20.0})
po_line.write({'product_qty': 2})
po_line._onchange_quantity()
self.assertEqual(20.0, po_line.price_unit, "Unit price should be set to 20.0 for 2 quantity")
po.button_confirm()
# Ensure price unit is updated when changing quantity on a confirmed PO
supplierinfo.write({'min_qty': 3, 'price': 30.0})
po_line.write({'product_qty': 3})
po_line._onchange_quantity()
self.assertEqual(30.0, po_line.price_unit, "Unit price should be set to 30.0 for 3 quantity")
po.action_create_invoice()
# Ensure price unit is NOT updated when changing quantity on PO confirmed and line linked to an invoice line
supplierinfo.write({'min_qty': 4, 'price': 40.0})
po_line.write({'product_qty': 4})
po_line._onchange_quantity()
self.assertEqual(30.0, po_line.price_unit, "Unit price should be set to 30.0 for 3 quantity")
with po_form.order_line.new() as po_line_form:
po_line_form.product_id = self.product_order
po_line_form.product_qty = 1
po = po_form.save()
po_line = po.order_line[1]
self.assertEqual(235.0, po_line.price_unit, "Unit price should be reset to 235.0 since the supplier supplies minimum of 4 quantities")
# Ensure price unit is updated when changing quantity on PO confirmed and line NOT linked to an invoice line
po_line.write({'product_qty': 4})
po_line._onchange_quantity()
self.assertEqual(40.0, po_line.price_unit, "Unit price should be set to 40.0 for 4 quantity")
def test_onchange_partner_currency(self):
"""
Test that the currency of the Bill is correctly set when the partner is changed
as well as the currency of the Bill lines
"""
vendor_eur = self.env['res.partner'].create({
'name': 'Vendor EUR',
'property_purchase_currency_id': self.env.ref('base.EUR').id,
})
vendor_us = self.env['res.partner'].create({
'name': 'Vendor USD',
'property_purchase_currency_id': self.env.ref('base.USD').id,
})
vendor_no_currency = self.env['res.partner'].create({
'name': 'Vendor No Currency',
})
move_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice'))
move_form.partner_id = vendor_eur
with move_form.invoice_line_ids.new() as line_form:
line_form.product_id = self.product_order
line_form.quantity = 1
bill = move_form.save()
self.assertEqual(bill.currency_id, self.env.ref('base.EUR'), "The currency of the Bill should be the same as the currency of the partner")
self.assertEqual(bill.invoice_line_ids.currency_id, self.env.ref('base.EUR'), "The currency of the Bill lines should be the same as the currency of the partner")
move_form.partner_id = vendor_us
bill = move_form.save()
self.assertEqual(bill.currency_id, self.env.ref('base.USD'), "The currency of the Bill should be the same as the currency of the partner")
self.assertEqual(bill.invoice_line_ids.currency_id, self.env.ref('base.USD'), "The currency of the Bill lines should be the same as the currency of the partner")
move_form.partner_id = vendor_no_currency
bill = move_form.save()
self.assertEqual(bill.currency_id, self.env.company.currency_id, "The currency of the Bill should be the same as the currency of the company")
self.assertEqual(bill.invoice_line_ids.currency_id, self.env.company.currency_id, "The currency of the Bill lines should be the same as the currency of the company")
def test_onchange_partner_no_currency(self):
"""
Test that the currency of the Bill is correctly set when the partner is changed
as well as the currency of the Bill lines even if the partner has no property_purchase_currency_id set
or when and the `default_currency_id` is defined in the context
"""
vendor_a = self.env['res.partner'].create({
'name': 'Vendor A with No Currency',
})
vendor_b = self.env['res.partner'].create({
'name': 'Vendor B with No Currency',
})
ctx = {'default_move_type': 'in_invoice'}
move_form = Form(self.env['account.move'].with_context(ctx))
move_form.partner_id = vendor_a
move_form.currency_id = self.env.ref('base.EUR')
with move_form.invoice_line_ids.new() as line_form:
line_form.product_id = self.product_order
line_form.quantity = 1
bill = move_form.save()
self.assertEqual(bill.currency_id, self.env.ref('base.EUR'), "The currency of the Bill should be the one set on the Bill")
self.assertEqual(bill.invoice_line_ids.currency_id, self.env.ref('base.EUR'), "The currency of the Bill lines should be the same as the currency of the Bill")
move_form.partner_id = vendor_b
bill = move_form.save()
self.assertEqual(bill.currency_id, self.env.ref('base.EUR'), "The currency of the Bill should be the one set on the Bill")
self.assertEqual(bill.invoice_line_ids.currency_id, self.env.ref('base.EUR'), "The currency of the Bill lines should be the same as the currency of the Bill")
ctx['default_currency_id'] = self.currency_data['currency'].id
move_form_currency_in_context = Form(self.env['account.move'].with_context(ctx))
move_form_currency_in_context.currency_id = self.env.ref('base.EUR')
with move_form_currency_in_context.invoice_line_ids.new() as line_form:
line_form.product_id = self.product_order
line_form.quantity = 1
move_form_currency_in_context.partner_id = vendor_a
bill = move_form_currency_in_context.save()
self.assertEqual(bill.currency_id, self.currency_data['currency'], "The currency of the Bill should be the one of the context")
self.assertEqual(bill.invoice_line_ids.currency_id, self.currency_data['currency'], "The currency of the Bill lines should be the same as the currency of the Bill")
| 46.127479
| 32,566
|
6,116
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import Form, tagged
from datetime import datetime, timedelta
@tagged('post_install', '-at_install')
class TestPurchaseOrderReport(AccountTestInvoicingCommon):
def test_00_purchase_order_report(self):
uom_dozen = self.env.ref('uom.product_uom_dozen')
po = self.env['purchase.order'].create({
'partner_id': self.partner_a.id,
'currency_id': self.currency_data['currency'].id,
'order_line': [
(0, 0, {
'name': self.product_a.name,
'product_id': self.product_a.id,
'product_qty': 1.0,
'product_uom': uom_dozen.id,
'price_unit': 100.0,
'date_planned': datetime.today(),
'taxes_id': False,
}),
(0, 0, {
'name': self.product_b.name,
'product_id': self.product_b.id,
'product_qty': 1.0,
'product_uom': uom_dozen.id,
'price_unit': 200.0,
'date_planned': datetime.today(),
'taxes_id': False,
}),
],
})
po.button_confirm()
f = Form(self.env['account.move'].with_context(default_move_type='in_invoice'))
f.invoice_date = f.date
f.partner_id = po.partner_id
f.purchase_id = po
invoice = f.save()
invoice.action_post()
po.flush()
res_product1 = self.env['purchase.report'].search([
('order_id', '=', po.id),
('product_id', '=', self.product_a.id),
('company_id', '=', self.company_data['company'].id),
])
# check that report will convert dozen to unit or not
self.assertEqual(res_product1.qty_ordered, 12.0, 'UoM conversion is not working')
# report should show in company currency (amount/rate) = (100/2)
self.assertEqual(res_product1.price_total, 50.0, 'Currency conversion is not working')
res_product2 = self.env['purchase.report'].search([
('order_id', '=', po.id),
('product_id', '=', self.product_b.id),
('company_id', '=', self.company_data['company'].id),
])
self.assertEqual(res_product2.qty_ordered, 1.0, 'No conversion needed since product_b is already a dozen')
# report should show in company currency (amount/rate) = (200/2)
self.assertEqual(res_product2.price_total, 100.0, 'Currency conversion is not working')
def test_01_delay_and_delay_pass(self):
po_form = Form(self.env['purchase.order'])
po_form.partner_id = self.partner_a
po_form.date_order = datetime.now() + timedelta(days=10)
with po_form.order_line.new() as line:
line.product_id = self.product_a
with po_form.order_line.new() as line:
line.product_id = self.product_b
po_form.date_planned = datetime.now() + timedelta(days=15)
po = po_form.save()
po.button_confirm()
po.flush()
report = self.env['purchase.report'].read_group(
[('order_id', '=', po.id)],
['order_id', 'delay', 'delay_pass'],
['order_id'],
)
self.assertEqual(round(report[0]['delay']), -10, msg="The PO has been confirmed 10 days in advance")
self.assertEqual(round(report[0]['delay_pass']), 5, msg="There are 5 days between the order date and the planned date")
def test_02_po_report_note_section_filter(self):
po = self.env['purchase.order'].create({
'partner_id': self.partner_a.id,
'currency_id': self.currency_data['currency'].id,
'order_line': [
(0, 0, {
'name': 'This is a note',
'display_type': 'line_note',
'product_id': False,
'product_qty': 0.0,
'product_uom': False,
'price_unit': 0.0,
'taxes_id': False,
}),
(0, 0, {
'name': 'This is a section',
'display_type': 'line_section',
'product_id': False,
'product_qty': 0.0,
'product_uom': False,
'price_unit': 0.0,
'taxes_id': False,
}),
],
})
po.button_confirm()
result_po = self.env['purchase.report'].search([('order_id', '=', po.id)])
self.assertFalse(result_po, "The report should ignore the notes and sections")
def test_avg_price_calculation(self):
"""
Check that the average price is calculated based on the quantity ordered in each line
PO:
- 10 unit of product A -> price $50
- 1 unit of product A -> price $10
Total qty_ordered: 11
avergae price: 46.36 = ((10 * 50) + (10 * 1)) / 11
"""
po = self.env['purchase.order'].create({
'partner_id': self.partner_a.id,
'order_line': [
(0, 0, {
'product_id': self.product_a.id,
'product_qty': 10.0,
'price_unit': 50.0,
}),
(0, 0, {
'product_id': self.product_a.id,
'product_qty': 1.0,
'price_unit': 10.0,
}),
],
})
po.button_confirm()
po.flush()
report = self.env['purchase.report'].read_group(
[('product_id', '=', self.product_a.id)],
['qty_ordered', 'price_average:avg'],
['product_id'],
)
self.assertEqual(report[0]['qty_ordered'], 11)
self.assertEqual(round(report[0]['price_average'], 2), 46.36)
| 39.458065
| 6,116
|
4,483
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import fields, Command
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged
from odoo.exceptions import UserError
@tagged('post_install', '-at_install')
class TestAccruedPurchaseOrders(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.alt_exp_account = cls.company_data['default_account_expense'].copy()
# set 'type' to 'service' to allow manualy set 'qty_delivered' even with purchase_stock installed
cls.product_a.type = 'service'
cls.product_b.type = 'service'
cls.product_b.property_account_expense_id = cls.alt_exp_account
cls.purchase_order = cls.env['purchase.order'].with_context(tracking_disable=True).create({
'partner_id': cls.partner_a.id,
'order_line': [
Command.create({
'name': cls.product_a.name,
'product_id': cls.product_a.id,
'product_qty': 10.0,
'product_uom': cls.product_a.uom_id.id,
'price_unit': cls.product_a.list_price,
'taxes_id': False,
}),
Command.create({
'name': cls.product_b.name,
'product_id': cls.product_b.id,
'product_qty': 10.0,
'product_uom': cls.product_b.uom_id.id,
'price_unit': cls.product_b.list_price,
'taxes_id': False,
}),
],
})
cls.purchase_order.button_confirm()
cls.account_revenue = cls.company_data['default_account_revenue']
cls.account_expense = cls.company_data['default_account_expense']
cls.wizard = cls.env['account.accrued.orders.wizard'].with_context({
'active_model': 'purchase.order',
'active_ids': cls.purchase_order.ids
}).create({
'account_id': cls.account_revenue.id,
})
def test_accrued_order(self):
# nothing to bill : no entries to be created
with self.assertRaises(UserError):
self.wizard.create_entries()
# 5 qty of each product billeable
self.purchase_order.order_line.qty_received = 5
self.assertRecordValues(self.env['account.move'].search(self.wizard.create_entries()['domain']).line_ids, [
# reverse move lines
{'account_id': self.account_expense.id, 'debit': 0, 'credit': 5000},
{'account_id': self.alt_exp_account.id, 'debit': 0, 'credit': 1000},
{'account_id': self.account_revenue.id, 'debit': 6000, 'credit': 0},
# move lines
{'account_id': self.account_expense.id, 'debit': 5000, 'credit': 0},
{'account_id': self.alt_exp_account.id, 'debit': 1000, 'credit': 0},
{'account_id': self.account_revenue.id, 'debit': 0, 'credit': 6000},
])
# received products billed, nothing to bill left
move = self.env['account.move'].browse(self.purchase_order.action_create_invoice()['res_id'])
move.invoice_date = '2020-01-01'
move.action_post()
with self.assertRaises(UserError):
self.wizard.create_entries()
def test_multi_currency_accrued_order(self):
# 5 qty of each product billeable
self.purchase_order.order_line.qty_received = 5
# set currency != company currency
self.purchase_order.currency_id = self.currency_data['currency']
self.assertRecordValues(self.env['account.move'].search(self.wizard.create_entries()['domain']).line_ids, [
# reverse move lines
{'account_id': self.account_expense.id, 'debit': 0, 'credit': 5000 / 2, 'amount_currency': -5000},
{'account_id': self.alt_exp_account.id, 'debit': 0, 'credit': 1000 / 2, 'amount_currency': -1000},
{'account_id': self.account_revenue.id, 'debit': 6000 / 2, 'credit': 0, 'amount_currency': 0.0},
# move lines
{'account_id': self.account_expense.id, 'debit': 5000 / 2, 'credit': 0, 'amount_currency': 5000},
{'account_id': self.alt_exp_account.id, 'debit': 1000 / 2, 'credit': 0, 'amount_currency': 1000},
{'account_id': self.account_revenue.id, 'debit': 0, 'credit': 6000 / 2, 'amount_currency': 0.0},
])
| 49.811111
| 4,483
|
1,201
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.addons.account.tests.test_invoice_tax_totals import TestTaxTotals
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class PurchaseTestTaxTotals(TestTaxTotals):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.po_product = cls.env['product.product'].create({
'name': 'Odoo course',
'type': 'service',
})
def _create_document_for_tax_totals_test(self, lines_data):
# Overridden in order to run the inherited tests with purchase.order's
# tax_totals_json field instead of account.move's
lines_vals = [
(0, 0, {
'name': 'test',
'product_id': self.po_product.id,
'product_qty': 1,
'product_uom': self.po_product.uom_po_id.id,
'price_unit': amount,
'taxes_id': [(6, 0, taxes.ids)],
})
for amount, taxes in lines_data]
return self.env['purchase.order'].create({
'partner_id': self.partner_a.id,
'order_line': lines_vals,
})
| 33.361111
| 1,201
|
636
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# purches Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class MailComposeMessage(models.TransientModel):
_inherit = 'mail.compose.message'
def _action_send_mail(self, auto_commit=False):
if self.model == 'purchase.order':
self = self.with_context(mailing_document_based=True)
if self.env.context.get('mark_rfq_as_sent'):
self = self.with_context(mail_notify_author=self.env.user.partner_id in self.partner_ids)
return super(MailComposeMessage, self)._action_send_mail(auto_commit=auto_commit)
| 42.4
| 636
|
72,222
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, time
from dateutil.relativedelta import relativedelta
from functools import partial
from itertools import groupby
import json
from markupsafe import escape, Markup
from pytz import timezone, UTC
from werkzeug.urls import url_encode
from odoo import api, fields, models, _
from odoo.osv import expression
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from odoo.tools.float_utils import float_compare, float_is_zero, float_round
from odoo.exceptions import AccessError, UserError, ValidationError
from odoo.tools.misc import formatLang, get_lang, format_amount
class PurchaseOrder(models.Model):
_name = "purchase.order"
_inherit = ['portal.mixin', 'mail.thread', 'mail.activity.mixin']
_description = "Purchase Order"
_order = 'priority desc, id desc'
@api.depends('order_line.price_total')
def _amount_all(self):
for order in self:
amount_untaxed = amount_tax = 0.0
for line in order.order_line:
line._compute_amount()
amount_untaxed += line.price_subtotal
amount_tax += line.price_tax
currency = order.currency_id or order.partner_id.property_purchase_currency_id or self.env.company.currency_id
order.update({
'amount_untaxed': currency.round(amount_untaxed),
'amount_tax': currency.round(amount_tax),
'amount_total': amount_untaxed + amount_tax,
})
@api.depends('state', 'order_line.qty_to_invoice')
def _get_invoiced(self):
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
for order in self:
if order.state not in ('purchase', 'done'):
order.invoice_status = 'no'
continue
if any(
not float_is_zero(line.qty_to_invoice, precision_digits=precision)
for line in order.order_line.filtered(lambda l: not l.display_type)
):
order.invoice_status = 'to invoice'
elif (
all(
float_is_zero(line.qty_to_invoice, precision_digits=precision)
for line in order.order_line.filtered(lambda l: not l.display_type)
)
and order.invoice_ids
):
order.invoice_status = 'invoiced'
else:
order.invoice_status = 'no'
@api.depends('order_line.invoice_lines.move_id')
def _compute_invoice(self):
for order in self:
invoices = order.mapped('order_line.invoice_lines.move_id')
order.invoice_ids = invoices
order.invoice_count = len(invoices)
READONLY_STATES = {
'purchase': [('readonly', True)],
'done': [('readonly', True)],
'cancel': [('readonly', True)],
}
name = fields.Char('Order Reference', required=True, index=True, copy=False, default='New')
priority = fields.Selection(
[('0', 'Normal'), ('1', 'Urgent')], 'Priority', default='0', index=True)
origin = fields.Char('Source Document', copy=False,
help="Reference of the document that generated this purchase order "
"request (e.g. a sales order)")
partner_ref = fields.Char('Vendor Reference', copy=False,
help="Reference of the sales order or bid sent by the vendor. "
"It's used to do the matching when you receive the "
"products as this reference is usually written on the "
"delivery order sent by your vendor.")
date_order = fields.Datetime('Order Deadline', required=True, states=READONLY_STATES, index=True, copy=False, default=fields.Datetime.now,
help="Depicts the date within which the Quotation should be confirmed and converted into a purchase order.")
date_approve = fields.Datetime('Confirmation Date', readonly=1, index=True, copy=False)
partner_id = fields.Many2one('res.partner', string='Vendor', required=True, states=READONLY_STATES, change_default=True, tracking=True, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]", help="You can find a vendor by its Name, TIN, Email or Internal Reference.")
dest_address_id = fields.Many2one('res.partner', domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]", string='Dropship Address', states=READONLY_STATES,
help="Put an address if you want to deliver directly from the vendor to the customer. "
"Otherwise, keep empty to deliver to your own company.")
currency_id = fields.Many2one('res.currency', 'Currency', required=True, states=READONLY_STATES,
default=lambda self: self.env.company.currency_id.id)
state = fields.Selection([
('draft', 'RFQ'),
('sent', 'RFQ Sent'),
('to approve', 'To Approve'),
('purchase', 'Purchase Order'),
('done', 'Locked'),
('cancel', 'Cancelled')
], string='Status', readonly=True, index=True, copy=False, default='draft', tracking=True)
order_line = fields.One2many('purchase.order.line', 'order_id', string='Order Lines', states={'cancel': [('readonly', True)], 'done': [('readonly', True)]}, copy=True)
notes = fields.Html('Terms and Conditions')
invoice_count = fields.Integer(compute="_compute_invoice", string='Bill Count', copy=False, default=0, store=True)
invoice_ids = fields.Many2many('account.move', compute="_compute_invoice", string='Bills', copy=False, store=True)
invoice_status = fields.Selection([
('no', 'Nothing to Bill'),
('to invoice', 'Waiting Bills'),
('invoiced', 'Fully Billed'),
], string='Billing Status', compute='_get_invoiced', store=True, readonly=True, copy=False, default='no')
date_planned = fields.Datetime(
string='Receipt Date', index=True, copy=False, compute='_compute_date_planned', store=True, readonly=False,
help="Delivery date promised by vendor. This date is used to determine expected arrival of products.")
date_calendar_start = fields.Datetime(compute='_compute_date_calendar_start', readonly=True, store=True)
amount_untaxed = fields.Monetary(string='Untaxed Amount', store=True, readonly=True, compute='_amount_all', tracking=True)
tax_totals_json = fields.Char(compute='_compute_tax_totals_json')
amount_tax = fields.Monetary(string='Taxes', store=True, readonly=True, compute='_amount_all')
amount_total = fields.Monetary(string='Total', store=True, readonly=True, compute='_amount_all')
fiscal_position_id = fields.Many2one('account.fiscal.position', string='Fiscal Position', domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]")
tax_country_id = fields.Many2one(
comodel_name='res.country',
compute='_compute_tax_country_id',
# Avoid access error on fiscal position, when reading a purchase order with company != user.company_ids
compute_sudo=True,
help="Technical field to filter the available taxes depending on the fiscal country and fiscal position.")
payment_term_id = fields.Many2one('account.payment.term', 'Payment Terms', domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]")
incoterm_id = fields.Many2one('account.incoterms', 'Incoterm', states={'done': [('readonly', True)]}, help="International Commercial Terms are a series of predefined commercial terms used in international transactions.")
product_id = fields.Many2one('product.product', related='order_line.product_id', string='Product')
user_id = fields.Many2one(
'res.users', string='Purchase Representative', index=True, tracking=True,
default=lambda self: self.env.user, check_company=True)
company_id = fields.Many2one('res.company', 'Company', required=True, index=True, states=READONLY_STATES, default=lambda self: self.env.company.id)
currency_rate = fields.Float("Currency Rate", compute='_compute_currency_rate', compute_sudo=True, store=True, readonly=True, help='Ratio between the purchase order currency and the company currency')
mail_reminder_confirmed = fields.Boolean("Reminder Confirmed", default=False, readonly=True, copy=False, help="True if the reminder email is confirmed by the vendor.")
mail_reception_confirmed = fields.Boolean("Reception Confirmed", default=False, readonly=True, copy=False, help="True if PO reception is confirmed by the vendor.")
receipt_reminder_email = fields.Boolean('Receipt Reminder Email', related='partner_id.receipt_reminder_email', readonly=False)
reminder_date_before_receipt = fields.Integer('Days Before Receipt', related='partner_id.reminder_date_before_receipt', readonly=False)
@api.constrains('company_id', 'order_line')
def _check_order_line_company_id(self):
for order in self:
companies = order.order_line.product_id.company_id
if companies and companies != order.company_id:
bad_products = order.order_line.product_id.filtered(lambda p: p.company_id and p.company_id != order.company_id)
raise ValidationError(_(
"Your quotation contains products from company %(product_company)s whereas your quotation belongs to company %(quote_company)s. \n Please change the company of your quotation or remove the products from other companies (%(bad_products)s).",
product_company=', '.join(companies.mapped('display_name')),
quote_company=order.company_id.display_name,
bad_products=', '.join(bad_products.mapped('display_name')),
))
def _compute_access_url(self):
super(PurchaseOrder, self)._compute_access_url()
for order in self:
order.access_url = '/my/purchase/%s' % (order.id)
@api.depends('state', 'date_order', 'date_approve')
def _compute_date_calendar_start(self):
for order in self:
order.date_calendar_start = order.date_approve if (order.state in ['purchase', 'done']) else order.date_order
@api.model
def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
args = args or []
domain = []
if name:
domain = ['|', ('name', operator, name), ('partner_ref', operator, name)]
return self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid)
@api.depends('date_order', 'currency_id', 'company_id', 'company_id.currency_id')
def _compute_currency_rate(self):
for order in self:
order.currency_rate = self.env['res.currency']._get_conversion_rate(order.company_id.currency_id, order.currency_id, order.company_id, order.date_order)
@api.depends('order_line.date_planned')
def _compute_date_planned(self):
""" date_planned = the earliest date_planned across all order lines. """
for order in self:
dates_list = order.order_line.filtered(lambda x: not x.display_type and x.date_planned).mapped('date_planned')
if dates_list:
order.date_planned = fields.Datetime.to_string(min(dates_list))
else:
order.date_planned = False
@api.depends('name', 'partner_ref')
def name_get(self):
result = []
for po in self:
name = po.name
if po.partner_ref:
name += ' (' + po.partner_ref + ')'
if self.env.context.get('show_total_amount') and po.amount_total:
name += ': ' + formatLang(self.env, po.amount_total, currency_obj=po.currency_id)
result.append((po.id, name))
return result
@api.depends('order_line.taxes_id', 'order_line.price_subtotal', 'amount_total', 'amount_untaxed')
def _compute_tax_totals_json(self):
def compute_taxes(order_line):
return order_line.taxes_id._origin.compute_all(**order_line._prepare_compute_all_values())
account_move = self.env['account.move']
for order in self:
tax_lines_data = account_move._prepare_tax_lines_data_for_totals_from_object(order.order_line, compute_taxes)
tax_totals = account_move._get_tax_totals(order.partner_id, tax_lines_data, order.amount_total, order.amount_untaxed, order.currency_id)
order.tax_totals_json = json.dumps(tax_totals)
@api.depends('company_id.account_fiscal_country_id', 'fiscal_position_id.country_id', 'fiscal_position_id.foreign_vat')
def _compute_tax_country_id(self):
for record in self:
if record.fiscal_position_id.foreign_vat:
record.tax_country_id = record.fiscal_position_id.country_id
else:
record.tax_country_id = record.company_id.account_fiscal_country_id
@api.onchange('date_planned')
def onchange_date_planned(self):
if self.date_planned:
self.order_line.filtered(lambda line: not line.display_type).date_planned = self.date_planned
def write(self, vals):
vals, partner_vals = self._write_partner_values(vals)
res = super().write(vals)
if partner_vals:
self.partner_id.sudo().write(partner_vals) # Because the purchase user doesn't have write on `res.partner`
return res
@api.model
def create(self, vals):
company_id = vals.get('company_id', self.default_get(['company_id'])['company_id'])
# Ensures default picking type and currency are taken from the right company.
self_comp = self.with_company(company_id)
if vals.get('name', 'New') == 'New':
seq_date = None
if 'date_order' in vals:
seq_date = fields.Datetime.context_timestamp(self, fields.Datetime.to_datetime(vals['date_order']))
vals['name'] = self_comp.env['ir.sequence'].next_by_code('purchase.order', sequence_date=seq_date) or '/'
vals, partner_vals = self._write_partner_values(vals)
res = super(PurchaseOrder, self_comp).create(vals)
if partner_vals:
res.sudo().write(partner_vals) # Because the purchase user doesn't have write on `res.partner`
return res
@api.ondelete(at_uninstall=False)
def _unlink_if_cancelled(self):
for order in self:
if not order.state == 'cancel':
raise UserError(_('In order to delete a purchase order, you must cancel it first.'))
def copy(self, default=None):
ctx = dict(self.env.context)
ctx.pop('default_product_id', None)
self = self.with_context(ctx)
new_po = super(PurchaseOrder, self).copy(default=default)
for line in new_po.order_line:
if line.product_id:
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)
line.date_planned = line._get_date_planned(seller)
return new_po
def _must_delete_date_planned(self, field_name):
# To be overridden
return field_name == 'order_line'
def onchange(self, values, field_name, field_onchange):
"""Override onchange to NOT to update all date_planned on PO lines when
date_planned on PO is updated by the change of date_planned on PO lines.
"""
result = super(PurchaseOrder, self).onchange(values, field_name, field_onchange)
if self._must_delete_date_planned(field_name) and 'value' in result:
already_exist = [ol[1] for ol in values.get('order_line', []) if ol[1]]
for line in result['value'].get('order_line', []):
if line[0] < 2 and 'date_planned' in line[2] and line[1] in already_exist:
del line[2]['date_planned']
return result
def _track_subtype(self, init_values):
self.ensure_one()
if 'state' in init_values and self.state == 'purchase':
if init_values['state'] == 'to approve':
return self.env.ref('purchase.mt_rfq_approved')
return self.env.ref('purchase.mt_rfq_confirmed')
elif 'state' in init_values and self.state == 'to approve':
return self.env.ref('purchase.mt_rfq_confirmed')
elif 'state' in init_values and self.state == 'done':
return self.env.ref('purchase.mt_rfq_done')
return super(PurchaseOrder, self)._track_subtype(init_values)
def _get_report_base_filename(self):
self.ensure_one()
return 'Purchase Order-%s' % (self.name)
@api.onchange('partner_id', 'company_id')
def onchange_partner_id(self):
# Ensures all properties and fiscal positions
# are taken with the company of the order
# if not defined, with_company doesn't change anything.
self = self.with_company(self.company_id)
default_currency = self._context.get("default_currency_id")
if not self.partner_id:
self.fiscal_position_id = False
self.currency_id = default_currency or self.env.company.currency_id.id
else:
self.fiscal_position_id = self.env['account.fiscal.position'].get_fiscal_position(self.partner_id.id)
self.payment_term_id = self.partner_id.property_supplier_payment_term_id.id
self.currency_id = default_currency or self.partner_id.property_purchase_currency_id.id or self.env.company.currency_id.id
return {}
@api.onchange('fiscal_position_id', 'company_id')
def _compute_tax_id(self):
"""
Trigger the recompute of the taxes if the fiscal position is changed on the PO.
"""
self.order_line._compute_tax_id()
@api.onchange('partner_id')
def onchange_partner_id_warning(self):
if not self.partner_id or not self.env.user.has_group('purchase.group_warning_purchase'):
return
partner = self.partner_id
# If partner has no warning, check its company
if partner.purchase_warn == 'no-message' and partner.parent_id:
partner = partner.parent_id
if partner.purchase_warn and partner.purchase_warn != 'no-message':
# Block if partner only has warning but parent company is blocked
if partner.purchase_warn != 'block' and partner.parent_id and partner.parent_id.purchase_warn == 'block':
partner = partner.parent_id
title = _("Warning for %s", partner.name)
message = partner.purchase_warn_msg
warning = {
'title': title,
'message': message
}
if partner.purchase_warn == 'block':
self.update({'partner_id': False})
return {'warning': warning}
return {}
def action_rfq_send(self):
'''
This function opens a window to compose an email, with the edi purchase template message loaded by default
'''
self.ensure_one()
ir_model_data = self.env['ir.model.data']
try:
if self.env.context.get('send_rfq', False):
template_id = ir_model_data._xmlid_lookup('purchase.email_template_edi_purchase')[2]
else:
template_id = ir_model_data._xmlid_lookup('purchase.email_template_edi_purchase_done')[2]
except ValueError:
template_id = False
try:
compose_form_id = ir_model_data._xmlid_lookup('mail.email_compose_message_wizard_form')[2]
except ValueError:
compose_form_id = False
ctx = dict(self.env.context or {})
ctx.update({
'default_model': 'purchase.order',
'active_model': 'purchase.order',
'active_id': self.ids[0],
'default_res_id': self.ids[0],
'default_use_template': bool(template_id),
'default_template_id': template_id,
'default_composition_mode': 'comment',
'custom_layout': "mail.mail_notification_paynow",
'force_email': True,
'mark_rfq_as_sent': True,
})
# In the case of a RFQ or a PO, we want the "View..." button in line with the state of the
# object. Therefore, we pass the model description in the context, in the language in which
# the template is rendered.
lang = self.env.context.get('lang')
if {'default_template_id', 'default_model', 'default_res_id'} <= ctx.keys():
template = self.env['mail.template'].browse(ctx['default_template_id'])
if template and template.lang:
lang = template._render_lang([ctx['default_res_id']])[ctx['default_res_id']]
self = self.with_context(lang=lang)
if self.state in ['draft', 'sent']:
ctx['model_description'] = _('Request for Quotation')
else:
ctx['model_description'] = _('Purchase Order')
return {
'name': _('Compose Email'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'mail.compose.message',
'views': [(compose_form_id, 'form')],
'view_id': compose_form_id,
'target': 'new',
'context': ctx,
}
@api.returns('mail.message', lambda value: value.id)
def message_post(self, **kwargs):
if self.env.context.get('mark_rfq_as_sent'):
self.filtered(lambda o: o.state == 'draft').write({'state': 'sent'})
return super(PurchaseOrder, self.with_context(mail_post_autofollow=self.env.context.get('mail_post_autofollow', True))).message_post(**kwargs)
def print_quotation(self):
self.write({'state': "sent"})
return self.env.ref('purchase.report_purchase_quotation').report_action(self)
def button_approve(self, force=False):
self = self.filtered(lambda order: order._approval_allowed())
self.write({'state': 'purchase', 'date_approve': fields.Datetime.now()})
self.filtered(lambda p: p.company_id.po_lock == 'lock').write({'state': 'done'})
return {}
def button_draft(self):
self.write({'state': 'draft'})
return {}
def button_confirm(self):
for order in self:
if order.state not in ['draft', 'sent']:
continue
order._add_supplier_to_product()
# Deal with double validation process
if order._approval_allowed():
order.button_approve()
else:
order.write({'state': 'to approve'})
if order.partner_id not in order.message_partner_ids:
order.message_subscribe([order.partner_id.id])
return True
def button_cancel(self):
for order in self:
for inv in order.invoice_ids:
if inv and inv.state not in ('cancel', 'draft'):
raise UserError(_("Unable to cancel this purchase order. You must first cancel the related vendor bills."))
self.write({'state': 'cancel', 'mail_reminder_confirmed': False})
def button_unlock(self):
self.write({'state': 'purchase'})
def button_done(self):
self.write({'state': 'done', 'priority': '0'})
def _prepare_supplier_info(self, partner, line, price, currency):
# Prepare supplierinfo data when adding a product
return {
'name': partner.id,
'sequence': max(line.product_id.seller_ids.mapped('sequence')) + 1 if line.product_id.seller_ids else 1,
'min_qty': 0.0,
'price': price,
'currency_id': currency.id,
'delay': 0,
}
def _add_supplier_to_product(self):
# Add the partner in the supplier list of the product if the supplier is not registered for
# this product. We limit to 10 the number of suppliers for a product to avoid the mess that
# could be caused for some generic products ("Miscellaneous").
for line in self.order_line:
# Do not add a contact as a supplier
partner = self.partner_id if not self.partner_id.parent_id else self.partner_id.parent_id
already_seller = (partner | self.partner_id) & line.product_id.seller_ids.mapped('name')
if line.product_id and not already_seller and len(line.product_id.seller_ids) <= 10:
# Convert the price in the right currency.
currency = partner.property_purchase_currency_id or self.env.company.currency_id
price = self.currency_id._convert(line.price_unit, currency, line.company_id, line.date_order or fields.Date.today(), round=False)
# Compute the price for the template's UoM, because the supplier's UoM is related to that UoM.
if line.product_id.product_tmpl_id.uom_po_id != line.product_uom:
default_uom = line.product_id.product_tmpl_id.uom_po_id
price = line.product_uom._compute_price(price, default_uom)
supplierinfo = self._prepare_supplier_info(partner, line, price, currency)
# In case the order partner is a contact address, a new supplierinfo is created on
# the parent company. In this case, we keep the product name and code.
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:
supplierinfo['product_name'] = seller.product_name
supplierinfo['product_code'] = seller.product_code
vals = {
'seller_ids': [(0, 0, supplierinfo)],
}
try:
line.product_id.write(vals)
except AccessError: # no write access rights -> just ignore
break
def action_create_invoice(self):
"""Create the invoice associated to the PO.
"""
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
# 1) Prepare invoice vals and clean-up the section lines
invoice_vals_list = []
sequence = 10
for order in self:
if order.invoice_status != 'to invoice':
continue
order = order.with_company(order.company_id)
pending_section = None
# Invoice values.
invoice_vals = order._prepare_invoice()
# Invoice line values (keep only necessary sections).
for line in order.order_line:
if line.display_type == 'line_section':
pending_section = line
continue
if not float_is_zero(line.qty_to_invoice, precision_digits=precision):
if pending_section:
line_vals = pending_section._prepare_account_move_line()
line_vals.update({'sequence': sequence})
invoice_vals['invoice_line_ids'].append((0, 0, line_vals))
sequence += 1
pending_section = None
line_vals = line._prepare_account_move_line()
line_vals.update({'sequence': sequence})
invoice_vals['invoice_line_ids'].append((0, 0, line_vals))
sequence += 1
invoice_vals_list.append(invoice_vals)
if not invoice_vals_list:
raise UserError(_('There is no invoiceable line. If a product has a control policy based on received quantity, please make sure that a quantity has been received.'))
# 2) group by (company_id, partner_id, currency_id) for batch creation
new_invoice_vals_list = []
for grouping_keys, invoices in groupby(invoice_vals_list, key=lambda x: (x.get('company_id'), x.get('partner_id'), x.get('currency_id'))):
origins = set()
payment_refs = set()
refs = set()
ref_invoice_vals = None
for invoice_vals in invoices:
if not ref_invoice_vals:
ref_invoice_vals = invoice_vals
else:
ref_invoice_vals['invoice_line_ids'] += invoice_vals['invoice_line_ids']
origins.add(invoice_vals['invoice_origin'])
payment_refs.add(invoice_vals['payment_reference'])
refs.add(invoice_vals['ref'])
ref_invoice_vals.update({
'ref': ', '.join(refs)[:2000],
'invoice_origin': ', '.join(origins),
'payment_reference': len(payment_refs) == 1 and payment_refs.pop() or False,
})
new_invoice_vals_list.append(ref_invoice_vals)
invoice_vals_list = new_invoice_vals_list
# 3) Create invoices.
moves = self.env['account.move']
AccountMove = self.env['account.move'].with_context(default_move_type='in_invoice')
for vals in invoice_vals_list:
moves |= AccountMove.with_company(vals['company_id']).create(vals)
# 4) Some moves might actually be refunds: convert them if the total amount is negative
# We do this after the moves have been created since we need taxes, etc. to know if the total
# is actually negative or not
moves.filtered(lambda m: m.currency_id.round(m.amount_total) < 0).action_switch_invoice_into_refund_credit_note()
return self.action_view_invoice(moves)
def _prepare_invoice(self):
"""Prepare the dict of values to create the new invoice for a purchase order.
"""
self.ensure_one()
move_type = self._context.get('default_move_type', 'in_invoice')
journal = self.env['account.move'].with_context(default_move_type=move_type)._get_default_journal()
if not journal:
raise UserError(_('Please define an accounting purchase journal for the company %s (%s).') % (self.company_id.name, self.company_id.id))
partner_invoice_id = self.partner_id.address_get(['invoice'])['invoice']
partner_bank_id = self.partner_id.commercial_partner_id.bank_ids.filtered_domain(['|', ('company_id', '=', False), ('company_id', '=', self.company_id.id)])[:1]
invoice_vals = {
'ref': self.partner_ref or '',
'move_type': move_type,
'narration': self.notes,
'currency_id': self.currency_id.id,
'invoice_user_id': self.user_id and self.user_id.id or self.env.user.id,
'partner_id': partner_invoice_id,
'fiscal_position_id': (self.fiscal_position_id or self.fiscal_position_id.get_fiscal_position(partner_invoice_id)).id,
'payment_reference': self.partner_ref or '',
'partner_bank_id': partner_bank_id.id,
'invoice_origin': self.name,
'invoice_payment_term_id': self.payment_term_id.id,
'invoice_line_ids': [],
'company_id': self.company_id.id,
}
return invoice_vals
def action_view_invoice(self, invoices=False):
"""This function returns an action that display existing vendor bills of
given purchase order ids. When only one found, show the vendor bill
immediately.
"""
if not invoices:
# Invoice_ids may be filtered depending on the user. To ensure we get all
# invoices related to the purchase order, we read them in sudo to fill the
# cache.
self.sudo()._read(['invoice_ids'])
invoices = self.invoice_ids
result = self.env['ir.actions.act_window']._for_xml_id('account.action_move_in_invoice_type')
# choose the view_mode accordingly
if len(invoices) > 1:
result['domain'] = [('id', 'in', invoices.ids)]
elif len(invoices) == 1:
res = self.env.ref('account.view_move_form', False)
form_view = [(res and res.id or False, 'form')]
if 'views' in result:
result['views'] = form_view + [(state, view) for state, view in result['views'] if view != 'form']
else:
result['views'] = form_view
result['res_id'] = invoices.id
else:
result = {'type': 'ir.actions.act_window_close'}
return result
@api.model
def retrieve_dashboard(self):
""" This function returns the values to populate the custom dashboard in
the purchase order views.
"""
self.check_access_rights('read')
result = {
'all_to_send': 0,
'all_waiting': 0,
'all_late': 0,
'my_to_send': 0,
'my_waiting': 0,
'my_late': 0,
'all_avg_order_value': 0,
'all_avg_days_to_purchase': 0,
'all_total_last_7_days': 0,
'all_sent_rfqs': 0,
'company_currency_symbol': self.env.company.currency_id.symbol
}
one_week_ago = fields.Datetime.to_string(fields.Datetime.now() - relativedelta(days=7))
# Get list of translation values
Translation = self.env['ir.translation']
list_old_value_char = []
list_new_value_char = []
field_name = 'ir.model.fields.selection,name'
for lang in self.env['res.lang'].search_read([], ['code']):
list_old_value_char.append(Translation._get_source(field_name, 'model', lang['code'], source='RFQ'))
list_new_value_char.append(Translation._get_source(field_name, 'model', lang['code'], source='RFQ Sent'))
# This query is brittle since it depends on the label values of a selection field
# not changing, but we don't have a direct time tracker of when a state changes
query = """SELECT COUNT(1)
FROM mail_tracking_value v
LEFT JOIN mail_message m ON (v.mail_message_id = m.id)
JOIN purchase_order po ON (po.id = m.res_id)
WHERE m.create_date >= %s
AND m.model = 'purchase.order'
AND m.message_type = 'notification'
AND v.old_value_char IN %s
AND v.new_value_char IN %s
AND po.company_id = %s;
"""
self.env.cr.execute(query, (one_week_ago, tuple(list_old_value_char), tuple(list_new_value_char), self.env.company.id))
res = self.env.cr.fetchone()
result['all_sent_rfqs'] = res[0] or 0
# easy counts
po = self.env['purchase.order']
result['all_to_send'] = po.search_count([('state', '=', 'draft')])
result['my_to_send'] = po.search_count([('state', '=', 'draft'), ('user_id', '=', self.env.uid)])
result['all_waiting'] = po.search_count([('state', '=', 'sent'), ('date_order', '>=', fields.Datetime.now())])
result['my_waiting'] = po.search_count([('state', '=', 'sent'), ('date_order', '>=', fields.Datetime.now()), ('user_id', '=', self.env.uid)])
result['all_late'] = po.search_count([('state', 'in', ['draft', 'sent', 'to approve']), ('date_order', '<', fields.Datetime.now())])
result['my_late'] = po.search_count([('state', 'in', ['draft', 'sent', 'to approve']), ('date_order', '<', fields.Datetime.now()), ('user_id', '=', self.env.uid)])
# Calculated values ('avg order value', 'avg days to purchase', and 'total last 7 days') note that 'avg order value' and
# 'total last 7 days' takes into account exchange rate and current company's currency's precision. Min of currency precision
# is taken to easily extract it from query.
# This is done via SQL for scalability reasons
query = """SELECT AVG(COALESCE(po.amount_total / NULLIF(po.currency_rate, 0), po.amount_total)),
AVG(extract(epoch from age(po.date_approve,po.create_date)/(24*60*60)::decimal(16,2))),
SUM(CASE WHEN po.date_approve >= %s THEN COALESCE(po.amount_total / NULLIF(po.currency_rate, 0), po.amount_total) ELSE 0 END)
FROM purchase_order po
JOIN res_company comp ON (po.company_id = comp.id)
WHERE po.state in ('purchase', 'done')
AND po.company_id = %s
"""
self._cr.execute(query, (one_week_ago, self.env.company.id))
res = self.env.cr.fetchone()
result['all_avg_days_to_purchase'] = round(res[1] or 0, 2)
currency = self.env.company.currency_id
result['all_avg_order_value'] = format_amount(self.env, res[0] or 0, currency)
result['all_total_last_7_days'] = format_amount(self.env, res[2] or 0, currency)
return result
def _send_reminder_mail(self, send_single=False):
if not self.user_has_groups('purchase.group_send_reminder'):
return
template = self.env.ref('purchase.email_template_edi_purchase_reminder', raise_if_not_found=False)
if template:
orders = self if send_single else self._get_orders_to_remind()
for order in orders:
date = order.date_planned
if date and (send_single or (date - relativedelta(days=order.reminder_date_before_receipt)).date() == datetime.today().date()):
if send_single:
return order._send_reminder_open_composer(template.id)
else:
order.with_context(is_reminder=True).message_post_with_template(template.id, email_layout_xmlid="mail.mail_notification_paynow", composition_mode='comment')
def send_reminder_preview(self):
self.ensure_one()
if not self.user_has_groups('purchase.group_send_reminder'):
return
template = self.env.ref('purchase.email_template_edi_purchase_reminder', raise_if_not_found=False)
if template and self.env.user.email and self.id:
template.with_context(is_reminder=True).send_mail(
self.id,
force_send=True,
raise_exception=False,
email_values={'email_to': self.env.user.email, 'recipient_ids': []},
notif_layout="mail.mail_notification_paynow")
return {'toast_message': escape(_("A sample email has been sent to %s.", self.env.user.email))}
def _send_reminder_open_composer(self,template_id):
self.ensure_one()
try:
compose_form_id = self.env['ir.model.data']._xmlid_lookup('mail.email_compose_message_wizard_form')[2]
except ValueError:
compose_form_id = False
ctx = dict(self.env.context or {})
ctx.update({
'default_model': 'purchase.order',
'active_model': 'purchase.order',
'active_id': self.ids[0],
'default_res_id': self.ids[0],
'default_use_template': bool(template_id),
'default_template_id': template_id,
'default_composition_mode': 'comment',
'custom_layout': "mail.mail_notification_paynow",
'force_email': True,
'mark_rfq_as_sent': True,
})
lang = self.env.context.get('lang')
if {'default_template_id', 'default_model', 'default_res_id'} <= ctx.keys():
template = self.env['mail.template'].browse(ctx['default_template_id'])
if template and template.lang:
lang = template._render_lang([ctx['default_res_id']])[ctx['default_res_id']]
self = self.with_context(lang=lang)
ctx['model_description'] = _('Purchase Order')
return {
'name': _('Compose Email'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'mail.compose.message',
'views': [(compose_form_id, 'form')],
'view_id': compose_form_id,
'target': 'new',
'context': ctx,
}
@api.model
def _get_orders_to_remind(self):
"""When auto sending a reminder mail, only send for unconfirmed purchase
order and not all products are service."""
return self.search([
('receipt_reminder_email', '=', True),
('state', 'in', ['purchase', 'done']),
('mail_reminder_confirmed', '=', False)
]).filtered(lambda p: p.mapped('order_line.product_id.product_tmpl_id.type') != ['service'])
def get_confirm_url(self, confirm_type=None):
"""Create url for confirm reminder or purchase reception email for sending
in mail."""
if confirm_type in ['reminder', 'reception']:
param = url_encode({
'confirm': confirm_type,
'confirmed_date': self.date_planned and self.date_planned.date(),
})
return self.get_portal_url(query_string='&%s' % param)
return self.get_portal_url()
def get_update_url(self):
"""Create portal url for user to update the scheduled date on purchase
order lines."""
update_param = url_encode({'update': 'True'})
return self.get_portal_url(query_string='&%s' % update_param)
def confirm_reminder_mail(self, confirmed_date=False):
for order in self:
if order.state in ['purchase', 'done'] and not order.mail_reminder_confirmed:
order.mail_reminder_confirmed = True
date = confirmed_date or self.date_planned.date()
order.message_post(body=_("%s confirmed the receipt will take place on %s.", order.partner_id.name, date))
def _approval_allowed(self):
"""Returns whether the order qualifies to be approved by the current user"""
self.ensure_one()
return (
self.company_id.po_double_validation == 'one_step'
or (self.company_id.po_double_validation == 'two_step'
and self.amount_total < self.env.company.currency_id._convert(
self.company_id.po_double_validation_amount, self.currency_id, self.company_id,
self.date_order or fields.Date.today()))
or self.user_has_groups('purchase.group_purchase_manager'))
def _confirm_reception_mail(self):
for order in self:
if order.state in ['purchase', 'done'] and not order.mail_reception_confirmed:
order.mail_reception_confirmed = True
order.message_post(body=_("The order receipt has been acknowledged by %s.", order.partner_id.name))
def _update_date_planned_for_lines(self, updated_dates):
# create or update the activity
activity = self.env['mail.activity'].search([
('summary', '=', _('Date Updated')),
('res_model_id', '=', 'purchase.order'),
('res_id', '=', self.id),
('user_id', '=', self.user_id.id)], limit=1)
if activity:
self._update_update_date_activity(updated_dates, activity)
else:
self._create_update_date_activity(updated_dates)
# update the date on PO line
for line, date in updated_dates:
line._update_date_planned(date)
def _create_update_date_activity(self, updated_dates):
note = Markup('<p>%s</p>\n') % _('%s modified receipt dates for the following products:', self.partner_id.name)
for line, date in updated_dates:
note += Markup('<p> - %s</p>\n') % _(
'%(product)s from %(original_receipt_date)s to %(new_receipt_date)s',
product=line.product_id.display_name,
original_receipt_date=line.date_planned.date(),
new_receipt_date=date.date()
)
activity = self.activity_schedule(
'mail.mail_activity_data_warning',
summary=_("Date Updated"),
user_id=self.user_id.id
)
# add the note after we post the activity because the note can be soon
# changed when updating the date of the next PO line. So instead of
# sending a mail with incomplete note, we send one with no note.
activity.note = note
return activity
def _update_update_date_activity(self, updated_dates, activity):
for line, date in updated_dates:
activity.note += Markup('<p> - %s</p>\n') % _(
'%(product)s from %(original_receipt_date)s to %(new_receipt_date)s',
product=line.product_id.display_name,
original_receipt_date=line.date_planned.date(),
new_receipt_date=date.date()
)
def _write_partner_values(self, vals):
partner_values = {}
if 'receipt_reminder_email' in vals:
partner_values['receipt_reminder_email'] = vals.pop('receipt_reminder_email')
if 'reminder_date_before_receipt' in vals:
partner_values['reminder_date_before_receipt'] = vals.pop('reminder_date_before_receipt')
return vals, partner_values
class PurchaseOrderLine(models.Model):
_name = 'purchase.order.line'
_description = 'Purchase Order Line'
_order = 'order_id, sequence, id'
name = fields.Text(string='Description', required=True)
sequence = fields.Integer(string='Sequence', default=10)
product_qty = fields.Float(string='Quantity', digits='Product Unit of Measure', required=True)
product_uom_qty = fields.Float(string='Total Quantity', compute='_compute_product_uom_qty', store=True)
date_planned = fields.Datetime(string='Delivery Date', index=True,
help="Delivery date expected from vendor. This date respectively defaults to vendor pricelist lead time then today's date.")
taxes_id = fields.Many2many('account.tax', string='Taxes', domain=['|', ('active', '=', False), ('active', '=', True)])
product_uom = fields.Many2one('uom.uom', string='Unit of Measure', domain="[('category_id', '=', product_uom_category_id)]")
product_uom_category_id = fields.Many2one(related='product_id.uom_id.category_id')
product_id = fields.Many2one('product.product', string='Product', domain=[('purchase_ok', '=', True)], change_default=True)
product_type = fields.Selection(related='product_id.detailed_type', readonly=True)
price_unit = fields.Float(string='Unit Price', required=True, digits='Product Price')
price_subtotal = fields.Monetary(compute='_compute_amount', string='Subtotal', store=True)
price_total = fields.Monetary(compute='_compute_amount', string='Total', store=True)
price_tax = fields.Float(compute='_compute_amount', string='Tax', store=True)
order_id = fields.Many2one('purchase.order', string='Order Reference', index=True, required=True, ondelete='cascade')
account_analytic_id = fields.Many2one('account.analytic.account', store=True, string='Analytic Account', compute='_compute_account_analytic_id', readonly=False)
analytic_tag_ids = fields.Many2many('account.analytic.tag', store=True, string='Analytic Tags', compute='_compute_analytic_tag_ids', readonly=False)
company_id = fields.Many2one('res.company', related='order_id.company_id', string='Company', store=True, readonly=True)
state = fields.Selection(related='order_id.state', store=True)
invoice_lines = fields.One2many('account.move.line', 'purchase_line_id', string="Bill Lines", readonly=True, copy=False)
# Replace by invoiced Qty
qty_invoiced = fields.Float(compute='_compute_qty_invoiced', string="Billed Qty", digits='Product Unit of Measure', store=True)
qty_received_method = fields.Selection([('manual', 'Manual')], string="Received Qty Method", compute='_compute_qty_received_method', store=True,
help="According to product configuration, the received quantity can be automatically computed by mechanism :\n"
" - Manual: the quantity is set manually on the line\n"
" - Stock Moves: the quantity comes from confirmed pickings\n")
qty_received = fields.Float("Received Qty", compute='_compute_qty_received', inverse='_inverse_qty_received', compute_sudo=True, store=True, digits='Product Unit of Measure')
qty_received_manual = fields.Float("Manual Received Qty", digits='Product Unit of Measure', copy=False)
qty_to_invoice = fields.Float(compute='_compute_qty_invoiced', string='To Invoice Quantity', store=True, readonly=True,
digits='Product Unit of Measure')
partner_id = fields.Many2one('res.partner', related='order_id.partner_id', string='Partner', readonly=True, store=True)
currency_id = fields.Many2one(related='order_id.currency_id', store=True, string='Currency', readonly=True)
date_order = fields.Datetime(related='order_id.date_order', string='Order Date', readonly=True)
product_packaging_id = fields.Many2one('product.packaging', string='Packaging', domain="[('purchase', '=', True), ('product_id', '=', product_id)]", check_company=True)
product_packaging_qty = fields.Float('Packaging Quantity')
display_type = fields.Selection([
('line_section', "Section"),
('line_note', "Note")], default=False, help="Technical field for UX purpose.")
_sql_constraints = [
('accountable_required_fields',
"CHECK(display_type IS NOT NULL OR (product_id IS NOT NULL AND product_uom IS NOT NULL AND date_planned IS NOT NULL))",
"Missing required fields on accountable purchase order line."),
('non_accountable_null_fields',
"CHECK(display_type IS NULL OR (product_id IS NULL AND price_unit = 0 AND product_uom_qty = 0 AND product_uom IS NULL AND date_planned is NULL))",
"Forbidden values on non-accountable purchase order line"),
]
@api.depends('product_qty', 'price_unit', 'taxes_id')
def _compute_amount(self):
for line in self:
taxes = line.taxes_id.compute_all(**line._prepare_compute_all_values())
line.update({
'price_tax': sum(t.get('amount', 0.0) for t in taxes.get('taxes', [])),
'price_total': taxes['total_included'],
'price_subtotal': taxes['total_excluded'],
})
def _prepare_compute_all_values(self):
# Hook method to returns the different argument values for the
# compute_all method, due to the fact that discounts mechanism
# is not implemented yet on the purchase orders.
# This method should disappear as soon as this feature is
# also introduced like in the sales module.
self.ensure_one()
return {
'price_unit': self.price_unit,
'currency': self.order_id.currency_id,
'quantity': self.product_qty,
'product': self.product_id,
'partner': self.order_id.partner_id,
}
def _compute_tax_id(self):
for line in self:
line = line.with_company(line.company_id)
fpos = line.order_id.fiscal_position_id or line.order_id.fiscal_position_id.get_fiscal_position(line.order_id.partner_id.id)
# filter taxes by company
taxes = line.product_id.supplier_taxes_id.filtered(lambda r: r.company_id == line.env.company)
line.taxes_id = fpos.map_tax(taxes)
@api.depends('invoice_lines.move_id.state', 'invoice_lines.quantity', 'qty_received', 'product_uom_qty', 'order_id.state')
def _compute_qty_invoiced(self):
for line in self:
# compute qty_invoiced
qty = 0.0
for inv_line in line._get_invoice_lines():
if inv_line.move_id.state not in ['cancel'] or inv_line.move_id.payment_state == 'invoicing_legacy':
if inv_line.move_id.move_type == 'in_invoice':
qty += inv_line.product_uom_id._compute_quantity(inv_line.quantity, line.product_uom)
elif inv_line.move_id.move_type == 'in_refund':
qty -= inv_line.product_uom_id._compute_quantity(inv_line.quantity, line.product_uom)
line.qty_invoiced = qty
# compute qty_to_invoice
if line.order_id.state in ['purchase', 'done']:
if line.product_id.purchase_method == 'purchase':
line.qty_to_invoice = line.product_qty - line.qty_invoiced
else:
line.qty_to_invoice = line.qty_received - line.qty_invoiced
else:
line.qty_to_invoice = 0
def _get_invoice_lines(self):
self.ensure_one()
if self._context.get('accrual_entry_date'):
return self.invoice_lines.filtered(
lambda l: l.move_id.invoice_date and l.move_id.invoice_date <= self._context['accrual_entry_date']
)
else:
return self.invoice_lines
@api.depends('product_id', 'product_id.type')
def _compute_qty_received_method(self):
for line in self:
if line.product_id and line.product_id.type in ['consu', 'service']:
line.qty_received_method = 'manual'
else:
line.qty_received_method = False
@api.depends('qty_received_method', 'qty_received_manual')
def _compute_qty_received(self):
for line in self:
if line.qty_received_method == 'manual':
line.qty_received = line.qty_received_manual or 0.0
else:
line.qty_received = 0.0
@api.onchange('qty_received')
def _inverse_qty_received(self):
""" When writing on qty_received, if the value should be modify manually (`qty_received_method` = 'manual' only),
then we put the value in `qty_received_manual`. Otherwise, `qty_received_manual` should be False since the
received qty is automatically compute by other mecanisms.
"""
for line in self:
if line.qty_received_method == 'manual':
line.qty_received_manual = line.qty_received
else:
line.qty_received_manual = 0.0
@api.model_create_multi
def create(self, vals_list):
for values in vals_list:
if values.get('display_type', self.default_get(['display_type'])['display_type']):
values.update(product_id=False, price_unit=0, product_uom_qty=0, product_uom=False, date_planned=False)
else:
values.update(self._prepare_add_missing_fields(values))
lines = super().create(vals_list)
for line in lines:
if line.product_id and line.order_id.state == 'purchase':
msg = _("Extra line with %s ") % (line.product_id.display_name,)
line.order_id.message_post(body=msg)
return lines
def write(self, values):
if 'display_type' in values and self.filtered(lambda line: line.display_type != values.get('display_type')):
raise UserError(_("You cannot change the type of a purchase order line. Instead you should delete the current line and create a new line of the proper type."))
if 'product_qty' in values:
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
for line in self:
if (
line.order_id.state == "purchase"
and float_compare(line.product_qty, values["product_qty"], precision_digits=precision) != 0
):
line.order_id.message_post_with_view('purchase.track_po_line_template',
values={'line': line, 'product_qty': values['product_qty']},
subtype_id=self.env.ref('mail.mt_note').id)
if 'qty_received' in values:
for line in self:
line._track_qty_received(values['qty_received'])
return super(PurchaseOrderLine, self).write(values)
@api.ondelete(at_uninstall=False)
def _unlink_except_purchase_or_done(self):
for line in self:
if line.order_id.state in ['purchase', 'done']:
state_description = {state_desc[0]: state_desc[1] for state_desc in self._fields['state']._description_selection(self.env)}
raise UserError(_('Cannot delete a purchase order line which is in state \'%s\'.') % (state_description.get(line.state),))
@api.model
def _get_date_planned(self, seller, po=False):
"""Return the datetime value to use as Schedule Date (``date_planned``) for
PO Lines that correspond to the given product.seller_ids,
when ordered at `date_order_str`.
:param Model seller: used to fetch the delivery delay (if no seller
is provided, the delay is 0)
:param Model po: purchase.order, necessary only if the PO line is
not yet attached to a PO.
:rtype: datetime
:return: desired Schedule Date for the PO line
"""
date_order = po.date_order if po else self.order_id.date_order
if date_order:
return date_order + relativedelta(days=seller.delay if seller else 0)
else:
return datetime.today() + relativedelta(days=seller.delay if seller else 0)
@api.depends('product_id', 'date_order')
def _compute_account_analytic_id(self):
for rec in self:
if not rec.display_type:
default_analytic_account = rec.env['account.analytic.default'].sudo().account_get(
product_id=rec.product_id.id,
partner_id=rec.order_id.partner_id.id,
user_id=rec.env.uid,
date=rec.date_order,
company_id=rec.company_id.id,
)
if default_analytic_account:
rec.account_analytic_id = default_analytic_account.analytic_id
@api.depends('product_id', 'date_order')
def _compute_analytic_tag_ids(self):
for rec in self:
if not rec.display_type:
default_analytic_account = rec.env['account.analytic.default'].sudo().account_get(
product_id=rec.product_id.id,
partner_id=rec.order_id.partner_id.id,
user_id=rec.env.uid,
date=rec.date_order,
company_id=rec.company_id.id,
)
if default_analytic_account:
rec.analytic_tag_ids = default_analytic_account.analytic_tag_ids
@api.onchange('product_id', 'company_id')
def onchange_product_id(self):
if not self.product_id or not self.company_id:
return
# Reset date, price and quantity since _onchange_quantity will provide default values
self.price_unit = self.product_qty = 0.0
self._product_id_change()
self._suggest_quantity()
self._onchange_quantity()
def _product_id_change(self):
if not self.product_id:
return
self.product_uom = self.product_id.uom_po_id or self.product_id.uom_id
product_lang = self.product_id.with_context(
lang=get_lang(self.env, self.partner_id.lang).code,
partner_id=self.partner_id.id,
company_id=self.company_id.id,
)
self.name = self._get_product_purchase_description(product_lang)
self._compute_tax_id()
@api.onchange('product_id')
def onchange_product_id_warning(self):
if not self.product_id or not self.env.user.has_group('purchase.group_warning_purchase'):
return
warning = {}
title = False
message = False
product_info = self.product_id
if product_info.purchase_line_warn != 'no-message':
title = _("Warning for %s", product_info.name)
message = product_info.purchase_line_warn_msg
warning['title'] = title
warning['message'] = message
if product_info.purchase_line_warn == 'block':
self.product_id = False
return {'warning': warning}
return {}
@api.onchange('product_qty', 'product_uom', 'company_id')
def _onchange_quantity(self):
if not self.product_id or self.invoice_lines or not self.company_id:
return
params = {'order_id': self.order_id}
seller = self.product_id._select_seller(
partner_id=self.partner_id,
quantity=self.product_qty,
date=self.order_id.date_order and self.order_id.date_order.date(),
uom_id=self.product_uom,
params=params)
if seller or not self.date_planned:
self.date_planned = self._get_date_planned(seller).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
# If not seller, use the standard price. It needs a proper currency conversion.
if not seller:
po_line_uom = self.product_uom or self.product_id.uom_po_id
price_unit = self.env['account.tax']._fix_tax_included_price_company(
self.product_id.uom_id._compute_price(self.product_id.standard_price, po_line_uom),
self.product_id.supplier_taxes_id,
self.taxes_id,
self.company_id,
)
if price_unit and self.order_id.currency_id and self.order_id.company_id.currency_id != self.order_id.currency_id:
price_unit = self.order_id.company_id.currency_id._convert(
price_unit,
self.order_id.currency_id,
self.order_id.company_id,
self.date_order or fields.Date.today(),
)
self.price_unit = price_unit
return
price_unit = self.env['account.tax']._fix_tax_included_price_company(seller.price, self.product_id.supplier_taxes_id, self.taxes_id, self.company_id) if seller else 0.0
if price_unit and seller and self.order_id.currency_id and seller.currency_id != self.order_id.currency_id:
price_unit = seller.currency_id._convert(
price_unit, self.order_id.currency_id, self.order_id.company_id, self.date_order or fields.Date.today())
if seller and self.product_uom and seller.product_uom != self.product_uom:
price_unit = seller.product_uom._compute_price(price_unit, self.product_uom)
self.price_unit = price_unit
default_names = []
vendors = self.product_id._prepare_sellers({})
for vendor in vendors:
product_ctx = {'seller_id': vendor.id, 'lang': get_lang(self.env, self.partner_id.lang).code}
default_names.append(self._get_product_purchase_description(self.product_id.with_context(product_ctx)))
if (self.name in default_names or not self.name):
product_ctx = {'seller_id': seller.id, 'lang': get_lang(self.env, self.partner_id.lang).code}
self.name = self._get_product_purchase_description(self.product_id.with_context(product_ctx))
@api.onchange('product_id', 'product_qty', 'product_uom')
def _onchange_suggest_packaging(self):
# remove packaging if not match the product
if self.product_packaging_id.product_id != self.product_id:
self.product_packaging_id = False
# suggest biggest suitable packaging
if self.product_id and self.product_qty and self.product_uom:
self.product_packaging_id = self.product_id.packaging_ids.filtered('purchase')._find_suitable_product_packaging(self.product_qty, self.product_uom) or self.product_packaging_id
@api.onchange('product_packaging_id')
def _onchange_product_packaging_id(self):
if self.product_packaging_id and self.product_qty:
newqty = self.product_packaging_id._check_qty(self.product_qty, self.product_uom, "UP")
if float_compare(newqty, self.product_qty, precision_rounding=self.product_uom.rounding) != 0:
return {
'warning': {
'title': _('Warning'),
'message': _(
"This product is packaged by %(pack_size).2f %(pack_name)s. You should purchase %(quantity).2f %(unit)s.",
pack_size=self.product_packaging_id.qty,
pack_name=self.product_id.uom_id.name,
quantity=newqty,
unit=self.product_uom.name
),
},
}
@api.onchange('product_packaging_id', 'product_uom', 'product_qty')
def _onchange_update_product_packaging_qty(self):
if not self.product_packaging_id:
self.product_packaging_qty = 0
else:
packaging_uom = self.product_packaging_id.product_uom_id
packaging_uom_qty = self.product_uom._compute_quantity(self.product_qty, packaging_uom)
self.product_packaging_qty = float_round(packaging_uom_qty / self.product_packaging_id.qty, precision_rounding=packaging_uom.rounding)
@api.onchange('product_packaging_qty')
def _onchange_product_packaging_qty(self):
if self.product_packaging_id:
packaging_uom = self.product_packaging_id.product_uom_id
qty_per_packaging = self.product_packaging_id.qty
product_qty = packaging_uom._compute_quantity(self.product_packaging_qty * qty_per_packaging, self.product_uom)
if float_compare(product_qty, self.product_qty, precision_rounding=self.product_uom.rounding) != 0:
self.product_qty = product_qty
@api.depends('product_uom', 'product_qty', 'product_id.uom_id')
def _compute_product_uom_qty(self):
for line in self:
if line.product_id and line.product_id.uom_id != line.product_uom:
line.product_uom_qty = line.product_uom._compute_quantity(line.product_qty, line.product_id.uom_id)
else:
line.product_uom_qty = line.product_qty
def _suggest_quantity(self):
'''
Suggest a minimal quantity based on the seller
'''
if not self.product_id:
return
seller_min_qty = self.product_id.seller_ids\
.filtered(lambda r: r.name == self.order_id.partner_id and (not r.product_id or r.product_id == self.product_id))\
.sorted(key=lambda r: r.min_qty)
if seller_min_qty:
self.product_qty = seller_min_qty[0].min_qty or 1.0
self.product_uom = seller_min_qty[0].product_uom
else:
self.product_qty = 1.0
def _get_product_purchase_description(self, product_lang):
self.ensure_one()
name = product_lang.display_name
if product_lang.description_purchase:
name += '\n' + product_lang.description_purchase
return name
def _prepare_account_move_line(self, move=False):
self.ensure_one()
aml_currency = move and move.currency_id or self.currency_id
date = move and move.date or fields.Date.today()
res = {
'display_type': self.display_type,
'sequence': self.sequence,
'name': '%s: %s' % (self.order_id.name, self.name),
'product_id': self.product_id.id,
'product_uom_id': self.product_uom.id,
'quantity': self.qty_to_invoice,
'price_unit': self.currency_id._convert(self.price_unit, aml_currency, self.company_id, date, round=False),
'tax_ids': [(6, 0, self.taxes_id.ids)],
'analytic_account_id': self.account_analytic_id.id,
'analytic_tag_ids': [(6, 0, self.analytic_tag_ids.ids)],
'purchase_line_id': self.id,
}
if not move:
return res
if self.currency_id == move.company_id.currency_id:
currency = False
else:
currency = move.currency_id
res.update({
'move_id': move.id,
'currency_id': currency and currency.id or False,
'date_maturity': move.invoice_date_due,
'partner_id': move.partner_id.id,
})
return res
@api.model
def _prepare_add_missing_fields(self, values):
""" Deduce missing required fields from the onchange """
res = {}
onchange_fields = ['name', 'price_unit', 'product_qty', 'product_uom', 'taxes_id', 'date_planned']
if values.get('order_id') and values.get('product_id') and any(f not in values for f in onchange_fields):
line = self.new(values)
line.onchange_product_id()
for field in onchange_fields:
if field not in values:
res[field] = line._fields[field].convert_to_write(line[field], line)
return res
@api.model
def _prepare_purchase_order_line(self, product_id, product_qty, product_uom, company_id, supplier, po):
partner = supplier.name
uom_po_qty = product_uom._compute_quantity(product_qty, product_id.uom_po_id)
# _select_seller is used if the supplier have different price depending
# the quantities ordered.
seller = product_id.with_company(company_id)._select_seller(
partner_id=partner,
quantity=uom_po_qty,
date=po.date_order and po.date_order.date(),
uom_id=product_id.uom_po_id)
product_taxes = product_id.supplier_taxes_id.filtered(lambda x: x.company_id.id == company_id.id)
taxes = po.fiscal_position_id.map_tax(product_taxes)
price_unit = self.env['account.tax']._fix_tax_included_price_company(
seller.price, product_taxes, taxes, company_id) if seller else 0.0
if price_unit and seller and po.currency_id and seller.currency_id != po.currency_id:
price_unit = seller.currency_id._convert(
price_unit, po.currency_id, po.company_id, po.date_order or fields.Date.today())
product_lang = product_id.with_prefetch().with_context(
lang=partner.lang,
partner_id=partner.id,
)
name = product_lang.with_context(seller_id=seller.id).display_name
if product_lang.description_purchase:
name += '\n' + product_lang.description_purchase
date_planned = self.order_id.date_planned or self._get_date_planned(seller, po=po)
return {
'name': name,
'product_qty': uom_po_qty,
'product_id': product_id.id,
'product_uom': product_id.uom_po_id.id,
'price_unit': price_unit,
'date_planned': date_planned,
'taxes_id': [(6, 0, taxes.ids)],
'order_id': po.id,
}
def _convert_to_middle_of_day(self, date):
"""Return a datetime which is the noon of the input date(time) according
to order user's time zone, convert to UTC time.
"""
return timezone(self.order_id.user_id.tz or self.company_id.partner_id.tz or 'UTC').localize(datetime.combine(date, time(12))).astimezone(UTC).replace(tzinfo=None)
def _update_date_planned(self, updated_date):
self.date_planned = updated_date
def _track_qty_received(self, new_qty):
self.ensure_one()
# don't track anything when coming from the accrued expense entry wizard, as it is only computing fields at a past date to get relevant amounts
# and doesn't actually change anything to the current record
if self.env.context.get('accrual_entry_date'):
return
if new_qty != self.qty_received and self.order_id.state == 'purchase':
self.order_id.message_post_with_view(
'purchase.track_po_line_qty_received_template',
values={'line': self, 'qty_received': new_qty},
subtype_id=self.env.ref('mail.mt_note').id
)
| 50.968243
| 72,222
|
6,636
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
class AccountMove(models.Model):
_inherit = 'account.move'
purchase_vendor_bill_id = fields.Many2one('purchase.bill.union', store=False, readonly=True,
states={'draft': [('readonly', False)]},
string='Auto-complete',
help="Auto-complete from a past bill / purchase order.")
purchase_id = fields.Many2one('purchase.order', store=False, readonly=True,
states={'draft': [('readonly', False)]},
string='Purchase Order',
help="Auto-complete from a past purchase order.")
def _get_invoice_reference(self):
self.ensure_one()
vendor_refs = [ref for ref in set(self.line_ids.mapped('purchase_line_id.order_id.partner_ref')) if ref]
if self.ref:
return [ref for ref in self.ref.split(', ') if ref and ref not in vendor_refs] + vendor_refs
return vendor_refs
@api.onchange('purchase_vendor_bill_id', 'purchase_id')
def _onchange_purchase_auto_complete(self):
''' Load from either an old purchase order, either an old vendor bill.
When setting a 'purchase.bill.union' in 'purchase_vendor_bill_id':
* If it's a vendor bill, 'invoice_vendor_bill_id' is set and the loading is done by '_onchange_invoice_vendor_bill'.
* If it's a purchase order, 'purchase_id' is set and this method will load lines.
/!\ All this not-stored fields must be empty at the end of this function.
'''
if self.purchase_vendor_bill_id.vendor_bill_id:
self.invoice_vendor_bill_id = self.purchase_vendor_bill_id.vendor_bill_id
self._onchange_invoice_vendor_bill()
elif self.purchase_vendor_bill_id.purchase_order_id:
self.purchase_id = self.purchase_vendor_bill_id.purchase_order_id
self.purchase_vendor_bill_id = False
if not self.purchase_id:
return
# Copy data from PO
invoice_vals = self.purchase_id.with_company(self.purchase_id.company_id)._prepare_invoice()
invoice_vals['currency_id'] = self.line_ids and self.currency_id or invoice_vals.get('currency_id')
del invoice_vals['ref']
self.update(invoice_vals)
# Copy purchase lines.
po_lines = self.purchase_id.order_line - self.line_ids.mapped('purchase_line_id')
new_lines = self.env['account.move.line']
sequence = max(self.line_ids.mapped('sequence')) + 1 if self.line_ids else 10
for line in po_lines.filtered(lambda l: not l.display_type):
line_vals = line._prepare_account_move_line(self)
line_vals.update({'sequence': sequence})
new_line = new_lines.new(line_vals)
sequence += 1
new_line.account_id = new_line._get_computed_account()
new_line._onchange_price_subtotal()
new_lines += new_line
new_lines._onchange_mark_recompute_taxes()
# Compute invoice_origin.
origins = set(self.line_ids.mapped('purchase_line_id.order_id.name'))
self.invoice_origin = ','.join(list(origins))
# Compute ref.
refs = self._get_invoice_reference()
self.ref = ', '.join(refs)
# Compute payment_reference.
if len(refs) == 1:
self.payment_reference = refs[0]
self.purchase_id = False
self._onchange_currency()
@api.onchange('partner_id', 'company_id')
def _onchange_partner_id(self):
res = super(AccountMove, self)._onchange_partner_id()
currency_id = (
self.partner_id.property_purchase_currency_id
or self.env['res.currency'].browse(self.env.context.get("default_currency_id"))
or self.currency_id
)
if self.partner_id and self.move_type in ['in_invoice', 'in_refund'] and self.currency_id != currency_id:
if not self.env.context.get('default_journal_id'):
journal_domain = [
('type', '=', 'purchase'),
('company_id', '=', self.company_id.id),
('currency_id', '=', currency_id.id),
]
default_journal_id = self.env['account.journal'].search(journal_domain, limit=1)
if default_journal_id:
self.journal_id = default_journal_id
self.currency_id = currency_id
self._onchange_currency()
return res
@api.model_create_multi
def create(self, vals_list):
# OVERRIDE
moves = super(AccountMove, self).create(vals_list)
for move in moves:
if move.reversed_entry_id:
continue
purchase = move.line_ids.mapped('purchase_line_id.order_id')
if not purchase:
continue
refs = ["<a href=# data-oe-model=purchase.order data-oe-id=%s>%s</a>" % tuple(name_get) for name_get in purchase.name_get()]
message = _("This vendor bill has been created from: %s") % ','.join(refs)
move.message_post(body=message)
return moves
def write(self, vals):
# OVERRIDE
old_purchases = [move.mapped('line_ids.purchase_line_id.order_id') for move in self]
res = super(AccountMove, self).write(vals)
for i, move in enumerate(self):
new_purchases = move.mapped('line_ids.purchase_line_id.order_id')
if not new_purchases:
continue
diff_purchases = new_purchases - old_purchases[i]
if diff_purchases:
refs = ["<a href=# data-oe-model=purchase.order data-oe-id=%s>%s</a>" % tuple(name_get) for name_get in diff_purchases.name_get()]
message = _("This vendor bill has been modified from: %s") % ','.join(refs)
move.message_post(body=message)
return res
class AccountMoveLine(models.Model):
""" Override AccountInvoice_line to add the link to the purchase order line it is related to"""
_inherit = 'account.move.line'
purchase_line_id = fields.Many2one('purchase.order.line', 'Purchase Order Line', ondelete='set null', index=True)
purchase_order_id = fields.Many2one('purchase.order', 'Purchase Order', related='purchase_line_id.order_id', readonly=True)
def _copy_data_extend_business_fields(self, values):
# OVERRIDE to copy the 'purchase_line_id' field as well.
super(AccountMoveLine, self)._copy_data_extend_business_fields(values)
values['purchase_line_id'] = self.purchase_line_id.id
| 44.837838
| 6,636
|
1,335
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class Company(models.Model):
_inherit = 'res.company'
po_lead = fields.Float(string='Purchase Lead Time', required=True,
help="Margin of error for vendor lead times. When the system "
"generates Purchase Orders for procuring products, "
"they will be scheduled that many days earlier "
"to cope with unexpected vendor delays.", default=0.0)
po_lock = fields.Selection([
('edit', 'Allow to edit purchase orders'),
('lock', 'Confirmed purchase orders are not editable')
], string="Purchase Order Modification", default="edit",
help='Purchase Order Modification used when you want to purchase order editable after confirm')
po_double_validation = fields.Selection([
('one_step', 'Confirm purchase orders in one step'),
('two_step', 'Get 2 levels of approvals to confirm a purchase order')
], string="Levels of Approvals", default='one_step',
help="Provide a double validation mechanism for purchases")
po_double_validation_amount = fields.Monetary(string='Double validation amount', default=5000,
help="Minimum amount for which a double validation is required")
| 47.678571
| 1,335
|
4,705
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.addons.base.models.res_partner import WARNING_MESSAGE, WARNING_HELP
from odoo.tools.float_utils import float_round
from dateutil.relativedelta import relativedelta
class ProductTemplate(models.Model):
_name = 'product.template'
_inherit = 'product.template'
property_account_creditor_price_difference = fields.Many2one(
'account.account', string="Price Difference Account", company_dependent=True,
help="This account is used in automated inventory valuation to "\
"record the price difference between a purchase order and its related vendor bill when validating this vendor bill.")
purchased_product_qty = fields.Float(compute='_compute_purchased_product_qty', string='Purchased')
purchase_method = fields.Selection([
('purchase', 'On ordered quantities'),
('receive', 'On received quantities'),
], string="Control Policy", help="On ordered quantities: Control bills based on ordered quantities.\n"
"On received quantities: Control bills based on received quantities.", default="receive")
purchase_line_warn = fields.Selection(WARNING_MESSAGE, 'Purchase Order Line Warning', help=WARNING_HELP, required=True, default="no-message")
purchase_line_warn_msg = fields.Text('Message for Purchase Order Line')
def _compute_purchased_product_qty(self):
for template in self:
template.purchased_product_qty = float_round(sum([p.purchased_product_qty for p in template.product_variant_ids]), precision_rounding=template.uom_id.rounding)
@api.model
def get_import_templates(self):
res = super(ProductTemplate, self).get_import_templates()
if self.env.context.get('purchase_product_template'):
return [{
'label': _('Import Template for Products'),
'template': '/purchase/static/xls/product_purchase.xls'
}]
return res
def action_view_po(self):
action = self.env["ir.actions.actions"]._for_xml_id("purchase.action_purchase_order_report_all")
action['domain'] = ['&', ('state', 'in', ['purchase', 'done']), ('product_tmpl_id', 'in', self.ids)]
action['context'] = {
'graph_measure': 'qty_ordered',
'search_default_later_than_a_year_ago': True
}
return action
class ProductProduct(models.Model):
_name = 'product.product'
_inherit = 'product.product'
purchased_product_qty = fields.Float(compute='_compute_purchased_product_qty', string='Purchased')
def _compute_purchased_product_qty(self):
date_from = fields.Datetime.to_string(fields.Date.context_today(self) - relativedelta(years=1))
domain = [
('order_id.state', 'in', ['purchase', 'done']),
('product_id', 'in', self.ids),
('order_id.date_approve', '>=', date_from)
]
order_lines = self.env['purchase.order.line'].read_group(domain, ['product_id', 'product_uom_qty'], ['product_id'])
purchased_data = dict([(data['product_id'][0], data['product_uom_qty']) for data in order_lines])
for product in self:
if not product.id:
product.purchased_product_qty = 0.0
continue
product.purchased_product_qty = float_round(purchased_data.get(product.id, 0), precision_rounding=product.uom_id.rounding)
def action_view_po(self):
action = self.env["ir.actions.actions"]._for_xml_id("purchase.action_purchase_order_report_all")
action['domain'] = ['&', ('state', 'in', ['purchase', 'done']), ('product_id', 'in', self.ids)]
action['context'] = {
'graph_measure': 'qty_ordered',
'search_default_later_than_a_year_ago': True
}
return action
class ProductCategory(models.Model):
_inherit = "product.category"
property_account_creditor_price_difference_categ = fields.Many2one(
'account.account', string="Price Difference Account",
company_dependent=True,
help="This account will be used to value price difference between purchase price and accounting cost.")
class ProductSupplierinfo(models.Model):
_inherit = "product.supplierinfo"
@api.onchange('name')
def _onchange_name(self):
self.currency_id = self.name.property_purchase_currency_id.id or self.env.company.currency_id.id
class ProductPackaging(models.Model):
_inherit = 'product.packaging'
purchase = fields.Boolean("Purchase", default=True, help="If true, the packaging can be used for purchase orders")
| 46.127451
| 4,705
|
2,815
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
lock_confirmed_po = fields.Boolean("Lock Confirmed Orders", default=lambda self: self.env.company.po_lock == 'lock')
po_lock = fields.Selection(related='company_id.po_lock', string="Purchase Order Modification *", readonly=False)
po_order_approval = fields.Boolean("Purchase Order Approval", default=lambda self: self.env.company.po_double_validation == 'two_step')
po_double_validation = fields.Selection(related='company_id.po_double_validation', string="Levels of Approvals *", readonly=False)
po_double_validation_amount = fields.Monetary(related='company_id.po_double_validation_amount', string="Minimum Amount", currency_field='company_currency_id', readonly=False)
company_currency_id = fields.Many2one('res.currency', related='company_id.currency_id', string="Company Currency", readonly=True,
help='Utility field to express amount currency')
default_purchase_method = fields.Selection([
('purchase', 'Ordered quantities'),
('receive', 'Received quantities'),
], string="Bill Control", default_model="product.template",
help="This default value is applied to any new product created. "
"This can be changed in the product detail form.", default="receive")
group_warning_purchase = fields.Boolean("Purchase Warnings", implied_group='purchase.group_warning_purchase')
module_account_3way_match = fields.Boolean("3-way matching: purchases, receptions and bills")
module_purchase_requisition = fields.Boolean("Purchase Agreements")
module_purchase_product_matrix = fields.Boolean("Purchase Grid Entry")
po_lead = fields.Float(related='company_id.po_lead', readonly=False)
use_po_lead = fields.Boolean(
string="Security Lead Time for Purchase",
config_parameter='purchase.use_po_lead',
help="Margin of error for vendor lead times. When the system generates Purchase Orders for reordering products,they will be scheduled that many days earlier to cope with unexpected vendor delays.")
group_send_reminder = fields.Boolean("Receipt Reminder", implied_group='purchase.group_send_reminder', default=True,
help="Allow automatically send email to remind your vendor the receipt date")
@api.onchange('use_po_lead')
def _onchange_use_po_lead(self):
if not self.use_po_lead:
self.po_lead = 0.0
def set_values(self):
super(ResConfigSettings, self).set_values()
self.po_lock = 'lock' if self.lock_confirmed_po else 'edit'
self.po_double_validation = 'two_step' if self.po_order_approval else 'one_step'
| 63.977273
| 2,815
|
1,265
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
class AccountAnalyticAccount(models.Model):
_inherit = 'account.analytic.account'
purchase_order_count = fields.Integer("Purchase Order Count", compute='_compute_purchase_order_count')
@api.depends('line_ids')
def _compute_purchase_order_count(self):
for account in self:
account.purchase_order_count = self.env['purchase.order'].search_count([
('order_line.invoice_lines.analytic_line_ids.account_id', '=', account.id)
])
def action_view_purchase_orders(self):
self.ensure_one()
purchase_orders = self.env['purchase.order'].search([
('order_line.invoice_lines.analytic_line_ids.account_id', '=', self.id)
])
result = {
"type": "ir.actions.act_window",
"res_model": "purchase.order",
"domain": [['id', 'in', purchase_orders.ids]],
"name": _("Purchase Orders"),
'view_mode': 'tree,form',
}
if len(purchase_orders) == 1:
result['view_mode'] = 'form'
result['res_id'] = purchase_orders.id
return result
| 37.205882
| 1,265
|
3,332
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.addons.base.models.res_partner import WARNING_MESSAGE, WARNING_HELP
class res_partner(models.Model):
_name = 'res.partner'
_inherit = 'res.partner'
def _compute_purchase_order_count(self):
# retrieve all children partners and prefetch 'parent_id' on them
all_partners = self.with_context(active_test=False).search([('id', 'child_of', self.ids)])
all_partners.read(['parent_id'])
purchase_order_groups = self.env['purchase.order'].read_group(
domain=[('partner_id', 'in', all_partners.ids)],
fields=['partner_id'], groupby=['partner_id']
)
partners = self.browse()
for group in purchase_order_groups:
partner = self.browse(group['partner_id'][0])
while partner:
if partner in self:
partner.purchase_order_count += group['partner_id_count']
partners |= partner
partner = partner.parent_id
(self - partners).purchase_order_count = 0
def _compute_supplier_invoice_count(self):
# retrieve all children partners and prefetch 'parent_id' on them
all_partners = self.with_context(active_test=False).search([('id', 'child_of', self.ids)])
all_partners.read(['parent_id'])
supplier_invoice_groups = self.env['account.move'].read_group(
domain=[('partner_id', 'in', all_partners.ids),
('move_type', 'in', ('in_invoice', 'in_refund'))],
fields=['partner_id'], groupby=['partner_id']
)
partners = self.browse()
for group in supplier_invoice_groups:
partner = self.browse(group['partner_id'][0])
while partner:
if partner in self:
partner.supplier_invoice_count += group['partner_id_count']
partners |= partner
partner = partner.parent_id
(self - partners).supplier_invoice_count = 0
@api.model
def _commercial_fields(self):
return super(res_partner, self)._commercial_fields()
property_purchase_currency_id = fields.Many2one(
'res.currency', string="Supplier Currency", company_dependent=True,
help="This currency will be used, instead of the default one, for purchases from the current partner")
purchase_order_count = fields.Integer(compute='_compute_purchase_order_count', string='Purchase Order Count')
supplier_invoice_count = fields.Integer(compute='_compute_supplier_invoice_count', string='# Vendor Bills')
purchase_warn = fields.Selection(WARNING_MESSAGE, 'Purchase Order', help=WARNING_HELP, default="no-message")
purchase_warn_msg = fields.Text('Message for Purchase Order')
receipt_reminder_email = fields.Boolean('Receipt Reminder', default=False, company_dependent=True,
help="Automatically send a confirmation email to the vendor X days before the expected receipt date, asking him to confirm the exact date.")
reminder_date_before_receipt = fields.Integer('Days Before Receipt', default=1, company_dependent=True,
help="Number of days to send reminder email before the promised receipt date")
| 50.484848
| 3,332
|
11,509
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
#
# Please note that these reports are not multi-currency !!!
#
import re
from odoo import api, fields, models, tools
from odoo.exceptions import UserError
from odoo.osv.expression import AND, expression
class PurchaseReport(models.Model):
_name = "purchase.report"
_description = "Purchase Report"
_auto = False
_order = 'date_order desc, price_total desc'
date_order = fields.Datetime('Order Date', readonly=True, help="Depicts the date when the Quotation should be validated and converted into a purchase order.")
state = fields.Selection([
('draft', 'Draft RFQ'),
('sent', 'RFQ Sent'),
('to approve', 'To Approve'),
('purchase', 'Purchase Order'),
('done', 'Done'),
('cancel', 'Cancelled')
], 'Status', readonly=True)
product_id = fields.Many2one('product.product', 'Product', readonly=True)
partner_id = fields.Many2one('res.partner', 'Vendor', readonly=True)
date_approve = fields.Datetime('Confirmation Date', readonly=True)
product_uom = fields.Many2one('uom.uom', 'Reference Unit of Measure', required=True)
company_id = fields.Many2one('res.company', 'Company', readonly=True)
currency_id = fields.Many2one('res.currency', 'Currency', readonly=True)
user_id = fields.Many2one('res.users', 'Purchase Representative', readonly=True)
delay = fields.Float('Days to Confirm', digits=(16, 2), readonly=True, group_operator='avg', help="Amount of time between purchase approval and order by date.")
delay_pass = fields.Float('Days to Receive', digits=(16, 2), readonly=True, group_operator='avg',
help="Amount of time between date planned and order by date for each purchase order line.")
avg_days_to_purchase = fields.Float(
'Average Days to Purchase', digits=(16, 2), readonly=True, store=False, # needs store=False to prevent showing up as a 'measure' option
help="Amount of time between purchase approval and document creation date. Due to a hack needed to calculate this, \
every record will show the same average value, therefore only use this as an aggregated value with group_operator=avg")
price_total = fields.Float('Total', readonly=True)
price_average = fields.Float('Average Cost', readonly=True, group_operator="avg")
nbr_lines = fields.Integer('# of Lines', readonly=True)
category_id = fields.Many2one('product.category', 'Product Category', readonly=True)
product_tmpl_id = fields.Many2one('product.template', 'Product Template', readonly=True)
country_id = fields.Many2one('res.country', 'Partner Country', readonly=True)
fiscal_position_id = fields.Many2one('account.fiscal.position', string='Fiscal Position', readonly=True)
account_analytic_id = fields.Many2one('account.analytic.account', 'Analytic Account', readonly=True)
commercial_partner_id = fields.Many2one('res.partner', 'Commercial Entity', readonly=True)
weight = fields.Float('Gross Weight', readonly=True)
volume = fields.Float('Volume', readonly=True)
order_id = fields.Many2one('purchase.order', 'Order', readonly=True)
untaxed_total = fields.Float('Untaxed Total', readonly=True)
qty_ordered = fields.Float('Qty Ordered', readonly=True)
qty_received = fields.Float('Qty Received', readonly=True)
qty_billed = fields.Float('Qty Billed', readonly=True)
qty_to_be_billed = fields.Float('Qty to be Billed', readonly=True)
@property
def _table_query(self):
''' Report needs to be dynamic to take into account multi-company selected + multi-currency rates '''
return '%s %s %s %s' % (self._select(), self._from(), self._where(), self._group_by())
def _select(self):
select_str = """
SELECT
po.id as order_id,
min(l.id) as id,
po.date_order as date_order,
po.state,
po.date_approve,
po.dest_address_id,
po.partner_id as partner_id,
po.user_id as user_id,
po.company_id as company_id,
po.fiscal_position_id as fiscal_position_id,
l.product_id,
p.product_tmpl_id,
t.categ_id as category_id,
po.currency_id,
t.uom_id as product_uom,
extract(epoch from age(po.date_approve,po.date_order))/(24*60*60)::decimal(16,2) as delay,
extract(epoch from age(l.date_planned,po.date_order))/(24*60*60)::decimal(16,2) as delay_pass,
count(*) as nbr_lines,
sum(l.price_total / COALESCE(po.currency_rate, 1.0))::decimal(16,2) * currency_table.rate as price_total,
(sum(l.product_qty * l.price_unit / COALESCE(po.currency_rate, 1.0))/NULLIF(sum(l.product_qty/line_uom.factor*product_uom.factor),0.0))::decimal(16,2) * currency_table.rate as price_average,
partner.country_id as country_id,
partner.commercial_partner_id as commercial_partner_id,
analytic_account.id as account_analytic_id,
sum(p.weight * l.product_qty/line_uom.factor*product_uom.factor) as weight,
sum(p.volume * l.product_qty/line_uom.factor*product_uom.factor) as volume,
sum(l.price_subtotal / COALESCE(po.currency_rate, 1.0))::decimal(16,2) * currency_table.rate as untaxed_total,
sum(l.product_qty / line_uom.factor * product_uom.factor) as qty_ordered,
sum(l.qty_received / line_uom.factor * product_uom.factor) as qty_received,
sum(l.qty_invoiced / line_uom.factor * product_uom.factor) as qty_billed,
case when t.purchase_method = 'purchase'
then sum(l.product_qty / line_uom.factor * product_uom.factor) - sum(l.qty_invoiced / line_uom.factor * product_uom.factor)
else sum(l.qty_received / line_uom.factor * product_uom.factor) - sum(l.qty_invoiced / line_uom.factor * product_uom.factor)
end as qty_to_be_billed
"""
return select_str
def _from(self):
from_str = """
FROM
purchase_order_line l
join purchase_order po on (l.order_id=po.id)
join res_partner partner on po.partner_id = partner.id
left join product_product p on (l.product_id=p.id)
left join product_template t on (p.product_tmpl_id=t.id)
left join uom_uom line_uom on (line_uom.id=l.product_uom)
left join uom_uom product_uom on (product_uom.id=t.uom_id)
left join account_analytic_account analytic_account on (l.account_analytic_id = analytic_account.id)
left join {currency_table} ON currency_table.company_id = po.company_id
""".format(
currency_table=self.env['res.currency']._get_query_currency_table({'multi_company': True, 'date': {'date_to': fields.Date.today()}}),
)
return from_str
def _where(self):
return """
WHERE
l.display_type IS NULL
"""
def _group_by(self):
group_by_str = """
GROUP BY
po.company_id,
po.user_id,
po.partner_id,
line_uom.factor,
po.currency_id,
l.price_unit,
po.date_approve,
l.date_planned,
l.product_uom,
po.dest_address_id,
po.fiscal_position_id,
l.product_id,
p.product_tmpl_id,
t.categ_id,
po.date_order,
po.state,
line_uom.uom_type,
line_uom.category_id,
t.uom_id,
t.purchase_method,
line_uom.id,
product_uom.factor,
partner.country_id,
partner.commercial_partner_id,
analytic_account.id,
po.id,
currency_table.rate
"""
return group_by_str
@api.model
def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
""" This is a hack to allow us to correctly calculate the average of PO specific date values since
the normal report query result will duplicate PO values across its PO lines during joins and
lead to incorrect aggregation values.
Only the AVG operator is supported for avg_days_to_purchase.
"""
avg_days_to_purchase = next((field for field in fields if re.search(r'\bavg_days_to_purchase\b', field)), False)
if avg_days_to_purchase:
fields.remove(avg_days_to_purchase)
if any(field.split(':')[1].split('(')[0] != 'avg' for field in [avg_days_to_purchase] if field):
raise UserError("Value: 'avg_days_to_purchase' should only be used to show an average. If you are seeing this message then it is being accessed incorrectly.")
if 'price_average:avg' in fields:
fields.extend(['aggregated_qty_ordered:array_agg(qty_ordered)'])
fields.extend(['aggregated_price_average:array_agg(price_average)'])
res = []
if fields:
res = super(PurchaseReport, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)
if 'price_average:avg' in fields:
qties = 'aggregated_qty_ordered'
special_field = 'aggregated_price_average'
for data in res:
if data[special_field] and data[qties]:
total_unit_cost = sum(float(value) * float(qty) for value, qty in zip(data[special_field], data[qties]) if qty and value)
total_qty_ordered = sum(float(qty) for qty in data[qties] if qty)
data['price_average'] = (total_unit_cost / total_qty_ordered) if total_qty_ordered else 0
del data[special_field]
del data[qties]
if not res and avg_days_to_purchase:
res = [{}]
if avg_days_to_purchase:
self.check_access_rights('read')
query = """ SELECT AVG(days_to_purchase.po_days_to_purchase)::decimal(16,2) AS avg_days_to_purchase
FROM (
SELECT extract(epoch from age(po.date_approve,po.create_date))/(24*60*60) AS po_days_to_purchase
FROM purchase_order po
WHERE po.id IN (
SELECT "purchase_report"."order_id" FROM %s WHERE %s)
) AS days_to_purchase
"""
subdomain = AND([domain, [('company_id', '=', self.env.company.id), ('date_approve', '!=', False)]])
subtables, subwhere, subparams = expression(subdomain, self).query.get_sql()
self.env.cr.execute(query % (subtables, subwhere), subparams)
res[0].update({
'__count': 1,
avg_days_to_purchase.split(':')[0]: self.env.cr.fetchall()[0][0],
})
return res
| 53.036866
| 11,509
|
2,450
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, tools
from odoo.tools import formatLang
class PurchaseBillUnion(models.Model):
_name = 'purchase.bill.union'
_auto = False
_description = 'Purchases & Bills Union'
_order = "date desc, name desc"
name = fields.Char(string='Reference', readonly=True)
reference = fields.Char(string='Source', readonly=True)
partner_id = fields.Many2one('res.partner', string='Vendor', readonly=True)
date = fields.Date(string='Date', readonly=True)
amount = fields.Float(string='Amount', readonly=True)
currency_id = fields.Many2one('res.currency', string='Currency', readonly=True)
company_id = fields.Many2one('res.company', 'Company', readonly=True)
vendor_bill_id = fields.Many2one('account.move', string='Vendor Bill', readonly=True)
purchase_order_id = fields.Many2one('purchase.order', string='Purchase Order', readonly=True)
def init(self):
tools.drop_view_if_exists(self.env.cr, 'purchase_bill_union')
self.env.cr.execute("""
CREATE OR REPLACE VIEW purchase_bill_union AS (
SELECT
id, name, ref as reference, partner_id, date, amount_untaxed as amount, currency_id, company_id,
id as vendor_bill_id, NULL as purchase_order_id
FROM account_move
WHERE
move_type='in_invoice' and state = 'posted'
UNION
SELECT
-id, name, partner_ref as reference, partner_id, date_order::date as date, amount_untaxed as amount, currency_id, company_id,
NULL as vendor_bill_id, id as purchase_order_id
FROM purchase_order
WHERE
state in ('purchase', 'done') AND
invoice_status in ('to invoice', 'no')
)""")
def name_get(self):
result = []
for doc in self:
name = doc.name or ''
if doc.reference:
name += ' - ' + doc.reference
amount = doc.amount
if doc.purchase_order_id and doc.purchase_order_id.invoice_status == 'no':
amount = 0.0
name += ': ' + formatLang(self.env, amount, monetary=True, currency_obj=doc.currency_id)
result.append((doc.id, name))
return result
| 45.37037
| 2,450
|
8,006
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
from collections import OrderedDict
from datetime import datetime
from odoo import http
from odoo.exceptions import AccessError, MissingError
from odoo.http import request, Response
from odoo.tools import image_process
from odoo.tools.translate import _
from odoo.addons.portal.controllers import portal
from odoo.addons.portal.controllers.portal import pager as portal_pager
class CustomerPortal(portal.CustomerPortal):
def _prepare_home_portal_values(self, counters):
values = super()._prepare_home_portal_values(counters)
PurchaseOrder = request.env['purchase.order']
if 'rfq_count' in counters:
values['rfq_count'] = PurchaseOrder.search_count([
('state', 'in', ['sent'])
]) if PurchaseOrder.check_access_rights('read', raise_exception=False) else 0
if 'purchase_count' in counters:
values['purchase_count'] = PurchaseOrder.search_count([
('state', 'in', ['purchase', 'done', 'cancel'])
]) if PurchaseOrder.check_access_rights('read', raise_exception=False) else 0
return values
def _render_portal(self, template, page, date_begin, date_end, sortby, filterby, domain, searchbar_filters, default_filter, url, history, page_name, key):
values = self._prepare_portal_layout_values()
PurchaseOrder = request.env['purchase.order']
if date_begin and date_end:
domain += [('create_date', '>', date_begin), ('create_date', '<=', date_end)]
searchbar_sortings = {
'date': {'label': _('Newest'), 'order': 'create_date desc, id desc'},
'name': {'label': _('Name'), 'order': 'name asc, id asc'},
'amount_total': {'label': _('Total'), 'order': 'amount_total desc, id desc'},
}
# default sort
if not sortby:
sortby = 'date'
order = searchbar_sortings[sortby]['order']
if searchbar_filters:
# default filter
if not filterby:
filterby = default_filter
domain += searchbar_filters[filterby]['domain']
# count for pager
count = PurchaseOrder.search_count(domain)
# make pager
pager = portal_pager(
url=url,
url_args={'date_begin': date_begin, 'date_end': date_end, 'sortby': sortby, 'filterby': filterby},
total=count,
page=page,
step=self._items_per_page
)
# search the purchase orders to display, according to the pager data
orders = PurchaseOrder.search(
domain,
order=order,
limit=self._items_per_page,
offset=pager['offset']
)
request.session[history] = orders.ids[:100]
values.update({
'date': date_begin,
key: orders,
'page_name': page_name,
'pager': pager,
'searchbar_sortings': searchbar_sortings,
'sortby': sortby,
'searchbar_filters': OrderedDict(sorted(searchbar_filters.items())),
'filterby': filterby,
'default_url': url,
})
return request.render(template, values)
def _purchase_order_get_page_view_values(self, order, access_token, **kwargs):
#
def resize_to_48(b64source):
if not b64source:
b64source = base64.b64encode(request.env['ir.http']._placeholder())
return image_process(b64source, size=(48, 48))
values = {
'order': order,
'resize_to_48': resize_to_48,
'report_type': 'html',
}
if order.state in ('sent'):
history = 'my_rfqs_history'
else:
history = 'my_purchases_history'
return self._get_page_view_values(order, access_token, values, history, False, **kwargs)
@http.route(['/my/rfq', '/my/rfq/page/<int:page>'], type='http', auth="user", website=True)
def portal_my_requests_for_quotation(self, page=1, date_begin=None, date_end=None, sortby=None, filterby=None, **kw):
return self._render_portal(
"purchase.portal_my_purchase_rfqs",
page, date_begin, date_end, sortby, filterby,
[('state', '=', 'sent')],
{},
None,
"/my/rfq",
'my_rfqs_history',
'rfq',
'rfqs'
)
@http.route(['/my/purchase', '/my/purchase/page/<int:page>'], type='http', auth="user", website=True)
def portal_my_purchase_orders(self, page=1, date_begin=None, date_end=None, sortby=None, filterby=None, **kw):
return self._render_portal(
"purchase.portal_my_purchase_orders",
page, date_begin, date_end, sortby, filterby,
[],
{
'all': {'label': _('All'), 'domain': [('state', 'in', ['purchase', 'done', 'cancel'])]},
'purchase': {'label': _('Purchase Order'), 'domain': [('state', '=', 'purchase')]},
'cancel': {'label': _('Cancelled'), 'domain': [('state', '=', 'cancel')]},
'done': {'label': _('Locked'), 'domain': [('state', '=', 'done')]},
},
'all',
"/my/purchase",
'my_purchases_history',
'purchase',
'orders'
)
@http.route(['/my/purchase/<int:order_id>'], type='http', auth="public", website=True)
def portal_my_purchase_order(self, order_id=None, access_token=None, **kw):
try:
order_sudo = self._document_check_access('purchase.order', order_id, access_token=access_token)
except (AccessError, MissingError):
return request.redirect('/my')
report_type = kw.get('report_type')
if report_type in ('html', 'pdf', 'text'):
return self._show_report(model=order_sudo, report_type=report_type, report_ref='purchase.action_report_purchase_order', download=kw.get('download'))
confirm_type = kw.get('confirm')
if confirm_type == 'reminder':
order_sudo.confirm_reminder_mail(kw.get('confirmed_date'))
if confirm_type == 'reception':
order_sudo._confirm_reception_mail()
values = self._purchase_order_get_page_view_values(order_sudo, access_token, **kw)
update_date = kw.get('update')
if order_sudo.company_id:
values['res_company'] = order_sudo.company_id
if update_date == 'True':
return request.render("purchase.portal_my_purchase_order_update_date", values)
return request.render("purchase.portal_my_purchase_order", values)
@http.route(['/my/purchase/<int:order_id>/update'], type='http', methods=['POST'], auth="public", website=True)
def portal_my_purchase_order_update_dates(self, order_id=None, access_token=None, **kw):
"""User update scheduled date on purchase order line.
"""
try:
order_sudo = self._document_check_access('purchase.order', order_id, access_token=access_token)
except (AccessError, MissingError):
return request.redirect('/my')
updated_dates = []
for id_str, date_str in kw.items():
try:
line_id = int(id_str)
except ValueError:
return request.redirect(order_sudo.get_portal_url())
line = order_sudo.order_line.filtered(lambda l: l.id == line_id)
if not line:
return request.redirect(order_sudo.get_portal_url())
try:
updated_date = line._convert_to_middle_of_day(datetime.strptime(date_str, '%Y-%m-%d'))
except ValueError:
continue
updated_dates.append((line, updated_date))
if updated_dates:
order_sudo._update_date_planned_for_lines(updated_dates)
return Response(status=204)
| 41.481865
| 8,006
|
1,193
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "Gift Card for point of sales module",
'summary': "Use gift card in your sales orders",
'description': """Integrate gift card mechanism in sales orders.""",
'category': 'Sales/Sales',
'version': '1.0',
'depends': ['gift_card', 'point_of_sale'],
'auto_install': True,
'data': [
'data/gift_card_data.xml',
'views/gift_card_views.xml',
'views/res_config_settings_views.xml',
'views/pos_config_views.xml',
'security/ir.model.access.csv',
],
'assets': {
'point_of_sale.assets': [
'pos_gift_card/static/src/css/giftCard.css',
'pos_gift_card/static/src/js/models.js',
'pos_gift_card/static/src/js/GiftCardButton.js',
'pos_gift_card/static/src/js/GiftCardPopup.js',
'pos_gift_card/static/src/js/PaymentScreen.js',
],
'web.assets_qweb': [
'pos_gift_card/static/src/xml/**/*',
],
'web.assets_tests': [
'pos_gift_card/static/src/js/tours/**/*',
],
},
'license': 'LGPL-3',
}
| 34.085714
| 1,193
|
2,116
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.point_of_sale.tests.test_frontend import TestPointOfSaleHttpCommon
from odoo.tests import Form, tagged
@tagged("post_install", "-at_install")
class TestGiftCardPromotion(TestPointOfSaleHttpCommon):
def test_gift_card_promotion(self):
"""PoS Coupon Basic Tour"""
self.product1 = self.env['product.product'].create({
'name': 'product1',
'type': 'product',
'list_price': 10,
'available_in_pos': True,
'taxes_id': False,
})
self.tax = self.env['account.tax'].create({
'name': 'Tax 0%',
'amount': 0,
'amount_type': 'percent',
})
self.gift_card_product = self.env['product.product'].create({
'name': 'Gift Card',
'type': 'service',
'taxes_id': [(6, 0, self.tax.ids)],
'available_in_pos': True,
})
self.auto_promo_program_current = self.env["coupon.program"].create(
{
"name": "Auto Promo Program - Cheapest Product",
"program_type": "promotion_program",
"promo_code_usage": "no_code_needed",
"discount_apply_on": "on_order",
"reward_type": "discount",
"discount_percentage": 10,
}
)
self.gift_card = self.env["gift.card"].create(
{
"code": "1234",
"initial_amount": 100,
})
with Form(self.main_pos_config) as pos_config:
pos_config.use_gift_card = True
pos_config.use_coupon_programs = True
pos_config.promo_program_ids.add(self.auto_promo_program_current)
pos_config.gift_card_product_id = self.gift_card_product
self.main_pos_config.open_session_cb(check_coa=False)
self.start_tour(
"/pos/web?config_id=%d" % self.main_pos_config.id,
"PosGiftCardTour",
login="accountman",
)
| 35.266667
| 2,116
|
1,155
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class PosConfig(models.Model):
_inherit = "pos.config"
use_gift_card = fields.Boolean(string="Gift Card")
gift_card_product_id = fields.Many2one(
"product.product",
string="Gift Card Product",
help="This product is used as reference on customer receipts.",
)
gift_card_settings = fields.Selection(
[
("create_set", "Generate a new barcode and set a price"),
("scan_set", "Scan an existing barcode and set a price"),
("scan_use", "Scan an existing barcode with an existing price"),
],
string="Gift Cards settings",
default="create_set",
help="Defines the way you want to set your gift cards.",
)
@api.onchange("use_gift_card")
def _onchange_giftproduct(self):
if self.use_gift_card:
self.gift_card_product_id = self.env.ref(
"gift_card.pay_with_gift_card_product", False
)
else:
self.gift_card_product_id = False
| 32.083333
| 1,155
|
1,036
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class PosOrderLine(models.Model):
_inherit = "pos.order.line"
generated_gift_card_ids = fields.One2many(
"gift.card", "buy_pos_order_line_id", string="Bought Gift Card"
)
gift_card_id = fields.Many2one(
"gift.card", help="Deducted from this Gift Card", copy=False
)
def _is_not_sellable_line(self):
return self.gift_card_id or super()._is_not_sellable_line()
def _create_gift_cards(self):
return self.env["gift.card"].create(
[self._build_gift_card() for _ in range(int(self.qty))]
)
def _build_gift_card(self):
return {
"initial_amount": self.order_id.currency_id._convert(
self.price_unit,
self.company_id.currency_id,
self.company_id,
fields.Date.today(),
),
"buy_pos_order_line_id": self.id,
}
| 30.470588
| 1,036
|
339
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields
class BarcodeRule(models.Model):
_inherit = 'barcode.rule'
type = fields.Selection(selection_add=[
('gift_card', 'Gift Card'),
], ondelete={
'gift_card': 'set default',
})
| 24.214286
| 339
|
1,576
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class GiftCard(models.Model):
_inherit = "gift.card"
buy_pos_order_line_id = fields.Many2one(
"pos.order.line",
copy=False,
readonly=True,
help="Pos Order line where this gift card has been bought.",
)
redeem_pos_order_line_ids = fields.One2many(
"pos.order.line", "gift_card_id", string="Pos Redeems"
)
@api.depends("redeem_pos_order_line_ids")
def _compute_balance(self):
super()._compute_balance()
for record in self:
confirmed_line = record.redeem_pos_order_line_ids.sudo().filtered(
lambda l: l.order_id.state in ('paid', 'done', 'invoiced')
)
balance = record.balance
if confirmed_line:
balance -= sum(
confirmed_line.mapped(
lambda line: line.currency_id._convert(
line.price_unit,
record.currency_id,
record.env.company,
line.create_date,
)
* -1
)
)
record.balance = balance
def can_be_used_in_pos(self):
# expired state are computed once a day, so can be not synchro
return self.state == 'valid' and self.balance > 0 and (not self.expired_date or self.expired_date >= fields.Date.today())
| 35.818182
| 1,576
|
2,765
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
import base64
class PosOrder(models.Model):
_inherit = "pos.order"
gift_card_count = fields.Integer(compute="_compute_gift_card_count")
@api.depends("lines.generated_gift_card_ids")
def _compute_gift_card_count(self):
for record in self:
record.gift_card_count = len(record.lines.mapped("generated_gift_card_ids"))
@api.model
def create_from_ui(self, orders, draft=False):
order_ids = super(PosOrder, self).create_from_ui(orders, draft)
for order in self.sudo().browse([o["id"] for o in order_ids]):
gift_card_config = order.config_id.gift_card_settings
for line in order.lines:
if line.product_id.id == order.config_id.gift_card_product_id.id:
if not line.gift_card_id:
if gift_card_config == "create_set":
new_card = line._create_gift_cards()
new_card.partner_id = order.partner_id or False
line.generated_gift_card_ids = new_card
else:
gift_card = self.env["gift.card"].search(
[("id", "=", line.generated_gift_card_ids.id)]
)
gift_card.buy_pos_order_line_id = line.id
gift_card.expired_date = fields.Date.add(
fields.Date.today(), years=1
)
gift_card.partner_id = order.partner_id or False
if gift_card_config == "scan_set":
gift_card.initial_amount = line.price_unit
return order_ids
def get_new_card_ids(self):
return self.lines.mapped("generated_gift_card_ids").ids
def _add_mail_attachment(self, name, ticket):
attachment = super()._add_mail_attachment(name, ticket)
if self.config_id.use_gift_card and len(self.get_new_card_ids()) > 0:
report = self.env.ref('pos_gift_card.gift_card_report_pdf')._render_qweb_pdf(self.get_new_card_ids())
filename = name + '.pdf'
gift_card = self.env['ir.attachment'].create({
'name': filename,
'type': 'binary',
'datas': base64.b64encode(report[0]),
'store_fname': filename,
'res_model': 'pos.order',
'res_id': self.ids[0],
'mimetype': 'application/x-pdf'
})
attachment += [(4, gift_card.id)]
return attachment
| 43.203125
| 2,765
|
1,007
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Test Full Event Flow',
'version': '1.0',
'category': 'Hidden/Tests',
'description': """
This module will test the main event flows of Odoo, both frontend and backend.
It installs sale capabilities, front-end flow, eCommerce, questions and
automatic lead generation, full Online support, ...
""",
'depends': [
'event',
'event_booth',
'event_crm',
'event_sale',
'website_event_booth_sale_exhibitor',
'website_event_crm_questions',
'website_event_exhibitor',
'website_event_questions',
'website_event_meet',
'website_event_sale',
'website_event_track',
'website_event_track_live',
'website_event_track_quiz',
],
'installable': True,
'assets': {
'web.assets_tests': [
'test_event_full/static/**/*',
],
},
'license': 'LGPL-3',
}
| 28.771429
| 1,007
|
11,224
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, timedelta, time
from odoo.addons.base.tests.common import HttpCaseWithUserDemo, HttpCaseWithUserPortal
from odoo.addons.event_crm.tests.common import TestEventCrmCommon
from odoo.addons.sales_team.tests.common import TestSalesCommon
from odoo.addons.website.tests.test_website_visitor import MockVisitor
from odoo.addons.website_event.tests.common import EventDtPatcher
class TestEventFullCommon(TestEventCrmCommon, TestSalesCommon, EventDtPatcher, MockVisitor):
@classmethod
def setUpClass(cls):
super(TestEventFullCommon, cls).setUpClass()
# ------------------------------------------------------------
# TICKET INFORMATIONS
# ------------------------------------------------------------
cls.event_product = cls.env['product.product'].create({
'name': 'Test Registration Product',
'description_sale': 'Mighty Description',
'list_price': 10,
'standard_price': 30.0,
'detailed_type': 'event',
})
cls.website = cls.env['website'].search([
('company_id', '=', cls.env.user.company_id.id)
], limit=1)
cls.event_0.write({
# event if 8-18 in Europe/Brussels (DST) (first day: begins at 9, last day: ends at 15)
'date_begin': datetime.combine(cls.reference_now, time(7, 0)) - timedelta(days=1),
'date_end': datetime.combine(cls.reference_now, time(13, 0)) + timedelta(days=1),
# ticket informations
'event_ticket_ids': [
(5, 0),
(0, 0, {
'name': 'First Ticket',
'product_id': cls.event_product.id,
'seats_max': 30,
}), (0, 0, {
'name': 'Second Ticket',
'product_id': cls.event_product.id,
})
],
})
# make a SO for a customer, selling some tickets
cls.customer_so = cls.env['sale.order'].with_user(cls.user_sales_salesman).create({
'partner_id': cls.event_customer.id,
})
# ------------------------------------------------------------
# QUESTIONS
# ------------------------------------------------------------
cls.event_question_1 = cls.env['event.question'].create({
'title': 'Question1',
'question_type': 'simple_choice',
'event_id': cls.event_0.id,
'once_per_order': False,
'answer_ids': [
(0, 0, {'name': 'Q1-Answer1'}),
(0, 0, {'name': 'Q1-Answer2'})
],
})
cls.event_question_2 = cls.env['event.question'].create({
'title': 'Question2',
'question_type': 'simple_choice',
'event_id': cls.event_0.id,
'once_per_order': True,
'answer_ids': [
(0, 0, {'name': 'Q2-Answer1'}),
(0, 0, {'name': 'Q2-Answer2'})
],
})
cls.event_question_3 = cls.env['event.question'].create({
'title': 'Question3',
'question_type': 'text_box',
'event_id': cls.event_0.id,
'once_per_order': True,
})
# ------------------------------------------------------------
# DATA MARSHMALLING
# ------------------------------------------------------------
cls.website_customer_data = [{
'name': 'My Customer %02d' % x,
'partner_id': cls.env.ref('base.public_partner').id,
'email': 'email.%02d@test.example.com' % x,
'phone': '04560000%02d' % x,
'registration_answer_ids': [
(0, 0, {
'question_id': cls.event_question_1.id,
'value_answer_id': cls.event_question_1.answer_ids[(x % 2)].id,
}), (0, 0, {
'question_id': cls.event_question_2.id,
'value_answer_id': cls.event_question_2.answer_ids[(x % 2)].id,
}), (0, 0, {
'question_id': cls.event_question_3.id,
'value_text_box': 'CustomerAnswer%s' % x,
})
],
} for x in range(0, 4)]
def assertLeadConvertion(self, rule, registrations, partner=None, **expected):
super(TestEventFullCommon, self).assertLeadConvertion(rule, registrations, partner=partner, **expected)
lead = self.env['crm.lead'].sudo().search([
('registration_ids', 'in', registrations.ids),
('event_lead_rule_id', '=', rule.id)
])
for registration in registrations:
if not registration.registration_answer_ids:
continue
for answer in registration.registration_answer_ids:
self.assertIn(answer.question_id.title, lead.description)
if answer.question_type == 'simple_choice':
self.assertIn(answer.value_answer_id.name, lead.description)
else:
self.assertIn(answer.value_text_box, lead.description) # better: check multi line
class TestWEventCommon(HttpCaseWithUserDemo, HttpCaseWithUserPortal, EventDtPatcher, MockVisitor):
def setUp(self):
super(TestWEventCommon, self).setUp()
self.event_product = self.env['product.product'].create({
'name': 'Test Event Registration',
'default_code': 'EVENT_REG',
'description_sale': 'Mighty Description',
'list_price': 10,
'standard_price': 30.0,
'detailed_type': 'event',
})
self.event_tag_category_1 = self.env['event.tag.category'].create({
'name': 'Type',
'sequence': 2,
})
self.event_tag_category_1_tag_1 = self.env['event.tag'].create({
'name': 'Online',
'sequence': 10,
'category_id': self.event_tag_category_1.id,
'color': 8,
})
self.env['event.event'].search(
[('name', 'like', '%Online Reveal%')]
).write(
{'name': 'Do not click on me'}
)
self.event = self.env['event.event'].create({
'name': 'Online Reveal TestEvent',
'auto_confirm': True,
'stage_id': self.env.ref('event.event_stage_booked').id,
'address_id': False,
'user_id': self.user_demo.id,
'tag_ids': [(4, self.event_tag_category_1_tag_1.id)],
# event if 8-18 in Europe/Brussels (DST) (first day: begins at 7, last day: ends at 17)
'date_tz': 'Europe/Brussels',
'date_begin': datetime.combine(self.reference_now, time(5, 0)) - timedelta(days=1),
'date_end': datetime.combine(self.reference_now, time(15, 0)) + timedelta(days=1),
# ticket informations
'event_ticket_ids': [
(0, 0, {
'name': 'Standard',
'product_id': self.event_product.id,
'price': 0,
}), (0, 0, {
'name': 'VIP',
'product_id': self.event_product.id,
'seats_max': 10,
})
],
# activate menus
'is_published': True,
'website_menu': True,
'website_track': True,
'website_track_proposal': True,
'exhibitor_menu': True,
'community_menu': True,
})
self.event_customer = self.env['res.partner'].create({
'name': 'Constantin Customer',
'email': 'constantin@test.example.com',
'country_id': self.env.ref('base.be').id,
'phone': '0485112233',
'mobile': False,
})
self.event_speaker = self.env['res.partner'].create({
'name': 'Brandon Freeman',
'email': 'brandon.freeman55@example.com',
'phone': '(355)-687-3262',
})
# ------------------------------------------------------------
# QUESTIONS
# ------------------------------------------------------------
self.event_question_1 = self.env['event.question'].create({
'title': 'Which field are you working in',
'question_type': 'simple_choice',
'event_id': self.event.id,
'once_per_order': False,
'answer_ids': [
(0, 0, {'name': 'Consumers'}),
(0, 0, {'name': 'Sales'}),
(0, 0, {'name': 'Research'}),
],
})
self.event_question_2 = self.env['event.question'].create({
'title': 'How did you hear about us ?',
'question_type': 'text_box',
'event_id': self.event.id,
'once_per_order': True,
})
# ------------------------------------------------------------
# TRACKS
# ------------------------------------------------------------
self.track_0 = self.env['event.track'].create({
'name': 'What This Event Is All About',
'event_id': self.event.id,
'stage_id': self.env.ref('website_event_track.event_track_stage3').id,
'date': self.reference_now + timedelta(hours=1),
'duration': 2,
'is_published': True,
'wishlisted_by_default': True,
'user_id': self.user_admin.id,
'partner_id': self.event_speaker.id,
})
self.track_1 = self.env['event.track'].create({
'name': 'Live Testimonial',
'event_id': self.event.id,
'stage_id': self.env.ref('website_event_track.event_track_stage3').id,
'date': self.reference_now - timedelta(minutes=30),
'duration': 0.75,
'is_published': True,
'user_id': self.user_admin.id,
'partner_id': self.event_speaker.id,
})
self.track_2 = self.env['event.track'].create({
'name': 'Our Last Day Together !',
'event_id': self.event.id,
'stage_id': self.env.ref('website_event_track.event_track_stage3').id,
'date': self.reference_now + timedelta(days=1),
'duration': 0.75,
'is_published': True,
'user_id': self.user_admin.id,
'partner_id': self.event_speaker.id,
})
# ------------------------------------------------------------
# MEETING ROOMS
# ----------------------------------------------------------
self.env['event.meeting.room'].create({
'name': 'Best wood for furniture',
'summary': 'Let\'s talk about wood types for furniture',
'target_audience': 'wood expert(s)',
'is_pinned': True,
'website_published': True,
'event_id': self.event.id,
'room_lang_id': self.env.ref('base.lang_en').id,
'room_max_capacity': '12',
'room_participant_count': 9,
})
self.event.flush()
| 40.374101
| 11,224
|
8,737
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime
from dateutil.relativedelta import relativedelta
from odoo.addons.event.tests.common import TestEventCommon
from odoo.exceptions import AccessError
from odoo.tests.common import users
from odoo.tools import mute_logger
class TestEventSecurity(TestEventCommon):
@users('user_employee')
@mute_logger('odoo.models.unlink', 'odoo.addons.base.models.ir_model')
def test_event_access_employee(self):
# Event: read ok
event = self.event_0.with_user(self.env.user)
event.read(['name'])
# Event: read only
with self.assertRaises(AccessError):
self.env['event.event'].create({
'name': 'TestEvent',
'date_begin': datetime.now() + relativedelta(days=-1),
'date_end': datetime.now() + relativedelta(days=1),
'seats_limited': True,
'seats_max': 10,
})
with self.assertRaises(AccessError):
event.write({
'name': 'TestEvent Modified',
})
# Event Type
with self.assertRaises(AccessError):
self.event_type_complex.with_user(self.env.user).read(['name'])
with self.assertRaises(AccessError):
self.event_type_complex.with_user(self.env.user).write({'name': 'Test Write'})
# Event Stage
with self.assertRaises(AccessError):
self.env['event.stage'].create({
'name': 'TestStage',
})
# Event Registration
with self.assertRaises(AccessError):
self.env['event.registration'].search([])
@users('user_eventregistrationdesk')
@mute_logger('odoo.models.unlink', 'odoo.addons.base.models.ir_model')
def test_event_access_event_registration(self):
# Event: read ok
event = self.event_0.with_user(self.env.user)
event.read(['name', 'user_id', 'kanban_state_label'])
# Event: read only
with self.assertRaises(AccessError):
event.name = 'Test'
with self.assertRaises(AccessError):
event.unlink()
# Event Registration
registration = self.env['event.registration'].create({
'event_id': self.event_0.id,
})
self.assertEqual(registration.event_id.name, self.event_0.name, 'Registration users should be able to read')
registration.name = 'Test write'
with self.assertRaises(AccessError):
registration.unlink()
@users('user_eventuser')
@mute_logger('odoo.models.unlink', 'odoo.addons.base.models.ir_model')
def test_event_access_event_user(self):
# Event
event = self.event_0.with_user(self.env.user)
event.read(['name', 'user_id', 'kanban_state_label'])
event.write({'name': 'New name'})
self.env['event.event'].create({
'name': 'Event',
'date_begin': datetime.now() + relativedelta(days=-1),
'date_end': datetime.now() + relativedelta(days=1),
})
# Event: cannot unlink
with self.assertRaises(AccessError):
event.unlink()
# Event Type
with self.assertRaises(AccessError):
self.env['event.type'].create({
'name': 'ManagerEventType',
'event_type_mail_ids': [(5, 0), (0, 0, {
'interval_nbr': 1, 'interval_unit': 'days', 'interval_type': 'before_event',
'template_ref': 'mail.template,%i' % self.env['ir.model.data']._xmlid_to_res_id('event.event_reminder')})]
})
@users('user_eventmanager')
@mute_logger('odoo.models.unlink', 'odoo.addons.base.models.ir_model')
def test_event_access_event_manager(self):
# Event Type
event_type = self.env['event.type'].create({
'name': 'ManagerEventType',
'event_type_mail_ids': [(5, 0), (0, 0, {
'interval_nbr': 1, 'interval_unit': 'days', 'interval_type': 'before_event',
'template_ref': 'mail.template,%i' % self.env['ir.model.data']._xmlid_to_res_id('event.event_reminder')})]
})
event_type.write({'name': 'New Name'})
# Event
event = self.env['event.event'].create({
'name': 'ManagerEvent',
'date_begin': datetime.now() + relativedelta(days=-1),
'date_end': datetime.now() + relativedelta(days=1),
})
event.write({'name': 'New Event Name'})
# Event Stage
stage = self.env['event.stage'].create({'name': 'test'})
stage.write({'name': 'ManagerTest'})
event.write({'stage_id': stage.id})
# Event Registration
registration = self.env['event.registration'].create({'event_id': event.id, 'name': 'Myself'})
registration.write({'name': 'Myself2'})
registration.unlink()
event.unlink()
stage.unlink()
event_type.unlink()
# Settings access rights required to enable some features
self.user_eventmanager.write({'groups_id': [
(3, self.env.ref('base.group_system').id),
(4, self.env.ref('base.group_erp_manager').id)
]})
with self.assertRaises(AccessError):
event_config = self.env['res.config.settings'].with_user(self.user_eventmanager).create({
})
event_config.execute()
def test_implied_groups(self):
"""Test that the implied groups are correctly set.
- Event Manager imply Event User
- Event User imply Registration user
"""
# Event Manager
self.assertTrue(
self.user_eventmanager.has_group('event.group_event_user'),
'The event manager group must imply the event user group')
self.assertTrue(
self.user_eventmanager.has_group('event.group_event_registration_desk'),
'The event manager group must imply the registration user group')
# Event User
self.assertTrue(
self.user_eventuser.has_group('event.group_event_registration_desk'),
'The event user group must imply the event user group')
self.assertFalse(
self.user_eventuser.has_group('event.group_event_manager'),
'The event user group must not imply the event user group')
# Registration User
self.assertFalse(
self.user_eventregistrationdesk.has_group('event.group_event_manager'),
'The event registration group must not imply the event user manager')
self.assertFalse(
self.user_eventregistrationdesk.has_group('event.group_event_user'),
'The event registration group must not imply the event user group')
def test_multi_companies(self):
"""Test ACLs with multi company. """
company_1 = self.env.ref("base.main_company")
company_2 = self.env['res.company'].create({'name': 'Company 2'})
user_company_1 = self.user_eventuser
event_company_1, event_company_2 = self.env['event.event'].create([
{
'name': 'Event Company 1',
'date_begin': datetime.now() + relativedelta(days=-1),
'date_end': datetime.now() + relativedelta(days=1),
'company_id': company_1.id,
}, {
'name': 'Event Company 2',
'date_begin': datetime.now() + relativedelta(days=-1),
'date_end': datetime.now() + relativedelta(days=1),
'company_id': company_2.id,
}
])
registration_company_1, registration_company_2 = self.env['event.registration'].create([
{
'name': 'Registration Company 1',
'event_id': event_company_1.id,
'company_id': company_1.id,
}, {
'name': 'Registration Company 2',
'event_id': event_company_2.id,
'company_id': company_2.id,
}
])
result = self.env['event.event'].with_user(user_company_1).search([])
self.assertIn(event_company_1, result, 'You must be able to read the events in your company')
self.assertNotIn(event_company_2, result, 'You must not be able to read events outside of your company')
result = self.env['event.registration'].with_user(user_company_1).search([])
self.assertIn(registration_company_1, result, 'You must be able to read the registrations in your company')
self.assertNotIn(registration_company_2, result, 'You must not be able to read registrations outside of your company')
| 41.212264
| 8,737
|
2,082
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.test_event_full.tests.common import TestWEventCommon
from odoo.exceptions import ValidationError
class TestTemplateRefModel(TestWEventCommon):
def test_template_ref_model_constraint(self):
test_cases = [
('mail', 'mail.template', True),
('mail', 'sms.template', False),
('sms', 'sms.template', True),
('sms', 'mail.template', False),
]
for notification_type, template_type, valid in test_cases:
with self.subTest(notification_type=notification_type, template_type=template_type):
if template_type == 'mail.template':
template = self.env[template_type].create({
'name': 'test template',
'model_id': self.env['ir.model']._get_id('event.registration'),
})
else:
template = self.env[template_type].create({
'name': 'test template',
'body': 'Body Test',
'model_id': self.env['ir.model']._get_id('event.registration'),
})
if not valid:
with self.assertRaises(ValidationError) as cm:
self.env['event.mail'].create({
'event_id': self.event.id,
'notification_type': notification_type,
'interval_unit': 'now',
'interval_type': 'before_event',
'template_ref': template,
})
if notification_type == 'mail':
self.assertEqual(str(cm.exception), 'The template which is referenced should be coming from mail.template model.')
else:
self.assertEqual(str(cm.exception), 'The template which is referenced should be coming from sms.template model.')
| 48.418605
| 2,082
|
7,227
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.test_event_full.tests.common import TestEventFullCommon
from odoo.tests import users
class TestEventCrm(TestEventFullCommon):
@classmethod
def setUpClass(cls):
super(TestEventCrm, cls).setUpClass()
cls.TICKET1_COUNT, cls.TICKET2_COUNT = 3, 1
ticket1 = cls.event_0.event_ticket_ids[0]
ticket2 = cls.event_0.event_ticket_ids[1]
# PREPARE SO DATA
# ------------------------------------------------------------
# adding some tickets to SO
cls.customer_so.write({
'order_line': [
(0, 0, {
'event_id': cls.event_0.id,
'event_ticket_id': ticket1.id,
'product_id': ticket1.product_id.id,
'product_uom_qty': cls.TICKET1_COUNT,
}), (0, 0, {
'event_id': cls.event_0.id,
'event_ticket_id': ticket2.id,
'product_id': ticket2.product_id.id,
'product_uom_qty': cls.TICKET2_COUNT,
'price_unit': 50,
})
]
})
@users('user_sales_salesman')
def test_event_crm_sale_customer(self):
""" Test a SO with a real customer set on it, check partner propagation
as well as group-based lead update. """
customer_so = self.env['sale.order'].browse(self.customer_so.id)
# adding some tickets to SO
t1_reg_vals = [
dict(customer_data,
partner_id=customer_so.partner_id.id,
sale_order_line_id=customer_so.order_line[0].id)
for customer_data in self.website_customer_data[:self.TICKET1_COUNT]
]
t1_registrations = self.env['event.registration'].create(t1_reg_vals)
# check effect: registrations, leads
self.assertEqual(self.event_0.registration_ids, t1_registrations)
self.assertEqual(len(self.test_rule_order.lead_ids), 1)
self.assertEqual(self.test_rule_order_done.lead_ids, self.env['crm.lead'])
# check lead converted based on registrations
self.assertLeadConvertion(self.test_rule_order, t1_registrations, partner=customer_so.partner_id)
# SO is confirmed -> missing registrations should be automatically added
# and added to the lead as part of the same group
customer_so.action_confirm()
self.assertEqual(customer_so.state, 'sale')
self.assertEqual(len(self.event_0.registration_ids), self.TICKET1_COUNT + self.TICKET2_COUNT)
self.assertEqual(len(self.test_rule_order.lead_ids), 1) # no new lead created
self.assertEqual(self.test_rule_order_done.lead_ids, self.env['crm.lead']) # this one still not triggered
# check existing lead has been updated with new registrations
self.assertLeadConvertion(self.test_rule_order, self.event_0.registration_ids, partner=customer_so.partner_id)
# Confirm registrations -> trigger the "DONE" rule, one new lead linked to all
# event registrations created in this test as all belong to the same SO
self.event_0.registration_ids.write({'state': 'done'})
self.assertLeadConvertion(self.test_rule_order_done, self.event_0.registration_ids, partner=customer_so.partner_id)
@users('user_sales_salesman')
def test_event_crm_sale_mixed_group(self):
""" Test a mixed sale order line creation. This should not happen in a customer
use case but should be supported by the code. """
public_partner = self.env.ref('base.public_partner')
public_so = self.env['sale.order'].create({
'partner_id': public_partner.id,
'order_line': [
(0, 0, {
'event_id': self.event_0.id,
'event_ticket_id': self.event_0.event_ticket_ids[0].id,
'product_id': self.event_0.event_ticket_ids[0].product_id.id,
'product_uom_qty': 2,
})
]
})
customer_so = self.env['sale.order'].browse(self.customer_so.id)
# make a multi-SO create
mixed_reg_vals = [
dict(self.website_customer_data[0],
partner_id=customer_so.partner_id.id,
sale_order_line_id=customer_so.order_line[0].id),
dict(self.website_customer_data[1],
partner_id=customer_so.partner_id.id,
sale_order_line_id=customer_so.order_line[0].id),
dict(self.website_customer_data[2],
partner_id=public_so.partner_id.id,
sale_order_line_id=public_so.order_line[0].id),
dict(self.website_customer_data[3],
partner_id=public_so.partner_id.id,
sale_order_line_id=public_so.order_line[0].id),
]
self.env['event.registration'].create(mixed_reg_vals)
public_regs = self.event_0.registration_ids.filtered(lambda reg: reg.sale_order_id == public_so)
self.assertEqual(len(public_regs), 2)
customer_regs = self.event_0.registration_ids.filtered(lambda reg: reg.sale_order_id == customer_so)
self.assertEqual(len(customer_regs), 2)
self.assertLeadConvertion(self.test_rule_order, public_regs, partner=None)
self.assertLeadConvertion(self.test_rule_order, customer_regs, partner=customer_so.partner_id)
@users('user_sales_salesman')
def test_event_crm_sale_public(self):
""" Test a SO with a public partner on it, then updated when SO is confirmed.
This somehow simulates a simplified website_event_sale flow. """
public_partner = self.env.ref('base.public_partner')
customer_so = self.env['sale.order'].browse(self.customer_so.id)
customer_so.write({'partner_id': public_partner.id})
# adding some tickets to SO
t1_reg_vals = [
dict(customer_data,
partner_id=public_partner.id,
sale_order_line_id=customer_so.order_line[0].id)
for customer_data in self.website_customer_data[:self.TICKET1_COUNT]
]
t1_registrations = self.env['event.registration'].create(t1_reg_vals)
self.assertEqual(self.event_0.registration_ids, t1_registrations)
# check lead converted based on registrations
self.assertLeadConvertion(self.test_rule_order, t1_registrations, partner=None)
# SO is confirmed -> missing registrations should be automatically added
# BUT as public user -> no email -> not taken into account by rule
customer_so.action_confirm()
self.assertEqual(customer_so.state, 'sale')
self.assertEqual(len(self.event_0.registration_ids), self.TICKET1_COUNT + self.TICKET2_COUNT)
self.assertLeadConvertion(self.test_rule_order, t1_registrations, partner=None)
# SO has a customer set -> main contact of lead is updated accordingly
customer_so.write({'partner_id': self.event_customer.id})
self.assertLeadConvertion(self.test_rule_order, t1_registrations, partner=self.event_customer)
| 48.503356
| 7,227
|
1,689
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import tests
from odoo.addons.test_event_full.tests.common import TestWEventCommon
from odoo.tests.common import HOST
@tests.common.tagged('post_install', '-at_install')
class TestWEventRegister(TestWEventCommon):
def test_register(self):
self.browser_js(
'/event',
'odoo.__DEBUG__.services["web_tour.tour"].run("wevent_register")',
'odoo.__DEBUG__.services["web_tour.tour"].tours.wevent_register.ready',
login=None
)
new_registrations = self.event.registration_ids
visitor = new_registrations.visitor_id
# check registration content
self.assertEqual(len(new_registrations), 2)
self.assertEqual(
set(new_registrations.mapped("name")),
set(["Raoulette Poiluchette", "Michel Tractopelle"])
)
self.assertEqual(
set(new_registrations.mapped("phone")),
set(["0456112233", "0456332211"])
)
self.assertEqual(
set(new_registrations.mapped("email")),
set(["raoulette@example.com", "michel@example.com"])
)
# check visitor stored information
self.assertEqual(visitor.name, "Raoulette Poiluchette")
self.assertEqual(visitor.event_registration_ids, new_registrations)
self.assertEqual(visitor.partner_id, self.env['res.partner'])
self.assertEqual(visitor.mobile, "0456112233")
self.assertEqual(visitor.email, "raoulette@example.com")
self.assertFalse(visitor.parent_id)
self.assertTrue(visitor.active)
| 38.386364
| 1,689
|
1,092
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Purchase Agreements',
'version': '0.1',
'category': 'Inventory/Purchase',
'description': """
This module allows you to manage your Purchase Agreements.
===========================================================
Manage calls for tenders and blanket orders. Calls for tenders are used to get
competing offers from different vendors and select the best ones. Blanket orders
are agreements you have with vendors to benefit from a predetermined pricing.
""",
'depends': ['purchase'],
'demo': ['data/purchase_requisition_demo.xml'],
'data': [
'security/purchase_requisition_security.xml',
'security/ir.model.access.csv',
'data/purchase_requisition_data.xml',
'views/product_views.xml',
'views/purchase_views.xml',
'views/purchase_requisition_views.xml',
'views/res_config_settings_views.xml',
'report/purchase_requisition_report.xml',
'report/report_purchaserequisition.xml',
],
'license': 'LGPL-3',
}
| 39
| 1,092
|
6,599
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.purchase_requisition.tests.common import TestPurchaseRequisitionCommon
from odoo.tests import Form
class TestPurchaseRequisition(TestPurchaseRequisitionCommon):
def test_00_purchase_requisition_users(self):
self.assertTrue(self.user_purchase_requisition_manager, 'Manager Should be created')
self.assertTrue(self.user_purchase_requisition_user, 'User Should be created')
def test_01_cancel_purchase_requisition(self):
self.requisition1.with_user(self.user_purchase_requisition_user).action_cancel()
# Check requisition after cancelled.
self.assertEqual(self.requisition1.state, 'cancel', 'Requisition should be in cancelled state.')
# I reset requisition as "New".
self.requisition1.with_user(self.user_purchase_requisition_user).action_draft()
# I duplicate requisition.
self.requisition1.with_user(self.user_purchase_requisition_user).copy()
def test_02_purchase_requisition(self):
price_product09 = 34
price_product13 = 62
quantity = 26
# Create a pruchase requisition with type blanket order and two product
line1 = (0, 0, {'product_id': self.product_09.id, 'product_qty': quantity, 'product_uom_id': self.product_uom_id.id, 'price_unit': price_product09})
line2 = (0, 0, {'product_id': self.product_13.id, 'product_qty': quantity, 'product_uom_id': self.product_uom_id.id, 'price_unit': price_product13})
requisition_type = self.env['purchase.requisition.type'].create({
'name': 'Blanket test',
'quantity_copy': 'none'
})
requisition_blanket = self.env['purchase.requisition'].create({
'line_ids': [line1, line2],
'type_id': requisition_type.id,
'vendor_id': self.res_partner_1.id,
})
# confirm the requisition
requisition_blanket.action_in_progress()
# Check for both product that the new supplier info(purchase.requisition.vendor_id) is added to the puchase tab
# and check the quantity
seller_partner1 = self.res_partner_1
supplierinfo09 = self.env['product.supplierinfo'].search([
('name', '=', seller_partner1.id),
('product_id', '=', self.product_09.id),
('purchase_requisition_id', '=', requisition_blanket.id),
])
self.assertEqual(supplierinfo09.name, seller_partner1, 'The supplierinfo is not the good one')
self.assertEqual(supplierinfo09.price, price_product09, 'The supplierinfo is not the good one')
supplierinfo13 = self.env['product.supplierinfo'].search([
('name', '=', seller_partner1.id),
('product_id', '=', self.product_13.id),
('purchase_requisition_id', '=', requisition_blanket.id),
])
self.assertEqual(supplierinfo13.name, seller_partner1, 'The supplierinfo is not the good one')
self.assertEqual(supplierinfo13.price, price_product13, 'The supplierinfo is not the good one')
# Put the requisition in done Status
requisition_blanket.action_in_progress()
requisition_blanket.action_done()
self.assertFalse(self.env['product.supplierinfo'].search([('id', '=', supplierinfo09.id)]), 'The supplier info should be removed')
self.assertFalse(self.env['product.supplierinfo'].search([('id', '=', supplierinfo13.id)]), 'The supplier info should be removed')
def test_06_purchase_requisition(self):
""" Create a blanquet order for a product and a vendor already linked via
a supplier info"""
product = self.env['product.product'].create({
'name': 'test6',
})
product2 = self.env['product.product'].create({
'name': 'test6',
})
vendor = self.env['res.partner'].create({
'name': 'vendor6',
})
supplier_info = self.env['product.supplierinfo'].create({
'product_id': product.id,
'name': vendor.id,
})
# create a empty blanquet order
requisition_type = self.env['purchase.requisition.type'].create({
'name': 'Blanket test',
'quantity_copy': 'none'
})
line1 = (0, 0, {
'product_id': product2.id,
'product_uom_id': product2.uom_po_id.id,
'price_unit': 41,
'product_qty': 10,
})
requisition_blanket = self.env['purchase.requisition'].create({
'line_ids': [line1],
'type_id': requisition_type.id,
'vendor_id': vendor.id,
})
requisition_blanket.action_in_progress()
self.env['purchase.requisition.line'].create({
'product_id': product.id,
'product_qty': 14.0,
'requisition_id': requisition_blanket.id,
'price_unit': 10,
})
new_si = self.env['product.supplierinfo'].search([
('product_id', '=', product.id),
('name', '=', vendor.id)
]) - supplier_info
self.assertEqual(new_si.purchase_requisition_id, requisition_blanket, 'the blanket order is not linked to the supplier info')
def test_07_purchase_requisition(self):
"""
Check that the analytic account and the account tag defined in the purchase requisition line
is used in the purchase order line when creating a PO.
"""
analytic_account = self.env['account.analytic.account'].create({'name': 'test_analytic_account'})
analytic_tag = self.env['account.analytic.tag'].create({'name': 'test_analytic_tag'})
self.assertEqual(len(self.requisition1.line_ids), 1)
self.requisition1.line_ids[0].write({
'account_analytic_id': analytic_account,
'analytic_tag_ids': analytic_tag,
})
# Create purchase order from purchase requisition
po_form = Form(self.env['purchase.order'].with_context(default_requisition_id=self.requisition1.id))
po_form.partner_id = self.res_partner_1
po = po_form.save()
self.assertEqual(po.order_line.account_analytic_id.id, analytic_account.id, 'The analytic account defined in the purchase requisition line must be the same as the one from the purchase order line.')
self.assertEqual(po.order_line.analytic_tag_ids.id, analytic_tag.id, 'The analytic account tag defined in the purchase requisition line must be the same as the one from the purchase order line.')
| 48.881481
| 6,599
|
2,607
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.tests import common
class TestPurchaseRequisitionCommon(common.TransactionCase):
@classmethod
def setUpClass(cls):
super(TestPurchaseRequisitionCommon, cls).setUpClass()
# Fetch purchase related user groups
user_group_purchase_manager = cls.env.ref('purchase.group_purchase_manager')
user_group_purchase_user = cls.env.ref('purchase.group_purchase_user')
# User Data: purchase requisition Manager and User
Users = cls.env['res.users'].with_context({'tracking_disable': True})
cls.user_purchase_requisition_manager = Users.create({
'name': 'Purchase requisition Manager',
'login': 'prm',
'email': 'requisition_manager@yourcompany.com',
'notification_type': 'inbox',
'groups_id': [(6, 0, [user_group_purchase_manager.id])]})
cls.user_purchase_requisition_user = Users.create({
'name': 'Purchase requisition User',
'login': 'pru',
'email': 'requisition_user@yourcompany.com',
'notification_type': 'inbox',
'groups_id': [(6, 0, [user_group_purchase_user.id])]})
# Create Product
cls.product_uom_id = cls.env.ref('uom.product_uom_unit')
cls.product_09 = cls.env['product.product'].create({
'name': 'Pedal Bin',
'categ_id': cls.env.ref('product.product_category_all').id,
'standard_price': 10.0,
'list_price': 47.0,
'type': 'consu',
'uom_id': cls.product_uom_id.id,
'uom_po_id': cls.product_uom_id.id,
'default_code': 'E-COM10',
})
cls.product_13 = cls.env['product.product'].create({
'name': 'Corner Desk Black',
'categ_id': cls.env.ref('product.product_category_all').id,
'standard_price': 78.0,
'list_price': 85.0,
'type': 'consu',
'uom_id': cls.product_uom_id.id,
'uom_po_id': cls.product_uom_id.id,
'default_code': 'FURN_1118',
'purchase_requisition': 'tenders',
})
# In order to test process of the purchase requisition ,create requisition
cls.requisition1 = cls.env['purchase.requisition'].create({
'line_ids': [(0, 0, {
'product_id': cls.product_09.id,
'product_qty': 10.0,
'product_uom_id': cls.product_uom_id.id})]
})
cls.res_partner_1 = cls.env['res.partner'].create({
'name': 'Wood Corner',
})
| 37.782609
| 2,607
|
5,479
|
py
|
PYTHON
|
15.0
|
# -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class PurchaseOrder(models.Model):
_inherit = 'purchase.order'
requisition_id = fields.Many2one('purchase.requisition', string='Purchase Agreement', copy=False)
is_quantity_copy = fields.Selection(related='requisition_id.is_quantity_copy', readonly=False)
@api.onchange('requisition_id')
def _onchange_requisition_id(self):
if not self.requisition_id:
return
self = self.with_company(self.company_id)
requisition = self.requisition_id
if self.partner_id:
partner = self.partner_id
else:
partner = requisition.vendor_id
payment_term = partner.property_supplier_payment_term_id
FiscalPosition = self.env['account.fiscal.position']
fpos = FiscalPosition.with_company(self.company_id).get_fiscal_position(partner.id)
self.partner_id = partner.id
self.fiscal_position_id = fpos.id
self.payment_term_id = payment_term.id,
self.company_id = requisition.company_id.id
self.currency_id = requisition.currency_id.id
if not self.origin or requisition.name not in self.origin.split(', '):
if self.origin:
if requisition.name:
self.origin = self.origin + ', ' + requisition.name
else:
self.origin = requisition.name
self.notes = requisition.description
self.date_order = fields.Datetime.now()
if requisition.type_id.line_copy != 'copy':
return
# Create PO lines if necessary
order_lines = []
for line in requisition.line_ids:
# Compute name
product_lang = line.product_id.with_context(
lang=partner.lang or self.env.user.lang,
partner_id=partner.id
)
name = product_lang.display_name
if product_lang.description_purchase:
name += '\n' + product_lang.description_purchase
# Compute taxes
taxes_ids = fpos.map_tax(line.product_id.supplier_taxes_id.filtered(lambda tax: tax.company_id == requisition.company_id)).ids
# Compute quantity and price_unit
if line.product_uom_id != line.product_id.uom_po_id:
product_qty = line.product_uom_id._compute_quantity(line.product_qty, line.product_id.uom_po_id)
price_unit = line.product_uom_id._compute_price(line.price_unit, line.product_id.uom_po_id)
else:
product_qty = line.product_qty
price_unit = line.price_unit
if requisition.type_id.quantity_copy != 'copy':
product_qty = 0
# Create PO line
order_line_values = line._prepare_purchase_order_line(
name=name, product_qty=product_qty, price_unit=price_unit,
taxes_ids=taxes_ids)
order_lines.append((0, 0, order_line_values))
self.order_line = order_lines
def button_confirm(self):
res = super(PurchaseOrder, self).button_confirm()
for po in self:
if not po.requisition_id:
continue
if po.requisition_id.type_id.exclusive == 'exclusive':
others_po = po.requisition_id.mapped('purchase_ids').filtered(lambda r: r.id != po.id)
others_po.button_cancel()
if po.state not in ['draft', 'sent', 'to approve']:
po.requisition_id.action_done()
return res
@api.model
def create(self, vals):
purchase = super(PurchaseOrder, self).create(vals)
if purchase.requisition_id:
purchase.message_post_with_view('mail.message_origin_link',
values={'self': purchase, 'origin': purchase.requisition_id},
subtype_id=self.env['ir.model.data']._xmlid_to_res_id('mail.mt_note'))
return purchase
def write(self, vals):
result = super(PurchaseOrder, self).write(vals)
if vals.get('requisition_id'):
self.message_post_with_view('mail.message_origin_link',
values={'self': self, 'origin': self.requisition_id, 'edit': True},
subtype_id=self.env['ir.model.data']._xmlid_to_res_id('mail.mt_note'))
return result
class PurchaseOrderLine(models.Model):
_inherit = 'purchase.order.line'
def _compute_account_analytic_id(self):
super(PurchaseOrderLine, self.filtered(lambda pol: not pol.order_id.requisition_id))._compute_account_analytic_id()
def _compute_analytic_tag_ids(self):
super(PurchaseOrderLine, self.filtered(lambda pol: not pol.order_id.requisition_id))._compute_analytic_tag_ids()
@api.onchange('product_qty', 'product_uom')
def _onchange_quantity(self):
res = super(PurchaseOrderLine, self)._onchange_quantity()
if self.order_id.requisition_id:
for line in self.order_id.requisition_id.line_ids.filtered(lambda l: l.product_id == self.product_id):
if line.product_uom_id != self.product_uom:
self.price_unit = line.product_uom_id._compute_price(
line.price_unit, self.product_uom)
else:
self.price_unit = line.price_unit
break
return res
| 42.472868
| 5,479
|
1,445
|
py
|
PYTHON
|
15.0
|
# -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class SupplierInfo(models.Model):
_inherit = 'product.supplierinfo'
purchase_requisition_id = fields.Many2one('purchase.requisition', related='purchase_requisition_line_id.requisition_id', string='Agreement')
purchase_requisition_line_id = fields.Many2one('purchase.requisition.line')
class ProductProduct(models.Model):
_inherit = 'product.product'
def _prepare_sellers(self, params=False):
sellers = super(ProductProduct, self)._prepare_sellers(params=params)
if params and params.get('order_id'):
return sellers.filtered(lambda s: not s.purchase_requisition_id or s.purchase_requisition_id == params['order_id'].requisition_id)
else:
return sellers
class ProductTemplate(models.Model):
_inherit = 'product.template'
purchase_requisition = fields.Selection(
[('rfq', 'Create a draft purchase order'),
('tenders', 'Propose a call for tenders')],
string='Procurement', default='rfq',
help="Create a draft purchase order: Based on your product configuration, the system will create a draft "
"purchase order.Propose a call for tender : If the 'purchase_requisition' module is installed and this option "
"is selected, the system will create a draft call for tender.")
| 42.5
| 1,445
|
15,171
|
py
|
PYTHON
|
15.0
|
# -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, time
from odoo import api, fields, models, _
from odoo.exceptions import UserError
PURCHASE_REQUISITION_STATES = [
('draft', 'Draft'),
('ongoing', 'Ongoing'),
('in_progress', 'Confirmed'),
('open', 'Bid Selection'),
('done', 'Closed'),
('cancel', 'Cancelled')
]
class PurchaseRequisitionType(models.Model):
_name = "purchase.requisition.type"
_description = "Purchase Requisition Type"
_order = "sequence"
name = fields.Char(string='Agreement Type', required=True, translate=True)
sequence = fields.Integer(default=1)
exclusive = fields.Selection([
('exclusive', 'Select only one RFQ (exclusive)'), ('multiple', 'Select multiple RFQ (non-exclusive)')],
string='Agreement Selection Type', required=True, default='multiple',
help="""Select only one RFQ (exclusive): when a purchase order is confirmed, cancel the remaining purchase order.\n
Select multiple RFQ (non-exclusive): allows multiple purchase orders. On confirmation of a purchase order it does not cancel the remaining orders""")
quantity_copy = fields.Selection([
('copy', 'Use quantities of agreement'), ('none', 'Set quantities manually')],
string='Quantities', required=True, default='none')
line_copy = fields.Selection([
('copy', 'Use lines of agreement'), ('none', 'Do not create RfQ lines automatically')],
string='Lines', required=True, default='copy')
active = fields.Boolean(default=True, help="Set active to false to hide the Purchase Agreement Types without removing it.")
class PurchaseRequisition(models.Model):
_name = "purchase.requisition"
_description = "Purchase Requisition"
_inherit = ['mail.thread', 'mail.activity.mixin']
_order = "id desc"
def _get_type_id(self):
return self.env['purchase.requisition.type'].search([], limit=1)
name = fields.Char(string='Reference', required=True, copy=False, default='New', readonly=True)
origin = fields.Char(string='Source Document')
order_count = fields.Integer(compute='_compute_orders_number', string='Number of Orders')
vendor_id = fields.Many2one('res.partner', string="Vendor", domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]")
type_id = fields.Many2one('purchase.requisition.type', string="Agreement Type", required=True, default=_get_type_id)
ordering_date = fields.Date(string="Ordering Date", tracking=True)
date_end = fields.Datetime(string='Agreement Deadline', tracking=True)
schedule_date = fields.Date(string='Delivery Date', index=True, help="The expected and scheduled delivery date where all the products are received", tracking=True)
user_id = fields.Many2one(
'res.users', string='Purchase Representative',
default=lambda self: self.env.user, check_company=True)
description = fields.Html()
company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.company)
purchase_ids = fields.One2many('purchase.order', 'requisition_id', string='Purchase Orders', states={'done': [('readonly', True)]})
line_ids = fields.One2many('purchase.requisition.line', 'requisition_id', string='Products to Purchase', states={'done': [('readonly', True)]}, copy=True)
product_id = fields.Many2one('product.product', related='line_ids.product_id', string='Product')
state = fields.Selection(PURCHASE_REQUISITION_STATES,
'Status', tracking=True, required=True,
copy=False, default='draft')
state_blanket_order = fields.Selection(PURCHASE_REQUISITION_STATES, compute='_set_state')
is_quantity_copy = fields.Selection(related='type_id.quantity_copy', readonly=True)
currency_id = fields.Many2one('res.currency', 'Currency', required=True,
default=lambda self: self.env.company.currency_id.id)
@api.depends('state')
def _set_state(self):
for requisition in self:
requisition.state_blanket_order = requisition.state
@api.onchange('vendor_id')
def _onchange_vendor(self):
self = self.with_company(self.company_id)
if not self.vendor_id:
self.currency_id = self.env.company.currency_id.id
else:
self.currency_id = self.vendor_id.property_purchase_currency_id.id or self.env.company.currency_id.id
requisitions = self.env['purchase.requisition'].search([
('vendor_id', '=', self.vendor_id.id),
('state', '=', 'ongoing'),
('type_id.quantity_copy', '=', 'none'),
('company_id', '=', self.company_id.id),
])
if any(requisitions):
title = _("Warning for %s", self.vendor_id.name)
message = _("There is already an open blanket order for this supplier. We suggest you complete this open blanket order, instead of creating a new one.")
warning = {
'title': title,
'message': message
}
return {'warning': warning}
@api.depends('purchase_ids')
def _compute_orders_number(self):
for requisition in self:
requisition.order_count = len(requisition.purchase_ids)
def action_cancel(self):
# try to set all associated quotations to cancel state
for requisition in self:
for requisition_line in requisition.line_ids:
requisition_line.supplier_info_ids.unlink()
requisition.purchase_ids.button_cancel()
for po in requisition.purchase_ids:
po.message_post(body=_('Cancelled by the agreement associated to this quotation.'))
self.write({'state': 'cancel'})
def action_in_progress(self):
self.ensure_one()
if not self.line_ids:
raise UserError(_("You cannot confirm agreement '%s' because there is no product line.", self.name))
if self.type_id.quantity_copy == 'none' and self.vendor_id:
for requisition_line in self.line_ids:
if requisition_line.price_unit <= 0.0:
raise UserError(_('You cannot confirm the blanket order without price.'))
if requisition_line.product_qty <= 0.0:
raise UserError(_('You cannot confirm the blanket order without quantity.'))
requisition_line.create_supplier_info()
self.write({'state': 'ongoing'})
else:
self.write({'state': 'in_progress'})
# Set the sequence number regarding the requisition type
if self.name == 'New':
if self.is_quantity_copy != 'none':
self.name = self.env['ir.sequence'].next_by_code('purchase.requisition.purchase.tender')
else:
self.name = self.env['ir.sequence'].next_by_code('purchase.requisition.blanket.order')
def action_open(self):
self.write({'state': 'open'})
def action_draft(self):
self.ensure_one()
self.name = 'New'
self.write({'state': 'draft'})
def action_done(self):
"""
Generate all purchase order based on selected lines, should only be called on one agreement at a time
"""
if any(purchase_order.state in ['draft', 'sent', 'to approve'] for purchase_order in self.mapped('purchase_ids')):
raise UserError(_('You have to cancel or validate every RfQ before closing the purchase requisition.'))
for requisition in self:
for requisition_line in requisition.line_ids:
requisition_line.supplier_info_ids.unlink()
self.write({'state': 'done'})
@api.ondelete(at_uninstall=False)
def _unlink_if_draft_or_cancel(self):
if any(requisition.state not in ('draft', 'cancel') for requisition in self):
raise UserError(_('You can only delete draft requisitions.'))
def unlink(self):
# Draft requisitions could have some requisition lines.
self.mapped('line_ids').unlink()
return super(PurchaseRequisition, self).unlink()
class PurchaseRequisitionLine(models.Model):
_name = "purchase.requisition.line"
_description = "Purchase Requisition Line"
_rec_name = 'product_id'
product_id = fields.Many2one('product.product', string='Product', domain=[('purchase_ok', '=', True)], required=True)
product_uom_id = fields.Many2one('uom.uom', string='Product Unit of Measure', domain="[('category_id', '=', product_uom_category_id)]")
product_uom_category_id = fields.Many2one(related='product_id.uom_id.category_id')
product_qty = fields.Float(string='Quantity', digits='Product Unit of Measure')
product_description_variants = fields.Char('Custom Description')
price_unit = fields.Float(string='Unit Price', digits='Product Price')
qty_ordered = fields.Float(compute='_compute_ordered_qty', string='Ordered Quantities')
requisition_id = fields.Many2one('purchase.requisition', required=True, string='Purchase Agreement', ondelete='cascade')
company_id = fields.Many2one('res.company', related='requisition_id.company_id', string='Company', store=True, readonly=True)
account_analytic_id = fields.Many2one('account.analytic.account', string='Analytic Account', store=True, compute='_compute_account_analytic_id', readonly=False)
analytic_tag_ids = fields.Many2many('account.analytic.tag', string='Analytic Tags', store=True, compute='_compute_analytic_tag_ids', readonly=False)
schedule_date = fields.Date(string='Scheduled Date')
supplier_info_ids = fields.One2many('product.supplierinfo', 'purchase_requisition_line_id')
@api.model
def create(self,vals):
res = super(PurchaseRequisitionLine, self).create(vals)
if res.requisition_id.state not in ['draft', 'cancel', 'done'] and res.requisition_id.is_quantity_copy == 'none':
supplier_infos = self.env['product.supplierinfo'].search([
('product_id', '=', vals.get('product_id')),
('name', '=', res.requisition_id.vendor_id.id),
])
if not any(s.purchase_requisition_id for s in supplier_infos):
res.create_supplier_info()
if vals['price_unit'] <= 0.0:
raise UserError(_('You cannot confirm the blanket order without price.'))
return res
def write(self, vals):
res = super(PurchaseRequisitionLine, self).write(vals)
if 'price_unit' in vals:
if vals['price_unit'] <= 0.0 and any(
requisition.state not in ['draft', 'cancel', 'done'] and
requisition.is_quantity_copy == 'none' for requisition in self.mapped('requisition_id')):
raise UserError(_('You cannot confirm the blanket order without price.'))
# If the price is updated, we have to update the related SupplierInfo
self.supplier_info_ids.write({'price': vals['price_unit']})
return res
def unlink(self):
to_unlink = self.filtered(lambda r: r.requisition_id.state not in ['draft', 'cancel', 'done'])
to_unlink.mapped('supplier_info_ids').unlink()
return super(PurchaseRequisitionLine, self).unlink()
def create_supplier_info(self):
purchase_requisition = self.requisition_id
if purchase_requisition.type_id.quantity_copy == 'none' and purchase_requisition.vendor_id:
# create a supplier_info only in case of blanket order
self.env['product.supplierinfo'].create({
'name': purchase_requisition.vendor_id.id,
'product_id': self.product_id.id,
'product_tmpl_id': self.product_id.product_tmpl_id.id,
'price': self.price_unit,
'currency_id': self.requisition_id.currency_id.id,
'purchase_requisition_line_id': self.id,
})
@api.depends('requisition_id.purchase_ids.state')
def _compute_ordered_qty(self):
line_found = set()
for line in self:
total = 0.0
for po in line.requisition_id.purchase_ids.filtered(lambda purchase_order: purchase_order.state in ['purchase', 'done']):
for po_line in po.order_line.filtered(lambda order_line: order_line.product_id == line.product_id):
if po_line.product_uom != line.product_uom_id:
total += po_line.product_uom._compute_quantity(po_line.product_qty, line.product_uom_id)
else:
total += po_line.product_qty
if line.product_id not in line_found :
line.qty_ordered = total
line_found.add(line.product_id)
else:
line.qty_ordered = 0
@api.depends('product_id', 'schedule_date')
def _compute_account_analytic_id(self):
for line in self:
default_analytic_account = line.env['account.analytic.default'].sudo().account_get(
product_id=line.product_id.id,
partner_id=line.requisition_id.vendor_id.id,
user_id=line.env.uid,
date=line.schedule_date,
company_id=line.company_id.id,
)
line.account_analytic_id = default_analytic_account.analytic_id
@api.depends('product_id', 'schedule_date')
def _compute_analytic_tag_ids(self):
for line in self:
default_analytic_account = line.env['account.analytic.default'].sudo().account_get(
product_id=line.product_id.id,
partner_id=line.requisition_id.vendor_id.id,
user_id=line.env.uid,
date=line.schedule_date,
company_id=line.company_id.id,
)
line.analytic_tag_ids = default_analytic_account.analytic_tag_ids
@api.onchange('product_id')
def _onchange_product_id(self):
if self.product_id:
self.product_uom_id = self.product_id.uom_po_id
self.product_qty = 1.0
if not self.schedule_date:
self.schedule_date = self.requisition_id.schedule_date
def _prepare_purchase_order_line(self, name, product_qty=0.0, price_unit=0.0, taxes_ids=False):
self.ensure_one()
requisition = self.requisition_id
if self.product_description_variants:
name += '\n' + self.product_description_variants
if requisition.schedule_date:
date_planned = datetime.combine(requisition.schedule_date, time.min)
else:
date_planned = datetime.now()
return {
'name': name,
'product_id': self.product_id.id,
'product_uom': self.product_id.uom_po_id.id,
'product_qty': product_qty,
'price_unit': price_unit,
'taxes_id': [(6, 0, taxes_ids)],
'date_planned': date_planned,
'account_analytic_id': self.account_analytic_id.id,
'analytic_tag_ids': self.analytic_tag_ids.ids,
}
| 51.080808
| 15,171
|
725
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Lead Generation From Website Visits',
'summary': 'Generate Leads/Opportunities from your website\'s traffic',
'version': '1.1',
'category': 'Sales/CRM',
'depends': [
'iap_crm',
'iap_mail',
'crm_iap_mine',
'website'
],
'data': [
'data/ir_cron_data.xml',
'data/ir_model_data.xml',
'security/ir_rules.xml',
'security/ir.model.access.csv',
'views/crm_lead_views.xml',
'views/crm_reveal_views.xml',
'views/res_config_settings_views.xml',
'views/crm_menus.xml',
],
'license': 'LGPL-3',
}
| 27.884615
| 725
|
8,722
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import exceptions
from odoo.addons.crm.tests.common import TestCrmCommon
from odoo.addons.website_crm_iap_reveal.tests.common import MockIAPReveal
from odoo.tests.common import users
class TestLeadMine(TestCrmCommon, MockIAPReveal):
@classmethod
def setUpClass(cls):
super(TestLeadMine, cls).setUpClass()
cls.registry.enter_test_mode(cls.cr)
cls.test_industry_tags = cls.env.ref('crm_iap_mine.crm_iap_mine_industry_33') + cls.env.ref('crm_iap_mine.crm_iap_mine_industry_148')
cls.test_roles = cls.env.ref('crm_iap_mine.crm_iap_mine_role_11') + cls.env.ref('crm_iap_mine.crm_iap_mine_role_19')
cls.test_seniority = cls.env.ref('crm_iap_mine.crm_iap_mine_seniority_2')
cls.test_crm_tags = cls.env['crm.tag'].create([
{'name': 'TestTag1'},
{'name': 'TestTag2'}
])
cls.test_request_1 = cls.env['crm.reveal.rule'].create({
'contact_filter_type': 'role',
'extra_contacts': 3,
'industry_tag_ids': cls.test_industry_tags.ids,
'lead_for': 'people',
'lead_type': 'lead',
'name': 'Test Reveal People',
'other_role_ids': cls.test_roles.ids,
'preferred_role_id': cls.test_roles[0].id,
'priority': '2',
'seniority_id': cls.test_seniority.id,
'suffix': '-ts1',
'tag_ids': [(6, 0, cls.test_crm_tags.ids)],
'team_id': cls.sales_team_1.id,
'user_id': cls.user_sales_leads.id,
})
cls.test_request_2 = cls.env['crm.reveal.rule'].create({
'contact_filter_type': 'role',
'industry_tag_ids': cls.test_industry_tags.ids,
'lead_for': 'companies',
'lead_type': 'opportunity',
'name': 'Test Reveal Companies',
'priority': '2',
'suffix': '-ts2',
'tag_ids': [(6, 0, cls.test_crm_tags.ids)],
'team_id': cls.sales_team_1.id,
'user_id': cls.user_admin.id,
})
cls.env['crm.reveal.view'].search([]).unlink()
cls.test_views = cls.env['crm.reveal.view'].create([
{'reveal_ip': '90.80.70.60',
'reveal_rule_id': cls.test_request_1.id,
'reveal_state': 'to_process',
},
{'reveal_ip': '90.80.70.61',
'reveal_rule_id': cls.test_request_1.id,
'reveal_state': 'to_process',
},
{'reveal_ip': '90.80.70.70',
'reveal_rule_id': cls.test_request_2.id,
'reveal_state': 'to_process',
}
])
cls.ip_to_rules = [
{'ip': '90.80.70.60', 'rules': cls.test_request_1},
{'ip': '90.80.70.61', 'rules': cls.test_request_1},
{'ip': '90.80.70.70', 'rules': cls.test_request_2},
]
@classmethod
def tearDownClass(cls):
cls.registry.leave_test_mode()
super().tearDownClass()
@users('user_sales_manager')
def test_reveal_error_credit(self):
# check initial state of views
self.assertEqual(
self.env['crm.reveal.view'].search([('reveal_ip', 'in', ['90.80.70.60', '90.80.70.61', '90.80.70.70'])]),
self.test_views
)
with self.mock_IAP_reveal(self.ip_to_rules, sim_error='credit'):
self.env['crm.reveal.rule']._process_lead_generation(autocommit=False)
# check initial state of views
self.assertEqual(
self.env['crm.reveal.view'].search([('reveal_ip', 'in', ['90.80.70.60', '90.80.70.61', '90.80.70.70'])]),
self.test_views
)
self.assertEqual(set(self.test_views.mapped('reveal_state')), set(['to_process']))
@users('user_sales_manager')
def test_reveal_error_jsonrpc_exception(self):
# check initial state of views
self.assertEqual(
self.env['crm.reveal.view'].search([('reveal_ip', 'in', ['90.80.70.60', '90.80.70.61', '90.80.70.70'])]),
self.test_views
)
with self.assertRaises(exceptions.UserError):
with self.mock_IAP_reveal(self.ip_to_rules, sim_error='jsonrpc_exception'):
self.env['crm.reveal.rule']._process_lead_generation(autocommit=False)
# check initial state of views
self.assertEqual(
self.env['crm.reveal.view'].search([('reveal_ip', 'in', ['90.80.70.60', '90.80.70.61', '90.80.70.70'])]),
self.test_views
)
self.assertEqual(set(self.test_views.mapped('reveal_state')), set(['to_process']))
@users('user_sales_manager')
def test_reveal_error_no_result(self):
# check initial state of views
self.assertEqual(
self.env['crm.reveal.view'].search([('reveal_ip', 'in', ['90.80.70.60', '90.80.70.61', '90.80.70.70'])]),
self.test_views
)
with self.mock_IAP_reveal(self.ip_to_rules, sim_error='no_result'):
self.env['crm.reveal.rule']._process_lead_generation(autocommit=False)
# check initial state of views
self.assertEqual(
self.env['crm.reveal.view'].search([('reveal_ip', 'in', ['90.80.70.60', '90.80.70.61', '90.80.70.70'])]),
self.test_views
)
self.assertEqual(set(self.test_views.mapped('reveal_state')), set(['not_found']))
@users('user_sales_manager')
def test_reveal(self):
country_de = self.base_de
state_de = self.de_state_st
# check initial state of views
self.assertEqual(
self.env['crm.reveal.view'].search([('reveal_ip', 'in', ['90.80.70.60', '90.80.70.61', '90.80.70.70'])]),
self.test_views
)
with self.mock_IAP_reveal(self.ip_to_rules, name_list=['Heinrich', 'Rivil', 'LidGen']):
self.env['crm.reveal.rule']._process_lead_generation(autocommit=False)
# check post state of views
self.assertEqual(
self.env['crm.reveal.view'].search([('reveal_ip', 'in', ['90.80.70.60', '90.80.70.61', '90.80.70.70'])]),
self.env['crm.reveal.view'], 'Views should have been unlinked after completion'
)
self.assertEqual(len(self._new_leads), 3, 'Number of leads should match IPs addresses')
for counter, base_name in enumerate(['Heinrich', 'Rivil', 'LidGen']):
if counter == 2:
rule = self.test_request_2
else:
rule = self.test_request_1
lead = self._new_leads.filtered(lambda lead: lead.name == '%s GmbH - %s' % (base_name, rule.suffix))
self.assertTrue(bool(lead))
# mine information
self.assertEqual(lead.type, 'lead' if rule == self.test_request_1 else 'opportunity')
self.assertEqual(lead.tag_ids, self.test_crm_tags)
self.assertEqual(lead.team_id, self.sales_team_1)
self.assertEqual(lead.user_id, self.user_sales_leads if rule == self.test_request_1 else self.user_admin)
# iap
self.assertEqual(lead.reveal_id, '123_ClearbitID_%s' % base_name, 'Ensure reveal_id is set to clearbit ID')
# clearbit information
if rule == self.test_request_1: # people-based
self.assertEqual(lead.contact_name, 'Contact %s 0' % base_name)
else:
self.assertFalse(lead.contact_name)
self.assertEqual(lead.city, 'Mönchengladbach')
self.assertEqual(lead.country_id, country_de)
if rule == self.test_request_1: # people-based
self.assertEqual(lead.email_from, 'test.contact.0@%s.example.com' % base_name,
'Lead email should be the one from first contact if search_type people is given')
else:
self.assertEqual(lead.email_from, 'info@%s.example.com' % base_name,
'Lead email should be the one from company data as there is no contact')
if rule == self.test_request_1: # people-based
self.assertEqual(lead.function, 'Doing stuff')
else:
self.assertFalse(lead.function)
self.assertFalse(lead.partner_id)
self.assertEqual(lead.partner_name, '%s GmbH legal_name' % base_name)
self.assertEqual(lead.phone, '+4930499193937')
self.assertEqual(lead.state_id, state_de)
self.assertEqual(lead.street, 'Mennrather Str. 123456')
self.assertEqual(lead.website, 'https://www.%s.de' % base_name)
self.assertEqual(lead.zip, '41179')
| 44.723077
| 8,721
|
3,463
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from contextlib import contextmanager
from unittest.mock import patch
from odoo import exceptions
from odoo.addons.crm.models.crm_lead import Lead
from odoo.addons.iap.tests.common import MockIAPEnrich
from odoo.addons.website_crm_iap_reveal.models.crm_reveal_rule import CRMRevealRule
class MockIAPReveal(MockIAPEnrich):
@classmethod
def setUpClass(cls):
super(MockIAPReveal, cls).setUpClass()
cls._new_leads = cls.env['crm.lead'].sudo()
cls.rules = False
cls.views = False
@contextmanager
def mock_IAP_reveal(self, ip_to_rules, name_list=None, default_data=None, sim_error=None):
self._new_leads = self.env['crm.lead'].sudo()
crm_lead_create_origin = Lead.create
def _crm_lead_create(model, *args, **kwargs):
res = crm_lead_create_origin(model, *args, **kwargs)
self._new_leads += res.sudo()
return res
def _iap_contact_reveal(params, timeout):
if sim_error and sim_error == 'credit':
return {'credit_error': True, 'reveal_data': []}
if sim_error and sim_error == 'jsonrpc_exception':
raise exceptions.AccessError(
'The url that this service requested returned an error. Please contact the author of the app. The url it tried to contact was [STRIPPED]'
)
if sim_error and sim_error == 'no_result':
return {'credit_error': False, 'reveal_data': []}
response = []
for counter, ip_values in enumerate(ip_to_rules):
ip, rule = ip_values['ip'], ip_values['rules']
if name_list:
base_name = name_list[counter % len(name_list)]
else:
base_name = 'heinrich_%d' % counter
iap_payload = {
'ip': ip,
'ip_time_zone': 'Europe/Berlin',
'not_found': False,
'rule_id': rule.id,
}
company_data = self._get_iap_company_data(base_name, service='reveal', add_values={'ip': ip, 'rule': rule})
if default_data:
company_data.update(default_data)
iap_payload['clearbit_id'] = company_data['clearbit_id']
iap_payload['reveal_data'] = company_data
if rule.lead_for == 'people':
people_data = self._get_iap_contact_data(base_name, service='reveal')
iap_payload['people_data'] = people_data
iap_payload['credit'] = 1 + (len(people_data) if rule.lead_for == 'people' else 0)
response.append(iap_payload)
return {
'reveal_data': response,
'credit_error': False
}
with patch.object(CRMRevealRule, '_iap_contact_reveal', side_effect=_iap_contact_reveal), \
patch.object(Lead, 'create', autospec=True, wraps=Lead, side_effect=_crm_lead_create):
yield
def _get_iap_company_data(self, base_name, service=None, add_values=None):
company_data = super(MockIAPReveal, self)._get_iap_company_data(base_name, service=service, add_values=add_values)
if service == 'reveal':
company_data['phone'] = company_data['phone_numbers'][0]
company_data['sector'] = 'Sector Info'
return company_data
| 41.722892
| 3,463
|
2,377
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import time
from odoo import models
from odoo.http import request
_logger = logging.getLogger(__name__)
class IrHttp(models.AbstractModel):
_inherit = 'ir.http'
@classmethod
def _serve_page(cls):
response = super(IrHttp, cls)._serve_page()
if response and getattr(response, 'status_code', 0) == 200 and request.env.user._is_public():
visitor_sudo = request.env['website.visitor']._get_visitor_from_request()
# We are avoiding to create a reveal_view if a lead is already
# created from another module, e.g. website_form
if not visitor_sudo or 'lead_ids' not in visitor_sudo or not visitor_sudo.lead_ids:
country_code = 'geoip' in request.session and request.session['geoip'].get('country_code')
state_code = 'geoip' in request.session and request.session['geoip'].get('region')
if country_code:
try:
url = request.httprequest.url
ip_address = request.httprequest.remote_addr
if not ip_address:
return response
website_id = request.website.id
rules_excluded = (request.httprequest.cookies.get('rule_ids') or '').split(',')
before = time.time()
new_rules_excluded = request.env['crm.reveal.view'].sudo()._create_reveal_view(website_id, url, ip_address, country_code, state_code, rules_excluded)
# even when we match, no view may have been created if this is a duplicate
_logger.info('Reveal process time: [%s], match rule: [%s?], country code: [%s], ip: [%s]',
time.time() - before, new_rules_excluded == rules_excluded, country_code,
ip_address)
if new_rules_excluded:
response.set_cookie('rule_ids', ','.join(new_rules_excluded))
except Exception:
# just in case - we never want to crash a page view
_logger.exception("Failed to process reveal rules")
return response
| 54.022727
| 2,377
|
2,772
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models
DEFAULT_REVEAL_VIEW_WEEKS_VALID = 5
class CRMRevealView(models.Model):
_name = 'crm.reveal.view'
_description = 'CRM Reveal View'
_order = 'id desc'
reveal_ip = fields.Char(string='IP Address', index=True)
reveal_rule_id = fields.Many2one('crm.reveal.rule', string='Lead Generation Rule', index=True)
reveal_state = fields.Selection([('to_process', 'To Process'), ('not_found', 'Not Found')], default='to_process', string="State", index=True)
create_date = fields.Datetime(index=True)
def init(self):
self._cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = %s', ('crm_reveal_view_ip_rule_id',))
if not self._cr.fetchone():
self._cr.execute('CREATE UNIQUE INDEX crm_reveal_view_ip_rule_id ON crm_reveal_view (reveal_rule_id,reveal_ip)')
self._cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = %s', ('crm_reveal_view_state_create_date',))
if not self._cr.fetchone():
self._cr.execute('CREATE INDEX crm_reveal_view_state_create_date ON crm_reveal_view (reveal_state,create_date)')
@api.model
def _clean_reveal_views(self):
""" Remove old views (> 1 month) """
weeks_valid = self.env['ir.config_parameter'].sudo().get_param('reveal.view_weeks_valid', DEFAULT_REVEAL_VIEW_WEEKS_VALID)
try:
weeks_valid = int(weeks_valid)
except ValueError:
weeks_valid = DEFAULT_REVEAL_VIEW_WEEKS_VALID
domain = []
domain.append(('reveal_state', '=', 'not_found'))
domain.append(('create_date', '<', fields.Datetime.to_string(datetime.date.today() - relativedelta(weeks=weeks_valid))))
self.search(domain).unlink()
def _create_reveal_view(self, website_id, url, ip_address, country_code, state_code, rules_excluded):
# we are avoiding reveal if reveal_view already created for this IP
rules = self.env['crm.reveal.rule']._match_url(website_id, url, country_code, state_code, rules_excluded)
if rules:
query = """
INSERT INTO crm_reveal_view (reveal_ip, reveal_rule_id, reveal_state, create_date)
VALUES (%s, %s, 'to_process', now() at time zone 'UTC')
ON CONFLICT DO NOTHING;
""" * len(rules)
params = []
for rule in rules:
params += [ip_address, rule['id']]
rules_excluded.append(str(rule['id']))
self.env.cr.execute(query, params)
return rules_excluded
return False
| 48.631579
| 2,772
|
18,931
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
import itertools
import logging
import re
from dateutil.relativedelta import relativedelta
import odoo
from odoo import api, fields, models, tools, _
from odoo.addons.iap.tools import iap_tools
from odoo.addons.crm.models import crm_stage
from odoo.exceptions import ValidationError
_logger = logging.getLogger(__name__)
DEFAULT_ENDPOINT = 'https://iap-services.odoo.com'
DEFAULT_REVEAL_BATCH_LIMIT = 25
DEFAULT_REVEAL_MONTH_VALID = 6
class CRMRevealRule(models.Model):
_name = 'crm.reveal.rule'
_description = 'CRM Lead Generation Rules'
_order = 'sequence'
name = fields.Char(string='Rule Name', required=True)
active = fields.Boolean(default=True)
# Website Traffic Filter
country_ids = fields.Many2many('res.country', string='Countries', help='Only visitors of following countries will be converted into leads/opportunities (using GeoIP).')
website_id = fields.Many2one('website', help='Restrict Lead generation to this website.')
state_ids = fields.Many2many('res.country.state', string='States', help='Only visitors of following states will be converted into leads/opportunities.')
regex_url = fields.Char(string='URL Expression', help='Regex to track website pages. Leave empty to track the entire website, or / to target the homepage. Example: /page* to track all the pages which begin with /page')
sequence = fields.Integer(help='Used to order the rules with same URL and countries. '
'Rules with a lower sequence number will be processed first.')
# Company Criteria Filter
industry_tag_ids = fields.Many2many('crm.iap.lead.industry', string='Industries', help='Leave empty to always match. Odoo will not create lead if no match')
filter_on_size = fields.Boolean(string="Filter on Size", default=True, help="Filter companies based on their size.")
company_size_min = fields.Integer(string='Company Size', default=0)
company_size_max = fields.Integer(default=1000)
# Contact Generation Filter
contact_filter_type = fields.Selection([('role', 'Role'), ('seniority', 'Seniority')], string="Filter On", required=True, default='role')
preferred_role_id = fields.Many2one('crm.iap.lead.role', string='Preferred Role')
other_role_ids = fields.Many2many('crm.iap.lead.role', string='Other Roles')
seniority_id = fields.Many2one('crm.iap.lead.seniority', string='Seniority')
extra_contacts = fields.Integer(string='Number of Contacts', help='This is the number of contacts to track if their role/seniority match your criteria. Their details will show up in the history thread of generated leads/opportunities. One credit is consumed per tracked contact.', default=1)
# Lead / Opportunity Data
lead_for = fields.Selection([('companies', 'Companies'), ('people', 'Companies and their Contacts')], string='Data Tracking', required=True, default='companies', help='Choose whether to track companies only or companies and their contacts')
lead_type = fields.Selection([('lead', 'Lead'), ('opportunity', 'Opportunity')], string='Type', required=True, default='opportunity')
suffix = fields.Char(string='Suffix', help='This will be appended in name of generated lead so you can identify lead/opportunity is generated with this rule')
team_id = fields.Many2one('crm.team', string='Sales Team', ondelete="set null")
tag_ids = fields.Many2many('crm.tag', string='Tags')
user_id = fields.Many2one('res.users', string='Salesperson')
priority = fields.Selection(crm_stage.AVAILABLE_PRIORITIES, string='Priority')
lead_ids = fields.One2many('crm.lead', 'reveal_rule_id', string='Generated Lead / Opportunity')
lead_count = fields.Integer(compute='_compute_lead_count', string='Number of Generated Leads')
opportunity_count = fields.Integer(compute='_compute_lead_count', string='Number of Generated Opportunity')
# This limits the number of extra contact.
# Even if more than 5 extra contacts provided service will return only 5 contacts (see service module for more)
_sql_constraints = [
('limit_extra_contacts', 'check(extra_contacts >= 1 and extra_contacts <= 5)', 'Maximum 5 contacts are allowed!'),
]
def _compute_lead_count(self):
leads = self.env['crm.lead'].read_group([
('reveal_rule_id', 'in', self.ids)
], fields=['reveal_rule_id', 'type'], groupby=['reveal_rule_id', 'type'], lazy=False)
mapping = {(lead['reveal_rule_id'][0], lead['type']): lead['__count'] for lead in leads}
for rule in self:
rule.lead_count = mapping.get((rule.id, 'lead'), 0)
rule.opportunity_count = mapping.get((rule.id, 'opportunity'), 0)
@api.constrains('regex_url')
def _check_regex_url(self):
try:
if self.regex_url:
re.compile(self.regex_url)
except Exception:
raise ValidationError(_('Enter Valid Regex.'))
@api.model
def _assert_geoip(self):
if not odoo._geoip_resolver:
message = _('Lead Generation requires a GeoIP resolver which could not be found on your system. Please consult https://pypi.org/project/GeoIP/.')
self.env['bus.bus']._sendone(self.env.user.partner_id, 'simple_notification', {
'title': _('Missing Library'),
'message': message,
'sticky': True,
'warning': True,
})
@api.model_create_multi
def create(self, vals_list):
self.clear_caches() # Clear the cache in order to recompute _get_active_rules
self._assert_geoip()
return super().create(vals_list)
def write(self, vals):
fields_set = {
'country_ids', 'regex_url', 'active'
}
if set(vals.keys()) & fields_set:
self.clear_caches() # Clear the cache in order to recompute _get_active_rules
self._assert_geoip()
return super(CRMRevealRule, self).write(vals)
def unlink(self):
self.clear_caches() # Clear the cache in order to recompute _get_active_rules
return super(CRMRevealRule, self).unlink()
def action_get_lead_tree_view(self):
action = self.env["ir.actions.actions"]._for_xml_id("crm.crm_lead_all_leads")
action['domain'] = [('id', 'in', self.lead_ids.ids), ('type', '=', 'lead')]
action['context'] = dict(self._context, create=False)
return action
def action_get_opportunity_tree_view(self):
action = self.env["ir.actions.actions"]._for_xml_id("crm.crm_lead_opportunities")
action['domain'] = [('id', 'in', self.lead_ids.ids), ('type', '=', 'opportunity')]
action['context'] = dict(self._context, create=False)
return action
@api.model
@tools.ormcache()
def _get_active_rules(self):
"""
Returns informations about the all rules.
The return is in the form :
{
'country_rules': {
'BE': [0, 1],
'US': [0]
},
'rules': [
{
'id': 0,
'regex': ***,
'website_id': 1,
'country_codes': ['BE', 'US'],
'state_codes': [('BE', False), ('US', 'NY'), ('US', 'CA')]
},
{
'id': 1,
'regex': ***,
'website_id': 1,
'country_codes': ['BE'],
'state_codes': [('BE', False)]
}
]
}
"""
country_rules = {}
rules_records = self.search([])
rules = []
# Fixes for special cases
for rule in rules_records:
regex_url = rule['regex_url']
if not regex_url:
regex_url = '.*' # for all pages if url not given
elif regex_url == '/':
regex_url = '.*/$' # for home
countries = rule.country_ids.mapped('code')
# First apply rules for any state in countries
states = [(country_id.code, False) for country_id in rule.country_ids]
if rule.state_ids:
for state_id in rule.state_ids:
if (state_id.country_id.code, False) in states:
# Remove country because rule doesn't apply to any state
states.remove((state_id.country_id.code, False))
states += [(state_id.country_id.code, state_id.code)]
rules.append({
'id': rule.id,
'regex': regex_url,
'website_id': rule.website_id.id if rule.website_id else False,
'country_codes': countries,
'state_codes': states
})
for country in countries:
country_rules = self._add_to_country(country_rules, country, len(rules) - 1)
return {
'country_rules': country_rules,
'rules': rules,
}
def _add_to_country(self, country_rules, country, rule_index):
"""
Add the rule index to the country code in the country_rules
"""
if country not in country_rules:
country_rules[country] = []
country_rules[country].append(rule_index)
return country_rules
def _match_url(self, website_id, url, country_code, state_code, rules_excluded):
"""
Return the matching rule based on the country, the website and URL.
"""
all_rules = self._get_active_rules()
rules_id = all_rules['country_rules'].get(country_code, [])
rules_matched = []
for rule_index in rules_id:
rule = all_rules['rules'][rule_index]
if ((country_code, state_code) in rule['state_codes'] or (country_code, False) in rule['state_codes'])\
and (not rule['website_id'] or rule['website_id'] == website_id)\
and str(rule['id']) not in rules_excluded\
and re.search(rule['regex'], url):
rules_matched.append(rule)
return rules_matched
@api.model
def _process_lead_generation(self, autocommit=True):
""" Cron Job for lead generation from page view """
_logger.info('Start Reveal Lead Generation')
self.env['crm.reveal.view']._clean_reveal_views()
self._unlink_unrelevant_reveal_view()
reveal_views = self._get_reveal_views_to_process()
view_count = 0
while reveal_views:
view_count += len(reveal_views)
server_payload = self._prepare_iap_payload(dict(reveal_views))
enough_credit = self._perform_reveal_service(server_payload)
if autocommit:
# auto-commit for batch processing
self._cr.commit()
if enough_credit:
reveal_views = self._get_reveal_views_to_process()
else:
reveal_views = False
_logger.info('End Reveal Lead Generation - %s views processed', view_count)
@api.model
def _unlink_unrelevant_reveal_view(self):
"""
We don't want to create the lead if in past (<6 months) we already
created lead with given IP. So, we unlink crm.reveal.view with same IP
as a already created lead.
"""
months_valid = self.env['ir.config_parameter'].sudo().get_param('reveal.lead_month_valid', DEFAULT_REVEAL_MONTH_VALID)
try:
months_valid = int(months_valid)
except ValueError:
months_valid = DEFAULT_REVEAL_MONTH_VALID
domain = []
domain.append(('reveal_ip', '!=', False))
domain.append(('create_date', '>', fields.Datetime.to_string(datetime.date.today() - relativedelta(months=months_valid))))
leads = self.env['crm.lead'].with_context(active_test=False).search(domain)
self.env['crm.reveal.view'].search([('reveal_ip', 'in', [lead.reveal_ip for lead in leads])]).unlink()
@api.model
def _get_reveal_views_to_process(self):
""" Return list of reveal rule ids grouped by IPs """
batch_limit = DEFAULT_REVEAL_BATCH_LIMIT
query = """
SELECT v.reveal_ip, array_agg(v.reveal_rule_id ORDER BY r.sequence)
FROM crm_reveal_view v
INNER JOIN crm_reveal_rule r
ON v.reveal_rule_id = r.id
WHERE v.reveal_state='to_process'
GROUP BY v.reveal_ip
LIMIT %s
"""
self.env.cr.execute(query, [batch_limit])
return self.env.cr.fetchall()
def _prepare_iap_payload(self, pgv):
""" This will prepare the page view and returns payload
Payload sample
{
ips: {
'192.168.1.1': [1,4],
'192.168.1.6': [2,4]
},
rules: {
1: {rule_data},
2: {rule_data},
4: {rule_data}
}
}
"""
new_list = list(set(itertools.chain.from_iterable(pgv.values())))
rule_records = self.browse(new_list)
return {
'ips': pgv,
'rules': rule_records._get_rules_payload()
}
def _get_rules_payload(self):
company_country = self.env.company.country_id
rule_payload = {}
for rule in self:
# accumulate all reveal_ids (separated by ',') into one list
# eg: 3 records with values: "175,176", "177" and "190,191"
# will become ['175','176','177','190','191']
reveal_ids = [
reveal_id.strip()
for reveal_ids in rule.mapped('industry_tag_ids.reveal_ids')
for reveal_id in reveal_ids.split(',')
]
data = {
'rule_id': rule.id,
'lead_for': rule.lead_for,
'countries': rule.country_ids.mapped('code'),
'filter_on_size': rule.filter_on_size,
'company_size_min': rule.company_size_min,
'company_size_max': rule.company_size_max,
'industry_tags': reveal_ids,
'user_country': company_country and company_country.code or False
}
if rule.lead_for == 'people':
data.update({
'contact_filter_type': rule.contact_filter_type,
'preferred_role': rule.preferred_role_id.reveal_id or '',
'other_roles': rule.other_role_ids.mapped('reveal_id'),
'seniority': rule.seniority_id.reveal_id or '',
'extra_contacts': rule.extra_contacts - 1
})
rule_payload[rule.id] = data
return rule_payload
def _perform_reveal_service(self, server_payload):
result = False
account_token = self.env['iap.account'].get('reveal')
params = {
'account_token': account_token.account_token,
'data': server_payload
}
result = self._iap_contact_reveal(params, timeout=300)
all_ips, done_ips = list(server_payload['ips'].keys()), []
for res in result.get('reveal_data', []):
done_ips.append(res['ip'])
if not res.get('not_found'):
lead = self._create_lead_from_response(res)
self.env['crm.reveal.view'].search([('reveal_ip', '=', res['ip'])]).unlink()
else:
views = self.env['crm.reveal.view'].search([('reveal_ip', '=', res['ip'])])
views.write({'reveal_state': 'not_found'})
views.flush()
if result.get('credit_error'):
self.env['crm.iap.lead.helpers'].notify_no_more_credit('reveal', self._name, 'reveal.already_notified')
return False
else:
# avoid loops if IAP return result is broken: otherwise some IP may create loops
views = self.env['crm.reveal.view'].search([
('reveal_ip', 'in', [ip for ip in all_ips if ip not in done_ips])
])
views.write({'reveal_state': 'not_found'})
views.flush()
# reset notified parameter to re-send credit notice if appears again
self.env['ir.config_parameter'].sudo().set_param('reveal.already_notified', False)
return True
def _iap_contact_reveal(self, params, timeout=300):
endpoint = self.env['ir.config_parameter'].sudo().get_param('reveal.endpoint', DEFAULT_ENDPOINT) + '/iap/clearbit/1/reveal'
return iap_tools.iap_jsonrpc(endpoint, params=params, timeout=timeout)
def _create_lead_from_response(self, result):
""" This method will get response from service and create the lead accordingly """
if result['rule_id']:
rule = self.browse(result['rule_id'])
else:
# Not create a lead if the information match no rule
# If there is no match, the service still returns all informations
# in order to let custom code use it.
return False
if not result['clearbit_id']:
return False
already_created_lead = self.env['crm.lead'].search([('reveal_id', '=', result['clearbit_id'])])
if already_created_lead:
_logger.info('Existing lead for this clearbit_id [%s]', result['clearbit_id'])
# Does not create a lead if the reveal_id is already known
return False
lead_vals = rule._lead_vals_from_response(result)
lead = self.env['crm.lead'].create(lead_vals)
template_values = result['reveal_data']
template_values.update({
'flavor_text': _("Opportunity created by Odoo Lead Generation"),
'people_data': result.get('people_data'),
})
lead.message_post_with_view(
'iap_mail.enrich_company',
values=template_values,
subtype_id=self.env.ref('mail.mt_note').id
)
return lead
# Methods responsible for format response data in to valid odoo lead data
def _lead_vals_from_response(self, result):
self.ensure_one()
company_data = result['reveal_data']
people_data = result.get('people_data')
lead_vals = self.env['crm.iap.lead.helpers'].lead_vals_from_response(self.lead_type, self.team_id.id, self.tag_ids.ids, self.user_id.id, company_data, people_data)
lead_vals.update({
'priority': self.priority,
'reveal_ip': result['ip'],
'reveal_rule_id': self.id,
'referred': 'Website Visitor',
'reveal_iap_credits': result['credit'],
})
if self.suffix:
lead_vals['name'] = '%s - %s' % (lead_vals['name'], self.suffix)
return lead_vals
| 45.289474
| 18,931
|
397
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class Lead(models.Model):
_inherit = 'crm.lead'
reveal_ip = fields.Char(string='IP Address')
reveal_iap_credits = fields.Integer(string='IAP Credits')
reveal_rule_id = fields.Many2one('crm.reveal.rule', string='Lead Generation Rule', index=True)
| 33.083333
| 397
|
682
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
import json
from odoo import http
from odoo.addons.website.controllers.form import WebsiteForm
from odoo.http import request
class ContactController(WebsiteForm):
def _handle_website_form(self, model_name, **kwargs):
if model_name == 'crm.lead':
# Add the ip_address to the request in order to add this to the lead
# that will be created. With this, we avoid to create a lead from
# reveal if a lead is already created from the contact form.
request.params['reveal_ip'] = request.httprequest.remote_addr
return super(ContactController, self)._handle_website_form(model_name, **kwargs)
| 37.888889
| 682
|
1,760
|
py
|
PYTHON
|
15.0
|
# -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Indonesia E-faktur',
'icon': '/l10n_id/static/description/icon.png',
'version': '1.0',
'description': """
E-Faktur Menu(Indonesia)
Format : 010.000-16.00000001
* 2 (dua) digit pertama adalah Kode Transaksi
* 1 (satu) digit berikutnya adalah Kode Status
* 3 (tiga) digit berikutnya adalah Kode Cabang
* 2 (dua) digit pertama adalah Tahun Penerbitan
* 8 (delapan) digit berikutnya adalah Nomor Urut
To be able to export customer invoices as e-Faktur,
you need to put the ranges of numbers you were assigned
by the government in Accounting > Customers > e-Faktur
When you validate an invoice, where the partner has the ID PKP
field checked, a tax number will be assigned to that invoice.
Afterwards, you can filter the invoices still to export in the
invoices list and click on Action > Download e-Faktur to download
the csv and upload it to the site of the government.
You can replace an already sent invoice by another by indicating
the replaced invoice and the new one and you can reset an invoice
you have not already sent to the government to reuse its number.
""",
'category': 'Accounting/Localizations/EDI',
'depends': ['l10n_id'],
'data': [
'security/ir.model.access.csv',
'views/account_move_views.xml',
'views/efaktur_views.xml',
'views/res_config_settings_views.xml',
'views/res_partner_views.xml',
],
'demo': [],
'installable': True,
'auto_install': True,
'license': 'LGPL-3',
}
| 40
| 1,760
|
4,654
|
py
|
PYTHON
|
15.0
|
from odoo.tests import tagged, common
from odoo.addons.l10n_id_efaktur.models.account_move import FK_HEAD_LIST, LT_HEAD_LIST, OF_HEAD_LIST, _csv_row
@tagged('post_install', '-at_install', 'post_install_l10n')
class TestIndonesianEfaktur(common.TransactionCase):
def setUp(self):
"""
1) contact with l10n_id_pkp=True, l10n_id_kode_transaksi="01"
2) tax: amount=10, type_tax_use=sale, price_include=True
3) invoice with partner_id=contact, journal=customer invoices,
"""
super().setUp()
self.maxDiff = 1500
# change company info for csv detai later
self.env.company.country_id = self.env.ref('base.id')
self.env.company.street = "test"
self.env.company.phone = "12345"
self.partner_id = self.env['res.partner'].create({"name": "l10ntest", "l10n_id_pkp": True, "l10n_id_kode_transaksi": "01", "l10n_id_nik": "12345"})
self.tax_id = self.env['account.tax'].create({"name": "test tax", "type_tax_use": "sale", "amount": 10.0, "price_include": True})
self.efaktur = self.env['l10n_id_efaktur.efaktur.range'].create({'min': '0000000000001', 'max': '0000000000010'})
self.out_invoice_1 = self.env['account.move'].create({
'move_type': 'out_invoice',
'partner_id': self.partner_id.id,
'invoice_date': '2019-05-01',
'date': '2019-05-01',
'invoice_line_ids': [
(0, 0, {'name': 'line1', 'price_unit': 110.0, 'tax_ids': self.tax_id.ids}),
],
'l10n_id_kode_transaksi': "01",
})
self.out_invoice_1.action_post()
self.out_invoice_2 = self.env['account.move'].create({
'move_type': 'out_invoice',
'partner_id': self.partner_id.id,
'invoice_date': '2019-05-01',
'date': '2019-05-01',
'invoice_line_ids': [
(0, 0, {'name': 'line1', 'price_unit': 110.11, 'quantity': 400, 'tax_ids': self.tax_id.ids})
],
'l10n_id_kode_transaksi': '01'
})
self.out_invoice_2.action_post()
def test_efaktur_csv_output_1(self):
"""
Test to ensure that the output csv data contains tax-excluded prices regardless of whether the tax configuration is tax-included or tax-excluded.
Current test is using price of 110 which is tax-included with tax of amount 10%. So the unit price listed has to be 100 whereas the original result would have 110 instead.
"""
# to check the diff when test fails
efaktur_csv_output = self.out_invoice_1._generate_efaktur_invoice(',')
output_head = '%s%s%s' % (
_csv_row(FK_HEAD_LIST, ','),
_csv_row(LT_HEAD_LIST, ','),
_csv_row(OF_HEAD_LIST, ','),
)
# remaining lines
line_4 = '"FK","01","0","0000000000001","5","2019","1/5/2019","12345","l10ntest","","100","10","0","","0","110.0","0.0","0","INV/2019/00001 12345","0"\n'
line_5 = '"OF","","","100.00","1.0","100.00","0.00","100.00","10.00","0","0"\n'
efaktur_csv_expected = output_head + line_4 + line_5
self.assertEqual(efaktur_csv_expected, efaktur_csv_output)
def test_efaktur_csv_output_decimal_place(self):
"""
Test to ensure that decimal place conversion is only done when inputting to csv
This is to test original calculation of invoice_line_total_price: invoice_line_total_price = invoice_line_unit_price * line.quantity
as invoice_line_unit_price is already converted to be tax-excluded and set to the decimal place as configured on the currency, the calculation of total could be flawed.
In this test case, the tax-included price unit is 110.11, hence tax-excluded is 100.1,
invoice_line_unit_price will be 100, if we continue with the calculation of total price, it will be 100*400 = 40000
eventhough the total is supposed to be 100.1*400 = 40040, there is a 40 discrepancy
"""
efaktur_csv_output = self.out_invoice_2._generate_efaktur_invoice(',')
output_head = '%s%s%s' % (
_csv_row(FK_HEAD_LIST, ','),
_csv_row(LT_HEAD_LIST, ','),
_csv_row(OF_HEAD_LIST, ','),
)
line_4 = '"FK","01","0","0000000000002","5","2019","1/5/2019","12345","l10ntest","","40040","4004","0","","0","44044.0","0.0","0","INV/2019/00002 12345","0"\n'
line_5 = '"OF","","","100.10","400.0","40040.00","0.00","40040.00","4004.00","0","0"\n'
efaktur_csv_expected = output_head + line_4 + line_5
self.assertEqual(efaktur_csv_expected, efaktur_csv_output)
| 52.292135
| 4,654
|
16,942
|
py
|
PYTHON
|
15.0
|
# -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
import re
from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
from odoo.tools import float_round, float_repr
FK_HEAD_LIST = ['FK', 'KD_JENIS_TRANSAKSI', 'FG_PENGGANTI', 'NOMOR_FAKTUR', 'MASA_PAJAK', 'TAHUN_PAJAK', 'TANGGAL_FAKTUR', 'NPWP', 'NAMA', 'ALAMAT_LENGKAP', 'JUMLAH_DPP', 'JUMLAH_PPN', 'JUMLAH_PPNBM', 'ID_KETERANGAN_TAMBAHAN', 'FG_UANG_MUKA', 'UANG_MUKA_DPP', 'UANG_MUKA_PPN', 'UANG_MUKA_PPNBM', 'REFERENSI', 'KODE_DOKUMEN_PENDUKUNG']
LT_HEAD_LIST = ['LT', 'NPWP', 'NAMA', 'JALAN', 'BLOK', 'NOMOR', 'RT', 'RW', 'KECAMATAN', 'KELURAHAN', 'KABUPATEN', 'PROPINSI', 'KODE_POS', 'NOMOR_TELEPON']
OF_HEAD_LIST = ['OF', 'KODE_OBJEK', 'NAMA', 'HARGA_SATUAN', 'JUMLAH_BARANG', 'HARGA_TOTAL', 'DISKON', 'DPP', 'PPN', 'TARIF_PPNBM', 'PPNBM']
def _csv_row(data, delimiter=',', quote='"'):
return quote + (quote + delimiter + quote).join([str(x).replace(quote, '\\' + quote) for x in data]) + quote + '\n'
class AccountMove(models.Model):
_inherit = "account.move"
l10n_id_tax_number = fields.Char(string="Tax Number", copy=False)
l10n_id_replace_invoice_id = fields.Many2one('account.move', string="Replace Invoice", domain="['|', '&', '&', ('state', '=', 'posted'), ('partner_id', '=', partner_id), ('reversal_move_id', '!=', False), ('state', '=', 'cancel')]", copy=False)
l10n_id_attachment_id = fields.Many2one('ir.attachment', readonly=True, copy=False)
l10n_id_csv_created = fields.Boolean('CSV Created', compute='_compute_csv_created', copy=False)
l10n_id_kode_transaksi = fields.Selection([
('01', '01 Kepada Pihak yang Bukan Pemungut PPN (Customer Biasa)'),
('02', '02 Kepada Pemungut Bendaharawan (Dinas Kepemerintahan)'),
('03', '03 Kepada Pemungut Selain Bendaharawan (BUMN)'),
('04', '04 DPP Nilai Lain (PPN 1%)'),
('05', '05 Besaran Tertentu'),
('06', '06 Penyerahan Lainnya (Turis Asing)'),
('07', '07 Penyerahan yang PPN-nya Tidak Dipungut (Kawasan Ekonomi Khusus/ Batam)'),
('08', '08 Penyerahan yang PPN-nya Dibebaskan (Impor Barang Tertentu)'),
('09', '09 Penyerahan Aktiva ( Pasal 16D UU PPN )'),
], string='Kode Transaksi', help='Dua digit pertama nomor pajak',
readonly=False, states={'posted': [('readonly', True)], 'cancel': [('readonly', True)]}, copy=False,
compute="_compute_kode_transaksi", store=True)
l10n_id_need_kode_transaksi = fields.Boolean(compute='_compute_need_kode_transaksi')
@api.onchange('l10n_id_tax_number')
def _onchange_l10n_id_tax_number(self):
for record in self:
if record.l10n_id_tax_number and record.move_type not in self.get_purchase_types():
raise UserError(_("You can only change the number manually for a Vendor Bills and Credit Notes"))
@api.depends('l10n_id_attachment_id')
def _compute_csv_created(self):
for record in self:
record.l10n_id_csv_created = bool(record.l10n_id_attachment_id)
@api.depends('partner_id')
def _compute_kode_transaksi(self):
for move in self:
move.l10n_id_kode_transaksi = move.partner_id.l10n_id_kode_transaksi
@api.depends('partner_id')
def _compute_need_kode_transaksi(self):
for move in self:
move.l10n_id_need_kode_transaksi = move.partner_id.l10n_id_pkp and not move.l10n_id_tax_number and move.move_type == 'out_invoice' and move.country_code == 'ID'
@api.constrains('l10n_id_kode_transaksi', 'line_ids')
def _constraint_kode_ppn(self):
ppn_tag = self.env.ref('l10n_id.ppn_tag')
for move in self.filtered(lambda m: m.l10n_id_kode_transaksi != '08'):
if any(ppn_tag.id in line.tax_tag_ids.ids for line in move.line_ids if line.exclude_from_invoice_tab is False and not line.display_type) \
and any(ppn_tag.id not in line.tax_tag_ids.ids for line in move.line_ids if line.exclude_from_invoice_tab is False and not line.display_type):
raise UserError(_('Cannot mix VAT subject and Non-VAT subject items in the same invoice with this kode transaksi.'))
for move in self.filtered(lambda m: m.l10n_id_kode_transaksi == '08'):
if any(ppn_tag.id in line.tax_tag_ids.ids for line in move.line_ids if line.exclude_from_invoice_tab is False and not line.display_type):
raise UserError('Kode transaksi 08 is only for non VAT subject items.')
@api.constrains('l10n_id_tax_number')
def _constrains_l10n_id_tax_number(self):
for record in self.filtered('l10n_id_tax_number'):
if record.l10n_id_tax_number != re.sub(r'\D', '', record.l10n_id_tax_number):
record.l10n_id_tax_number = re.sub(r'\D', '', record.l10n_id_tax_number)
if len(record.l10n_id_tax_number) != 16:
raise UserError(_('A tax number should have 16 digits'))
elif record.l10n_id_tax_number[:2] not in dict(self._fields['l10n_id_kode_transaksi'].selection).keys():
raise UserError(_('A tax number must begin by a valid Kode Transaksi'))
elif record.l10n_id_tax_number[2] not in ('0', '1'):
raise UserError(_('The third digit of a tax number must be 0 or 1'))
def _post(self, soft=True):
"""Set E-Faktur number after validation."""
for move in self:
if move.l10n_id_need_kode_transaksi:
if not move.l10n_id_kode_transaksi:
raise ValidationError(_('You need to put a Kode Transaksi for this partner.'))
if move.l10n_id_replace_invoice_id.l10n_id_tax_number:
if not move.l10n_id_replace_invoice_id.l10n_id_attachment_id:
raise ValidationError(_('Replacement invoice only for invoices on which the e-Faktur is generated. '))
rep_efaktur_str = move.l10n_id_replace_invoice_id.l10n_id_tax_number
move.l10n_id_tax_number = '%s1%s' % (move.l10n_id_kode_transaksi, rep_efaktur_str[3:])
else:
efaktur = self.env['l10n_id_efaktur.efaktur.range'].pop_number(move.company_id.id)
if not efaktur:
raise ValidationError(_('There is no Efaktur number available. Please configure the range you get from the government in the e-Faktur menu. '))
move.l10n_id_tax_number = '%s0%013d' % (str(move.l10n_id_kode_transaksi), efaktur)
return super()._post(soft)
def reset_efaktur(self):
"""Reset E-Faktur, so it can be use for other invoice."""
for move in self:
if move.l10n_id_attachment_id:
raise UserError(_('You have already generated the tax report for this document: %s', move.name))
self.env['l10n_id_efaktur.efaktur.range'].push_number(move.company_id.id, move.l10n_id_tax_number[3:])
move.message_post(
body='e-Faktur Reset: %s ' % (move.l10n_id_tax_number),
subject="Reset Efaktur")
move.l10n_id_tax_number = False
return True
def download_csv(self):
action = {
'type': 'ir.actions.act_url',
'url': "web/content/?model=ir.attachment&id=" + str(self.l10n_id_attachment_id.id) + "&filename_field=name&field=datas&download=true&name=" + self.l10n_id_attachment_id.name,
'target': 'self'
}
return action
def download_efaktur(self):
"""Collect the data and execute function _generate_efaktur."""
for record in self:
if record.state == 'draft':
raise ValidationError(_('Could not download E-faktur in draft state'))
if record.partner_id.l10n_id_pkp and not record.l10n_id_tax_number:
raise ValidationError(_('Connect %(move_number)s with E-faktur to download this report', move_number=record.name))
self._generate_efaktur(',')
return self.download_csv()
def _generate_efaktur_invoice(self, delimiter):
"""Generate E-Faktur for customer invoice."""
# Invoice of Customer
company_id = self.company_id
dp = company_id.currency_id.decimal_places
dp_product_id = self.env['ir.config_parameter'].sudo().get_param('sale.default_deposit_product_id')
output_head = '%s%s%s' % (
_csv_row(FK_HEAD_LIST, delimiter),
_csv_row(LT_HEAD_LIST, delimiter),
_csv_row(OF_HEAD_LIST, delimiter),
)
for move in self.filtered(lambda m: m.state == 'posted'):
eTax = move._prepare_etax()
nik = str(move.partner_id.l10n_id_nik) if not move.partner_id.vat else ''
if move.l10n_id_replace_invoice_id:
number_ref = str(move.l10n_id_replace_invoice_id.name) + " replaced by " + str(move.name) + " " + nik
else:
number_ref = str(move.name) + " " + nik
street = ', '.join([x for x in (move.partner_id.street, move.partner_id.street2) if x])
invoice_npwp = '000000000000000'
if move.partner_id.vat and len(move.partner_id.vat) >= 12:
invoice_npwp = move.partner_id.vat
elif (not move.partner_id.vat or len(move.partner_id.vat) < 12) and move.partner_id.l10n_id_nik:
invoice_npwp = move.partner_id.l10n_id_nik
invoice_npwp = invoice_npwp.replace('.', '').replace('-', '')
# Here all fields or columns based on eTax Invoice Third Party
eTax['KD_JENIS_TRANSAKSI'] = move.l10n_id_tax_number[0:2] or 0
eTax['FG_PENGGANTI'] = move.l10n_id_tax_number[2:3] or 0
eTax['NOMOR_FAKTUR'] = move.l10n_id_tax_number[3:] or 0
eTax['MASA_PAJAK'] = move.invoice_date.month
eTax['TAHUN_PAJAK'] = move.invoice_date.year
eTax['TANGGAL_FAKTUR'] = '{0}/{1}/{2}'.format(move.invoice_date.day, move.invoice_date.month, move.invoice_date.year)
eTax['NPWP'] = invoice_npwp
eTax['NAMA'] = move.partner_id.name if eTax['NPWP'] == '000000000000000' else move.partner_id.l10n_id_tax_name or move.partner_id.name
eTax['ALAMAT_LENGKAP'] = move.partner_id.contact_address.replace('\n', '') if eTax['NPWP'] == '000000000000000' else move.partner_id.l10n_id_tax_address or street
eTax['JUMLAH_DPP'] = int(float_round(move.amount_untaxed, 0)) # currency rounded to the unit
eTax['JUMLAH_PPN'] = int(float_round(move.amount_tax, 0, rounding_method="DOWN")) # tax amount ALWAYS rounded down
eTax['ID_KETERANGAN_TAMBAHAN'] = '1' if move.l10n_id_kode_transaksi == '07' else ''
eTax['REFERENSI'] = number_ref
eTax['KODE_DOKUMEN_PENDUKUNG'] = '0'
lines = move.line_ids.filtered(lambda x: x.product_id.id == int(dp_product_id) and x.price_unit < 0 and not x.display_type)
eTax['FG_UANG_MUKA'] = 0
eTax['UANG_MUKA_DPP'] = abs(float_round(sum(lines.mapped(lambda l: float_round(l.price_subtotal, 2))), 0))
eTax['UANG_MUKA_PPN'] = abs(float_round(sum(lines.mapped(lambda l: float_round(l.price_total - l.price_subtotal, 2))), 0))
fk_values_list = ['FK'] + [eTax[f] for f in FK_HEAD_LIST[1:]]
# HOW TO ADD 2 line to 1 line for free product
free, sales = [], []
for line in move.line_ids.filtered(lambda l: not l.exclude_from_invoice_tab and not l.display_type):
# *invoice_line_unit_price is price unit use for harga_satuan's column
# *invoice_line_quantity is quantity use for jumlah_barang's column
# *invoice_line_total_price is bruto price use for harga_total's column
# *invoice_line_discount_m2m is discount price use for diskon's column
# *line.price_subtotal is subtotal price use for dpp's column
# *tax_line or free_tax_line is tax price use for ppn's column
free_tax_line = tax_line = bruto_total = total_discount = 0.0
for tax in line.tax_ids:
if tax.amount > 0:
tax_line += line.price_subtotal * (tax.amount / 100.0)
discount = 1 - (line.discount / 100)
# guarantees price to be tax-excluded
invoice_line_total_price = line.price_subtotal / discount if discount else 0
invoice_line_unit_price = invoice_line_total_price / line.quantity if line.quantity else 0
line_dict = {
'KODE_OBJEK': line.product_id.default_code or '',
'NAMA': line.product_id.name or '',
'HARGA_SATUAN': float_repr(float_round(invoice_line_unit_price, dp), dp),
'JUMLAH_BARANG': line.quantity,
'HARGA_TOTAL': float_repr(float_round(invoice_line_total_price, dp), dp),
'DPP': float_round(line.price_subtotal, dp),
'product_id': line.product_id.id,
}
if line.price_subtotal < 0:
for tax in line.tax_ids:
free_tax_line += (line.price_subtotal * (tax.amount / 100.0)) * -1.0
line_dict.update({
'DISKON': float_round(invoice_line_total_price - line.price_subtotal, dp),
'PPN': float_round(free_tax_line, dp),
})
free.append(line_dict)
elif line.price_subtotal != 0.0:
invoice_line_discount_m2m = invoice_line_total_price - line.price_subtotal
line_dict.update({
'DISKON': float_round(invoice_line_discount_m2m, dp),
'PPN': float_round(tax_line, dp),
})
sales.append(line_dict)
sub_total_before_adjustment = sub_total_ppn_before_adjustment = 0.0
# We are finding the product that has affected
# by free product to adjustment the calculation
# of discount and subtotal.
# - the price total of free product will be
# included as a discount to related of product.
for sale in sales:
for f in free:
if f['product_id'] == sale['product_id']:
sale['DISKON'] = sale['DISKON'] - f['DISKON'] + f['PPN']
sale['DPP'] = sale['DPP'] + f['DPP']
tax_line = 0
for tax in line.tax_ids:
if tax.amount > 0:
tax_line += sale['DPP'] * (tax.amount / 100.0)
sale['PPN'] = int(float_round(tax_line, 0))
free.remove(f)
sub_total_before_adjustment += sale['DPP']
sub_total_ppn_before_adjustment += sale['PPN']
bruto_total += sale['DISKON']
total_discount += float_round(sale['DISKON'], 2)
# Change the values to string format after being used
sale.update({
'DPP': float_repr(sale['DPP'], dp),
'PPN': float_repr(sale['PPN'], dp),
'DISKON': float_repr(sale['DISKON'], dp),
})
output_head += _csv_row(fk_values_list, delimiter)
for sale in sales:
of_values_list = ['OF'] + [str(sale[f]) for f in OF_HEAD_LIST[1:-2]] + ['0', '0']
output_head += _csv_row(of_values_list, delimiter)
return output_head
def _prepare_etax(self):
# These values are never set
return {'JUMLAH_PPNBM': 0, 'UANG_MUKA_PPNBM': 0, 'JUMLAH_BARANG': 0, 'TARIF_PPNBM': 0, 'PPNBM': 0}
def _generate_efaktur(self, delimiter):
if self.filtered(lambda x: not x.l10n_id_kode_transaksi):
raise UserError(_('Some documents don\'t have a transaction code'))
if self.filtered(lambda x: x.move_type != 'out_invoice'):
raise UserError(_('Some documents are not Customer Invoices'))
output_head = self._generate_efaktur_invoice(delimiter)
my_utf8 = output_head.encode("utf-8")
out = base64.b64encode(my_utf8)
attachment = self.env['ir.attachment'].create({
'datas': out,
'name': 'efaktur_%s.csv' % (fields.Datetime.to_string(fields.Datetime.now()).replace(" ", "_")),
'type': 'binary',
})
for record in self:
record.message_post(attachment_ids=[attachment.id])
self.l10n_id_attachment_id = attachment.id
return {
'type': 'ir.actions.client',
'tag': 'reload',
}
| 54.828479
| 16,942
|
4,396
|
py
|
PYTHON
|
15.0
|
# -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
import re
class Efaktur(models.Model):
_name = "l10n_id_efaktur.efaktur.range"
_description = "Available E-faktur range"
company_id = fields.Many2one('res.company', required=True, default=lambda self: self.env.company)
max = fields.Char(compute='_compute_default', store=True, readonly=False)
min = fields.Char(compute='_compute_default', store=True, readonly=False)
available = fields.Integer(compute='_compute_available', store=True)
@api.model
def pop_number(self, company_id):
range = self.search([('company_id', '=', company_id)], order="min ASC", limit=1)
if not range:
return None
popped = int(range.min)
if int(range.min) >= int(range.max):
range.unlink()
else:
range.min = '%013d' % (popped + 1)
return popped
@api.model
def push_number(self, company_id, number):
return self.push_numbers(company_id, number, number)
@api.model
def push_numbers(self, company_id, min, max):
range_sup = self.search([('min', '=', '%013d' % (int(max) + 1))])
if range_sup:
range_sup.min = '%013d' % int(min)
max = range_sup.max
range_low = self.search([('max', '=', '%013d' % (int(max) - 1))])
if range_low:
range_sup.unlink()
range_low.max = '%013d' % int(max)
if not range_sup and not range_low:
self.create({
'company_id': company_id,
'max': '%013d' % int(max),
'min': '%013d' % int(min),
})
@api.constrains('min', 'max')
def _constrains_min_max(self):
for record in self:
if not len(record.min) == 13 or not len(record.max) == 13:
raise ValidationError(_("There should be 13 digits in each number."))
if record.min[:-8] != record.max[:-8]:
raise ValidationError(_("First 5 digits should be same in Start Number and End Number."))
if int(record.min[-8:]) > int(record.max[-8:]):
raise ValidationError(_("Last 8 digits of End Number should be greater than the last 8 digit of Start Number"))
if (int(record.max) - int(record.min)) > 10000:
raise ValidationError(_("The difference between the two numbers must not be greater than 10.000"))
# The number of records should always be very small, so it is ok to search in loop
if self.search([
'&', ('id', '!=', record.id), '|', '|',
'&', ('min', '<=', record.max), ('max', '>=', record.max),
'&', ('min', '<=', record.min), ('max', '>=', record.min),
'&', ('min', '>=', record.min), ('max', '<=', record.max),
]):
raise ValidationError(_('Efaktur interleaving range detected'))
@api.depends('min', 'max')
def _compute_available(self):
for record in self:
record.available = 1 + int(record.max) - int(record.min)
@api.depends('company_id')
def _compute_default(self):
for record in self:
query = """
SELECT MAX(SUBSTRING(l10n_id_tax_number FROM 4))
FROM account_move
WHERE l10n_id_tax_number IS NOT NULL
AND company_id = %s
"""
self.env.cr.execute(query, [record.company_id.id])
max_used = int(self.env.cr.fetchone()[0] or 0)
max_available = int(self.env['l10n_id_efaktur.efaktur.range'].search([('company_id', '=', record.company_id.id)], order='max DESC', limit=1).max)
record.min = record.max = '%013d' % (max(max_available, max_used) + 1)
@api.onchange('min')
def _onchange_min(self):
min_val = re.sub(r'\D', '', str(self.min)) or 0
self.min = '%013d' % int(min_val)
if not self.max or int(self.min) > int(self.max):
self.max = self.min
@api.onchange('max')
def _onchange_max(self):
max_val = re.sub(r'\D', '', str(self.max)) or 0
self.max = '%013d' % int(max_val)
if not self.min or int(self.min) > int(self.max):
self.min = self.max
| 39.603604
| 4,396
|
1,786
|
py
|
PYTHON
|
15.0
|
# -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api
class ResPartner(models.Model):
"""Inherit res.partner object to add NPWP field and Kode Transaksi"""
_inherit = "res.partner"
l10n_id_pkp = fields.Boolean(string="ID PKP", compute='_compute_l10n_id_pkp', store=True, readonly=False)
l10n_id_nik = fields.Char(string='NIK')
l10n_id_tax_address = fields.Char('Tax Address')
l10n_id_tax_name = fields.Char('Tax Name')
l10n_id_kode_transaksi = fields.Selection([
('01', '01 Kepada Pihak yang Bukan Pemungut PPN (Customer Biasa)'),
('02', '02 Kepada Pemungut Bendaharawan (Dinas Kepemerintahan)'),
('03', '03 Kepada Pemungut Selain Bendaharawan (BUMN)'),
('04', '04 DPP Nilai Lain (PPN 1%)'),
('05', '05 Besaran Tertentu'),
('06', '06 Penyerahan Lainnya (Turis Asing)'),
('07', '07 Penyerahan yang PPN-nya Tidak Dipungut (Kawasan Ekonomi Khusus/ Batam)'),
('08', '08 Penyerahan yang PPN-nya Dibebaskan (Impor Barang Tertentu)'),
('09', '09 Penyerahan Aktiva ( Pasal 16D UU PPN )'),
], string='Kode Transaksi', help='Dua digit pertama nomor pajak')
@api.depends('vat', 'country_code')
def _compute_l10n_id_pkp(self):
for record in self:
record.l10n_id_pkp = record.vat and record.country_code == 'ID'
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
l10n_id_tax_address = fields.Char('Tax Address', related='company_id.partner_id.l10n_id_tax_address', readonly=False)
l10n_id_tax_name = fields.Char('Tax Name', related='company_id.partner_id.l10n_id_tax_address', readonly=False)
| 48.27027
| 1,786
|
943
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name': 'Website Payment',
'category': 'Hidden',
'summary': 'Payment integration with website',
'version': '1.0',
'description': """
This is a bridge module that adds multi-website support for payment acquirers.
""",
'depends': [
'website',
'payment',
'portal',
],
'data': [
'data/donation_data.xml',
'views/payment_acquirer.xml',
'views/donation_templates.xml',
'views/snippets/snippets.xml',
'views/snippets/s_donation.xml',
],
'auto_install': True,
'assets': {
'website.assets_wysiwyg': [
'website_payment/static/src/snippets/s_donation/options.js',
],
'web.assets_frontend': [
'website_payment/static/src/js/website_payment_donation.js',
'website_payment/static/src/js/website_payment_form.js',
],
},
'license': 'LGPL-3',
}
| 27.735294
| 943
|
2,133
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, fields, models
class PaymentTransaction(models.Model):
_inherit = "payment.transaction"
is_donation = fields.Boolean(string="Is donation", help="Is the payment a donation")
def _finalize_post_processing(self):
super()._finalize_post_processing()
for tx in self.filtered('is_donation'):
tx._send_donation_email()
msg = [_('Payment received from donation with following details:')]
for field in ['company_id', 'partner_id', 'partner_name', 'partner_country_id', 'partner_email']:
field_name = tx._fields[field].string
value = tx[field]
if value:
if hasattr(value, 'name'):
value = value.name
msg.append('<br/>- %s: %s' % (field_name, value))
tx.payment_id._message_log(body=''.join(msg))
def _send_donation_email(self, is_internal_notification=False, comment=None, recipient_email=None):
self.ensure_one()
if is_internal_notification or self.state == 'done':
subject = _('A donation has been made on your website') if is_internal_notification else _('Donation confirmation')
body = self.env.ref('website_payment.donation_mail_body')._render({
'is_internal_notification': is_internal_notification,
'tx': self,
'comment': comment,
}, engine='ir.qweb', minimal_qcontext=True)
self.env.ref('website_payment.mail_template_donation').send_mail(
self.id, notif_layout="mail.mail_notification_light",
force_send=True,
email_values={
'email_to': recipient_email if is_internal_notification else self.partner_email,
'email_from': self.company_id.email_formatted,
'author_id': self.partner_id.id,
'subject': subject,
'body_html': body,
},
)
| 47.4
| 2,133
|
560
|
py
|
PYTHON
|
15.0
|
# coding: utf-8
from odoo import fields, models
from odoo.http import request
class PaymentAcquirer(models.Model):
_inherit = "payment.acquirer"
website_id = fields.Many2one(
"website",
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]",
ondelete="restrict",
)
def get_base_url(self):
# Give priority to url_root to handle multi-website cases
if request and request.httprequest.url_root:
return request.httprequest.url_root
return super().get_base_url()
| 28
| 560
|
404
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class Page(models.Model):
_inherit = 'website.page'
@classmethod
def _get_cached_blacklist(cls):
return super()._get_cached_blacklist() + (
# Contains a form with a dynamically added CSRF token
'data-snippet="s_donation"',
)
| 26.933333
| 404
|
339
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class AccountPayment(models.Model):
_inherit = 'account.payment'
is_donation = fields.Boolean(string="Is Donation", related="payment_transaction_id.is_donation", help="Is the payment a donation")
| 33.9
| 339
|
6,921
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import http, _
from odoo.exceptions import ValidationError
from odoo.http import request
from odoo.tools.json import scriptsafe as json_safe
from odoo.addons.payment import utils as payment_utils
from odoo.addons.payment.controllers import portal as payment_portal
class PaymentPortal(payment_portal.PaymentPortal):
@http.route('/donation/pay', type='http', methods=['GET', 'POST'], auth='public', website=True, sitemap=False)
def donation_pay(self, **kwargs):
""" Behaves like PaymentPortal.payment_pay but for donation
:param dict kwargs: As the parameters of in payment_pay, with the additional:
- str donation_options: The options settled in the donation snippet
- str donation_descriptions: The descriptions for all prefilled amounts
:return: The rendered donation form
:rtype: str
:raise: werkzeug.exceptions.NotFound if the access token is invalid
"""
kwargs['is_donation'] = True
kwargs['currency_id'] = int(kwargs.get('currency_id', request.env.company.currency_id.id))
kwargs['amount'] = float(kwargs.get('amount', 25))
kwargs['donation_options'] = kwargs.get('donation_options', json_safe.dumps(dict(customAmount="freeAmount")))
if request.env.user._is_public():
kwargs['partner_id'] = request.env.user.partner_id.id
kwargs['access_token'] = payment_utils.generate_access_token(kwargs['partner_id'], kwargs['amount'], kwargs['currency_id'])
return self.payment_pay(**kwargs)
@http.route('/donation/get_acquirer_fees', type='json', auth='public', website=True, sitemap=False)
def get_acquirer_fees(self, acquirer_ids=None, amount=None, currency_id=None, country_id=None):
acquirers_sudo = request.env['payment.acquirer'].sudo().browse(acquirer_ids)
currency = request.env['res.currency'].browse(currency_id)
country = request.env['res.country'].browse(country_id)
# Compute the fees taken by acquirers supporting the feature
fees_by_acquirer = {
acq_sudo.id: acq_sudo._compute_fees(amount, currency, country)
for acq_sudo in acquirers_sudo.filtered('fees_active')
}
return fees_by_acquirer
@http.route('/donation/transaction/<minimum_amount>', type='json', auth='public', website=True, sitemap=False)
def donation_transaction(self, amount, currency_id, partner_id, access_token, minimum_amount=0, **kwargs):
if float(amount) < float(minimum_amount):
raise ValidationError(_('Donation amount must be at least %.2f.', float(minimum_amount)))
use_public_partner = request.env.user._is_public() or not partner_id
if use_public_partner:
details = kwargs['partner_details']
if not details.get('name'):
raise ValidationError(_('Name is required.'))
if not details.get('email'):
raise ValidationError(_('Email is required.'))
if not details.get('country_id'):
raise ValidationError(_('Country is required.'))
partner_id = request.website.user_id.partner_id.id
del kwargs['partner_details']
else:
partner_id = request.env.user.partner_id.id
kwargs.pop('custom_create_values', None) # Don't allow passing arbitrary create values
tx_sudo = self._create_transaction(
amount=amount, currency_id=currency_id, partner_id=partner_id, **kwargs
)
tx_sudo.is_donation = True
if use_public_partner:
tx_sudo.update({
'partner_name': details['name'],
'partner_email': details['email'],
'partner_country_id': details['country_id'],
})
elif not tx_sudo.partner_country_id:
tx_sudo.partner_country_id = kwargs['partner_details']['country_id']
# the user can change the donation amount on the payment page,
# therefor we need to recompute the access_token
access_token = payment_utils.generate_access_token(
tx_sudo.partner_id.id, tx_sudo.amount, tx_sudo.currency_id.id
)
self._update_landing_route(tx_sudo, access_token)
# Send a notification to warn that a donation has been made
recipient_email = kwargs['donation_recipient_email']
comment = kwargs['donation_comment']
tx_sudo._send_donation_email(True, comment, recipient_email)
return tx_sudo._get_processing_values()
def _get_custom_rendering_context_values(self, donation_options=None, donation_descriptions=None, is_donation=False, **kwargs):
rendering_context = super()._get_custom_rendering_context_values(**kwargs)
if is_donation:
user_sudo = request.env.user
logged_in = not user_sudo._is_public()
# If the user is logged in, take their partner rather than the partner set in the params.
# This is something that we want, since security rules are based on the partner, and created
# tokens should not be assigned to the public user. This should have no impact on the
# transaction itself besides making reconciliation possibly more difficult (e.g. The
# transaction and invoice partners are different).
partner_sudo = user_sudo.partner_id
partner_details = {}
countries = request.env['res.country']
if logged_in:
partner_details = {
'name': partner_sudo.name,
'email': partner_sudo.email,
'country_id': partner_sudo.country_id.id,
}
countries = request.env['res.country'].sudo().search([])
descriptions = request.httprequest.form.getlist('donation_descriptions')
donation_options = json_safe.loads(donation_options) if donation_options else {}
donation_amounts = json_safe.loads(donation_options.get('donationAmounts', '[]'))
rendering_context.update({
'is_donation': True,
'partner': partner_sudo,
'transaction_route': '/donation/transaction/%s' % donation_options.get('minimumAmount', 0),
'partner_details': partner_details,
'error': {},
'countries': countries,
'donation_options': donation_options,
'donation_amounts': donation_amounts,
'donation_descriptions': descriptions,
})
return rendering_context
def _get_payment_page_template_xmlid(self, **kwargs):
if kwargs.get('is_donation'):
return 'website_payment.donation_pay'
return super()._get_payment_page_template_xmlid(**kwargs)
| 50.889706
| 6,921
|
412
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.http import request
from odoo.addons.portal.controllers.portal import CustomerPortal
class CustomerPortalPasswordPolicy(CustomerPortal):
def _prepare_portal_layout_values(self):
d = super()._prepare_portal_layout_values()
d['password_minimum_length'] = request.env['ir.config_parameter'].sudo().get_param('auth_password_policy.minlength')
return d
| 41.2
| 412
|
340
|
py
|
PYTHON
|
15.0
|
{
'name': "Password Policy support for Signup",
'depends': ['auth_password_policy', 'portal'],
'category': 'Tools',
'auto_install': True,
'data': ['views/templates.xml'],
'assets': {
'web.assets_frontend': [
'auth_password_policy_portal/static/**/*',
],
},
'license': 'LGPL-3',
}
| 26.153846
| 340
|
812
|
py
|
PYTHON
|
15.0
|
# -*- encoding: utf-8 -*-
{
'name': 'Digital Products',
'version': '0.1',
'summary': 'Sell digital products in your eCommerce store',
'category': 'Website/Website',
'description': """
Sell e-goods in your eCommerce store (e.g. webinars, articles, e-books, video tutorials).
To do so, create the product and attach the file to share via the *Files* button of the product form.
Once the order is paid, the file is made available in the order confirmation page and in the customer portal.
""",
'depends': [
'attachment_indexation',
'website_sale',
],
'installable': True,
'data': [
'views/website_sale_digital.xml',
'views/website_sale_digital_view.xml',
],
'demo': [
'data/product_demo.xml',
],
'license': 'LGPL-3',
}
| 32.48
| 812
|
294
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class Attachment(models.Model):
_inherit = ['ir.attachment']
product_downloadable = fields.Boolean("Downloadable from product portal", default=False)
| 26.727273
| 294
|
1,147
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class AccountInvoiceLine(models.Model):
_inherit = ['account.move.line']
def get_digital_purchases(self):
partner = self.env.user.partner_id
# Get paid invoices
purchases = self.sudo().search_read(
domain=[
('move_id.payment_state', 'in', ['paid', 'in_payment']),
('move_id.partner_id', '=', partner.id),
('product_id', '!=', False),
],
fields=['product_id'],
)
# Get free products
purchases += self.env['sale.order.line'].sudo().search_read(
domain=[('display_type', '=', False), ('order_id.partner_id', '=', partner.id), '|', ('price_subtotal', '=', 0.0), ('order_id.amount_total', '=', 0.0)],
fields=['product_id'],
)
# I only want product_ids, but search_read insists in giving me a list of
# (product_id: <id>, name: <product code> <template_name> <attributes>)
return [line['product_id'][0] for line in purchases]
| 35.84375
| 1,147
|
3,141
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
class ProductTemplate(models.Model):
_inherit = ['product.template']
attachment_count = fields.Integer(compute='_compute_attachment_count', string="File")
def _compute_attachment_count(self):
attachment_data = self.env['ir.attachment'].read_group([('res_model', '=', self._name), ('res_id', 'in', self.ids), ('product_downloadable', '=', True)], ['res_id'], ['res_id'])
mapped_data = dict([(data['res_id'], data['res_id_count']) for data in attachment_data])
for product_template in self:
product_template.attachment_count = mapped_data.get(product_template.id, 0)
def action_open_attachments(self):
self.ensure_one()
return {
'name': _('Digital Attachments'),
'domain': [('res_model', '=', self._name), ('res_id', '=', self.id), ('product_downloadable', '=', True)],
'res_model': 'ir.attachment',
'type': 'ir.actions.act_window',
'view_mode': 'kanban,form',
'context': "{'default_res_model': '%s','default_res_id': %d, 'default_product_downloadable': True}" % (self._name, self.id),
'help': """
<p class="o_view_nocontent_smiling_face">%s</p>
<p>%s</p>
""" % (_("Add attachments for this digital product"),
_("The attached files are the ones that will be purchased and sent to the customer.")),
}
class Product(models.Model):
_inherit = 'product.product'
attachment_count = fields.Integer(compute='_compute_attachment_count', string="File")
def _compute_attachment_count(self):
for product in self:
product.attachment_count = self.env['ir.attachment'].search_count([
'|',
'&', '&', ('res_model', '=', 'product.template'), ('res_id', '=', product.product_tmpl_id.id), ('product_downloadable', '=', True),
'&', '&', ('res_model', '=', 'product.product'), ('res_id', '=', product.id), ('product_downloadable', '=', True)])
def action_open_attachments(self):
self.ensure_one()
return {
'name': _('Digital Attachments'),
'domain': [('product_downloadable', '=', True), '|',
'&', ('res_model', '=', 'product.template'), ('res_id', '=', self.product_tmpl_id.id),
'&', ('res_model', '=', self._name), ('res_id', '=', self.id)],
'res_model': 'ir.attachment',
'type': 'ir.actions.act_window',
'view_mode': 'kanban,form',
'context': "{'default_res_model': '%s','default_res_id': %d, 'default_product_downloadable': True}" % (self._name, self.id),
'help': """
<p class="o_view_nocontent_smiling_face">%s</p>
<p>%s</p>
""" % (_("Add attachments for this digital product"),
_("The attached files are the ones that will be purchased and sent to the customer.")),
}
| 49.857143
| 3,141
|
4,767
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
import io
import os
import mimetypes
from odoo import http
from odoo.exceptions import AccessError
from odoo.http import request
from odoo.addons.sale.controllers.portal import CustomerPortal
class WebsiteSaleDigital(CustomerPortal):
orders_page = '/my/orders'
@http.route([
'/my/orders/<int:order_id>',
], type='http', auth='public', website=True)
def portal_order_page(self, order_id=None, **post):
response = super(WebsiteSaleDigital, self).portal_order_page(order_id=order_id, **post)
if not 'sale_order' in response.qcontext:
return response
order = response.qcontext['sale_order']
invoiced_lines = request.env['account.move.line'].sudo().search([('move_id', 'in', order.invoice_ids.ids), ('move_id.payment_state', 'in', ['paid', 'in_payment'])])
products = invoiced_lines.mapped('product_id') | order.order_line.filtered(lambda r: not r.price_subtotal).mapped('product_id')
if not order.amount_total:
# in that case, we should add all download links to the products
# since there is nothing to pay, so we shouldn't wait for an invoice
products = order.order_line.mapped('product_id')
Attachment = request.env['ir.attachment'].sudo()
purchased_products_attachments = {}
for product in products.filtered(lambda p: p.attachment_count):
# Search for product attachments
product_id = product.id
template = product.product_tmpl_id
att = Attachment.sudo().search_read(
domain=['|', '&', ('res_model', '=', product._name), ('res_id', '=', product_id), '&', ('res_model', '=', template._name), ('res_id', '=', template.id), ('product_downloadable', '=', True)],
fields=['name', 'write_date'],
order='write_date desc',
)
# Ignore products with no attachments
if not att:
continue
purchased_products_attachments[product_id] = att
response.qcontext.update({
'digital_attachments': purchased_products_attachments,
})
return response
@http.route([
'/my/download',
], type='http', auth='public')
def download_attachment(self, attachment_id):
# Check if this is a valid attachment id
attachment = request.env['ir.attachment'].sudo().search_read(
[('id', '=', int(attachment_id))],
["name", "datas", "mimetype", "res_model", "res_id", "type", "url"]
)
if attachment:
attachment = attachment[0]
else:
return request.redirect(self.orders_page)
try:
request.env['ir.attachment'].browse(attachment_id).check('read')
except AccessError: # The user does not have read access on the attachment.
# Check if access can be granted through their purchases.
res_model = attachment['res_model']
res_id = attachment['res_id']
digital_purchases = request.env['account.move.line'].get_digital_purchases()
if res_model == 'product.product':
purchased_product_ids = digital_purchases
elif res_model == 'product.template':
purchased_product_ids = request.env['product.product'].sudo().browse(
digital_purchases
).mapped('product_tmpl_id').ids
else:
purchased_product_ids = [] # The purchases must be related to products.
if res_id not in purchased_product_ids: # No related purchase was found.
return request.redirect(self.orders_page) # Prevent the user from downloading.
# The user has bought the product, or has the rights to the attachment
if attachment["type"] == "url":
if attachment["url"]:
return request.redirect(attachment["url"])
else:
return request.not_found()
elif attachment["datas"]:
data = io.BytesIO(base64.standard_b64decode(attachment["datas"]))
# we follow what is done in ir_http's binary_content for the extension management
extension = os.path.splitext(attachment["name"] or '')[1]
extension = extension if extension else mimetypes.guess_extension(attachment["mimetype"] or '')
filename = attachment['name']
filename = filename if os.path.splitext(filename)[1] else filename + extension
return http.send_file(data, filename=filename, as_attachment=True)
else:
return request.not_found()
| 45.836538
| 4,767
|
2,124
|
py
|
PYTHON
|
15.0
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os.path
try:
import GeoIP # Legacy
except ImportError:
GeoIP = None
try:
import geoip2
import geoip2.database
except ImportError:
geoip2 = None
class GeoIPResolver(object):
def __init__(self, fname):
self.fname = fname
try:
self._db = geoip2.database.Reader(fname)
self.version = 2
except Exception:
try:
self._db = GeoIP.open(fname, GeoIP.GEOIP_STANDARD)
self.version = 1
assert self._db.database_info is not None
except Exception:
raise ValueError('Invalid GeoIP database: %r' % fname)
def __del__(self):
if self.version == 2:
self._db.close()
@classmethod
def open(cls, fname):
if not GeoIP and not geoip2:
return None
if not os.path.exists(fname):
return None
return GeoIPResolver(fname)
def resolve(self, ip):
if self.version == 1:
return self._db.record_by_addr(ip) or {}
elif self.version == 2:
try:
r = self._db.city(ip)
except (ValueError, geoip2.errors.AddressNotFoundError):
return {}
# Compatibility with Legacy database.
# Some ips cannot be located to a specific country. Legacy DB used to locate them in
# continent instead of country. Do the same to not change behavior of existing code.
country, attr = (r.country, 'iso_code') if r.country.geoname_id else (r.continent, 'code')
return {
'city': r.city.name,
'country_code': getattr(country, attr),
'country_name': country.name,
'latitude': r.location.latitude,
'longitude': r.location.longitude,
'region': r.subdivisions[0].iso_code if r.subdivisions else None,
'time_zone': r.location.time_zone,
}
# compat
def record_by_addr(self, addr):
return self.resolve(addr)
| 32.181818
| 2,124
|
480
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Web Routing',
'summary': 'Web Routing',
'sequence': '9100',
'category': 'Hidden',
'description': """
Proposes advanced routing options not available in web or base to keep
base modules simple.
""",
'data': [
'views/http_routing_template.xml',
'views/res_lang_views.xml',
],
'depends': ['web'],
'license': 'LGPL-3',
}
| 25.263158
| 480
|
0
|
py
|
PYTHON
|
15.0
| 0
| 0
|
|
28,433
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
import logging
import os
import re
import traceback
import unicodedata
import werkzeug.exceptions
import werkzeug.routing
import werkzeug.urls
# optional python-slugify import (https://github.com/un33k/python-slugify)
try:
import slugify as slugify_lib
except ImportError:
slugify_lib = None
import odoo
from odoo import api, models, registry, exceptions, tools, http
from odoo.addons.base.models import ir_http
from odoo.addons.base.models.ir_http import RequestUID
from odoo.addons.base.models.qweb import QWebException
from odoo.http import request
from odoo.osv import expression
from odoo.tools import config, ustr, pycompat
from ..geoipresolver import GeoIPResolver
_logger = logging.getLogger(__name__)
# global resolver (GeoIP API is thread-safe, for multithreaded workers)
# This avoids blowing up open files limit
odoo._geoip_resolver = None
# ------------------------------------------------------------
# Slug API
# ------------------------------------------------------------
def _guess_mimetype(ext=False, default='text/html'):
exts = {
'.css': 'text/css',
'.less': 'text/less',
'.scss': 'text/scss',
'.js': 'text/javascript',
'.xml': 'text/xml',
'.csv': 'text/csv',
'.html': 'text/html',
}
return ext is not False and exts.get(ext, default) or exts
def slugify_one(s, max_length=0):
""" Transform a string to a slug that can be used in a url path.
This method will first try to do the job with python-slugify if present.
Otherwise it will process string by stripping leading and ending spaces,
converting unicode chars to ascii, lowering all chars and replacing spaces
and underscore with hyphen "-".
:param s: str
:param max_length: int
:rtype: str
"""
s = ustr(s)
if slugify_lib:
# There are 2 different libraries only python-slugify is supported
try:
return slugify_lib.slugify(s, max_length=max_length)
except TypeError:
pass
uni = unicodedata.normalize('NFKD', s).encode('ascii', 'ignore').decode('ascii')
slug_str = re.sub(r'[\W_]', ' ', uni).strip().lower()
slug_str = re.sub(r'[-\s]+', '-', slug_str)
return slug_str[:max_length] if max_length > 0 else slug_str
def slugify(s, max_length=0, path=False):
if not path:
return slugify_one(s, max_length=max_length)
else:
res = []
for u in s.split('/'):
if slugify_one(u, max_length=max_length) != '':
res.append(slugify_one(u, max_length=max_length))
# check if supported extension
path_no_ext, ext = os.path.splitext(s)
if ext and ext in _guess_mimetype():
res[-1] = slugify_one(path_no_ext) + ext
return '/'.join(res)
def slug(value):
if isinstance(value, models.BaseModel):
if not value.id:
raise ValueError("Cannot slug non-existent record %s" % value)
# [(id, name)] = value.name_get()
identifier, name = value.id, getattr(value, 'seo_name', False) or value.display_name
else:
# assume name_search result tuple
identifier, name = value
slugname = slugify(name or '').strip().strip('-')
if not slugname:
return str(identifier)
return "%s-%d" % (slugname, identifier)
# NOTE: as the pattern is used as it for the ModelConverter (ir_http.py), do not use any flags
_UNSLUG_RE = re.compile(r'(?:(\w{1,2}|\w[A-Za-z0-9-_]+?\w)-)?(-?\d+)(?=$|/)')
def unslug(s):
"""Extract slug and id from a string.
Always return un 2-tuple (str|None, int|None)
"""
m = _UNSLUG_RE.match(s)
if not m:
return None, None
return m.group(1), int(m.group(2))
def unslug_url(s):
""" From /blog/my-super-blog-1" to "blog/1" """
parts = s.split('/')
if parts:
unslug_val = unslug(parts[-1])
if unslug_val[1]:
parts[-1] = str(unslug_val[1])
return '/'.join(parts)
return s
# ------------------------------------------------------------
# Language tools
# ------------------------------------------------------------
def url_lang(path_or_uri, lang_code=None):
''' Given a relative URL, make it absolute and add the required lang or
remove useless lang.
Nothing will be done for absolute or invalid URL.
If there is only one language installed, the lang will not be handled
unless forced with `lang` parameter.
:param lang_code: Must be the lang `code`. It could also be something
else, such as `'[lang]'` (used for url_return).
'''
Lang = request.env['res.lang']
location = pycompat.to_text(path_or_uri).strip()
force_lang = lang_code is not None
try:
url = werkzeug.urls.url_parse(location)
except ValueError:
# e.g. Invalid IPv6 URL, `werkzeug.urls.url_parse('http://]')`
url = False
# relative URL with either a path or a force_lang
if url and not url.netloc and not url.scheme and (url.path or force_lang):
location = werkzeug.urls.url_join(request.httprequest.path, location)
lang_url_codes = [url_code for _, url_code, *_ in Lang.get_available()]
lang_code = pycompat.to_text(lang_code or request.context['lang'])
lang_url_code = Lang._lang_code_to_urlcode(lang_code)
lang_url_code = lang_url_code if lang_url_code in lang_url_codes else lang_code
if (len(lang_url_codes) > 1 or force_lang) and is_multilang_url(location, lang_url_codes):
loc, sep, qs = location.partition('?')
ps = loc.split(u'/')
default_lg = request.env['ir.http']._get_default_lang()
if ps[1] in lang_url_codes:
# Replace the language only if we explicitly provide a language to url_for
if force_lang:
ps[1] = lang_url_code
# Remove the default language unless it's explicitly provided
elif ps[1] == default_lg.url_code:
ps.pop(1)
# Insert the context language or the provided language
elif lang_url_code != default_lg.url_code or force_lang:
ps.insert(1, lang_url_code)
location = u'/'.join(ps) + sep + qs
return location
def url_for(url_from, lang_code=None, no_rewrite=False):
''' Return the url with the rewriting applied.
Nothing will be done for absolute URL, invalid URL, or short URL from 1 char.
:param url_from: The URL to convert.
:param lang_code: Must be the lang `code`. It could also be something
else, such as `'[lang]'` (used for url_return).
:param no_rewrite: don't try to match route with website.rewrite.
'''
new_url = False
# don't try to match route if we know that no rewrite has been loaded.
routing = getattr(request, 'website_routing', None) # not modular, but not overridable
if not getattr(request.env['ir.http'], '_rewrite_len', {}).get(routing):
no_rewrite = True
path, _, qs = (url_from or '').partition('?')
if (not no_rewrite and path and (
len(path) > 1
and path.startswith('/')
and '/static/' not in path
and not path.startswith('/web/')
)):
new_url, _ = request.env['ir.http'].url_rewrite(path)
new_url = new_url if not qs else new_url + '?%s' % qs
return url_lang(new_url or url_from, lang_code=lang_code)
def is_multilang_url(local_url, lang_url_codes=None):
''' Check if the given URL content is supposed to be translated.
To be considered as translatable, the URL should either:
1. Match a POST (non-GET actually) controller that is `website=True` and
either `multilang` specified to True or if not specified, with `type='http'`.
2. If not matching 1., everything not under /static/ or /web/ will be translatable
'''
if not lang_url_codes:
lang_url_codes = [url_code for _, url_code, *_ in request.env['res.lang'].get_available()]
spath = local_url.split('/')
# if a language is already in the path, remove it
if spath[1] in lang_url_codes:
spath.pop(1)
local_url = '/'.join(spath)
url = local_url.partition('#')[0].split('?')
path = url[0]
# Consider /static/ and /web/ files as non-multilang
if '/static/' in path or path.startswith('/web/'):
return False
query_string = url[1] if len(url) > 1 else None
# Try to match an endpoint in werkzeug's routing table
try:
_, func = request.env['ir.http'].url_rewrite(path, query_args=query_string)
# /page/xxx has no endpoint/func but is multilang
return (not func or (
func.routing.get('website', False)
and func.routing.get('multilang', func.routing['type'] == 'http')
))
except Exception as exception:
_logger.warning(exception)
return False
class ModelConverter(ir_http.ModelConverter):
def __init__(self, url_map, model=False, domain='[]'):
super(ModelConverter, self).__init__(url_map, model)
self.domain = domain
self.regex = _UNSLUG_RE.pattern
def to_url(self, value):
return slug(value)
def to_python(self, value):
matching = re.match(self.regex, value)
_uid = RequestUID(value=value, match=matching, converter=self)
record_id = int(matching.group(2))
env = api.Environment(request.cr, _uid, request.context)
if record_id < 0:
# limited support for negative IDs due to our slug pattern, assume abs() if not found
if not env[self.model].browse(record_id).exists():
record_id = abs(record_id)
return env[self.model].with_context(_converter_value=value).browse(record_id)
class IrHttp(models.AbstractModel):
_inherit = ['ir.http']
rerouting_limit = 10
@classmethod
def _get_converters(cls):
""" Get the converters list for custom url pattern werkzeug need to
match Rule. This override adds the website ones.
"""
return dict(
super(IrHttp, cls)._get_converters(),
model=ModelConverter,
)
@classmethod
def _get_default_lang(cls):
lang_code = request.env['ir.default'].sudo().get('res.partner', 'lang')
if lang_code:
return request.env['res.lang']._lang_get(lang_code)
return request.env['res.lang'].search([], limit=1)
@api.model
def get_frontend_session_info(self):
session_info = super(IrHttp, self).get_frontend_session_info()
IrHttpModel = request.env['ir.http'].sudo()
modules = IrHttpModel.get_translation_frontend_modules()
user_context = request.session.get_context() if request.session.uid else {}
lang = user_context.get('lang')
translation_hash = request.env['ir.translation'].get_web_translations_hash(modules, lang)
session_info.update({
'translationURL': '/website/translations',
'cache_hashes': {
'translations': translation_hash,
},
})
return session_info
@api.model
def get_translation_frontend_modules(self):
Modules = request.env['ir.module.module'].sudo()
extra_modules_domain = self._get_translation_frontend_modules_domain()
extra_modules_name = self._get_translation_frontend_modules_name()
if extra_modules_domain:
new = Modules.search(
expression.AND([extra_modules_domain, [('state', '=', 'installed')]])
).mapped('name')
extra_modules_name += new
return extra_modules_name
@classmethod
def _get_translation_frontend_modules_domain(cls):
""" Return a domain to list the domain adding web-translations and
dynamic resources that may be used frontend views
"""
return []
@classmethod
def _get_translation_frontend_modules_name(cls):
""" Return a list of module name where web-translations and
dynamic resources may be used in frontend views
"""
return ['web']
bots = "bot|crawl|slurp|spider|curl|wget|facebookexternalhit".split("|")
@classmethod
def is_a_bot(cls):
# We don't use regexp and ustr voluntarily
# timeit has been done to check the optimum method
user_agent = request.httprequest.environ.get('HTTP_USER_AGENT', '').lower()
try:
return any(bot in user_agent for bot in cls.bots)
except UnicodeDecodeError:
return any(bot in user_agent.encode('ascii', 'ignore') for bot in cls.bots)
@classmethod
def _get_frontend_langs(cls):
return [code for code, _ in request.env['res.lang'].get_installed()]
@classmethod
def get_nearest_lang(cls, lang_code):
""" Try to find a similar lang. Eg: fr_BE and fr_FR
:param lang_code: the lang `code` (en_US)
"""
if not lang_code:
return False
short_match = False
short = lang_code.partition('_')[0]
for code in cls._get_frontend_langs():
if code == lang_code:
return code
if not short_match and code.startswith(short):
short_match = code
return short_match
@classmethod
def _geoip_setup_resolver(cls):
# Lazy init of GeoIP resolver
if odoo._geoip_resolver is not None:
return
geofile = config.get('geoip_database')
try:
odoo._geoip_resolver = GeoIPResolver.open(geofile) or False
except Exception as e:
_logger.warning('Cannot load GeoIP: %s', ustr(e))
@classmethod
def _geoip_resolve(cls):
if 'geoip' not in request.session:
record = {}
if odoo._geoip_resolver and request.httprequest.remote_addr:
record = odoo._geoip_resolver.resolve(request.httprequest.remote_addr) or {}
request.session['geoip'] = record
@classmethod
def _add_dispatch_parameters(cls, func):
Lang = request.env['res.lang']
# only called for is_frontend request
if request.routing_iteration == 1:
context = dict(request.context)
path = request.httprequest.path.split('/')
is_a_bot = cls.is_a_bot()
lang_codes = [code for code, *_ in Lang.get_available()]
nearest_lang = not func and cls.get_nearest_lang(Lang._lang_get_code(path[1]))
cook_lang = request.httprequest.cookies.get('frontend_lang')
cook_lang = cook_lang in lang_codes and cook_lang
if nearest_lang:
lang = Lang._lang_get(nearest_lang)
else:
nearest_ctx_lg = not is_a_bot and cls.get_nearest_lang(request.env.context.get('lang'))
nearest_ctx_lg = nearest_ctx_lg in lang_codes and nearest_ctx_lg
preferred_lang = Lang._lang_get(cook_lang or nearest_ctx_lg)
lang = preferred_lang or cls._get_default_lang()
request.lang = lang
context['lang'] = lang._get_cached('code')
# bind modified context
request.context = context
@classmethod
def _dispatch(cls):
""" Before executing the endpoint method, add website params on request, such as
- current website (record)
- multilang support (set on cookies)
- geoip dict data are added in the session
Then follow the parent dispatching.
Reminder : Do not use `request.env` before authentication phase, otherwise the env
set on request will be created with uid=None (and it is a lazy property)
"""
request.routing_iteration = getattr(request, 'routing_iteration', 0) + 1
func = None
routing_error = None
# handle // in url
if request.httprequest.method == 'GET' and '//' in request.httprequest.path:
new_url = request.httprequest.path.replace('//', '/') + '?' + request.httprequest.query_string.decode('utf-8')
return request.redirect(new_url, code=301)
# locate the controller method
try:
rule, arguments = cls._match(request.httprequest.path)
func = rule.endpoint
request.is_frontend = func.routing.get('website', False)
except werkzeug.exceptions.NotFound as e:
# either we have a language prefixed route, either a real 404
# in all cases, website processes them exept if second element is static
# Checking static will avoid to generate an expensive 404 web page since
# most of the time the browser is loading and inexisting assets or image. A standard 404 is enough.
# Earlier check would be difficult since we don't want to break data modules
path_components = request.httprequest.path.split('/')
request.is_frontend = len(path_components) < 3 or path_components[2] != 'static' or '.' not in path_components[-1]
routing_error = e
request.is_frontend_multilang = not func or (func and request.is_frontend and func.routing.get('multilang', func.routing['type'] == 'http'))
# check authentication level
try:
if func:
cls._authenticate(func)
elif request.uid is None and request.is_frontend:
cls._auth_method_public()
except Exception as e:
return cls._handle_exception(e)
cls._geoip_setup_resolver()
cls._geoip_resolve()
# For website routes (only), add website params on `request`
if request.is_frontend:
cls._add_dispatch_parameters(func)
path = request.httprequest.path.split('/')
default_lg_id = cls._get_default_lang()
if request.routing_iteration == 1:
is_a_bot = cls.is_a_bot()
nearest_lang = not func and cls.get_nearest_lang(request.env['res.lang']._lang_get_code(path[1]))
url_lg = nearest_lang and path[1]
# The default lang should never be in the URL, and a wrong lang
# should never be in the URL.
wrong_url_lg = url_lg and (url_lg != request.lang.url_code or url_lg == default_lg_id.url_code)
# The lang is missing from the URL if multi lang is enabled for
# the route and the current lang is not the default lang.
# POST requests are excluded from this condition.
missing_url_lg = not url_lg and request.is_frontend_multilang and request.lang != default_lg_id and request.httprequest.method != 'POST'
# Bots should never be redirected when the lang is missing
# because it is the only way for them to index the default lang.
if wrong_url_lg or (missing_url_lg and not is_a_bot):
if url_lg:
path.pop(1)
if request.lang != default_lg_id:
path.insert(1, request.lang.url_code)
path = '/'.join(path) or '/'
routing_error = None
redirect = request.redirect(path + '?' + request.httprequest.query_string.decode('utf-8'))
redirect.set_cookie('frontend_lang', request.lang.code)
return redirect
elif url_lg:
request.uid = None
if request.httprequest.path == '/%s/' % url_lg:
# special case for homepage controller, mimick `_postprocess_args()` redirect
path = request.httprequest.path[:-1]
if request.httprequest.query_string:
path += '?' + request.httprequest.query_string.decode('utf-8')
return request.redirect(path, code=301)
path.pop(1)
routing_error = None
return cls.reroute('/'.join(path) or '/')
elif missing_url_lg and is_a_bot:
# Ensure that if the URL without lang is not redirected, the
# current lang is indeed the default lang, because it is the
# lang that bots should index in that case.
request.lang = default_lg_id
request.context = dict(request.context, lang=default_lg_id.code)
if request.lang == default_lg_id:
context = dict(request.context)
context['edit_translations'] = False
request.context = context
if routing_error:
return cls._handle_exception(routing_error)
# removed cache for auth public
result = super(IrHttp, cls)._dispatch()
cook_lang = request.httprequest.cookies.get('frontend_lang')
if request.is_frontend and cook_lang != request.lang._get_cached('code') and hasattr(result, 'set_cookie'):
result.set_cookie('frontend_lang', request.lang._get_cached('code'))
return result
@classmethod
def _redirect(cls, location, code=303):
if request and request.db and getattr(request, 'is_frontend', False):
location = url_for(location)
return super()._redirect(location, code)
@classmethod
def reroute(cls, path):
if not hasattr(request, 'rerouting'):
request.rerouting = [request.httprequest.path]
if path in request.rerouting:
raise Exception("Rerouting loop is forbidden")
request.rerouting.append(path)
if len(request.rerouting) > cls.rerouting_limit:
raise Exception("Rerouting limit exceeded")
request.httprequest.environ['PATH_INFO'] = path
# void werkzeug cached_property. TODO: find a proper way to do this
for key in ('full_path', 'url', 'base_url'):
request.httprequest.__dict__.pop(key, None)
# since werkzeug 2.0 `path`` became an attribute and is not a cached property anymore
if hasattr(type(request.httprequest), 'path'): # cached property
request.httprequest.__dict__.pop('path', None)
else: # direct attribute
request.httprequest.path = '/' + path.lstrip('/')
return cls._dispatch()
@classmethod
def _postprocess_args(cls, arguments, rule):
super(IrHttp, cls)._postprocess_args(arguments, rule)
try:
_, path = rule.build(arguments)
assert path is not None
except odoo.exceptions.MissingError:
return cls._handle_exception(werkzeug.exceptions.NotFound())
except Exception as e:
return cls._handle_exception(e)
if getattr(request, 'is_frontend_multilang', False) and request.httprequest.method in ('GET', 'HEAD'):
generated_path = werkzeug.urls.url_unquote_plus(path)
current_path = werkzeug.urls.url_unquote_plus(request.httprequest.path)
if generated_path != current_path:
if request.lang != cls._get_default_lang():
path = '/' + request.lang.url_code + path
if request.httprequest.query_string:
path += '?' + request.httprequest.query_string.decode('utf-8')
return request.redirect(path, code=301)
@classmethod
def _get_exception_code_values(cls, exception):
""" Return a tuple with the error code following by the values matching the exception"""
code = 500 # default code
values = dict(
exception=exception,
traceback=traceback.format_exc(),
)
if isinstance(exception, exceptions.UserError):
values['error_message'] = exception.args[0]
code = 400
if isinstance(exception, exceptions.AccessError):
code = 403
elif isinstance(exception, QWebException):
values.update(qweb_exception=exception)
if type(exception.error) == exceptions.AccessError:
code = 403
elif isinstance(exception, werkzeug.exceptions.HTTPException):
code = exception.code
values.update(
status_message=werkzeug.http.HTTP_STATUS_CODES.get(code, ''),
status_code=code,
)
return (code, values)
@classmethod
def _get_values_500_error(cls, env, values, exception):
values['view'] = env["ir.ui.view"]
return values
@classmethod
def _get_error_html(cls, env, code, values):
return code, env['ir.ui.view']._render_template('http_routing.%s' % code, values)
@classmethod
def _handle_exception(cls, exception):
is_frontend_request = bool(getattr(request, 'is_frontend', False))
if not is_frontend_request:
# Don't touch non frontend requests exception handling
return super(IrHttp, cls)._handle_exception(exception)
try:
response = super(IrHttp, cls)._handle_exception(exception)
if isinstance(response, Exception):
exception = response
else:
# if parent excplicitely returns a plain response, then we don't touch it
return response
except Exception as e:
if 'werkzeug' in config['dev_mode']:
raise e
exception = e
code, values = cls._get_exception_code_values(exception)
if code is None:
# Hand-crafted HTTPException likely coming from abort(),
# usually for a redirect response -> return it directly
return exception
if not request.uid:
cls._auth_method_public()
# We rollback the current transaction before initializing a new
# cursor to avoid potential deadlocks.
# If the current (failed) transaction was holding a lock, the new
# cursor might have to wait for this lock to be released further
# down the line. However, this will only happen after the
# request is done (and in fact it won't happen). As a result, the
# current thread/worker is frozen until its timeout is reached.
# So rolling back the transaction will release any potential lock
# and, since we are in a case where an exception was raised, the
# transaction shouldn't be committed in the first place.
request.env.cr.rollback()
with registry(request.env.cr.dbname).cursor() as cr:
env = api.Environment(cr, request.uid, request.env.context)
if code == 500:
_logger.error("500 Internal Server Error:\n\n%s", values['traceback'])
values = cls._get_values_500_error(env, values, exception)
elif code == 403:
_logger.warning("403 Forbidden:\n\n%s", values['traceback'])
elif code == 400:
_logger.warning("400 Bad Request:\n\n%s", values['traceback'])
try:
code, html = cls._get_error_html(env, code, values)
except Exception:
code, html = 418, env['ir.ui.view']._render_template('http_routing.http_error', values)
return werkzeug.wrappers.Response(html, status=code, content_type='text/html;charset=utf-8')
@api.model
@tools.ormcache('path', 'query_args')
def url_rewrite(self, path, query_args=None):
new_url = False
router = http.root.get_db_router(request.db).bind('')
endpoint = False
try:
endpoint = router.match(path, method='POST', query_args=query_args)
except werkzeug.exceptions.MethodNotAllowed:
endpoint = router.match(path, method='GET', query_args=query_args)
except werkzeug.routing.RequestRedirect as e:
# get path from http://{path}?{current query string}
new_url = e.new_url.split('?')[0][7:]
_, endpoint = self.url_rewrite(new_url, query_args)
endpoint = endpoint and [endpoint]
except werkzeug.exceptions.NotFound:
new_url = path
return new_url or path, endpoint and endpoint[0]
| 41.147612
| 28,433
|
470
|
py
|
PYTHON
|
15.0
|
# -*- coding: ascii -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models
from odoo.addons.http_routing.models.ir_http import slug, unslug_url
class IrUiView(models.Model):
_inherit = ["ir.ui.view"]
@api.model
def _prepare_qcontext(self):
qcontext = super(IrUiView, self)._prepare_qcontext()
qcontext['slug'] = slug
qcontext['unslug_url'] = unslug_url
return qcontext
| 29.375
| 470
|
894
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import http
from odoo.http import request
from odoo.addons.web.controllers.main import WebClient, Home, Session
class Routing(Home):
@http.route('/website/translations/<string:unique>', type='http', auth="public", website=True)
def get_website_translations(self, unique, lang=None, mods=None):
IrHttp = request.env['ir.http'].sudo()
modules = IrHttp.get_translation_frontend_modules()
if mods:
modules += mods.split(',')
return WebClient().translations(unique, mods=','.join(modules), lang=lang)
class SessionWebsite(Session):
@http.route('/web/session/logout', type='http', auth="none", website=True, multilang=False, sitemap=False)
def logout(self, redirect='/web'):
return super().logout(redirect=redirect)
| 37.25
| 894
|
1,048
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "Sale Matrix",
'summary': "Add variants to Sales Order through a grid entry.",
'description': """
This module allows to fill Sales Order rapidly
by choosing product variants quantity through a Grid Entry.
""",
'category': 'Sales/Sales',
'version': '1.0',
'depends': ['sale', 'product_matrix', 'sale_product_configurator'],
'data': [
'views/product_template_views.xml',
'views/sale_views.xml',
'report/sale_report_templates.xml',
],
'demo': [
'data/product_matrix_demo.xml'
],
'assets': {
'web.assets_backend': [
'sale_product_matrix/static/src/**/*',
],
'web.qunit_suite_tests': [
'sale_product_matrix/static/tests/section_and_note_widget_tests.js',
],
'web.assets_tests': [
'sale_product_matrix/static/tests/tours/**/*',
],
},
'license': 'LGPL-3',
}
| 31.757576
| 1,048
|
1,848
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import odoo.tests
from odoo.addons.product_matrix.tests import common
@odoo.tests.tagged('post_install', '-at_install')
class TestSaleMatrixUi(common.TestMatrixCommon):
"""
This test needs sale_management module to work.
"""
def test_sale_matrix_ui(self):
# Set the template as configurable by matrix.
self.matrix_template.product_add_mode = "matrix"
self.start_tour("/web", 'sale_matrix_tour', login="admin")
# Ensures some dynamic create variants have been created by the matrix
# Ensures a SO has been created with exactly x lines ...
self.assertEqual(len(self.matrix_template.product_variant_ids), 8)
self.assertEqual(len(self.matrix_template.product_variant_ids.product_template_attribute_value_ids), 6)
self.assertEqual(len(self.matrix_template.attribute_line_ids.product_template_value_ids), 8)
self.env['sale.order.line'].search([('product_id', 'in', self.matrix_template.product_variant_ids.ids)]).order_id.action_confirm()
self.matrix_template.flush()
self.assertEqual(round(self.matrix_template.sales_count, 2), 56.8)
for variant in self.matrix_template.product_variant_ids:
# 5 and 9.2 because of no variant attributes
self.assertIn(round(variant.sales_count, 2), [5, 9.2])
# Ensure no duplicate line has been created on the SO.
# NB: the *2 is because the no_variant attribute doesn't create a variant
# but still gives different order lines.
self.assertEqual(
len(self.env['sale.order.line'].search([('product_id', 'in', self.matrix_template.product_variant_ids.ids)])),
len(self.matrix_template.product_variant_ids)*2
)
| 45.073171
| 1,848
|
8,324
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class SaleOrder(models.Model):
_inherit = 'sale.order'
report_grids = fields.Boolean(
string="Print Variant Grids", default=True,
help="If set, the matrix of the products configurable by matrix will be shown on the report of the order.")
""" Matrix loading and update: fields and methods :
NOTE: The matrix functionality was done in python, server side, to avoid js
restriction. Indeed, the js framework only loads the x first lines displayed
in the client, which means in case of big matrices and lots of so_lines,
the js doesn't have access to the 41nth and following lines.
To force the loading, a 'hack' of the js framework would have been needed...
"""
grid_product_tmpl_id = fields.Many2one(
'product.template', store=False,
help="Technical field for product_matrix functionalities.")
grid_update = fields.Boolean(
default=False, store=False,
help="Whether the grid field contains a new matrix to apply or not.")
grid = fields.Char(
"Matrix local storage", store=False,
help="Technical local storage of grid. \nIf grid_update, will be loaded on the SO. \nIf not, represents the matrix to open.")
@api.onchange('grid_product_tmpl_id')
def _set_grid_up(self):
"""Save locally the matrix of the given product.template, to be used by the matrix configurator."""
if self.grid_product_tmpl_id:
self.grid_update = False
self.grid = json.dumps(self._get_matrix(self.grid_product_tmpl_id))
@api.onchange('grid')
def _apply_grid(self):
"""Apply the given list of changed matrix cells to the current SO."""
if self.grid and self.grid_update:
grid = json.loads(self.grid)
product_template = self.env['product.template'].browse(grid['product_template_id'])
product_ids = set()
dirty_cells = grid['changes']
Attrib = self.env['product.template.attribute.value']
default_so_line_vals = {}
new_lines = []
for cell in dirty_cells:
combination = Attrib.browse(cell['ptav_ids'])
no_variant_attribute_values = combination - combination._without_no_variant_attributes()
# create or find product variant from combination
product = product_template._create_product_variant(combination)
order_lines = self.order_line.filtered(
lambda line: line.product_id.id == product.id
and line.product_no_variant_attribute_value_ids.ids == no_variant_attribute_values.ids
)
# if product variant already exist in order lines
old_qty = sum(order_lines.mapped('product_uom_qty'))
qty = cell['qty']
diff = qty - old_qty
if not diff:
continue
product_ids.add(product.id)
# TODO keep qty check? cannot be 0 because we only get cell changes ...
if order_lines:
if qty == 0:
if self.state in ['draft', 'sent']:
# Remove lines if qty was set to 0 in matrix
# only if SO state = draft/sent
self.order_line -= order_lines
else:
order_lines.update({'product_uom_qty': 0.0})
else:
"""
When there are multiple lines for same product and its quantity was changed in the matrix,
An error is raised.
A 'good' strategy would be to:
* Sets the quantity of the first found line to the cell value
* Remove the other lines.
But this would remove all business logic linked to the other lines...
Therefore, it only raises an Error for now.
"""
if len(order_lines) > 1:
raise ValidationError(_("You cannot change the quantity of a product present in multiple sale lines."))
else:
order_lines[0].product_uom_qty = qty
# If we want to support multiple lines edition:
# removal of other lines.
# For now, an error is raised instead
# if len(order_lines) > 1:
# # Remove 1+ lines
# self.order_line -= order_lines[1:]
else:
if not default_so_line_vals:
OrderLine = self.env['sale.order.line']
default_so_line_vals = OrderLine.default_get(OrderLine._fields.keys())
last_sequence = self.order_line[-1:].sequence
if last_sequence:
default_so_line_vals['sequence'] = last_sequence
new_lines.append((0, 0, dict(
default_so_line_vals,
product_id=product.id,
product_uom_qty=qty,
product_no_variant_attribute_value_ids=no_variant_attribute_values.ids)
))
if product_ids:
res = False
if new_lines:
# Add new SO lines
self.update(dict(order_line=new_lines))
# Recompute prices for new/modified lines
for line in self.order_line.filtered(lambda line: line.product_id.id in product_ids):
res = line.product_id_change() or res
line._onchange_discount()
line._onchange_product_id_set_customer_lead()
return res
def _get_matrix(self, product_template):
"""Return the matrix of the given product, updated with current SOLines quantities.
:param product.template product_template:
:return: matrix to display
:rtype dict:
"""
def has_ptavs(line, sorted_attr_ids):
# TODO instead of sorting on ids, use odoo-defined order for matrix ?
ptav = line.product_template_attribute_value_ids.ids
pnav = line.product_no_variant_attribute_value_ids.ids
pav = pnav + ptav
pav.sort()
return pav == sorted_attr_ids
matrix = product_template._get_template_matrix(
company_id=self.company_id,
currency_id=self.currency_id,
display_extra_price=True)
if self.order_line:
lines = matrix['matrix']
order_lines = self.order_line.filtered(lambda line: line.product_template_id == product_template)
for line in lines:
for cell in line:
if not cell.get('name', False):
line = order_lines.filtered(lambda line: has_ptavs(line, cell['ptav_ids']))
if line:
cell.update({
'qty': sum(line.mapped('product_uom_qty'))
})
return matrix
def get_report_matrixes(self):
"""Reporting method.
:return: array of matrices to display in the report
:rtype: list
"""
matrixes = []
if self.report_grids:
grid_configured_templates = self.order_line.filtered('is_configurable_product').product_template_id.filtered(lambda ptmpl: ptmpl.product_add_mode == 'matrix')
for template in grid_configured_templates:
if len(self.order_line.filtered(lambda line: line.product_template_id == template)) > 1:
# TODO do we really want the whole matrix even if there isn't a lot of lines ??
matrixes.append(self._get_matrix(template))
return matrixes
| 47.565714
| 8,324
|
858
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, fields
class ProductTemplate(models.Model):
_inherit = 'product.template'
product_add_mode = fields.Selection([
('configurator', 'Product Configurator'),
('matrix', 'Order Grid Entry'),
], string='Add product mode', default='configurator', help="Configurator: choose attribute values to add the matching \
product variant to the order.\nGrid: add several variants at once from the grid of attribute values")
def get_single_product_variant(self):
res = super(ProductTemplate, self).get_single_product_variant()
if self.has_configurable_attributes:
res['mode'] = self.product_add_mode
else:
res['mode'] = 'configurator'
return res
| 40.857143
| 858
|
761
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Quotation Builder',
'category': 'Sales/Sales',
'summary': 'Build great quotation templates',
'website': 'https://www.odoo.com/app/sales',
'version': '1.0',
'description': "Design great quotation templates with building blocks to significantly boost your success rate.",
'depends': ['website', 'sale_management', 'website_mail'],
'data': [
'data/sale_order_template_data.xml',
'views/sale_portal_templates.xml',
'views/sale_order_template_views.xml',
'views/res_config_settings_views.xml',
'views/sale_order_views.xml',
],
'installable': True,
'license': 'LGPL-3',
}
| 36.238095
| 761
|
2,305
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.tools.translate import html_translate
class SaleOrderTemplate(models.Model):
_inherit = "sale.order.template"
website_description = fields.Html('Website Description', translate=html_translate, sanitize_attributes=False, sanitize_form=False)
def open_template(self):
self.ensure_one()
return {
'type': 'ir.actions.act_url',
'target': 'self',
'url': '/sale_quotation_builder/template/%d' % self.id
}
class SaleOrderTemplateLine(models.Model):
_inherit = "sale.order.template.line"
website_description = fields.Html('Website Description', related='product_id.product_tmpl_id.quotation_only_description', translate=html_translate, readonly=False, sanitize_form=False)
@api.onchange('product_id')
def _onchange_product_id(self):
ret = super(SaleOrderTemplateLine, self)._onchange_product_id()
if self.product_id:
self.website_description = self.product_id.quotation_description
return ret
@api.model
def create(self, values):
values = self._inject_quotation_description(values)
return super(SaleOrderTemplateLine, self).create(values)
def write(self, values):
values = self._inject_quotation_description(values)
return super(SaleOrderTemplateLine, self).write(values)
def _inject_quotation_description(self, values):
values = dict(values or {})
if not values.get('website_description') and values.get('product_id'):
product = self.env['product.product'].browse(values['product_id'])
values['website_description'] = product.quotation_description
return values
class SaleOrderTemplateOption(models.Model):
_inherit = "sale.order.template.option"
website_description = fields.Html('Website Description', translate=html_translate, sanitize_attributes=False)
@api.onchange('product_id')
def _onchange_product_id(self):
ret = super(SaleOrderTemplateOption, self)._onchange_product_id()
if self.product_id:
self.website_description = self.product_id.quotation_description
return ret
| 37.786885
| 2,305
|
3,148
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.tools.translate import html_translate
class SaleOrder(models.Model):
_inherit = 'sale.order'
website_description = fields.Html('Website Description', sanitize_attributes=False, translate=html_translate, sanitize_form=False)
@api.onchange('partner_id')
def onchange_update_description_lang(self):
if not self.sale_order_template_id:
return
else:
template = self.sale_order_template_id.with_context(lang=self.partner_id.lang)
self.website_description = template.website_description
def _compute_line_data_for_template_change(self, line):
vals = super(SaleOrder, self)._compute_line_data_for_template_change(line)
vals.update(website_description=line.website_description)
return vals
def _compute_option_data_for_template_change(self, option):
vals = super(SaleOrder, self)._compute_option_data_for_template_change(option)
vals.update(website_description=option.website_description)
return vals
@api.onchange('sale_order_template_id')
def onchange_sale_order_template_id(self):
ret = super(SaleOrder, self).onchange_sale_order_template_id()
if self.sale_order_template_id:
template = self.sale_order_template_id.with_context(lang=self.partner_id.lang)
self.website_description = template.website_description
return ret
class SaleOrderLine(models.Model):
_inherit = "sale.order.line"
website_description = fields.Html('Website Description', sanitize=False, translate=html_translate, sanitize_form=False)
@api.model
def create(self, values):
values = self._inject_quotation_description(values)
return super(SaleOrderLine, self).create(values)
def write(self, values):
values = self._inject_quotation_description(values)
return super(SaleOrderLine, self).write(values)
def _inject_quotation_description(self, values):
values = dict(values or {})
if not values.get('website_description') and values.get('product_id'):
product = self.env['product.product'].browse(values['product_id'])
values.update(website_description=product.quotation_description)
return values
class SaleOrderOption(models.Model):
_inherit = "sale.order.option"
website_description = fields.Html('Website Description', sanitize_attributes=False, translate=html_translate)
@api.onchange('product_id', 'uom_id')
def _onchange_product_id(self):
ret = super(SaleOrderOption, self)._onchange_product_id()
if self.product_id:
product = self.product_id.with_context(lang=self.order_id.partner_id.lang)
self.website_description = product.quotation_description
return ret
def _get_values_to_add_to_order(self):
values = super(SaleOrderOption, self)._get_values_to_add_to_order()
values.update(website_description=self.website_description)
return values
| 40.358974
| 3,148
|
1,162
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api
from odoo.tools.translate import html_translate
class ProductTemplate(models.Model):
_inherit = "product.template"
quotation_only_description = fields.Html('Quotation Only Description', sanitize_attributes=False,
translate=html_translate, help="The quotation description (not used on eCommerce)")
quotation_description = fields.Html('Quotation Description', compute='_compute_quotation_description',
sanitize_attributes=False, help="This field uses the Quotation Only Description if it is defined, otherwise it will try to read the eCommerce Description.")
def _compute_quotation_description(self):
for record in self:
if record.quotation_only_description:
record.quotation_description = record.quotation_only_description
elif hasattr(record, 'website_description') and record.website_description:
record.quotation_description = record.website_description
else:
record.quotation_description = ''
| 48.416667
| 1,162
|
589
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api
class ResCompany(models.Model):
_inherit = 'res.company'
@api.model
def _set_default_sale_order_template_id_if_empty(self):
template = self.env.ref('sale_quotation_builder.sale_order_template_default', raise_if_not_found=False)
if not template:
return
companies = self.sudo().search([])
for company in companies:
company.sale_order_template_id = company.sale_order_template_id or template
| 34.647059
| 589
|
823
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import http
from odoo.http import request
from odoo.addons.http_routing.models.ir_http import unslug
from odoo.addons.portal.controllers import portal
class CustomerPortal(portal.CustomerPortal):
@http.route(["/sale_quotation_builder/template/<string:template_id>"], type='http', auth="user", website=True)
def sale_quotation_builder_template_view(self, template_id, **post):
template_id = unslug(template_id)[-1]
template = request.env['sale.order.template'].browse(template_id).with_context(
allowed_company_ids=request.env.user.company_ids.ids,
)
values = {'template': template}
return request.render('sale_quotation_builder.so_template', values)
| 43.315789
| 823
|
789
|
py
|
PYTHON
|
15.0
|
{
'name': 'Barcode',
'version': '2.0',
'category': 'Hidden',
'summary': 'Scan and Parse Barcodes',
'depends': ['web'],
'data': [
'data/barcodes_data.xml',
'views/barcodes_view.xml',
'security/ir.model.access.csv',
],
'installable': True,
'auto_install': False,
'post_init_hook': '_assign_default_nomeclature_id',
'assets': {
'web.assets_backend': [
'barcodes/static/src/**/*',
],
'web.qunit_suite_tests': [
'barcodes/static/tests/barcode_tests.js',
'barcodes/static/tests/barcode_parser_tests.js',
],
'web.qunit_mobile_suite_tests': [
'barcodes/static/tests/barcode_mobile_tests.js',
],
},
'license': 'LGPL-3',
}
| 28.178571
| 789
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.