19.0 vanilla

This commit is contained in:
Ernad Husremovic 2026-03-09 09:32:12 +01:00
parent 79f83631d5
commit 73afc09215
6267 changed files with 1534193 additions and 1130106 deletions

View file

@ -1,7 +1,7 @@
# -*- 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

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
@ -32,20 +31,24 @@ Print product labels with barcode.
'security/ir.model.access.csv',
'wizard/product_label_layout_views.xml',
'views/product_views.xml',
'wizard/update_product_attribute_value_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_packaging_views.xml',
'views/product_combo_views.xml',
'views/product_document_views.xml',
'views/product_pricelist_item_views.xml',
'views/product_pricelist_views.xml',
'views/product_supplierinfo_views.xml',
'views/product_template_attribute_line_views.xml',
'views/product_template_views.xml',
'views/product_tag_views.xml',
'views/res_country_group_views.xml',
'views/res_partner_views.xml',
'views/uom_views.xml',
'report/product_reports.xml',
'report/product_product_templates.xml',
@ -54,20 +57,29 @@ Print product labels with barcode.
'report/product_pricelist_report_templates.xml',
],
'demo': [
'data/product_attribute_demo.xml',
'data/product_category_demo.xml',
'data/product_demo.xml',
'data/product_document_demo.xml',
'data/product_supplierinfo_demo.xml',
],
'installable': True,
'assets': {
'web.assets_backend': [
'product/static/src/js/**/*',
'product/static/src/xml/**/*',
'product/static/src/product_catalog/**/*.js',
'product/static/src/product_catalog/**/*.xml',
'product/static/src/product_catalog/**/*.scss',
'product/static/src/product_name_and_description/**/*.js',
'product/static/src/scss/product_form.scss',
],
'web.report_assets_common': [
'product/static/src/scss/report_label_sheet.scss',
],
'web.qunit_suite_tests': [
'web.assets_unit_tests': [
'product/static/tests/**/*',
],
},
'author': 'Odoo S.A.',
'license': 'LGPL-3',
}

View file

@ -0,0 +1,3 @@
from . import catalog
from . import product_document
from . import pricelist_report

View file

