Начальное наполнение
This commit is contained in:
parent
906f001e42
commit
89cc053eb2
8
__init__.py
Normal file
8
__init__.py
Normal file
@ -0,0 +1,8 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from . import controllers
|
||||
from . import models
|
||||
from . import report
|
||||
from . import populate
|
||||
from . import wizard
|
76
__manifest__.py
Normal file
76
__manifest__.py
Normal file
@ -0,0 +1,76 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
{
|
||||
'name': 'Products & Pricelists',
|
||||
'version': '1.2',
|
||||
'category': 'Sales/Sales',
|
||||
'depends': ['base', 'mail', 'uom'],
|
||||
'description': """
|
||||
This is the base module for managing products and pricelists in Odoo.
|
||||
========================================================================
|
||||
|
||||
Products support variants, different pricing methods, vendors information,
|
||||
make to stock/order, different units of measure, packaging and properties.
|
||||
|
||||
Pricelists support:
|
||||
-------------------
|
||||
* Multiple-level of discount (by product, category, quantities)
|
||||
* Compute price based on different criteria:
|
||||
* Other pricelist
|
||||
* Cost price
|
||||
* List price
|
||||
* Vendor price
|
||||
|
||||
Pricelists preferences by product and/or partners.
|
||||
|
||||
Print product labels with barcode.
|
||||
""",
|
||||
'data': [
|
||||
'data/product_data.xml',
|
||||
'security/product_security.xml',
|
||||
'security/ir.model.access.csv',
|
||||
|
||||
'wizard/product_label_layout_views.xml',
|
||||
'views/product_tag_views.xml',
|
||||
'views/product_views.xml', # To keep after product_tag_views.xml because it depends on it.
|
||||
|
||||
'views/res_config_settings_views.xml',
|
||||
'views/product_attribute_views.xml',
|
||||
'views/product_attribute_value_views.xml',
|
||||
'views/product_category_views.xml',
|
||||
'views/product_document_views.xml',
|
||||
'views/product_packaging_views.xml',
|
||||
'views/product_pricelist_item_views.xml',
|
||||
'views/product_pricelist_views.xml',
|
||||
'views/product_supplierinfo_views.xml',
|
||||
'views/product_template_views.xml',
|
||||
'views/res_country_group_views.xml',
|
||||
'views/res_partner_views.xml',
|
||||
|
||||
'report/product_reports.xml',
|
||||
'report/product_product_templates.xml',
|
||||
'report/product_template_templates.xml',
|
||||
'report/product_packaging.xml',
|
||||
'report/product_pricelist_report_templates.xml',
|
||||
],
|
||||
'demo': [
|
||||
'data/product_demo.xml',
|
||||
],
|
||||
'installable': True,
|
||||
'assets': {
|
||||
'web.assets_backend': [
|
||||
'product/static/src/js/**/*',
|
||||
'product/static/src/product_catalog/**/*.js',
|
||||
'product/static/src/product_catalog/**/*.xml',
|
||||
'product/static/src/product_catalog/**/*.scss',
|
||||
],
|
||||
'web.report_assets_common': [
|
||||
'product/static/src/scss/report_label_sheet.scss',
|
||||
],
|
||||
'web.qunit_suite_tests': [
|
||||
'product/static/tests/**/*',
|
||||
],
|
||||
},
|
||||
'license': 'LGPL-3',
|
||||
}
|
2
controllers/__init__.py
Normal file
2
controllers/__init__.py
Normal file
@ -0,0 +1,2 @@
|
||||
from . import catalog
|
||||
from . import product_document
|
42
controllers/catalog.py
Normal file
42
controllers/catalog.py
Normal file
@ -0,0 +1,42 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo.http import request, route, Controller
|
||||
|
||||
|
||||
class ProductCatalogController(Controller):
|
||||
|
||||
@route('/product/catalog/order_lines_info', auth='user', type='json')
|
||||
def product_catalog_get_order_lines_info(self, res_model, order_id, product_ids, **kwargs):
|
||||
""" Returns products information to be shown in the catalog.
|
||||
|
||||
:param string res_model: The order model.
|
||||
:param int order_id: The order id.
|
||||
:param list product_ids: The products currently displayed in the product catalog, as a list
|
||||
of `product.product` ids.
|
||||
:rtype: dict
|
||||
:return: A dict with the following structure:
|
||||
{
|
||||
product.id: {
|
||||
'productId': int
|
||||
'quantity': float (optional)
|
||||
'price': float
|
||||
'readOnly': bool (optional)
|
||||
}
|
||||
}
|
||||
"""
|
||||
order = request.env[res_model].browse(order_id)
|
||||
return order._get_product_catalog_order_line_info(product_ids, **kwargs)
|
||||
|
||||
@route('/product/catalog/update_order_line_info', auth='user', type='json')
|
||||
def product_catalog_update_order_line_info(self, res_model, order_id, product_id, quantity=0, **kwargs):
|
||||
""" Update order line information on a given order for a given product.
|
||||
|
||||
:param string res_model: The order model.
|
||||
:param int order_id: The order id.
|
||||
:param int product_id: The product, as a `product.product` id.
|
||||
:return: The unit price price of the product, based on the pricelist of the order and
|
||||
the quantity selected.
|
||||
:rtype: float
|
||||
"""
|
||||
order = request.env[res_model].browse(order_id)
|
||||
return order._update_order_line_info(product_id, quantity, **kwargs)
|
41
controllers/product_document.py
Normal file
41
controllers/product_document.py
Normal file
@ -0,0 +1,41 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
import json
|
||||
import logging
|
||||
|
||||
from odoo import _
|
||||
from odoo.http import request, route, Controller
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ProductDocumentController(Controller):
|
||||
|
||||
@route('/product/document/upload', type='http', methods=['POST'], auth='user')
|
||||
def upload_document(self, ufile, res_model, res_id):
|
||||
if res_model not in ('product.product', 'product.template'):
|
||||
return
|
||||
|
||||
record = request.env[res_model].browse(int(res_id)).exists()
|
||||
|
||||
if not record or not record.check_access_rights('write'):
|
||||
return
|
||||
|
||||
files = request.httprequest.files.getlist('ufile')
|
||||
result = {'success': _("All files uploaded")}
|
||||
for ufile in files:
|
||||
try:
|
||||
mimetype = ufile.content_type
|
||||
request.env['product.document'].create({
|
||||
'name': ufile.filename,
|
||||
'res_model': record._name,
|
||||
'res_id': record.id,
|
||||
'company_id': record.company_id.id,
|
||||
'mimetype': mimetype,
|
||||
'raw': ufile.read(),
|
||||
})
|
||||
except Exception as e:
|
||||
logger.exception("Failed to upload document %s", ufile.filename)
|
||||
result = {'error': str(e)}
|
||||
|
||||
return json.dumps(result)
|
47
data/product_data.xml
Normal file
47
data/product_data.xml
Normal file
@ -0,0 +1,47 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<data noupdate="1">
|
||||
<record id="product_category_all" model="product.category">
|
||||
<field name="name">All</field>
|
||||
</record>
|
||||
<record id="product_category_1" model="product.category">
|
||||
<field name="parent_id" ref="product_category_all"/>
|
||||
<field name="name">Saleable</field>
|
||||
</record>
|
||||
<record id="cat_expense" model="product.category">
|
||||
<field name="parent_id" ref="product_category_all"/>
|
||||
<field name="name">Expenses</field>
|
||||
</record>
|
||||
|
||||
<!--
|
||||
Precisions
|
||||
-->
|
||||
<record forcecreate="True" id="decimal_price" model="decimal.precision">
|
||||
<field name="name">Product Price</field>
|
||||
<field name="digits">2</field>
|
||||
</record>
|
||||
<record forcecreate="True" id="decimal_discount" model="decimal.precision">
|
||||
<field name="name">Discount</field>
|
||||
<field name="digits">2</field>
|
||||
</record>
|
||||
<record forcecreate="True" id="decimal_stock_weight" model="decimal.precision">
|
||||
<field name="name">Stock Weight</field>
|
||||
<field name="digits">2</field>
|
||||
</record>
|
||||
<record forcecreate="True" id="decimal_volume" model="decimal.precision">
|
||||
<field name="name">Volume</field>
|
||||
<field name="digits">2</field>
|
||||
</record>
|
||||
<record forcecreate="True" id="decimal_product_uom" model="decimal.precision">
|
||||
<field name="name">Product Unit of Measure</field>
|
||||
<field name="digits" eval="2"/>
|
||||
</record>
|
||||
|
||||
<!--
|
||||
... to here, it should be in product_demo but we cant just move it
|
||||
there yet otherwise people who have installed the server (even with the without-demo
|
||||
parameter) will see those record just disappear.
|
||||
-->
|
||||
|
||||
</data>
|
||||
</odoo>
|
838
data/product_demo.xml
Normal file
838
data/product_demo.xml
Normal file
@ -0,0 +1,838 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<data noupdate="1">
|
||||
<!-- We want to activate product variant by default for easier demoing. -->
|
||||
<record id="base.group_user" model="res.groups">
|
||||
<field name="implied_ids" eval="[(4, ref('product.group_product_variant'))]"/>
|
||||
</record>
|
||||
|
||||
<record id="product_category_2" model="product.category">
|
||||
<field name="parent_id" ref="product.product_category_all"/>
|
||||
<field name="name">Internal</field>
|
||||
</record>
|
||||
<record id="product_category_3" model="product.category">
|
||||
<field name="parent_id" ref="product.product_category_1"/>
|
||||
<field name="name">Services</field>
|
||||
</record>
|
||||
<record id="product_category_6" model="product.category">
|
||||
<field name="parent_id" ref="product.product_category_3"/>
|
||||
<field name="name">Saleable</field>
|
||||
</record>
|
||||
<record id="product_category_4" model="product.category">
|
||||
<field name="parent_id" ref="product.product_category_1"/>
|
||||
<field name="name">Software</field>
|
||||
</record>
|
||||
<record id="product_category_5" model="product.category">
|
||||
<field name="parent_id" ref="product_category_1"/>
|
||||
<field name="name">Office Furniture</field>
|
||||
</record>
|
||||
<record id="product_category_consumable" model="product.category">
|
||||
<field name="parent_id" ref="product_category_all"/>
|
||||
<field name="name">Consumable</field>
|
||||
</record>
|
||||
|
||||
<!-- Expensable products -->
|
||||
<record id="expense_product" model="product.product">
|
||||
<field name="name">Restaurant Expenses</field>
|
||||
<field name="list_price">14.0</field>
|
||||
<field name="standard_price">8.0</field>
|
||||
<field name="detailed_type">service</field>
|
||||
<field name="categ_id" ref="product.cat_expense"/>
|
||||
</record>
|
||||
|
||||
<record id="expense_hotel" model="product.product">
|
||||
<field name="name">Hotel Accommodation</field>
|
||||
<field name="list_price">400.0</field>
|
||||
<field name="standard_price">400.0</field>
|
||||
<field name="detailed_type">service</field>
|
||||
<field name="uom_id" ref="uom.product_uom_day"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_day"/>
|
||||
<field name="categ_id" ref="cat_expense"/>
|
||||
</record>
|
||||
|
||||
<!-- Service products -->
|
||||
<record id="product_product_1" model="product.product">
|
||||
<field name="name">Virtual Interior Design</field>
|
||||
<field name="categ_id" ref="product_category_3"/>
|
||||
<field name="standard_price">20.5</field>
|
||||
<field name="list_price">30.75</field>
|
||||
<field name="detailed_type">service</field>
|
||||
<field name="uom_id" ref="uom.product_uom_hour"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_hour"/>
|
||||
</record>
|
||||
|
||||
<record id="product_product_2" model="product.product">
|
||||
<field name="name">Virtual Home Staging</field>
|
||||
<field name="categ_id" ref="product_category_3"/>
|
||||
<field name="standard_price">25.5</field>
|
||||
<field name="list_price">38.25</field>
|
||||
<field name="detailed_type">service</field>
|
||||
<field name="uom_id" ref="uom.product_uom_hour"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_hour"/>
|
||||
</record>
|
||||
|
||||
<!-- Physical Products -->
|
||||
|
||||
<record id="product_delivery_01" model="product.product">
|
||||
<field name="name">Office Chair</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="standard_price">55.0</field>
|
||||
<field name="list_price">70.0</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="default_code">FURN_7777</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_chair.jpg"/>
|
||||
</record>
|
||||
|
||||
<record id="product_delivery_02" model="product.product">
|
||||
<field name="name">Office Lamp</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="standard_price">35.0</field>
|
||||
<field name="list_price">40.0</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="default_code">FURN_8888</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_lamp.png"/>
|
||||
</record>
|
||||
|
||||
<record id="product_order_01" model="product.product">
|
||||
<field name="name">Office Design Software</field>
|
||||
<field name="categ_id" ref="product_category_4"/>
|
||||
<field name="standard_price">235.0</field>
|
||||
<field name="list_price">280.0</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="default_code">FURN_9999</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_product_43-image.jpg"/>
|
||||
</record>
|
||||
|
||||
<record id="product_product_3" model="product.product">
|
||||
<field name="name">Desk Combination</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="list_price">450.0</field>
|
||||
<field name="standard_price">300.0</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="description_sale">Desk combination, black-brown: chair + desk + drawer.</field>
|
||||
<field name="default_code">FURN_7800</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_product_3-image.jpg"/>
|
||||
</record>
|
||||
|
||||
<!-- Variants -->
|
||||
|
||||
<record id="product_attribute_1" model="product.attribute">
|
||||
<field name="name">Legs</field>
|
||||
<field name="sequence">10</field>
|
||||
</record>
|
||||
<record id="product_attribute_value_1" model="product.attribute.value">
|
||||
<field name="name">Steel</field>
|
||||
<field name="attribute_id" ref="product_attribute_1"/>
|
||||
<field name="sequence">1</field>
|
||||
</record>
|
||||
<record id="product_attribute_value_2" model="product.attribute.value">
|
||||
<field name="name">Aluminium</field>
|
||||
<field name="attribute_id" ref="product_attribute_1"/>
|
||||
<field name="sequence">2</field>
|
||||
</record>
|
||||
|
||||
<record id="product_attribute_2" model="product.attribute">
|
||||
<field name="name">Color</field>
|
||||
<field name="sequence">20</field>
|
||||
</record>
|
||||
<record id="product_attribute_value_3" model="product.attribute.value">
|
||||
<field name="name">White</field>
|
||||
<field name="attribute_id" ref="product_attribute_2"/>
|
||||
<field name="sequence">1</field>
|
||||
</record>
|
||||
<record id="product_attribute_value_4" model="product.attribute.value">
|
||||
<field name="name">Black</field>
|
||||
<field name="attribute_id" ref="product_attribute_2"/>
|
||||
<field name="sequence">2</field>
|
||||
</record>
|
||||
|
||||
<record id="product_attribute_3" model="product.attribute">
|
||||
<field name="name">Duration</field>
|
||||
<field name="sequence">30</field>
|
||||
</record>
|
||||
<record id="product_attribute_value_5" model="product.attribute.value">
|
||||
<field name="name">1 year</field>
|
||||
<field name="attribute_id" ref="product_attribute_3"/>
|
||||
</record>
|
||||
<record id="product_attribute_value_6" model="product.attribute.value">
|
||||
<field name="name">2 year</field>
|
||||
<field name="attribute_id" ref="product_attribute_3"/>
|
||||
</record>
|
||||
|
||||
<record id="product_product_4_product_template" model="product.template">
|
||||
<field name="name">Customizable Desk</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="standard_price">500.0</field>
|
||||
<field name="list_price">750.0</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="description_sale">160x80cm, with large legs.</field>
|
||||
</record>
|
||||
|
||||
<record id="product_product_4_product_template_document" model="product.document">
|
||||
<field name="name">Customizable Desk Document.pdf</field>
|
||||
<field name="datas" type="base64" file="product/static/demo/customizable_desk_document.pdf"/>
|
||||
<field name="mimetype">application/pdf</field>
|
||||
<field name="res_model">product.template</field>
|
||||
<field name="res_id" ref="product.product_product_4_product_template"/>
|
||||
</record>
|
||||
|
||||
<!-- the product template attribute lines have to be defined before creating the variants -->
|
||||
<record id="product_4_attribute_1_product_template_attribute_line" model="product.template.attribute.line">
|
||||
<field name="product_tmpl_id" ref="product_product_4_product_template"/>
|
||||
<field name="attribute_id" ref="product_attribute_1"/>
|
||||
<field name="value_ids" eval="[(6, 0, [ref('product.product_attribute_value_1'), ref('product.product_attribute_value_2')])]"/>
|
||||
</record>
|
||||
<record id="product_4_attribute_2_product_template_attribute_line" model="product.template.attribute.line">
|
||||
<field name="product_tmpl_id" ref="product_product_4_product_template"/>
|
||||
<field name="attribute_id" ref="product_attribute_2"/>
|
||||
<field name="value_ids" eval="[(6, 0, [ref('product.product_attribute_value_3'), ref('product.product_attribute_value_4')])]"/>
|
||||
</record>
|
||||
|
||||
<!--
|
||||
Handle automatically created product.template.attribute.value.
|
||||
Meaning that the combination between the "customizable desk" and the attribute value "black" will be materialized
|
||||
into a "product.template.attribute.value" with the ref "product.product_4_attribute_1_value_1".
|
||||
This will allow setting fields like "price_extra" and "exclude_for"
|
||||
-->
|
||||
<function model="ir.model.data" name="_update_xmlids">
|
||||
<value model="base" eval="[{
|
||||
'xml_id': 'product.product_4_attribute_1_value_1',
|
||||
'record': obj().env.ref('product.product_4_attribute_1_product_template_attribute_line').product_template_value_ids[0],
|
||||
'noupdate': True,
|
||||
}, {
|
||||
'xml_id': 'product.product_4_attribute_1_value_2',
|
||||
'record': obj().env.ref('product.product_4_attribute_1_product_template_attribute_line').product_template_value_ids[1],
|
||||
'noupdate': True,
|
||||
}, {
|
||||
'xml_id': 'product.product_4_attribute_2_value_1',
|
||||
'record': obj().env.ref('product.product_4_attribute_2_product_template_attribute_line').product_template_value_ids[0],
|
||||
'noupdate': True,
|
||||
}, {
|
||||
'xml_id': 'product.product_4_attribute_2_value_2',
|
||||
'record': obj().env.ref('product.product_4_attribute_2_product_template_attribute_line').product_template_value_ids[1],
|
||||
'noupdate': True,
|
||||
},]"/>
|
||||
</function>
|
||||
|
||||
<function model="ir.model.data" name="_update_xmlids">
|
||||
<value model="base" eval="[{
|
||||
'xml_id': 'product.product_product_4',
|
||||
'record': obj().env.ref('product.product_product_4_product_template')._get_variant_for_combination(obj().env.ref('product.product_4_attribute_1_value_1') + obj().env.ref('product.product_4_attribute_2_value_1')),
|
||||
'noupdate': True,
|
||||
}, {
|
||||
'xml_id': 'product.product_product_4b',
|
||||
'record': obj().env.ref('product.product_product_4_product_template')._get_variant_for_combination(obj().env.ref('product.product_4_attribute_1_value_1') + obj().env.ref('product.product_4_attribute_2_value_2')),
|
||||
'noupdate': True,
|
||||
}, {
|
||||
'xml_id': 'product.product_product_4c',
|
||||
'record': obj().env.ref('product.product_product_4_product_template')._get_variant_for_combination(obj().env.ref('product.product_4_attribute_1_value_2') + obj().env.ref('product.product_4_attribute_2_value_1')),
|
||||
'noupdate': True,
|
||||
},]"/>
|
||||
</function>
|
||||
|
||||
<record id="product_product_4" model="product.product">
|
||||
<field name="default_code">FURN_0096</field>
|
||||
<field name="standard_price">500.0</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/table02.jpg"/>
|
||||
</record>
|
||||
<record id="product_product_4b" model="product.product">
|
||||
<field name="default_code">FURN_0097</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="standard_price">500.0</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/table04.jpg"/>
|
||||
</record>
|
||||
<record id="product_product_4c" model="product.product">
|
||||
<field name="default_code">FURN_0098</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="standard_price">500.0</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/table03.jpg"/>
|
||||
</record>
|
||||
|
||||
<record id="product_product_5" model="product.product">
|
||||
<field name="name">Corner Desk Right Sit</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="standard_price">600.0</field>
|
||||
<field name="list_price">147.0</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="default_code">E-COM06</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_product_5-image.jpg"/>
|
||||
</record>
|
||||
|
||||
<record id="product_product_6" model="product.product">
|
||||
<field name="name">Large Cabinet</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="standard_price">800.0</field>
|
||||
<field name="list_price">320.0</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="default_code">E-COM07</field>
|
||||
<field name='weight'>0.330</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_product_6-image.jpg"/>
|
||||
</record>
|
||||
|
||||
<record id="product_product_7" model="product.product">
|
||||
<field name="name">Storage Box</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="standard_price">14.0</field>
|
||||
<field name="list_price">15.8</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="default_code">E-COM08</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_product_7-image.png"/>
|
||||
</record>
|
||||
|
||||
<record id="product_product_8" model="product.product">
|
||||
<field name="name">Large Desk</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="standard_price">1299.0</field>
|
||||
<field name="list_price">1799.0</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="default_code">E-COM09</field>
|
||||
<field name='weight'>9.54</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_product_8-image.png"/>
|
||||
</record>
|
||||
|
||||
<record id="product_product_9" model="product.product">
|
||||
<field name="name">Pedal Bin</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="standard_price">10.0</field>
|
||||
<field name="list_price">47.0</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="default_code">E-COM10</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_product_9-image.jpg"/>
|
||||
</record>
|
||||
|
||||
<record id="product_product_10" model="product.product">
|
||||
<field name="name">Cabinet with Doors</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="standard_price">120.50</field>
|
||||
<field name="list_price">140</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="default_code">E-COM11</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_product_10-image.jpg"/>
|
||||
</record>
|
||||
|
||||
<record id="product_product_11_product_template" model="product.template">
|
||||
<field name="name">Conference Chair</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="standard_price">28</field>
|
||||
<field name="list_price">33</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_product_11-image.png"/>
|
||||
</record>
|
||||
|
||||
<!-- the product template attribute lines have to be defined before creating the variants -->
|
||||
<record id="product_11_attribute_1_product_template_attribute_line" model="product.template.attribute.line">
|
||||
<field name="product_tmpl_id" ref="product_product_11_product_template"/>
|
||||
<field name="attribute_id" ref="product_attribute_1"/>
|
||||
<field name="value_ids" eval="[(6,0,[ref('product.product_attribute_value_1'), ref('product.product_attribute_value_2')])]"/>
|
||||
</record>
|
||||
|
||||
<function model="ir.model.data" name="_update_xmlids">
|
||||
<value model="base" eval="[{
|
||||
'xml_id': 'product.product_11_attribute_1_value_1',
|
||||
'record': obj().env.ref('product.product_11_attribute_1_product_template_attribute_line').product_template_value_ids[0],
|
||||
'noupdate': True,
|
||||
}, {
|
||||
'xml_id': 'product.product_11_attribute_1_value_2',
|
||||
'record': obj().env.ref('product.product_11_attribute_1_product_template_attribute_line').product_template_value_ids[1],
|
||||
'noupdate': True,
|
||||
}]"/>
|
||||
</function>
|
||||
|
||||
<function model="ir.model.data" name="_update_xmlids">
|
||||
<value model="base" eval="[{
|
||||
'xml_id': 'product.product_product_11',
|
||||
'record': obj().env.ref('product.product_product_11_product_template')._get_variant_for_combination(obj().env.ref('product.product_11_attribute_1_value_1')),
|
||||
'noupdate': True,
|
||||
}, {
|
||||
'xml_id': 'product.product_product_11b',
|
||||
'record': obj().env.ref('product.product_product_11_product_template')._get_variant_for_combination(obj().env.ref('product.product_11_attribute_1_value_2')),
|
||||
'noupdate': True,
|
||||
},]"/>
|
||||
</function>
|
||||
|
||||
<record id="product_product_11" model="product.product">
|
||||
<field name="default_code">E-COM12</field>
|
||||
<field name="weight">0.01</field>
|
||||
</record>
|
||||
<record id="product_product_11b" model="product.product">
|
||||
<field name="default_code">E-COM13</field>
|
||||
<field name="weight">0.01</field>
|
||||
</record>
|
||||
|
||||
<record id="product.product_4_attribute_1_value_2" model="product.template.attribute.value">
|
||||
<field name="price_extra">50.40</field>
|
||||
</record>
|
||||
|
||||
<record id="product.product_11_attribute_1_value_2" model="product.template.attribute.value">
|
||||
<field name="price_extra">6.40</field>
|
||||
</record>
|
||||
|
||||
<record id="product_template_attribute_exclusion_1" model="product.template.attribute.exclusion">
|
||||
<field name="product_tmpl_id" ref="product.product_product_4_product_template" />
|
||||
<field name="value_ids" eval="[(6, 0, [ref('product.product_4_attribute_2_value_2')])]"/>
|
||||
</record>
|
||||
<record id="product_template_attribute_exclusion_2" model="product.template.attribute.exclusion">
|
||||
<field name="product_tmpl_id" ref="product.product_product_11_product_template" />
|
||||
<field name="value_ids" eval="[(6, 0, [ref('product.product_11_attribute_1_value_1')])]"/>
|
||||
</record>
|
||||
<record id="product_template_attribute_exclusion_3" model="product.template.attribute.exclusion">
|
||||
<field name="product_tmpl_id" ref="product.product_product_11_product_template" />
|
||||
<field name="value_ids" eval="[(6, 0, [ref('product.product_11_attribute_1_value_2')])]"/>
|
||||
</record>
|
||||
|
||||
<!--
|
||||
The "Customizable Desk's Aluminium" attribute value will excude:
|
||||
- The "Customizable Desk's Black" attribute
|
||||
- The "Office Chair's Steel" attribute
|
||||
-->
|
||||
<record id="product_4_attribute_1_value_2" model="product.template.attribute.value">
|
||||
<field name="exclude_for" eval="[(6, 0, [ref('product.product_template_attribute_exclusion_1'), ref('product.product_template_attribute_exclusion_2')])]" />
|
||||
</record>
|
||||
<!--
|
||||
The "Customizable Desk's Steel" attribute value will excude:
|
||||
- The "Office Chair's Aluminium" attribute
|
||||
-->
|
||||
<record id="product_4_attribute_1_value_1" model="product.template.attribute.value">
|
||||
<field name="exclude_for" eval="[(6, 0, [ref('product.product_template_attribute_exclusion_3')])]" />
|
||||
</record>
|
||||
|
||||
<!-- MRP Demo Data-->
|
||||
|
||||
<record id="product_product_12" model="product.product">
|
||||
<field name="name">Office Chair Black</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="standard_price">180</field>
|
||||
<field name="list_price">120.50</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="default_code">FURN_0269</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_product_12-image.png"/>
|
||||
</record>
|
||||
|
||||
<record id="product_product_13" model="product.product">
|
||||
<field name="name">Corner Desk Left Sit</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="standard_price">78.0</field>
|
||||
<field name="list_price">85.0</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="default_code">FURN_1118</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_product_13-image.jpg"/>
|
||||
</record>
|
||||
|
||||
<record id="product_product_16" model="product.product">
|
||||
<field name="name">Drawer Black</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="standard_price">20.0</field>
|
||||
<field name="list_price">25.0</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="default_code">FURN_8900</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_product_16-image.jpg"/>
|
||||
</record>
|
||||
|
||||
<record id="product_product_20" model="product.product">
|
||||
<field name="name">Flipover</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="standard_price">1700.0</field>
|
||||
<field name="list_price">1950.0</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="default_code">FURN_9001</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_product_20-image.png"/>
|
||||
</record>
|
||||
<record id="product_product_22" model="product.product">
|
||||
<field name="name">Desk Stand with Screen</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="standard_price">2010.0</field>
|
||||
<field name="list_price">2100.0</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="default_code">FURN_7888</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_product_22-image.png"/>
|
||||
</record>
|
||||
|
||||
<record id="product_product_24" model="product.product">
|
||||
<field name="name">Individual Workplace</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="standard_price">876.0</field>
|
||||
<field name="list_price">885.0</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="default_code">FURN_0789</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_product_24-image.jpg"/>
|
||||
</record>
|
||||
|
||||
<record id="product_product_25" model="product.product">
|
||||
<field name="name">Acoustic Bloc Screens</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="standard_price">287.0</field>
|
||||
<field name="list_price">295.0</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="default_code">FURN_6666</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_product_25-image.png"/>
|
||||
</record>
|
||||
|
||||
<record id="product_product_25_document" model="product.document">
|
||||
<field name="name">Acoustic Bloc Screens Document.pdf</field>
|
||||
<field name="datas" type="base64" file="product/static/demo/acoustic_bloc_screen_document.pdf"/>
|
||||
<field name="mimetype">application/pdf</field>
|
||||
<field name="res_model">product.product</field>
|
||||
<field name="res_id" ref="product.product_product_25"/>
|
||||
</record>
|
||||
|
||||
<record id="product_product_27" model="product.product">
|
||||
<field name="name">Drawer</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="standard_price">100.0</field>
|
||||
<field name="list_price">110.50</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="description">Drawer with two routing possiblities.</field>
|
||||
<field name="default_code">FURN_8855</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_product_27-image.jpg"/>
|
||||
</record>
|
||||
|
||||
<record id="consu_delivery_03" model="product.product">
|
||||
<field name="name">Four Person Desk</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="standard_price">2500.0</field>
|
||||
<field name="list_price">2350.0</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="description_sale">Four person modern office workstation</field>
|
||||
<field name="default_code">FURN_8220</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_product_d03-image.png"/>
|
||||
</record>
|
||||
|
||||
<record id="consu_delivery_02" model="product.product">
|
||||
<field name="name">Large Meeting Table</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="standard_price">4500.0</field>
|
||||
<field name="list_price">4000.0</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="description_sale">Conference room table</field>
|
||||
<field name="default_code">FURN_6741</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_product_46-image.jpg"/>
|
||||
</record>
|
||||
|
||||
<record id="consu_delivery_02_document" model="product.document">
|
||||
<field name="name">Large Meeting Table Document.pdf</field>
|
||||
<field name="datas" type="base64" file="product/static/demo/large_meeting_table_document.pdf"/>
|
||||
<field name="mimetype">application/pdf</field>
|
||||
<field name="res_model">product.template</field>
|
||||
<field name="res_id" ref="consu_delivery_02_product_template"/>
|
||||
</record>
|
||||
|
||||
<record id="consu_delivery_01" model="product.product">
|
||||
<field name="name">Three-Seat Sofa</field>
|
||||
<field name="categ_id" ref="product_category_5"/>
|
||||
<field name="standard_price">1000</field>
|
||||
<field name="list_price">1500</field>
|
||||
<field name="detailed_type">consu</field>
|
||||
<field name="weight">0.01</field>
|
||||
<field name="uom_id" ref="uom.product_uom_unit"/>
|
||||
<field name="uom_po_id" ref="uom.product_uom_unit"/>
|
||||
<field name="description_sale">Three Seater Sofa with Lounger in Steel Grey Colour</field>
|
||||
<field name="default_code">FURN_8999</field>
|
||||
<field name="image_1920" type="base64" file="product/static/img/product_product_d01-image.jpg"/>
|
||||
</record>
|
||||
|
||||
<!--
|
||||
Resource: product.supplierinfo
|
||||
-->
|
||||
|
||||
<record id="product_supplierinfo_1" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_product_6_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_1"/>
|
||||
<field name="delay">3</field>
|
||||
<field name="min_qty">1</field>
|
||||
<field name="price">750</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_2" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_product_6_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_4"/>
|
||||
<field name="delay">3</field>
|
||||
<field name="min_qty">1</field>
|
||||
<field name="price">790</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_2bis" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_product_6_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_4"/>
|
||||
<field name="delay">3</field>
|
||||
<field name="min_qty">3</field>
|
||||
<field name="price">785</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_3" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_product_7_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_1"/>
|
||||
<field name="delay">3</field>
|
||||
<field name="min_qty">1</field>
|
||||
<field name="price">13.0</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_4" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_product_7_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_4"/>
|
||||
<field name="delay">3</field>
|
||||
<field name="min_qty">1</field>
|
||||
<field name="price">14.4</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_5" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_product_8_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_1"/>
|
||||
<field name="delay">2</field>
|
||||
<field name="min_qty">5</field>
|
||||
<field name="price">1299</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_6" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_product_8_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_12"/>
|
||||
<field name="delay">4</field>
|
||||
<field name="min_qty">1</field>
|
||||
<field name="price">1399</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_7" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_product_10_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_1"/>
|
||||
<field name="delay">2</field>
|
||||
<field name="min_qty">1</field>
|
||||
<field name="price">120.50</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_8" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_product_11_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_1"/>
|
||||
<field name="delay">2</field>
|
||||
<field name="min_qty">1</field>
|
||||
<field name="price">28</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_9" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_product_13_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_4"/>
|
||||
<field name="delay">5</field>
|
||||
<field name="min_qty">1</field>
|
||||
<field name="price">78</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_10" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_product_16_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_3"/>
|
||||
<field name="delay">1</field>
|
||||
<field name="min_qty">1</field>
|
||||
<field name="price">20</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_12" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_product_20_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_4"/>
|
||||
<field name="delay">3</field>
|
||||
<field name="min_qty">1</field>
|
||||
<field name="price">1700</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_13" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_product_20_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_1"/>
|
||||
<field name="delay">4</field>
|
||||
<field name="min_qty">5</field>
|
||||
<field name="price">1720</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_14" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_product_22_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_2"/>
|
||||
<field name="delay">3</field>
|
||||
<field name="min_qty">1</field>
|
||||
<field name="price">2010</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_15" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_product_24_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_2"/>
|
||||
<field name="delay">3</field>
|
||||
<field name="min_qty">1</field>
|
||||
<field name="price">876</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_16" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_product_25_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_1"/>
|
||||
<field name="delay">8</field>
|
||||
<field name="min_qty">1</field>
|
||||
<field name="price">287</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_17" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_delivery_02_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_2"/>
|
||||
<field name="delay">4</field>
|
||||
<field name="min_qty">1</field>
|
||||
<field name="price">390</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_18" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_delivery_01_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_3"/>
|
||||
<field name="delay">2</field>
|
||||
<field name="min_qty">12</field>
|
||||
<field name="price">90</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_19" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_delivery_01_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_1"/>
|
||||
<field name="delay">4</field>
|
||||
<field name="min_qty">1</field>
|
||||
<field name="price">66</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_20" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_delivery_02_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_1"/>
|
||||
<field name="delay">5</field>
|
||||
<field name="min_qty">1</field>
|
||||
<field name="price">35</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_21" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_delivery_01_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_12"/>
|
||||
<field name="delay">7</field>
|
||||
<field name="min_qty">1</field>
|
||||
<field name="price">55</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_22" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_product_9_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_12"/>
|
||||
<field name="delay">4</field>
|
||||
<field name="min_qty">0</field>
|
||||
<field name="price">10</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_23" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_product_27_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_1"/>
|
||||
<field name="delay">10</field>
|
||||
<field name="min_qty">0</field>
|
||||
<field name="price">95.50</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_24" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_product_12_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_1"/>
|
||||
<field name="delay">3</field>
|
||||
<field name="min_qty">0</field>
|
||||
<field name="price">120.50</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_25" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_product_12_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_4"/>
|
||||
<field name="delay">2</field>
|
||||
<field name="min_qty">0</field>
|
||||
<field name="price">130.50</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
<record id="product_supplierinfo_26" model="product.supplierinfo">
|
||||
<field name="product_tmpl_id" ref="product_product_5_product_template"/>
|
||||
<field name="partner_id" ref="base.res_partner_10"/>
|
||||
<field name="delay">1</field>
|
||||
<field name="min_qty">0</field>
|
||||
<field name="price">145</field>
|
||||
<field name="currency_id" ref="base.USD"/>
|
||||
</record>
|
||||
|
||||
</data>
|
||||
</odoo>
|
3130
i18n/af.po
Normal file
3130
i18n/af.po
Normal file
File diff suppressed because it is too large
Load Diff
3126
i18n/am.po
Normal file
3126
i18n/am.po
Normal file
File diff suppressed because it is too large
Load Diff
3948
i18n/ar.po
Normal file
3948
i18n/ar.po
Normal file
File diff suppressed because it is too large
Load Diff
3138
i18n/az.po
Normal file
3138
i18n/az.po
Normal file
File diff suppressed because it is too large
Load Diff
3821
i18n/bg.po
Normal file
3821
i18n/bg.po
Normal file
File diff suppressed because it is too large
Load Diff
3136
i18n/bs.po
Normal file
3136
i18n/bs.po
Normal file
File diff suppressed because it is too large
Load Diff
3938
i18n/ca.po
Normal file
3938
i18n/ca.po
Normal file
File diff suppressed because it is too large
Load Diff
3920
i18n/cs.po
Normal file
3920
i18n/cs.po
Normal file
File diff suppressed because it is too large
Load Diff
3896
i18n/da.po
Normal file
3896
i18n/da.po
Normal file
File diff suppressed because it is too large
Load Diff
4007
i18n/de.po
Normal file
4007
i18n/de.po
Normal file
File diff suppressed because it is too large
Load Diff
3140
i18n/el.po
Normal file
3140
i18n/el.po
Normal file
File diff suppressed because it is too large
Load Diff
3129
i18n/en_GB.po
Normal file
3129
i18n/en_GB.po
Normal file
File diff suppressed because it is too large
Load Diff
3994
i18n/es.po
Normal file
3994
i18n/es.po
Normal file
File diff suppressed because it is too large
Load Diff
3997
i18n/es_419.po
Normal file
3997
i18n/es_419.po
Normal file
File diff suppressed because it is too large
Load Diff
3128
i18n/es_BO.po
Normal file
3128
i18n/es_BO.po
Normal file
File diff suppressed because it is too large
Load Diff
3132
i18n/es_CL.po
Normal file
3132
i18n/es_CL.po
Normal file
File diff suppressed because it is too large
Load Diff
3136
i18n/es_CO.po
Normal file
3136
i18n/es_CO.po
Normal file
File diff suppressed because it is too large
Load Diff
3131
i18n/es_CR.po
Normal file
3131
i18n/es_CR.po
Normal file
File diff suppressed because it is too large
Load Diff
3134
i18n/es_DO.po
Normal file
3134
i18n/es_DO.po
Normal file
File diff suppressed because it is too large
Load Diff
3134
i18n/es_EC.po
Normal file
3134
i18n/es_EC.po
Normal file
File diff suppressed because it is too large
Load Diff
3129
i18n/es_PE.po
Normal file
3129
i18n/es_PE.po
Normal file
File diff suppressed because it is too large
Load Diff
3128
i18n/es_PY.po
Normal file
3128
i18n/es_PY.po
Normal file
File diff suppressed because it is too large
Load Diff
3135
i18n/es_VE.po
Normal file
3135
i18n/es_VE.po
Normal file
File diff suppressed because it is too large
Load Diff
3911
i18n/et.po
Normal file
3911
i18n/et.po
Normal file
File diff suppressed because it is too large
Load Diff
3131
i18n/eu.po
Normal file
3131
i18n/eu.po
Normal file
File diff suppressed because it is too large
Load Diff
3847
i18n/fa.po
Normal file
3847
i18n/fa.po
Normal file
File diff suppressed because it is too large
Load Diff
3994
i18n/fi.po
Normal file
3994
i18n/fi.po
Normal file
File diff suppressed because it is too large
Load Diff
4006
i18n/fr.po
Normal file
4006
i18n/fr.po
Normal file
File diff suppressed because it is too large
Load Diff
3127
i18n/fr_BE.po
Normal file
3127
i18n/fr_BE.po
Normal file
File diff suppressed because it is too large
Load Diff
3128
i18n/gl.po
Normal file
3128
i18n/gl.po
Normal file
File diff suppressed because it is too large
Load Diff
3134
i18n/gu.po
Normal file
3134
i18n/gu.po
Normal file
File diff suppressed because it is too large
Load Diff
3908
i18n/he.po
Normal file
3908
i18n/he.po
Normal file
File diff suppressed because it is too large
Load Diff
3173
i18n/hr.po
Normal file
3173
i18n/hr.po
Normal file
File diff suppressed because it is too large
Load Diff
3846
i18n/hu.po
Normal file
3846
i18n/hu.po
Normal file
File diff suppressed because it is too large
Load Diff
3977
i18n/id.po
Normal file
3977
i18n/id.po
Normal file
File diff suppressed because it is too large
Load Diff
3130
i18n/is.po
Normal file
3130
i18n/is.po
Normal file
File diff suppressed because it is too large
Load Diff
3996
i18n/it.po
Normal file
3996
i18n/it.po
Normal file
File diff suppressed because it is too large
Load Diff
3872
i18n/ja.po
Normal file
3872
i18n/ja.po
Normal file
File diff suppressed because it is too large
Load Diff
3131
i18n/kab.po
Normal file
3131
i18n/kab.po
Normal file
File diff suppressed because it is too large
Load Diff
3133
i18n/km.po
Normal file
3133
i18n/km.po
Normal file
File diff suppressed because it is too large
Load Diff
3885
i18n/ko.po
Normal file
3885
i18n/ko.po
Normal file
File diff suppressed because it is too large
Load Diff
3130
i18n/lb.po
Normal file
3130
i18n/lb.po
Normal file
File diff suppressed because it is too large
Load Diff
3880
i18n/lt.po
Normal file
3880
i18n/lt.po
Normal file
File diff suppressed because it is too large
Load Diff
3855
i18n/lv.po
Normal file
3855
i18n/lv.po
Normal file
File diff suppressed because it is too large
Load Diff
3136
i18n/mk.po
Normal file
3136
i18n/mk.po
Normal file
File diff suppressed because it is too large
Load Diff
3166
i18n/mn.po
Normal file
3166
i18n/mn.po
Normal file
File diff suppressed because it is too large
Load Diff
3151
i18n/nb.po
Normal file
3151
i18n/nb.po
Normal file
File diff suppressed because it is too large
Load Diff
3990
i18n/nl.po
Normal file
3990
i18n/nl.po
Normal file
File diff suppressed because it is too large
Load Diff
3948
i18n/pl.po
Normal file
3948
i18n/pl.po
Normal file
File diff suppressed because it is too large
Load Diff
3783
i18n/product.pot
Normal file
3783
i18n/product.pot
Normal file
File diff suppressed because it is too large
Load Diff
3838
i18n/pt.po
Normal file
3838
i18n/pt.po
Normal file
File diff suppressed because it is too large
Load Diff
3985
i18n/pt_BR.po
Normal file
3985
i18n/pt_BR.po
Normal file
File diff suppressed because it is too large
Load Diff
3175
i18n/ro.po
Normal file
3175
i18n/ro.po
Normal file
File diff suppressed because it is too large
Load Diff
4004
i18n/ru.po
Normal file
4004
i18n/ru.po
Normal file
File diff suppressed because it is too large
Load Diff
3826
i18n/sk.po
Normal file
3826
i18n/sk.po
Normal file
File diff suppressed because it is too large
Load Diff
3832
i18n/sl.po
Normal file
3832
i18n/sl.po
Normal file
File diff suppressed because it is too large
Load Diff
3923
i18n/sr.po
Normal file
3923
i18n/sr.po
Normal file
File diff suppressed because it is too large
Load Diff
3135
i18n/sr@latin.po
Normal file
3135
i18n/sr@latin.po
Normal file
File diff suppressed because it is too large
Load Diff
3842
i18n/sv.po
Normal file
3842
i18n/sv.po
Normal file
File diff suppressed because it is too large
Load Diff
3949
i18n/th.po
Normal file
3949
i18n/th.po
Normal file
File diff suppressed because it is too large
Load Diff
3947
i18n/tr.po
Normal file
3947
i18n/tr.po
Normal file
File diff suppressed because it is too large
Load Diff
3929
i18n/uk.po
Normal file
3929
i18n/uk.po
Normal file
File diff suppressed because it is too large
Load Diff
3972
i18n/vi.po
Normal file
3972
i18n/vi.po
Normal file
File diff suppressed because it is too large
Load Diff
3872
i18n/zh_CN.po
Normal file
3872
i18n/zh_CN.po
Normal file
File diff suppressed because it is too large
Load Diff
3867
i18n/zh_TW.po
Normal file
3867
i18n/zh_TW.po
Normal file
File diff suppressed because it is too large
Load Diff
32
models/__init__.py
Normal file
32
models/__init__.py
Normal file
@ -0,0 +1,32 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
# flake8: noqa: F401
|
||||
|
||||
# don't try to be a good boy and sort imports alphabetically.
|
||||
# `product.template` should be initialised before `product.product`
|
||||
from . import product_template
|
||||
from . import product_product
|
||||
|
||||
from . import decimal_precision
|
||||
from . import ir_attachment
|
||||
from . import product_attribute
|
||||
from . import product_attribute_custom_value
|
||||
from . import product_attribute_value
|
||||
from . import product_catalog_mixin
|
||||
from . import product_category
|
||||
from . import product_document
|
||||
from . import product_packaging
|
||||
from . import product_pricelist
|
||||
from . import product_pricelist_item
|
||||
from . import product_supplierinfo
|
||||
from . import product_tag
|
||||
from . import product_template_attribute_line
|
||||
from . import product_template_attribute_exclusion
|
||||
from . import product_template_attribute_value
|
||||
from . import res_company
|
||||
from . import res_config_settings
|
||||
from . import res_country_group
|
||||
from . import res_currency
|
||||
from . import res_partner
|
||||
from . import uom_uom
|
40
models/decimal_precision.py
Normal file
40
models/decimal_precision.py
Normal file
@ -0,0 +1,40 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, models, tools, _
|
||||
from odoo.exceptions import ValidationError
|
||||
|
||||
|
||||
class DecimalPrecision(models.Model):
|
||||
_inherit = 'decimal.precision'
|
||||
|
||||
@api.constrains('digits')
|
||||
def _check_main_currency_rounding(self):
|
||||
if any(precision.name == 'Account' and
|
||||
tools.float_compare(self.env.company.currency_id.rounding, 10 ** - precision.digits, precision_digits=6) == -1
|
||||
for precision in self):
|
||||
raise ValidationError(_("You cannot define the decimal precision of 'Account' as greater than the rounding factor of the company's main currency"))
|
||||
return True
|
||||
|
||||
@api.onchange('digits')
|
||||
def _onchange_digits(self):
|
||||
if self.name != "Product Unit of Measure": # precision_get() relies on this name
|
||||
return
|
||||
# We are changing the precision of UOM fields; check whether the
|
||||
# precision is equal or higher than existing units of measure.
|
||||
rounding = 1.0 / 10.0**self.digits
|
||||
dangerous_uom = self.env['uom.uom'].search([('rounding', '<', rounding)])
|
||||
if dangerous_uom:
|
||||
uom_descriptions = [
|
||||
" - %s (id=%s, precision=%s)" % (uom.name, uom.id, uom.rounding)
|
||||
for uom in dangerous_uom
|
||||
]
|
||||
return {'warning': {
|
||||
'title': _('Warning!'),
|
||||
'message': _(
|
||||
"You are setting a Decimal Accuracy less precise than the UOMs:\n"
|
||||
"%s\n"
|
||||
"This may cause inconsistencies in computations.\n"
|
||||
"Please increase the rounding of those units of measure, or the digits of this Decimal Accuracy.",
|
||||
'\n'.join(uom_descriptions)),
|
||||
}}
|
25
models/ir_attachment.py
Normal file
25
models/ir_attachment.py
Normal file
@ -0,0 +1,25 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, models
|
||||
|
||||
|
||||
class IrAttachment(models.Model):
|
||||
_inherit = 'ir.attachment'
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
"""Create product.document for attachments added in products chatters"""
|
||||
attachments = super().create(vals_list)
|
||||
if not self.env.context.get('disable_product_documents_creation'):
|
||||
product_attachments = attachments.filtered(
|
||||
lambda attachment:
|
||||
attachment.res_model in ('product.product', 'product.template')
|
||||
and not attachment.res_field
|
||||
)
|
||||
if product_attachments:
|
||||
self.env['product.document'].sudo().create(
|
||||
{
|
||||
'ir_attachment_id': attachment.id
|
||||
} for attachment in product_attachments
|
||||
)
|
||||
return attachments
|
122
models/product_attribute.py
Normal file
122
models/product_attribute.py
Normal file
@ -0,0 +1,122 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, fields, models, _
|
||||
from odoo.exceptions import UserError
|
||||
|
||||
|
||||
class ProductAttribute(models.Model):
|
||||
_name = "product.attribute"
|
||||
_description = "Product Attribute"
|
||||
# if you change this _order, keep it in sync with the method
|
||||
# `_sort_key_attribute_value` in `product.template`
|
||||
_order = 'sequence, id'
|
||||
|
||||
_sql_constraints = [
|
||||
(
|
||||
'check_multi_checkbox_no_variant',
|
||||
"CHECK(display_type != 'multi' OR create_variant = 'no_variant')",
|
||||
"Multi-checkbox display type is not compatible with the creation of variants"
|
||||
),
|
||||
]
|
||||
|
||||
name = fields.Char(string="Attribute", required=True, translate=True)
|
||||
create_variant = fields.Selection(
|
||||
selection=[
|
||||
('always', 'Instantly'),
|
||||
('dynamic', 'Dynamically'),
|
||||
('no_variant', 'Never (option)'),
|
||||
],
|
||||
default='always',
|
||||
string="Variants Creation Mode",
|
||||
help="""- Instantly: All possible variants are created as soon as the attribute and its values are added to a product.
|
||||
- Dynamically: Each variant is created only when its corresponding attributes and values are added to a sales order.
|
||||
- Never: Variants are never created for the attribute.
|
||||
Note: the variants creation mode cannot be changed once the attribute is used on at least one product.""",
|
||||
required=True)
|
||||
display_type = fields.Selection(
|
||||
selection=[
|
||||
('radio', 'Radio'),
|
||||
('pills', 'Pills'),
|
||||
('select', 'Select'),
|
||||
('color', 'Color'),
|
||||
('multi', 'Multi-checkbox (option)'),
|
||||
],
|
||||
default='radio',
|
||||
required=True,
|
||||
help="The display type used in the Product Configurator.")
|
||||
sequence = fields.Integer(string="Sequence", help="Determine the display order", index=True)
|
||||
|
||||
value_ids = fields.One2many(
|
||||
comodel_name='product.attribute.value',
|
||||
inverse_name='attribute_id',
|
||||
string="Values", copy=True)
|
||||
|
||||
attribute_line_ids = fields.One2many(
|
||||
comodel_name='product.template.attribute.line',
|
||||
inverse_name='attribute_id',
|
||||
string="Lines")
|
||||
product_tmpl_ids = fields.Many2many(
|
||||
comodel_name='product.template',
|
||||
string="Related Products",
|
||||
compute='_compute_products',
|
||||
store=True)
|
||||
number_related_products = fields.Integer(compute='_compute_number_related_products')
|
||||
|
||||
@api.depends('product_tmpl_ids')
|
||||
def _compute_number_related_products(self):
|
||||
for pa in self:
|
||||
pa.number_related_products = len(pa.product_tmpl_ids)
|
||||
|
||||
@api.depends('attribute_line_ids.active', 'attribute_line_ids.product_tmpl_id')
|
||||
def _compute_products(self):
|
||||
for pa in self:
|
||||
pa.with_context(active_test=False).product_tmpl_ids = pa.attribute_line_ids.product_tmpl_id
|
||||
|
||||
def _without_no_variant_attributes(self):
|
||||
return self.filtered(lambda pa: pa.create_variant != 'no_variant')
|
||||
|
||||
def write(self, vals):
|
||||
"""Override to make sure attribute type can't be changed if it's used on
|
||||
a product template.
|
||||
|
||||
This is important to prevent because changing the type would make
|
||||
existing combinations invalid without recomputing them, and recomputing
|
||||
them might take too long and we don't want to change products without
|
||||
the user knowing about it."""
|
||||
if 'create_variant' in vals:
|
||||
for pa in self:
|
||||
if vals['create_variant'] != pa.create_variant and pa.number_related_products:
|
||||
raise UserError(_(
|
||||
"You cannot change the Variants Creation Mode of the attribute %(attribute)s"
|
||||
" because it is used on the following products:\n%(products)s",
|
||||
attribute=pa.display_name,
|
||||
products=", ".join(pa.product_tmpl_ids.mapped('display_name')),
|
||||
))
|
||||
invalidate = 'sequence' in vals and any(record.sequence != vals['sequence'] for record in self)
|
||||
res = super().write(vals)
|
||||
if invalidate:
|
||||
# prefetched o2m have to be resequenced
|
||||
# (eg. product.template: attribute_line_ids)
|
||||
self.env.flush_all()
|
||||
self.env.invalidate_all()
|
||||
return res
|
||||
|
||||
@api.ondelete(at_uninstall=False)
|
||||
def _unlink_except_used_on_product(self):
|
||||
for pa in self:
|
||||
if pa.number_related_products:
|
||||
raise UserError(_(
|
||||
"You cannot delete the attribute %(attribute)s because it is used on the"
|
||||
" following products:\n%(products)s",
|
||||
attribute=pa.display_name,
|
||||
products=", ".join(pa.product_tmpl_ids.mapped('display_name')),
|
||||
))
|
||||
|
||||
def action_open_related_products(self):
|
||||
return {
|
||||
'type': 'ir.actions.act_window',
|
||||
'name': _("Related Products"),
|
||||
'res_model': 'product.template',
|
||||
'view_mode': 'tree,form',
|
||||
'domain': [('id', 'in', self.product_tmpl_ids.ids)],
|
||||
}
|
25
models/product_attribute_custom_value.py
Normal file
25
models/product_attribute_custom_value.py
Normal file
@ -0,0 +1,25 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, fields, models
|
||||
|
||||
|
||||
class ProductAttributeCustomValue(models.Model):
|
||||
_name = 'product.attribute.custom.value'
|
||||
_description = "Product Attribute Custom Value"
|
||||
_order = 'custom_product_template_attribute_value_id, id'
|
||||
|
||||
name = fields.Char(string="Name", compute='_compute_name')
|
||||
custom_product_template_attribute_value_id = fields.Many2one(
|
||||
comodel_name='product.template.attribute.value',
|
||||
string="Attribute Value",
|
||||
required=True,
|
||||
ondelete='restrict')
|
||||
custom_value = fields.Char(string="Custom Value")
|
||||
|
||||
@api.depends('custom_product_template_attribute_value_id.name', 'custom_value')
|
||||
def _compute_name(self):
|
||||
for record in self:
|
||||
name = (record.custom_value or '').strip()
|
||||
if record.custom_product_template_attribute_value_id.display_name:
|
||||
name = "%s: %s" % (record.custom_product_template_attribute_value_id.display_name, name)
|
||||
record.name = name
|
123
models/product_attribute_value.py
Normal file
123
models/product_attribute_value.py
Normal file
@ -0,0 +1,123 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from random import randint
|
||||
|
||||
from odoo import api, fields, models, _
|
||||
from odoo.exceptions import UserError
|
||||
|
||||
|
||||
class ProductAttributeValue(models.Model):
|
||||
_name = 'product.attribute.value'
|
||||
# if you change this _order, keep it in sync with the method
|
||||
# `_sort_key_variant` in `product.template'
|
||||
_order = 'attribute_id, sequence, id'
|
||||
_description = "Attribute Value"
|
||||
|
||||
def _get_default_color(self):
|
||||
return randint(1, 11)
|
||||
|
||||
name = fields.Char(string="Value", required=True, translate=True)
|
||||
sequence = fields.Integer(string="Sequence", help="Determine the display order", index=True)
|
||||
attribute_id = fields.Many2one(
|
||||
comodel_name='product.attribute',
|
||||
string="Attribute",
|
||||
help="The attribute cannot be changed once the value is used on at least one product.",
|
||||
ondelete='cascade',
|
||||
required=True,
|
||||
index=True)
|
||||
|
||||
pav_attribute_line_ids = fields.Many2many(
|
||||
comodel_name='product.template.attribute.line',
|
||||
relation='product_attribute_value_product_template_attribute_line_rel',
|
||||
string="Lines",
|
||||
copy=False)
|
||||
is_used_on_products = fields.Boolean(
|
||||
string="Used on Products", compute='_compute_is_used_on_products')
|
||||
|
||||
default_extra_price = fields.Float()
|
||||
is_custom = fields.Boolean(
|
||||
string="Is custom value",
|
||||
help="Allow users to input custom values for this attribute value")
|
||||
html_color = fields.Char(
|
||||
string="Color",
|
||||
help="Here you can set a specific HTML color index (e.g. #ff0000)"
|
||||
" to display the color if the attribute type is 'Color'.")
|
||||
display_type = fields.Selection(related='attribute_id.display_type')
|
||||
color = fields.Integer(string="Color Index", default=_get_default_color)
|
||||
image = fields.Image(
|
||||
string="Image",
|
||||
help="You can upload an image that will be used as the color of the attribute value.",
|
||||
max_width=70,
|
||||
max_height=70,
|
||||
)
|
||||
|
||||
_sql_constraints = [
|
||||
('value_company_uniq',
|
||||
'unique (name, attribute_id)',
|
||||
"You cannot create two values with the same name for the same attribute.")
|
||||
]
|
||||
|
||||
@api.depends('pav_attribute_line_ids')
|
||||
def _compute_is_used_on_products(self):
|
||||
for pav in self:
|
||||
pav.is_used_on_products = bool(pav.pav_attribute_line_ids)
|
||||
|
||||
@api.depends('attribute_id')
|
||||
@api.depends_context('show_attribute')
|
||||
def _compute_display_name(self):
|
||||
"""Override because in general the name of the value is confusing if it
|
||||
is displayed without the name of the corresponding attribute.
|
||||
Eg. on product list & kanban views, on BOM form view
|
||||
|
||||
However during variant set up (on the product template form) the name of
|
||||
the attribute is already on each line so there is no need to repeat it
|
||||
on every value.
|
||||
"""
|
||||
if not self.env.context.get('show_attribute', True):
|
||||
return super()._compute_display_name()
|
||||
for value in self:
|
||||
value.display_name = f"{value.attribute_id.name}: {value.name}"
|
||||
|
||||
def write(self, values):
|
||||
if 'attribute_id' in values:
|
||||
for pav in self:
|
||||
if pav.attribute_id.id != values['attribute_id'] and pav.is_used_on_products:
|
||||
raise UserError(_(
|
||||
"You cannot change the attribute of the value %(value)s because it is used"
|
||||
" on the following products: %(products)s",
|
||||
value=pav.display_name,
|
||||
products=", ".join(pav.pav_attribute_line_ids.product_tmpl_id.mapped('display_name')),
|
||||
))
|
||||
|
||||
invalidate = 'sequence' in values and any(record.sequence != values['sequence'] for record in self)
|
||||
res = super().write(values)
|
||||
if invalidate:
|
||||
# prefetched o2m have to be resequenced
|
||||
# (eg. product.template.attribute.line: value_ids)
|
||||
self.env.flush_all()
|
||||
self.env.invalidate_all()
|
||||
return res
|
||||
|
||||
@api.ondelete(at_uninstall=False)
|
||||
def _unlink_except_used_on_product(self):
|
||||
for pav in self:
|
||||
if pav.is_used_on_products:
|
||||
raise UserError(_(
|
||||
"You cannot delete the value %(value)s because it is used on the following "
|
||||
"products:\n%(products)s\n If the value has been associated to a product in the"
|
||||
" past, you will not be able to delete it.",
|
||||
value=pav.display_name,
|
||||
products=", ".join(pav.pav_attribute_line_ids.product_tmpl_id.mapped('display_name')),
|
||||
))
|
||||
linked_products = pav.env['product.template.attribute.value'].search(
|
||||
[('product_attribute_value_id', '=', pav.id)]
|
||||
).with_context(active_test=False).ptav_product_variant_ids
|
||||
unlinkable_products = linked_products._filter_to_unlink()
|
||||
if linked_products != unlinkable_products:
|
||||
raise UserError(_(
|
||||
"You cannot delete value %s because it was used in some products.",
|
||||
pav.display_name
|
||||
))
|
||||
|
||||
def _without_no_variant_attributes(self):
|
||||
return self.filtered(lambda pav: pav.attribute_id.create_variant != 'no_variant')
|
124
models/product_catalog_mixin.py
Normal file
124
models/product_catalog_mixin.py
Normal file
@ -0,0 +1,124 @@
|
||||
from odoo import _, models
|
||||
|
||||
|
||||
|
||||
class ProductCatalogMixin(models.AbstractModel):
|
||||
""" This mixin should be inherited when the model should be able to work
|
||||
with the product catalog.
|
||||
It assumes the model using this mixin has a O2M field where the products are added/removed and
|
||||
this field's co-related model should has a method named `_get_product_catalog_lines_data`.
|
||||
"""
|
||||
_name = 'product.catalog.mixin'
|
||||
_description = 'Product Catalog Mixin'
|
||||
|
||||
def action_add_from_catalog(self):
|
||||
kanban_view_id = self.env.ref('product.product_view_kanban_catalog').id
|
||||
search_view_id = self.env.ref('product.product_view_search_catalog').id
|
||||
additional_context = self._get_action_add_from_catalog_extra_context()
|
||||
return {
|
||||
'type': 'ir.actions.act_window',
|
||||
'name': _('Products'),
|
||||
'res_model': 'product.product',
|
||||
'views': [(kanban_view_id, 'kanban'), (False, 'form')],
|
||||
'search_view_id': [search_view_id, 'search'],
|
||||
'domain': self._get_product_catalog_domain(),
|
||||
'context': {**self.env.context, **additional_context},
|
||||
}
|
||||
|
||||
def _default_order_line_values(self):
|
||||
return {
|
||||
'quantity': 0,
|
||||
'readOnly': self._is_readonly() if self else False,
|
||||
}
|
||||
|
||||
def _get_product_catalog_domain(self):
|
||||
"""Get the domain to search for products in the catalog.
|
||||
|
||||
For a model that uses products that has to be hidden in the catalog, it
|
||||
must override this method and extend the appropriate domain.
|
||||
:returns: A list of tuples that represents a domain.
|
||||
:rtype: list
|
||||
"""
|
||||
return [('company_id', 'in', [self.company_id.id, False])]
|
||||
|
||||
def _get_product_catalog_record_lines(self, product_ids):
|
||||
""" Returns the record's lines grouped by product.
|
||||
Must be overrided by each model using this mixin.
|
||||
|
||||
:param list product_ids: The ids of the products currently displayed in the product catalog.
|
||||
:rtype: dict
|
||||
"""
|
||||
return {}
|
||||
|
||||
def _get_product_catalog_order_data(self, products, **kwargs):
|
||||
""" Returns a dict containing the products' data. Those data are for products who aren't in
|
||||
the record yet. For products already in the record, see `_get_product_catalog_lines_data`.
|
||||
|
||||
For each product, its id is the key and the value is another dict with all needed data.
|
||||
By default, the price is the only needed data but each model is free to add more data.
|
||||
Must be overrided by each model using this mixin.
|
||||
|
||||
:param products: Recordset of `product.product`.
|
||||
:param dict kwargs: additional values given for inherited models.
|
||||
:rtype: dict
|
||||
:return: A dict with the following structure:
|
||||
{
|
||||
'productId': int
|
||||
'quantity': float (optional)
|
||||
'price': float
|
||||
'readOnly': bool (optional)
|
||||
}
|
||||
"""
|
||||
return {}
|
||||
|
||||
def _get_product_catalog_order_line_info(self, product_ids, **kwargs):
|
||||
""" Returns products information to be shown in the catalog.
|
||||
:param list product_ids: The products currently displayed in the product catalog, as a list
|
||||
of `product.product` ids.
|
||||
:param dict kwargs: additional values given for inherited models.
|
||||
:rtype: dict
|
||||
:return: A dict with the following structure:
|
||||
{
|
||||
'productId': int
|
||||
'quantity': float (optional)
|
||||
'price': float
|
||||
'readOnly': bool (optional)
|
||||
}
|
||||
"""
|
||||
order_line_info = {}
|
||||
default_data = self._default_order_line_values()
|
||||
|
||||
for product, record_lines in self._get_product_catalog_record_lines(product_ids).items():
|
||||
order_line_info[product.id] = record_lines._get_product_catalog_lines_data(**kwargs)
|
||||
product_ids.remove(product.id)
|
||||
|
||||
products = self.env['product.product'].browse(product_ids)
|
||||
product_data = self._get_product_catalog_order_data(products, **kwargs)
|
||||
for product_id, data in product_data.items():
|
||||
order_line_info[product_id] = {**default_data, **data}
|
||||
return order_line_info
|
||||
|
||||
def _get_action_add_from_catalog_extra_context(self):
|
||||
return {
|
||||
'product_catalog_order_id': self.id,
|
||||
'product_catalog_order_model': self._name,
|
||||
}
|
||||
|
||||
def _is_readonly(self):
|
||||
""" Must be overrided by each model using this mixin.
|
||||
:return: Whether the record is read-only or not.
|
||||
:rtype: bool
|
||||
"""
|
||||
return False
|
||||
|
||||
def _update_order_line_info(self, product_id, quantity, **kwargs):
|
||||
""" Update the line information for a given product or create a new one if none exists yet.
|
||||
Must be overrided by each model using this mixin.
|
||||
:param int product_id: The product, as a `product.product` id.
|
||||
:param int quantity: The product's quantity.
|
||||
:param dict kwargs: additional values given for inherited models.
|
||||
:return: The unit price of the product, based on the pricelist of the
|
||||
purchase order and the quantity selected.
|
||||
:rtype: float
|
||||
"""
|
||||
return 0
|
69
models/product_category.py
Normal file
69
models/product_category.py
Normal file
@ -0,0 +1,69 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, fields, models, _
|
||||
from odoo.exceptions import UserError, ValidationError
|
||||
|
||||
|
||||
class ProductCategory(models.Model):
|
||||
_name = "product.category"
|
||||
_description = "Product Category"
|
||||
_parent_name = "parent_id"
|
||||
_parent_store = True
|
||||
_rec_name = 'complete_name'
|
||||
_order = 'complete_name'
|
||||
|
||||
name = fields.Char('Name', index='trigram', required=True)
|
||||
complete_name = fields.Char(
|
||||
'Complete Name', compute='_compute_complete_name', recursive=True,
|
||||
store=True)
|
||||
parent_id = fields.Many2one('product.category', 'Parent Category', index=True, ondelete='cascade')
|
||||
parent_path = fields.Char(index=True, unaccent=False)
|
||||
child_id = fields.One2many('product.category', 'parent_id', 'Child Categories')
|
||||
product_count = fields.Integer(
|
||||
'# Products', compute='_compute_product_count',
|
||||
help="The number of products under this category (Does not consider the children categories)")
|
||||
product_properties_definition = fields.PropertiesDefinition('Product Properties')
|
||||
|
||||
@api.depends('name', 'parent_id.complete_name')
|
||||
def _compute_complete_name(self):
|
||||
for category in self:
|
||||
if category.parent_id:
|
||||
category.complete_name = '%s / %s' % (category.parent_id.complete_name, category.name)
|
||||
else:
|
||||
category.complete_name = category.name
|
||||
|
||||
def _compute_product_count(self):
|
||||
read_group_res = self.env['product.template']._read_group([('categ_id', 'child_of', self.ids)], ['categ_id'], ['__count'])
|
||||
group_data = {categ.id: count for categ, count in read_group_res}
|
||||
for categ in self:
|
||||
product_count = 0
|
||||
for sub_categ_id in categ.search([('id', 'child_of', categ.ids)]).ids:
|
||||
product_count += group_data.get(sub_categ_id, 0)
|
||||
categ.product_count = product_count
|
||||
|
||||
@api.constrains('parent_id')
|
||||
def _check_category_recursion(self):
|
||||
if not self._check_recursion():
|
||||
raise ValidationError(_('You cannot create recursive categories.'))
|
||||
|
||||
@api.model
|
||||
def name_create(self, name):
|
||||
category = self.create({'name': name})
|
||||
return category.id, category.display_name
|
||||
|
||||
@api.depends_context('hierarchical_naming')
|
||||
def _compute_display_name(self):
|
||||
if self.env.context.get('hierarchical_naming', True):
|
||||
return super()._compute_display_name()
|
||||
for record in self:
|
||||
record.display_name = record.name
|
||||
|
||||
@api.ondelete(at_uninstall=False)
|
||||
def _unlink_except_default_category(self):
|
||||
main_category = self.env.ref('product.product_category_all', raise_if_not_found=False)
|
||||
if main_category and main_category in self:
|
||||
raise UserError(_("You cannot delete this product category, it is the default generic category."))
|
||||
expense_category = self.env.ref('product.cat_expense', raise_if_not_found=False)
|
||||
if expense_category and expense_category in self:
|
||||
raise UserError(_("You cannot delete the %s product category.", expense_category.name))
|
47
models/product_document.py
Normal file
47
models/product_document.py
Normal file
@ -0,0 +1,47 @@
|
||||
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, fields, models
|
||||
|
||||
|
||||
class ProductDocument(models.Model):
|
||||
_name = 'product.document'
|
||||
_description = "Product Document"
|
||||
_inherits = {
|
||||
'ir.attachment': 'ir_attachment_id',
|
||||
}
|
||||
_order = 'id desc'
|
||||
|
||||
ir_attachment_id = fields.Many2one(
|
||||
'ir.attachment',
|
||||
string="Related attachment",
|
||||
required=True,
|
||||
ondelete='cascade')
|
||||
|
||||
active = fields.Boolean(default=True)
|
||||
|
||||
#=== CRUD METHODS ===#
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
return super(
|
||||
ProductDocument,
|
||||
self.with_context(disable_product_documents_creation=True),
|
||||
).create(vals_list)
|
||||
|
||||
def copy(self, default=None):
|
||||
default = default if default is not None else {}
|
||||
ir_default = default
|
||||
if ir_default:
|
||||
ir_fields = list(self.env['ir.attachment']._fields)
|
||||
ir_default = {field : default[field] for field in default if field in ir_fields}
|
||||
new_attach = self.ir_attachment_id.with_context(
|
||||
no_document=True,
|
||||
disable_product_documents_creation=True,
|
||||
).copy(ir_default)
|
||||
return super().copy(dict(default, ir_attachment_id=new_attach.id))
|
||||
|
||||
def unlink(self):
|
||||
attachments = self.ir_attachment_id
|
||||
res = super().unlink()
|
||||
return res and attachments.unlink()
|
80
models/product_packaging.py
Normal file
80
models/product_packaging.py
Normal file
@ -0,0 +1,80 @@
|
||||
# -*- coding: 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
|
||||
from odoo.osv import expression
|
||||
|
||||
|
||||
from odoo.tools import float_compare, float_round
|
||||
|
||||
|
||||
class ProductPackaging(models.Model):
|
||||
_name = "product.packaging"
|
||||
_description = "Product Packaging"
|
||||
_order = 'product_id, sequence, id'
|
||||
_check_company_auto = True
|
||||
|
||||
name = fields.Char('Product Packaging', required=True)
|
||||
sequence = fields.Integer('Sequence', default=1, help="The first in the sequence is the default one.")
|
||||
product_id = fields.Many2one('product.product', string='Product', check_company=True, required=True, ondelete="cascade")
|
||||
qty = fields.Float('Contained Quantity', default=1, digits='Product Unit of Measure', help="Quantity of products contained in the packaging.")
|
||||
barcode = fields.Char('Barcode', copy=False, help="Barcode used for packaging identification. Scan this packaging barcode from a transfer in the Barcode app to move all the contained units")
|
||||
product_uom_id = fields.Many2one('uom.uom', related='product_id.uom_id', readonly=True)
|
||||
company_id = fields.Many2one('res.company', 'Company', index=True)
|
||||
|
||||
_sql_constraints = [
|
||||
('positive_qty', 'CHECK(qty > 0)', 'Contained Quantity should be positive.'),
|
||||
('barcode_uniq', 'unique(barcode)', 'A barcode can only be assigned to one packaging.'),
|
||||
]
|
||||
|
||||
@api.constrains('barcode')
|
||||
def _check_barcode_uniqueness(self):
|
||||
""" With GS1 nomenclature, products and packagings use the same pattern. Therefore, we need
|
||||
to ensure the uniqueness between products' barcodes and packagings' ones"""
|
||||
domain = [('barcode', 'in', [b for b in self.mapped('barcode') if b])]
|
||||
if self.env['product.product'].search(domain, order="id", limit=1):
|
||||
raise ValidationError(_("A product already uses the barcode"))
|
||||
|
||||
def _check_qty(self, product_qty, uom_id, rounding_method="HALF-UP"):
|
||||
"""Check if product_qty in given uom is a multiple of the packaging qty.
|
||||
If not, rounding the product_qty to closest multiple of the packaging qty
|
||||
according to the rounding_method "UP", "HALF-UP or "DOWN".
|
||||
"""
|
||||
self.ensure_one()
|
||||
default_uom = self.product_id.uom_id
|
||||
packaging_qty = default_uom._compute_quantity(self.qty, uom_id)
|
||||
# We do not use the modulo operator to check if qty is a mltiple of q. Indeed the quantity
|
||||
# per package might be a float, leading to incorrect results. For example:
|
||||
# 8 % 1.6 = 1.5999999999999996
|
||||
# 5.4 % 1.8 = 2.220446049250313e-16
|
||||
if product_qty and packaging_qty:
|
||||
rounded_qty = float_round(product_qty / packaging_qty, precision_rounding=1.0,
|
||||
rounding_method=rounding_method) * packaging_qty
|
||||
return rounded_qty if float_compare(rounded_qty, product_qty, precision_rounding=default_uom.rounding) else product_qty
|
||||
return product_qty
|
||||
|
||||
def _find_suitable_product_packaging(self, product_qty, uom_id):
|
||||
""" try find in `self` if a packaging's qty in given uom is a divisor of
|
||||
the given product_qty. If so, return the one with greatest divisor.
|
||||
"""
|
||||
packagings = self.sorted(lambda p: p.qty, reverse=True)
|
||||
for packaging in packagings:
|
||||
new_qty = packaging._check_qty(product_qty, uom_id)
|
||||
if new_qty == product_qty:
|
||||
return packaging
|
||||
return self.env['product.packaging']
|
||||
|
||||
def _compute_qty(self, qty, qty_uom=False):
|
||||
"""Returns the qty of this packaging that qty converts to.
|
||||
A float is returned because there are edge cases where some users use
|
||||
"part" of a packaging
|
||||
|
||||
:param qty: float of product quantity (given in product UoM if no qty_uom provided)
|
||||
:param qty_uom: Optional uom of quantity
|
||||
:returns: float of packaging qty
|
||||
"""
|
||||
self.ensure_one()
|
||||
if qty_uom:
|
||||
qty = qty_uom._compute_quantity(qty, self.product_uom_id)
|
||||
return float_round(qty / self.qty, precision_rounding=self.product_uom_id.rounding)
|
348
models/product_pricelist.py
Normal file
348
models/product_pricelist.py
Normal file
@ -0,0 +1,348 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, fields, models, _
|
||||
from odoo.exceptions import UserError
|
||||
|
||||
|
||||
class Pricelist(models.Model):
|
||||
_name = "product.pricelist"
|
||||
_inherit = ['mail.thread', 'mail.activity.mixin']
|
||||
_description = "Pricelist"
|
||||
_rec_names_search = ['name', 'currency_id'] # TODO check if should be removed
|
||||
_order = "sequence asc, id asc"
|
||||
|
||||
def _default_currency_id(self):
|
||||
return self.env.company.currency_id.id
|
||||
|
||||
name = fields.Char(string="Pricelist Name", required=True, translate=True)
|
||||
|
||||
active = fields.Boolean(
|
||||
string="Active",
|
||||
default=True,
|
||||
help="If unchecked, it will allow you to hide the pricelist without removing it.")
|
||||
sequence = fields.Integer(default=16)
|
||||
|
||||
currency_id = fields.Many2one(
|
||||
comodel_name='res.currency',
|
||||
default=_default_currency_id,
|
||||
required=True,
|
||||
tracking=1,
|
||||
)
|
||||
|
||||
company_id = fields.Many2one(
|
||||
comodel_name='res.company',
|
||||
tracking=5,
|
||||
)
|
||||
country_group_ids = fields.Many2many(
|
||||
comodel_name='res.country.group',
|
||||
relation='res_country_group_pricelist_rel',
|
||||
column1='pricelist_id',
|
||||
column2='res_country_group_id',
|
||||
string="Country Groups",
|
||||
tracking=10,
|
||||
)
|
||||
|
||||
discount_policy = fields.Selection(
|
||||
selection=[
|
||||
('with_discount', "Discount included in the price"),
|
||||
('without_discount', "Show public price & discount to the customer"),
|
||||
],
|
||||
default='with_discount',
|
||||
required=True,
|
||||
tracking=15,
|
||||
)
|
||||
|
||||
item_ids = fields.One2many(
|
||||
comodel_name='product.pricelist.item',
|
||||
inverse_name='pricelist_id',
|
||||
string="Pricelist Rules",
|
||||
domain=[
|
||||
'&',
|
||||
'|', ('product_tmpl_id', '=', None), ('product_tmpl_id.active', '=', True),
|
||||
'|', ('product_id', '=', None), ('product_id.active', '=', True),
|
||||
],
|
||||
copy=True)
|
||||
|
||||
@api.depends('currency_id')
|
||||
def _compute_display_name(self):
|
||||
for pricelist in self:
|
||||
pricelist.display_name = f'{pricelist.name} ({pricelist.currency_id.name})'
|
||||
|
||||
def _get_products_price(self, products, *args, **kwargs):
|
||||
"""Compute the pricelist prices for the specified products, quantity & uom.
|
||||
|
||||
Note: self and self.ensure_one()
|
||||
|
||||
:param products: recordset of products (product.product/product.template)
|
||||
:param float quantity: quantity of products requested (in given uom)
|
||||
:param currency: record of currency (res.currency) (optional)
|
||||
:param uom: unit of measure (uom.uom record) (optional)
|
||||
If not specified, prices returned are expressed in product uoms
|
||||
:param date: date to use for price computation and currency conversions (optional)
|
||||
:type date: date or datetime
|
||||
|
||||
:returns: {product_id: product price}, considering the current pricelist if any
|
||||
:rtype: dict(int, float)
|
||||
"""
|
||||
self and self.ensure_one() # self is at most one record
|
||||
return {
|
||||
product_id: res_tuple[0]
|
||||
for product_id, res_tuple in self._compute_price_rule(products, *args, **kwargs).items()
|
||||
}
|
||||
|
||||
def _get_product_price(self, product, *args, **kwargs):
|
||||
"""Compute the pricelist price for the specified product, qty & uom.
|
||||
|
||||
Note: self and self.ensure_one()
|
||||
|
||||
:param product: product record (product.product/product.template)
|
||||
:param float quantity: quantity of products requested (in given uom)
|
||||
:param currency: record of currency (res.currency) (optional)
|
||||
:param uom: unit of measure (uom.uom record) (optional)
|
||||
If not specified, prices returned are expressed in product uoms
|
||||
:param date: date to use for price computation and currency conversions (optional)
|
||||
:type date: date or datetime
|
||||
|
||||
:returns: unit price of the product, considering pricelist rules if any
|
||||
:rtype: float
|
||||
"""
|
||||
self and self.ensure_one() # self is at most one record
|
||||
return self._compute_price_rule(product, *args, **kwargs)[product.id][0]
|
||||
|
||||
def _get_product_price_rule(self, product, *args, **kwargs):
|
||||
"""Compute the pricelist price & rule for the specified product, qty & uom.
|
||||
|
||||
Note: self and self.ensure_one()
|
||||
|
||||
:param product: product record (product.product/product.template)
|
||||
:param float quantity: quantity of products requested (in given uom)
|
||||
:param currency: record of currency (res.currency) (optional)
|
||||
:param uom: unit of measure (uom.uom record) (optional)
|
||||
If not specified, prices returned are expressed in product uoms
|
||||
:param date: date to use for price computation and currency conversions (optional)
|
||||
:type date: date or datetime
|
||||
|
||||
:returns: (product unit price, applied pricelist rule id)
|
||||
:rtype: tuple(float, int)
|
||||
"""
|
||||
self and self.ensure_one() # self is at most one record
|
||||
return self._compute_price_rule(product, *args, **kwargs)[product.id]
|
||||
|
||||
def _get_product_rule(self, product, *args, **kwargs):
|
||||
"""Compute the pricelist price & rule for the specified product, qty & uom.
|
||||
|
||||
Note: self and self.ensure_one()
|
||||
|
||||
:param product: product record (product.product/product.template)
|
||||
:param float quantity: quantity of products requested (in given uom)
|
||||
:param currency: record of currency (res.currency) (optional)
|
||||
:param uom: unit of measure (uom.uom record) (optional)
|
||||
If not specified, prices returned are expressed in product uoms
|
||||
:param date: date to use for price computation and currency conversions (optional)
|
||||
:type date: date or datetime
|
||||
|
||||
:returns: applied pricelist rule id
|
||||
:rtype: int or False
|
||||
"""
|
||||
self and self.ensure_one() # self is at most one record
|
||||
return self._compute_price_rule(product, *args, compute_price=False, **kwargs)[product.id][1]
|
||||
|
||||
def _compute_price_rule(
|
||||
self, products, quantity, currency=None, uom=None, date=False, compute_price=True,
|
||||
**kwargs
|
||||
):
|
||||
""" Low-level method - Mono pricelist, multi products
|
||||
Returns: dict{product_id: (price, suitable_rule) for the given pricelist}
|
||||
|
||||
Note: self and self.ensure_one()
|
||||
|
||||
:param products: recordset of products (product.product/product.template)
|
||||
:param float quantity: quantity of products requested (in given uom)
|
||||
:param currency: record of currency (res.currency)
|
||||
note: currency.ensure_one()
|
||||
:param uom: unit of measure (uom.uom record)
|
||||
If not specified, prices returned are expressed in product uoms
|
||||
:param date: date to use for price computation and currency conversions
|
||||
:type date: date or datetime
|
||||
:param bool compute_price: whether the price should be computed (default: True)
|
||||
|
||||
:returns: product_id: (price, pricelist_rule)
|
||||
:rtype: dict
|
||||
"""
|
||||
self and self.ensure_one() # self is at most one record
|
||||
|
||||
currency = currency or self.currency_id or self.env.company.currency_id
|
||||
currency.ensure_one()
|
||||
|
||||
if not products:
|
||||
return {}
|
||||
|
||||
if not date:
|
||||
# Used to fetch pricelist rules and currency rates
|
||||
date = fields.Datetime.now()
|
||||
|
||||
# Fetch all rules potentially matching specified products/templates/categories and date
|
||||
rules = self._get_applicable_rules(products, date, **kwargs)
|
||||
|
||||
results = {}
|
||||
for product in products:
|
||||
suitable_rule = self.env['product.pricelist.item']
|
||||
|
||||
product_uom = product.uom_id
|
||||
target_uom = uom or product_uom # If no uom is specified, fall back on the product uom
|
||||
|
||||
# Compute quantity in product uom because pricelist rules are specified
|
||||
# w.r.t product default UoM (min_quantity, price_surchage, ...)
|
||||
if target_uom != product_uom:
|
||||
qty_in_product_uom = target_uom._compute_quantity(
|
||||
quantity, product_uom, raise_if_failure=False
|
||||
)
|
||||
else:
|
||||
qty_in_product_uom = quantity
|
||||
|
||||
for rule in rules:
|
||||
if rule._is_applicable_for(product, qty_in_product_uom):
|
||||
suitable_rule = rule
|
||||
break
|
||||
|
||||
if compute_price:
|
||||
price = suitable_rule._compute_price(
|
||||
product, quantity, target_uom, date=date, currency=currency)
|
||||
else:
|
||||
# Skip price computation when only the rule is requested.
|
||||
price = 0.0
|
||||
results[product.id] = (price, suitable_rule.id)
|
||||
|
||||
return results
|
||||
|
||||
# Split methods to ease (community) overrides
|
||||
def _get_applicable_rules(self, products, date, **kwargs):
|
||||
self and self.ensure_one() # self is at most one record
|
||||
if not self:
|
||||
return self.env['product.pricelist.item']
|
||||
|
||||
# Do not filter out archived pricelist items, since it means current pricelist is also archived
|
||||
# We do not want the computation of prices for archived pricelist to always fallback on the Sales price
|
||||
# because no rule was found (thanks to the automatic orm filtering on active field)
|
||||
return self.env['product.pricelist.item'].with_context(active_test=False).search(
|
||||
self._get_applicable_rules_domain(products=products, date=date, **kwargs)
|
||||
).with_context(self.env.context)
|
||||
|
||||
def _get_applicable_rules_domain(self, products, date, **kwargs):
|
||||
self and self.ensure_one() # self is at most one record
|
||||
if products._name == 'product.template':
|
||||
templates_domain = ('product_tmpl_id', 'in', products.ids)
|
||||
products_domain = ('product_id.product_tmpl_id', 'in', products.ids)
|
||||
else:
|
||||
templates_domain = ('product_tmpl_id', 'in', products.product_tmpl_id.ids)
|
||||
products_domain = ('product_id', 'in', products.ids)
|
||||
|
||||
return [
|
||||
('pricelist_id', '=', self.id),
|
||||
'|', ('categ_id', '=', False), ('categ_id', 'parent_of', products.categ_id.ids),
|
||||
'|', ('product_tmpl_id', '=', False), templates_domain,
|
||||
'|', ('product_id', '=', False), products_domain,
|
||||
'|', ('date_start', '=', False), ('date_start', '<=', date),
|
||||
'|', ('date_end', '=', False), ('date_end', '>=', date),
|
||||
]
|
||||
|
||||
# Multi pricelists price|rule computation
|
||||
def _price_get(self, product, quantity, **kwargs):
|
||||
""" Multi pricelist, mono product - returns price per pricelist """
|
||||
return {
|
||||
key: price[0]
|
||||
for key, price in self._compute_price_rule_multi(product, quantity, **kwargs)[product.id].items()}
|
||||
|
||||
def _compute_price_rule_multi(self, products, quantity, uom=None, date=False, **kwargs):
|
||||
""" Low-level method - Multi pricelist, multi products
|
||||
Returns: dict{product_id: dict{pricelist_id: (price, suitable_rule)} }"""
|
||||
if not self.ids:
|
||||
pricelists = self.search([])
|
||||
else:
|
||||
pricelists = self
|
||||
results = {}
|
||||
for pricelist in pricelists:
|
||||
subres = pricelist._compute_price_rule(products, quantity, uom=uom, date=date, **kwargs)
|
||||
for product_id, price in subres.items():
|
||||
results.setdefault(product_id, {})
|
||||
results[product_id][pricelist.id] = price
|
||||
return results
|
||||
|
||||
# res.partner.property_product_pricelist field computation
|
||||
@api.model
|
||||
def _get_partner_pricelist_multi(self, partner_ids):
|
||||
""" Retrieve the applicable pricelist for given partners in a given company.
|
||||
|
||||
It will return the first found pricelist in this order:
|
||||
First, the pricelist of the specific property (res_id set), this one
|
||||
is created when saving a pricelist on the partner form view.
|
||||
Else, it will return the pricelist of the partner country group
|
||||
Else, it will return the generic property (res_id not set)
|
||||
Else, it will return the first available pricelist if any
|
||||
|
||||
:param int company_id: if passed, used for looking up properties,
|
||||
instead of current user's company
|
||||
:return: a dict {partner_id: pricelist}
|
||||
"""
|
||||
# `partner_ids` might be ID from inactive users. We should use active_test
|
||||
# as we will do a search() later (real case for website public user).
|
||||
Partner = self.env['res.partner'].with_context(active_test=False)
|
||||
company_id = self.env.company.id
|
||||
|
||||
Property = self.env['ir.property'].with_company(company_id)
|
||||
Pricelist = self.env['product.pricelist']
|
||||
pl_domain = self._get_partner_pricelist_multi_search_domain_hook(company_id)
|
||||
|
||||
# if no specific property, try to find a fitting pricelist
|
||||
result = Property._get_multi('property_product_pricelist', Partner._name, partner_ids)
|
||||
|
||||
remaining_partner_ids = [pid for pid, val in result.items() if not val or
|
||||
not val._get_partner_pricelist_multi_filter_hook()]
|
||||
if remaining_partner_ids:
|
||||
# get fallback pricelist when no pricelist for a given country
|
||||
pl_fallback = (
|
||||
Pricelist.search(pl_domain + [('country_group_ids', '=', False)], limit=1) or
|
||||
Property._get('property_product_pricelist', 'res.partner') or
|
||||
Pricelist.search(pl_domain, limit=1)
|
||||
)
|
||||
# group partners by country, and find a pricelist for each country
|
||||
remaining_partners = self.env['res.partner'].browse(remaining_partner_ids)
|
||||
partners_by_country = remaining_partners.grouped('country_id')
|
||||
for country, partners in partners_by_country.items():
|
||||
pl = Pricelist.search(pl_domain + [('country_group_ids.country_ids', '=', country.id if country else False)], limit=1)
|
||||
pl = pl or pl_fallback
|
||||
for pid in partners.ids:
|
||||
result[pid] = pl
|
||||
|
||||
return result
|
||||
|
||||
def _get_partner_pricelist_multi_search_domain_hook(self, company_id):
|
||||
return [
|
||||
('active', '=', True),
|
||||
('company_id', 'in', [company_id, False]),
|
||||
]
|
||||
|
||||
def _get_partner_pricelist_multi_filter_hook(self):
|
||||
return self.filtered('active')
|
||||
|
||||
@api.model
|
||||
def get_import_templates(self):
|
||||
return [{
|
||||
'label': _('Import Template for Pricelists'),
|
||||
'template': '/product/static/xls/product_pricelist.xls'
|
||||
}]
|
||||
|
||||
@api.ondelete(at_uninstall=False)
|
||||
def _unlink_except_used_as_rule_base(self):
|
||||
linked_items = self.env['product.pricelist.item'].sudo().with_context(active_test=False).search([
|
||||
('base', '=', 'pricelist'),
|
||||
('base_pricelist_id', 'in', self.ids),
|
||||
('pricelist_id', 'not in', self.ids),
|
||||
])
|
||||
if linked_items:
|
||||
raise UserError(_(
|
||||
'You cannot delete those pricelist(s):\n(%s)\n, they are used in other pricelist(s):\n%s',
|
||||
'\n'.join(linked_items.base_pricelist_id.mapped('display_name')),
|
||||
'\n'.join(linked_items.pricelist_id.mapped('display_name'))
|
||||
))
|
462
models/product_pricelist_item.py
Normal file
462
models/product_pricelist_item.py
Normal file
@ -0,0 +1,462 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, fields, models, tools, _
|
||||
from odoo.exceptions import ValidationError
|
||||
from odoo.tools import format_datetime, formatLang
|
||||
|
||||
|
||||
class PricelistItem(models.Model):
|
||||
_name = "product.pricelist.item"
|
||||
_description = "Pricelist Rule"
|
||||
_order = "applied_on, min_quantity desc, categ_id desc, id desc"
|
||||
_check_company_auto = True
|
||||
|
||||
def _default_pricelist_id(self):
|
||||
return self.env['product.pricelist'].search([
|
||||
'|', ('company_id', '=', False),
|
||||
('company_id', '=', self.env.company.id)], limit=1)
|
||||
|
||||
pricelist_id = fields.Many2one(
|
||||
comodel_name='product.pricelist',
|
||||
string="Pricelist",
|
||||
index=True, ondelete='cascade',
|
||||
required=True,
|
||||
default=_default_pricelist_id)
|
||||
|
||||
company_id = fields.Many2one(related='pricelist_id.company_id', store=True)
|
||||
currency_id = fields.Many2one(related='pricelist_id.currency_id', store=True)
|
||||
|
||||
date_start = fields.Datetime(
|
||||
string="Start Date",
|
||||
help="Starting datetime for the pricelist item validation\n"
|
||||
"The displayed value depends on the timezone set in your preferences.")
|
||||
date_end = fields.Datetime(
|
||||
string="End Date",
|
||||
help="Ending datetime for the pricelist item validation\n"
|
||||
"The displayed value depends on the timezone set in your preferences.")
|
||||
|
||||
min_quantity = fields.Float(
|
||||
string="Min. Quantity",
|
||||
default=0,
|
||||
digits='Product Unit of Measure',
|
||||
help="For the rule to apply, bought/sold quantity must be greater "
|
||||
"than or equal to the minimum quantity specified in this field.\n"
|
||||
"Expressed in the default unit of measure of the product.")
|
||||
|
||||
applied_on = fields.Selection(
|
||||
selection=[
|
||||
('3_global', "All Products"),
|
||||
('2_product_category', "Product Category"),
|
||||
('1_product', "Product"),
|
||||
('0_product_variant', "Product Variant"),
|
||||
],
|
||||
string="Apply On",
|
||||
default='3_global',
|
||||
required=True,
|
||||
help="Pricelist Item applicable on selected option")
|
||||
|
||||
categ_id = fields.Many2one(
|
||||
comodel_name='product.category',
|
||||
string="Product Category",
|
||||
ondelete='cascade',
|
||||
help="Specify a product category if this rule only applies to products belonging to this category or its children categories. Keep empty otherwise.")
|
||||
product_tmpl_id = fields.Many2one(
|
||||
comodel_name='product.template',
|
||||
string="Product",
|
||||
ondelete='cascade', check_company=True,
|
||||
help="Specify a template if this rule only applies to one product template. Keep empty otherwise.")
|
||||
product_id = fields.Many2one(
|
||||
comodel_name='product.product',
|
||||
string="Product Variant",
|
||||
ondelete='cascade', check_company=True,
|
||||
help="Specify a product if this rule only applies to one product. Keep empty otherwise.")
|
||||
|
||||
base = fields.Selection(
|
||||
selection=[
|
||||
('list_price', 'Sales Price'),
|
||||
('standard_price', 'Cost'),
|
||||
('pricelist', 'Other Pricelist'),
|
||||
],
|
||||
string="Based on",
|
||||
default='list_price',
|
||||
required=True,
|
||||
help="Base price for computation.\n"
|
||||
"Sales Price: The base price will be the Sales Price.\n"
|
||||
"Cost Price: The base price will be the cost price.\n"
|
||||
"Other Pricelist: Computation of the base price based on another Pricelist.")
|
||||
base_pricelist_id = fields.Many2one('product.pricelist', 'Other Pricelist', check_company=True)
|
||||
|
||||
compute_price = fields.Selection(
|
||||
selection=[
|
||||
('fixed', "Fixed Price"),
|
||||
('percentage', "Discount"),
|
||||
('formula', "Formula"),
|
||||
],
|
||||
index=True, default='fixed', required=True)
|
||||
|
||||
fixed_price = fields.Float(string="Fixed Price", digits='Product Price')
|
||||
percent_price = fields.Float(
|
||||
string="Percentage Price",
|
||||
help="You can apply a mark-up by setting a negative discount.")
|
||||
|
||||
price_discount = fields.Float(
|
||||
string="Price Discount",
|
||||
default=0,
|
||||
digits=(16, 2),
|
||||
help="You can apply a mark-up by setting a negative discount.")
|
||||
price_round = fields.Float(
|
||||
string="Price Rounding",
|
||||
digits='Product Price',
|
||||
help="Sets the price so that it is a multiple of this value.\n"
|
||||
"Rounding is applied after the discount and before the surcharge.\n"
|
||||
"To have prices that end in 9.99, set rounding 10, surcharge -0.01")
|
||||
price_surcharge = fields.Float(
|
||||
string="Price Surcharge",
|
||||
digits='Product Price',
|
||||
help="Specify the fixed amount to add or subtract (if negative) to the amount calculated with the discount.")
|
||||
|
||||
price_min_margin = fields.Float(
|
||||
string="Min. Price Margin",
|
||||
digits='Product Price',
|
||||
help="Specify the minimum amount of margin over the base price.")
|
||||
price_max_margin = fields.Float(
|
||||
string="Max. Price Margin",
|
||||
digits='Product Price',
|
||||
help="Specify the maximum amount of margin over the base price.")
|
||||
|
||||
# functional fields used for usability purposes
|
||||
name = fields.Char(
|
||||
string="Name",
|
||||
compute='_compute_name_and_price',
|
||||
help="Explicit rule name for this pricelist line.")
|
||||
price = fields.Char(
|
||||
string="Price",
|
||||
compute='_compute_name_and_price',
|
||||
help="Explicit rule name for this pricelist line.")
|
||||
rule_tip = fields.Char(compute='_compute_rule_tip')
|
||||
|
||||
#=== COMPUTE METHODS ===#
|
||||
|
||||
@api.depends('applied_on', 'categ_id', 'product_tmpl_id', 'product_id', 'compute_price', 'fixed_price', \
|
||||
'pricelist_id', 'percent_price', 'price_discount', 'price_surcharge')
|
||||
def _compute_name_and_price(self):
|
||||
for item in self:
|
||||
if item.categ_id and item.applied_on == '2_product_category':
|
||||
item.name = _("Category: %s", item.categ_id.display_name)
|
||||
elif item.product_tmpl_id and item.applied_on == '1_product':
|
||||
item.name = _("Product: %s", item.product_tmpl_id.display_name)
|
||||
elif item.product_id and item.applied_on == '0_product_variant':
|
||||
item.name = _("Variant: %s", item.product_id.display_name)
|
||||
else:
|
||||
item.name = _("All Products")
|
||||
|
||||
if item.compute_price == 'fixed':
|
||||
item.price = formatLang(
|
||||
item.env, item.fixed_price, monetary=True, dp="Product Price", currency_obj=item.currency_id)
|
||||
elif item.compute_price == 'percentage':
|
||||
item.price = _("%s %% discount", item.percent_price)
|
||||
else:
|
||||
item.price = _("%(percentage)s %% discount and %(price)s surcharge", percentage=item.price_discount, price=item.price_surcharge)
|
||||
|
||||
@api.depends_context('lang')
|
||||
@api.depends('compute_price', 'price_discount', 'price_surcharge', 'base', 'price_round')
|
||||
def _compute_rule_tip(self):
|
||||
base_selection_vals = {elem[0]: elem[1] for elem in self._fields['base']._description_selection(self.env)}
|
||||
self.rule_tip = False
|
||||
for item in self:
|
||||
if item.compute_price != 'formula':
|
||||
continue
|
||||
base_amount = 100
|
||||
discount_factor = (100 - item.price_discount) / 100
|
||||
discounted_price = base_amount * discount_factor
|
||||
if item.price_round:
|
||||
discounted_price = tools.float_round(discounted_price, precision_rounding=item.price_round)
|
||||
surcharge = tools.format_amount(item.env, item.price_surcharge, item.currency_id)
|
||||
item.rule_tip = _(
|
||||
"%(base)s with a %(discount)s %% discount and %(surcharge)s extra fee\n"
|
||||
"Example: %(amount)s * %(discount_charge)s + %(price_surcharge)s → %(total_amount)s",
|
||||
base=base_selection_vals[item.base],
|
||||
discount=item.price_discount,
|
||||
surcharge=surcharge,
|
||||
amount=tools.format_amount(item.env, 100, item.currency_id),
|
||||
discount_charge=discount_factor,
|
||||
price_surcharge=surcharge,
|
||||
total_amount=tools.format_amount(
|
||||
item.env, discounted_price + item.price_surcharge, item.currency_id),
|
||||
)
|
||||
|
||||
#=== CONSTRAINT METHODS ===#
|
||||
|
||||
@api.constrains('base_pricelist_id', 'pricelist_id', 'base')
|
||||
def _check_recursion(self):
|
||||
if any(item.base == 'pricelist' and item.pricelist_id and item.pricelist_id == item.base_pricelist_id for item in self):
|
||||
raise ValidationError(_('You cannot assign the Main Pricelist as Other Pricelist in PriceList Item'))
|
||||
|
||||
@api.constrains('date_start', 'date_end')
|
||||
def _check_date_range(self):
|
||||
for item in self:
|
||||
if item.date_start and item.date_end and item.date_start >= item.date_end:
|
||||
raise ValidationError(_('%s: end date (%s) should be greater than start date (%s)', item.display_name, format_datetime(self.env, item.date_end), format_datetime(self.env, item.date_start)))
|
||||
return True
|
||||
|
||||
@api.constrains('price_min_margin', 'price_max_margin')
|
||||
def _check_margin(self):
|
||||
if any(item.price_min_margin > item.price_max_margin for item in self):
|
||||
raise ValidationError(_('The minimum margin should be lower than the maximum margin.'))
|
||||
|
||||
@api.constrains('product_id', 'product_tmpl_id', 'categ_id')
|
||||
def _check_product_consistency(self):
|
||||
for item in self:
|
||||
if item.applied_on == "2_product_category" and not item.categ_id:
|
||||
raise ValidationError(_("Please specify the category for which this rule should be applied"))
|
||||
elif item.applied_on == "1_product" and not item.product_tmpl_id:
|
||||
raise ValidationError(_("Please specify the product for which this rule should be applied"))
|
||||
elif item.applied_on == "0_product_variant" and not item.product_id:
|
||||
raise ValidationError(_("Please specify the product variant for which this rule should be applied"))
|
||||
|
||||
#=== ONCHANGE METHODS ===#
|
||||
|
||||
@api.onchange('compute_price')
|
||||
def _onchange_compute_price(self):
|
||||
if self.compute_price != 'fixed':
|
||||
self.fixed_price = 0.0
|
||||
if self.compute_price != 'percentage':
|
||||
self.percent_price = 0.0
|
||||
if self.compute_price != 'formula':
|
||||
self.update({
|
||||
'base': 'list_price',
|
||||
'price_discount': 0.0,
|
||||
'price_surcharge': 0.0,
|
||||
'price_round': 0.0,
|
||||
'price_min_margin': 0.0,
|
||||
'price_max_margin': 0.0,
|
||||
})
|
||||
|
||||
@api.onchange('product_id')
|
||||
def _onchange_product_id(self):
|
||||
has_product_id = self.filtered('product_id')
|
||||
for item in has_product_id:
|
||||
item.product_tmpl_id = item.product_id.product_tmpl_id
|
||||
if self.env.context.get('default_applied_on', False) == '1_product':
|
||||
# If a product variant is specified, apply on variants instead
|
||||
# Reset if product variant is removed
|
||||
has_product_id.update({'applied_on': '0_product_variant'})
|
||||
(self - has_product_id).update({'applied_on': '1_product'})
|
||||
|
||||
@api.onchange('product_tmpl_id')
|
||||
def _onchange_product_tmpl_id(self):
|
||||
has_tmpl_id = self.filtered('product_tmpl_id')
|
||||
for item in has_tmpl_id:
|
||||
if item.product_id and item.product_id.product_tmpl_id != item.product_tmpl_id:
|
||||
item.product_id = None
|
||||
|
||||
@api.onchange('product_id', 'product_tmpl_id', 'categ_id')
|
||||
def _onchange_rule_content(self):
|
||||
if not self.user_has_groups('product.group_sale_pricelist') and not self.env.context.get('default_applied_on', False):
|
||||
# If advanced pricelists are disabled (applied_on field is not visible)
|
||||
# AND we aren't coming from a specific product template/variant.
|
||||
variants_rules = self.filtered('product_id')
|
||||
template_rules = (self-variants_rules).filtered('product_tmpl_id')
|
||||
variants_rules.update({'applied_on': '0_product_variant'})
|
||||
template_rules.update({'applied_on': '1_product'})
|
||||
(self-variants_rules-template_rules).update({'applied_on': '3_global'})
|
||||
|
||||
@api.onchange('price_round')
|
||||
def _onchange_price_round(self):
|
||||
if any(item.price_round and item.price_round < 0.0 for item in self):
|
||||
raise ValidationError(_("The rounding method must be strictly positive."))
|
||||
|
||||
#=== CRUD METHODS ===#
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
for values in vals_list:
|
||||
if values.get('applied_on', False):
|
||||
# Ensure item consistency for later searches.
|
||||
applied_on = values['applied_on']
|
||||
if applied_on == '3_global':
|
||||
values.update(dict(product_id=None, product_tmpl_id=None, categ_id=None))
|
||||
elif applied_on == '2_product_category':
|
||||
values.update(dict(product_id=None, product_tmpl_id=None))
|
||||
elif applied_on == '1_product':
|
||||
values.update(dict(product_id=None, categ_id=None))
|
||||
elif applied_on == '0_product_variant':
|
||||
values.update(dict(categ_id=None))
|
||||
return super().create(vals_list)
|
||||
|
||||
def write(self, values):
|
||||
if values.get('applied_on', False):
|
||||
# Ensure item consistency for later searches.
|
||||
applied_on = values['applied_on']
|
||||
if applied_on == '3_global':
|
||||
values.update(dict(product_id=None, product_tmpl_id=None, categ_id=None))
|
||||
elif applied_on == '2_product_category':
|
||||
values.update(dict(product_id=None, product_tmpl_id=None))
|
||||
elif applied_on == '1_product':
|
||||
values.update(dict(product_id=None, categ_id=None))
|
||||
elif applied_on == '0_product_variant':
|
||||
values.update(dict(categ_id=None))
|
||||
return super().write(values)
|
||||
|
||||
#=== BUSINESS METHODS ===#
|
||||
|
||||
def _is_applicable_for(self, product, qty_in_product_uom):
|
||||
"""Check whether the current rule is valid for the given product & qty.
|
||||
|
||||
Note: self.ensure_one()
|
||||
|
||||
:param product: product record (product.product/product.template)
|
||||
:param float qty_in_product_uom: quantity, expressed in product UoM
|
||||
:returns: Whether rules is valid or not
|
||||
:rtype: bool
|
||||
"""
|
||||
self.ensure_one()
|
||||
product.ensure_one()
|
||||
res = True
|
||||
|
||||
is_product_template = product._name == 'product.template'
|
||||
if self.min_quantity and qty_in_product_uom < self.min_quantity:
|
||||
res = False
|
||||
|
||||
elif self.applied_on == "2_product_category":
|
||||
if (
|
||||
product.categ_id != self.categ_id
|
||||
and not product.categ_id.parent_path.startswith(self.categ_id.parent_path)
|
||||
):
|
||||
res = False
|
||||
else:
|
||||
# Applied on a specific product template/variant
|
||||
if is_product_template:
|
||||
if self.applied_on == "1_product" and product.id != self.product_tmpl_id.id:
|
||||
res = False
|
||||
elif self.applied_on == "0_product_variant" and not (
|
||||
product.product_variant_count == 1
|
||||
and product.product_variant_id.id == self.product_id.id
|
||||
):
|
||||
# product self acceptable on template if has only one variant
|
||||
res = False
|
||||
else:
|
||||
if self.applied_on == "1_product" and product.product_tmpl_id.id != self.product_tmpl_id.id:
|
||||
res = False
|
||||
elif self.applied_on == "0_product_variant" and product.id != self.product_id.id:
|
||||
res = False
|
||||
|
||||
return res
|
||||
|
||||
def _compute_price(self, product, quantity, uom, date, currency=None):
|
||||
"""Compute the unit price of a product in the context of a pricelist application.
|
||||
|
||||
Note: self and self.ensure_one()
|
||||
|
||||
:param product: recordset of product (product.product/product.template)
|
||||
:param float qty: quantity of products requested (in given uom)
|
||||
:param uom: unit of measure (uom.uom record)
|
||||
:param datetime date: date to use for price computation and currency conversions
|
||||
:param currency: currency (for the case where self is empty)
|
||||
|
||||
:returns: price according to pricelist rule or the product price, expressed in the param
|
||||
currency, the pricelist currency or the company currency
|
||||
:rtype: float
|
||||
"""
|
||||
self and self.ensure_one() # self is at most one record
|
||||
product.ensure_one()
|
||||
uom.ensure_one()
|
||||
|
||||
currency = currency or self.currency_id or self.env.company.currency_id
|
||||
currency.ensure_one()
|
||||
|
||||
# Pricelist specific values are specified according to product UoM
|
||||
# and must be multiplied according to the factor between uoms
|
||||
product_uom = product.uom_id
|
||||
if product_uom != uom:
|
||||
convert = lambda p: product_uom._compute_price(p, uom)
|
||||
else:
|
||||
convert = lambda p: p
|
||||
|
||||
if self.compute_price == 'fixed':
|
||||
price = convert(self.fixed_price)
|
||||
elif self.compute_price == 'percentage':
|
||||
base_price = self._compute_base_price(product, quantity, uom, date, currency)
|
||||
price = (base_price - (base_price * (self.percent_price / 100))) or 0.0
|
||||
elif self.compute_price == 'formula':
|
||||
base_price = self._compute_base_price(product, quantity, uom, date, currency)
|
||||
# complete formula
|
||||
price_limit = base_price
|
||||
price = (base_price - (base_price * (self.price_discount / 100))) or 0.0
|
||||
if self.price_round:
|
||||
price = tools.float_round(price, precision_rounding=self.price_round)
|
||||
|
||||
if self.price_surcharge:
|
||||
price += convert(self.price_surcharge)
|
||||
|
||||
if self.price_min_margin:
|
||||
price = max(price, price_limit + convert(self.price_min_margin))
|
||||
|
||||
if self.price_max_margin:
|
||||
price = min(price, price_limit + convert(self.price_max_margin))
|
||||
else: # empty self, or extended pricelist price computation logic
|
||||
price = self._compute_base_price(product, quantity, uom, date, currency)
|
||||
|
||||
return price
|
||||
|
||||
def _compute_base_price(self, product, quantity, uom, date, currency):
|
||||
""" Compute the base price for a given rule
|
||||
|
||||
:param product: recordset of product (product.product/product.template)
|
||||
:param float qty: quantity of products requested (in given uom)
|
||||
:param uom: unit of measure (uom.uom record)
|
||||
:param datetime date: date to use for price computation and currency conversions
|
||||
:param currency: currency in which the returned price must be expressed
|
||||
|
||||
:returns: base price, expressed in provided pricelist currency
|
||||
:rtype: float
|
||||
"""
|
||||
currency.ensure_one()
|
||||
|
||||
rule_base = self.base or 'list_price'
|
||||
if rule_base == 'pricelist' and self.base_pricelist_id:
|
||||
price = self.base_pricelist_id._get_product_price(
|
||||
product, quantity, currency=self.base_pricelist_id.currency_id, uom=uom, date=date
|
||||
)
|
||||
src_currency = self.base_pricelist_id.currency_id
|
||||
elif rule_base == "standard_price":
|
||||
src_currency = product.cost_currency_id
|
||||
price = product._price_compute(rule_base, uom=uom, date=date)[product.id]
|
||||
else: # list_price
|
||||
src_currency = product.currency_id
|
||||
price = product._price_compute(rule_base, uom=uom, date=date)[product.id]
|
||||
|
||||
if src_currency != currency:
|
||||
price = src_currency._convert(price, currency, self.env.company, date, round=False)
|
||||
|
||||
return price
|
||||
|
||||
def _compute_price_before_discount(self, *args, **kwargs):
|
||||
"""Compute the base price of the lowest pricelist rule whose pricelist discount_policy
|
||||
is set to show the discount to the customer.
|
||||
|
||||
:param product: recordset of product (product.product/product.template)
|
||||
:param float qty: quantity of products requested (in given uom)
|
||||
:param uom: unit of measure (uom.uom record)
|
||||
:param datetime date: date to use for price computation and currency conversions
|
||||
:param currency: currency in which the returned price must be expressed
|
||||
|
||||
:returns: base price, expressed in provided pricelist currency
|
||||
:rtype: float
|
||||
"""
|
||||
pricelist_rule = self
|
||||
if pricelist_rule and pricelist_rule.pricelist_id.discount_policy == 'without_discount':
|
||||
pricelist_item = pricelist_rule
|
||||
# Find the lowest pricelist rule whose pricelist is configured to show the discount
|
||||
# to the customer.
|
||||
while (
|
||||
pricelist_item.base == 'pricelist'
|
||||
and pricelist_item.base_pricelist_id.discount_policy == 'without_discount'
|
||||
):
|
||||
rule_id = pricelist_item.base_pricelist_id._get_product_rule(*args, **kwargs)
|
||||
pricelist_item = self.env['product.pricelist.item'].browse(rule_id)
|
||||
|
||||
pricelist_rule = pricelist_item
|
||||
|
||||
return pricelist_rule._compute_base_price(*args, **kwargs)
|
800
models/product_product.py
Normal file
800
models/product_product.py
Normal file
@ -0,0 +1,800 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
import re
|
||||
from collections import defaultdict
|
||||
from operator import itemgetter
|
||||
|
||||
from odoo import api, fields, models, tools, _
|
||||
from odoo.exceptions import ValidationError
|
||||
from odoo.osv import expression
|
||||
from odoo.tools import float_compare, groupby
|
||||
from odoo.tools.misc import unique
|
||||
|
||||
|
||||
class ProductProduct(models.Model):
|
||||
_name = "product.product"
|
||||
_description = "Product Variant"
|
||||
_inherits = {'product.template': 'product_tmpl_id'}
|
||||
_inherit = ['mail.thread', 'mail.activity.mixin']
|
||||
_order = 'priority desc, default_code, name, id'
|
||||
|
||||
# price_extra: catalog extra value only, sum of variant extra attributes
|
||||
price_extra = fields.Float(
|
||||
'Variant Price Extra', compute='_compute_product_price_extra',
|
||||
digits='Product Price',
|
||||
help="This is the sum of the extra price of all attributes")
|
||||
# lst_price: catalog value + extra, context dependent (uom)
|
||||
lst_price = fields.Float(
|
||||
'Sales Price', compute='_compute_product_lst_price',
|
||||
digits='Product Price', inverse='_set_product_lst_price',
|
||||
help="The sale price is managed from the product template. Click on the 'Configure Variants' button to set the extra attribute prices.")
|
||||
|
||||
default_code = fields.Char('Internal Reference', index=True)
|
||||
code = fields.Char('Reference', compute='_compute_product_code')
|
||||
partner_ref = fields.Char('Customer Ref', compute='_compute_partner_ref')
|
||||
|
||||
active = fields.Boolean(
|
||||
'Active', default=True,
|
||||
help="If unchecked, it will allow you to hide the product without removing it.")
|
||||
product_tmpl_id = fields.Many2one(
|
||||
'product.template', 'Product Template',
|
||||
auto_join=True, index=True, ondelete="cascade", required=True)
|
||||
barcode = fields.Char(
|
||||
'Barcode', copy=False, index='btree_not_null',
|
||||
help="International Article Number used for product identification.")
|
||||
product_template_attribute_value_ids = fields.Many2many('product.template.attribute.value', relation='product_variant_combination', string="Attribute Values", ondelete='restrict')
|
||||
product_template_variant_value_ids = fields.Many2many('product.template.attribute.value', relation='product_variant_combination',
|
||||
domain=[('attribute_line_id.value_count', '>', 1)], string="Variant Values", ondelete='restrict')
|
||||
combination_indices = fields.Char(compute='_compute_combination_indices', store=True, index=True)
|
||||
is_product_variant = fields.Boolean(compute='_compute_is_product_variant')
|
||||
|
||||
standard_price = fields.Float(
|
||||
'Cost', company_dependent=True,
|
||||
digits='Product Price',
|
||||
groups="base.group_user",
|
||||
help="""Value of the product (automatically computed in AVCO).
|
||||
Used to value the product when the purchase cost is not known (e.g. inventory adjustment).
|
||||
Used to compute margins on sale orders.""")
|
||||
volume = fields.Float('Volume', digits='Volume')
|
||||
weight = fields.Float('Weight', digits='Stock Weight')
|
||||
|
||||
pricelist_item_count = fields.Integer("Number of price rules", compute="_compute_variant_item_count")
|
||||
|
||||
product_document_ids = fields.One2many(
|
||||
string="Documents",
|
||||
comodel_name='product.document',
|
||||
inverse_name='res_id',
|
||||
domain=lambda self: [('res_model', '=', self._name)])
|
||||
product_document_count = fields.Integer(
|
||||
string="Documents Count", compute='_compute_product_document_count')
|
||||
|
||||
packaging_ids = fields.One2many(
|
||||
'product.packaging', 'product_id', 'Product Packages',
|
||||
help="Gives the different ways to package the same product.")
|
||||
|
||||
additional_product_tag_ids = fields.Many2many(
|
||||
string="Additional Product Tags",
|
||||
comodel_name='product.tag',
|
||||
relation='product_tag_product_product_rel',
|
||||
domain="[('id', 'not in', product_tag_ids)]",
|
||||
)
|
||||
all_product_tag_ids = fields.Many2many('product.tag', compute='_compute_all_product_tag_ids', search='_search_all_product_tag_ids')
|
||||
|
||||
# all image fields are base64 encoded and PIL-supported
|
||||
|
||||
# all image_variant fields are technical and should not be displayed to the user
|
||||
image_variant_1920 = fields.Image("Variant Image", max_width=1920, max_height=1920)
|
||||
|
||||
# resized fields stored (as attachment) for performance
|
||||
image_variant_1024 = fields.Image("Variant Image 1024", related="image_variant_1920", max_width=1024, max_height=1024, store=True)
|
||||
image_variant_512 = fields.Image("Variant Image 512", related="image_variant_1920", max_width=512, max_height=512, store=True)
|
||||
image_variant_256 = fields.Image("Variant Image 256", related="image_variant_1920", max_width=256, max_height=256, store=True)
|
||||
image_variant_128 = fields.Image("Variant Image 128", related="image_variant_1920", max_width=128, max_height=128, store=True)
|
||||
can_image_variant_1024_be_zoomed = fields.Boolean("Can Variant Image 1024 be zoomed", compute='_compute_can_image_variant_1024_be_zoomed', store=True)
|
||||
|
||||
# Computed fields that are used to create a fallback to the template if
|
||||
# necessary, it's recommended to display those fields to the user.
|
||||
image_1920 = fields.Image("Image", compute='_compute_image_1920', inverse='_set_image_1920')
|
||||
image_1024 = fields.Image("Image 1024", compute='_compute_image_1024')
|
||||
image_512 = fields.Image("Image 512", compute='_compute_image_512')
|
||||
image_256 = fields.Image("Image 256", compute='_compute_image_256')
|
||||
image_128 = fields.Image("Image 128", compute='_compute_image_128')
|
||||
can_image_1024_be_zoomed = fields.Boolean("Can Image 1024 be zoomed", compute='_compute_can_image_1024_be_zoomed')
|
||||
write_date = fields.Datetime(compute='_compute_write_date', store=True)
|
||||
|
||||
@api.depends('image_variant_1920', 'image_variant_1024')
|
||||
def _compute_can_image_variant_1024_be_zoomed(self):
|
||||
for record in self:
|
||||
record.can_image_variant_1024_be_zoomed = record.image_variant_1920 and tools.is_image_size_above(record.image_variant_1920, record.image_variant_1024)
|
||||
|
||||
def _set_template_field(self, template_field, variant_field):
|
||||
for record in self:
|
||||
if (
|
||||
# We are trying to remove a field from the variant even though it is already
|
||||
# not set on the variant, remove it from the template instead.
|
||||
(not record[template_field] and not record[variant_field])
|
||||
# We are trying to add a field to the variant, but the template field is
|
||||
# not set, write on the template instead.
|
||||
or (record[template_field] and not record.product_tmpl_id[template_field])
|
||||
# There is only one variant, always write on the template.
|
||||
or self.search_count([
|
||||
('product_tmpl_id', '=', record.product_tmpl_id.id),
|
||||
('active', '=', True),
|
||||
]) <= 1
|
||||
):
|
||||
record[variant_field] = False
|
||||
record.product_tmpl_id[template_field] = record[template_field]
|
||||
else:
|
||||
record[variant_field] = record[template_field]
|
||||
|
||||
@api.depends("product_tmpl_id.write_date")
|
||||
def _compute_write_date(self):
|
||||
"""
|
||||
First, the purpose of this computation is to update a product's
|
||||
write_date whenever its template's write_date is updated. Indeed,
|
||||
when a template's image is modified, updating its products'
|
||||
write_date will invalidate the browser's cache for the products'
|
||||
image, which may be the same as the template's. This guarantees UI
|
||||
consistency.
|
||||
|
||||
Second, the field 'write_date' is automatically updated by the
|
||||
framework when the product is modified. The recomputation of the
|
||||
field supplements that behavior to keep the product's write_date
|
||||
up-to-date with its template's write_date.
|
||||
|
||||
Third, the framework normally prevents us from updating write_date
|
||||
because it is a "magic" field. However, the assignment inside the
|
||||
compute method is not subject to this restriction. It therefore
|
||||
works as intended :-)
|
||||
"""
|
||||
for record in self:
|
||||
record.write_date = max(record.write_date or self.env.cr.now(), record.product_tmpl_id.write_date)
|
||||
|
||||
def _compute_image_1920(self):
|
||||
"""Get the image from the template if no image is set on the variant."""
|
||||
for record in self:
|
||||
record.image_1920 = record.image_variant_1920 or record.product_tmpl_id.image_1920
|
||||
|
||||
def _set_image_1920(self):
|
||||
return self._set_template_field('image_1920', 'image_variant_1920')
|
||||
|
||||
def _compute_image_1024(self):
|
||||
"""Get the image from the template if no image is set on the variant."""
|
||||
for record in self:
|
||||
record.image_1024 = record.image_variant_1024 or record.product_tmpl_id.image_1024
|
||||
|
||||
def _compute_image_512(self):
|
||||
"""Get the image from the template if no image is set on the variant."""
|
||||
for record in self:
|
||||
record.image_512 = record.image_variant_512 or record.product_tmpl_id.image_512
|
||||
|
||||
def _compute_image_256(self):
|
||||
"""Get the image from the template if no image is set on the variant."""
|
||||
for record in self:
|
||||
record.image_256 = record.image_variant_256 or record.product_tmpl_id.image_256
|
||||
|
||||
def _compute_image_128(self):
|
||||
"""Get the image from the template if no image is set on the variant."""
|
||||
for record in self:
|
||||
record.image_128 = record.image_variant_128 or record.product_tmpl_id.image_128
|
||||
|
||||
def _compute_can_image_1024_be_zoomed(self):
|
||||
"""Get the image from the template if no image is set on the variant."""
|
||||
for record in self:
|
||||
record.can_image_1024_be_zoomed = record.can_image_variant_1024_be_zoomed if record.image_variant_1920 else record.product_tmpl_id.can_image_1024_be_zoomed
|
||||
|
||||
def _get_placeholder_filename(self, field):
|
||||
image_fields = ['image_%s' % size for size in [1920, 1024, 512, 256, 128]]
|
||||
if field in image_fields:
|
||||
return 'product/static/img/placeholder_thumbnail.png'
|
||||
return super()._get_placeholder_filename(field)
|
||||
|
||||
def init(self):
|
||||
"""Ensure there is at most one active variant for each combination.
|
||||
|
||||
There could be no variant for a combination if using dynamic attributes.
|
||||
"""
|
||||
self.env.cr.execute("CREATE UNIQUE INDEX IF NOT EXISTS product_product_combination_unique ON %s (product_tmpl_id, combination_indices) WHERE active is true"
|
||||
% self._table)
|
||||
|
||||
def _get_barcodes_by_company(self):
|
||||
return [
|
||||
(company_id, [p.barcode for p in products if p.barcode])
|
||||
for company_id, products in groupby(self, lambda p: p.company_id.id)
|
||||
]
|
||||
|
||||
def _get_barcode_search_domain(self, barcodes_within_company, company_id):
|
||||
domain = [('barcode', 'in', barcodes_within_company)]
|
||||
if company_id:
|
||||
domain.append(('company_id', 'in', (False, company_id)))
|
||||
return domain
|
||||
|
||||
def _check_duplicated_product_barcodes(self, barcodes_within_company, company_id):
|
||||
domain = self._get_barcode_search_domain(barcodes_within_company, company_id)
|
||||
products_by_barcode = self.sudo().read_group(domain, ['barcode', 'id:array_agg'], ['barcode'])
|
||||
|
||||
duplicates_as_str = "\n".join(
|
||||
_(
|
||||
"- Barcode \"%s\" already assigned to product(s): %s",
|
||||
record['barcode'], ", ".join(p.display_name for p in self.search([('id', 'in', record['id'])]))
|
||||
)
|
||||
for record in products_by_barcode if len(record['id']) > 1
|
||||
)
|
||||
if duplicates_as_str.strip():
|
||||
duplicates_as_str += _(
|
||||
"\n\nNote: products that you don't have access to will not be shown above."
|
||||
)
|
||||
raise ValidationError(_("Barcode(s) already assigned:\n\n%s", duplicates_as_str))
|
||||
|
||||
def _check_duplicated_packaging_barcodes(self, barcodes_within_company, company_id):
|
||||
packaging_domain = self._get_barcode_search_domain(barcodes_within_company, company_id)
|
||||
if self.env['product.packaging'].sudo().search(packaging_domain, order="id", limit=1):
|
||||
raise ValidationError(_("A packaging already uses the barcode"))
|
||||
|
||||
@api.constrains('barcode')
|
||||
def _check_barcode_uniqueness(self):
|
||||
""" With GS1 nomenclature, products and packagings use the same pattern. Therefore, we need
|
||||
to ensure the uniqueness between products' barcodes and packagings' ones"""
|
||||
# Barcodes should only be unique within a company
|
||||
for company_id, barcodes_within_company in self._get_barcodes_by_company():
|
||||
self._check_duplicated_product_barcodes(barcodes_within_company, company_id)
|
||||
self._check_duplicated_packaging_barcodes(barcodes_within_company, company_id)
|
||||
|
||||
def _get_invoice_policy(self):
|
||||
return False
|
||||
|
||||
@api.depends('product_template_attribute_value_ids')
|
||||
def _compute_combination_indices(self):
|
||||
for product in self:
|
||||
product.combination_indices = product.product_template_attribute_value_ids._ids2str()
|
||||
|
||||
def _compute_is_product_variant(self):
|
||||
self.is_product_variant = True
|
||||
|
||||
@api.onchange('lst_price')
|
||||
def _set_product_lst_price(self):
|
||||
for product in self:
|
||||
if self._context.get('uom'):
|
||||
value = self.env['uom.uom'].browse(self._context['uom'])._compute_price(product.lst_price, product.uom_id)
|
||||
else:
|
||||
value = product.lst_price
|
||||
value -= product.price_extra
|
||||
product.write({'list_price': value})
|
||||
|
||||
@api.depends("product_template_attribute_value_ids.price_extra")
|
||||
def _compute_product_price_extra(self):
|
||||
for product in self:
|
||||
product.price_extra = sum(product.product_template_attribute_value_ids.mapped('price_extra'))
|
||||
|
||||
@api.depends('list_price', 'price_extra')
|
||||
@api.depends_context('uom')
|
||||
def _compute_product_lst_price(self):
|
||||
to_uom = None
|
||||
if 'uom' in self._context:
|
||||
to_uom = self.env['uom.uom'].browse(self._context['uom'])
|
||||
|
||||
for product in self:
|
||||
if to_uom:
|
||||
list_price = product.uom_id._compute_price(product.list_price, to_uom)
|
||||
else:
|
||||
list_price = product.list_price
|
||||
product.lst_price = list_price + product.price_extra
|
||||
|
||||
@api.depends_context('partner_id')
|
||||
def _compute_product_code(self):
|
||||
for product in self:
|
||||
product.code = product.default_code
|
||||
if self.env['ir.model.access'].check('product.supplierinfo', 'read', False):
|
||||
for supplier_info in product.seller_ids:
|
||||
if supplier_info.partner_id.id == product._context.get('partner_id'):
|
||||
product.code = supplier_info.product_code or product.default_code
|
||||
break
|
||||
|
||||
@api.depends_context('partner_id')
|
||||
def _compute_partner_ref(self):
|
||||
for product in self:
|
||||
for supplier_info in product.seller_ids:
|
||||
if supplier_info.partner_id.id == product._context.get('partner_id'):
|
||||
product_name = supplier_info.product_name or product.default_code or product.name
|
||||
product.partner_ref = '%s%s' % (product.code and '[%s] ' % product.code or '', product_name)
|
||||
break
|
||||
else:
|
||||
product.partner_ref = product.display_name
|
||||
|
||||
def _compute_variant_item_count(self):
|
||||
for product in self:
|
||||
domain = ['|',
|
||||
'&', ('product_tmpl_id', '=', product.product_tmpl_id.id), ('applied_on', '=', '1_product'),
|
||||
'&', ('product_id', '=', product.id), ('applied_on', '=', '0_product_variant')]
|
||||
product.pricelist_item_count = self.env['product.pricelist.item'].search_count(domain)
|
||||
|
||||
def _compute_product_document_count(self):
|
||||
for product in self:
|
||||
product.product_document_count = product.env['product.document'].search_count([
|
||||
('res_model', '=', 'product.product'),
|
||||
('res_id', '=', product.id),
|
||||
])
|
||||
|
||||
@api.depends('product_tag_ids', 'additional_product_tag_ids')
|
||||
def _compute_all_product_tag_ids(self):
|
||||
for product in self:
|
||||
product.all_product_tag_ids = product.product_tag_ids | product.additional_product_tag_ids
|
||||
|
||||
def _search_all_product_tag_ids(self, operator, operand):
|
||||
if operator in expression.NEGATIVE_TERM_OPERATORS:
|
||||
return [('product_tag_ids', operator, operand), ('additional_product_tag_ids', operator, operand)]
|
||||
return ['|', ('product_tag_ids', operator, operand), ('additional_product_tag_ids', operator, operand)]
|
||||
|
||||
@api.onchange('uom_id')
|
||||
def _onchange_uom_id(self):
|
||||
if self.uom_id:
|
||||
self.uom_po_id = self.uom_id.id
|
||||
|
||||
@api.onchange('uom_po_id')
|
||||
def _onchange_uom(self):
|
||||
if self.uom_id and self.uom_po_id and self.uom_id.category_id != self.uom_po_id.category_id:
|
||||
self.uom_po_id = self.uom_id
|
||||
|
||||
@api.onchange('default_code')
|
||||
def _onchange_default_code(self):
|
||||
if not self.default_code:
|
||||
return
|
||||
|
||||
domain = [('default_code', '=', self.default_code)]
|
||||
if self.id.origin:
|
||||
domain.append(('id', '!=', self.id.origin))
|
||||
|
||||
if self.env['product.product'].search(domain, limit=1):
|
||||
return {'warning': {
|
||||
'title': _("Note:"),
|
||||
'message': _("The Internal Reference '%s' already exists.", self.default_code),
|
||||
}}
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
for vals in vals_list:
|
||||
self.product_tmpl_id._sanitize_vals(vals)
|
||||
products = super(ProductProduct, self.with_context(create_product_product=False)).create(vals_list)
|
||||
# `_get_variant_id_for_combination` depends on existing variants
|
||||
self.env.registry.clear_cache()
|
||||
return products
|
||||
|
||||
def write(self, values):
|
||||
self.product_tmpl_id._sanitize_vals(values)
|
||||
res = super(ProductProduct, self).write(values)
|
||||
if 'product_template_attribute_value_ids' in values:
|
||||
# `_get_variant_id_for_combination` depends on `product_template_attribute_value_ids`
|
||||
self.env.registry.clear_cache()
|
||||
elif 'active' in values:
|
||||
# `_get_first_possible_variant_id` depends on variants active state
|
||||
self.env.registry.clear_cache()
|
||||
return res
|
||||
|
||||
def unlink(self):
|
||||
unlink_products = self.env['product.product']
|
||||
unlink_templates = self.env['product.template']
|
||||
for product in self:
|
||||
# If there is an image set on the variant and no image set on the
|
||||
# template, move the image to the template.
|
||||
if product.image_variant_1920 and not product.product_tmpl_id.image_1920:
|
||||
product.product_tmpl_id.image_1920 = product.image_variant_1920
|
||||
# Check if product still exists, in case it has been unlinked by unlinking its template
|
||||
if not product.exists():
|
||||
continue
|
||||
# Check if the product is last product of this template...
|
||||
other_products = self.search([('product_tmpl_id', '=', product.product_tmpl_id.id), ('id', '!=', product.id)])
|
||||
# ... and do not delete product template if it's configured to be created "on demand"
|
||||
if not other_products and not product.product_tmpl_id.has_dynamic_attributes():
|
||||
unlink_templates |= product.product_tmpl_id
|
||||
unlink_products |= product
|
||||
res = super(ProductProduct, unlink_products).unlink()
|
||||
# delete templates after calling super, as deleting template could lead to deleting
|
||||
# products due to ondelete='cascade'
|
||||
unlink_templates.unlink()
|
||||
# `_get_variant_id_for_combination` depends on existing variants
|
||||
self.env.registry.clear_cache()
|
||||
return res
|
||||
|
||||
def _filter_to_unlink(self, check_access=True):
|
||||
return self
|
||||
|
||||
def _unlink_or_archive(self, check_access=True):
|
||||
"""Unlink or archive products.
|
||||
Try in batch as much as possible because it is much faster.
|
||||
Use dichotomy when an exception occurs.
|
||||
"""
|
||||
|
||||
# Avoid access errors in case the products is shared amongst companies
|
||||
# but the underlying objects are not. If unlink fails because of an
|
||||
# AccessError (e.g. while recomputing fields), the 'write' call will
|
||||
# fail as well for the same reason since the field has been set to
|
||||
# recompute.
|
||||
if check_access:
|
||||
self.check_access_rights('unlink')
|
||||
self.check_access_rule('unlink')
|
||||
self.check_access_rights('write')
|
||||
self.check_access_rule('write')
|
||||
self = self.sudo()
|
||||
to_unlink = self._filter_to_unlink()
|
||||
to_archive = self - to_unlink
|
||||
to_archive.write({'active': False})
|
||||
self = to_unlink
|
||||
|
||||
try:
|
||||
with self.env.cr.savepoint(), tools.mute_logger('odoo.sql_db'):
|
||||
self.unlink()
|
||||
except Exception:
|
||||
# We catch all kind of exceptions to be sure that the operation
|
||||
# doesn't fail.
|
||||
if len(self) > 1:
|
||||
self[:len(self) // 2]._unlink_or_archive(check_access=False)
|
||||
self[len(self) // 2:]._unlink_or_archive(check_access=False)
|
||||
else:
|
||||
if self.active:
|
||||
# Note: this can still fail if something is preventing
|
||||
# from archiving.
|
||||
# This is the case from existing stock reordering rules.
|
||||
self.write({'active': False})
|
||||
|
||||
@api.returns('self', lambda value: value.id)
|
||||
def copy(self, default=None):
|
||||
"""Variants are generated depending on the configuration of attributes
|
||||
and values on the template, so copying them does not make sense.
|
||||
|
||||
For convenience the template is copied instead and its first variant is
|
||||
returned.
|
||||
"""
|
||||
# copy variant is disabled in https://github.com/odoo/odoo/pull/38303
|
||||
# this returns the first possible combination of variant to make it
|
||||
# works for now, need to be fixed to return product_variant_id if it's
|
||||
# possible in the future
|
||||
template = self.product_tmpl_id.copy(default=default)
|
||||
return template.product_variant_id or template._create_first_product_variant()
|
||||
|
||||
@api.model
|
||||
def _search(self, domain, offset=0, limit=None, order=None, access_rights_uid=None):
|
||||
# TDE FIXME: strange
|
||||
if self._context.get('search_default_categ_id'):
|
||||
domain = domain.copy()
|
||||
domain.append((('categ_id', 'child_of', self._context['search_default_categ_id'])))
|
||||
return super()._search(domain, offset, limit, order, access_rights_uid)
|
||||
|
||||
@api.depends('name', 'default_code', 'product_tmpl_id')
|
||||
@api.depends_context('display_default_code', 'seller_id', 'company_id', 'partner_id')
|
||||
def _compute_display_name(self):
|
||||
|
||||
def get_display_name(name, code):
|
||||
if self._context.get('display_default_code', True) and code:
|
||||
return f'[{code}] {name}'
|
||||
return name
|
||||
|
||||
partner_id = self._context.get('partner_id')
|
||||
if partner_id:
|
||||
partner_ids = [partner_id, self.env['res.partner'].browse(partner_id).commercial_partner_id.id]
|
||||
else:
|
||||
partner_ids = []
|
||||
company_id = self.env.context.get('company_id')
|
||||
|
||||
# all user don't have access to seller and partner
|
||||
# check access and use superuser
|
||||
self.check_access_rights("read")
|
||||
self.check_access_rule("read")
|
||||
|
||||
product_template_ids = self.sudo().product_tmpl_id.ids
|
||||
|
||||
if partner_ids:
|
||||
# prefetch the fields used by the `display_name`
|
||||
supplier_info = self.env['product.supplierinfo'].sudo().search_fetch(
|
||||
[('product_tmpl_id', 'in', product_template_ids), ('partner_id', 'in', partner_ids)],
|
||||
['product_tmpl_id', 'product_id', 'company_id', 'product_name', 'product_code'],
|
||||
)
|
||||
supplier_info_by_template = {}
|
||||
for r in supplier_info:
|
||||
supplier_info_by_template.setdefault(r.product_tmpl_id, []).append(r)
|
||||
|
||||
for product in self.sudo():
|
||||
variant = product.product_template_attribute_value_ids._get_combination_name()
|
||||
|
||||
name = variant and "%s (%s)" % (product.name, variant) or product.name
|
||||
sellers = self.env['product.supplierinfo'].sudo().browse(self.env.context.get('seller_id')) or []
|
||||
if not sellers and partner_ids:
|
||||
product_supplier_info = supplier_info_by_template.get(product.product_tmpl_id, [])
|
||||
sellers = [x for x in product_supplier_info if x.product_id and x.product_id == product]
|
||||
if not sellers:
|
||||
sellers = [x for x in product_supplier_info if not x.product_id]
|
||||
# Filter out sellers based on the company. This is done afterwards for a better
|
||||
# code readability. At this point, only a few sellers should remain, so it should
|
||||
# not be a performance issue.
|
||||
if company_id:
|
||||
sellers = [x for x in sellers if x.company_id.id in [company_id, False]]
|
||||
if sellers:
|
||||
temp = []
|
||||
for s in sellers:
|
||||
seller_variant = s.product_name and (
|
||||
variant and "%s (%s)" % (s.product_name, variant) or s.product_name
|
||||
) or False
|
||||
temp.append(get_display_name(seller_variant or name, s.product_code or product.default_code))
|
||||
|
||||
# => Feature drop here, one record can only have one display_name now, instead separate with `,`
|
||||
# Remove this comment
|
||||
product.display_name = ", ".join(unique(temp))
|
||||
else:
|
||||
product.display_name = get_display_name(name, product.default_code)
|
||||
|
||||
@api.model
|
||||
def _name_search(self, name, domain=None, operator='ilike', limit=None, order=None):
|
||||
domain = domain or []
|
||||
if name:
|
||||
positive_operators = ['=', 'ilike', '=ilike', 'like', '=like']
|
||||
product_ids = []
|
||||
if operator in positive_operators:
|
||||
product_ids = list(self._search([('default_code', '=', name)] + domain, limit=limit, order=order))
|
||||
if not product_ids:
|
||||
product_ids = list(self._search([('barcode', '=', name)] + domain, limit=limit, order=order))
|
||||
if not product_ids and operator not in expression.NEGATIVE_TERM_OPERATORS:
|
||||
# Do not merge the 2 next lines into one single search, SQL search performance would be abysmal
|
||||
# on a database with thousands of matching products, due to the huge merge+unique needed for the
|
||||
# OR operator (and given the fact that the 'name' lookup results come from the ir.translation table
|
||||
# Performing a quick memory merge of ids in Python will give much better performance
|
||||
product_ids = list(self._search(domain + [('default_code', operator, name)], limit=limit, order=order))
|
||||
if not limit or len(product_ids) < limit:
|
||||
# we may underrun the limit because of dupes in the results, that's fine
|
||||
limit2 = (limit - len(product_ids)) if limit else False
|
||||
product2_ids = self._search(domain + [('name', operator, name), ('id', 'not in', product_ids)], limit=limit2, order=order)
|
||||
product_ids.extend(product2_ids)
|
||||
elif not product_ids and operator in expression.NEGATIVE_TERM_OPERATORS:
|
||||
domain2 = expression.OR([
|
||||
['&', ('default_code', operator, name), ('name', operator, name)],
|
||||
['&', ('default_code', '=', False), ('name', operator, name)],
|
||||
])
|
||||
domain2 = expression.AND([domain, domain2])
|
||||
product_ids = list(self._search(domain2, limit=limit, order=order))
|
||||
if not product_ids and operator in positive_operators:
|
||||
ptrn = re.compile('(\[(.*?)\])')
|
||||
res = ptrn.search(name)
|
||||
if res:
|
||||
product_ids = list(self._search([('default_code', '=', res.group(2))] + domain, limit=limit, order=order))
|
||||
# still no results, partner in context: search on supplier info as last hope to find something
|
||||
if not product_ids and self._context.get('partner_id'):
|
||||
suppliers_ids = self.env['product.supplierinfo']._search([
|
||||
('partner_id', '=', self._context.get('partner_id')),
|
||||
'|',
|
||||
('product_code', operator, name),
|
||||
('product_name', operator, name)])
|
||||
if suppliers_ids:
|
||||
product_ids = self._search([('product_tmpl_id.seller_ids', 'in', suppliers_ids)], limit=limit, order=order)
|
||||
else:
|
||||
product_ids = self._search(domain, limit=limit, order=order)
|
||||
return product_ids
|
||||
|
||||
@api.model
|
||||
def view_header_get(self, view_id, view_type):
|
||||
if self._context.get('categ_id'):
|
||||
return _(
|
||||
'Products: %(category)s',
|
||||
category=self.env['product.category'].browse(self.env.context['categ_id']).name,
|
||||
)
|
||||
return super().view_header_get(view_id, view_type)
|
||||
|
||||
#=== ACTION METHODS ===#
|
||||
|
||||
def action_open_label_layout(self):
|
||||
action = self.env['ir.actions.act_window']._for_xml_id('product.action_open_label_layout')
|
||||
action['context'] = {'default_product_ids': self.ids}
|
||||
return action
|
||||
|
||||
def open_pricelist_rules(self):
|
||||
self.ensure_one()
|
||||
domain = ['|',
|
||||
'&', ('product_tmpl_id', '=', self.product_tmpl_id.id), ('applied_on', '=', '1_product'),
|
||||
'&', ('product_id', '=', self.id), ('applied_on', '=', '0_product_variant')]
|
||||
return {
|
||||
'name': _('Price Rules'),
|
||||
'view_mode': 'tree,form',
|
||||
'views': [(self.env.ref('product.product_pricelist_item_tree_view_from_product').id, 'tree'), (False, 'form')],
|
||||
'res_model': 'product.pricelist.item',
|
||||
'type': 'ir.actions.act_window',
|
||||
'target': 'current',
|
||||
'domain': domain,
|
||||
'context': {
|
||||
'default_product_id': self.id,
|
||||
'default_applied_on': '0_product_variant',
|
||||
'search_default_visible': True,
|
||||
}
|
||||
}
|
||||
|
||||
def open_product_template(self):
|
||||
""" Utility method used to add an "Open Template" button in product views """
|
||||
self.ensure_one()
|
||||
return {
|
||||
'type': 'ir.actions.act_window',
|
||||
'res_model': 'product.template',
|
||||
'view_mode': 'form',
|
||||
'res_id': self.product_tmpl_id.id,
|
||||
'target': 'new'
|
||||
}
|
||||
|
||||
def action_open_documents(self):
|
||||
res = self.product_tmpl_id.action_open_documents()
|
||||
res['context'].update({
|
||||
'default_res_model': self._name,
|
||||
'default_res_id': self.id,
|
||||
'search_default_context_variant': True,
|
||||
})
|
||||
return res
|
||||
|
||||
#=== BUSINESS METHODS ===#
|
||||
|
||||
def _prepare_sellers(self, params=False):
|
||||
return self.seller_ids.filtered(lambda s: s.partner_id.active).sorted(lambda s: (s.sequence, -s.min_qty, s.price, s.id))
|
||||
|
||||
def _get_filtered_sellers(self, partner_id=False, quantity=0.0, date=None, uom_id=False, params=False):
|
||||
self.ensure_one()
|
||||
if date is None:
|
||||
date = fields.Date.context_today(self)
|
||||
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
|
||||
|
||||
sellers_filtered = self._prepare_sellers(params)
|
||||
sellers_filtered = sellers_filtered.filtered(lambda s: not s.company_id or s.company_id.id == self.env.company.id)
|
||||
sellers = self.env['product.supplierinfo']
|
||||
for seller in sellers_filtered:
|
||||
# Set quantity in UoM of seller
|
||||
quantity_uom_seller = quantity
|
||||
if quantity_uom_seller and uom_id and uom_id != seller.product_uom:
|
||||
quantity_uom_seller = uom_id._compute_quantity(quantity_uom_seller, seller.product_uom)
|
||||
|
||||
if seller.date_start and seller.date_start > date:
|
||||
continue
|
||||
if seller.date_end and seller.date_end < date:
|
||||
continue
|
||||
if partner_id and seller.partner_id not in [partner_id, partner_id.parent_id]:
|
||||
continue
|
||||
if quantity is not None and float_compare(quantity_uom_seller, seller.min_qty, precision_digits=precision) == -1:
|
||||
continue
|
||||
if seller.product_id and seller.product_id != self:
|
||||
continue
|
||||
sellers |= seller
|
||||
return sellers
|
||||
|
||||
def _select_seller(self, partner_id=False, quantity=0.0, date=None, uom_id=False, ordered_by='price_discounted', params=False):
|
||||
# Always sort by discounted price but another field can take the primacy through the `ordered_by` param.
|
||||
sort_key = itemgetter('price_discounted', 'sequence', 'id')
|
||||
if ordered_by != 'price_discounted':
|
||||
sort_key = itemgetter(ordered_by, 'price_discounted', 'sequence', 'id')
|
||||
|
||||
sellers = self._get_filtered_sellers(partner_id=partner_id, quantity=quantity, date=date, uom_id=uom_id, params=params)
|
||||
res = self.env['product.supplierinfo']
|
||||
for seller in sellers:
|
||||
if not res or res.partner_id == seller.partner_id:
|
||||
res |= seller
|
||||
return res and res.sorted(sort_key)[:1]
|
||||
|
||||
def _get_product_price_context(self, combination):
|
||||
self.ensure_one()
|
||||
res = {}
|
||||
|
||||
# It is possible that a no_variant attribute is still in a variant if
|
||||
# the type of the attribute has been changed after creation.
|
||||
no_variant_attributes_price_extra = [
|
||||
ptav.price_extra for ptav in combination.filtered(
|
||||
lambda ptav:
|
||||
ptav.price_extra
|
||||
and ptav.product_tmpl_id == self.product_tmpl_id
|
||||
and ptav not in self.product_template_attribute_value_ids
|
||||
)
|
||||
]
|
||||
if no_variant_attributes_price_extra:
|
||||
res['no_variant_attributes_price_extra'] = tuple(no_variant_attributes_price_extra)
|
||||
|
||||
return res
|
||||
|
||||
def _get_attributes_extra_price(self):
|
||||
self.ensure_one()
|
||||
|
||||
return self.price_extra + sum(
|
||||
self.env.context.get('no_variant_attributes_price_extra', []))
|
||||
|
||||
def _price_compute(self, price_type, uom=None, currency=None, company=None, date=False):
|
||||
company = company or self.env.company
|
||||
date = date or fields.Date.context_today(self)
|
||||
|
||||
self = self.with_company(company)
|
||||
if price_type == 'standard_price':
|
||||
# standard_price field can only be seen by users in base.group_user
|
||||
# Thus, in order to compute the sale price from the cost for users not in this group
|
||||
# We fetch the standard price as the superuser
|
||||
self = self.sudo()
|
||||
|
||||
prices = dict.fromkeys(self.ids, 0.0)
|
||||
for product in self:
|
||||
price = product[price_type] or 0.0
|
||||
price_currency = product.currency_id
|
||||
if price_type == 'standard_price':
|
||||
price_currency = product.cost_currency_id
|
||||
elif price_type == 'list_price':
|
||||
price += product._get_attributes_extra_price()
|
||||
|
||||
if uom:
|
||||
price = product.uom_id._compute_price(price, uom)
|
||||
|
||||
# Convert from current user company currency to asked one
|
||||
# This is right cause a field cannot be in more than one currency
|
||||
if currency:
|
||||
price = price_currency._convert(price, currency, company, date)
|
||||
|
||||
prices[product.id] = price
|
||||
|
||||
return prices
|
||||
|
||||
@api.model
|
||||
def get_empty_list_help(self, help_message):
|
||||
self = self.with_context(
|
||||
empty_list_help_document_name=_("product"),
|
||||
)
|
||||
return super(ProductProduct, self).get_empty_list_help(help_message)
|
||||
|
||||
def get_product_multiline_description_sale(self):
|
||||
""" Compute a multiline description of this product, in the context of sales
|
||||
(do not use for purchases or other display reasons that don't intend to use "description_sale").
|
||||
It will often be used as the default description of a sale order line referencing this product.
|
||||
"""
|
||||
name = self.display_name
|
||||
if self.description_sale:
|
||||
name += '\n' + self.description_sale
|
||||
|
||||
return name
|
||||
|
||||
def _is_variant_possible(self, parent_combination=None):
|
||||
"""Return whether the variant is possible based on its own combination,
|
||||
and optionally a parent combination.
|
||||
|
||||
See `_is_combination_possible` for more information.
|
||||
|
||||
:param parent_combination: combination from which `self` is an
|
||||
optional or accessory product.
|
||||
:type parent_combination: recordset `product.template.attribute.value`
|
||||
|
||||
:return: ẁhether the variant is possible based on its own combination
|
||||
:rtype: bool
|
||||
"""
|
||||
self.ensure_one()
|
||||
return self.product_tmpl_id._is_combination_possible(self.product_template_attribute_value_ids, parent_combination=parent_combination, ignore_no_variant=True)
|
||||
|
||||
def toggle_active(self):
|
||||
""" Archiving related product.template if there is not any more active product.product
|
||||
(and vice versa, unarchiving the related product template if there is now an active product.product) """
|
||||
result = super().toggle_active()
|
||||
# We deactivate product templates which are active with no active variants.
|
||||
tmpl_to_deactivate = self.filtered(lambda product: (product.product_tmpl_id.active
|
||||
and not product.product_tmpl_id.product_variant_ids)).mapped('product_tmpl_id')
|
||||
# We activate product templates which are inactive with active variants.
|
||||
tmpl_to_activate = self.filtered(lambda product: (not product.product_tmpl_id.active
|
||||
and product.product_tmpl_id.product_variant_ids)).mapped('product_tmpl_id')
|
||||
(tmpl_to_deactivate + tmpl_to_activate).toggle_active()
|
||||
return result
|
||||
|
||||
def get_contextual_price(self):
|
||||
return self._get_contextual_price()
|
||||
|
||||
def _get_contextual_price(self):
|
||||
self.ensure_one()
|
||||
return self.product_tmpl_id._get_contextual_price(self)
|
||||
|
||||
def _get_contextual_discount(self):
|
||||
self.ensure_one()
|
||||
|
||||
pricelist = self.product_tmpl_id._get_contextual_pricelist()
|
||||
if not pricelist:
|
||||
# No pricelist = no discount
|
||||
return 0.0
|
||||
|
||||
lst_price = self.currency_id._convert(
|
||||
self.lst_price,
|
||||
pricelist.currency_id,
|
||||
self.env.company,
|
||||
fields.Datetime.now(),
|
||||
)
|
||||
if lst_price:
|
||||
return (lst_price - self._get_contextual_price()) / lst_price
|
||||
return 0.0
|
102
models/product_supplierinfo.py
Normal file
102
models/product_supplierinfo.py
Normal file
@ -0,0 +1,102 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, fields, models, _
|
||||
|
||||
|
||||
class SupplierInfo(models.Model):
|
||||
_name = "product.supplierinfo"
|
||||
_description = "Supplier Pricelist"
|
||||
_order = 'sequence, min_qty DESC, price, id'
|
||||
_rec_name = 'partner_id'
|
||||
|
||||
def _default_product_id(self):
|
||||
product_id = self.env.get('default_product_id')
|
||||
if not product_id:
|
||||
model, active_id = [self.env.context.get(k) for k in ['model', 'active_id']]
|
||||
if model == 'product.product' and active_id:
|
||||
product_id = self.env[model].browse(active_id).exists()
|
||||
return product_id
|
||||
|
||||
partner_id = fields.Many2one(
|
||||
'res.partner', 'Vendor',
|
||||
ondelete='cascade', required=True,
|
||||
check_company=True)
|
||||
product_name = fields.Char(
|
||||
'Vendor Product Name',
|
||||
help="This vendor's product name will be used when printing a request for quotation. Keep empty to use the internal one.")
|
||||
product_code = fields.Char(
|
||||
'Vendor Product Code',
|
||||
help="This vendor's product code will be used when printing a request for quotation. Keep empty to use the internal one.")
|
||||
sequence = fields.Integer(
|
||||
'Sequence', default=1, help="Assigns the priority to the list of product vendor.")
|
||||
product_uom = fields.Many2one(
|
||||
'uom.uom', 'Unit of Measure',
|
||||
related='product_tmpl_id.uom_po_id')
|
||||
min_qty = fields.Float(
|
||||
'Quantity', default=0.0, required=True, digits="Product Unit of Measure",
|
||||
help="The quantity to purchase from this vendor to benefit from the price, expressed in the vendor Product Unit of Measure if not any, in the default unit of measure of the product otherwise.")
|
||||
price = fields.Float(
|
||||
'Price', default=0.0, digits='Product Price',
|
||||
required=True, help="The price to purchase a product")
|
||||
price_discounted = fields.Float('Discounted Price', compute='_compute_price_discounted')
|
||||
company_id = fields.Many2one(
|
||||
'res.company', 'Company',
|
||||
default=lambda self: self.env.company.id, index=1)
|
||||
currency_id = fields.Many2one(
|
||||
'res.currency', 'Currency',
|
||||
default=lambda self: self.env.company.currency_id.id,
|
||||
required=True)
|
||||
date_start = fields.Date('Start Date', help="Start date for this vendor price")
|
||||
date_end = fields.Date('End Date', help="End date for this vendor price")
|
||||
product_id = fields.Many2one(
|
||||
'product.product', 'Product Variant', check_company=True,
|
||||
domain="[('product_tmpl_id', '=', product_tmpl_id)] if product_tmpl_id else []",
|
||||
default=_default_product_id,
|
||||
help="If not set, the vendor price will apply to all variants of this product.")
|
||||
product_tmpl_id = fields.Many2one(
|
||||
'product.template', 'Product Template', check_company=True,
|
||||
index=True, ondelete='cascade')
|
||||
product_variant_count = fields.Integer('Variant Count', related='product_tmpl_id.product_variant_count')
|
||||
delay = fields.Integer(
|
||||
'Delivery Lead Time', default=1, required=True,
|
||||
help="Lead time in days between the confirmation of the purchase order and the receipt of the products in your warehouse. Used by the scheduler for automatic computation of the purchase order planning.")
|
||||
discount = fields.Float(
|
||||
string="Discount (%)",
|
||||
digits='Discount',
|
||||
readonly=False)
|
||||
|
||||
@api.depends('discount', 'price')
|
||||
def _compute_price_discounted(self):
|
||||
for rec in self:
|
||||
rec.price_discounted = rec.price * (1 - rec.discount / 100)
|
||||
|
||||
@api.onchange('product_tmpl_id')
|
||||
def _onchange_product_tmpl_id(self):
|
||||
"""Clear product variant if it no longer matches the product template."""
|
||||
if self.product_id and self.product_id not in self.product_tmpl_id.product_variant_ids:
|
||||
self.product_id = False
|
||||
|
||||
@api.model
|
||||
def get_import_templates(self):
|
||||
return [{
|
||||
'label': _('Import Template for Vendor Pricelists'),
|
||||
'template': '/product/static/xls/product_supplierinfo.xls'
|
||||
}]
|
||||
|
||||
def _sanitize_vals(self, vals):
|
||||
"""Sanitize vals to sync product variant & template on read/write."""
|
||||
# add product's product_tmpl_id if none present in vals
|
||||
if vals.get('product_id') and not vals.get('product_tmpl_id'):
|
||||
product = self.env['product.product'].browse(vals['product_id'])
|
||||
vals['product_tmpl_id'] = product.product_tmpl_id.id
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
for vals in vals_list:
|
||||
self._sanitize_vals(vals)
|
||||
return super().create(vals_list)
|
||||
|
||||
def write(self, vals):
|
||||
self._sanitize_vals(vals)
|
||||
return super().write(vals)
|
56
models/product_tag.py
Normal file
56
models/product_tag.py
Normal file
@ -0,0 +1,56 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import _, api, fields, models
|
||||
from odoo.osv import expression
|
||||
|
||||
class ProductTag(models.Model):
|
||||
_name = 'product.tag'
|
||||
_description = 'Product Tag'
|
||||
|
||||
def _get_default_template_id(self):
|
||||
return self.env['product.template'].browse(self.env.context.get('product_template_id'))
|
||||
|
||||
def _get_default_variant_id(self):
|
||||
return self.env['product.product'].browse(self.env.context.get('product_variant_id'))
|
||||
|
||||
name = fields.Char(string="Name", required=True, translate=True)
|
||||
color = fields.Char(string="Color", default='#3C3C3C')
|
||||
product_template_ids = fields.Many2many(
|
||||
string="Product Templates",
|
||||
comodel_name='product.template',
|
||||
relation='product_tag_product_template_rel',
|
||||
default=_get_default_template_id,
|
||||
)
|
||||
product_product_ids = fields.Many2many(
|
||||
string="Product Variants",
|
||||
comodel_name='product.product',
|
||||
relation='product_tag_product_product_rel',
|
||||
domain="[('attribute_line_ids', '!=', False), ('product_tmpl_id', 'not in', product_template_ids)]",
|
||||
default=_get_default_variant_id,
|
||||
)
|
||||
product_ids = fields.Many2many(
|
||||
'product.product', string='All Product Variants using this Tag',
|
||||
compute='_compute_product_ids', search='_search_product_ids'
|
||||
)
|
||||
|
||||
_sql_constraints = [
|
||||
('name_uniq', 'unique (name)', "Tag name already exists!"),
|
||||
]
|
||||
|
||||
@api.depends('product_template_ids', 'product_product_ids')
|
||||
def _compute_product_ids(self):
|
||||
for tag in self:
|
||||
tag.product_ids = tag.product_template_ids.product_variant_ids | tag.product_product_ids
|
||||
|
||||
@api.returns(None, lambda value: value[0])
|
||||
def copy_data(self, default=None):
|
||||
default = default or {}
|
||||
if not default.get('name'):
|
||||
default['name'] = _('%s (copy)', self.name)
|
||||
return super().copy_data(default=default)
|
||||
|
||||
def _search_product_ids(self, operator, operand):
|
||||
if operator in expression.NEGATIVE_TERM_OPERATORS:
|
||||
return [('product_template_ids.product_variant_ids', operator, operand), ('product_product_ids', operator, operand)]
|
||||
return ['|', ('product_template_ids.product_variant_ids', operator, operand), ('product_product_ids', operator, operand)]
|
1439
models/product_template.py
Normal file
1439
models/product_template.py
Normal file
File diff suppressed because it is too large
Load Diff
26
models/product_template_attribute_exclusion.py
Normal file
26
models/product_template_attribute_exclusion.py
Normal file
@ -0,0 +1,26 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import fields, models
|
||||
|
||||
|
||||
class ProductTemplateAttributeExclusion(models.Model):
|
||||
_name = 'product.template.attribute.exclusion'
|
||||
_description = "Product Template Attribute Exclusion"
|
||||
_order = 'product_tmpl_id, id'
|
||||
|
||||
product_template_attribute_value_id = fields.Many2one(
|
||||
comodel_name='product.template.attribute.value',
|
||||
string="Attribute Value",
|
||||
ondelete='cascade',
|
||||
index=True)
|
||||
product_tmpl_id = fields.Many2one(
|
||||
comodel_name='product.template',
|
||||
string="Product Template",
|
||||
ondelete='cascade',
|
||||
required=True,
|
||||
index=True)
|
||||
value_ids = fields.Many2many(
|
||||
comodel_name='product.template.attribute.value',
|
||||
relation='product_attr_exclusion_value_ids_rel',
|
||||
string="Attribute Values",
|
||||
domain="[('product_tmpl_id', '=', product_tmpl_id), ('ptav_active', '=', True)]")
|
269
models/product_template_attribute_line.py
Normal file
269
models/product_template_attribute_line.py
Normal file
@ -0,0 +1,269 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, fields, models, tools, _
|
||||
from odoo.exceptions import UserError, ValidationError
|
||||
from odoo.fields import Command
|
||||
|
||||
|
||||
class ProductTemplateAttributeLine(models.Model):
|
||||
"""Attributes available on product.template with their selected values in a m2m.
|
||||
Used as a configuration model to generate the appropriate product.template.attribute.value"""
|
||||
|
||||
_name = 'product.template.attribute.line'
|
||||
_rec_name = 'attribute_id'
|
||||
_rec_names_search = ['attribute_id', 'value_ids']
|
||||
_description = "Product Template Attribute Line"
|
||||
_order = 'sequence, attribute_id, id'
|
||||
|
||||
active = fields.Boolean(default=True)
|
||||
product_tmpl_id = fields.Many2one(
|
||||
comodel_name='product.template',
|
||||
string="Product Template",
|
||||
ondelete='cascade',
|
||||
required=True,
|
||||
index=True)
|
||||
sequence = fields.Integer("Sequence", default=10)
|
||||
attribute_id = fields.Many2one(
|
||||
comodel_name='product.attribute',
|
||||
string="Attribute",
|
||||
ondelete='restrict',
|
||||
required=True,
|
||||
index=True)
|
||||
value_ids = fields.Many2many(
|
||||
comodel_name='product.attribute.value',
|
||||
relation='product_attribute_value_product_template_attribute_line_rel',
|
||||
string="Values",
|
||||
domain="[('attribute_id', '=', attribute_id)]",
|
||||
ondelete='restrict')
|
||||
value_count = fields.Integer(compute='_compute_value_count', store=True)
|
||||
product_template_value_ids = fields.One2many(
|
||||
comodel_name='product.template.attribute.value',
|
||||
inverse_name='attribute_line_id',
|
||||
string="Product Attribute Values")
|
||||
|
||||
@api.depends('value_ids')
|
||||
def _compute_value_count(self):
|
||||
for record in self:
|
||||
record.value_count = len(record.value_ids)
|
||||
|
||||
@api.onchange('attribute_id')
|
||||
def _onchange_attribute_id(self):
|
||||
self.value_ids = self.value_ids.filtered(lambda pav: pav.attribute_id == self.attribute_id)
|
||||
|
||||
@api.constrains('active', 'value_ids', 'attribute_id')
|
||||
def _check_valid_values(self):
|
||||
for ptal in self:
|
||||
if ptal.active and not ptal.value_ids:
|
||||
raise ValidationError(_(
|
||||
"The attribute %(attribute)s must have at least one value for the product %(product)s.",
|
||||
attribute=ptal.attribute_id.display_name,
|
||||
product=ptal.product_tmpl_id.display_name,
|
||||
))
|
||||
for pav in ptal.value_ids:
|
||||
if pav.attribute_id != ptal.attribute_id:
|
||||
raise ValidationError(_(
|
||||
"On the product %(product)s you cannot associate the value %(value)s"
|
||||
" with the attribute %(attribute)s because they do not match.",
|
||||
product=ptal.product_tmpl_id.display_name,
|
||||
value=pav.display_name,
|
||||
attribute=ptal.attribute_id.display_name,
|
||||
))
|
||||
return True
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
"""Override to:
|
||||
- Activate archived lines having the same configuration (if they exist)
|
||||
instead of creating new lines.
|
||||
- Set up related values and related variants.
|
||||
|
||||
Reactivating existing lines allows to re-use existing variants when
|
||||
possible, keeping their configuration and avoiding duplication.
|
||||
"""
|
||||
create_values = []
|
||||
activated_lines = self.env['product.template.attribute.line']
|
||||
for value in vals_list:
|
||||
vals = dict(value, active=value.get('active', True))
|
||||
# While not ideal for peformance, this search has to be done at each
|
||||
# step to exclude the lines that might have been activated at a
|
||||
# previous step. Since `vals_list` will likely be a small list in
|
||||
# all use cases, this is an acceptable trade-off.
|
||||
archived_ptal = self.search([
|
||||
('active', '=', False),
|
||||
('product_tmpl_id', '=', vals.pop('product_tmpl_id', 0)),
|
||||
('attribute_id', '=', vals.pop('attribute_id', 0)),
|
||||
], limit=1)
|
||||
if archived_ptal:
|
||||
# Write given `vals` in addition of `active` to ensure
|
||||
# `value_ids` or other fields passed to `create` are saved too,
|
||||
# but change the context to avoid updating the values and the
|
||||
# variants until all the expected lines are created/updated.
|
||||
archived_ptal.with_context(update_product_template_attribute_values=False).write(vals)
|
||||
activated_lines += archived_ptal
|
||||
else:
|
||||
create_values.append(value)
|
||||
res = activated_lines + super().create(create_values)
|
||||
if self._context.get("create_product_product", True):
|
||||
res._update_product_template_attribute_values()
|
||||
return res
|
||||
|
||||
def write(self, values):
|
||||
"""Override to:
|
||||
- Add constraints to prevent doing changes that are not supported such
|
||||
as modifying the template or the attribute of existing lines.
|
||||
- Clean up related values and related variants when archiving or when
|
||||
updating `value_ids`.
|
||||
"""
|
||||
if 'product_tmpl_id' in values:
|
||||
for ptal in self:
|
||||
if ptal.product_tmpl_id.id != values['product_tmpl_id']:
|
||||
raise UserError(_(
|
||||
"You cannot move the attribute %(attribute)s from the product"
|
||||
" %(product_src)s to the product %(product_dest)s.",
|
||||
attribute=ptal.attribute_id.display_name,
|
||||
product_src=ptal.product_tmpl_id.display_name,
|
||||
product_dest=values['product_tmpl_id'],
|
||||
))
|
||||
|
||||
if 'attribute_id' in values:
|
||||
for ptal in self:
|
||||
if ptal.attribute_id.id != values['attribute_id']:
|
||||
raise UserError(_(
|
||||
"On the product %(product)s you cannot transform the attribute"
|
||||
" %(attribute_src)s into the attribute %(attribute_dest)s.",
|
||||
product=ptal.product_tmpl_id.display_name,
|
||||
attribute_src=ptal.attribute_id.display_name,
|
||||
attribute_dest=values['attribute_id'],
|
||||
))
|
||||
# Remove all values while archiving to make sure the line is clean if it
|
||||
# is ever activated again.
|
||||
if not values.get('active', True):
|
||||
values['value_ids'] = [Command.clear()]
|
||||
res = super().write(values)
|
||||
if 'active' in values:
|
||||
self.env.flush_all()
|
||||
self.env['product.template'].invalidate_model(['attribute_line_ids'])
|
||||
# If coming from `create`, no need to update the values and the variants
|
||||
# before all lines are created.
|
||||
if self.env.context.get('update_product_template_attribute_values', True):
|
||||
self._update_product_template_attribute_values()
|
||||
return res
|
||||
|
||||
def unlink(self):
|
||||
"""Override to:
|
||||
- Archive the line if unlink is not possible.
|
||||
- Clean up related values and related variants.
|
||||
|
||||
Archiving is typically needed when the line has values that can't be
|
||||
deleted because they are referenced elsewhere (on a variant that can't
|
||||
be deleted, on a sales order line, ...).
|
||||
"""
|
||||
# Try to remove the values first to remove some potentially blocking
|
||||
# references, which typically works:
|
||||
# - For single value lines because the values are directly removed from
|
||||
# the variants.
|
||||
# - For values that are present on variants that can be deleted.
|
||||
self.product_template_value_ids._only_active().unlink()
|
||||
# Keep a reference to the related templates before the deletion.
|
||||
templates = self.product_tmpl_id
|
||||
# Now delete or archive the lines.
|
||||
ptal_to_archive = self.env['product.template.attribute.line']
|
||||
for ptal in self:
|
||||
try:
|
||||
with self.env.cr.savepoint(), tools.mute_logger('odoo.sql_db'):
|
||||
super(ProductTemplateAttributeLine, ptal).unlink()
|
||||
except Exception:
|
||||
# We catch all kind of exceptions to be sure that the operation
|
||||
# doesn't fail.
|
||||
ptal_to_archive += ptal
|
||||
ptal_to_archive.action_archive() # only calls write if there are records
|
||||
# For archived lines `_update_product_template_attribute_values` is
|
||||
# implicitly called during the `write` above, but for products that used
|
||||
# unlinked lines `_create_variant_ids` has to be called manually.
|
||||
(templates - ptal_to_archive.product_tmpl_id)._create_variant_ids()
|
||||
return True
|
||||
|
||||
def _update_product_template_attribute_values(self):
|
||||
"""Create or unlink `product.template.attribute.value` for each line in
|
||||
`self` based on `value_ids`.
|
||||
|
||||
The goal is to delete all values that are not in `value_ids`, to
|
||||
activate those in `value_ids` that are currently archived, and to create
|
||||
those in `value_ids` that didn't exist.
|
||||
|
||||
This is a trick for the form view and for performance in general,
|
||||
because we don't want to generate in advance all possible values for all
|
||||
templates, but only those that will be selected.
|
||||
"""
|
||||
ProductTemplateAttributeValue = self.env['product.template.attribute.value']
|
||||
ptav_to_create = []
|
||||
ptav_to_unlink = ProductTemplateAttributeValue
|
||||
for ptal in self:
|
||||
ptav_to_activate = ProductTemplateAttributeValue
|
||||
remaining_pav = ptal.value_ids
|
||||
for ptav in ptal.product_template_value_ids:
|
||||
if ptav.product_attribute_value_id not in remaining_pav:
|
||||
# Remove values that existed but don't exist anymore, but
|
||||
# ignore those that are already archived because if they are
|
||||
# archived it means they could not be deleted previously.
|
||||
if ptav.ptav_active:
|
||||
ptav_to_unlink += ptav
|
||||
else:
|
||||
# Activate corresponding values that are currently archived.
|
||||
remaining_pav -= ptav.product_attribute_value_id
|
||||
if not ptav.ptav_active:
|
||||
ptav_to_activate += ptav
|
||||
|
||||
for pav in remaining_pav:
|
||||
# The previous loop searched for archived values that belonged to
|
||||
# the current line, but if the line was deleted and another line
|
||||
# was recreated for the same attribute, we need to expand the
|
||||
# search to those with matching `attribute_id`.
|
||||
# While not ideal for peformance, this search has to be done at
|
||||
# each step to exclude the values that might have been activated
|
||||
# at a previous step. Since `remaining_pav` will likely be a
|
||||
# small list in all use cases, this is an acceptable trade-off.
|
||||
ptav = ProductTemplateAttributeValue.search([
|
||||
('ptav_active', '=', False),
|
||||
('product_tmpl_id', '=', ptal.product_tmpl_id.id),
|
||||
('attribute_id', '=', ptal.attribute_id.id),
|
||||
('product_attribute_value_id', '=', pav.id),
|
||||
], limit=1)
|
||||
if ptav:
|
||||
ptav.write({'ptav_active': True, 'attribute_line_id': ptal.id})
|
||||
# If the value was marked for deletion, now keep it.
|
||||
ptav_to_unlink -= ptav
|
||||
else:
|
||||
# create values that didn't exist yet
|
||||
ptav_to_create.append({
|
||||
'product_attribute_value_id': pav.id,
|
||||
'attribute_line_id': ptal.id,
|
||||
'price_extra': pav.default_extra_price,
|
||||
})
|
||||
# Handle active at each step in case a following line might want to
|
||||
# re-use a value that was archived at a previous step.
|
||||
ptav_to_activate.write({'ptav_active': True})
|
||||
ptav_to_unlink.write({'ptav_active': False})
|
||||
if ptav_to_unlink:
|
||||
ptav_to_unlink.unlink()
|
||||
ProductTemplateAttributeValue.create(ptav_to_create)
|
||||
self.product_tmpl_id._create_variant_ids()
|
||||
|
||||
def _without_no_variant_attributes(self):
|
||||
return self.filtered(lambda ptal: ptal.attribute_id.create_variant != 'no_variant')
|
||||
|
||||
def action_open_attribute_values(self):
|
||||
return {
|
||||
'type': 'ir.actions.act_window',
|
||||
'name': _("Product Variant Values"),
|
||||
'res_model': 'product.template.attribute.value',
|
||||
'view_mode': 'tree,form',
|
||||
'domain': [('id', 'in', self.product_template_value_ids.ids)],
|
||||
'views': [
|
||||
(self.env.ref('product.product_template_attribute_value_view_tree').id, 'list'),
|
||||
(self.env.ref('product.product_template_attribute_value_view_form').id, 'form'),
|
||||
],
|
||||
'context': {
|
||||
'search_default_active': 1,
|
||||
},
|
||||
}
|
198
models/product_template_attribute_value.py
Normal file
198
models/product_template_attribute_value.py
Normal file
@ -0,0 +1,198 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from random import randint
|
||||
|
||||
from odoo import api, fields, models, tools, _
|
||||
from odoo.exceptions import UserError, ValidationError
|
||||
from odoo.fields import Command
|
||||
|
||||
|
||||
class ProductTemplateAttributeValue(models.Model):
|
||||
"""Materialized relationship between attribute values
|
||||
and product template generated by the product.template.attribute.line"""
|
||||
|
||||
_name = 'product.template.attribute.value'
|
||||
_description = "Product Template Attribute Value"
|
||||
_order = 'attribute_line_id, product_attribute_value_id, id'
|
||||
|
||||
def _get_default_color(self):
|
||||
return randint(1, 11)
|
||||
|
||||
# Not just `active` because we always want to show the values except in
|
||||
# specific case, as opposed to `active_test`.
|
||||
ptav_active = fields.Boolean(string="Active", default=True)
|
||||
name = fields.Char(string="Value", related="product_attribute_value_id.name")
|
||||
|
||||
# defining fields: the product template attribute line and the product attribute value
|
||||
product_attribute_value_id = fields.Many2one(
|
||||
comodel_name='product.attribute.value',
|
||||
string="Attribute Value",
|
||||
required=True, ondelete='cascade', index=True)
|
||||
attribute_line_id = fields.Many2one(
|
||||
comodel_name='product.template.attribute.line',
|
||||
required=True, ondelete='cascade', index=True)
|
||||
# configuration fields: the price_extra and the exclusion rules
|
||||
price_extra = fields.Float(
|
||||
string="Value Price Extra",
|
||||
default=0.0,
|
||||
digits='Product Price',
|
||||
help="Extra price for the variant with this attribute value on sale price."
|
||||
" eg. 200 price extra, 1000 + 200 = 1200.")
|
||||
currency_id = fields.Many2one(related='attribute_line_id.product_tmpl_id.currency_id')
|
||||
|
||||
exclude_for = fields.One2many(
|
||||
comodel_name='product.template.attribute.exclusion',
|
||||
inverse_name='product_template_attribute_value_id',
|
||||
string="Exclude for",
|
||||
help="Make this attribute value not compatible with "
|
||||
"other values of the product or some attribute values of optional and accessory products.")
|
||||
|
||||
# related fields: product template and product attribute
|
||||
product_tmpl_id = fields.Many2one(
|
||||
related='attribute_line_id.product_tmpl_id', store=True, index=True)
|
||||
attribute_id = fields.Many2one(
|
||||
related='attribute_line_id.attribute_id', store=True, index=True)
|
||||
ptav_product_variant_ids = fields.Many2many(
|
||||
comodel_name='product.product', relation='product_variant_combination',
|
||||
string="Related Variants", readonly=True)
|
||||
|
||||
html_color = fields.Char(string="HTML Color Index", related='product_attribute_value_id.html_color')
|
||||
is_custom = fields.Boolean(related='product_attribute_value_id.is_custom')
|
||||
display_type = fields.Selection(related='product_attribute_value_id.display_type')
|
||||
color = fields.Integer(string="Color", default=_get_default_color)
|
||||
image = fields.Image(related='product_attribute_value_id.image')
|
||||
|
||||
_sql_constraints = [
|
||||
('attribute_value_unique',
|
||||
'unique(attribute_line_id, product_attribute_value_id)',
|
||||
"Each value should be defined only once per attribute per product."),
|
||||
]
|
||||
|
||||
@api.constrains('attribute_line_id', 'product_attribute_value_id')
|
||||
def _check_valid_values(self):
|
||||
for ptav in self:
|
||||
if ptav.ptav_active and ptav.product_attribute_value_id not in ptav.attribute_line_id.value_ids:
|
||||
raise ValidationError(_(
|
||||
"The value %(value)s is not defined for the attribute %(attribute)s"
|
||||
" on the product %(product)s.",
|
||||
value=ptav.product_attribute_value_id.display_name,
|
||||
attribute=ptav.attribute_id.display_name,
|
||||
product=ptav.product_tmpl_id.display_name,
|
||||
))
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
if any('ptav_product_variant_ids' in v for v in vals_list):
|
||||
# Force write on this relation from `product.product` to properly
|
||||
# trigger `_compute_combination_indices`.
|
||||
raise UserError(_("You cannot update related variants from the values. Please update related values from the variants."))
|
||||
return super().create(vals_list)
|
||||
|
||||
def write(self, values):
|
||||
if 'ptav_product_variant_ids' in values:
|
||||
# Force write on this relation from `product.product` to properly
|
||||
# trigger `_compute_combination_indices`.
|
||||
raise UserError(_("You cannot update related variants from the values. Please update related values from the variants."))
|
||||
pav_in_values = 'product_attribute_value_id' in values
|
||||
product_in_values = 'product_tmpl_id' in values
|
||||
if pav_in_values or product_in_values:
|
||||
for ptav in self:
|
||||
if pav_in_values and ptav.product_attribute_value_id.id != values['product_attribute_value_id']:
|
||||
raise UserError(_(
|
||||
"You cannot change the value of the value %(value)s set on product %(product)s.",
|
||||
value=ptav.display_name,
|
||||
product=ptav.product_tmpl_id.display_name,
|
||||
))
|
||||
if product_in_values and ptav.product_tmpl_id.id != values['product_tmpl_id']:
|
||||
raise UserError(_(
|
||||
"You cannot change the product of the value %(value)s set on product %(product)s.",
|
||||
value=ptav.display_name,
|
||||
product=ptav.product_tmpl_id.display_name,
|
||||
))
|
||||
res = super().write(values)
|
||||
if 'exclude_for' in values:
|
||||
self.product_tmpl_id._create_variant_ids()
|
||||
return res
|
||||
|
||||
def unlink(self):
|
||||
"""Override to:
|
||||
- Clean up the variants that use any of the values in self:
|
||||
- Remove the value from the variant if the value belonged to an
|
||||
attribute line with only one value.
|
||||
- Unlink or archive all related variants.
|
||||
- Archive the value if unlink is not possible.
|
||||
|
||||
Archiving is typically needed when the value is referenced elsewhere
|
||||
(on a variant that can't be deleted, on a sales order line, ...).
|
||||
"""
|
||||
# Directly remove the values from the variants for lines that had single
|
||||
# value (counting also the values that are archived).
|
||||
single_values = self.filtered(lambda ptav: len(ptav.attribute_line_id.product_template_value_ids) == 1)
|
||||
for ptav in single_values:
|
||||
ptav.ptav_product_variant_ids.write({
|
||||
'product_template_attribute_value_ids': [Command.unlink(ptav.id)],
|
||||
})
|
||||
# Try to remove the variants before deleting to potentially remove some
|
||||
# blocking references.
|
||||
self.ptav_product_variant_ids._unlink_or_archive()
|
||||
# Now delete or archive the values.
|
||||
ptav_to_archive = self.env['product.template.attribute.value']
|
||||
for ptav in self:
|
||||
try:
|
||||
with self.env.cr.savepoint(), tools.mute_logger('odoo.sql_db'):
|
||||
super(ProductTemplateAttributeValue, ptav).unlink()
|
||||
except Exception:
|
||||
# We catch all kind of exceptions to be sure that the operation
|
||||
# doesn't fail.
|
||||
ptav_to_archive += ptav
|
||||
ptav_to_archive.write({'ptav_active': False})
|
||||
return True
|
||||
|
||||
@api.depends('attribute_id')
|
||||
def _compute_display_name(self):
|
||||
"""Override because in general the name of the value is confusing if it
|
||||
is displayed without the name of the corresponding attribute.
|
||||
Eg. on exclusion rules form
|
||||
"""
|
||||
for value in self:
|
||||
value.display_name = f"{value.attribute_id.name}: {value.name}"
|
||||
|
||||
def _only_active(self):
|
||||
return self.filtered(lambda ptav: ptav.ptav_active)
|
||||
|
||||
def _without_no_variant_attributes(self):
|
||||
return self.filtered(lambda ptav: ptav.attribute_id.create_variant != 'no_variant')
|
||||
|
||||
def _ids2str(self):
|
||||
return ','.join([str(i) for i in sorted(self.ids)])
|
||||
|
||||
def _get_combination_name(self):
|
||||
"""Exclude values from single value lines or from no_variant attributes."""
|
||||
ptavs = self._without_no_variant_attributes().with_prefetch(self._prefetch_ids)
|
||||
ptavs = ptavs._filter_single_value_lines().with_prefetch(self._prefetch_ids)
|
||||
return ", ".join([ptav.name for ptav in ptavs])
|
||||
|
||||
def _filter_single_value_lines(self):
|
||||
"""Return `self` with values from single value lines filtered out
|
||||
depending on the active state of all the values in `self`.
|
||||
|
||||
If any value in `self` is archived, archived values are also taken into
|
||||
account when checking for single values.
|
||||
This allows to display the correct name for archived variants.
|
||||
|
||||
If all values in `self` are active, only active values are taken into
|
||||
account when checking for single values.
|
||||
This allows to display the correct name for active combinations.
|
||||
"""
|
||||
only_active = all(ptav.ptav_active for ptav in self)
|
||||
return self.filtered(lambda ptav: not ptav._is_from_single_value_line(only_active))
|
||||
|
||||
def _is_from_single_value_line(self, only_active=True):
|
||||
"""Return whether `self` is from a single value line, counting also
|
||||
archived values if `only_active` is False.
|
||||
"""
|
||||
self.ensure_one()
|
||||
all_values = self.attribute_line_id.product_template_value_ids
|
||||
if only_active:
|
||||
all_values = all_values._only_active()
|
||||
return len(all_values) == 1
|
69
models/res_company.py
Normal file
69
models/res_company.py
Normal file
@ -0,0 +1,69 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import _, api, models
|
||||
|
||||
|
||||
class ResCompany(models.Model):
|
||||
_inherit = "res.company"
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
companies = super().create(vals_list)
|
||||
companies._activate_or_create_pricelists()
|
||||
return companies
|
||||
|
||||
def _activate_or_create_pricelists(self):
|
||||
""" Manage the default pricelists for needed companies. """
|
||||
if self.env.context.get('disable_company_pricelist_creation'):
|
||||
return
|
||||
|
||||
if self.user_has_groups('product.group_product_pricelist'):
|
||||
companies = self or self.env['res.company'].search([])
|
||||
ProductPricelist = self.env['product.pricelist'].sudo()
|
||||
# Activate existing default pricelists
|
||||
default_pricelists_sudo = ProductPricelist.with_context(active_test=False).search(
|
||||
[('item_ids', '=', False), ('company_id', 'in', companies.ids)]
|
||||
).filtered(lambda pl: pl.currency_id == pl.company_id.currency_id)
|
||||
default_pricelists_sudo.action_unarchive()
|
||||
companies_without_pricelist = companies.filtered(
|
||||
lambda c: c.id not in default_pricelists_sudo.company_id.ids
|
||||
)
|
||||
# Create missing default pricelists
|
||||
ProductPricelist.create([
|
||||
company._get_default_pricelist_vals() for company in companies_without_pricelist
|
||||
])
|
||||
|
||||
def _get_default_pricelist_vals(self):
|
||||
"""Add values to the default pricelist at company creation or activation of the pricelist
|
||||
|
||||
Note: self.ensure_one()
|
||||
|
||||
:rtype: dict
|
||||
"""
|
||||
self.ensure_one()
|
||||
values = {}
|
||||
values.update({
|
||||
'name': _("Default %s pricelist", self.currency_id.name),
|
||||
'currency_id': self.currency_id.id,
|
||||
'company_id': self.id,
|
||||
'sequence': 10,
|
||||
})
|
||||
return values
|
||||
|
||||
def write(self, vals):
|
||||
"""Delay the automatic creation of pricelists post-company update.
|
||||
|
||||
This makes sure that the pricelist(s) automatically created are created with the right
|
||||
currency.
|
||||
"""
|
||||
if not vals.get('currency_id'):
|
||||
return super().write(vals)
|
||||
|
||||
enabled_pricelists = self.user_has_groups('product.group_product_pricelist')
|
||||
res = super(
|
||||
ResCompany, self.with_context(disable_company_pricelist_creation=True)
|
||||
).write(vals)
|
||||
if not enabled_pricelists and self.user_has_groups('product.group_product_pricelist'):
|
||||
self.browse()._activate_or_create_pricelists()
|
||||
|
||||
return res
|
74
models/res_config_settings.py
Normal file
74
models/res_config_settings.py
Normal file
@ -0,0 +1,74 @@
|
||||
# -*- 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'
|
||||
|
||||
group_discount_per_so_line = fields.Boolean("Discounts", implied_group='product.group_discount_per_so_line')
|
||||
group_uom = fields.Boolean("Units of Measure", implied_group='uom.group_uom')
|
||||
group_product_variant = fields.Boolean("Variants", implied_group='product.group_product_variant')
|
||||
module_sale_product_matrix = fields.Boolean("Sales Grid Entry")
|
||||
module_loyalty = fields.Boolean("Promotions, Coupons, Gift Card & Loyalty Program")
|
||||
group_stock_packaging = fields.Boolean('Product Packagings',
|
||||
implied_group='product.group_stock_packaging')
|
||||
group_product_pricelist = fields.Boolean("Pricelists",
|
||||
implied_group='product.group_product_pricelist')
|
||||
group_sale_pricelist = fields.Boolean("Advanced Pricelists",
|
||||
implied_group='product.group_sale_pricelist',
|
||||
help="""Allows to manage different prices based on rules per category of customers.
|
||||
Example: 10% for retailers, promotion of 5 EUR on this product, etc.""")
|
||||
product_pricelist_setting = fields.Selection([
|
||||
('basic', 'Multiple prices per product'),
|
||||
('advanced', 'Advanced price rules (discounts, formulas)')
|
||||
], default='basic', string="Pricelists Method", config_parameter='product.product_pricelist_setting',
|
||||
help="Multiple prices: Pricelists with fixed price rules by product,\nAdvanced rules: enables advanced price rules for pricelists.")
|
||||
product_weight_in_lbs = fields.Selection([
|
||||
('0', 'Kilograms'),
|
||||
('1', 'Pounds'),
|
||||
], 'Weight unit of measure', config_parameter='product.weight_in_lbs', default='0')
|
||||
product_volume_volume_in_cubic_feet = fields.Selection([
|
||||
('0', 'Cubic Meters'),
|
||||
('1', 'Cubic Feet'),
|
||||
], 'Volume unit of measure', config_parameter='product.volume_in_cubic_feet', default='0')
|
||||
|
||||
@api.onchange('group_product_variant')
|
||||
def _onchange_group_product_variant(self):
|
||||
"""The product Configurator requires the product variants activated.
|
||||
If the user disables the product variants -> disable the product configurator as well"""
|
||||
if self.module_sale_product_matrix and not self.group_product_variant:
|
||||
self.module_sale_product_matrix = False
|
||||
|
||||
@api.onchange('group_product_pricelist')
|
||||
def _onchange_group_sale_pricelist(self):
|
||||
if not self.group_product_pricelist:
|
||||
if self.group_sale_pricelist:
|
||||
self.group_sale_pricelist = False
|
||||
active_pricelist = self.env['product.pricelist'].sudo().search([('active', '=', True)])
|
||||
if active_pricelist:
|
||||
return {
|
||||
'warning': {
|
||||
'message': _("You are deactivating the pricelist feature. "
|
||||
"Every active pricelist will be archived.")
|
||||
}}
|
||||
|
||||
@api.onchange('product_pricelist_setting')
|
||||
def _onchange_product_pricelist_setting(self):
|
||||
if self.product_pricelist_setting == 'basic':
|
||||
self.group_sale_pricelist = False
|
||||
else:
|
||||
self.group_sale_pricelist = True
|
||||
|
||||
def set_values(self):
|
||||
had_group_pl = self.default_get(['group_product_pricelist'])['group_product_pricelist']
|
||||
super().set_values()
|
||||
if not self.group_discount_per_so_line:
|
||||
pl = self.env['product.pricelist'].search([('discount_policy', '=', 'without_discount')])
|
||||
pl.write({'discount_policy': 'with_discount'})
|
||||
|
||||
if self.group_product_pricelist and not had_group_pl:
|
||||
self.env['res.company']._activate_or_create_pricelists()
|
||||
elif not self.group_product_pricelist:
|
||||
self.env['product.pricelist'].sudo().search([]).action_archive()
|
15
models/res_country_group.py
Normal file
15
models/res_country_group.py
Normal file
@ -0,0 +1,15 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import fields, models
|
||||
|
||||
|
||||
class ResCountryGroup(models.Model):
|
||||
_inherit = 'res.country.group'
|
||||
|
||||
pricelist_ids = fields.Many2many(
|
||||
comodel_name='product.pricelist',
|
||||
relation='res_country_group_pricelist_rel',
|
||||
column1='res_country_group_id',
|
||||
column2='pricelist_id',
|
||||
string="Pricelists")
|
25
models/res_currency.py
Normal file
25
models/res_currency.py
Normal file
@ -0,0 +1,25 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import models
|
||||
|
||||
|
||||
class ResCurrency(models.Model):
|
||||
_inherit = 'res.currency'
|
||||
|
||||
def _activate_group_multi_currency(self):
|
||||
# for Sale/ POS - Multi currency flows require pricelists
|
||||
super()._activate_group_multi_currency()
|
||||
if not self.user_has_groups('product.group_product_pricelist'):
|
||||
group_user = self.env.ref('base.group_user').sudo()
|
||||
group_user._apply_group(self.env.ref('product.group_product_pricelist'))
|
||||
self.env['res.company']._activate_or_create_pricelists()
|
||||
|
||||
def write(self, vals):
|
||||
""" Archive pricelist when the linked currency is archived. """
|
||||
res = super().write(vals)
|
||||
|
||||
if self and 'active' in vals and not vals['active']:
|
||||
self.env['product.pricelist'].search([('currency_id', 'in', self.ids)]).action_archive()
|
||||
|
||||
return res
|
49
models/res_partner.py
Normal file
49
models/res_partner.py
Normal file
@ -0,0 +1,49 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, fields, models
|
||||
|
||||
|
||||
class ResPartner(models.Model):
|
||||
_inherit = 'res.partner'
|
||||
|
||||
# NOT A REAL PROPERTY !!!!
|
||||
property_product_pricelist = fields.Many2one(
|
||||
comodel_name='product.pricelist',
|
||||
string="Pricelist",
|
||||
compute='_compute_product_pricelist',
|
||||
inverse="_inverse_product_pricelist",
|
||||
company_dependent=False,
|
||||
domain=lambda self: [('company_id', 'in', (self.env.company.id, False))],
|
||||
help="This pricelist will be used, instead of the default one, for sales to the current partner")
|
||||
|
||||
@api.depends('country_id')
|
||||
@api.depends_context('company')
|
||||
def _compute_product_pricelist(self):
|
||||
res = self.env['product.pricelist']._get_partner_pricelist_multi(self.ids)
|
||||
for partner in self:
|
||||
partner.property_product_pricelist = res.get(partner._origin.id)
|
||||
|
||||
def _inverse_product_pricelist(self):
|
||||
for partner in self:
|
||||
pls = self.env['product.pricelist'].search(
|
||||
[('country_group_ids.country_ids.code', '=', partner.country_id and partner.country_id.code or False)],
|
||||
limit=1
|
||||
)
|
||||
default_for_country = pls
|
||||
actual = self.env['ir.property']._get(
|
||||
'property_product_pricelist',
|
||||
'res.partner',
|
||||
'res.partner,%s' % partner.id)
|
||||
# update at each change country, and so erase old pricelist
|
||||
if partner.property_product_pricelist or (actual and default_for_country and default_for_country.id != actual.id):
|
||||
# keep the company of the current user before sudo
|
||||
self.env['ir.property']._set_multi(
|
||||
'property_product_pricelist',
|
||||
partner._name,
|
||||
{partner.id: partner.property_product_pricelist or default_for_country.id},
|
||||
default_value=default_for_country.id
|
||||
)
|
||||
|
||||
def _commercial_fields(self):
|
||||
return super()._commercial_fields() + ['property_product_pricelist']
|
21
models/uom_uom.py
Normal file
21
models/uom_uom.py
Normal file
@ -0,0 +1,21 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, models, _
|
||||
|
||||
|
||||
class UoM(models.Model):
|
||||
_inherit = 'uom.uom'
|
||||
|
||||
@api.onchange('rounding')
|
||||
def _onchange_rounding(self):
|
||||
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
|
||||
if self.rounding < 1.0 / 10.0**precision:
|
||||
return {'warning': {
|
||||
'title': _('Warning!'),
|
||||
'message': _(
|
||||
"This rounding precision is higher than the Decimal Accuracy"
|
||||
" (%s digits).\nThis may cause inconsistencies in computations.\n"
|
||||
"Please set a precision between %s and 1.",
|
||||
precision, 1.0 / 10.0**precision),
|
||||
}}
|
6
populate/__init__.py
Normal file
6
populate/__init__.py
Normal file
@ -0,0 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from . import product
|
||||
from . import product_template
|
||||
from . import product_pricelist
|
116
populate/product.py
Normal file
116
populate/product.py
Normal file
@ -0,0 +1,116 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
import logging
|
||||
import collections
|
||||
|
||||
from odoo import models
|
||||
from odoo.tools import populate
|
||||
from odoo.addons.stock.populate.stock import COMPANY_NB_WITH_STOCK
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ProductCategory(models.Model):
|
||||
_inherit = "product.category"
|
||||
_populate_sizes = {"small": 50, "medium": 500, "large": 5_000}
|
||||
|
||||
def _populate_factories(self):
|
||||
return [("name", populate.constant('PC_{counter}'))]
|
||||
|
||||
def _populate(self, size):
|
||||
categories = super()._populate(size)
|
||||
# Set parent/child relation
|
||||
self._populate_set_parents(categories, size)
|
||||
return categories
|
||||
|
||||
def _populate_set_parents(self, categories, size):
|
||||
_logger.info('Set parent/child relation of product categories')
|
||||
parent_ids = []
|
||||
rand = populate.Random('product.category+parent_generator')
|
||||
|
||||
for category in categories:
|
||||
if rand.random() < 0.25:
|
||||
parent_ids.append(category.id)
|
||||
|
||||
categories -= self.browse(parent_ids) # Avoid recursion in parent-child relations.
|
||||
parent_childs = collections.defaultdict(lambda: self.env['product.category'])
|
||||
for category in categories:
|
||||
if rand.random() < 0.25: # 1/4 of remaining categories have a parent.
|
||||
parent_childs[rand.choice(parent_ids)] |= category
|
||||
|
||||
for count, (parent, children) in enumerate(parent_childs.items()):
|
||||
if (count + 1) % 1000 == 0:
|
||||
_logger.info('Setting parent: %s/%s', count + 1, len(parent_childs))
|
||||
children.write({'parent_id': parent})
|
||||
|
||||
class ProductProduct(models.Model):
|
||||
_inherit = "product.product"
|
||||
_populate_sizes = {"small": 150, "medium": 5_000, "large": 50_000}
|
||||
_populate_dependencies = ["product.category"]
|
||||
|
||||
def _populate_get_types(self):
|
||||
return ["consu", "service"], [2, 1]
|
||||
|
||||
def _populate_get_product_factories(self):
|
||||
category_ids = self.env.registry.populated_models["product.category"]
|
||||
types, types_distribution = self._populate_get_types()
|
||||
|
||||
def get_rand_float(values, counter, random):
|
||||
return random.randrange(0, 1500) * random.random()
|
||||
|
||||
# TODO sale & purchase uoms
|
||||
|
||||
return [
|
||||
("sequence", populate.randomize([False] + [i for i in range(1, 101)])),
|
||||
("active", populate.randomize([True, False], [0.8, 0.2])),
|
||||
("type", populate.randomize(types, types_distribution)),
|
||||
("categ_id", populate.randomize(category_ids)),
|
||||
("list_price", populate.compute(get_rand_float)),
|
||||
("standard_price", populate.compute(get_rand_float)),
|
||||
]
|
||||
|
||||
def _populate_factories(self):
|
||||
return [
|
||||
("name", populate.constant('product_product_name_{counter}')),
|
||||
("description", populate.constant('product_product_description_{counter}')),
|
||||
("default_code", populate.constant('PP-{counter}')),
|
||||
("barcode", populate.constant('BARCODE-PP-{counter}')),
|
||||
] + self._populate_get_product_factories()
|
||||
|
||||
|
||||
class SupplierInfo(models.Model):
|
||||
_inherit = 'product.supplierinfo'
|
||||
|
||||
_populate_sizes = {'small': 450, 'medium': 15_000, 'large': 180_000}
|
||||
_populate_dependencies = ['res.partner', 'product.product', 'product.template']
|
||||
|
||||
def _populate_factories(self):
|
||||
random = populate.Random('product_with_supplierinfo')
|
||||
company_ids = self.env.registry.populated_models['res.company'][:COMPANY_NB_WITH_STOCK] + [False]
|
||||
partner_ids = self.env.registry.populated_models['res.partner']
|
||||
product_templates_ids = self.env['product.product'].browse(self.env.registry.populated_models['product.product']).product_tmpl_id.ids
|
||||
product_templates_ids += self.env.registry.populated_models['product.template']
|
||||
product_templates_ids = random.sample(product_templates_ids, int(len(product_templates_ids) * 0.95))
|
||||
|
||||
def get_company_id(values, counter, random):
|
||||
partner = self.env['res.partner'].browse(values['partner_id'])
|
||||
if partner.company_id:
|
||||
return partner.company_id.id
|
||||
return random.choice(company_ids)
|
||||
|
||||
def get_delay(values, counter, random):
|
||||
# 5 % with huge delay (between 5 month and 6 month), otherwise between 1 and 10 days
|
||||
if random.random() > 0.95:
|
||||
return random.randint(150, 210)
|
||||
return random.randint(1, 10)
|
||||
|
||||
return [
|
||||
('partner_id', populate.randomize(partner_ids)),
|
||||
('company_id', populate.compute(get_company_id)),
|
||||
('product_tmpl_id', populate.iterate(product_templates_ids)),
|
||||
('product_name', populate.constant("SI-{counter}")),
|
||||
('sequence', populate.randint(1, 10)),
|
||||
('min_qty', populate.randint(0, 10)),
|
||||
('price', populate.randint(10, 100)),
|
||||
('delay', populate.compute(get_delay)),
|
||||
]
|
113
populate/product_pricelist.py
Normal file
113
populate/product_pricelist.py
Normal file
@ -0,0 +1,113 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import models
|
||||
from odoo.tools import populate
|
||||
from datetime import timedelta, date
|
||||
|
||||
|
||||
class Pricelist(models.Model):
|
||||
_inherit = "product.pricelist"
|
||||
_populate_sizes = {"small": 20, "medium": 100, "large": 1_500}
|
||||
_populate_dependencies = ["res.company"]
|
||||
|
||||
def _populate(self, size):
|
||||
|
||||
# Reflect the settings with data created
|
||||
self.env['res.config.settings'].create({
|
||||
'group_product_pricelist': True, # Activate pricelist
|
||||
'group_sale_pricelist': True, # Activate advanced pricelist
|
||||
}).execute()
|
||||
|
||||
return super()._populate(size)
|
||||
|
||||
def _populate_factories(self):
|
||||
company_ids = self.env.registry.populated_models["res.company"]
|
||||
|
||||
return [
|
||||
("company_id", populate.iterate(company_ids + [False for i in range(len(company_ids))])),
|
||||
("name", populate.constant('product_pricelist_{counter}')),
|
||||
("currency_id", populate.randomize(self.env["res.currency"].search([("active", "=", True)]).ids)),
|
||||
("sequence", populate.randomize([False] + [i for i in range(1, 101)])),
|
||||
("discount_policy", populate.randomize(["with_discount", "without_discount"])),
|
||||
("active", populate.randomize([True, False], [0.8, 0.2])),
|
||||
]
|
||||
|
||||
|
||||
class PricelistItem(models.Model):
|
||||
_inherit = "product.pricelist.item"
|
||||
_populate_sizes = {"small": 500, "medium": 5_000, "large": 50_000}
|
||||
_populate_dependencies = ["product.product", "product.template", "product.pricelist"]
|
||||
|
||||
def _populate_factories(self):
|
||||
pricelist_ids = self.env.registry.populated_models["product.pricelist"]
|
||||
product_ids = self.env.registry.populated_models["product.product"]
|
||||
p_tmpl_ids = self.env.registry.populated_models["product.template"]
|
||||
categ_ids = self.env.registry.populated_models["product.category"]
|
||||
|
||||
def get_target_info(iterator, field_name, model_name):
|
||||
random = populate.Random("pricelist_target")
|
||||
for values in iterator:
|
||||
# If product population is updated to consider multi company
|
||||
# the company of product would have to be considered
|
||||
# for product_id & product_tmpl_id
|
||||
applied_on = values["applied_on"]
|
||||
if applied_on == "0_product_variant":
|
||||
values["product_id"] = random.choice(product_ids)
|
||||
elif applied_on == "1_product":
|
||||
values["product_tmpl_id"] = random.choice(p_tmpl_ids)
|
||||
elif applied_on == "2_product_category":
|
||||
values["categ_id"] = random.choice(categ_ids)
|
||||
yield values
|
||||
|
||||
def get_prices(iterator, field_name, model_name):
|
||||
random = populate.Random("pricelist_prices")
|
||||
for values in iterator:
|
||||
# Fixed price, percentage, formula
|
||||
compute_price = values["compute_price"]
|
||||
if compute_price == "fixed":
|
||||
# base = "list_price" = default
|
||||
# fixed_price
|
||||
values["fixed_price"] = random.randint(1, 1000)
|
||||
elif compute_price == "percentage":
|
||||
# base = "list_price" = default
|
||||
# percent_price
|
||||
values["percent_price"] = random.randint(1, 100)
|
||||
else: # formula
|
||||
# pricelist base not considered atm.
|
||||
values["base"] = random.choice(["list_price", "standard_price"])
|
||||
values["price_discount"] = random.randint(0, 100)
|
||||
# price_min_margin, price_max_margin
|
||||
# price_round ??? price_discount, price_surcharge
|
||||
yield values
|
||||
|
||||
now = date.today()
|
||||
|
||||
def get_date_start(values, counter, random):
|
||||
if random.random() > 0.5: # 50 % of chance to have validation dates
|
||||
return now + timedelta(days=random.randint(-20, 20))
|
||||
else:
|
||||
False
|
||||
|
||||
def get_date_end(values, counter, random):
|
||||
if values['date_start']: # 50 % of chance to have validation dates
|
||||
return values['date_start'] + timedelta(days=random.randint(5, 100))
|
||||
else:
|
||||
False
|
||||
|
||||
return [
|
||||
("pricelist_id", populate.randomize(pricelist_ids)),
|
||||
("applied_on", populate.randomize(
|
||||
["3_global", "2_product_category", "1_product", "0_product_variant"],
|
||||
[5, 3, 2, 1],
|
||||
)),
|
||||
("compute_price", populate.randomize(
|
||||
["fixed", "percentage", "formula"],
|
||||
[5, 3, 1],
|
||||
)),
|
||||
("_price", get_prices),
|
||||
("_target", get_target_info),
|
||||
("min_quantity", populate.randint(0, 50)),
|
||||
("date_start", populate.compute(get_date_start)),
|
||||
("date_end", populate.compute(get_date_end)),
|
||||
]
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user