Debian Codegraph @

addons/point_of_sale/models/pos_order.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2 import logging
3 import json
4 from datetime import datetime
5 from markupsafe import Markup
6 from itertools import groupby
7 from collections import defaultdict
8 from uuid import uuid4
9 from random import randrange
10 from pprint import pformat
11
12 import pytz
13
14 from odoo import api, fields, models, tools, _
15 from odoo.tools import float_is_zero, float_round, float_repr, float_compare, formatLang
16 from odoo.exceptions import ValidationError, UserError
17 from odoo.fields import Command, Domain
18 import base64
19
20
21 _logger = logging.getLogger(__name__)
22
23
24 class PosOrder(models.Model):
25 _name = 'pos.order'
26 _inherit = ["portal.mixin", "pos.bus.mixin", "pos.load.mixin", "mail.thread"]
27 _description = "Point of Sale Orders"
28 _order = "date_order desc, name desc, id desc"
29 _mailing_enabled = True
30
31 # This function deals with orders that belong to a closed session. It attempts to find
32 # any open session that can be used to capture the order. If no open session is found,
33 # an error is raised, asking the user to open a session.
34 def _get_valid_session(self, order):
35 PosSession = self.env['pos.session']
36 closed_session = PosSession.browse(order['session_id'])
37
38 _logger.warning('Session %s (ID: %s) was closed but received order %s (total: %s) belonging to it',
39 closed_session.name,
40 closed_session.id,
41 order['uuid'],
42 order['amount_total'])
43
44 open_session = PosSession.search([
45 ('state', 'not in', ('closed', 'closing_control')),
46 ('config_id', '=', closed_session.config_id.id)
47 ], limit=1)
48
49 if open_session:
50 _logger.warning('Using open session %s for uuid number %s', open_session.name, order['uuid'])
51 return open_session
52
53 raise UserError(_('No open session available. Please open a new session to capture the order.'))
54
55 @api.model
56 def _load_pos_data_domain(self, data, config):
57 return [('state', '=', 'draft'), ('config_id', '=', config.id)]
58
59 @api.model
60 def _process_order(self, order, existing_order):
61 """Create or update an pos.order from a given dictionary.
62
63 :param dict order: dictionary representing the order.
64 :param existing_order: order to be updated or False.
65 :type existing_order: pos.order.
66 :returns: id of created/updated pos.order
67 :rtype: int
68 """
69 draft = True if order.get('state') == 'draft' else False
70 pos_session = self.env['pos.session'].browse(order['session_id'])
71 if pos_session.state == 'closing_control' or pos_session.state == 'closed':
72 pos_session = self._get_valid_session(order)
73 order['session_id'] = pos_session.id
74
75 if not order.get('source'):
76 order['source'] = 'pos'
77
78 if order.get('partner_id'):
79 partner_id = self.env['res.partner'].browse(order['partner_id'])
80 if not partner_id.exists():
81 order.update({
82 "partner_id": False,
83 "to_invoice": False,
84 })
85
86 if not order.get('company_id'):
87 order['company_id'] = pos_session.config_id.company_id.id
88
89 pos_order = False
90 record_uuid_mapping = order.pop('relations_uuid_mapping', {})
91
92 if not existing_order:
93 pos_order = self.create({
94 **{key: value for key, value in order.items() if key != 'name'},
95 })
96 pos_order = pos_order.with_company(pos_order.company_id)
97 else:
98 pos_order = existing_order
99
100 # If the order is belonging to another session, it must be moved to the current session first
101 if order.get('session_id') and order['session_id'] != pos_order.session_id.id:
102 pos_order.write({'session_id': order['session_id']})
103
104 # Save lines and payments before to avoid exception if a line is deleted
105 # when vals change the state to 'paid'
106 for field in ['lines', 'payment_ids']:
107 if order.get(field):
108 existing_ids = set(pos_order[field].ids)
109 pos_order.write({field: order[field]})
110 added_ids = set(pos_order[field].ids) - existing_ids
111 if added_ids:
112 _logger.info("Added %s %s to pos.order #%s", field, list(added_ids), pos_order.id)
113 order[field] = []
114
115 del order['uuid']
116 del order['access_token']
117 if order.get('state') == 'paid':
118 # The "paid" state will be assigned later by `_process_saved_order`
119 order['state'] = pos_order.state
120 pos_order.write(order)
121
122 for model_name, mapping in record_uuid_mapping.items():
123 owner_records = self.env[model_name].search([('uuid', 'in', mapping.keys())])
124 for uuid, fields in mapping.items():
125 for name, uuids in fields.items():
126 params = self.env[model_name]._fields[name]
127 if params.type in ['one2many', 'many2many']:
128 records = self.env[params.comodel_name].search([('uuid', 'in', uuids)])
129 owner_records.filtered(lambda r: r.uuid == uuid).write({name: [Command.link(r.id) for r in records]})
130 else:
131 record = self.env[params.comodel_name].search([('uuid', '=', uuids)])
132 owner_records.filtered(lambda r: r.uuid == uuid).write({name: record.id})
133
134 self = self.with_company(pos_order.company_id)
135 self._process_payment_lines(order, pos_order, pos_session, draft)
136 return pos_order._process_saved_order(draft)
137
138 def _process_saved_order(self, draft):
139 self.ensure_one()
140 if not draft and self.state != 'cancel':
141 self.action_pos_order_paid()
142 self._create_order_picking()
143 self._compute_total_cost_in_real_time()
144
145 if self.to_invoice and self.state == 'paid' and self.config_id.invoice_journal_id:
146 self._generate_pos_order_invoice()
147 elif not self.config_id.invoice_journal_id:
148 _logger.warning('Trying to create an invoice without any journal configured')
149 raise UserError(_('No invoice journal configured for this POS session.'))
150
151 return self.id
152
153 def _clean_payment_lines(self):
154 self.ensure_one()
155 self.payment_ids.unlink()
156
157 def _compute_amount_paid(self):
158 return sum(self.payment_ids.mapped('amount'))
159
160 def _process_payment_lines(self, pos_order, order, pos_session, draft):
161 """Create account.bank.statement.lines from the dictionary given to the parent function.
162
163 If the payment_line is an updated version of an existing one, the existing payment_line will first be
164 removed before making a new one.
165 :param pos_order: dictionary representing the order.
166 :type pos_order: dict.
167 :param order: Order object the payment lines should belong to.
168 :type order: pos.order
169 :param pos_session: PoS session the order was created in.
170 :type pos_session: pos.session
171 :param draft: Indicate that the pos_order is not validated yet.
172 :type draft: bool.
173 """
174 prec_acc = order.currency_id.decimal_places
175
176 # Recompute amount paid because we don't trust the client
177 order.write({'amount_paid': order._compute_amount_paid()})
178
179 if not draft and not float_is_zero(pos_order['amount_return'], prec_acc):
180 cash_payment_method = pos_session.payment_method_ids.filtered('is_cash_count')[:1]
181 if not cash_payment_method:
182 raise UserError(_("No cash statement found for this session. Unable to record returned cash."))
183 return_payment_vals = {
184 'name': _('return'),
185 'pos_order_id': order.id,
186 'amount': pos_order['amount_return'],
187 'payment_date': fields.Datetime.now(),
188 'payment_method_id': cash_payment_method.id,
189 'is_change': True,
190 }
191 order.add_payment(return_payment_vals)
192 order._compute_prices()
193
194 def _prepare_tax_base_line_values(self):
195 """ Convert pos order lines into dictionaries that would be used to compute taxes later.
196
197 :return: A list of python dictionaries (see '_prepare_base_line_for_taxes_computation' in account.tax).
198 """
199 result = []
200 for order in self:
201 result.extend(order.lines._prepare_tax_base_line_values() or [])
202 return result
203
204 @api.model
205 def _get_invoice_lines_values(self, line_values, pos_line, move_type):
206 # correct quantity sign based on move type and if line is refund.
207 is_refund_order = pos_line.order_id.is_refund
208 qty_sign = -1 if (
209 (move_type == 'out_invoice' and is_refund_order)
210 or (move_type == 'out_refund' and not is_refund_order)
211 ) else 1
212
213 if line_values['product_id'].type == 'combo':
214 quantity = int(line_values['quantity']) if line_values['quantity'] == int(
215 line_values['quantity']) else line_values['quantity']
216 return {
217 'display_type': 'line_section',
218 'name': f"{line_values['product_id'].name} x {quantity}",
219 'quantity': qty_sign * line_values['quantity'],
220 'product_uom_id': line_values['uom_id'].id,
221 }
222
223 return {
224 'product_id': line_values['product_id'].id,
225 'quantity': qty_sign * line_values['quantity'],
226 'discount': line_values['discount'],
227 'price_unit': line_values['price_unit'],
228 'name': line_values['name'],
229 'tax_ids': [(6, 0, line_values['tax_ids'].ids)],
230 'product_uom_id': line_values['uom_id'].id,
231 'extra_tax_data': self.env['account.tax']._export_base_line_extra_tax_data(line_values),
232 }
233
234 def _prepare_invoice_lines(self, move_type):
235 """ Prepare a list of orm commands containing the dictionaries to fill the
236 'invoice_line_ids' field when creating an invoice.
237
238 :return: A list of Command.create to fill 'invoice_line_ids' when calling account.move.create.
239 """
240 invoice_lines = []
241 for order in self:
242 line_values_list = order.with_context(invoicing=True)._prepare_tax_base_line_values()
243 for line_values in line_values_list:
244 line = line_values['record']
245 invoice_lines_values = order._get_invoice_lines_values(line_values, line, move_type)
246 invoice_lines.append((0, None, invoice_lines_values))
247
248 is_percentage = order.pricelist_id and any(
249 order.pricelist_id.item_ids.filtered(
250 lambda rule: rule.compute_price == "percentage")
251 )
252 if is_percentage and float_compare(line.price_unit, line.product_id.lst_price, precision_rounding=order.currency_id.rounding) < 0:
253 invoice_lines.append((0, None, {
254 'name': _('Price discount from %(original_price)s to %(discounted_price)s',
255 original_price=float_repr(line.product_id.lst_price, order.currency_id.decimal_places),
256 discounted_price=float_repr(line.price_unit, order.currency_id.decimal_places)),
257 'display_type': 'line_note',
258 }))
259 if line.customer_note:
260 invoice_lines.append((0, None, {
261 'name': line.customer_note,
262 'display_type': 'line_note',
263 }))
264 if order.general_customer_note:
265 invoice_lines.append((0, None, {
266 'name': order.general_customer_note,
267 'display_type': 'line_note',
268 }))
269 return invoice_lines
270
271 def _get_pos_anglo_saxon_price_unit(self, product, partner_id, quantity):
272 moves = self.filtered(lambda o: o.partner_id.id == partner_id)\
273 .mapped('picking_ids.move_ids')\
274 .filtered(lambda m: m.is_valued and m.product_id.valuation == 'real_time' and m.product_id.id == product.id)\
275 .sorted(lambda x: x.date)
276 return moves._get_price_unit()
277
278 name = fields.Char(string='Order Ref', required=True, readonly=True, copy=False, default='/')
279 last_order_preparation_change = fields.Char(string='Last preparation change', help="Last printed state of the order")
280 date_order = fields.Datetime(string='Date', readonly=True, index=True, default=fields.Datetime.now)
281 user_id = fields.Many2one(
282 comodel_name='res.users', string='Employee',
283 help="Employee who uses the cash register.",
284 default=lambda self: self.env.uid,
285 )
286 amount_difference = fields.Monetary(string='Difference', readonly=True)
287 amount_tax = fields.Monetary(string='Taxes', readonly=True, required=True)
288 amount_total = fields.Monetary(string='Total', readonly=True, required=True)
289 amount_paid = fields.Monetary(string='Paid', required=True)
290 amount_return = fields.Monetary(string='Returned', required=True, readonly=True)
291 margin = fields.Monetary(string="Margin", compute='_compute_margin')
292 margin_percent = fields.Float(string="Margin (%)", compute='_compute_margin', digits=(12, 4))
293 is_total_cost_computed = fields.Boolean(compute='_compute_is_total_cost_computed',
294 help="Allows to know if all the total cost of the order lines have already been computed")
295 lines = fields.One2many('pos.order.line', 'order_id', string='Order Lines', copy=True)
296 company_id = fields.Many2one('res.company', string='Company', required=True, readonly=True, index=True)
297 country_code = fields.Char(related='company_id.account_fiscal_country_id.code')
298 pricelist_id = fields.Many2one('product.pricelist', string='Pricelist')
299 partner_id = fields.Many2one('res.partner', string='Customer', change_default=True, index='btree_not_null')
300 sequence_number = fields.Integer(string='Sequence Number', copy=False,
301 help='A session-unique sequence number for the order. Negative if generated from the client')
302 session_id = fields.Many2one('pos.session', string='Session', index=True, domain="[('state', '=', 'opened')]")
303 config_id = fields.Many2one('pos.config', compute='_compute_order_config_id', string="Point of Sale", readonly=False, store=True)
304 currency_id = fields.Many2one('res.currency', related='config_id.currency_id', string="Currency")
305 currency_rate = fields.Float("Currency Rate", compute='_compute_currency_rate', compute_sudo=True, store=True, digits=0, readonly=True,
306 help='The rate of the currency to the currency of rate applicable at the date of the order')
307
308 is_refund = fields.Boolean(string='Is Refund', readonly=True, default=False)
309 state = fields.Selection(
310 [('draft', 'New'), ('cancel', 'Cancelled'), ('paid', 'Paid'), ('done', 'Posted')],
311 'Status', readonly=True, copy=False, default='draft', index=True)
312
313 account_move = fields.Many2one('account.move', string='Invoice', readonly=True, copy=False, index="btree_not_null")
314 picking_ids = fields.One2many('stock.picking', 'pos_order_id')
315 picking_count = fields.Integer(compute='_compute_picking_count')
316 failed_pickings = fields.Boolean(compute='_compute_picking_count')
317 picking_type_id = fields.Many2one('stock.picking.type', related='session_id.config_id.picking_type_id', string="Operation Type", readonly=False)
318 stock_reference_ids = fields.Many2many('stock.reference', 'stock_reference_pos_order_rel', 'pos_order_id', 'reference_id', string="Reference")
319 preset_id = fields.Many2one('pos.preset', string='Preset')
320 floating_order_name = fields.Char(string='Order Name')
321 general_customer_note = fields.Text(string='General Customer Note')
322 internal_note = fields.Text(string='Internal Note')
323 nb_print = fields.Integer(string='Number of Print', readonly=True, copy=False, default=0)
324 pos_reference = fields.Char(string='Receipt Number', readonly=True, copy=False, index=True)
325 sale_journal = fields.Many2one('account.journal', related='session_id.config_id.journal_id', string='Sales Journal', store=True, readonly=True, ondelete='restrict')
326 fiscal_position_id = fields.Many2one(
327 comodel_name='account.fiscal.position', string='Fiscal Position',
328 readonly=False,
329 )
330 payment_ids = fields.One2many('pos.payment', 'pos_order_id', string='Payments')
331 session_move_id = fields.Many2one('account.move', string='Session Journal Entry', related='session_id.move_id', readonly=True, copy=False)
332 to_invoice = fields.Boolean('To invoice', copy=False)
333 shipping_date = fields.Date('Shipping Date')
334 preset_time = fields.Datetime(string='Hour', help="Hour of the day for the order")
335 is_invoiced = fields.Boolean('Is Invoiced', compute='_compute_is_invoiced')
336 is_tipped = fields.Boolean('Is this already tipped?', readonly=True)
337 tip_amount = fields.Monetary(string='Tip Amount', readonly=True)
338 refund_orders_count = fields.Integer('Number of Refund Orders', compute='_compute_refund_related_fields', help="Number of orders where items from this order were refunded")
339 refunded_order_id = fields.Many2one('pos.order', compute='_compute_refund_related_fields', help="Order from which items were refunded in this order")
340 has_refundable_lines = fields.Boolean('Has Refundable Lines', compute='_compute_has_refundable_lines')
341 ticket_code = fields.Char(help='5 digits alphanumeric code to be used by portal user to request an invoice')
342 tracking_number = fields.Char(string="Order Number", readonly=True, copy=False)
343 uuid = fields.Char(string='Uuid', readonly=True, default=lambda self: str(uuid4()), copy=False)
344 email = fields.Char(string='Email', compute="_compute_contact_details", readonly=False, store=True)
345 mobile = fields.Char(string='Mobile', compute="_compute_contact_details", readonly=False, store=True)
346 is_edited = fields.Boolean(string='Edited', compute='_compute_is_edited')
347 has_deleted_line = fields.Boolean(string='Has Deleted Line')
348 order_edit_tracking = fields.Boolean(related="config_id.order_edit_tracking", readonly=True)
349 available_payment_method_ids = fields.Many2many('pos.payment.method', related='config_id.payment_method_ids', string='Available Payment Methods', readonly=True, store=False)
350 invoice_status = fields.Selection([
351 ('invoiced', 'Fully Invoiced'),
352 ('to_invoice', 'To Invoice'),
353 ], string='Invoice Status', compute='_compute_invoice_status')
354 reversed_move_ids = fields.One2many(
355 'account.move',
356 'reversed_pos_order_id',
357 string="Reversal Account Moves",
358 help="List of account moves created when this POS order was reversed and invoiced after session close."
359 )
360 source = fields.Selection(string="Origin", selection=[('pos', 'Point of Sale')], default='pos')
361
362 _unique_uuid = models.Constraint('unique (uuid)', 'An order with this uuid already exists')
363
364 def get_preparation_change(self):
365 self.ensure_one()
366 return {
367 'last_order_preparation_change': self.last_order_preparation_change,
368 }
369
370 def _ensure_to_keep_last_preparation_change(self, vals):
371 for record in self:
372 if record.last_order_preparation_change:
373 change = json.loads(record.last_order_preparation_change)
374 if not change.get('metadata'):
375 return
376
377 local_change = json.loads(vals.get('last_order_preparation_change', '{}'))
378 if not local_change.get('metadata'):
379 vals['last_order_preparation_change'] = record.last_order_preparation_change
380 return
381
382 server_date = fields.Datetime.from_string(change['metadata'].get('serverDate'))
383 local_date = fields.Datetime.from_string(local_change['metadata'].get('serverDate'))
384
385 if server_date > local_date:
386 _logger.warning("Preparation changes were outdated, probably linked to a synching issue.")
387 vals['last_order_preparation_change'] = record.last_order_preparation_change
388 else:
389 local_change['metadata']['serverDate'] = fields.Datetime.now().strftime('%Y-%m-%d %H:%M:%S')
390 vals['last_order_preparation_change'] = json.dumps(local_change)
391
392 @api.depends('account_move')
393 def _compute_invoice_status(self):
394 for order in self:
395 order.invoice_status = 'invoiced' if len(order.account_move) else 'to_invoice'
396
397 @api.depends('session_id')
398 def _compute_order_config_id(self):
399 for order in self:
400 if order.session_id:
401 order.config_id = order.session_id.config_id
402
403 @api.depends('lines.refund_orderline_ids', 'lines.refunded_orderline_id')
404 def _compute_refund_related_fields(self):
405 for order in self:
406 order.refund_orders_count = len(order.mapped('lines.refund_orderline_ids.order_id'))
407 order.refunded_order_id = next(iter(order.lines.refunded_orderline_id.order_id), False)
408
409 @api.depends('lines.refunded_qty', 'lines.qty')
410 def _compute_has_refundable_lines(self):
411 digits = self.env['decimal.precision'].precision_get('Product Unit')
412 for order in self:
413 order.has_refundable_lines = any([float_compare(line.qty, line.refunded_qty, digits) > 0 for line in order.lines])
414
415 @api.depends('account_move')
416 def _compute_is_invoiced(self):
417 for order in self:
418 order.is_invoiced = bool(order.account_move)
419
420 @api.depends('picking_ids', 'picking_ids.state')
421 def _compute_picking_count(self):
422 for order in self:
423 order.picking_count = len(order.picking_ids)
424 order.failed_pickings = bool(order.picking_ids.filtered(lambda p: p.state != 'done'))
425
426 @api.depends('date_order', 'company_id', 'currency_id', 'company_id.currency_id')
427 def _compute_currency_rate(self):
428 for order in self:
429 order.currency_rate = self.env['res.currency']._get_conversion_rate(order.company_id.currency_id, order.currency_id, order.company_id, order.date_order.date())
430
431 @api.depends('lines.is_total_cost_computed')
432 def _compute_is_total_cost_computed(self):
433 for order in self:
434 order.is_total_cost_computed = not False in order.lines.mapped('is_total_cost_computed')
435
436 @api.depends('partner_id')
437 def _compute_contact_details(self):
438 for order in self:
439 order.email = order.partner_id.email or ""
440 order.mobile = order._phone_format(number=order.partner_id.phone or "",
441 country=order.partner_id.country_id)
442
443 def _compute_total_cost_in_real_time(self):
444 """
445 Compute the total cost of the order when it's processed by the server. It will compute the total cost of all the lines
446 if it's possible. If a margin of one of the order's lines cannot be computed (because of session_id.update_stock_at_closing),
447 then the margin of said order is not computed (it will be computed when closing the session).
448 """
449 for order in self:
450 lines = order.lines
451 if not order._should_create_picking_real_time():
452 storable_fifo_avco_lines = lines.filtered(lambda l: l._is_product_storable_fifo_avco())
453 lines -= storable_fifo_avco_lines
454 stock_moves = order.picking_ids.move_ids
455 lines._compute_total_cost(stock_moves)
456
457 def _compute_total_cost_at_session_closing(self, stock_moves):
458 """
459 Compute the margin at the end of the session. This method should be called to compute the remaining lines margin
460 containing a storable product with a fifo/avco cost method and then compute the order margin
461 """
462 for order in self:
463 storable_fifo_avco_lines = order.lines.filtered(lambda l: l._is_product_storable_fifo_avco())
464 storable_fifo_avco_lines._compute_total_cost(stock_moves)
465
466 @api.depends('lines.margin', 'is_total_cost_computed')
467 def _compute_margin(self):
468 for order in self:
469 sign = -1 if order.is_refund else 1
470 if order.is_total_cost_computed:
471 order.margin = sum(order.lines.mapped('margin'))
472 amount_untaxed = order.currency_id.round(sum(line.price_subtotal for line in order.lines)) * sign
473 order.margin_percent = not float_is_zero(amount_untaxed, precision_rounding=order.currency_id.rounding) \
474 and order.margin / amount_untaxed \
475 or 0
476 else:
477 order.margin = 0
478 order.margin_percent = 0
479
480 @api.onchange('payment_ids', 'lines')
481 def _onchange_amount_all(self):
482 self._compute_prices()
483
484 def _compute_prices(self):
485 AccountTax = self.env['account.tax']
486 for order in self:
487 if not order.currency_id:
488 raise UserError(_("You can't: create a pos order from the backend interface, or unset the pricelist, or create a pos.order in a python test with Form tool, or edit the form view in studio if no PoS order exist"))
489 order.amount_paid = sum(payment.amount for payment in order.payment_ids)
490 order.amount_return = -sum(payment.amount < 0 and payment.amount or 0 for payment in order.payment_ids)
491
492 base_lines = order.lines._prepare_tax_base_line_values()
493 AccountTax._add_tax_details_in_base_lines(base_lines, order.company_id)
494 AccountTax._round_base_lines_tax_details(base_lines, order.company_id)
495
496 cash_rounding = None
497 if (
498 order.config_id.cash_rounding
499 and not order.config_id.only_round_cash_method
500 and order.config_id.rounding_method
501 ):
502 cash_rounding = order.config_id.rounding_method
503
504 tax_totals = AccountTax._get_tax_totals_summary(
505 base_lines=base_lines,
506 currency=order.currency_id,
507 company=order.company_id,
508 cash_rounding=cash_rounding,
509 )
510 refund_factor = -1 if (order.amount_total < 0.0) else 1
511 order.amount_tax = refund_factor * tax_totals['tax_amount_currency']
512 order.amount_total = refund_factor * tax_totals['total_amount_currency']
513 order.amount_difference = order.amount_paid - order.amount_total
514
515 @api.depends('lines.is_edited', 'has_deleted_line')
516 def _compute_is_edited(self):
517 for order in self:
518 order.is_edited = any(order.lines.mapped('is_edited')) or order.has_deleted_line
519
520 @api.onchange('partner_id')
521 def _onchange_partner_id(self):
522 if self.partner_id:
523 self.pricelist_id = self.partner_id.property_product_pricelist.id
524
525 @api.ondelete(at_uninstall=False)
526 def _unlink_except_draft_or_cancel(self):
527 if any(pos_order.state not in ['draft', 'cancel'] for pos_order in self):
528 raise UserError(_('In order to delete a sale, it must be new or cancelled.'))
529
530 @api.model_create_multi
531 def create(self, vals_list):
532 for vals in vals_list:
533 session = self.env['pos.session'].browse(vals['session_id'])
534 vals = self._complete_values_from_session(session, vals)
535 return super().create(vals_list)
536
537 def _update_sequence_number(self, session, values):
538 # Some localization needs orders to have a sequence number
539 values['sequence_number'] = (
540 session.config_id.order_seq_id
541 ._next()
542 .removeprefix(session.config_id.order_seq_id.prefix or '')
543 .removesuffix(session.config_id.order_seq_id.suffix or '')
544 )
545
546 @api.model
547 def _complete_values_from_session(self, session, values):
548 values.setdefault('pricelist_id', session.config_id.pricelist_id.id)
549 values.setdefault('fiscal_position_id', session.config_id.default_fiscal_position_id.id)
550 values.setdefault('company_id', session.config_id.company_id.id)
551
552 if not values.get('pos_reference'):
553 reference, tracking_number = session.config_id._get_next_order_refs()
554 values['pos_reference'] = reference
555 values['tracking_number'] = tracking_number
556
557 if not values.get('sequence_number'):
558 self._update_sequence_number(session, values)
559
560 return values
561
562 def write(self, vals):
563 for order in self:
564 if vals.get('state') and vals['state'] == 'paid' and order.name == '/':
565 session = self.env['pos.session'].browse(vals['session_id']) if not self.session_id and vals.get('session_id') else False
566 vals['name'] = self._compute_order_name(session)
567 if vals.get('mobile'):
568 vals['mobile'] = order._phone_format(number=vals.get('mobile'),
569 country=order.partner_id.country_id or self.env.company.country_id)
570 if vals.get('has_deleted_line') is not None and self.has_deleted_line:
571 del vals['has_deleted_line']
572 allowed_vals = ['paid', 'done', 'invoiced']
573 if vals.get('state') and vals['state'] not in allowed_vals and order.state in allowed_vals:
574 raise UserError(_('This order has already been paid. You cannot set it back to draft or edit it.'))
575
576 list_line = self._create_pm_change_log(vals)
577 res = super().write(vals)
578 for order in self:
579 if vals.get('payment_ids'):
580 order._compute_prices()
581 totally_paid_or_more = order.currency_id.compare_amounts(order.amount_paid, order.amount_total)
582 if totally_paid_or_more < 0 and order.state in ['paid', 'done']:
583 raise UserError(_('The paid amount is different from the total amount of the order.'))
584 elif totally_paid_or_more > 0 and order.state == 'paid':
585 list_line.append(_("Warning, the paid amount is higher than the total amount. (Difference: %s)", formatLang(self.env, order.amount_paid - order.amount_total, currency_obj=order.currency_id)))
586 if order.nb_print > 0 and any(command[0] in [0, 1] and command[2].get('payment_status') and command[2]['payment_status'] != 'cancelled' for command in vals.get('payment_ids')):
587 raise UserError(_('You cannot change the payment of a printed order.'))
588
589 if len(list_line) > 0:
590 body = _("Payment changes:")
591 body += self._markup_list_message(list_line)
592 for order in self:
593 if vals.get('payment_ids'):
594 order.message_post(body=body)
595
596 return res
597
598 def _create_pm_change_log(self, vals):
599 if not vals.get('payment_ids'):
600 return []
601
602 message_list = []
603 new_pms = vals.get('payment_ids', [])
604 for new_pm in new_pms:
605 orm_command = new_pm[0]
606
607 if orm_command == 0:
608 payment_method_id = self.env['pos.payment.method'].browse(new_pm[2].get('payment_method_id'))
609 amount = formatLang(self.env, new_pm[2].get('amount'), currency_obj=self.currency_id)
610 message_list.append(_("Added %(payment_method)s with %(amount)s",
611 payment_method=payment_method_id.name,
612 amount=amount))
613 elif orm_command == 1:
614 pm_id = self.env['pos.payment'].browse(new_pm[1])
615 old_pm = pm_id.payment_method_id.name
616 old_amount = formatLang(self.env, pm_id.amount, currency_obj=pm_id.currency_id)
617 new_amount = False
618 new_payment_method = False
619
620 if new_pm[2].get('payment_method_id'):
621 new_payment_method = self.env['pos.payment.method'].browse(new_pm[2].get('payment_method_id'))
622 if new_pm[2].get('amount'):
623 new_amount = formatLang(self.env, new_pm[2].get('amount'), currency_obj=pm_id.currency_id)
624
625 if new_payment_method and new_amount:
626 message_list.append(_("%(old_pm)s changed to %(new_pm)s and from %(old_amount)s to %(new_amount)s",
627 old_pm=old_pm,
628 new_pm=new_payment_method.name,
629 old_amount=old_amount,
630 new_amount=new_amount))
631 elif new_payment_method:
632 message_list.append(_("%(old_pm)s changed to %(new_pm)s for %(old_amount)s",
633 old_pm=old_pm,
634 new_pm=new_payment_method.name,
635 old_amount=old_amount))
636 elif new_amount:
637 message_list.append(_("Amount for %(old_pm)s changed from %(old_amount)s to %(new_amount)s",
638 old_amount=old_amount,
639 new_amount=new_amount,
640 old_pm=old_pm))
641 elif orm_command == 2:
642 pm_id = self.env['pos.payment'].browse(new_pm[1])
643 amount = formatLang(self.env, pm_id.amount, currency_obj=pm_id.currency_id)
644 message_list.append(_("Removed %(payment_method)s with %(amount)s",
645 payment_method=pm_id.payment_method_id.name,
646 amount=amount))
647
648 return message_list
649
650 def _markup_list_message(self, message):
651 body = Markup("<ul>")
652 for line in message:
653 body += Markup("<li>")
654 body += line
655 body += Markup("</li>")
656 body += Markup("</ul>")
657 return body
658
659 def _compute_order_name(self, session=None):
660 session = session or self.session_id
661 if self.refunded_order_id.exists():
662 return _('%(refunded_order)s REFUND', refunded_order=self.refunded_order_id.name)
663 else:
664 last_reference_part = self.get_reference_last_part()
665 prefix = session.config_id.order_seq_id.prefix or session.config_id.name
666 suffix = f" - {session.config_id.order_seq_id.suffix}" if session.config_id.order_seq_id.suffix else ''
667 return f"{prefix} - {last_reference_part}{suffix}"
668
669 def get_reference_last_part(self):
670 return self.pos_reference.split('-')[-1]
671
672 def action_stock_picking(self):
673 self.ensure_one()
674 action = self.env['ir.actions.act_window']._for_xml_id('stock.action_picking_tree_ready')
675 action['display_name'] = _('Pickings')
676 action['context'] = {}
677 action['domain'] = [('id', 'in', self.picking_ids.ids)]
678 return action
679
680 def action_view_invoice(self):
681 invoices = self.account_move
682 if (len(invoices) == 1):
683 return {
684 'name': _('Customer Invoice'),
685 'view_mode': 'form',
686 'view_id': self.env.ref('account.view_move_form').id,
687 'res_model': 'account.move',
688 'context': "{'move_type':'out_invoice'}",
689 'type': 'ir.actions.act_window',
690 'res_id': self.account_move.id,
691 }
692 else:
693 return {
694 'name': _('Customer Invoices'),
695 'view_mode': 'list,form',
696 'res_model': 'account.move',
697 'type': 'ir.actions.act_window',
698 'domain': [('id', 'in', invoices.ids)],
699 }
700
701 def action_create_invoices(self):
702 return {
703 'name': _('Create Invoice(s)'),
704 'view_mode': 'form',
705 'view_id': self.env.ref('point_of_sale.view_pos_make_invoice').id,
706 'res_model': 'pos.make.invoice',
707 'target': 'new',
708 'type': 'ir.actions.act_window',
709 'context': {'dialog_size': 'medium'}
710 }
711
712 # the refunded order is the order from which the items were refunded in this order
713 def action_view_refunded_order(self):
714 return {
715 'name': _('Refunded Order'),
716 'view_mode': 'form',
717 'view_id': self.env.ref('point_of_sale.view_pos_pos_form').id,
718 'res_model': 'pos.order',
719 'type': 'ir.actions.act_window',
720 'res_id': self.refunded_order_id.id,
721 }
722
723 # the refund orders are the orders where the items from this order were refunded
724 def action_view_refund_orders(self):
725 return {
726 'name': _('Refund Orders'),
727 'view_mode': 'list,form',
728 'res_model': 'pos.order',
729 'type': 'ir.actions.act_window',
730 'domain': [('id', 'in', self.mapped('lines.refund_orderline_ids.order_id').ids)],
731 }
732
733 def _is_pos_order_paid(self):
734 amount_total = self.amount_total
735 # If we are checking if a refund was paid and if it was a total refund, we take into account the amount paid on
736 # the original order. For a pertial refund, we take into account the value of the items returned.
737 if float_is_zero(self.refunded_order_id.amount_total + amount_total, precision_rounding=self.currency_id.rounding):
738 amount_total = -self.refunded_order_id.amount_paid
739 return float_is_zero(self._get_rounded_amount(amount_total) - self.amount_paid, precision_rounding=self.currency_id.rounding)
740
741 def _get_rounded_amount(self, amount, force_round=False):
742 # TODO: add support for mix of cash and non-cash payments when both cash_rounding and only_round_cash_method are True
743 if self.config_id.cash_rounding \
744 and (force_round or (not self.config_id.only_round_cash_method \
745 or any(p.payment_method_id.is_cash_count for p in self.payment_ids))):
746 amount = float_round(amount, precision_rounding=self.config_id.rounding_method.rounding, rounding_method=self.config_id.rounding_method.rounding_method)
747 currency = self.currency_id
748 return currency.round(amount) if currency else amount
749
750 def _get_partner_bank_id(self):
751 bank_partner_id = False
752 amount_total = sum(order.amount_total for order in self)
753 if amount_total <= 0 and self.partner_id.bank_ids:
754 bank_partner_id = self.partner_id.bank_ids[0].id
755 elif amount_total >= 0 and self.payment_ids and self.payment_ids[0].payment_method_id.journal_id.bank_account_id:
756 bank_partner_id = self.payment_ids[0].payment_method_id.journal_id.bank_account_id.id
757 elif amount_total >= 0 and self.company_id.partner_id.bank_ids:
758 bank_partner_id = self.company_id.partner_id.bank_ids[0].id
759 return bank_partner_id
760
761 def _create_invoice(self, move_vals):
762 AccountMove = self.env['account.move']
763
764 invoice = AccountMove.sudo()\
765 .with_company(self.company_id)\
766 .with_context(default_move_type=move_vals['move_type'], linked_to_pos=True)\
767 .create(move_vals)
768 currency = self.currency_id
769 amount_total = sum(order.amount_total for order in self)
770 payment_total = sum(order.amount_paid for order in self)
771
772 if self.config_id.cash_rounding:
773 line_ids_commands = []
774 rate = invoice.invoice_currency_rate
775 sign = invoice.direction_sign
776 amount_paid = (-1 if amount_total < 0.0 else 1) * payment_total
777 difference_currency = sign * (amount_paid - invoice.amount_total)
778 difference_balance = invoice.company_currency_id.round(difference_currency / rate) if rate else 0.0
779 if not currency.is_zero(difference_currency):
780 rounding_line = invoice.line_ids.filtered(lambda line: line.display_type == 'rounding' and not line.tax_line_id)
781 if rounding_line:
782 line_ids_commands.append(Command.update(rounding_line.id, {
783 'amount_currency': rounding_line.amount_currency + difference_currency,
784 'balance': rounding_line.balance + difference_balance,
785 }))
786 else:
787 if difference_currency > 0.0:
788 account = invoice.invoice_cash_rounding_id.loss_account_id
789 else:
790 account = invoice.invoice_cash_rounding_id.profit_account_id
791 line_ids_commands.append(Command.create({
792 'name': invoice.invoice_cash_rounding_id.name,
793 'amount_currency': difference_currency,
794 'balance': difference_balance,
795 'currency_id': invoice.currency_id.id,
796 'display_type': 'rounding',
797 'account_id': account.id,
798 }))
799 existing_terms_line = invoice.line_ids\
800 .filtered(lambda line: line.display_type == 'payment_term')\
801 .sorted(lambda line: -abs(line.amount_currency))[:1]
802 line_ids_commands.append(Command.update(existing_terms_line.id, {
803 'amount_currency': existing_terms_line.amount_currency - difference_currency,
804 'balance': existing_terms_line.balance - difference_balance,
805 }))
806 with AccountMove._check_balanced({'records': invoice}):
807 invoice.with_context(skip_invoice_sync=True).line_ids = line_ids_commands
808 body = _("This invoice has been created from the point of sale session:%s",
809 Markup().join(Markup("%s ") % order._get_html_link() for order in self)
810 )
811 invoice.message_post(body=body)
812 return invoice
813
814 def action_pos_order_paid(self):
815 self.ensure_one()
816
817 # TODO: add support for mix of cash and non-cash payments when both cash_rounding and only_round_cash_method are True
818 if not self.config_id.cash_rounding \
819 or self.config_id.only_round_cash_method \
820 and not any(p.payment_method_id.is_cash_count for p in self.payment_ids):
821 total = self.amount_total
822 else:
823 total = float_round(self.amount_total, precision_rounding=self.config_id.rounding_method.rounding, rounding_method=self.config_id.rounding_method.rounding_method)
824
825 isPaid = float_is_zero(total - self.amount_paid, precision_rounding=self.currency_id.rounding)
826
827 if not isPaid and not self.config_id.cash_rounding:
828 raise UserError(_("Order %s is not fully paid.", self.name))
829 elif not isPaid and self.config_id.cash_rounding:
830 currency = self.currency_id
831 if self.config_id.rounding_method.rounding_method == "HALF-UP":
832 maxDiff = currency.round(self.config_id.rounding_method.rounding / 2)
833 else:
834 maxDiff = currency.round(self.config_id.rounding_method.rounding)
835
836 diff = currency.round(self.amount_total - self.amount_paid)
837 if not abs(diff) <= maxDiff:
838 raise UserError(_("Order %s is not fully paid.", self.name))
839
840 self.write({'state': 'paid'})
841
842 return True
843
844 def _prepare_invoice_vals(self):
845 """We have orders filtered by company > config > partners > fiscal_positions so it won't make any issue
846 when we access user, partner, bank or similar directly.
847 """
848 timezone = self.env.tz
849 invoice_date = fields.Datetime.now()
850 is_single_order = len(self) == 1
851
852 if is_single_order and self.session_id.state != 'closed':
853 invoice_date = self.date_order
854
855 pos_refunded_invoice_ids = []
856 for orderline in self.lines:
857 if orderline.refunded_orderline_id and orderline.refunded_orderline_id.order_id.account_move:
858 pos_refunded_invoice_ids.append(orderline.refunded_orderline_id.order_id.account_move.id)
859
860 fiscal_position = self.fiscal_position_id
861 pos_config = self.config_id
862 rounding_method = pos_config.rounding_method
863 move_type = 'out_invoice' if not any(order.is_refund for order in self) else 'out_refund'
864 invoice_payment_term_id = (
865 self.partner_id.property_payment_term_id.id
866 if self.partner_id.property_payment_term_id and any(p.payment_method_id.type == 'pay_later' for p in self.payment_ids)
867 else False
868 )
869
870 vals = {
871 'invoice_origin': ', '.join(ref or '' for ref in self.mapped('pos_reference')),
872 'pos_refunded_invoice_ids': pos_refunded_invoice_ids,
873 'pos_order_ids': self.ids,
874 'ref': self.name if is_single_order else False,
875 'journal_id': self.config_id.invoice_journal_id.id,
876 'move_type': move_type,
877 'partner_id': self.partner_id.address_get(['invoice'])['invoice'],
878 'partner_shipping_id': self.partner_id.address_get(['delivery'])['delivery'],
879 'partner_bank_id': self._get_partner_bank_id(),
880 'currency_id': self.currency_id.id,
881 'invoice_date': invoice_date.astimezone(timezone).date(),
882 'invoice_user_id': self.user_id.id,
883 'fiscal_position_id': fiscal_position.id,
884 'invoice_line_ids': self._prepare_invoice_lines(move_type),
885 'invoice_payment_term_id': invoice_payment_term_id,
886 'invoice_cash_rounding_id': rounding_method.id,
887 }
888 if is_single_order and self.refunded_order_id.account_move:
889 vals['ref'] = _('Reversal of: %s', self.refunded_order_id.account_move.name)
890 vals['reversed_entry_id'] = self.refunded_order_id.account_move.id
891
892 if any(order.floating_order_name for order in self):
893 vals.update({'narration': ', '.join(self.filtered('floating_order_name').mapped('floating_order_name'))})
894
895 return vals
896
897 def _prepare_product_aml_dict(self, base_line_vals, update_base_line_vals, rate, sign):
898 amount_currency = update_base_line_vals['amount_currency']
899 balance = self.company_id.currency_id.round(amount_currency * rate)
900 order_line = base_line_vals['record']
901 return {
902 'name': order_line.full_product_name,
903 'product_id': order_line.product_id.id,
904 'quantity': order_line.qty * sign,
905 'account_id': base_line_vals['account_id'].id,
906 'partner_id': base_line_vals['partner_id'].id,
907 'currency_id': base_line_vals['currency_id'].id,
908 'tax_ids': [(6, 0, base_line_vals['tax_ids'].ids)],
909 'tax_tag_ids': update_base_line_vals['tax_tag_ids'],
910 'amount_currency': amount_currency,
911 'balance': balance,
912 'no_followup': False,
913 }
914
915 def _prepare_aml_values_list_per_nature(self):
916 AccountTax = self.env['account.tax']
917 sign = 1 if self.amount_total < 0 else -1
918 commercial_partner = self.partner_id.commercial_partner_id
919 company_currency = self.company_id.currency_id
920 rate = self.currency_id._get_conversion_rate(self.currency_id, company_currency, self.company_id, self.date_order)
921
922 # Concert each order line to a dictionary containing business values. Also, prepare for taxes computation.
923 base_lines = self._prepare_tax_base_line_values()
924 AccountTax._add_tax_details_in_base_lines(base_lines, self.company_id)
925 AccountTax._round_base_lines_tax_details(base_lines, self.company_id)
926 AccountTax._add_accounting_data_in_base_lines_tax_details(base_lines, self.company_id)
927 tax_results = AccountTax._prepare_tax_lines(base_lines, self.company_id)
928
929 total_balance = 0.0
930 total_amount_currency = 0.0
931 aml_vals_list_per_nature = defaultdict(list)
932
933 # Create the tax lines
934 for tax_line in tax_results['tax_lines_to_add']:
935 aml_vals_list_per_nature['tax'].append({
936 **tax_line,
937 'display_type': 'tax',
938 })
939 total_amount_currency += tax_line['amount_currency']
940 total_balance += tax_line['balance']
941
942 # Create the aml values for order lines.
943 for base_line_vals, update_base_line_vals in tax_results['base_lines_to_update']:
944 product_dict = self._prepare_product_aml_dict(base_line_vals, update_base_line_vals, rate, sign)
945 aml_vals_list_per_nature['product'].append(product_dict)
946 total_amount_currency += product_dict['amount_currency']
947 total_balance += product_dict['balance']
948
949 # Cash rounding.
950 cash_rounding = self.config_id.rounding_method
951 if self.config_id.cash_rounding and cash_rounding and (not self.config_id.only_round_cash_method or any(p.payment_method_id.is_cash_count for p in self.payment_ids)):
952 if self.config_id.only_round_cash_method and any(not p.payment_method_id.is_cash_count for p in self.payment_ids):
953 # If only_round_cash_method is True, and there are non-cash payments, cash rounding must be computed
954 # based on the total amount of the order, and total payment amount.
955 total_payment_amount = self.currency_id.round(sum(p.amount for p in self.payment_ids))
956 amount_currency = sign * self.currency_id.round(self.currency_id.round(total_amount_currency) + total_payment_amount)
957 else:
958 amount_currency = cash_rounding.compute_difference(self.currency_id, total_amount_currency)
959 if not self.currency_id.is_zero(amount_currency):
960 balance = company_currency.round(amount_currency * rate)
961
962 if cash_rounding.strategy == 'biggest_tax':
963 biggest_tax_aml_vals = None
964 for aml_vals in aml_vals_list_per_nature['tax']:
965 if not biggest_tax_aml_vals or float_compare(-sign * aml_vals['amount_currency'], -sign * biggest_tax_aml_vals['amount_currency'], precision_rounding=self.currency_id.rounding) > 0:
966 biggest_tax_aml_vals = aml_vals
967 if biggest_tax_aml_vals:
968 biggest_tax_aml_vals['amount_currency'] += amount_currency
969 biggest_tax_aml_vals['balance'] += balance
970 elif cash_rounding.strategy == 'add_invoice_line':
971 if -sign * amount_currency > 0.0 and cash_rounding.loss_account_id:
972 account_id = cash_rounding.loss_account_id.id
973 else:
974 account_id = cash_rounding.profit_account_id.id
975 aml_vals_list_per_nature['cash_rounding'].append({
976 'name': cash_rounding.name,
977 'account_id': account_id,
978 'partner_id': commercial_partner.id,
979 'currency_id': self.currency_id.id,
980 'amount_currency': amount_currency,
981 'balance': balance,
982 'display_type': 'rounding',
983 })
984 # Stock.
985 if self.company_id.inventory_valuation == 'real_time' and self.picking_ids.ids:
986 stock_moves = self.env['stock.move'].sudo().search([
987 ('picking_id', 'in', self.picking_ids.ids),
988 ('product_id.valuation', '=', 'real_time'),
989 ])
990 for stock_move in stock_moves:
991 product_accounts = stock_move.product_id._get_product_accounts()
992 expense_account = product_accounts['expense']
993 stock_account = product_accounts['stock_valuation']
994 balance = -sum(stock_move.mapped('value'))
995 aml_vals_list_per_nature['stock'].append({
996 'name': _("Stock variation for %s", stock_move.product_id.name),
997 'account_id': expense_account.id,
998 'partner_id': commercial_partner.id,
999 'currency_id': self.company_id.currency_id.id,
1000 'amount_currency': balance,
1001 'balance': balance,
1002 })
1003 aml_vals_list_per_nature['stock'].append({
1004 'name': _("Stock variation for %s", stock_move.product_id.name),
1005 'account_id': stock_account.id,
1006 'partner_id': commercial_partner.id,
1007 'currency_id': self.company_id.currency_id.id,
1008 'amount_currency': -balance,
1009 'balance': -balance,
1010 })
1011
1012 # sort self.payment_ids by is_split_transaction:
1013 for payment_id in self.payment_ids:
1014 is_split_transaction = payment_id.payment_method_id.split_transactions
1015 if is_split_transaction:
1016 reversed_move_receivable_account_id = self.partner_id.property_account_receivable_id
1017 else:
1018 reversed_move_receivable_account_id = payment_id.payment_method_id.receivable_account_id or self.company_id.account_default_pos_receivable_account_id
1019
1020 aml_vals_entry_found = [aml_entry for aml_entry in aml_vals_list_per_nature['payment_terms']
1021 if aml_entry['account_id'] == reversed_move_receivable_account_id.id
1022 and not aml_entry['partner_id']]
1023
1024 if aml_vals_entry_found and not is_split_transaction:
1025 aml_vals_entry_found[0]['amount_currency'] += self.session_id._amount_converter(payment_id.amount, self.date_order, False)
1026 aml_vals_entry_found[0]['balance'] += payment_id.amount
1027 else:
1028 aml_vals_list_per_nature['payment_terms'].append({
1029 'partner_id': commercial_partner.id if is_split_transaction else False,
1030 'name': f"{reversed_move_receivable_account_id.code} {reversed_move_receivable_account_id.code}",
1031 'account_id': reversed_move_receivable_account_id.id,
1032 'currency_id': self.currency_id.id,
1033 'amount_currency': payment_id.amount,
1034 'balance': self.session_id._amount_converter(payment_id.amount, self.date_order, False),
1035 'display_type': 'payment_term',
1036 })
1037
1038 return aml_vals_list_per_nature
1039
1040 def _create_misc_reversal_move(self, payment_moves):
1041 """ Create a misc move to reverse POS orders and "remove" it from the POS closing entry.
1042 This is done by taking data from the orders and using it to somewhat replicate the resulting entry in orders to
1043 reverse partially the movements done in the POS closing entry.
1044 """
1045 self.ensure_one()
1046 aml_values_list_per_nature = self._prepare_aml_values_list_per_nature()
1047 move_lines = []
1048 for aml_values_list in aml_values_list_per_nature.values():
1049 for aml_values in aml_values_list:
1050 aml_values['balance'] = -aml_values['balance']
1051 aml_values['amount_currency'] = -aml_values['amount_currency']
1052 move_lines.append(aml_values)
1053
1054 # Make a move with all the lines.
1055 reversal_entry = self.env['account.move'].with_context(
1056 default_journal_id=self.config_id.journal_id.id,
1057 skip_invoice_sync=True,
1058 skip_invoice_line_sync=True,
1059 ).create({
1060 'journal_id': self.config_id.journal_id.id,
1061 'date': fields.Date.context_today(self),
1062 'ref': _('Reversal of POS closing entry %(entry)s for order %(order)s from session %(session)s', entry=self.session_move_id.name, order=self.name, session=self.session_id.name),
1063 'line_ids': [(0, 0, aml_value) for aml_value in move_lines],
1064 'reversed_pos_order_id': self.id
1065 })
1066 reversal_entry.action_post()
1067
1068 pos_account_receivable = self.company_id.account_default_pos_receivable_account_id
1069 account_receivable = self.payment_ids.payment_method_id.receivable_account_id
1070 reversal_entry_receivable = reversal_entry.line_ids.filtered(lambda l: l.account_id in (pos_account_receivable + account_receivable))
1071 payment_receivable = payment_moves.line_ids.filtered(lambda l: l.account_id in (pos_account_receivable + account_receivable))
1072 lines_to_reconcile = defaultdict(lambda: self.env['account.move.line'])
1073 for line in (reversal_entry_receivable | payment_receivable):
1074 lines_to_reconcile[line.account_id] |= line
1075 for line in lines_to_reconcile.values():
1076 line.filtered(lambda l: not l.reconciled).reconcile()
1077
1078 def action_pos_order_invoice(self):
1079 self.ensure_one()
1080 if not (move := self.account_move):
1081 self.write({'to_invoice': True})
1082 if self.company_id.anglo_saxon_accounting and self.session_id.update_stock_at_closing and self.session_id.state != 'closed':
1083 self._create_order_picking()
1084 move = self._generate_pos_order_invoice()
1085 return {
1086 'name': _('Customer Invoice'),
1087 'view_mode': 'form',
1088 'view_id': self.env.ref('account.view_move_form').id,
1089 'res_model': 'account.move',
1090 'context': "{'move_type':'out_invoice'}",
1091 'type': 'ir.actions.act_window',
1092 'target': 'current',
1093 'res_id': move.id,
1094 }
1095
1096 def _get_invoice_post_context(self):
1097 return {"skip_invoice_sync": True}
1098
1099 def _generate_pos_order_invoice(self):
1100 if not self.env['res.company']._with_locked_records(self, allow_raising=False):
1101 raise UserError(_("Some orders are already being invoiced. Please try again later."))
1102 self.state = 'done'
1103
1104 company = self.company_id
1105 invoice_vals = self._prepare_invoice_vals()
1106 invoice = self._create_invoice(invoice_vals)
1107 invoice.sudo().with_company(company).with_context(**self._get_invoice_post_context())._post()
1108
1109 # invoice payments
1110 payment_moves_from_closed_sessions = {}
1111 all_payment_moves = self.env['account.move']
1112 for session, orders in self.grouped('session_id').items():
1113 is_session_closed = session.state == 'closed'
1114 for order in orders:
1115 order_payments = order.payment_ids.sudo().with_company(company)
1116 payment_moves = order_payments._create_payment_moves(is_session_closed)
1117 all_payment_moves |= payment_moves
1118 if is_session_closed:
1119 payment_moves_from_closed_sessions[order] = payment_moves
1120
1121 self._reconcile_invoice_payments(invoice, all_payment_moves)
1122
1123 # reverse payment moves from closed sessions
1124 for order, payment_moves in payment_moves_from_closed_sessions.items():
1125 order._create_misc_reversal_move(payment_moves)
1126
1127 if self.env.context.get('generate_pdf', True):
1128 invoice.with_context(skip_invoice_sync=True)._generate_and_send()
1129
1130 return invoice
1131
1132 def _reconcile_invoice_payments(self, invoice, payment_moves):
1133 receivable_account = self.env["res.partner"]._find_accounting_partner(invoice.partner_id).with_company(self.company_id).property_account_receivable_id
1134 if not receivable_account.reconcile:
1135 return
1136 payment_receivable_lines = payment_moves.pos_payment_ids._get_receivable_lines_for_invoice_reconciliation(receivable_account)
1137 invoice_receivable_lines = invoice.line_ids.filtered(lambda line: line.account_id == receivable_account and not line.reconciled)
1138 (payment_receivable_lines | invoice_receivable_lines).sudo().with_company(invoice.company_id).reconcile()
1139
1140 def action_pos_order_cancel(self):
1141 if self.env.context.get('active_ids'):
1142 orders = self.browse(self.env.context.get('active_ids'))
1143 order_is_in_futur = any(order.preset_time and order.preset_time.date() > fields.Date.today() for order in orders)
1144 if order_is_in_futur:
1145 raise UserError(_('The order delivery / pickup date is in the future. You cannot cancel it.'))
1146
1147 today_orders = self.filtered(lambda order: order.state == 'draft' and (not order.preset_time or order.preset_time.date() <= fields.Date.today()))
1148 next_days_orders = self.filtered(lambda order: order.preset_time and order.preset_time.date() > fields.Date.today() and order.state == 'draft')
1149 next_days_orders.session_id = False
1150 today_orders.write({'state': 'cancel'})
1151 for config in today_orders.config_id:
1152 config.notify_synchronisation(config.current_session_id.id, self.env.context.get('device_identifier', 0))
1153 return {
1154 'pos.order': self._load_pos_data_read(today_orders, self.config_id)
1155 }
1156
1157 def _get_open_order(self, order):
1158 return self.env["pos.order"].search([('uuid', '=', order.get('uuid'))], limit=1, order='id desc')
1159
1160 @staticmethod
1161 def _get_order_log_representation(order):
1162 return dict((k, order.get(k)) for k in ("name", "uuid"))
1163
1164 @api.model
1165 def sync_from_ui(self, orders):
1166 """ Create and update Orders from the frontend PoS application.
1167
1168 Create new orders and update orders that are in draft status. If an order already exists with a status
1169 different from 'draft' it will be discarded, otherwise it will be saved to the database. If saved with
1170 'draft' status the order can be overwritten later by this function.
1171
1172 :param orders: dictionary with the orders to be created.
1173 :type orders: dict.
1174 :returns: list of db-ids for the created and updated orders.
1175 :rtype: list
1176 """
1177 sync_token = randrange(100_000_000) # Use to differentiate 2 parallels calls to this function in the logs
1178 _logger.info("PoS synchronisation #%d started for PoS orders references: %s", sync_token, [self._get_order_log_representation(order) for order in orders])
1179 order_ids = []
1180
1181 for order in orders:
1182 order_log_name = self._get_order_log_representation(order)
1183 _logger.debug("PoS synchronisation #%d processing order %s order full data: %s", sync_token, order_log_name, pformat(order))
1184
1185 refunded_orders = self._get_refunded_orders(order)
1186 if len(refunded_orders) > 1:
1187 raise ValidationError(_('You can only refund products from the same order.'))
1188 elif len(refunded_orders) == 1:
1189 order_ids.append(refunded_orders[0].id)
1190
1191 existing_order = self._get_open_order(order)
1192 if existing_order and existing_order.state == 'draft':
1193 existing_order._ensure_to_keep_last_preparation_change(order)
1194 order_ids.append(self._process_order(order, existing_order))
1195 _logger.info("PoS synchronisation #%d order %s updated pos.order #%d", sync_token, order_log_name, order_ids[-1])
1196 elif not existing_order:
1197 order_ids.append(self._process_order(order, False))
1198 _logger.info("PoS synchronisation #%d order %s created pos.order #%d", sync_token, order_log_name, order_ids[-1])
1199 else:
1200 # In theory, this situation is unintended
1201 # In practice it can happen when "Tip later" option is used
1202 existing_order._ensure_to_keep_last_preparation_change(order)
1203 order_ids.append(existing_order.id)
1204 _logger.info("PoS synchronisation #%d order %s sync ignored for existing PoS order %s (state: %s)", sync_token, order_log_name, existing_order, existing_order.state)
1205
1206 # Sometime pos_orders_ids can be empty.
1207 pos_order_ids = self.env['pos.order'].browse(order_ids)
1208 config = pos_order_ids.config_id[0] if pos_order_ids else False
1209
1210 for order in pos_order_ids:
1211 order._ensure_access_token()
1212 if not self.env.context.get('preparation'):
1213 order.config_id.notify_synchronisation(order.config_id.current_session_id.id, self.env.context.get('device_identifier', 0))
1214
1215 _logger.info("PoS synchronisation #%d finished", sync_token)
1216 return pos_order_ids.read_pos_data(orders, config)
1217
1218 @api.model
1219 def read_pos_orders(self, domain=False):
1220 orders = self.search(domain)
1221 config_id = orders[0].config_id if orders else False
1222 return orders.read_pos_data([], config_id) if config_id else {'pos.order': []}
1223
1224 @api.model
1225 def read_pos_data_uuid(self, uuid):
1226 return self.read_pos_orders([('uuid', '=', uuid)])
1227
1228 def read_pos_data(self, data, config):
1229 # If the previous session is closed, the order will get a new session_id due to _get_valid_session in _process_order
1230 account_moves = self.sudo().account_move | self.sudo().payment_ids.account_move_id | self.sudo().session_move_id
1231 return {
1232 'pos.order': self._load_pos_data_read(self, config) if config else [],
1233 'pos.session': [],
1234 'pos.payment': self.env['pos.payment']._load_pos_data_read(self.payment_ids, config) if config else [],
1235 'pos.order.line': self.env['pos.order.line']._load_pos_data_read(self.lines, config) if config else [],
1236 'pos.pack.operation.lot': self.env['pos.pack.operation.lot']._load_pos_data_read(self.lines.pack_lot_ids, config) if config else [],
1237 'product.attribute.custom.value': self.env['product.attribute.custom.value']._load_pos_data_read(self.lines.custom_attribute_value_ids, config) if config else [],
1238 'account.move': self.env['account.move'].sudo()._load_pos_data_read(account_moves, config) if config else [],
1239 }
1240
1241 @api.model
1242 def _get_refunded_orders(self, order):
1243 refunded_orderline_ids = [line[2]['refunded_orderline_id'] for line in order['lines'] if line[0] in [0, 1] and line[2].get('refunded_orderline_id')]
1244 return self.env['pos.order.line'].browse(refunded_orderline_ids).mapped('order_id')
1245
1246 def _should_create_picking_real_time(self):
1247 return not self.session_id.update_stock_at_closing or (self.company_id.anglo_saxon_accounting and self.to_invoice)
1248
1249 def _create_order_picking(self):
1250 self.ensure_one()
1251 if self.shipping_date:
1252 self.sudo().lines._launch_stock_rule_from_pos_order_lines()
1253 else:
1254 if self._should_create_picking_real_time():
1255 picking_type = self.config_id.picking_type_id
1256 if self.partner_id.property_stock_customer:
1257 destination_id = self.partner_id.property_stock_customer.id
1258 elif not picking_type or not picking_type.default_location_dest_id:
1259 destination_id = self.env['stock.warehouse']._get_partner_locations()[0].id
1260 else:
1261 destination_id = picking_type.default_location_dest_id.id
1262
1263 pickings = self.env['stock.picking']._create_picking_from_pos_order_lines(destination_id, self.lines, picking_type, self.partner_id)
1264 pickings.write({'pos_session_id': self.session_id.id, 'pos_order_id': self.id, 'origin': self.name})
1265
1266 def add_payment(self, data):
1267 """Create a new payment for the order"""
1268 self.ensure_one()
1269 self.env['pos.payment'].create(data)
1270 self.amount_paid = self._compute_amount_paid()
1271
1272 def _prepare_refund_values(self, current_session):
1273 self.ensure_one()
1274 pos_reference, tracking_number = current_session.config_id._get_next_order_refs()
1275 return {
1276 'name': _('%(name)s REFUND', name=self.name),
1277 'session_id': current_session.id,
1278 'date_order': fields.Datetime.now(),
1279 'pos_reference': pos_reference,
1280 'lines': False,
1281 'amount_paid': 0,
1282 'is_total_cost_computed': False,
1283 'is_refund': True,
1284 'tracking_number': tracking_number,
1285 }
1286
1287 def _prepare_mail_values(self, email, ticket, basic_ticket):
1288 message = Markup(
1289 _("<p>Dear %(client_name)s,<br/>Here is your Receipt %(is_invoiced)sfor \
1290 %(pos_name)s amounting in %(amount)s from %(company_name)s. </p>")
1291 ) % {
1292 'client_name': self.partner_id.name or _('Customer'),
1293 'pos_name': self.name,
1294 'amount': self.currency_id.format(self.amount_total),
1295 'company_name': self.company_id.name,
1296 'is_invoiced': "and Invoice " if self.account_move else "",
1297 }
1298
1299 return {
1300 'subject': _('Receipt %s', self.name),
1301 'body_html': message,
1302 'author_id': self.env.user.partner_id.id,
1303 'email_from': self.env.company.email or self.env.user.email_formatted,
1304 'email_to': email,
1305 'attachment_ids': self._add_mail_attachment(self.name, ticket, basic_ticket),
1306 }
1307
1308 def _refund(self):
1309 """ Create a copy of order to refund them.
1310
1311 return The newly created refund orders.
1312 """
1313 refund_orders = self.env['pos.order']
1314 for order in self:
1315 # When a refund is performed, we are creating it in a session having the same config as the original
1316 # order. It can be the same session, or if it has been closed the new one that has been opened.
1317 current_session = order.session_id.config_id.current_session_id
1318 if not current_session:
1319 raise UserError(_('To return product(s), you need to open a session in the POS %s', order.session_id.config_id.display_name))
1320 refund_order = order.copy(
1321 order._prepare_refund_values(current_session)
1322 )
1323 for line in order.lines.filtered(lambda l: l.refunded_qty < l.qty):
1324 PosPackOperationLot = self.env['pos.pack.operation.lot']
1325 for pack_lot in line.pack_lot_ids:
1326 PosPackOperationLot += pack_lot.copy()
1327 refund_line = line.copy(line._prepare_refund_data(refund_order, PosPackOperationLot))
1328 refund_line._onchange_amount_line_all()
1329 refund_order._compute_prices()
1330 refund_orders |= refund_order
1331 refund_order.config_id.notify_synchronisation(current_session.id, 0)
1332 refund_orders._compute_prices()
1333 return refund_orders
1334
1335 def refund(self):
1336 return {
1337 'name': _('Return Products'),
1338 'view_mode': 'form',
1339 'res_model': 'pos.order',
1340 'res_id': self._refund().ids[0],
1341 'view_id': False,
1342 'context': self.env.context,
1343 'type': 'ir.actions.act_window',
1344 'target': 'current',
1345 }
1346
1347 def action_send_mail(self):
1348 template = self.env['mail.template'].search([('model', '=', self._name)], limit=1)
1349 return {
1350 'name': _('Send Email'),
1351 'view_mode': 'form',
1352 'res_model': 'mail.compose.message',
1353 'type': 'ir.actions.act_window',
1354 'context': {
1355 'default_composition_mode': 'mass_mail',
1356 'default_res_ids': self.ids,
1357 'default_template_id': template.id,
1358 },
1359 'target': 'new'
1360 }
1361
1362 def action_send_receipt(self, email, ticket_image, basic_image):
1363 self.ensure_one()
1364 self.email = email
1365 mail_template_id = 'point_of_sale.email_template_pos_receipt'
1366 mail_template = self.env.ref(mail_template_id, raise_if_not_found=False)
1367 if not mail_template:
1368 raise UserError(_("The mail template with xmlid %s has been deleted.", mail_template_id))
1369 mail_template.send_mail(self.id, force_send=True, email_values={'email_to': email,
1370 'attachment_ids': self._get_mail_attachments(self.name, ticket_image, basic_image)})
1371
1372 def _get_mail_attachments(self, name, ticket, basic_ticket):
1373 attachments = []
1374 receipt = self.env['ir.attachment'].create({
1375 'name': 'Receipt-' + name + '.jpg',
1376 'type': 'binary',
1377 'datas': ticket,
1378 'res_model': 'pos.order',
1379 'res_id': self.ids[0],
1380 'mimetype': 'image/jpeg',
1381 })
1382 attachments += [(4, receipt.id)]
1383
1384 if basic_ticket:
1385 basic_receipt = self.env['ir.attachment'].create({
1386 'name': 'Receipt-' + name + '-1' + '.jpg',
1387 'type': 'binary',
1388 'datas': basic_ticket,
1389 'res_model': 'pos.order',
1390 'res_id': self.ids[0],
1391 'mimetype': 'image/jpeg',
1392 })
1393 attachments += [(4, basic_receipt.id)]
1394
1395 if self.mapped('account_move'):
1396 report = self.env['ir.actions.report']._render_qweb_pdf("account.account_invoices", self.account_move.ids[0])
1397 invoice = self.env['ir.attachment'].create({
1398 'name': name + '.pdf',
1399 'type': 'binary',
1400 'datas': base64.b64encode(report[0]),
1401 'res_model': 'pos.order',
1402 'res_id': self.ids[0],
1403 'mimetype': 'application/pdf'
1404 })
1405 attachments += [(4, invoice.id)]
1406
1407 return attachments
1408
1409
1410 @api.model
1411 def remove_from_ui(self, server_ids):
1412 """ Remove orders from the frontend PoS application
1413
1414 Remove orders from the server by id.
1415 :param server_ids: list of the id's of orders to remove from the server.
1416 :type server_ids: list.
1417 :returns: list -- list of db-ids for the removed orders.
1418 """
1419 orders = self.search([('id', 'in', server_ids), ('state', '=', 'draft')])
1420 orders.write({'state': 'cancel'})
1421 # TODO Looks like delete cascade is a better solution.
1422 orders.mapped('payment_ids').sudo().unlink()
1423 orders.sudo().unlink()
1424 return orders.ids
1425
1426 @api.model
1427 def search_paid_order_ids(self, config_id, domain, limit, offset):
1428 """Search for 'paid' orders that satisfy the given domain, limit and offset."""
1429 pos_config = self.env['pos.config'].browse(config_id)
1430 default_domain = Domain('state', '!=', 'draft') & Domain('state', '!=', 'cancel') & Domain('config_id', 'in', [config_id] + pos_config.trusted_config_ids.ids)
1431 real_domain = Domain(domain) & default_domain
1432 orders = self.search(real_domain, limit=limit, offset=offset, order='create_date desc')
1433 # We clean here the orders that does not have the same currency.
1434 # As we cannot use currency_id in the domain (because it is not a stored field),
1435 # we must do it after the search.
1436 orders = orders.filtered(lambda order: order.currency_id == pos_config.currency_id)
1437 orderlines = self.env['pos.order.line'].search(['|', ('refunded_orderline_id.order_id', 'in', orders.ids), ('order_id', 'in', orders.ids)])
1438
1439 # We will return to the frontend the ids and the date of their last modification
1440 # so that it can compare to the last time it fetched the orders and can ask to fetch
1441 # orders that are not up-to-date.
1442 # The date of their last modification is either the last time one of its orderline has changed,
1443 # or the last time a refunded orderline related to it has changed.
1444 orders_info = defaultdict(lambda: datetime.min)
1445 for orderline in orderlines:
1446 key_order = orderline.order_id.id if orderline.order_id in orders \
1447 else orderline.refunded_orderline_id.order_id.id
1448 if orders_info[key_order] < orderline.write_date:
1449 orders_info[key_order] = orderline.write_date
1450 totalCount = self.search_count(real_domain)
1451 return {'ordersInfo': list(orders_info.items())[::-1], 'totalCount': totalCount}
1452
1453 def _send_order(self):
1454 # This function is made to be overriden by pos_self_order_preparation_display
1455 pass
1456
1457 def _prepare_pos_log(self, body):
1458 return body
1459
1460
1461 class PosOrderLine(models.Model):
1462 _name = 'pos.order.line'
1463 _description = "Point of Sale Order Lines"
1464 _rec_name = "product_id"
1465 _inherit = ['pos.load.mixin']
1466
1467 company_id = fields.Many2one('res.company', string='Company', related="order_id.company_id", store=True)
1468 name = fields.Char(string='Line No', required=True, copy=False)
1469 notice = fields.Char(string='Discount Notice')
1470 product_id = fields.Many2one('product.product', string='Product', domain=[('sale_ok', '=', True)], required=True, change_default=True)
1471 attribute_value_ids = fields.Many2many('product.template.attribute.value', string="Selected Attributes")
1472 custom_attribute_value_ids = fields.One2many(
1473 comodel_name='product.attribute.custom.value', inverse_name='pos_order_line_id',
1474 string="Custom Values",
1475 store=True, readonly=False)
1476 price_unit = fields.Float(string='Unit Price', digits=0)
1477 qty = fields.Float('Quantity', digits='Product Unit', default=1)
1478 price_subtotal = fields.Monetary(string='Tax Excl.',
1479 readonly=True, required=True)
1480 price_subtotal_incl = fields.Monetary(string='Tax Incl.',
1481 readonly=True, required=True)
1482 price_extra = fields.Float(string="Price extra")
1483 price_type = fields.Selection([
1484 ('original', 'Original'),
1485 ('manual', 'Manual'),
1486 ('automatic', 'Automatic'),
1487 ], string='Price Type', default='original')
1488 margin = fields.Monetary(string="Margin", compute='_compute_margin')
1489 margin_percent = fields.Float(string="Margin (%)", compute='_compute_margin', digits=(12, 4))
1490 total_cost = fields.Float(string='Total cost', min_display_digits='Product Price', readonly=True)
1491 is_total_cost_computed = fields.Boolean(help="Allows to know if the total cost has already been computed or not")
1492 discount = fields.Float(string='Discount (%)', digits=0, default=0.0)
1493 order_id = fields.Many2one('pos.order', string='Order Ref', ondelete='cascade', required=True, index=True)
1494 tax_ids = fields.Many2many('account.tax', string='Taxes', readonly=True)
1495 tax_ids_after_fiscal_position = fields.Many2many('account.tax', compute='_get_tax_ids_after_fiscal_position', string='Taxes to Apply')
1496 pack_lot_ids = fields.One2many('pos.pack.operation.lot', 'pos_order_line_id', string='Lot/serial Number')
1497 product_uom_id = fields.Many2one('uom.uom', string='Product Unit', related='product_id.uom_id')
1498 currency_id = fields.Many2one('res.currency', related='order_id.currency_id')
1499 full_product_name = fields.Char('Full Product Name')
1500 customer_note = fields.Char('Customer Note')
1501 refund_orderline_ids = fields.One2many('pos.order.line', 'refunded_orderline_id', 'Refund Order Lines', help='Orderlines in this field are the lines that refunded this orderline.')
1502 refunded_orderline_id = fields.Many2one('pos.order.line', 'Refunded Order Line', index='btree_not_null', help='If this orderline is a refund, then the refunded orderline is specified in this field.')
1503 refunded_qty = fields.Float('Refunded Quantity', compute='_compute_refund_qty', help='Number of items refunded in this orderline.')
1504 uuid = fields.Char(string='Uuid', readonly=True, default=lambda self: str(uuid4()), copy=False)
1505 note = fields.Char('Product Note')
1506
1507 combo_parent_id = fields.Many2one('pos.order.line', string='Combo Parent', index='btree_not_null') # FIXME rename to parent_line_id
1508 combo_line_ids = fields.One2many('pos.order.line', 'combo_parent_id', string='Combo Lines') # FIXME rename to child_line_ids
1509
1510 combo_item_id = fields.Many2one('product.combo.item', string='Combo Item')
1511 is_edited = fields.Boolean('Edited', default=False)
1512 # Technical field holding custom data for the taxes computation engine.
1513 extra_tax_data = fields.Json()
1514
1515 _unique_uuid = models.Constraint('unique (uuid)', 'An order line with this uuid already exists')
1516
1517 @api.model
1518 def _load_pos_data_domain(self, data, config):
1519 return [('order_id', 'in', [order['id'] for order in data['pos.order']])]
1520
1521 @api.model
1522 def _load_pos_data_fields(self, config):
1523 return [
1524 'qty', 'attribute_value_ids', 'custom_attribute_value_ids', 'price_unit',
1525 'uuid', 'price_subtotal', 'price_subtotal_incl', 'order_id', 'note', 'price_type',
1526 'product_id', 'discount', 'tax_ids', 'pack_lot_ids', 'customer_note',
1527 'refunded_qty', 'price_extra', 'full_product_name', 'refunded_orderline_id',
1528 'combo_parent_id', 'combo_line_ids', 'combo_item_id', 'refund_orderline_ids',
1529 'extra_tax_data', 'write_date',
1530 ]
1531
1532 @api.model
1533 def _is_field_accepted(self, field):
1534 return field in self._fields and not field in ['combo_parent_id', 'combo_line_ids']
1535
1536 @api.depends('refund_orderline_ids', 'refund_orderline_ids.order_id.state')
1537 def _compute_refund_qty(self):
1538 for orderline in self:
1539 refund_order_line = orderline.refund_orderline_ids.filtered(lambda l: l.order_id.state != 'cancel')
1540 orderline.refunded_qty = -sum(refund_order_line.mapped('qty'))
1541
1542 def _prepare_refund_data(self, refund_order, PosPackOperationLot):
1543 """
1544 This prepares data for refund order line. Inheritance may inject more data here
1545
1546 @param refund_order: the pre-created refund order
1547 @type refund_order: pos.order
1548
1549 @param PosPackOperationLot: the pre-created Pack operation Lot
1550 @type PosPackOperationLot: pos.pack.operation.lot
1551
1552 @return: dictionary of data which is for creating a refund order line from the original line
1553 @rtype: dict
1554 """
1555 self.ensure_one()
1556 return {
1557 'name': _('%(name)s REFUND', name=self.name),
1558 'qty': -(self.qty - self.refunded_qty),
1559 'order_id': refund_order.id,
1560 'pack_lot_ids': PosPackOperationLot,
1561 'is_total_cost_computed': False,
1562 'refunded_orderline_id': self.id,
1563 }
1564
1565 @api.model_create_multi
1566 def create(self, vals_list):
1567 for vals in vals_list:
1568 order = self.env['pos.order'].browse(vals['order_id']) if vals.get('order_id') else False
1569 if order and order.exists() and not vals.get('name'):
1570 # set name based on the sequence specified on the config
1571 config = order.session_id.config_id
1572 if config.order_line_seq_id:
1573 vals['name'] = config.order_line_seq_id._next()
1574 if not vals.get('name'):
1575 # fallback on any pos.order sequence
1576 vals['name'] = self.env['ir.sequence'].next_by_code('pos.order.line')
1577 return super().create(vals_list)
1578
1579 def write(self, vals):
1580 if vals.get('pack_lot_line_ids'):
1581 for pl in vals.get('pack_lot_ids'):
1582 if pl[2].get('server_id'):
1583 pl[2]['id'] = pl[2]['server_id']
1584 del pl[2]['server_id']
1585 if self.order_id.config_id.order_edit_tracking and vals.get('qty') is not None and vals.get('qty') < self.qty:
1586 self.is_edited = True
1587 body = _("%(product_name)s: Ordered quantity: %(old_qty)s", product_name=self.full_product_name, old_qty=self.qty)
1588 body += Markup("&rarr;") + str(vals.get('qty'))
1589 for line in self:
1590 line.order_id.message_post(body=line.order_id._prepare_pos_log(body))
1591 return super().write(vals)
1592
1593 @api.model
1594 def get_existing_lots(self, company_id, config_id, product_id):
1595 """
1596 Return the lots that are still available in the given company.
1597 The lot is available if its quantity in the corresponding stock_quant and pos stock location is > 0.
1598 """
1599 self.check_access('read')
1600 pos_config = self.env['pos.config'].browse(config_id)
1601 if not pos_config:
1602 raise UserError(_('No PoS configuration found'))
1603
1604 src_loc = pos_config.picking_type_id.default_location_src_id
1605
1606 domain = [
1607 '|',
1608 ('company_id', '=', False),
1609 ('company_id', '=', company_id),
1610 ('product_id', '=', product_id),
1611 ('location_id', 'in', src_loc.child_internal_location_ids.ids),
1612 ('quantity', '>', 0),
1613 ('lot_id', '!=', False),
1614 ]
1615
1616 groups = self.sudo().env['stock.quant']._read_group(
1617 domain=domain,
1618 groupby=['lot_id'],
1619 aggregates=['quantity:sum']
1620 )
1621
1622 result = []
1623 for lot_recordset, total_quantity in groups:
1624 if lot_recordset:
1625 result.append({
1626 'id': lot_recordset.id,
1627 'name': lot_recordset.name,
1628 'product_qty': total_quantity
1629 })
1630
1631 return result
1632
1633 @api.ondelete(at_uninstall=False)
1634 def _unlink_except_order_state(self):
1635 if self.filtered(lambda x: x.order_id.state not in ["draft", "cancel"]):
1636 raise UserError(_("You can only unlink PoS order lines that are related to orders in new or cancelled state."))
1637
1638 @api.onchange('price_unit', 'tax_ids', 'qty', 'discount', 'product_id')
1639 def _onchange_amount_line_all(self):
1640 for line in self:
1641 res = line._compute_amount_line_all()
1642 line.update(res)
1643
1644 def _compute_amount_line_all(self):
1645 self.ensure_one()
1646 fpos = self.order_id.fiscal_position_id
1647 tax_ids_after_fiscal_position = fpos.map_tax(self.tax_ids)
1648 price = self.price_unit * (1 - (self.discount or 0.0) / 100.0)
1649 taxes = tax_ids_after_fiscal_position.compute_all(price, self.order_id.currency_id, self.qty, product=self.product_id, partner=self.order_id.partner_id)
1650 return {
1651 'price_subtotal_incl': taxes['total_included'],
1652 'price_subtotal': taxes['total_excluded'],
1653 }
1654
1655 @api.onchange('product_id')
1656 def _onchange_product_id(self):
1657 if self.product_id:
1658 price = self.order_id.pricelist_id._get_product_price(
1659 self.product_id, self.qty or 1.0, currency=self.currency_id
1660 )
1661 self.tax_ids = self.product_id.taxes_id.filtered_domain(self.env['account.tax']._check_company_domain(self.company_id))
1662 tax_ids_after_fiscal_position = self.order_id.fiscal_position_id.map_tax(self.tax_ids)
1663 self.price_unit = self.env['account.tax']._fix_tax_included_price_company(price, self.tax_ids, tax_ids_after_fiscal_position, self.company_id)
1664 self._onchange_qty()
1665
1666 @api.onchange('qty', 'discount', 'price_unit', 'tax_ids')
1667 def _onchange_qty(self):
1668 if self.product_id:
1669 price = self.price_unit * (1 - (self.discount or 0.0) / 100.0)
1670 self.price_subtotal = self.price_subtotal_incl = price * self.qty
1671 if (self.tax_ids):
1672 taxes = self.tax_ids.compute_all(price, self.order_id.currency_id, self.qty, product=self.product_id, partner=False)
1673 self.price_subtotal = taxes['total_excluded']
1674 self.price_subtotal_incl = taxes['total_included']
1675
1676 @api.depends('order_id', 'order_id.fiscal_position_id', 'tax_ids')
1677 def _get_tax_ids_after_fiscal_position(self):
1678 for line in self:
1679 line.tax_ids_after_fiscal_position = line.order_id.fiscal_position_id.map_tax(line.tax_ids)
1680
1681 def _prepare_reference_vals(self):
1682 return {
1683 'name': self.order_id.name,
1684 'pos_order_ids': [Command.link(self.order_id.id)],
1685 }
1686
1687 def _prepare_procurement_values(self):
1688 """ Prepare specific key for moves or other components that will be created from a stock rule
1689 coming from a sale order line. This method could be override in order to add other custom key that could
1690 be used in move/po creation.
1691 """
1692 self.ensure_one()
1693 # Use the delivery date if there is else use date_order and lead time
1694 if self.order_id.shipping_date:
1695 # get timezone from user
1696 # and convert to UTC to avoid any timezone issue
1697 # because shipping_date is date and date_planned is datetime
1698 from_zone = self.env.tz
1699 shipping_date = fields.Datetime.to_datetime(self.order_id.shipping_date)
1700 shipping_date = from_zone.localize(shipping_date)
1701 date_deadline = shipping_date.astimezone(pytz.UTC).replace(tzinfo=None)
1702 else:
1703 date_deadline = self.order_id.date_order
1704
1705 values = {
1706 'date_planned': date_deadline,
1707 'date_deadline': date_deadline,
1708 'route_ids': self.order_id.config_id.route_id,
1709 'warehouse_id': self.order_id.config_id.warehouse_id or False,
1710 'partner_id': self.order_id.partner_id.id,
1711 'product_description_variants': self.full_product_name,
1712 'company_id': self.order_id.company_id,
1713 'reference_ids': self.order_id.stock_reference_ids,
1714 }
1715 return values
1716
1717 def _launch_stock_rule_from_pos_order_lines(self):
1718
1719 procurements = []
1720 for line in self:
1721 line = line.with_company(line.company_id)
1722 if line.product_id.type != 'consu':
1723 continue
1724
1725 reference_ids = line.order_id.stock_reference_ids
1726 if not reference_ids:
1727 reference_ids = self.env['stock.reference'].create(line._prepare_reference_vals())
1728 line.order_id.stock_reference_ids = [Command.set(reference_ids.ids)]
1729
1730 values = line._prepare_procurement_values()
1731 product_qty = line.qty
1732
1733 procurement_uom = line.product_id.uom_id
1734 procurements.append(self.env['stock.rule'].Procurement(
1735 line.product_id, product_qty, procurement_uom,
1736 line.order_id.partner_id.property_stock_customer,
1737 line.name, line.order_id.name, line.order_id.company_id, values))
1738 if procurements:
1739 self.env['stock.rule'].run(procurements)
1740
1741 # This next block is currently needed only because the scheduler trigger is done by picking confirmation rather than stock.move confirmation
1742 orders = self.mapped('order_id')
1743 for order in orders:
1744 pickings_to_confirm = order.picking_ids
1745 if pickings_to_confirm:
1746 # Trigger the Scheduler for Pickings
1747 tracked_lines = order.lines.filtered(lambda l: l.product_id.tracking != 'none')
1748 lines_by_tracked_product = groupby(sorted(tracked_lines, key=lambda l: l.product_id.id), key=lambda l: l.product_id.id)
1749 pickings_to_confirm.action_confirm()
1750 for product_id, lines in lines_by_tracked_product:
1751 lines = self.env['pos.order.line'].concat(*lines)
1752 moves = pickings_to_confirm.move_ids.filtered(lambda m: m.product_id.id == product_id)
1753 moves.move_line_ids.unlink()
1754 moves._add_mls_related_to_order(lines, are_qties_done=False)
1755 moves._recompute_state()
1756 return True
1757
1758 def _is_product_storable_fifo_avco(self):
1759 self.ensure_one()
1760 return self.product_id.is_storable and self.product_id.cost_method in ['fifo', 'average']
1761
1762 def _compute_total_cost(self, stock_moves):
1763 """
1764 Compute the total cost of the order lines.
1765 :param stock_moves: recordset of `stock.move`, used for fifo/avco lines
1766 """
1767 for line in self.filtered(lambda l: not l.is_total_cost_computed):
1768 product = line.product_id
1769 cost_currency = product.sudo().cost_currency_id
1770 if line._is_product_storable_fifo_avco() and stock_moves:
1771 moves = line._get_stock_moves_to_consider(stock_moves, product)
1772 product_cost = moves._get_price_unit()
1773 if (cost_currency.is_zero(product_cost) and line.order_id.shipping_date and line.refunded_orderline_id):
1774 product_cost = line.refunded_orderline_id.total_cost / line.refunded_orderline_id.qty
1775 else:
1776 product_cost = product.standard_price
1777 line.total_cost = line.qty * cost_currency._convert(
1778 from_amount=product_cost,
1779 to_currency=line.currency_id,
1780 company=line.company_id or self.env.company,
1781 date=line.order_id.date_order or fields.Date.today(),
1782 round=False,
1783 )
1784 line.is_total_cost_computed = True
1785
1786 def _get_stock_moves_to_consider(self, stock_moves, product):
1787 self.ensure_one()
1788 return stock_moves.filtered(lambda ml: ml.product_id.id == product.id)
1789
1790 @api.depends('price_subtotal', 'total_cost')
1791 def _compute_margin(self):
1792 for line in self:
1793 sign = -1 if line.order_id.is_refund else 1
1794 if line.product_id.type == 'combo':
1795 line.margin = 0
1796 line.margin_percent = 0
1797 else:
1798 line.margin = (line.price_subtotal * sign) - line.total_cost
1799 line.margin_percent = not float_is_zero(line.price_subtotal, precision_rounding=line.currency_id.rounding) \
1800 and line.margin / (line.price_subtotal * sign) \
1801 or 0
1802
1803 def _prepare_base_line_for_taxes_computation(self):
1804 self.ensure_one()
1805 commercial_partner = self.order_id.partner_id.commercial_partner_id
1806 fiscal_position = self.order_id.fiscal_position_id
1807 line = self.with_company(self.order_id.company_id)
1808 account = line.product_id._get_product_accounts()['income'] or self.order_id.config_id.journal_id.default_account_id
1809 if not account:
1810 raise UserError(_(
1811 "Please define income account for this product: '%(product)s' (id:%(id)d).",
1812 product=line.product_id.name, id=line.product_id.id,
1813 ))
1814
1815 if fiscal_position:
1816 account = fiscal_position.map_account(account)
1817
1818 is_refund_order = line.order_id.amount_total < 0.0
1819 is_refund_line = line.qty * line.price_unit < 0
1820
1821 lang = line.order_id.partner_id.lang or self.env.user.lang
1822 product_name = line.with_context(lang=lang).full_product_name or line.product_id.with_context(lang=lang).display_name
1823 if line.product_id.description_sale:
1824 product_name += '\n' + line.product_id.with_context(lang=lang).description_sale
1825 return {
1826 **self.env['account.tax']._prepare_base_line_for_taxes_computation(
1827 line,
1828 partner_id=commercial_partner,
1829 currency_id=self.order_id.currency_id,
1830 rate=self.order_id.currency_rate,
1831 product_id=line.product_id,
1832 tax_ids=line.tax_ids_after_fiscal_position,
1833 price_unit=line.price_unit,
1834 quantity=line.qty * (-1 if is_refund_order else 1),
1835 discount=line.discount,
1836 account_id=account,
1837 is_refund=is_refund_line,
1838 sign=1 if is_refund_order else -1,
1839 ),
1840 'uom_id': line.product_uom_id,
1841 'name': product_name,
1842 }
1843
1844 def _prepare_tax_base_line_values(self):
1845 """ Convert pos order lines into dictionaries that would be used to compute taxes later.
1846
1847 :return: A list of python dictionaries (see '_prepare_base_line_for_taxes_computation' in account.tax).
1848 """
1849 return [line._prepare_base_line_for_taxes_computation() for line in self]
1850
1851 def unlink(self):
1852 for line in self:
1853 if line.order_id.config_id.order_edit_tracking:
1854 line.order_id.has_deleted_line = True
1855 body = _("%(product_name)s: Deleted line (quantity: %(qty)s)", product_name=line.full_product_name, qty=line.qty)
1856 line.order_id.message_post(body=line.order_id._prepare_pos_log(body))
1857 res = super().unlink()
1858 return res
1859
1860 def _get_discount_amount(self):
1861 self.ensure_one()
1862 original_price = self.tax_ids.compute_all(self.price_unit, self.currency_id, self.qty, product=self.product_id, partner=self.order_id.partner_id)['total_included']
1863 return original_price - self.price_subtotal_incl
1864
1865
1866 class PosPackOperationLot(models.Model):
1867 _name = 'pos.pack.operation.lot'
1868 _description = "Specify product lot/serial number in pos order line"
1869 _rec_name = "lot_name"
1870 _inherit = ['pos.load.mixin']
1871
1872 pos_order_line_id = fields.Many2one('pos.order.line', index='btree_not_null')
1873 order_id = fields.Many2one('pos.order', related="pos_order_line_id.order_id", readonly=False)
1874 lot_name = fields.Char('Lot Name')
1875 product_id = fields.Many2one('product.product', related='pos_order_line_id.product_id', readonly=False)
1876
1877 @api.model
1878 def _load_pos_data_domain(self, data, config):
1879 return [('pos_order_line_id', 'in', [line['id'] for line in data['pos.order.line']])]
1880
1881 @api.model
1882 def _load_pos_data_fields(self, config):
1883 return ['lot_name', 'pos_order_line_id', 'write_date']
1884
1885
1886 class AccountCashRounding(models.Model):
1887 _name = 'account.cash.rounding'
1888 _inherit = ['account.cash.rounding', 'pos.load.mixin']
1889
1890 @api.constrains('rounding', 'rounding_method', 'strategy')
1891 def _check_session_state(self):
1892 open_session = self.env['pos.session'].search([('config_id.rounding_method', 'in', self.ids), ('state', '!=', 'closed')], limit=1)
1893 if open_session:
1894 raise ValidationError(
1895 _("You are not allowed to change the cash rounding configuration while a pos session using it is already opened."))
1896
1897 @api.model
1898 def _load_pos_data_domain(self, data, config):
1899 return [('id', '=', config.rounding_method.id)]
1900
1901 @api.model
1902 def _load_pos_data_fields(self, config):
1903 return ['id', 'name', 'rounding', 'rounding_method', 'strategy']