@ -0,0 +1,48 @@
# 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='jsonrpc', readonly=True)
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
'uomDisplayName': string
'code': string (optional)
'readOnly': bool (optional)
}
}
"""
order = request.env[res_model].browse(order_id)
return order.with_company(order.company_id)._get_product_catalog_order_line_info(
product_ids, **kwargs,
)
@route('/product/catalog/update_order_line_info', auth='user', type='jsonrpc')
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.with_company(order.company_id)._update_order_line_info(
product_id, quantity, **kwargs,
)

View file

@ -0,0 +1,77 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import csv
import io
import json
from odoo import _
from odoo.http import Controller, request, route, content_disposition
class ProductPricelistExportController(Controller):
@route('/product/export/pricelist/', type='http', auth='user', readonly=True)
def export_pricelist(self, report_data, export_format):
json_data = json.loads(report_data)
report_data = request.env['report.product.report_pricelist']._get_report_data(json_data)
pricelist_name = report_data['pricelist']['name']
quantities = report_data['quantities']
products = report_data['products']
headers = [
_("Product"),
_("UOM"),
] + [_("Quantity (%s UoM)", qty) for qty in quantities]
if export_format == 'csv':
return self._generate_csv(pricelist_name, quantities, products, headers)
else:
return self._generate_xlsx(pricelist_name, quantities, products, headers)
def _generate_rows(self, products, quantities):
rows = []
for product in products:
variants = product.get('variants', [product])
for variant in variants:
row = [
variant['name'],
variant['uom']
] + [variant['price'].get(qty, 0.0) for qty in quantities]
rows.append(row)
return rows
def _generate_csv(self, pricelist_name, quantities, products, headers):
buffer = io.StringIO()
writer = csv.writer(buffer)
writer.writerow(headers)
rows = self._generate_rows(products, quantities)
writer.writerows(rows)
content = buffer.getvalue()
buffer.close()
headers = [
('Content-Type', 'text/csv'),
('Content-Disposition', content_disposition(f'Pricelist - {pricelist_name}.csv'))
]
return request.make_response(content, headers)
def _generate_xlsx(self, pricelist_name, quantities, products, headers):
buffer = io.BytesIO()
import xlsxwriter # noqa: PLC0415
workbook = xlsxwriter.Workbook(buffer, {'in_memory': True})
worksheet = workbook.add_worksheet()
worksheet.write_row(0, 0, headers)
rows = self._generate_rows(products, quantities)
column_widths = [len(header) for header in headers]
for row_idx, row in enumerate(rows, start=1):
worksheet.write_row(row_idx, 0, row)
for col_idx, cell_value in enumerate(row):
column_widths[col_idx] = max(column_widths[col_idx], len(str(cell_value)))
for col_idx, width in enumerate(column_widths):
worksheet.set_column(col_idx, col_idx, width)
workbook.close()
content = buffer.getvalue()
buffer.close()
headers = [
('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
('Content-Disposition', content_disposition(f'Pricelist - {pricelist_name}.xlsx'))
]
return request.make_response(content, headers)

View file

@ -0,0 +1,49 @@
# 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, **kwargs):
if not self.is_model_valid(res_model):
return
record = request.env[res_model].browse(int(res_id)).exists()
if not record or not record.browse().has_access('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(),
**self.get_additional_create_params(**kwargs)
})
except Exception as e:
logger.exception("Failed to upload document %s", ufile.filename)
result = {'error': str(e)}
return json.dumps(result)
# mrp hook
def get_additional_create_params(self, **kwargs):
return {}
# eco hook
def is_model_valid(self, res_model):
return res_model in ('product.product', 'product.template')

View file

@ -0,0 +1,578 @@
<?xml version="1.0" encoding="UTF-8"?>
<odoo noupdate="1">
<!-- Brand -->
<record id="pa_brand" model="product.attribute">
<field name="name">Brand</field>
<field name="sequence">10</field>
</record>
<record id="pav_brand_adidas" model="product.attribute.value">
<field name="name">Adidas</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_apple" model="product.attribute.value">
<field name="name">Apple</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_ariel" model="product.attribute.value">
<field name="name">Ariel</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_canon" model="product.attribute.value">
<field name="name">Canon</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_cocacola" model="product.attribute.value">
<field name="name">Coca-Cola</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_colgate" model="product.attribute.value">
<field name="name">Colgate</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_dell" model="product.attribute.value">
<field name="name">Dell</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_dove" model="product.attribute.value">
<field name="name">Dove</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_dyson" model="product.attribute.value">
<field name="name">Dyson</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_gillette" model="product.attribute.value">
<field name="name">Gillette</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_h_m" model="product.attribute.value">
<field name="name">H&amp;M</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_head_shoulders" model="product.attribute.value">
<field name="name">Head &amp; Shoulders</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_loreal" model="product.attribute.value">
<field name="name">L'Oréal</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_lenovo" model="product.attribute.value">
<field name="name">Lenovo</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_levis" model="product.attribute.value">
<field name="name">Levi's</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_LG" model="product.attribute.value">
<field name="name">LG</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_maybelline" model="product.attribute.value">
<field name="name">Maybelline</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_montblanc" model="product.attribute.value">
<field name="name">Montblanc</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_nestle" model="product.attribute.value">
<field name="name">Nestlé</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_new_balance" model="product.attribute.value">
<field name="name">New Balance</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_nike" model="product.attribute.value">
<field name="name">Nike</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_nikon" model="product.attribute.value">
<field name="name">Nikon</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_nivea" model="product.attribute.value">
<field name="name">Nivea</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_olay" model="product.attribute.value">
<field name="name">Olay</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_oral_b" model="product.attribute.value">
<field name="name">Oral-B</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_panasonic" model="product.attribute.value">
<field name="name">Panasonic</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_pantene" model="product.attribute.value">
<field name="name">Pantene</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_pepsi" model="product.attribute.value">
<field name="name">Pepsi</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_philips" model="product.attribute.value">
<field name="name">Philips</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_puma" model="product.attribute.value">
<field name="name">Puma</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_rayban" model="product.attribute.value">
<field name="name">Ray-Ban</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_reebok" model="product.attribute.value">
<field name="name">Reebok</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_rolex" model="product.attribute.value">
<field name="name">Rolex</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_samsung" model="product.attribute.value">
<field name="name">Samsung</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_sony" model="product.attribute.value">
<field name="name">Sony</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_tide" model="product.attribute.value">
<field name="name">Tide</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_underarmour" model="product.attribute.value">
<field name="name">Under Armour</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_uniqlo" model="product.attribute.value">
<field name="name">Uniqlo</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_whirlpool" model="product.attribute.value">
<field name="name">Whirlpool</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<record id="pav_brand_zara" model="product.attribute.value">
<field name="name">Zara</field>
<field name="attribute_id" ref="product.pa_brand"/>
</record>
<!-- Size -->
<record id="pa_size" model="product.attribute">
<field name="name">Size</field>
<field name="sequence">20</field>
<field name="display_type">pills</field>
<field name="create_variant">always</field>
</record>
<record id="pav_size_xs" model="product.attribute.value">
<field name="name">XS</field>
<field name="sequence">0</field>
<field name="attribute_id" ref="pa_size"/>
</record>
<record id="pav_size_s" model="product.attribute.value">
<field name="name">S</field>
<field name="sequence">1</field>
<field name="attribute_id" ref="pa_size"/>
</record>
<record id="pav_size_m" model="product.attribute.value">
<field name="name">M</field>
<field name="sequence">2</field>
<field name="attribute_id" ref="pa_size"/>
</record>
<record id="pav_size_l" model="product.attribute.value">
<field name="name">L</field>
<field name="sequence">3</field>
<field name="attribute_id" ref="pa_size"/>
</record>
<record id="pav_size_xl" model="product.attribute.value">
<field name="name">XL</field>
<field name="sequence">4</field>
<field name="attribute_id" ref="pa_size"/>
</record>
<record id="pav_size_2xl" model="product.attribute.value">
<field name="name">2XL</field>
<field name="default_extra_price">2</field>
<field name="sequence">5</field>
<field name="attribute_id" ref="pa_size"/>
</record>
<record id="pav_size_3xl" model="product.attribute.value">
<field name="name">3XL</field>
<field name="default_extra_price">3</field>
<field name="sequence">6</field>
<field name="attribute_id" ref="pa_size"/>
</record>
<record id="pav_size_4xl" model="product.attribute.value">
<field name="name">4XL</field>
<field name="default_extra_price">4</field>
<field name="sequence">7</field>
<field name="attribute_id" ref="pa_size"/>
</record>
<record id="pav_size_5xl" model="product.attribute.value">
<field name="name">5XL</field>
<field name="default_extra_price">5</field>
<field name="sequence">8</field>
<field name="attribute_id" ref="pa_size"/>
</record>
<!-- Colors -->
<record id="pa_color" model="product.attribute">
<field name="name">Color</field>
<field name="display_type">color</field>
<field name="sequence">30</field>
</record>
<record id="pav_color_white" model="product.attribute.value">
<field name="name">White</field>
<field name="html_color">#FAFAFA</field>
<field name="attribute_id" ref="pa_color"/>
<field name="sequence">1</field>
</record>
<record id="pav_color_black" model="product.attribute.value">
<field name="name">Black</field>
<field name="html_color">#1C1C1C</field>
<field name="attribute_id" ref="pa_color"/>
<field name="sequence">2</field>
</record>
<record id="pav_color_gray" model="product.attribute.value">
<field name="name">Gray</field>
<field name="html_color">#B0B0B0</field>
<field name="attribute_id" ref="pa_color"/>
<field name="sequence">3</field>
</record>
<record id="pav_color_brown" model="product.attribute.value">
<field name="name">Brown</field>
<field name="html_color">#8B5E3C</field>
<field name="attribute_id" ref="pa_color"/>
<field name="sequence">4</field>
</record>
<record id="pav_color_beige" model="product.attribute.value">
<field name="name">Beige</field>
<field name="html_color">#EAE0D5</field>
<field name="attribute_id" ref="pa_color"/>
<field name="sequence">5</field>
</record>
<record id="pav_color_red" model="product.attribute.value">
<field name="name">Red</field>
<field name="html_color">#E63946</field>
<field name="attribute_id" ref="pa_color"/>
<field name="sequence">6</field>
</record>
<record id="pav_color_blue" model="product.attribute.value">
<field name="name">Blue</field>
<field name="html_color">#457B9D</field>
<field name="attribute_id" ref="pa_color"/>
<field name="sequence">7</field>
</record>
<record id="pav_color_green" model="product.attribute.value">
<field name="name">Green</field>
<field name="html_color">#2A9D8F</field>
<field name="attribute_id" ref="pa_color"/>
<field name="sequence">8</field>
</record>
<record id="pav_color_yellow" model="product.attribute.value">
<field name="name">Yellow</field>
<field name="html_color">#F4D35E</field>
<field name="attribute_id" ref="pa_color"/>
<field name="sequence">9</field>
</record>
<record id="pav_color_orange" model="product.attribute.value">
<field name="name">Orange</field>
<field name="html_color">#F38E1E</field>
<field name="attribute_id" ref="pa_color"/>
<field name="sequence">10</field>
</record>
<record id="pav_color_pink" model="product.attribute.value">
<field name="name">Pink</field>
<field name="html_color">#C08081</field>
<field name="attribute_id" ref="pa_color"/>
<field name="sequence">11</field>
</record>
<record id="pav_color_purple" model="product.attribute.value">
<field name="name">Purple</field>
<field name="attribute_id" ref="pa_color"/>
<field name="html_color">#8E4585</field>
<field name="sequence">12</field>
<field name="default_extra_price">6</field>
<field name="image" type="base64" file="product/static/img/purple.png"/>
</record>
<record id="pav_color_cyan" model="product.attribute.value">
<field name="name">Cyan</field>
<field name="html_color">#6EEBFF</field>
<field name="attribute_id" ref="pa_color"/>
<field name="sequence">13</field>
</record>
<record id="pav_color_teal" model="product.attribute.value">
<field name="name">Teal</field>
<field name="html_color">#3AAFA9</field>
<field name="attribute_id" ref="pa_color"/>
<field name="sequence">14</field>
</record>
<record id="pav_color_navy" model="product.attribute.value">
<field name="name">Navy</field>
<field name="html_color">#264653</field>
<field name="attribute_id" ref="pa_color"/>
<field name="sequence">15</field>
</record>
<record id="pav_color_gold" model="product.attribute.value">
<field name="name">Gold</field>
<field name="html_color">#FFD86F</field>
<field name="attribute_id" ref="pa_color"/>
<field name="sequence">16</field>
</record>
<record id="pav_color_silver" model="product.attribute.value">
<field name="name">Silver</field>
<field name="html_color">#D8D8D8</field>
<field name="attribute_id" ref="pa_color"/>
<field name="sequence">17</field>
</record>
<record id="pav_color_maroon" model="product.attribute.value">
<field name="name">Maroon</field>
<field name="html_color">#6D2932</field>
<field name="attribute_id" ref="pa_color"/>
<field name="image" type="base64" file="product/static/img/maroon.png"/>
<field name="default_extra_price">5</field>
<field name="sequence">18</field>
</record>
<record id="pav_color_olive" model="product.attribute.value">
<field name="name">Olive</field>
<field name="html_color">#A4A644</field>
<field name="attribute_id" ref="pa_color"/>
<field name="sequence">19</field>
</record>
<record id="pav_color_tan" model="product.attribute.value">
<field name="name">Tan</field>
<field name="html_color">#D8B08C</field>
<field name="attribute_id" ref="pa_color"/>
<field name="sequence">20</field>
</record>
<!-- Height -->
<record id="pa_height" model="product.attribute">
<field name="name">Height</field>
<field name="sequence">40</field>
<field name="display_type">select</field>
</record>
<record id="pav_height_45" model="product.attribute.value">
<field name="name">45</field>
<field name="attribute_id" ref="pa_height"/>
</record>
<record id="pav_height_85" model="product.attribute.value">
<field name="name">85</field>
<field name="attribute_id" ref="pa_height"/>
</record>
<record id="pav_height_100" model="product.attribute.value">
<field name="name">100</field>
<field name="attribute_id" ref="pa_height"/>
</record>
<!-- Length -->
<record id="pa_length" model="product.attribute">
<field name="name">Length</field>
<field name="sequence">50</field>
<field name="display_type">pills</field>
<field name="create_variant">dynamic</field>
</record>
<record id="pav_length_120" model="product.attribute.value">
<field name="name">120</field>
<field name="attribute_id" ref="pa_length"/>
</record>
<record id="pav_length_140" model="product.attribute.value">
<field name="name">140</field>
<field name="default_extra_price">20</field>
<field name="attribute_id" ref="pa_length"/>
</record>
<record id="pav_length_160" model="product.attribute.value">
<field name="name">160</field>
<field name="default_extra_price">30</field>
<field name="attribute_id" ref="pa_length"/>
</record>
<record id="pav_length_custom" model="product.attribute.value">
<field name="name">Custom</field>
<field name="attribute_id" ref="pa_length"/>
<field name="default_extra_price">50</field>
<field name="is_custom">True</field>
</record>
<!-- Duration -->
<record id="pa_duration" model="product.attribute">
<field name="name">Duration</field>
<field name="display_type">select</field>
<field name="create_variant">no_variant</field>
<field name="sequence">60</field>
</record>
<record id="pav_duration_month_1" model="product.attribute.value">
<field name="name">1 month</field>
<field name="attribute_id" ref="pa_duration"/>
</record>
<record id="pav_duration_month_6" model="product.attribute.value">
<field name="name">6 months</field>
<field name="attribute_id" ref="pa_duration"/>
</record>
<record id="pav_duration_year_1" model="product.attribute.value">
<field name="name">1 year</field>
<field name="attribute_id" ref="pa_duration"/>
</record>
<record id="pav_duration_year_2" model="product.attribute.value">
<field name="name">2 years</field>
<field name="attribute_id" ref="pa_duration"/>
</record>
<record id="pav_duration_year_3" model="product.attribute.value">
<field name="name">3 years</field>
<field name="attribute_id" ref="pa_duration"/>
</record>
<!-- Fabric -->
<record id="pa_fabric" model="product.attribute">
<field name="name">Fabric</field>
<field name="sequence">80</field>
<field name="display_type">color</field>
<field name="create_variant">always</field>
</record>
<record id="pav_fabric_linen" model="product.attribute.value">
<field name="name">Linen</field>
<field name="sequence">1</field>
<field name="image" type="base64" file="product/static/img/linen.png"/>
<field name="attribute_id" ref="pa_fabric"/>
</record>
<record id="pav_fabric_velvet" model="product.attribute.value">
<field name="name">Velvet</field>
<field name="sequence">2</field>
<field name="image" type="base64" file="product/static/img/velvet.png"/>
<field name="attribute_id" ref="pa_fabric"/>
</record>
<record id="pav_fabric_leather" model="product.attribute.value">
<field name="name">Leather</field>
<field name="sequence">3</field>
<field name="image" type="base64" file="product/static/img/leather.png"/>
<field name="attribute_id" ref="pa_fabric"/>
</record>
<record id="pav_fabric_wood" model="product.attribute.value">
<field name="name">Wood</field>
<field name="sequence">4</field>
<field name="image" type="base64" file="product/static/img/wood.png"/>
<field name="attribute_id" ref="pa_fabric"/>
</record>
<record id="pav_fabric_glass" model="product.attribute.value">
<field name="name">Glass</field>
<field name="sequence">5</field>
<field name="default_extra_price">50</field>
<field name="image" type="base64" file="product/static/img/glass.png"/>
<field name="attribute_id" ref="pa_fabric"/>
</record>
<record id="pav_fabric_metal" model="product.attribute.value">
<field name="name">Metal</field>
<field name="sequence">6</field>
<field name="image" type="base64" file="product/static/img/metal.png"/>
<field name="attribute_id" ref="pa_fabric"/>
</record>
<!-- Legs Material -->
<record id="pa_legs" model="product.attribute">
<field name="name">Legs</field>
<field name="sequence">90</field>
</record>
<record id="pav_legs_steel" model="product.attribute.value">
<field name="name">Steel</field>
<field name="attribute_id" ref="pa_legs"/>
<field name="sequence">1</field>
</record>
<record id="pav_legs_aluminium" model="product.attribute.value">
<field name="name">Aluminium</field>
<field name="attribute_id" ref="pa_legs"/>
<field name="sequence">2</field>
</record>
<record id="pav_legs_wood" model="product.attribute.value">
<field name="name">Wood</field>
<field name="attribute_id" ref="pa_legs"/>
<field name="sequence">3</field>
</record>
<record id="pav_legs_custom" model="product.attribute.value">
<field name="name">Custom</field>
<field name="attribute_id" ref="pa_legs"/>
<field name="is_custom">True</field>
<field name="sequence">4</field>
</record>
<!-- Options -->
<record id="pa_options" model="product.attribute">
<field name="name">Options</field>
<field name="display_type">multi</field>
<field name="create_variant">no_variant</field>
<field name="sequence">110</field>
</record>
<record id="pav_options_drawers" model="product.attribute.value">
<field name="name">Drawers</field>
<field name="default_extra_price">250</field>
<field name="attribute_id" ref="pa_options"/>
</record>
<record id="pav_options_file_cabinets" model="product.attribute.value">
<field name="name">File cabinets</field>
<field name="default_extra_price">300</field>
<field name="attribute_id" ref="pa_options"/>
</record>
<record id="pav_options_under_desk_pedestals" model="product.attribute.value">
<field name="name">Under-desk pedestals</field>
<field name="default_extra_price">75</field>
<field name="attribute_id" ref="pa_options"/>
</record>
<record id="pav_options_overhead_shelves" model="product.attribute.value">
<field name="name">Overhead shelves</field>
<field name="default_extra_price">225</field>
<field name="attribute_id" ref="pa_options"/>
</record>
<!-- Customization -->
<record id="pa_customization" model="product.attribute">
<field name="name">Customization</field>
<field name="create_variant">no_variant</field>
<field name="sequence">120</field>
</record>
<record id="pav_custom" model="product.attribute.value">
<field name="name">Custom</field>
<field name="default_extra_price">25</field>
<field name="attribute_id" ref="product.pa_customization"/>
<field name="is_custom">True</field>
</record>
<!-- Shoe Size -->
<record id="pa_shoe_size" model="product.attribute">
<field name="name">Shoes size</field>
<field name="create_variant">no_variant</field>
<field name="display_type">pills</field>
</record>
<record id="pav_shoe_size_39" model="product.attribute.value">
<field name="name">39</field>
<field name="attribute_id" ref="pa_shoe_size"/>
</record>
<record id="pav_shoe_size_40" model="product.attribute.value">
<field name="name">40</field>
<field name="attribute_id" ref="pa_shoe_size"/>
</record>
<record id="pav_shoe_size_41" model="product.attribute.value">
<field name="name">41</field>
<field name="attribute_id" ref="pa_shoe_size"/>
</record>
<record id="pav_shoe_size_42" model="product.attribute.value">
<field name="name">42</field>
<field name="attribute_id" ref="pa_shoe_size"/>
</record>
<record id="pav_shoe_size_43" model="product.attribute.value">
<field name="name">43</field>
<field name="attribute_id" ref="pa_shoe_size"/>
</record>
</odoo>

View file

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<odoo noupdate="1">
<record id="product_category_furniture" model="product.category">
<field name="name">Furniture</field>
</record>
<record id="product_category_office" model="product.category">
<field name="parent_id" ref="product.product_category_furniture"/>
<field name="name">Office</field>
</record>
<record id="product_category_outdoor_furniture" model="product.category">
<field name="parent_id" ref="product.product_category_furniture"/>
<field name="name">Outdoor</field>
</record>
<record id="product_category_construction" model="product.category">
<field name="name">Home Construction</field>
</record>
</odoo>

View file

@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<data noupdate="1">
<record id="product_category_all" model="product.category">
<field name="name">All</field>
<!-- Categories -->
<record id="product_category_goods" model="product.category">
<field name="name">Goods</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"/>
<record id="product_category_expenses" model="product.category">
<field name="name">Expenses</field>
</record>
<record id="product_category_services" model="product.category">
<field name="name">Services</field>
</record>
<!--
Precisions
@ -32,10 +32,6 @@
<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
@ -43,15 +39,5 @@ there yet otherwise people who have installed the server (even with the without-
parameter) will see those record just disappear.
-->
<!-- Price list -->
<record id="list0" model="product.pricelist">
<field name="name">Public Pricelist</field>
<field name="sequence">1</field>
</record>
<!--
Property
-->
</data>
</odoo>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<odoo noupdate="1">
<record id="product_product_4_product_template_document" model="product.document">
<field name="name">Customizable Desk Document</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>
<record id="product_product_25_document" model="product.document">
<field name="name">Acoustic Bloc Screens Document</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>
</odoo>

View file

@ -0,0 +1,238 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo noupdate="1">
<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_template_acoustic_bloc_screens"/>
<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>
</odoo>

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# flake8: noqa: F401
@ -8,14 +7,23 @@
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_packaging
from . import product_combo
from . import product_combo_item
from . import product_document
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 product_uom
from . import res_company
from . import res_config_settings
from . import res_country_group

View file

@ -1,40 +0,0 @@
# -*- 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)),
}}

View file

@ -0,0 +1,26 @@
# 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

View file

@ -1,55 +1,108 @@
# -*- coding: utf-8 -*-
# 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.osv import expression
from odoo import api, fields, models, _
from odoo.exceptions import UserError
class ProductAttribute(models.Model):
_name = "product.attribute"
_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'
name = fields.Char('Attribute', required=True, translate=True)
value_ids = fields.One2many('product.attribute.value', 'attribute_id', 'Values', copy=True)
sequence = fields.Integer('Sequence', help="Determine the display order", index=True, default=20)
attribute_line_ids = fields.One2many('product.template.attribute.line', 'attribute_id', 'Lines')
create_variant = fields.Selection([
('always', 'Instantly'),
('dynamic', 'Dynamically'),
('no_variant', 'Never (option)')],
_check_multi_checkbox_no_variant = models.Constraint(
"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)
active = fields.Boolean(
default=True,
help="If unchecked, it will allow you to hide the attribute without removing it.",
)
create_variant = fields.Selection(
selection=[
('always', 'Instantly'),
('dynamic', 'Dynamically'),
('no_variant', 'Never'),
],
default='always',
string="Variants Creation Mode",
string="Variant Creation",
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.""",
Note: this cannot be changed once the attribute is used on a product.""",
required=True)
display_type = fields.Selection(
selection=[
('radio', 'Radio'),
('pills', 'Pills'),
('select', 'Select'),
('color', 'Color'),
('multi', 'Multi-checkbox'),
('image', 'Image'),
],
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, default=20)
value_ids = fields.One2many(
comodel_name='product.attribute.value',
inverse_name='attribute_id',
string="Values", copy=True)
template_value_ids = fields.One2many(
comodel_name='product.template.attribute.value',
inverse_name='attribute_id',
string="Template Values")
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')
product_tmpl_ids = fields.Many2many('product.template', string="Related Products", compute='_compute_products', store=True)
display_type = fields.Selection([
('radio', 'Radio'),
('pills', 'Pills'),
('select', 'Select'),
('color', 'Color')], default='radio', required=True, help="The display type used in the Product Configurator.")
# === COMPUTE METHODS === #
@api.depends('product_tmpl_ids')
def _compute_number_related_products(self):
res = {
attribute.id: count
for attribute, count in self.env['product.template.attribute.line']._read_group(
domain=[('attribute_id', 'in', self.ids), ('product_tmpl_id.active', '=', 'True')],
groupby=['attribute_id'],
aggregates=['__count'],
)
}
for pa in self:
pa.number_related_products = len(pa.product_tmpl_ids)
pa.number_related_products = res.get(pa.id, 0)
@api.depends('attribute_line_ids.active', 'attribute_line_ids.product_tmpl_id')
def _compute_products(self):
templates_by_attribute = {
attribute.id: templates
for attribute, templates in self.env['product.template.attribute.line']._read_group(
domain=[('attribute_id', 'in', self.ids)],
groupby=['attribute_id'],
aggregates=['product_tmpl_id:recordset']
)
}
for pa in self:
pa.with_context(active_test=False).product_tmpl_ids = pa.attribute_line_ids.product_tmpl_id
pa.with_context(active_test=False).product_tmpl_ids = templates_by_attribute.get(pa.id, False)
def _without_no_variant_attributes(self):
return self.filtered(lambda pa: pa.create_variant != 'no_variant')
# === ONCHANGE METHODS === #
@api.onchange('display_type')
def _onchange_display_type(self):
if self.display_type == 'multi' and self.number_related_products == 0:
self.create_variant = 'no_variant'
# === CRUD METHODS === #
def write(self, vals):
"""Override to make sure attribute type can't be changed if it's used on
@ -62,12 +115,14 @@ class ProductAttribute(models.Model):
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 %s because it is used on the following products:\n%s") %
(pa.display_name, ", ".join(pa.product_tmpl_ids.mapped('display_name')))
)
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(ProductAttribute, self).write(vals)
res = super().write(vals)
if invalidate:
# prefetched o2m have to be resequenced
# (eg. product.template: attribute_line_ids)
@ -79,566 +134,35 @@ class ProductAttribute(models.Model):
def _unlink_except_used_on_product(self):
for pa in self:
if pa.number_related_products:
raise UserError(
_("You cannot delete the attribute %s because it is used on the following products:\n%s") %
(pa.display_name, ", ".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.with_context(active_test=False).product_tmpl_ids.ids)],
}
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('product.attribute', string="Attribute", ondelete='cascade', required=True, index=True,
help="The attribute cannot be changed once the value is used on at least one product.")
pav_attribute_line_ids = fields.Many2many('product.template.attribute.line', string="Lines",
relation='product_attribute_value_product_template_attribute_line_rel', copy=False)
is_used_on_products = fields.Boolean('Used on Products', compute='_compute_is_used_on_products')
is_custom = fields.Boolean('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', readonly=True)
color = fields.Integer('Color Index', default=_get_default_color)
_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)
def name_get(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._context.get('show_attribute', True):
return super(ProductAttributeValue, self).name_get()
return [(value.id, "%s: %s" % (value.attribute_id.name, value.name)) for value in self]
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 %s because it is used on the following products:%s") %
(pav.display_name, ", ".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(ProductAttributeValue, self).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 %s because it is used on the following products:"
"\n%s\n If the value has been associated to a product in the past, you will "
"not be able to delete it.") %
(pav.display_name, ", ".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
"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 _without_no_variant_attributes(self):
return self.filtered(lambda pav: pav.attribute_id.create_variant != 'no_variant')
# === ACTION METHODS === #
def action_archive(self):
for attribute in self:
if attribute.number_related_products:
raise UserError(_(
"You cannot archive this attribute as there are still products linked to it",
))
return super().action_archive()
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 = 'attribute_id, id'
active = fields.Boolean(default=True)
product_tmpl_id = fields.Many2one('product.template', string="Product Template", ondelete='cascade', required=True, index=True)
attribute_id = fields.Many2one('product.attribute', string="Attribute", ondelete='restrict', required=True, index=True)
value_ids = fields.Many2many('product.attribute.value', string="Values", domain="[('attribute_id', '=', attribute_id)]",
relation='product_attribute_value_product_template_attribute_line_rel', ondelete='restrict')
value_count = fields.Integer(compute='_compute_value_count', store=True, readonly=True)
product_template_value_ids = fields.One2many('product.template.attribute.value', '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 %s must have at least one value for the product %s.") %
(ptal.attribute_id.display_name, ptal.product_tmpl_id.display_name)
)
for pav in ptal.value_ids:
if pav.attribute_id != ptal.attribute_id:
raise ValidationError(
_("On the product %s you cannot associate the value %s with the attribute %s because they do not match.") %
(ptal.product_tmpl_id.display_name, pav.display_name, 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(ProductTemplateAttributeLine, self).create(create_values)
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 %s from the product %s to the product %s.") %
(ptal.attribute_id.display_name, ptal.product_tmpl_id.display_name, 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 %s you cannot transform the attribute %s into the attribute %s.") %
(ptal.product_tmpl_id.display_name, ptal.attribute_id.display_name, 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'] = [(5, 0, 0)]
res = super(ProductTemplateAttributeLine, self).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
})
# 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):
@api.readonly
def action_open_product_template_attribute_lines(self):
self.ensure_one()
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,
},
'name': _("Products"),
'res_model': 'product.template.attribute.line',
'view_mode': 'list,form',
'domain': [('attribute_id', '=', self.id), ('product_tmpl_id.active', '=', 'True')],
}
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("Active", default=True)
name = fields.Char('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(
'product.attribute.value', string='Attribute Value',
required=True, ondelete='cascade', index=True)
attribute_line_id = fields.Many2one('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(
'product.template.attribute.exclusion',
'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('product.template', string="Product Template", related='attribute_line_id.product_tmpl_id', store=True, index=True)
attribute_id = fields.Many2one('product.attribute', string="Attribute", related='attribute_line_id.attribute_id', store=True, index=True)
ptav_product_variant_ids = fields.Many2many('product.product', relation='product_variant_combination', string="Related Variants", readonly=True)
html_color = fields.Char('HTML Color Index', related="product_attribute_value_id.html_color")
is_custom = fields.Boolean('Is custom value', related="product_attribute_value_id.is_custom")
display_type = fields.Selection(related='product_attribute_value_id.display_type', readonly=True)
color = fields.Integer('Color', default=_get_default_color)
_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.product_attribute_value_id not in ptav.attribute_line_id.value_ids:
raise ValidationError(
_("The value %s is not defined for the attribute %s on the product %s.") %
(ptav.product_attribute_value_id.display_name, ptav.attribute_id.display_name, 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(ProductTemplateAttributeValue, self).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 %s set on product %s.") %
(ptav.display_name, 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 %s set on product %s.") %
(ptav.display_name, ptav.product_tmpl_id.display_name)
)
res = super(ProductTemplateAttributeValue, self).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': [(3, ptav.id, 0)]})
# 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
def name_get(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
"""
return [(value.id, "%s: %s" % (value.attribute_id.name, value.name)) for value in self]
def _only_active(self):
return self.filtered(lambda ptav: ptav.ptav_active)
# === TOOLING === #
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
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(
'product.template.attribute.value', string="Attribute Value", ondelete='cascade', index=True)
product_tmpl_id = fields.Many2one(
'product.template', string='Product Template', ondelete='cascade', required=True, index=True)
value_ids = fields.Many2many(
'product.template.attribute.value', relation="product_attr_exclusion_value_ids_rel",
string='Attribute Values', domain="[('product_tmpl_id', '=', product_tmpl_id), ('ptav_active', '=', True)]")
@api.model_create_multi
def create(self, vals_list):
exclusions = super().create(vals_list)
exclusions.product_tmpl_id._create_variant_ids()
return exclusions
def unlink(self):
# Keep a reference to the related templates before the deletion.
templates = self.product_tmpl_id
res = super().unlink()
templates._create_variant_ids()
return res
def write(self, values):
templates = self.env['product.template']
if 'product_tmpl_id' in values:
templates = self.product_tmpl_id
res = super().write(values)
(templates | self.product_tmpl_id)._create_variant_ids()
return res
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("Name", compute='_compute_name')
custom_product_template_attribute_value_id = fields.Many2one('product.template.attribute.value', string="Attribute Value", required=True, ondelete='restrict')
custom_value = fields.Char("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
return self.filtered(lambda pa: pa.create_variant != 'no_variant')

View 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

View file

@ -0,0 +1,180 @@
# 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):
# if you change this _order, keep it in sync with the method
# `_sort_key_variant` in `product.template'
_name = 'product.attribute.value'
_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)
default_extra_price = fields.Float()
is_custom = fields.Boolean(
string="Free text",
help="Allow customers to set their own 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,
)
active = fields.Boolean(default=True)
is_used_on_products = fields.Boolean(
string="Used on Products", compute='_compute_is_used_on_products')
default_extra_price_changed = fields.Boolean(compute='_compute_default_extra_price_changed')
# === COMPUTE METHODS === #
@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}"
@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.filtered('product_tmpl_id.active'))
@api.depends('default_extra_price')
def _compute_default_extra_price_changed(self):
company_domain = self.env['product.template']._check_company_domain(self.env.companies)
# `sudo` required to know which products we lack access to
ptavs_by_pav = self.env['product.template.attribute.value'].sudo().search_fetch([
('product_attribute_value_id', 'in', self.ids),
('product_tmpl_id', 'any', company_domain),
], ['price_extra', 'product_attribute_value_id']).grouped('product_attribute_value_id')
for pav in self:
ptavs = ptavs_by_pav.get(pav, [])
pav.default_extra_price_changed = (
pav.default_extra_price != pav._origin.default_extra_price
or any(pav.default_extra_price != ptav.price_extra for ptav in ptavs)
)
# === CRUD METHODS === #
def write(self, vals):
if 'attribute_id' in vals:
for pav in self:
if pav.attribute_id.id != vals['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 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: value_ids)
self.env.flush_all()
self.env.invalidate_all()
return res
def check_is_used_on_products(self):
for pav in self.filtered('is_used_on_products'):
return _(
"You cannot delete the value %(value)s because it is used on the following"
" products:\n%(products)s\n",
value=pav.display_name,
products=", ".join(pav.pav_attribute_line_ids.product_tmpl_id.mapped('display_name')),
)
return False
@api.ondelete(at_uninstall=False)
def _unlink_except_used_on_product(self):
if is_used_on_products := self.check_is_used_on_products():
raise UserError(is_used_on_products)
def unlink(self):
pavs_to_archive = self.env['product.attribute.value']
for pav in self:
linked_products = pav.env['product.template.attribute.value'].search(
[('product_attribute_value_id', '=', pav.id)]
).with_context(active_test=False).ptav_product_variant_ids
active_linked_products = linked_products.filtered('active')
if not active_linked_products and linked_products:
# If product attribute value found on non-active product variants
# archive PAV instead of deleting
pavs_to_archive |= pav
if pavs_to_archive:
pavs_to_archive.action_archive()
return super(ProductAttributeValue, self - pavs_to_archive).unlink()
def _without_no_variant_attributes(self):
return self.filtered(lambda pav: pav.attribute_id.create_variant != 'no_variant')
# === ACTION METHODS === #
@api.readonly
def action_add_to_products(self):
return {
'name': _("Add to all products"),
'type': 'ir.actions.act_window',
'res_model': 'update.product.attribute.value',
'view_mode': 'form',
'target': 'new',
'context': {
'default_attribute_value_id': self.id,
'default_mode': 'add',
'dialog_size': 'medium',
},
}
@api.readonly
def action_update_prices(self):
return {
'name': _("Update product extra prices"),
'type': 'ir.actions.act_window',
'res_model': 'update.product.attribute.value',
'view_mode': 'form',
'target': 'new',
'context': {
'default_attribute_value_id': self.id,
'default_mode': 'update_extra_price',
'dialog_size': 'medium',
},
}

View file

@ -0,0 +1,151 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, models
from odoo.fields import Domain
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'
@api.readonly
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, child_field=False):
return {
'quantity': 0,
'readOnly': self._is_readonly() if self else False,
}
def _get_product_catalog_domain(self) -> Domain:
"""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 domain.
"""
return (
Domain('company_id', '=', False) | Domain('company_id', 'parent_of', self.company_id.id)
) & Domain('type', '!=', 'combo')
def _get_product_catalog_record_lines(self, product_ids, **kwargs):
""" 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)
'productType': string
'price': float
'uomDisplayName': string
'code': string (optional)
'readOnly': bool (optional)
}
"""
return {
product.id: {
'productType': product.type,
'uomDisplayName': product.uom_id.display_name,
'code': product.code if product.code else '',
}
for product in products
}
def _get_product_catalog_order_line_info(self, product_ids, child_field=False, **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)
'productType': string
'price': float
'uomDisplayName': string
'code': string (optional)
'readOnly': bool (optional)
}
"""
order_line_info = {}
for product, record_lines in self._get_product_catalog_record_lines(product_ids, child_field=child_field, **kwargs).items():
order_line_info[product.id] = {
**record_lines._get_product_catalog_lines_data(parent_record=self, **kwargs),
'productType': product.type,
'code': product.code if product.code else '',
}
if not order_line_info[product.id]['uomDisplayName']:
order_line_info[product.id]['uomDisplayName'] = product.uom_id.display_name
default_data = self._default_order_line_values(child_field)
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():
if product_id in order_line_info:
continue
order_line_info[product_id] = {**default_data, **data}
return order_line_info
def _get_action_add_from_catalog_extra_context(self):
return {
'display_uom': self.env.user.has_group('uom.group_uom'),
'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

View file

@ -2,11 +2,12 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
from odoo.exceptions import ValidationError
class ProductCategory(models.Model):
_name = "product.category"
_name = 'product.category'
_inherit = ['mail.thread']
_description = "Product Category"
_parent_name = "parent_id"
_parent_store = True
@ -18,11 +19,12 @@ class ProductCategory(models.Model):
'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)
parent_path = fields.Char(index=True)
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):
@ -33,8 +35,8 @@ class ProductCategory(models.Model):
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'], ['categ_id'])
group_data = dict((data['categ_id'][0], data['categ_id_count']) for data in read_group_res)
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:
@ -43,26 +45,25 @@ class ProductCategory(models.Model):
@api.constrains('parent_id')
def _check_category_recursion(self):
if not self._check_recursion():
if self._has_cycle():
raise ValidationError(_('You cannot create recursive categories.'))
@api.model
def name_create(self, name):
return self.create({'name': name}).name_get()[0]
category = self.create({'name': name})
return category.id, category.display_name
def name_get(self):
if not self.env.context.get('hierarchical_naming', True):
return [(record.id, record.name) for record in self]
return super().name_get()
@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))
saleable_category = self.env.ref('product.product_category_1', raise_if_not_found=False)
if saleable_category and saleable_category in self:
raise UserError(_("You cannot delete the %s product category.", saleable_category.name))
def copy_data(self, default=None):
default = dict(default or {})
vals_list = super().copy_data(default=default)
if 'name' not in default:
for category, vals in zip(self, vals_list):
vals['name'] = _("%s (copy)", category.name)
return vals_list

View file

@ -0,0 +1,79 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class ProductCombo(models.Model):
_name = 'product.combo'
_description = "Product Combo"
_order = 'sequence, id'
name = fields.Char(string="Name", required=True)
sequence = fields.Integer(default=10, copy=False)
company_id = fields.Many2one(string="Company", comodel_name='res.company', index=True)
combo_item_ids = fields.One2many(
comodel_name='product.combo.item',
inverse_name='combo_id',
copy=True,
)
combo_item_count = fields.Integer(string="Product Count", compute='_compute_combo_item_count')
currency_id = fields.Many2one(comodel_name='res.currency', compute='_compute_currency_id')
base_price = fields.Float(
string="Combo Price",
help="The minimum price among the products in this combo. This value will be used to"
" prorate the price of this combo with respect to the other combos in a combo product."
" This heuristic ensures that whatever product the user chooses in a combo, it will"
" always be the same price.",
min_display_digits='Product Price',
compute='_compute_base_price',
)
@api.depends('combo_item_ids')
def _compute_combo_item_count(self):
# Initialize combo_item_count to 0 as _read_group won't return any results for new combos.
self.combo_item_count = 0
# Optimization to count the number of combo items in each combo.
for combo, item_count in self.env['product.combo.item']._read_group(
domain=[('combo_id', 'in', self.ids)],
groupby=['combo_id'],
aggregates=['__count'],
):
combo.combo_item_count = item_count
@api.depends('company_id')
def _compute_currency_id(self):
main_company = self.env['res.company']._get_main_company()
for combo in self:
combo.currency_id = (
combo.company_id.sudo().currency_id or main_company.currency_id
)
@api.depends('combo_item_ids')
def _compute_base_price(self):
for combo in self:
combo.base_price = min(combo.combo_item_ids.mapped(
lambda item: item.currency_id._convert(
from_amount=item.lst_price,
to_currency=combo.currency_id,
company=combo.company_id or self.env.company,
date=self.env.cr.now(),
)
)) if combo.combo_item_ids else 0
@api.constrains('combo_item_ids')
def _check_combo_item_ids_not_empty(self):
if any(not combo.combo_item_ids for combo in self):
raise ValidationError(_("A combo choice must contain at least 1 product."))
@api.constrains('combo_item_ids')
def _check_combo_item_ids_no_duplicates(self):
for combo in self:
if len(combo.combo_item_ids.mapped('product_id')) < len(combo.combo_item_ids):
raise ValidationError(_("A combo choice can't contain duplicate products."))
@api.constrains('company_id')
def _check_company_id(self):
templates = self.env['product.template'].sudo().search([('combo_ids', 'in', self.ids)])
templates._check_company(fnames=['combo_ids'])
self.combo_item_ids._check_company(fnames=['product_id'])

View file

@ -0,0 +1,33 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class ProductComboItem(models.Model):
_name = 'product.combo.item'
_description = "Product Combo Item"
_check_company_auto = True
company_id = fields.Many2one(related='combo_id.company_id', precompute=True, store=True)
combo_id = fields.Many2one(comodel_name='product.combo', ondelete='cascade', required=True, index=True)
product_id = fields.Many2one(
string="Options",
comodel_name='product.product',
ondelete='restrict',
domain=[('type', '!=', 'combo')],
required=True,
check_company=True,
)
currency_id = fields.Many2one(comodel_name='res.currency', related='product_id.currency_id')
lst_price = fields.Float(
string="Original Price",
min_display_digits='Product Price',
related='product_id.lst_price',
)
extra_price = fields.Float(string="Extra Price", min_display_digits='Product Price', default=0.0)
@api.constrains('product_id')
def _check_product_id_no_combo(self):
if any(combo_item.product_id.type == 'combo' for combo_item in self):
raise ValidationError(_("A combo choice can't contain products of type \"combo\"."))

View file

@ -0,0 +1,60 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class ProductDocument(models.Model):
_name = 'product.document'
_description = "Product Document"
_inherits = {
'ir.attachment': 'ir_attachment_id',
}
_order = 'sequence, name'
ir_attachment_id = fields.Many2one(
'ir.attachment',
string="Related attachment",
required=True,
ondelete='cascade')
active = fields.Boolean(default=True)
sequence = fields.Integer(default=10)
@api.onchange('url')
def _onchange_url(self):
for attachment in self:
if attachment.type == 'url' and attachment.url and\
not attachment.url.startswith(('https://', 'http://', 'ftp://')):
raise ValidationError(_(
"Please enter a valid URL.\nExample: https://www.odoo.com\n\nInvalid URL: %s",
attachment.url
))
#=== 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_data(self, default=None):
vals_list = super().copy_data(default=default)
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}
for document, vals in zip(self, vals_list):
vals['ir_attachment_id'] = document.ir_attachment_id.with_context(
no_document=True,
disable_product_documents_creation=True,
).copy(ir_default).id
return vals_list
def unlink(self):
attachments = self.ir_attachment_id
res = super().unlink()
return res and attachments.unlink()

View file

@ -1,72 +0,0 @@
# -*- 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)
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 write(self, vals):
res = super().write(vals)
if res and not vals.get('product_id', True):
self.unlink()
return res

Some files were not shown because too many files have changed in this diff Show more