Debian Codegraph @

addons/point_of_sale/models/pos_config.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 from datetime import datetime
4 from uuid import uuid4
5 import pytz
6 from collections import defaultdict
7
8 from odoo import api, fields, models, _, Command, tools, SUPERUSER_ID
9 from odoo.http import request
10 from odoo.exceptions import AccessError, ValidationError, UserError
11 from odoo.tools import SQL, convert
12 from odoo.service.common import exp_version
13 from odoo.addons.point_of_sale.models.pos_printer import format_epson_certified_domain
14
15 DEFAULT_LIMIT_LOAD_PRODUCT = 5000
16 DEFAULT_LIMIT_LOAD_PARTNER = 100
17
18
19 class PosConfig(models.Model):
20 _name = 'pos.config'
21 _inherit = ['pos.bus.mixin', 'pos.load.mixin']
22 _description = 'Point of Sale Configuration'
23 _check_company_auto = True
24
25 def _default_warehouse_id(self):
26 return self.env['stock.warehouse'].search(self.env['stock.warehouse']._check_company_domain(self.env.company), limit=1).id
27
28 def _default_picking_type_id(self):
29 return self.env['stock.warehouse'].with_context(active_test=False).search(self.env['stock.warehouse']._check_company_domain(self.env.company), limit=1).pos_type_id.id
30
31 def _default_sale_journal(self):
32 journal = self.env['account.journal']._ensure_company_account_journal()
33 return journal
34
35 def _default_invoice_journal(self):
36 return self.env['account.journal'].search([
37 *self.env['account.journal']._check_company_domain(self.env.company),
38 ('type', '=', 'sale'),
39 ], limit=1)
40
41 def _default_payment_methods(self):
42 """ Should only default to payment methods that are compatible to this config's company and currency.
43 """
44 domain = [
45 *self.env['pos.payment.method']._check_company_domain(self.env.company),
46 ('split_transactions', '=', False),
47 '|',
48 ('journal_id', '=', False),
49 ('journal_id.currency_id', 'in', (False, self.env.company.currency_id.id)),
50 ]
51 non_cash_pm = self.env['pos.payment.method'].search(domain + [('is_cash_count', '=', False)])
52 available_cash_pm = self.env['pos.payment.method'].search(domain + [('is_cash_count', '=', True),
53 ('config_ids', '=', False)], limit=1)
54 if not (non_cash_pm or available_cash_pm):
55 _dummy, payment_methods = self._create_journal_and_payment_methods()
56 return self.env['pos.payment.method'].browse(payment_methods)
57 return non_cash_pm | available_cash_pm
58
59 def _get_group_pos_manager(self):
60 return self.env.ref('point_of_sale.group_pos_manager')
61
62 def _get_group_pos_user(self):
63 return self.env.ref('point_of_sale.group_pos_user')
64
65 def _get_default_tip_product(self):
66 tip_product_id = self.env.ref("point_of_sale.product_product_tip", raise_if_not_found=False)
67 if not tip_product_id or (tip_product_id.sudo().company_id and tip_product_id.sudo().company_id != self.env.company):
68 tip_product_id = self.env['product.product'].search([('default_code', '=', 'TIPS')], limit=1)
69 return tip_product_id
70
71 name = fields.Char(string='Point of Sale', required=True, help="An internal identification of the point of sale.")
72 printer_ids = fields.Many2many('pos.printer', 'pos_config_printer_rel', 'config_id', 'printer_id', string='Order Printers')
73 is_order_printer = fields.Boolean('Order Printer')
74 is_installed_account_accountant = fields.Boolean(string="Is the Full Accounting Installed",
75 compute="_compute_is_installed_account_accountant")
76 picking_type_id = fields.Many2one(
77 'stock.picking.type',
78 string='Operation Type',
79 default=_default_picking_type_id,
80 required=True,
81 domain=lambda self: [('code', '=', 'outgoing'), ('warehouse_id.company_id', '=', self.env.company.id)],
82 ondelete='restrict')
83 journal_id = fields.Many2one(
84 'account.journal', string='Point of Sale Journal',
85 domain=[('type', 'in', ('general', 'sale'))],
86 check_company=True,
87 help="Accounting journal used to post POS session journal entries and POS invoice payments.",
88 default=_default_sale_journal,
89 ondelete='restrict')
90 invoice_journal_id = fields.Many2one(
91 'account.journal', string='Invoice Journal',
92 check_company=True,
93 domain=[('type', '=', 'sale')],
94 help="Accounting journal used to create invoices.",
95 default=_default_invoice_journal)
96 currency_id = fields.Many2one('res.currency', compute='_compute_currency', store=True, compute_sudo=True, string="Currency")
97 order_seq_id = fields.Many2one('ir.sequence', string='Order Sequence', readonly=True, copy=False)
98 order_backend_seq_id = fields.Many2one('ir.sequence', string='Order Backend Sequence', readonly=True, copy=False)
99 order_line_seq_id = fields.Many2one('ir.sequence', string='Order Line Sequence', readonly=True, copy=False)
100 device_seq_id = fields.Many2one('ir.sequence', string='Device Sequence', readonly=True, copy=False)
101 iface_cashdrawer = fields.Boolean(string='Cashdrawer', help="Automatically open the cashdrawer.")
102 iface_electronic_scale = fields.Boolean(string='Electronic Scale', help="Enables Electronic Scale integration.")
103 iface_print_via_proxy = fields.Boolean(string='Print via Proxy', help="Bypass browser printing and prints via the hardware proxy.")
104 iface_scan_via_proxy = fields.Boolean(string='Scan via Proxy', help="Enable barcode scanning with a remotely connected barcode scanner and card swiping with a Vantiv card reader.")
105 iface_big_scrollbars = fields.Boolean('Large Scrollbars', help='For imprecise industrial touchscreens.')
106 iface_group_by_categ = fields.Boolean("Group products by categories", help='Display products grouped by categories.')
107 iface_print_auto = fields.Boolean(string='Automatic Receipt Printing', default=False,
108 help='The receipt will automatically be printed at the end of each order.')
109 iface_print_skip_screen = fields.Boolean(string='Skip Preview Screen', default=True,
110 help='The receipt screen will be skipped if the receipt can be printed automatically.')
111 iface_tax_included = fields.Selection([('subtotal', 'Tax-Excluded Price'), ('total', 'Tax-Included Price')], string="Tax Display", default='total', required=True)
112 iface_available_categ_ids = fields.Many2many('pos.category', string='Available PoS Product Categories',
113 help='The point of sale will only display products which are within one of the selected category trees. If no category is specified, all available products will be shown')
114 customer_display_bg_img = fields.Image(string='Background Image', max_width=1920, max_height=1920)
115 customer_display_bg_img_name = fields.Char(string='Background Image Name')
116 restrict_price_control = fields.Boolean(string='Restrict Price Modifications to Managers',
117 help="Only users with Manager access rights for PoS app can modify the product prices on orders.")
118 is_margins_costs_accessible_to_every_user = fields.Boolean(string='Margins & Costs', default=False,
119 help='When disabled, only PoS manager can view the margin and cost of product among the Product info.')
120 cash_control = fields.Boolean(string='Advanced Cash Control', compute='_compute_cash_control', help="Check the amount of the cashbox at opening and closing.")
121 set_maximum_difference = fields.Boolean('Set Maximum Difference', help="Set a maximum difference allowed between the expected and counted money during the closing of the session.")
122 receipt_header = fields.Text(string='Receipt Header', help="A short text that will be inserted as a header in the printed receipt.")
123 receipt_footer = fields.Text(string='Receipt Footer', help="A short text that will be inserted as a footer in the printed receipt.")
124 basic_receipt = fields.Boolean(string='Basic Receipt', help="Print basic ticket without prices. Can be used for gifts.")
125 proxy_ip = fields.Char(string='IP Address', size=45,
126 help='The hostname or ip address of the hardware proxy, Will be autodetected if left empty.')
127 active = fields.Boolean(default=True)
128 uuid = fields.Char(readonly=True, default=lambda self: str(uuid4()), copy=False,
129 help='A globally unique identifier for this pos configuration, used to prevent conflicts in client-generated data.')
130 session_ids = fields.One2many('pos.session', 'config_id', string='Sessions')
131 current_session_id = fields.Many2one('pos.session', compute='_compute_current_session', string="Current Session")
132 current_session_state = fields.Char(compute='_compute_current_session')
133 number_of_rescue_session = fields.Integer(string="Number of Rescue Session", compute='_compute_current_session')
134 last_session_closing_cash = fields.Float(compute='_compute_last_session')
135 last_session_closing_date = fields.Date(compute='_compute_last_session')
136 pos_session_username = fields.Char(compute='_compute_current_session_user')
137 pos_session_state = fields.Char(compute='_compute_current_session_user')
138 pos_session_duration = fields.Char(compute='_compute_current_session_user')
139 pricelist_id = fields.Many2one('product.pricelist', string='Default Pricelist',
140 help="The pricelist used if no customer is selected or if the customer has no Sale Pricelist configured if any.")
141 available_pricelist_ids = fields.Many2many('product.pricelist', string='Available Pricelists',
142 help="Make several pricelists available in the Point of Sale. You can also apply a pricelist to specific customers from their contact form (in Sales tab). To be valid, this pricelist must be listed here as an available pricelist. Otherwise the default pricelist will apply.")
143 company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.company)
144 group_pos_manager_id = fields.Many2one('res.groups', string='Point of Sale Manager Group', default=_get_group_pos_manager,
145 help='This field is there to pass the id of the pos manager group to the point of sale client.')
146 group_pos_user_id = fields.Many2one('res.groups', string='Point of Sale User Group', default=_get_group_pos_user,
147 help='This field is there to pass the id of the pos user group to the point of sale client.')
148 iface_tipproduct = fields.Boolean(string="Product tips")
149 tip_product_id = fields.Many2one('product.product', string='Tip Product', default=_get_default_tip_product, help="This product is used as reference on customer receipts.")
150 fiscal_position_ids = fields.Many2many('account.fiscal.position', string='Fiscal Positions', help='This is useful for restaurants with onsite and take-away services that imply specific tax rates.')
151 default_fiscal_position_id = fields.Many2one('account.fiscal.position', string='Default Fiscal Position')
152 default_bill_ids = fields.Many2many('pos.bill', string="Coins/Bills")
153 use_pricelist = fields.Boolean("Use a pricelist.")
154 use_presets = fields.Boolean("Use Presets")
155 default_preset_id = fields.Many2one('pos.preset', string='Default Preset')
156 available_preset_ids = fields.Many2many('pos.preset', string='Available Presets')
157 tax_regime_selection = fields.Boolean("Tax Regime Selection value")
158 limit_categories = fields.Boolean("Restrict Categories")
159 module_pos_restaurant = fields.Boolean("Is a Bar/Restaurant")
160 module_pos_avatax = fields.Boolean("AvaTax PoS Integration", help="Use automatic taxes mapping with Avatax in PoS")
161 module_pos_discount = fields.Boolean("Global Discounts")
162 module_pos_appointment = fields.Boolean("Online Booking")
163 is_posbox = fields.Boolean("PosBox")
164 is_header_or_footer = fields.Boolean("Custom Header & Footer")
165 module_pos_hr = fields.Boolean(help="Show employee login screen")
166 amount_authorized_diff = fields.Float('Amount Authorized Difference',
167 help="This field depicts the maximum difference allowed between the ending balance and the theoretical cash when "
168 "closing a session, for non-POS managers. If this maximum is reached, the user will have an error message at "
169 "the closing of his session saying that he needs to contact his manager.")
170 payment_method_ids = fields.Many2many('pos.payment.method', string='Payment Methods', default=lambda self: self._default_payment_methods(), copy=False)
171 company_has_template = fields.Boolean(string="Company has chart of accounts", compute="_compute_company_has_template")
172 current_user_id = fields.Many2one('res.users', string='Current Session Responsible', compute='_compute_current_session_user')
173 other_devices = fields.Boolean(string="Other Devices", help="Connect devices to your PoS without an IoT Box.")
174 rounding_method = fields.Many2one('account.cash.rounding', string="Cash rounding")
175 cash_rounding = fields.Boolean(string="Cash Rounding")
176 only_round_cash_method = fields.Boolean(string="Only apply rounding on cash")
177 has_active_session = fields.Boolean(compute='_compute_current_session')
178 manual_discount = fields.Boolean(string="Line Discounts", default=True)
179 ship_later = fields.Boolean(string="Ship Later")
180 warehouse_id = fields.Many2one('stock.warehouse', default=_default_warehouse_id, ondelete='restrict')
181 route_id = fields.Many2one('stock.route', string="Spefic route for products delivered later.")
182 picking_policy = fields.Selection([
183 ('direct', 'As soon as possible'),
184 ('one', 'When all products are ready')],
185 string='Shipping Policy', required=True, default='direct',
186 help="If you deliver all products at once, the delivery order will be scheduled based on the greatest "
187 "product lead time. Otherwise, it will be based on the shortest.")
188 auto_validate_terminal_payment = fields.Boolean(default=True, help="Automatically validates orders paid with a payment terminal.")
189 trusted_config_ids = fields.Many2many("pos.config", relation="pos_config_trust_relation", column1="is_trusting",
190 column2="is_trusted", string="Trusted Point of Sale Configurations",
191 domain="[('company_id', '=', company_id)]")
192 access_token = fields.Char("Access Token", default=lambda self: uuid4().hex[:16])
193 show_product_images = fields.Boolean(string="Show Product Images", help="Show product images in the Point of Sale interface.", default=True)
194 show_category_images = fields.Boolean(string="Show Category Images", help="Show category images in the Point of Sale interface.", default=True)
195 note_ids = fields.Many2many('pos.note', string='Note Models', help='The predefined notes of this point of sale.')
196 module_pos_sms = fields.Boolean(string="SMS Enabled", help="Activate SMS feature for point_of_sale")
197 is_closing_entry_by_product = fields.Boolean(
198 string='Closing Entry by product',
199 help="Display the breakdown of sales lines by product in the automatically generated closing entry.")
200 order_edit_tracking = fields.Boolean(string="Track orders edits", help="Store edited orders in the backend", default=False)
201 last_data_change = fields.Datetime(string='Last Write Date', readonly=True, compute='_compute_local_data_integrity', store=True)
202 fallback_nomenclature_id = fields.Many2one('barcode.nomenclature', string="Fallback Nomenclature")
203 epson_printer_ip = fields.Char(
204 string='Epson Printer IP',
205 help=(
206 "Local IP address of an Epson receipt printer, or its serial number if the "
207 "'Automatic Certificate Update' option is enabled in the printer settings."
208 ),
209 )
210 use_fast_payment = fields.Boolean('Fast Payment Validation', help="Enable fast payment methods to validate orders on the product screen.")
211 fast_payment_method_ids = fields.Many2many(
212 'pos.payment.method', string='Fast Payment Methods', compute="_compute_fast_payment_method_ids", relation='pos_payment_method_config_fast_validation_relation',
213 store=True, help="These payment methods will be available for fast payment", readonly=False)
214 statistics_for_current_session = fields.Json(string="Session Statistics", compute="_compute_statistics_for_session")
215
216 def _get_next_order_refs(self, device_identifier='0'):
217 next_number = self.order_backend_seq_id._next()
218 year_2_digits = str(datetime.now().year)[-2:]
219 tracking_number = f"{int(next_number) % 1000}"
220 return f"{year_2_digits}{device_identifier}-{self.id}-{next_number}", tracking_number
221
222 def notify_synchronisation(self, session_id, device_identifier, records={}):
223 self.ensure_one()
224 static_records = {}
225
226 for model, ids in records.items():
227 records = self.env[model].browse(ids).exists()
228 static_records[model] = self.env[model]._load_pos_data_read(records, self)
229
230 self._notify('SYNCHRONISATION', {
231 'static_records': static_records,
232 'session_id': session_id,
233 'device_identifier': device_identifier,
234 'records': records
235 })
236
237 for config in self.trusted_config_ids:
238 config._notify('SYNCHRONISATION', {
239 'static_records': static_records,
240 'session_id': config.current_session_id.id,
241 'login_number': 0,
242 'records': records
243 })
244
245 def read_config_open_orders(self, domain, record_ids=[]):
246 delete_record_ids = {}
247 dynamic_records = {}
248
249 for model, dom in domain.items():
250 ids = record_ids.get(model, [])
251 browsed = self.env[model].browse(ids)
252
253 dynamic_records[model] = self.env[model].search(dom)
254 delete_record_ids[model] = browsed.filtered(lambda r: not r.exists()).ids
255 # Cancelled orders must be forced deleted from the user interface.
256 if model == "pos.order":
257 delete_record_ids[model] += browsed.filtered(lambda r: r.state == "cancel").ids
258
259 pos_order_data = dynamic_records.get('pos.order') or self.env['pos.order']
260 data = pos_order_data.read_pos_data([], self)
261
262 for key, records in dynamic_records.items():
263 fields = self.env[key]._load_pos_data_fields(self)
264 ids = list(set(records.ids + [record['id'] for record in data.get(key, [])]))
265 dynamic_records[key] = self.env[key].browse(ids).read(fields, load=False)
266
267 for key, value in data.items():
268 if key not in dynamic_records:
269 dynamic_records[key] = value
270
271 return {
272 'dynamic_records': dynamic_records,
273 'deleted_record_ids': delete_record_ids,
274 }
275
276 @api.model
277 def _load_pos_data_domain(self, data, config):
278 return [('id', '=', config.id)]
279
280 @api.model
281 def _load_pos_data_read(self, records, config):
282 read_records = super()._load_pos_data_read(records, config)
283 if not read_records:
284 return read_records
285
286 record = read_records[0]
287 record['_server_version'] = exp_version()
288 record['_base_url'] = self.get_base_url()
289 record['_data_server_date'] = self.env.context.get('pos_last_server_date') or self.env.cr.now()
290 record['_has_cash_move_perm'] = self.env.user.has_group('account.group_account_invoice')
291 record['_has_cash_delete_perm'] = self.env.user.has_group('account.group_account_basic')
292 record['_pos_special_products_ids'] = self.env['pos.config']._get_special_products().ids
293
294 # Add custom fields for 'formula' taxes.
295 # We can ignore data for _load_pos_data_domain since isn't needed in the domain computation of account.tax
296 taxes = self.env['account.tax'].search(self.env['account.tax']._load_pos_data_domain({}, config))
297 product_fields = taxes._eval_taxes_computation_prepare_product_fields()
298 record['_product_default_values'] = \
299 self.env['account.tax']._eval_taxes_computation_prepare_product_default_values(product_fields)
300
301 if not record['use_pricelist']:
302 record['pricelist_id'] = False
303 record['_IS_VAT'] = self.env.company.country_id.id in self.env.ref("base.europe").country_ids.ids
304 return read_records
305
306 @api.depends('payment_method_ids')
307 def _compute_fast_payment_method_ids(self):
308 for config in self:
309 config.fast_payment_method_ids = config.fast_payment_method_ids.filtered(lambda pm: pm.id in config.payment_method_ids.ids)
310 if not config.fast_payment_method_ids:
311 config.use_fast_payment = False
312
313 @api.depends('payment_method_ids')
314 def _compute_cash_control(self):
315 for config in self:
316 config.cash_control = bool(config.payment_method_ids.filtered('is_cash_count'))
317
318 @api.depends('company_id')
319 def _compute_company_has_template(self):
320 for config in self:
321 config.company_has_template = config.company_id.root_id.sudo()._existing_accounting() or config.company_id.chart_template
322
323 def _compute_is_installed_account_accountant(self):
324 account_accountant = self.env['ir.module.module'].sudo().search([('name', '=', 'account_accountant'), ('state', '=', 'installed')])
325 for pos_config in self:
326 pos_config.is_installed_account_accountant = account_accountant and account_accountant.id
327
328 @api.depends('journal_id.currency_id', 'journal_id.company_id.currency_id', 'company_id', 'company_id.currency_id')
329 def _compute_currency(self):
330 for pos_config in self:
331 if pos_config.journal_id:
332 pos_config.currency_id = pos_config.journal_id.currency_id.id or pos_config.journal_id.company_id.sudo().currency_id.id
333 else:
334 pos_config.currency_id = pos_config.company_id.sudo().currency_id.id
335
336 @api.depends('session_ids', 'session_ids.state')
337 def _compute_current_session(self):
338 """If there is an open session, store it to current_session_id / current_session_State.
339 """
340 self.session_ids.fetch(["state"])
341 for pos_config in self:
342 opened_sessions = pos_config.session_ids.filtered(lambda s: s.state != 'closed')
343 rescue_sessions = opened_sessions.filtered('rescue')
344 session = pos_config.session_ids.filtered(lambda s: s.state != 'closed' and not s.rescue)
345 # sessions ordered by id desc
346 pos_config.has_active_session = opened_sessions and True or False
347 pos_config.current_session_id = session and session[0].id or False
348 pos_config.current_session_state = session and session[0].state or False
349 pos_config.number_of_rescue_session = len(rescue_sessions)
350
351 def _compute_statistics_for_session(self):
352 for config in self:
353 session = config.session_ids.filtered(lambda s: s.state != 'closed' and not s.rescue)
354 session_record = session[0] if session else None
355 if not session_record or not session_record.exists():
356 config.statistics_for_current_session = False
357 continue
358 config.statistics_for_current_session = config.get_statistics_for_session(session_record)
359
360 def get_statistics_for_session(self, session):
361 self.ensure_one()
362 currency = self.currency_id
363 timezone = pytz.timezone(self.env.context.get('tz') or self.env.user.tz or 'UTC')
364 statistics = {
365 'cash': {
366 'raw_opening_cash': session.cash_register_balance_start,
367 'opening_cash': currency.format(session.cash_register_balance_start)
368 },
369 'date': {
370 'is_started': bool(session.start_at),
371 'start_date': session.start_at.astimezone(timezone).strftime('%b %d') if session.start_at else False,
372 },
373 'orders': {
374 'paid': False,
375 'draft': False,
376 },
377 }
378
379 all_paid_orders = session.order_ids.filtered(lambda o: o.state in ['paid', 'done'])
380 refund_orders = all_paid_orders.filtered(lambda o: o.is_refund)
381 draft_orders = session.order_ids.filtered(lambda o: o.state == 'draft')
382 non_refund_orders = all_paid_orders - refund_orders
383
384 # calculate total refunded amount per original order for refund count check
385 refund_totals = defaultdict(float)
386 for refund in refund_orders:
387 if refund.refunded_order_id:
388 refund_totals[refund.refunded_order_id.id] += abs(refund.amount_total)
389
390 # count paid orders that are not completely refunded
391 paid_order_count = sum(
392 1 for order in non_refund_orders
393 if refund_totals.get(order.id, 0.0) != order.amount_total
394 )
395
396 if paid_order_count:
397 total_paid = sum(all_paid_orders.mapped('amount_total'))
398 statistics['orders']['paid'] = {
399 'amount': total_paid,
400 'count': paid_order_count,
401 'display': f"{currency.format(total_paid)} ({paid_order_count} {'order' if paid_order_count == 1 else 'orders'})"
402 }
403
404 if draft_orders:
405 total_draft = sum(draft_orders.mapped('amount_total'))
406 count_draft = len(draft_orders)
407 statistics['orders']['draft'] = {
408 'amount': total_draft,
409 'count': count_draft,
410 'display': f"{currency.format(total_draft)} ({count_draft} {'order' if count_draft == 1 else 'orders'})"
411 }
412
413 return statistics
414
415 @api.depends('session_ids')
416 def _compute_last_session(self):
417 PosSession = self.env['pos.session']
418 for pos_config in self:
419 session = PosSession.search_read(
420 [('config_id', '=', pos_config.id), ('state', '=', 'closed')],
421 ['cash_register_balance_end_real', 'stop_at'],
422 order="stop_at desc", limit=1)
423 if session:
424 timezone = self.env.tz
425 pos_config.last_session_closing_date = session[0]['stop_at'].astimezone(timezone).date()
426 pos_config.last_session_closing_cash = session[0]['cash_register_balance_end_real']
427 else:
428 pos_config.last_session_closing_cash = 0
429 pos_config.last_session_closing_date = False
430
431 @api.depends('session_ids')
432 def _compute_current_session_user(self):
433 for pos_config in self:
434 session = pos_config.session_ids.filtered(lambda s: s.state in ['opening_control', 'opened', 'closing_control'] and not s.rescue)
435 if session:
436 pos_config.pos_session_username = session[0].user_id.sudo().name
437 pos_config.pos_session_state = session[0].state
438 pos_config.pos_session_duration = (
439 datetime.now() - session[0].start_at
440 ).days if session[0].start_at else 0
441 pos_config.current_user_id = session[0].user_id
442 else:
443 pos_config.pos_session_username = False
444 pos_config.pos_session_state = False
445 pos_config.pos_session_duration = 0
446 pos_config.current_user_id = False
447
448 @api.constrains('rounding_method')
449 def _check_rounding_method_strategy(self):
450 for config in self:
451 if config.cash_rounding and config.rounding_method.strategy != 'add_invoice_line':
452 selection_value = "Add a rounding line"
453 for key, val in self.env["account.cash.rounding"]._fields["strategy"]._description_selection(config.env):
454 if key == "add_invoice_line":
455 selection_value = val
456 break
457 raise ValidationError(_(
458 "The cash rounding strategy of the point of sale %(pos)s must be: '%(value)s'",
459 pos=config.name,
460 value=selection_value,
461 ))
462
463 def _check_profit_loss_cash_journal(self):
464 if self.cash_control and self.payment_method_ids:
465 for method in self.payment_method_ids:
466 if method.is_cash_count and (not method.journal_id.loss_account_id or not method.journal_id.profit_account_id):
467 raise ValidationError(_("You need a loss and profit account on your cash journal."))
468
469 @api.constrains('company_id', 'payment_method_ids')
470 def _check_company_payment(self):
471 for config in self:
472 if self.env['pos.payment.method'].search_count([('id', 'in', config.payment_method_ids.ids), ('company_id', '!=', config.company_id.id)]):
473 raise ValidationError(_("The payment methods for the point of sale %s must belong to its company.", self.name))
474
475 @api.constrains('pricelist_id', 'use_pricelist', 'available_pricelist_ids', 'journal_id', 'invoice_journal_id', 'payment_method_ids')
476 def _check_currencies(self):
477 for config in self:
478 if config.use_pricelist and config.pricelist_id and config.pricelist_id not in config.available_pricelist_ids:
479 raise ValidationError(_("The default pricelist must be included in the available pricelists."))
480
481 # Check if the config's payment methods are compatible with its currency
482 for pm in config.payment_method_ids:
483 if pm.journal_id and pm.journal_id.currency_id and pm.journal_id.currency_id != config.currency_id:
484 raise ValidationError(_("All payment methods must be in the same currency as the Sales Journal or the company currency if that is not set."))
485
486 if config.use_pricelist and any(config.available_pricelist_ids.mapped(lambda pricelist: pricelist.currency_id != config.currency_id)):
487 raise ValidationError(_("All available pricelists must be in the same currency as the company or"
488 " as the Sales Journal set on this point of sale if you use"
489 " the Accounting application."))
490 if config.invoice_journal_id.currency_id and config.invoice_journal_id.currency_id != config.currency_id:
491 raise ValidationError(_("The invoice journal must be in the same currency as the Sales Journal or the company currency if that is not set."))
492
493 def _check_payment_method_ids(self):
494 self.ensure_one()
495 if not self.payment_method_ids:
496 raise ValidationError(
497 _("You must have at least one payment method configured to launch a session.")
498 )
499
500 @api.constrains('pricelist_id', 'available_pricelist_ids')
501 def _check_pricelists(self):
502 self._check_companies()
503 self = self.sudo()
504 if self.pricelist_id.company_id and self.pricelist_id.company_id != self.company_id:
505 raise ValidationError(
506 _("The default pricelist must belong to no company or the company of the point of sale."))
507
508 @api.constrains('company_id', 'available_pricelist_ids')
509 def _check_companies(self):
510 for config in self:
511 if any(pricelist.company_id.id not in [False, config.company_id.id] for pricelist in config.available_pricelist_ids):
512 raise ValidationError(_("The selected pricelists must belong to no company or the company of the point of sale."))
513
514 def _check_company_has_template(self):
515 self.ensure_one()
516 if not self.company_has_template:
517 raise ValidationError(_("No chart of account configured, go to the \"configuration / settings\" menu, and "
518 "install one from the Invoicing tab."))
519
520 @api.constrains('payment_method_ids')
521 def _check_payment_method_ids_journal(self):
522 for config in self:
523 for cash_method in config.payment_method_ids.filtered(lambda m: m.journal_id.type == 'cash'):
524 if self.env['pos.config'].search_count([('id', '!=', config.id), ('payment_method_ids', 'in', cash_method.ids)], limit=1):
525 raise ValidationError(_("This cash payment method is already used in another Point of Sale.\n"
526 "A new cash payment method should be created for this Point of Sale."))
527 if len(cash_method.journal_id.pos_payment_method_ids) > 1:
528 raise ValidationError(_("You cannot use the same journal on multiples cash payment methods."))
529
530 @api.constrains('trusted_config_ids')
531 def _check_trusted_config_ids_currency(self):
532 for config in self:
533 for trusted_config in config.trusted_config_ids:
534 if trusted_config.currency_id != config.currency_id:
535 raise ValidationError(_("You cannot share open orders with configuration that does not use the same currency."))
536
537 def _check_header_footer(self, values):
538 if not self.env.is_admin() and {'is_header_or_footer', 'receipt_header', 'receipt_footer'} & values.keys():
539 raise AccessError(_('Only administrators can edit receipt headers and footers'))
540
541 def _check_company_has_fiscal_country(self):
542 self.ensure_one()
543 if not self.company_id.account_fiscal_country_id:
544 raise ValidationError(_("The company must have a fiscal country set."))
545
546 @api.model_create_multi
547 def create(self, vals_list):
548 if not self._default_warehouse_id():
549 self.env['stock.warehouse'].create({
550 'code': vals_list[0].get('name')[:3], # first 3 characters of pos.config name
551 'company_id': self.env.company.id,
552 })
553 for vals in vals_list:
554 self._check_header_footer(vals)
555
556 pos_configs = super().create(vals_list)
557 pos_configs._create_sequences()
558 pos_configs.sudo()._check_modules_to_install()
559 pos_configs.sudo()._check_groups_implied()
560 pos_configs._update_preparation_printers_menuitem_visibility()
561 # If you plan to add something after this, use a new environment. The one above is no longer valid after the modules install.
562 return pos_configs
563
564 def _create_sequences(self):
565 for pos_config in self:
566 sequence_vals = {
567 'padding': 6,
568 'code': "pos.order",
569 'company_id': pos_config.company_id.id,
570 'implementation': 'no_gap',
571 }
572
573 # Create sequences for all orders
574 pos_config.order_seq_id = self.env['ir.sequence'].sudo().create({
575 **sequence_vals,
576 'name': _('POS order from config #%s', pos_config.id),
577 })
578
579 # Create sequences for order that are created from self ore backend
580 pos_config.order_backend_seq_id = self.env['ir.sequence'].sudo().create({
581 **sequence_vals,
582 'name': _('POS order backend from config #%s', pos_config.id),
583 })
584
585 # Create sequences for all order lines
586 pos_config.order_line_seq_id = self.env['ir.sequence'].sudo().create({
587 **sequence_vals,
588 'name': _('POS order line from config #%s', pos_config.id),
589 })
590
591 # Create sequences for devices
592 pos_config.device_seq_id = self.env['ir.sequence'].sudo().create({
593 **sequence_vals,
594 'name': _('POS device from config #%s', pos_config.id),
595 'padding': 0,
596 })
597
598 def register_new_device_identifier(self):
599 self.ensure_one()
600 identifier = self.device_seq_id._next()
601 return {
602 'device_identifier': identifier,
603 }
604
605 def _reset_default_on_vals(self, vals):
606 if 'tip_product_id' in vals and not vals['tip_product_id'] and 'iface_tipproduct' in vals and vals['iface_tipproduct']:
607 default_product = self.env.ref('point_of_sale.product_product_tip', False)
608 if default_product:
609 vals['tip_product_id'] = default_product.id
610 else:
611 raise UserError(_('The default tip product is missing. Please manually specify the tip product. (See Tips field.)'))
612
613 def _update_preparation_printers_menuitem_visibility(self):
614 prepa_printers_menuitem = self.sudo().env.ref('point_of_sale.menu_pos_preparation_printer', raise_if_not_found=False)
615 if prepa_printers_menuitem:
616 prepa_printers_menuitem.active = self.sudo().env['pos.config'].search_count([('is_order_printer', '=', True)], limit=1) > 0
617
618 @api.depends('use_pricelist', 'pricelist_id', 'available_pricelist_ids', 'payment_method_ids', 'limit_categories',
619 'iface_available_categ_ids', 'module_pos_hr', 'module_pos_discount', 'iface_tipproduct', 'default_preset_id', 'module_pos_appointment')
620 def _compute_local_data_integrity(self):
621 self.last_data_change = self.env.cr.now()
622
623 def write(self, vals):
624 self._check_header_footer(vals)
625 self._reset_default_on_vals(vals)
626 if ('is_order_printer' in vals and not vals['is_order_printer']):
627 vals['printer_ids'] = [fields.Command.clear()]
628
629 bypass_payment_method_ids_forbidden_change = self.env.context.get('bypass_payment_method_ids_forbidden_change', False)
630
631 self._preprocess_x2many_vals_from_settings_view(vals)
632 vals = self._keep_new_vals(vals)
633 opened_session = self.mapped('session_ids').filtered(lambda s: s.state != 'closed')
634 if opened_session:
635 forbidden_fields = []
636 for key in self._get_forbidden_change_fields():
637 if key in vals.keys():
638 if bypass_payment_method_ids_forbidden_change and key == 'payment_method_ids':
639 continue
640 field_name = self._fields[key].get_description(self.env)["string"]
641 forbidden_fields.append(field_name)
642
643 if len(forbidden_fields) > 0:
644 raise UserError(_(
645 "Unable to modify this PoS Configuration because you can't modify %s while a session is open.",
646 ", ".join(forbidden_fields)
647 ))
648
649 result = super(PosConfig, self).write(vals)
650
651 for config in self:
652 if config.use_presets and config.default_preset_id and config.default_preset_id.id not in config.available_preset_ids.ids:
653 config.available_preset_ids |= config.default_preset_id
654
655 self.sudo()._set_fiscal_position()
656 self.sudo()._check_modules_to_install()
657 self.sudo()._check_groups_implied()
658 if 'is_order_printer' in vals:
659 self._update_preparation_printers_menuitem_visibility()
660 return result
661
662 def _preprocess_x2many_vals_from_settings_view(self, vals):
663 """ From the res.config.settings view, changes in the x2many fields always result to an array of link commands or a single set command.
664 - As a result, the items that should be unlinked are not properly unlinked.
665 - So before doing the write, we inspect the commands to determine which records should be unlinked.
666 - We only care about the link command.
667 - We can consider set command as absolute as it will replace all.
668 """
669 from_settings_view = self.env.context.get('from_settings_view')
670 if not from_settings_view:
671 # If vals is not from the settings view, we don't need to preprocess.
672 return
673
674 # Only ensure one when write is from settings view.
675 self.ensure_one()
676
677 fields_to_preprocess = []
678 for f in self.fields_get([]).values():
679 if f['type'] in ['many2many', 'one2many']:
680 fields_to_preprocess.append(f['name'])
681
682 for x2many_field in fields_to_preprocess:
683 if x2many_field in vals:
684 linked_ids = set(self[x2many_field].ids)
685
686 for command in vals[x2many_field]:
687 if command[0] == 4:
688 _id = command[1]
689 if _id in linked_ids:
690 linked_ids.remove(_id)
691
692 # Remaining items in linked_ids should be unlinked.
693 unlink_commands = [Command.unlink(_id) for _id in linked_ids]
694
695 vals[x2many_field] = unlink_commands + vals[x2many_field]
696
697 def _keep_new_vals(self, vals):
698 """ Keep values in vals that are different than
699 self's values.
700 """
701 from_settings_view = self.env.context.get('from_settings_view')
702 if not from_settings_view:
703 return vals
704 new_vals = {}
705 for field, val in vals.items():
706 config_field = self._fields.get(field)
707 if config_field:
708 cache_value = config_field.convert_to_cache(val, self)
709 record_value = config_field.convert_to_record(cache_value, self)
710 if record_value != self[field]:
711 new_vals[field] = val
712 return new_vals
713
714 def _get_forbidden_change_fields(self):
715 return ['module_pos_restaurant', 'payment_method_ids', 'active']
716
717 def unlink(self):
718 # Delete the pos.config records first then delete the sequences linked to them
719 sequences_to_delete = self.order_line_seq_id | self.device_seq_id
720 res = super(PosConfig, self).unlink()
721 sequences_to_delete.unlink()
722 return res
723
724 # TODO-JCB: Maybe we can move this logic in `_reset_default_on_vals`
725 def _set_fiscal_position(self):
726 for config in self:
727 if config.tax_regime_selection and config.default_fiscal_position_id and (config.default_fiscal_position_id.id not in config.fiscal_position_ids.ids):
728 config.fiscal_position_ids = [(4, config.default_fiscal_position_id.id)]
729 elif not config.tax_regime_selection and config.fiscal_position_ids.ids:
730 config.fiscal_position_ids = [(5, 0, 0)]
731
732 def _check_modules_to_install(self):
733 # determine modules to install
734 expected = [
735 fname[7:] # 'module_account' -> 'account'
736 for fname in self._fields
737 if fname.startswith('module_')
738 if any(pos_config[fname] for pos_config in self)
739 ]
740 if expected:
741 STATES = ('installed', 'to install', 'to upgrade')
742 modules = self.env['ir.module.module'].sudo().search([('name', 'in', expected)])
743 modules = modules.filtered(lambda module: module.state not in STATES)
744 if modules:
745 modules.button_immediate_install()
746 # just in case we want to do something if we install a module. (like a refresh ...)
747 return True
748 return False
749
750 def _check_groups_implied(self):
751 for pos_config in self:
752 for field_name in [f for f in pos_config._fields if f.startswith('group_')]:
753 field = pos_config._fields[field_name]
754 if field.type in ('boolean', 'selection') and hasattr(field, 'implied_group'):
755 field_group_xmlids = getattr(field, 'group', 'base.group_user').split(',')
756 field_groups = self.env['res.groups'].concat(*(self.env.ref(it) for it in field_group_xmlids))
757 field_groups.write({'implied_ids': [(4, self.env.ref(field.implied_group).id)]})
758
759
760 def execute(self):
761 return {
762 'type': 'ir.actions.client',
763 'tag': 'reload',
764 }
765
766 # Methods to open the POS
767 def _action_to_open_ui(self):
768 if not self.current_session_id:
769 self.env['pos.session'].create({'user_id': self.env.uid, 'config_id': self.id})
770 pos_url = '/pos/ui/%d?from_backend=True' % self.id
771 debug = request and request.session.debug
772 if debug:
773 pos_url += '&debug=%s' % debug
774 return {
775 'type': 'ir.actions.act_url',
776 'url': pos_url,
777 'target': 'self',
778 }
779
780 def _get_url_to_cache(self, debug):
781 url_to_cache = [
782 f"/pos/ui/{self.id}?from_backend=True",
783 f"/pos/ui/{self.id}",
784 ]
785 return self.env["ir.qweb"]._get_asset_links("point_of_sale.assets_prod", debug=debug) + url_to_cache
786
787 def _check_before_creating_new_session(self):
788 self._check_company_has_template()
789 self._check_pricelists()
790 self._check_company_payment()
791 self._check_currencies()
792 self._check_profit_loss_cash_journal()
793 self._check_payment_method_ids()
794
795 def open_ui(self):
796 """Open the pos interface with config_id as an extra argument.
797
798 In vanilla PoS each user can only have one active session, therefore it was not needed to pass the config_id
799 on opening a session. It is also possible to login to sessions created by other users.
800
801 :returns: dict
802 """
803 self.ensure_one()
804 # In case of test environment, don't create the pdf
805 if self.env.uid == SUPERUSER_ID and not tools.config['test_enable']:
806 raise UserError(_("You do not have permission to open a POS session. Please try opening a session with a different user"))
807
808 if not self.current_session_id:
809 res = self._check_before_creating_new_session()
810 if res:
811 return res
812 self._validate_fields(self._fields)
813
814 self._check_company_has_fiscal_country()
815 return self._action_to_open_ui()
816
817 def close_ui(self):
818 return self.open_ui()
819
820 def open_existing_session_cb(self):
821 """ close session button
822
823 access session form to validate entries
824 """
825 self.ensure_one()
826 return self._open_session(self.current_session_id.id)
827
828 def _open_session(self, session_id):
829 self._check_pricelists() # The pricelist company might have changed after the first opening of the session
830 return {
831 'name': _('Session'),
832 'view_mode': 'form,list',
833 'res_model': 'pos.session',
834 'res_id': session_id,
835 'view_id': False,
836 'type': 'ir.actions.act_window',
837 }
838
839 def open_opened_rescue_session_form(self):
840 rescue_session_ids = self.session_ids.filtered(lambda s: s.state != 'closed' and s.rescue)
841
842 if len(rescue_session_ids) == 1:
843 return {
844 'res_model': 'pos.session',
845 'view_mode': 'form',
846 'res_id': rescue_session_ids.id,
847 'type': 'ir.actions.act_window',
848 }
849 else:
850 return {
851 'name': _('Rescue Sessions'),
852 'res_model': 'pos.session',
853 'view_mode': 'list,form',
854 'domain': [('id', 'in', rescue_session_ids.ids)],
855 'type': 'ir.actions.act_window',
856 }
857
858 def _link_same_non_cash_payment_methods(self, source_config):
859 pms = source_config.payment_method_ids.filtered(lambda pm: not pm.is_cash_count)
860 if pms:
861 self.payment_method_ids = [Command.link(pm.id) for pm in pms]
862
863 def _is_journal_exist(self, journal_code, name, company_id):
864 account_journal = self.env['account.journal']
865 existing_journal = account_journal.search([
866 ('name', '=', name),
867 ('code', '=', journal_code),
868 ('company_id', '=', company_id),
869 ], limit=1)
870
871 return existing_journal.id or account_journal.create({
872 'name': name,
873 'code': journal_code,
874 'type': 'cash',
875 'company_id': company_id,
876 }).id
877
878 def _is_pos_pm_exist(self, name, journal_id, company_id):
879 pos_payment = self.env['pos.payment.method']
880 existing_pos_cash_pm = pos_payment.search([
881 ('name', '=', name),
882 ('journal_id', '=', journal_id),
883 ('company_id', '=', company_id),
884 ], limit=1)
885
886 return existing_pos_cash_pm.id or pos_payment.create({
887 'name': name,
888 'journal_id': journal_id,
889 'company_id': company_id,
890 }).id
891
892 def get_limited_product_count(self):
893 config_param = self.env['ir.config_parameter'].sudo().get_param('point_of_sale.limited_product_count', DEFAULT_LIMIT_LOAD_PRODUCT)
894 try:
895 return int(config_param)
896 except (TypeError, ValueError, OverflowError):
897 return DEFAULT_LIMIT_LOAD_PRODUCT
898
899 def _get_limited_partner_count(self):
900 config_param = self.env['ir.config_parameter'].sudo().get_param('point_of_sale.limited_customer_count', DEFAULT_LIMIT_LOAD_PARTNER)
901 try:
902 return int(config_param)
903 except (TypeError, ValueError, OverflowError):
904 return DEFAULT_LIMIT_LOAD_PARTNER
905
906 def get_limited_partners_loading(self, offset=0):
907 return self.env.execute_query(SQL("""
908 WITH pm AS
909 (
910 SELECT partner_id,
911 Count(partner_id) order_count
912 FROM pos_order
913 GROUP BY partner_id)
914 SELECT id
915 FROM res_partner AS partner
916 LEFT JOIN pm
917 ON (
918 partner.id = pm.partner_id)
919 WHERE (
920 partner.company_id=%s OR partner.company_id IS NULL
921 )
922 ORDER BY COALESCE(pm.order_count, 0) DESC,
923 NAME limit %s offset %s;
924 """, self.company_id.id, self._get_limited_partner_count(), offset))
925
926 def action_pos_config_modal_edit(self):
927 return {
928 'view_mode': 'form',
929 'res_model': 'pos.config',
930 'type': 'ir.actions.act_window',
931 'target': 'new',
932 'res_id': self.id,
933 'context': {'pos_config_open_modal': True},
934 }
935
936 def _add_trusted_config_id(self, config_id):
937 self.trusted_config_ids += config_id
938
939 def _remove_trusted_config_id(self, config_id):
940 self.trusted_config_ids -= config_id
941
942 def _get_payment_method(self, payment_type):
943 for pm in self.payment_method_ids:
944 if pm.type == payment_type:
945 return pm
946 return False
947
948 def _get_special_products(self):
949 return self.env.ref('point_of_sale.product_product_tip', raise_if_not_found=False) or self.env['product.product']
950
951 def update_customer_display(self, order, device_uuid):
952 self.ensure_one()
953 self._notify(f"UPDATE_CUSTOMER_DISPLAY-{device_uuid}", order)
954
955 def _get_display_device_ip(self):
956 self.ensure_one()
957 return self.proxy_ip
958
959 def _get_customer_display_data(self):
960 self.ensure_one()
961 return {
962 'config_id': self.id,
963 'access_token': self.access_token,
964 'has_bg_img': bool(self.customer_display_bg_img),
965 'company_id': self.company_id.id,
966 'proxy_ip': self._get_display_device_ip(),
967 }
968
969 @api.model
970 def _create_cash_payment_method(self, cash_journal_vals=None):
971 if cash_journal_vals is None:
972 cash_journal_vals = {}
973 journal_vals = {
974 'name': _('Cash'),
975 'type': 'cash',
976 'company_id': self.env.company.id,
977 **cash_journal_vals,
978 }
979
980 default_cash_account = self.env['account.account'].with_context(lang='en_US').search([
981 ('account_type', '=', 'asset_cash'),
982 ('name', '=', 'Cash'),
983 ('company_ids', 'in', self.env.company.root_id.id)
984 ], limit=1)
985
986 if default_cash_account:
987 journal_vals['default_account_id'] = default_cash_account.id
988
989 cash_journal = self.env['account.journal'].create(journal_vals)
990 return self.env['pos.payment.method'].create({
991 'name': _('Cash'),
992 'journal_id': cash_journal.id,
993 'company_id': self.env.company.id,
994 })
995
996 def _create_journal_and_payment_methods(self, cash_ref=None, cash_journal_vals=None):
997 """This should only be called at creation of a new pos.config."""
998
999 journal = self.env['account.journal']._ensure_company_account_journal()
1000 payment_methods = self.env['pos.payment.method']
1001
1002 # create cash payment method per config
1003 cash_pm_from_ref = cash_ref and self.env.ref(cash_ref, raise_if_not_found=False)
1004 if cash_pm_from_ref:
1005 try:
1006 cash_pm_from_ref.check_access('read')
1007 cash_pm = cash_pm_from_ref
1008 except AccessError:
1009 cash_pm = self._create_cash_payment_method(cash_journal_vals)
1010 else:
1011 cash_pm = self._create_cash_payment_method(cash_journal_vals)
1012
1013 if cash_ref and cash_pm != cash_pm_from_ref:
1014 self.env['ir.model.data']._update_xmlids([{
1015 'xml_id': cash_ref,
1016 'record': cash_pm,
1017 'noupdate': True,
1018 }])
1019
1020 payment_methods |= cash_pm
1021
1022 # only create bank and customer account payment methods per company
1023 bank_pm = self.env['pos.payment.method'].search([('journal_id.type', '=', 'bank'), ('company_id', 'in', self.env.company.parent_ids.ids)])
1024 if not bank_pm:
1025 bank_journal = self.env['account.journal'].search([('type', '=', 'bank'), ('company_id', 'in', self.env.company.parent_ids.ids)], limit=1)
1026 if not bank_journal:
1027 raise UserError(_('Ensure that there is an existing bank journal. Check if chart of accounts is installed in your company.'))
1028 bank_pm = self.env['pos.payment.method'].create({
1029 'name': _('Card'),
1030 'journal_id': bank_journal.id,
1031 'company_id': self.env.company.id,
1032 'sequence': 1,
1033 })
1034
1035 payment_methods |= bank_pm
1036
1037 pay_later_pm = self.env['pos.payment.method'].search([('journal_id', '=', False), ('company_id', 'in', self.env.company.parent_ids.ids)])
1038 if not pay_later_pm:
1039 pay_later_pm = self.env['pos.payment.method'].create({
1040 'name': _('Customer Account'),
1041 'company_id': self.env.company.id,
1042 'split_transactions': True,
1043 'sequence': 2,
1044 })
1045
1046 payment_methods |= pay_later_pm
1047
1048 return journal, payment_methods.ids
1049
1050 def get_record_by_ref(self, recordRefs):
1051 # filters out unavailable external id
1052 return [self.env.ref(record).id for record in recordRefs if self.env.ref(record, raise_if_not_found=False)]
1053
1054 def load_demo_data(self):
1055 self = self.with_context(bypass_categories_forbidden_change=True)
1056 xml_id = self.get_external_id().get(self.id) or self._get_default_demo_data_xml_id()
1057 loaders = self._get_demo_data_loader_methods()
1058 for prefix, loader in loaders.items():
1059 if xml_id.startswith(prefix):
1060 return loader(True)
1061 return loaders.get(self._get_default_demo_data_xml_id(), self._load_onboarding_furniture_demo_data)(True)
1062
1063 def _get_demo_data_loader_methods(self):
1064 return {
1065 'point_of_sale.pos_config_clothes': self._load_onboarding_clothes_demo_data,
1066 'point_of_sale.pos_config_bakery': self._load_onboarding_bakery_demo_data,
1067 'point_of_sale.pos_config_main': self._load_onboarding_furniture_demo_data,
1068 }
1069
1070 def _get_default_demo_data_xml_id(self):
1071 return 'point_of_sale.pos_config_main'
1072
1073 @api.model
1074 def load_onboarding_clothes_scenario(self, with_demo_data=True):
1075 journal, payment_methods_ids = self._create_journal_and_payment_methods(
1076 cash_journal_vals={'name': _('Cash Clothes Shop'), 'show_on_dashboard': False})
1077 config = self.env['pos.config'].create([{
1078 'name': _('Clothes Shop'),
1079 'company_id': self.env.company.id,
1080 'journal_id': journal.id,
1081 'payment_method_ids': payment_methods_ids
1082 }])
1083 self.env['ir.model.data']._update_xmlids([{
1084 'xml_id': self._get_suffixed_ref_name('point_of_sale.pos_config_clothes'),
1085 'record': config,
1086 'noupdate': True,
1087 }])
1088 config._load_onboarding_clothes_demo_data(with_demo_data)
1089 return {'config_id': config.id}
1090
1091 def _load_onboarding_clothes_demo_data(self, with_demo_data=True):
1092 self.ensure_one()
1093 convert.convert_file(self._env_with_clean_context(), 'point_of_sale', 'data/scenarios/clothes_category_data.xml', idref=None, mode='init', noupdate=True)
1094 if with_demo_data:
1095 product_module = self.env['ir.module.module'].search([('name', '=', 'product')])
1096 if not product_module.demo:
1097 convert.convert_file(self._env_with_clean_context(), 'product', 'data/product_attribute_demo.xml', idref=None, mode='init', noupdate=True)
1098 convert.convert_file(self._env_with_clean_context(), 'point_of_sale', 'data/scenarios/clothes_data.xml', idref=None, mode='init', noupdate=True)
1099 clothes_categories = self.get_record_by_ref([
1100 'point_of_sale.pos_category_upper',
1101 'point_of_sale.pos_category_lower',
1102 'point_of_sale.pos_category_others'
1103 ])
1104 if clothes_categories:
1105 self.limit_categories = True
1106 self.iface_available_categ_ids = clothes_categories
1107
1108 @api.model
1109 def load_onboarding_bakery_scenario(self, with_demo_data=True):
1110 journal, payment_methods_ids = self._create_journal_and_payment_methods(
1111 cash_journal_vals={'name': _('Cash Bakery'), 'show_on_dashboard': False})
1112 config = self.env['pos.config'].create({
1113 'name': _('Bakery Shop'),
1114 'company_id': self.env.company.id,
1115 'journal_id': journal.id,
1116 'payment_method_ids': payment_methods_ids
1117 })
1118 self.env['ir.model.data']._update_xmlids([{
1119 'xml_id': self._get_suffixed_ref_name('point_of_sale.pos_config_bakery'),
1120 'record': config,
1121 'noupdate': True,
1122 }])
1123 config._load_onboarding_bakery_demo_data(with_demo_data)
1124 return {'config_id': config.id}
1125
1126 def _load_onboarding_bakery_demo_data(self, with_demo_data=True):
1127 self.ensure_one()
1128 convert.convert_file(self._env_with_clean_context(), 'point_of_sale', 'data/scenarios/bakery_category_data.xml', idref=None, mode='init', noupdate=True)
1129 if with_demo_data:
1130 convert.convert_file(self._env_with_clean_context(), 'point_of_sale', 'data/scenarios/bakery_data.xml', idref=None, mode='init', noupdate=True)
1131
1132 bakery_categories = self.get_record_by_ref([
1133 'point_of_sale.pos_category_breads',
1134 'point_of_sale.pos_category_pastries',
1135 ])
1136 if bakery_categories:
1137 self.limit_categories = True
1138 self.iface_available_categ_ids = bakery_categories
1139
1140 @api.model
1141 def load_onboarding_furniture_scenario(self, with_demo_data=True):
1142 journal, payment_methods_ids = self._create_journal_and_payment_methods(
1143 cash_ref='point_of_sale.cash_payment_method_furniture',
1144 cash_journal_vals={'name': _("Cash Furn. Shop"), 'show_on_dashboard': False},
1145 )
1146 config = self.env['pos.config'].create([{
1147 'name': _('Furniture Shop'),
1148 'company_id': self.env.company.id,
1149 'journal_id': journal.id,
1150 'payment_method_ids': payment_methods_ids
1151 }])
1152 self.env['ir.model.data']._update_xmlids([{
1153 'xml_id': self._get_suffixed_ref_name('point_of_sale.pos_config_main'),
1154 'record': config,
1155 'noupdate': True,
1156 }])
1157 config._load_onboarding_furniture_demo_data(with_demo_data)
1158 existing_session = self.env.ref('point_of_sale.pos_closed_session_2', raise_if_not_found=False)
1159 if with_demo_data and self.env.company.id == self.env.ref('base.main_company').id and not existing_session:
1160 convert.convert_file(self._env_with_clean_context(), 'point_of_sale', 'data/orders_demo.xml', idref=None, mode='init', noupdate=True)
1161 return {'config_id': config.id}
1162
1163 def _load_onboarding_furniture_demo_data(self, with_demo_data=False):
1164 self.ensure_one()
1165 convert.convert_file(self._env_with_clean_context(), 'point_of_sale', 'data/scenarios/furniture_category_data.xml', idref=None, mode='init', noupdate=True)
1166 if with_demo_data:
1167 product_module = self.env['ir.module.module'].search([('name', '=', 'product')])
1168 if not product_module.demo:
1169 convert.convert_file(self._env_with_clean_context(), 'product', 'data/product_category_demo.xml', idref=None, mode='init', noupdate=True)
1170 convert.convert_file(self._env_with_clean_context(), 'product', 'data/product_attribute_demo.xml', idref=None, mode='init', noupdate=True)
1171 convert.convert_file(self._env_with_clean_context(), 'product', 'data/product_demo.xml', idref=None, mode='init', noupdate=True)
1172 convert.convert_file(self._env_with_clean_context(), 'point_of_sale', 'data/scenarios/furniture_data.xml', idref=None, mode='init', noupdate=True)
1173
1174 furniture_categories = self.get_record_by_ref([
1175 'point_of_sale.pos_category_miscellaneous',
1176 'point_of_sale.pos_category_desks',
1177 'point_of_sale.pos_category_chairs'
1178 ])
1179 if furniture_categories:
1180 self.limit_categories = True
1181 self.iface_available_categ_ids = furniture_categories
1182
1183 @api.model
1184 def load_onboarding_retail_scenario(self, with_demo_data=False):
1185 journal, payment_methods_ids = self._create_journal_and_payment_methods(
1186 cash_journal_vals={'name': _("Cash %s", self.env.company.name), 'show_on_dashboard': False},
1187 )
1188 config = self.env['pos.config'].create([{
1189 'name': self.env.company.name,
1190 'company_id': self.env.company.id,
1191 'journal_id': journal.id,
1192 'payment_method_ids': payment_methods_ids
1193 }])
1194 self.env['ir.model.data']._update_xmlids([{
1195 'xml_id': self._get_suffixed_ref_name('point_of_sale.pos_config_retail'),
1196 'record': config,
1197 'noupdate': True,
1198 }])
1199 return {'config_id': config.id}
1200
1201 def _get_suffixed_ref_name(self, ref_name):
1202 """Suffix the given ref_name with the id of the current company if it's not the main company."""
1203 main_company = self.env.ref('base.main_company', raise_if_not_found=False)
1204 if main_company and self.env.company.id == main_company.id:
1205 return ref_name
1206 else:
1207 return f"{ref_name}_{self.env.company.id}"
1208
1209 @api.model
1210 def get_pos_kanban_view_state(self):
1211 has_pos_config = bool(self.env['pos.config'].search_count(
1212 self._check_company_domain(self.env.company)
1213 ))
1214 has_chart_template = bool(self.env.company.chart_template)
1215 main_company = self.env.ref('base.main_company', raise_if_not_found=False)
1216 return {
1217 "has_pos_config": has_pos_config,
1218 "has_chart_template": has_chart_template,
1219 "is_restaurant_installed": bool(self.env['ir.module.module'].search_count([('name', '=', 'pos_restaurant'), ('state', '=', 'installed')])),
1220 "is_main_company": main_company and self.env.company.id == main_company.id or False
1221 }
1222
1223 @api.model
1224 def install_pos_restaurant(self):
1225 pos_restaurant_module = self.env['ir.module.module'].search([('name', '=', 'pos_restaurant')])
1226 pos_restaurant_module.button_immediate_install()
1227 return {'installed_with_demo': pos_restaurant_module.demo}
1228
1229 def _get_available_pricelists(self):
1230 self.ensure_one()
1231 return self.available_pricelist_ids + self.pricelist_id if self.use_pricelist else self.pricelist_id
1232
1233 def _env_with_clean_context(self):
1234 safe_context = {}
1235 if 'allowed_company_ids' in self.env.context:
1236 safe_context['allowed_company_ids'] = self.env.context['allowed_company_ids']
1237 return self.env(context=safe_context)
1238
1239 @api.model
1240 def _set_default_pos_load_limit(self):
1241 param_model = self.env["ir.config_parameter"]
1242 if not param_model.get_param("point_of_sale.limited_product_count"):
1243 param_model.set_param("point_of_sale.limited_product_count", DEFAULT_LIMIT_LOAD_PRODUCT)
1244
1245 if not param_model.get_param("point_of_sale.limited_customer_count"):
1246 param_model.set_param("point_of_sale.limited_customer_count", DEFAULT_LIMIT_LOAD_PARTNER)
1247
1248 def _is_quantities_set(self):
1249 return self.is_closing_entry_by_product
1250
1251 @api.onchange("epson_printer_ip")
1252 def _onchange_epson_printer_ip(self):
1253 for rec in self:
1254 if rec.epson_printer_ip:
1255 rec.epson_printer_ip = format_epson_certified_domain(rec.epson_printer_ip)