Debian Codegraph @

addons/point_of_sale/models/report_sale_details.py

raw symbols SCIP
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2 from datetime import timedelta
3
4 import pytz
5
6 from odoo import api, fields, models, _
7 from odoo.fields import Domain
8 from odoo.tools import SQL
9
10
11 class ReportPoint_Of_SaleReport_Saledetails(models.AbstractModel):
12 _name = 'report.point_of_sale.report_saledetails'
13
14 _description = 'Point of Sale Details'
15
16 def _get_date_start_and_date_stop(self, date_start, date_stop):
17 if date_start:
18 date_start = fields.Datetime.from_string(date_start)
19 else:
20 # start by default today 00:00:00
21 user_tz = self.env.tz
22 today = user_tz.localize(fields.Datetime.from_string(fields.Date.context_today(self)))
23 date_start = today.astimezone(pytz.timezone('UTC')).replace(tzinfo=None)
24
25 if date_stop:
26 date_stop = fields.Datetime.from_string(date_stop)
27 # avoid a date_stop smaller than date_start
28 if (date_stop < date_start):
29 date_stop = date_start + timedelta(days=1, seconds=-1)
30 else:
31 # stop by default today 23:59:59
32 date_stop = date_start + timedelta(days=1, seconds=-1)
33
34 return date_start, date_stop
35
36 def _get_domain(self, date_start=False, date_stop=False, config_ids=False, session_ids=False):
37 domain = Domain('state', 'in', ['paid', 'done'])
38
39 if (session_ids):
40 domain &= Domain('session_id', 'in', session_ids)
41 else:
42 date_start, date_stop = self._get_date_start_and_date_stop(date_start, date_stop)
43
44 domain &= Domain('date_order', '>=', fields.Datetime.to_string(date_start))
45 domain &= Domain('date_order', '<=', fields.Datetime.to_string(date_stop))
46
47 if config_ids:
48 domain &= Domain('config_id', 'in', config_ids)
49
50 return domain
51
52 @api.model
53 def get_sale_details(self, date_start=False, date_stop=False, config_ids=False, session_ids=False, **kwargs):
54 """ Serialise the orders of the requested time period, configs and sessions.
55 :param date_start: The dateTime to start, default today 00:00:00.
56 :type date_start: str.
57 :param date_stop: The dateTime to stop, default date_start + 23:59:59.
58 :type date_stop: str.
59 :param config_ids: Pos Config id's to include.
60 :type config_ids: list of numbers.
61 :param session_ids: Pos Config id's to include.
62 :type session_ids: list of numbers.
63 :returns: dict -- Serialised sales.
64 """
65 if (not session_ids):
66 date_start, date_stop = self._get_date_start_and_date_stop(date_start, date_stop)
67
68 domain = self._get_domain(date_start, date_stop, config_ids, session_ids, **kwargs)
69 orders = self.env['pos.order'].search(domain)
70
71 if config_ids:
72 config_currencies = self.env['pos.config'].search([('id', 'in', config_ids)]).mapped('currency_id')
73 else:
74 config_currencies = self.env['pos.session'].search([('id', 'in', session_ids)]).mapped('config_id.currency_id')
75 # If all the pos.config have the same currency, we can use it, else we use the company currency
76 if config_currencies and all(i == config_currencies.ids[0] for i in config_currencies.ids):
77 user_currency = config_currencies[0]
78 else:
79 user_currency = self.env.company.currency_id
80
81 total = 0.0
82 products_sold = {}
83 taxes = {
84 'base_amount': 0.0,
85 'taxes': {},
86 }
87 refund_done = {}
88 refund_taxes = {
89 'base_amount': 0.0,
90 'taxes': {},
91 }
92 for order in orders:
93 if user_currency != order.pricelist_id.currency_id:
94 total += order.pricelist_id.currency_id._convert(
95 order.amount_total, user_currency, order.company_id, order.date_order or fields.Date.today())
96 else:
97 total += order.amount_total
98 currency = order.session_id.currency_id
99
100 for line in order.lines:
101 if not line.order_id.is_refund:
102 products_sold, taxes = self._get_products_and_taxes_dict(line, products_sold, taxes, currency)
103 else:
104 refund_done, refund_taxes = self._get_products_and_taxes_dict(line, refund_done, refund_taxes, currency)
105
106 taxes_info = self._get_taxes_info(taxes)
107 refund_taxes_info = self._get_taxes_info(refund_taxes)
108 taxes = taxes['taxes']
109 refund_taxes = refund_taxes['taxes']
110
111 payment_ids = self.env["pos.payment"].search([('pos_order_id', 'in', orders.ids)]).ids
112 if payment_ids:
113 method_name = self.env['pos.payment.method']._field_to_sql('method', 'name')
114 self.env.cr.execute(SQL("""
115 SELECT method.id as id, payment.session_id as session, %(method_name)s as name, method.is_cash_count as cash,
116 sum(amount) total, method.journal_id journal_id
117 FROM pos_payment AS payment,
118 pos_payment_method AS method
119 WHERE payment.payment_method_id = method.id
120 AND payment.id IN %(payment_ids)s
121 GROUP BY method.name, method.is_cash_count, payment.session_id, method.id, journal_id
122 ORDER BY method.id, payment.session_id
123 """, method_name=method_name, payment_ids=tuple(payment_ids)))
124 payments = self.env.cr.dictfetchall()
125 else:
126 payments = []
127
128 configs = []
129 sessions = []
130 if config_ids:
131 configs = self.env['pos.config'].search([('id', 'in', config_ids)])
132 if session_ids:
133 sessions = self.env['pos.session'].search([('id', 'in', session_ids)])
134 else:
135 sessions = self.env['pos.session'].search([('config_id', 'in', configs.ids), ('start_at', '>=', date_start), ('stop_at', '<=', date_stop)])
136 else:
137 sessions = self.env['pos.session'].search([('id', 'in', session_ids)])
138 for session in sessions:
139 configs.append(session.config_id)
140
141 for payment in payments:
142 payment['count'] = False
143
144 for session in sessions:
145 cash_counted = 0
146 if session.cash_register_balance_end_real:
147 cash_counted = session.cash_register_balance_end_real
148 is_cash_method = False
149 for payment in payments:
150 account_payments = self.env['account.payment'].search([('pos_session_id', '=', session.id)])
151 if payment['session'] == session.id:
152 if not payment['cash']:
153 ref_value = "Closing difference in %s (%s)" % (payment['name'], session.name)
154 account_move = self.env['account.move'].search([("ref", "=", ref_value)], limit=1)
155 if account_move:
156 payment_method = self.env['pos.payment.method'].browse(payment['id'])
157 is_loss = any(l.account_id == payment_method.journal_id.loss_account_id for l in account_move.line_ids)
158 is_profit = any(l.account_id == payment_method.journal_id.profit_account_id for l in account_move.line_ids)
159 payment['final_count'] = payment['total']
160 payment['money_difference'] = -account_move.amount_total if is_loss else account_move.amount_total
161 payment['money_counted'] = payment['final_count'] + payment['money_difference']
162 payment['cash_moves'] = []
163 if is_profit:
164 move_name = 'Difference observed during the counting (Profit)'
165 payment['cash_moves'] = [{'name': move_name, 'amount': payment['money_difference']}]
166 elif is_loss:
167 move_name = 'Difference observed during the counting (Loss)'
168 payment['cash_moves'] = [{'name': move_name, 'amount': payment['money_difference']}]
169 payment['count'] = True
170 elif payment['id'] in account_payments.mapped('pos_payment_method_id.id'):
171 account_payment = account_payments.filtered(lambda p: p.pos_payment_method_id.id == payment['id'])
172 payment['final_count'] = payment['total']
173 payment['money_counted'] = sum(account_payment.mapped('amount_signed'))
174 payment['money_difference'] = payment['money_counted'] - payment['final_count']
175 payment['cash_moves'] = []
176 if payment['money_difference'] > 0:
177 move_name = 'Difference observed during the counting (Profit)'
178 payment['cash_moves'] = [{'name': move_name, 'amount': payment['money_difference']}]
179 elif payment['money_difference'] < 0:
180 move_name = 'Difference observed during the counting (Loss)'
181 payment['cash_moves'] = [{'name': move_name, 'amount': payment['money_difference']}]
182 payment['count'] = True
183 else:
184 is_cash_method = True
185 payment['final_count'] = payment['total'] + session.cash_register_balance_start + session.cash_real_transaction
186 payment['money_counted'] = cash_counted
187 payment['money_difference'] = payment['money_counted'] - payment['final_count']
188 cash_moves = self.env['account.bank.statement.line'].search([('pos_session_id', '=', session.id)])
189 cash_in_out_list = []
190 cash_in_count = 0
191 cash_out_count = 0
192 if session.cash_register_balance_start > 0:
193 cash_in_out_list.append({
194 'name': _('Cash Opening'),
195 'amount': session.cash_register_balance_start,
196 })
197 for cash_move in cash_moves:
198 if cash_move.amount > 0:
199 cash_in_count += 1
200 name = f'Cash in {cash_in_count}'
201 else:
202 cash_out_count += 1
203 name = f'Cash out {cash_out_count}'
204 if cash_move.move_id.journal_id.id == payment['journal_id']:
205 cash_in_out_list.append({
206 'name': cash_move.payment_ref if cash_move.payment_ref else name,
207 'amount': cash_move.amount
208 })
209 payment['cash_moves'] = cash_in_out_list
210 payment['count'] = True
211 if not is_cash_method:
212 cash_name = _('Cash %(session_name)s', session_name=session.name)
213 previous_session = self.env['pos.session'].search([('id', '<', session.id), ('state', '=', 'closed'), ('config_id', '=', session.config_id.id)], limit=1)
214 final_count = previous_session.cash_register_balance_end_real + session.cash_real_transaction
215 cash_difference = session.cash_register_balance_end_real - final_count
216 cash_moves = self.env['account.bank.statement.line'].search([('pos_session_id', '=', session.id)], order='date asc')
217 cash_in_out_list = []
218
219 if previous_session.cash_register_balance_end_real > 0:
220 cash_in_out_list.append({
221 'name': _('Cash Opening'),
222 'amount': previous_session.cash_register_balance_end_real,
223 })
224
225 # If there is a cash difference, we remove the last cash move which is the cash difference
226 if session.currency_id.round(cash_difference) != 0:
227 cash_moves = cash_moves[:-1]
228
229 for cash_move in cash_moves:
230 cash_in_out_list.append({
231 'name': cash_move.payment_ref,
232 'amount': cash_move.amount
233 })
234 payments.insert(0, {
235 'name': cash_name,
236 'total': 0,
237 'final_count': final_count,
238 'money_counted': session.cash_register_balance_end_real,
239 'money_difference': cash_difference,
240 'cash_moves': cash_in_out_list,
241 'count': True,
242 'session': session.id,
243 })
244 products = []
245 refund_products = []
246 for category_name, product_list in products_sold.items():
247 category_dictionnary = {
248 'name': category_name,
249 'products': sorted([{
250 'product_id': product.id,
251 'product_name': product.display_name,
252 'barcode': product.barcode,
253 'quantity': qty,
254 'price_unit': price_unit,
255 'discount': discount,
256 'uom': product.uom_id.name,
257 'total_paid': product_total,
258 'base_amount': base_amount,
259 'combo_products_label': combo_products_label,
260 } for (product, price_unit, discount), (qty, product_total, base_amount, combo_products_label) in product_list.items()], key=lambda l: l['product_name']),
261 }
262 products.append(category_dictionnary)
263 products = sorted(products, key=lambda l: str(l['name']))
264
265 for category_name, product_list in refund_done.items():
266 category_dictionnary = {
267 'name': category_name,
268 'products': sorted([{
269 'product_id': product.id,
270 'product_name': product.display_name,
271 'barcode': product.barcode,
272 'quantity': qty,
273 'price_unit': price_unit,
274 'discount': discount,
275 'uom': product.uom_id.name,
276 'total_paid': product_total,
277 'base_amount': base_amount,
278 'combo_products_label': combo_products_label,
279 } for (product, price_unit, discount), (qty, product_total, base_amount, combo_products_label) in product_list.items()], key=lambda l: l['product_name']),
280 }
281 refund_products.append(category_dictionnary)
282 refund_products = sorted(refund_products, key=lambda l: str(l['name']))
283
284 products, products_info = self.with_context(config_id=configs[0].id if len(configs) > 0 else False)._get_total_and_qty_per_category(products)
285 refund_products, refund_info = self.with_context(config_id=configs[0].id if len(configs) > 0 else False)._get_total_and_qty_per_category(refund_products)
286
287 currency = {
288 'symbol': user_currency.symbol,
289 'position': True if user_currency.position == 'after' else False,
290 'total_paid': user_currency.round(total),
291 'precision': user_currency.decimal_places,
292 }
293
294 session_name = False
295 if len(sessions) == 1:
296 state = sessions[0].state
297 date_start = sessions[0].start_at
298 date_stop = sessions[0].stop_at
299 session_name = sessions[0].name
300 else:
301 state = "multiple"
302
303 config_names = []
304 for config in configs:
305 config_names.append(config.name)
306
307 discount_number = len(orders.filtered(lambda o: o.lines.filtered(lambda l: l.discount > 0)))
308 discount_amount = sum(l._get_discount_amount() for l in orders.lines.filtered(lambda l: l.discount > 0))
309
310 invoiceList = []
311 invoiceTotal = 0
312 totalPaymentsAmount = 0
313
314 for session in sessions:
315 invoiceList.append({
316 'name': session.name,
317 'invoices': session._get_invoice_total_list(),
318 })
319 invoiceTotal += session._get_total_invoice()
320 totalPaymentsAmount += session.total_payments_amount
321 payments_per_method = {}
322 for payment in payments:
323 if payment.get('id'):
324 method_name = self.env['pos.payment.method'].browse(payment['id']).name
325 payment['name'] = method_name + ' ' + self.env['pos.session'].browse(payment['session']).name
326 if payments_per_method.get(payment['id']):
327 payments_per_method[payment['id']]['total'] += payment['total']
328 else:
329 payments_per_method[payment['id']] = {
330 'name': method_name,
331 'total': payment['total'],
332 }
333
334 return {
335 'opening_note': sessions[0].opening_notes if len(sessions) == 1 else False,
336 'closing_note': sessions[0].closing_notes if len(sessions) == 1 else False,
337 'state': state,
338 'currency': currency,
339 'nbr_orders': len(orders),
340 'date_start': date_start,
341 'date_stop': date_stop,
342 'session_name': session_name or False,
343 'config_names': config_names,
344 'payments': payments,
345 'company_name': self.env.company.name,
346 'taxes': list(taxes.values()),
347 'taxes_info': taxes_info,
348 'products': products,
349 'products_info': products_info,
350 'refund_taxes': list(refund_taxes.values()),
351 'refund_taxes_info': refund_taxes_info,
352 'refund_info': refund_info,
353 'refund_products': refund_products,
354 'discount_number': discount_number,
355 'discount_amount': discount_amount,
356 'invoiceList': invoiceList,
357 'invoiceTotal': invoiceTotal,
358 'total_paid': totalPaymentsAmount,
359 'payments_per_method': payments_per_method.values(),
360 'show_payment_per_method': not session_ids,
361 }
362
363 def _get_product_total_amount(self, line):
364 return line.currency_id.round(line.price_unit * line.qty * (100 - line.discount) / 100.0)
365
366 def _get_products_and_taxes_dict(self, line, products, taxes, currency):
367 key2 = (line.product_id, line.price_unit, line.discount)
368 key1 = line.product_id.product_tmpl_id.pos_categ_ids[0].name if len(line.product_id.product_tmpl_id.pos_categ_ids) else _('Not Categorized')
369 precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
370 products.setdefault(key1, {})
371 products[key1].setdefault(key2, [0.0, 0.0, 0.0, ''])
372 products[key1][key2][0] = round(products[key1][key2][0] + abs(line.qty), precision)
373 products[key1][key2][1] += self._get_product_total_amount(line)
374 products[key1][key2][2] += line.price_subtotal
375
376 # Name of each combo products along with the combo
377 if line.combo_line_ids:
378 combo_products_label = ' (' + ", ".join(line.combo_line_ids.product_id.mapped('name')) + ')'
379 products[key1][key2][3] = combo_products_label
380
381 if line.tax_ids_after_fiscal_position:
382 line_taxes = line.tax_ids_after_fiscal_position.sudo().compute_all(line.price_unit * (1-(line.discount or 0.0)/100.0), currency, line.qty, product=line.product_id, partner=line.order_id.partner_id or False)
383 base_amounts = {}
384 for tax in line_taxes['taxes']:
385 taxes['taxes'].setdefault(tax['id'], {'name': tax['name'], 'tax_amount': 0.0, 'base_amount': 0.0})
386 taxes['taxes'][tax['id']]['tax_amount'] += tax['amount']
387 base_amounts[tax['id']] = tax['base']
388
389 for tax_id, base_amount in base_amounts.items():
390 taxes['taxes'][tax_id]['base_amount'] += currency.round(base_amount)
391 else:
392 taxes['taxes'].setdefault(0, {'name': _('No Taxes'), 'tax_amount': 0.0, 'base_amount': 0.0})
393 taxes['taxes'][0]['base_amount'] += line.price_subtotal_incl
394
395 refund_sign = -1 if line.order_id.is_refund else 1
396 taxes['base_amount'] += line.price_subtotal * refund_sign
397 return products, taxes
398
399 def _get_total_and_qty_per_category(self, categories):
400 all_qty = 0
401 all_total = 0
402 for category_dict in categories:
403 qty_cat = 0
404 total_cat = 0
405 for product in category_dict['products']:
406 qty_cat += product['quantity']
407 total_cat += product['base_amount']
408 category_dict['total'] = total_cat
409 category_dict['qty'] = qty_cat
410 # IMPROVEMENT: It would be better if the `products` are grouped by pos.order.line.id.
411 unique_products = list({tuple(sorted(product.items())): product for category in categories for product in category['products']}.values())
412 all_qty = sum([product['quantity'] for product in unique_products])
413 all_total = sum([product['base_amount'] for product in unique_products])
414
415 return categories, {'total': all_total, 'qty': all_qty}
416
417 def _prepare_get_sale_details_args_kwargs(self, data):
418 configs = self.env['pos.config'].browse(data['config_ids'])
419 args = (data['date_start'], data['date_stop'], configs.ids, data['session_ids'])
420 kwargs = {}
421 return args, kwargs
422
423 @api.model
424 def _get_report_values(self, docids, data=None):
425 data = dict(data or {})
426 # initialize data keys with their value if provided, else None
427 data.update({
428 #If no data is provided it means that the report is called from the PoS, and docids represent the session_id
429 'session_ids': data.get('session_ids') or (docids if not data.get('config_ids') and not data.get('date_start') and not data.get('date_stop') else None),
430 'config_ids': data.get('config_ids'),
431 'date_start': data.get('date_start'),
432 'date_stop': data.get('date_stop'),
433 })
434 args, kwargs = self._prepare_get_sale_details_args_kwargs(data)
435 data.update(self.get_sale_details(*args, **kwargs))
436 return data
437
438 def _get_taxes_info(self, taxes):
439 total_tax_amount = 0
440 total_base_amount = taxes['base_amount']
441 for tax in taxes['taxes'].values():
442 total_tax_amount += tax['tax_amount']
443 return {'tax_amount': total_tax_amount, 'base_amount': total_base_amount}