Debian Codegraph @

addons/point_of_sale/models/product_template.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2 from odoo import api, fields, models, _
3 from odoo.exceptions import UserError
4 from collections import defaultdict
5 from odoo.tools import SQL, is_html_empty
6 from itertools import groupby
7 from operator import itemgetter
8 from datetime import date
9 from odoo.fields import Domain
10
11
12 class ProductTemplate(models.Model):
13 _name = 'product.template'
14 _inherit = ['product.template', 'pos.load.mixin']
15
16 @api.model
17 def _default_pos_sequence(self):
18 self.env.cr.execute('SELECT MAX(pos_sequence) FROM %s' % self._table)
19 max_sequence = self.env.cr.fetchone()[0]
20 if max_sequence is None:
21 return 1
22 return max_sequence + 1
23
24 available_in_pos = fields.Boolean(string='Available in POS', help='Check if you want this product to appear in the Point of Sale.', default=False)
25 to_weight = fields.Boolean(string='To Weigh With Scale', help="Check if the product should be weighted using the hardware scale integration.")
26 pos_categ_ids = fields.Many2many(
27 'pos.category', string='Point of Sale Category',
28 help="Category used in the Point of Sale.")
29 public_description = fields.Html(
30 string="Product Description",
31 translate=True
32 )
33 pos_optional_product_ids = fields.Many2many(
34 comodel_name='product.template',
35 relation='pos_product_optional_rel',
36 column1='src_id',
37 column2='dest_id',
38 string="POS Optional Products",
39 help="Optional products are suggested when customers add items to their cart (e.g., adding a burger suggests cold drinks or fries).")
40 color = fields.Integer('Color Index', compute="_compute_color", store=True, readonly=False)
41 pos_sequence = fields.Integer(
42 string="POS Sequence",
43 help="Determine the display order in the POS Terminal",
44 default=_default_pos_sequence,
45 copy=False,
46 )
47
48 def write(self, vals):
49 # Clear empty public description content to avoid side-effects on product page
50 # when there is no content to display anyway.
51 if vals.get('public_description') and is_html_empty(vals['public_description']):
52 vals['public_description'] = ''
53 return super().write(vals)
54
55 @api.depends('pos_categ_ids')
56 def _compute_color(self):
57 """Automatically set the color field based on the selected category."""
58 for product in self:
59 if product.pos_categ_ids:
60 product.color = product.pos_categ_ids[0].color
61
62 def create_product_variant_from_pos(self, attribute_value_ids, config_id):
63 """ Create a product variant from the POS interface. """
64 self.ensure_one()
65 pos_config = self.env['pos.config'].browse(config_id)
66 product_template_attribute_value_ids = self.env['product.template.attribute.value'].browse(attribute_value_ids)
67 product_variant = self._create_product_variant(product_template_attribute_value_ids)
68 return {
69 'product.product': product_variant.read(self.env['product.product']._load_pos_data_fields(pos_config), load=False),
70 }
71
72 @api.model
73 def _load_pos_data_domain(self, data, config):
74 domain = [
75 *self.env['product.template']._check_company_domain(config.company_id),
76 ('available_in_pos', '=', True),
77 ('sale_ok', '=', True),
78 ]
79 if config.limit_categories:
80 domain += [('pos_categ_ids', 'in', config.iface_available_categ_ids.ids)]
81 return domain
82
83 @api.model
84 def load_product_from_pos(self, config_id, domain, offset=0, limit=0):
85 load_archived = self.env.context.get('load_archived', False)
86 domain = Domain(domain)
87 config = self.env['pos.config'].browse(config_id)
88 product_tmpls = self._load_product_with_domain(domain, load_archived, offset, limit)
89
90 # product.combo and product.combo.item loading
91 for product_tmpl in product_tmpls:
92 if product_tmpl.type == 'combo':
93 product_tmpls += product_tmpl.combo_ids.combo_item_ids.product_id.product_tmpl_id
94
95 combo_domain = Domain('id', 'in', product_tmpls.combo_ids.ids)
96 combo_records = self.env['product.combo'].search(combo_domain)
97 combo_read = self.env['product.combo']._load_pos_data_read(combo_records, config)
98 combo_item_domain = Domain('combo_id', 'in', product_tmpls.combo_ids.ids)
99 combo_item_records = self.env['product.combo.item'].search(combo_item_domain)
100 combo_item_read = self.env['product.combo.item']._load_pos_data_read(combo_item_records, config)
101
102 products = product_tmpls.product_variant_ids
103
104 # product.pricelist_item & product.pricelist loading
105 pricelists = config.current_session_id.get_pos_ui_product_pricelist_item_by_product(
106 product_tmpls.ids,
107 products.ids,
108 config.id
109 )
110
111 # product.template.attribute.value & product.template.attribute.line loading
112 product_tmpl_attr_line = product_tmpls.attribute_line_ids
113 product_tmpl_attr_line_read = product_tmpl_attr_line._load_pos_data_read(product_tmpl_attr_line, config)
114 product_tmpl_attr_value = product_tmpls.attribute_line_ids.product_template_value_ids
115 product_tmpl_attr_value_read = product_tmpl_attr_value._load_pos_data_read(product_tmpl_attr_value, config)
116
117 # product.template.attribute.exclusion loading
118 product_tmpl_excl = self.env['product.template.attribute.exclusion']
119 product_tmpl_exclusion = product_tmpl_attr_value.exclude_for + product_tmpl_excl.search([
120 ('product_tmpl_id', 'in', product_tmpls.ids),
121 ])
122 product_tmpl_exclusion_read = product_tmpl_excl._load_pos_data_read(product_tmpl_exclusion, config)
123
124 # product.product loading
125 product_read = products._load_pos_data_read(products.with_context(display_default_code=False), config)
126
127 # product.template loading
128 product_tmpl_read = self._load_pos_data_read(product_tmpls, config)
129
130 # product.uom loading
131 packaging_domain = Domain('product_id', 'in', products.ids)
132 barcode_in_domain = any('barcode' in condition.field_expr for condition in domain.iter_conditions())
133
134 if barcode_in_domain:
135 barcode = [condition.value for condition in domain.iter_conditions() if 'barcode' in condition.field_expr]
136 flat = [item for sublist in barcode for item in sublist]
137 packaging_domain |= Domain('barcode', 'in', flat)
138
139 product_uom = self.env['product.uom']
140 packaging = product_uom.search(packaging_domain)
141 condition = packaging and packaging.product_id
142 packaging_read = product_uom._load_pos_data_read(packaging, config) if condition else []
143
144 # account.tax loading
145 account_tax = self.env['account.tax']
146 tax_domain = Domain(account_tax._check_company_domain(config.company_id.id))
147 tax_domain &= Domain('id', 'in', product_tmpls.taxes_id.ids)
148 tax_read = account_tax._load_pos_data_read(account_tax.search(tax_domain), config)
149
150 return {
151 **pricelists,
152 'account.tax': tax_read,
153 'product.product': product_read,
154 'product.template': product_tmpl_read,
155 'product.uom': packaging_read,
156 'product.combo': combo_read,
157 'product.combo.item': combo_item_read,
158 'product.template.attribute.value': product_tmpl_attr_value_read,
159 'product.template.attribute.line': product_tmpl_attr_line_read,
160 'product.template.attribute.exclusion': product_tmpl_exclusion_read,
161 }
162
163 @api.model
164 def _load_pos_data_fields(self, config_id):
165 return [
166 'id', 'display_name', 'standard_price', 'categ_id', 'pos_categ_ids', 'taxes_id', 'barcode', 'name', 'list_price', 'is_favorite',
167 'default_code', 'to_weight', 'uom_id', 'description_sale', 'description', 'tracking', 'type', 'service_tracking', 'is_storable',
168 'write_date', 'color', 'pos_sequence', 'available_in_pos', 'attribute_line_ids', 'active', 'image_128', 'combo_ids', 'product_variant_ids', 'public_description',
169 'pos_optional_product_ids', 'sequence', 'product_tag_ids'
170 ]
171
172 @api.model
173 def _load_pos_data_search_read(self, data, config):
174 limit_count = config.get_limited_product_count()
175 pos_limited_loading = self.env.context.get('pos_limited_loading', True)
176 if limit_count and pos_limited_loading:
177 query = self._search(self._load_pos_data_domain(data, config), bypass_access=True)
178 sql = SQL(
179 """
180 WITH pm AS (
181 SELECT pp.product_tmpl_id,
182 MAX(sml.write_date) date
183 FROM stock_move_line sml
184 JOIN product_product pp ON sml.product_id = pp.id
185 GROUP BY pp.product_tmpl_id
186 )
187 SELECT product_template.id
188 FROM %s
189 LEFT JOIN pm ON product_template.id = pm.product_tmpl_id
190 WHERE %s
191 ORDER BY product_template.is_favorite DESC NULLS LAST,
192 CASE WHEN product_template.type = 'service' THEN 1 ELSE 0 END DESC,
193 pm.date DESC NULLS LAST,
194 product_template.write_date DESC
195 LIMIT %s
196 """,
197 query.from_clause,
198 query.where_clause or SQL("TRUE"),
199 limit_count,
200 )
201 product_tmpl_ids = [r[0] for r in self.env.execute_query(sql)]
202 products = self._load_product_with_domain([('id', 'in', product_tmpl_ids)])
203 else:
204 domain = self._load_pos_data_domain(data, config)
205 products = self._load_product_with_domain(domain)
206
207 product_combo = products.filtered(lambda p: p['type'] == 'combo')
208 products += product_combo.combo_ids.combo_item_ids.product_id.product_tmpl_id
209
210 special_products = config._get_special_products().filtered(
211 lambda product: not product.sudo().company_id
212 or product.sudo().company_id == self.env.company
213 )
214 products += special_products.product_tmpl_id
215 if config.tip_product_id:
216 tip_company_id = config.tip_product_id.sudo().company_id
217 if not tip_company_id or tip_company_id == self.env.company:
218 products += config.tip_product_id.product_tmpl_id
219
220 # Ensure optional products are loaded when configured.
221 if products.filtered(lambda p: p.pos_optional_product_ids):
222 products |= products.mapped("pos_optional_product_ids")
223
224 # Ensure products from loaded orders are loaded
225 if data.get('pos.order.line'):
226 products += self.env['product.product'].browse([l['product_id'] for l in data['pos.order.line']]).product_tmpl_id
227
228 return self._load_pos_data_read(products, config)
229
230 @api.model
231 def _load_pos_data_read(self, records, config):
232 read_records = super()._load_pos_data_read(records, config)
233 self._process_pos_ui_product_product(read_records, config)
234 return read_records
235
236 def _load_product_with_domain(self, domain, load_archived=False, offset=0, limit=0):
237 context = {**self.env.context, 'display_default_code': False, 'active_test': not load_archived, 'bin_size': True}
238 domain = self._server_date_to_domain(domain)
239 return self.with_context(context).search(
240 domain,
241 order='sequence,default_code,name',
242 offset=offset,
243 limit=limit if limit else False
244 )
245
246 def _process_pos_ui_product_product(self, products, config_id):
247
248 def filter_taxes_on_company(product_taxes, taxes_by_company):
249 """
250 Filter the list of tax ids on a single company starting from the current one.
251 If there is no tax in the result, it's filtered on the parent company and so
252 on until a non empty result is found.
253 """
254 taxes, comp = None, self.env.company
255 while not taxes and comp:
256 taxes = list(set(product_taxes) & set(taxes_by_company[comp.id]))
257 comp = comp.parent_id
258 return taxes
259
260 taxes = self.env['account.tax'].search(self.env['account.tax']._check_company_domain(self.env.company))
261 # group all taxes by company in a dict where:
262 # - key: ID of the company
263 # - values: list of tax ids
264 taxes_by_company = defaultdict(set)
265 if self.env.company.parent_id:
266 for tax in taxes:
267 taxes_by_company[tax.company_id.id].add(tax.id)
268
269 different_currency = config_id.currency_id != self.env.company.currency_id
270
271 self._add_archived_combinations(products)
272 for product in products:
273 if different_currency:
274 product['list_price'] = self.env.company.currency_id._convert(product['list_price'], config_id.currency_id, self.env.company, fields.Date.today())
275 product['standard_price'] = self.env.company.currency_id._convert(product['standard_price'], config_id.currency_id, self.env.company, fields.Date.today())
276
277 product['image_128'] = bool(product['image_128'])
278
279 if len(taxes_by_company) > 1 and len(product['taxes_id']) > 1:
280 product['taxes_id'] = filter_taxes_on_company(product['taxes_id'], taxes_by_company)
281
282 def _add_archived_combinations(self, products):
283 """ Add archived combinations to the product template data. """
284 product_data = {product['id']: product for product in products}
285 for product_tmpl in self.browse(product_data.keys()):
286 product = product_data[product_tmpl.id]
287 attribute_exclusions = product_tmpl._get_attribute_exclusions()
288 product['_archived_combinations'] = attribute_exclusions['archived_combinations']
289 excluded = {}
290 for ptav_id, ptav_ids in attribute_exclusions['exclusions'].items():
291 for ptav_id2 in set(ptav_ids) - excluded.keys():
292 excluded[ptav_id] = ptav_id2
293 product['_archived_combinations'].extend(excluded.items())
294
295 @api.ondelete(at_uninstall=False)
296 def _unlink_except_open_session(self):
297 product_ctx = dict(self.env.context or {}, active_test=False)
298 if self.with_context(product_ctx).search_count([('id', 'in', self.ids), ('available_in_pos', '=', True)]):
299 if self.env['pos.session'].sudo().search_count([('state', '!=', 'closed')]):
300 raise UserError(_(
301 "To delete a product, make sure all point of sale sessions are closed.\n\n"
302 "Deleting a product available in a session would be like attempting to snatch a hamburger from a customer’s hand mid-bite; chaos will ensue as ketchup and mayo go flying everywhere!",
303 ))
304
305 def _ensure_unused_in_pos(self):
306 open_pos_sessions = self.env['pos.session'].sudo().search([('state', '!=', 'closed')])
307 used_products = open_pos_sessions.order_ids.filtered(lambda o: o.state == "draft").lines.product_id.product_tmpl_id
308 if used_products & self:
309 raise UserError(_(
310 "Hold up! Archiving products while POS sessions are active is like pulling a plate mid-meal.\n"
311 "Make sure to close all sessions first to avoid any issues.",
312 ))
313
314 def action_archive(self):
315 self._ensure_unused_in_pos()
316 return super().action_archive()
317
318 @api.onchange('sale_ok')
319 def _onchange_sale_ok(self):
320 if not self.sale_ok:
321 self.available_in_pos = False
322
323 @api.onchange('available_in_pos')
324 def _onchange_available_in_pos(self):
325 if self.available_in_pos and not self.sale_ok:
326 self.sale_ok = True
327
328 @api.constrains('available_in_pos')
329 def _check_combo_inclusions(self):
330 for product in self:
331 if not product.available_in_pos:
332 combo_name = self.env['product.combo.item'].sudo().search([('product_id', 'in', product.product_variant_ids.ids)], limit=1).combo_id.name
333 if combo_name:
334 raise UserError(_('You must first remove this product from the %s combo', combo_name))
335
336 def get_product_info_pos(self, price, quantity, pos_config_id, product_variant_id=False):
337 self.ensure_one()
338 config = self.env['pos.config'].browse(pos_config_id)
339 product_variant = self.env['product.product'].browse(product_variant_id) if product_variant_id else False
340 template_or_variant = product_variant or self.product_variant_id
341
342 # Tax related
343 tax_to_use = self.env['account.tax']
344 company = config.company_id
345 while not tax_to_use and company:
346 tax_to_use = self.taxes_id.filtered(lambda tax: tax.company_id.id == company.id)
347 if not tax_to_use:
348 company = company.sudo().parent_id
349 taxes = tax_to_use.compute_all(price, config.currency_id, quantity, self)
350 grouped_taxes = {}
351 for tax in taxes['taxes']:
352 if tax['id'] in grouped_taxes:
353 grouped_taxes[tax['id']]['amount'] += tax['amount'] / quantity if quantity else 0
354 else:
355 grouped_taxes[tax['id']] = {
356 'name': tax['name'],
357 'amount': tax['amount'] / quantity if quantity else 0
358 }
359
360 all_prices = {
361 'price_without_tax': taxes['total_excluded'] / quantity if quantity else 0,
362 'price_with_tax': taxes['total_included'] / quantity if quantity else 0,
363 'tax_details': list(grouped_taxes.values()),
364 }
365
366 # Pricelists
367 if config.use_pricelist:
368 pricelists = config.available_pricelist_ids
369 else:
370 pricelists = config.pricelist_id
371 price_per_pricelist_id = pricelists._price_get(template_or_variant, quantity) if pricelists else False
372 pricelist_list = [{'name': pl.name, 'price': price_per_pricelist_id[pl.id]} for pl in pricelists]
373
374 # Warehouses
375 warehouse_list = [
376 {'id': w.id,
377 'name': w.name,
378 'available_quantity': template_or_variant.with_context({'warehouse_id': w.id}).qty_available,
379 'free_qty': template_or_variant.with_context({'warehouse_id': w.id}).free_qty,
380 'forecasted_quantity': template_or_variant.with_context({'warehouse_id': w.id}).virtual_available,
381 'uom': template_or_variant.uom_name}
382 for w in self.env['stock.warehouse'].search([('company_id', '=', config.company_id.id)])]
383
384 if config.picking_type_id.warehouse_id:
385 # Sort the warehouse_list, prioritizing config.picking_type_id.warehouse_id
386 warehouse_list = sorted(
387 warehouse_list,
388 key=lambda w: w['id'] != config.picking_type_id.warehouse_id.id
389 )
390
391 # Suppliers
392 key = itemgetter('partner_id')
393 supplier_list = []
394 for _key, group in groupby(sorted(self.seller_ids, key=key), key=key):
395 for s in group:
396 if not ((s.date_start and s.date_start > date.today()) or (s.date_end and s.date_end < date.today()) or (s.min_qty > quantity)):
397 supplier_list.append({
398 'id': s.id,
399 'name': s.partner_id.name,
400 'delay': s.delay,
401 'price': s.price
402 })
403 break
404
405 # Variants
406 variant_list = [{'name': attribute_line.attribute_id.name,
407 'values': [{'name': attr_name, 'search': f'{self.name} {attr_name}'} for attr_name in attribute_line.value_ids.mapped('name')]}
408 for attribute_line in self.attribute_line_ids]
409
410 return {
411 'all_prices': all_prices,
412 'pricelists': pricelist_list,
413 'warehouses': warehouse_list,
414 'suppliers': supplier_list,
415 'variants': variant_list,
416 'optional_products': self.pos_optional_product_ids.read(['id', 'name', 'list_price']),
417 }