| 1 |
# Part of Odoo. See LICENSE file for full copyright and licensing details. |
| 2 |
from collections import defaultdict |
| 3 |
from datetime import timedelta |
| 4 |
from itertools import groupby, starmap |
| 5 |
from markupsafe import Markup |
| 6 |
import logging |
| 7 |
|
| 8 |
from odoo import api, fields, models, _ |
| 9 |
from odoo.exceptions import AccessError, UserError, ValidationError |
| 10 |
from odoo.fields import Command, Domain |
| 11 |
from odoo.tools import float_is_zero, float_compare, frozendict, plaintext2html, split_every |
| 12 |
from odoo.tools.constants import PREFETCH_MAX |
| 13 |
|
| 14 |
_logger = logging.getLogger(__name__) |
| 15 |
|
| 16 |
|
| 17 |
class PosSession(models.Model): |
| 18 |
_name = 'pos.session' |
| 19 |
_order = 'id desc' |
| 20 |
_description = 'Point of Sale Session' |
| 21 |
_inherit = ['mail.thread', 'mail.activity.mixin', "pos.bus.mixin", 'pos.load.mixin'] |
| 22 |
|
| 23 |
POS_SESSION_STATE = [ |
| 24 |
('opening_control', 'Opening Control'), # method action_pos_session_open |
| 25 |
('opened', 'In Progress'), # method action_pos_session_closing_control |
| 26 |
('closing_control', 'Closing Control'), # method action_pos_session_close |
| 27 |
('closed', 'Closed & Posted'), |
| 28 |
] |
| 29 |
|
| 30 |
company_id = fields.Many2one('res.company', related='config_id.company_id', string="Company", readonly=True) |
| 31 |
|
| 32 |
config_id = fields.Many2one( |
| 33 |
'pos.config', string='Point of Sale', |
| 34 |
required=True, |
| 35 |
index=True) |
| 36 |
name = fields.Char(string='Session ID', readonly=True, default='/') |
| 37 |
user_id = fields.Many2one( |
| 38 |
'res.users', string='Opened By', |
| 39 |
required=True, |
| 40 |
index=True, |
| 41 |
readonly=False, |
| 42 |
default=lambda self: self.env.uid, |
| 43 |
ondelete='restrict') |
| 44 |
currency_id = fields.Many2one('res.currency', related='config_id.currency_id', string="Currency", readonly=False) |
| 45 |
start_at = fields.Datetime(string='Opening Date', readonly=True) |
| 46 |
stop_at = fields.Datetime(string='Closing Date', readonly=True, copy=False) |
| 47 |
|
| 48 |
state = fields.Selection( |
| 49 |
POS_SESSION_STATE, string='Status', |
| 50 |
required=True, readonly=True, |
| 51 |
index=True, copy=False, default='opening_control') |
| 52 |
|
| 53 |
opening_notes = fields.Text(string="Opening Notes") |
| 54 |
closing_notes = fields.Text(string="Closing Notes") |
| 55 |
cash_control = fields.Boolean(compute='_compute_cash_control', string='Has Cash Control') |
| 56 |
cash_journal_id = fields.Many2one('account.journal', compute='_compute_cash_journal', string='Cash Journal', store=True) |
| 57 |
|
| 58 |
cash_register_balance_end_real = fields.Monetary( |
| 59 |
string="Ending Balance", |
| 60 |
readonly=True) |
| 61 |
cash_register_balance_start = fields.Monetary( |
| 62 |
string="Starting Balance", |
| 63 |
readonly=True) |
| 64 |
cash_register_balance_end = fields.Monetary( |
| 65 |
compute='_compute_cash_balance', |
| 66 |
string="Theoretical Closing Balance", |
| 67 |
help="Opening balance summed to all cash transactions.", |
| 68 |
readonly=True) |
| 69 |
cash_register_difference = fields.Monetary( |
| 70 |
compute='_compute_cash_balance', |
| 71 |
string='Before Closing Difference', |
| 72 |
help="Difference between the theoretical closing balance and the real closing balance.", |
| 73 |
readonly=True) |
| 74 |
|
| 75 |
# Total Cash In/Out |
| 76 |
cash_real_transaction = fields.Monetary(string='Transaction', readonly=True) |
| 77 |
|
| 78 |
order_ids = fields.One2many('pos.order', 'session_id', string='Orders') |
| 79 |
order_count = fields.Integer(compute='_compute_order_count') |
| 80 |
statement_line_ids = fields.One2many('account.bank.statement.line', 'pos_session_id', string='Cash Lines', readonly=True) |
| 81 |
failed_pickings = fields.Boolean(compute='_compute_picking_count') |
| 82 |
picking_count = fields.Integer(compute='_compute_picking_count') |
| 83 |
picking_ids = fields.One2many('stock.picking', 'pos_session_id') |
| 84 |
rescue = fields.Boolean(string='Recovery Session', |
| 85 |
help="Auto-generated session for orphan orders, ignored in constraints", |
| 86 |
readonly=True, |
| 87 |
copy=False) |
| 88 |
move_id = fields.Many2one('account.move', string='Journal Entry', index=True) |
| 89 |
payment_method_ids = fields.Many2many('pos.payment.method', related='config_id.payment_method_ids', string='Payment Methods') |
| 90 |
total_payments_amount = fields.Float(compute='_compute_total_payments_amount', string='Total Payments Amount') |
| 91 |
is_in_company_currency = fields.Boolean('Is Using Company Currency', compute='_compute_is_in_company_currency') |
| 92 |
update_stock_at_closing = fields.Boolean('Stock should be updated at closing') |
| 93 |
bank_payment_ids = fields.One2many('account.payment', 'pos_session_id', 'Bank Payments', help='Account payments representing aggregated and bank split payments.') |
| 94 |
|
| 95 |
def write(self, vals): |
| 96 |
if vals.get('state') == 'closed': |
| 97 |
for record in self: |
| 98 |
record.config_id._notify(('CLOSING_SESSION', { |
| 99 |
'device_identifier': self.env.context.get('device_identifier', False), |
| 100 |
'session_id': record.id |
| 101 |
})) |
| 102 |
return super().write(vals) |
| 103 |
|
| 104 |
@api.model |
| 105 |
def _load_pos_data_relations(self, model, fields): |
| 106 |
model_fields = self.env[model]._fields |
| 107 |
relations = {} |
| 108 |
|
| 109 |
for name, params in model_fields.items(): |
| 110 |
if (name not in fields and len(fields)) or (params.manual and not len(fields)): |
| 111 |
continue |
| 112 |
|
| 113 |
if params.comodel_name: |
| 114 |
relations[name] = { |
| 115 |
'name': name, |
| 116 |
'model': params.model_name, |
| 117 |
'compute': bool(params.compute), |
| 118 |
'related': bool(params.related), |
| 119 |
'relation': params.comodel_name, |
| 120 |
'type': params.type, |
| 121 |
} |
| 122 |
if params.type == 'many2one' and params.ondelete: |
| 123 |
relations[name]['ondelete'] = params.ondelete |
| 124 |
if params.type == 'one2many' and params.inverse_name: |
| 125 |
relations[name]['inverse_name'] = params.inverse_name |
| 126 |
if params.type == 'many2many': |
| 127 |
relations[name]['relation_table'] = self.env[model]._fields[name].relation |
| 128 |
else: |
| 129 |
relations[name] = { |
| 130 |
'name': name, |
| 131 |
'type': params.type, |
| 132 |
'compute': bool(params.compute), |
| 133 |
'related': bool(params.related), |
| 134 |
} |
| 135 |
|
| 136 |
return relations |
| 137 |
|
| 138 |
@api.model |
| 139 |
def _load_pos_data_models(self, config): |
| 140 |
return ['pos.config', 'pos.preset', 'resource.calendar.attendance', 'pos.order', 'pos.order.line', 'pos.pack.operation.lot', 'pos.payment', 'pos.payment.method', 'pos.printer', |
| 141 |
'pos.category', 'pos.bill', 'res.company', 'account.tax', 'account.tax.group', 'product.template', 'product.product', 'product.attribute', 'product.attribute.custom.value', |
| 142 |
'product.template.attribute.line', 'product.template.attribute.value', 'product.template.attribute.exclusion', 'product.combo', 'product.combo.item', 'res.users', 'res.partner', 'product.uom', |
| 143 |
'decimal.precision', 'uom.uom', 'res.country', 'res.country.state', 'res.lang', 'product.category', 'product.pricelist', 'product.pricelist.item', |
| 144 |
'account.cash.rounding', 'account.fiscal.position', 'stock.picking.type', 'res.currency', 'pos.note', 'product.tag', 'ir.module.module', 'account.move', 'account.account'] |
| 145 |
|
| 146 |
@api.model |
| 147 |
def _load_pos_data_domain(self, data, config): |
| 148 |
return [('id', '=', self.id)] |
| 149 |
|
| 150 |
@api.model |
| 151 |
def _load_pos_data_fields(self, config): |
| 152 |
return [ |
| 153 |
'id', 'name', 'user_id', 'config_id', 'start_at', 'stop_at', |
| 154 |
'payment_method_ids', 'state', 'update_stock_at_closing', 'cash_register_balance_start', 'access_token' |
| 155 |
] |
| 156 |
|
| 157 |
def load_data(self, models_to_load): |
| 158 |
response = {} |
| 159 |
response['pos.session'] = self._load_pos_data_search_read(response, self.config_id) |
| 160 |
|
| 161 |
for model in self._load_pos_data_models(self.config_id): |
| 162 |
if models_to_load and model not in models_to_load: |
| 163 |
continue |
| 164 |
|
| 165 |
try: |
| 166 |
response[model] = self.env[model]._load_pos_data_search_read(response, self.config_id) |
| 167 |
except AccessError as e: |
| 168 |
response[model] = [] |
| 169 |
_logger.info("Could not load model %s due to AccessError: %s", model, e) |
| 170 |
|
| 171 |
return response |
| 172 |
|
| 173 |
def load_data_params(self): |
| 174 |
response = {} |
| 175 |
fields = self._load_pos_data_fields(self.config_id) |
| 176 |
response['pos.session'] = { |
| 177 |
'fields': fields, |
| 178 |
'relations': self._load_pos_data_relations('pos.session', fields) |
| 179 |
} |
| 180 |
|
| 181 |
for model in self._load_pos_data_models(self.config_id): |
| 182 |
fields = self.env[model]._load_pos_data_fields(self.config_id) |
| 183 |
response[model] = { |
| 184 |
'fields': fields, |
| 185 |
'relations': self._load_pos_data_relations(model, fields) |
| 186 |
} |
| 187 |
|
| 188 |
return response |
| 189 |
|
| 190 |
def filter_local_data(self, models_to_filter): |
| 191 |
response = {} |
| 192 |
for model, ids in models_to_filter.items(): |
| 193 |
existing_records = self.env[model].browse(ids).exists() |
| 194 |
|
| 195 |
non_existent_ids = set(ids) - set(existing_records.ids) |
| 196 |
inactive_ids = set(existing_records._unrelevant_records(self.config_id)) |
| 197 |
|
| 198 |
response[model] = list(non_existent_ids | inactive_ids) |
| 199 |
return response |
| 200 |
|
| 201 |
def delete_opening_control_session(self): |
| 202 |
self.ensure_one() |
| 203 |
if not self.exists(): |
| 204 |
return { |
| 205 |
'status': 'success', |
| 206 |
} |
| 207 |
if self.state != 'opening_control' or len(self.order_ids) > 0: |
| 208 |
raise UserError(_("You can only cancel a session that is in opening control state and has no orders.")) |
| 209 |
self.sudo().unlink() |
| 210 |
return { |
| 211 |
'status': 'success', |
| 212 |
} |
| 213 |
|
| 214 |
def get_pos_ui_product_pricelist_item_by_product(self, product_tmpl_ids, product_ids, config_id): |
| 215 |
pos_config = self.env['pos.config'].browse(config_id) |
| 216 |
pricelist_fields = self.env['product.pricelist']._load_pos_data_fields(pos_config) |
| 217 |
pricelist_item_fields = self.env['product.pricelist.item']._load_pos_data_fields(pos_config) |
| 218 |
today = fields.Date.today() |
| 219 |
pricelist_item_domain = [ |
| 220 |
'&', |
| 221 |
('pricelist_id', 'in', self.config_id._get_available_pricelists().ids), |
| 222 |
*self.env['product.pricelist.item']._check_company_domain(self.company_id), |
| 223 |
'|', |
| 224 |
'&', ('product_id', '=', False), ('product_tmpl_id', 'in', product_tmpl_ids), |
| 225 |
('product_id', 'in', product_ids), |
| 226 |
'|', ('date_start', '=', False), ('date_start', '<=', today), |
| 227 |
'|', ('date_end', '=', False), ('date_end', '>=', today)] |
| 228 |
|
| 229 |
pricelist_item = self.env['product.pricelist.item'].search(pricelist_item_domain) |
| 230 |
pricelist = pricelist_item.pricelist_id |
| 231 |
|
| 232 |
return { |
| 233 |
'product.pricelist.item': pricelist_item.read(pricelist_item_fields, load=False), |
| 234 |
'product.pricelist': pricelist.read(pricelist_fields, load=False) |
| 235 |
} |
| 236 |
|
| 237 |
@api.depends('currency_id', 'company_id.currency_id') |
| 238 |
def _compute_is_in_company_currency(self): |
| 239 |
for session in self: |
| 240 |
session.is_in_company_currency = session.currency_id == session.company_id.currency_id |
| 241 |
|
| 242 |
@api.depends('payment_method_ids', 'order_ids', 'cash_register_balance_start') |
| 243 |
def _compute_cash_balance(self): |
| 244 |
for session in self: |
| 245 |
cash_payment_method = session.payment_method_ids.filtered('is_cash_count')[:1] |
| 246 |
if cash_payment_method: |
| 247 |
total_cash_payment = 0.0 |
| 248 |
captured_cash_payments_domain = Domain.AND([session._get_captured_payments_domain(), [('payment_method_id', '=', cash_payment_method.id)]]) |
| 249 |
result = self.env['pos.payment']._read_group(captured_cash_payments_domain, aggregates=['amount:sum']) |
| 250 |
total_cash_payment = result[0][0] or 0.0 |
| 251 |
if session.state == 'closed': |
| 252 |
total_cash = session.cash_real_transaction + total_cash_payment |
| 253 |
else: |
| 254 |
total_cash = sum(session.statement_line_ids.mapped('amount')) + total_cash_payment |
| 255 |
|
| 256 |
session.cash_register_balance_end = session.cash_register_balance_start + total_cash |
| 257 |
session.cash_register_difference = session.cash_register_balance_end_real - session.cash_register_balance_end |
| 258 |
else: |
| 259 |
session.cash_register_balance_end = 0.0 |
| 260 |
session.cash_register_difference = 0.0 |
| 261 |
|
| 262 |
@api.depends('order_ids.payment_ids.amount') |
| 263 |
def _compute_total_payments_amount(self): |
| 264 |
result = self.env['pos.payment']._read_group(self._get_captured_payments_domain(), ['session_id'], ['amount:sum']) |
| 265 |
session_amount_map = {session.id: amount for session, amount in result} |
| 266 |
for session in self: |
| 267 |
session.total_payments_amount = session_amount_map.get(session.id) or 0 |
| 268 |
|
| 269 |
def _compute_order_count(self): |
| 270 |
orders_data = self.env['pos.order']._read_group([('session_id', 'in', self.ids)], ['session_id'], ['__count']) |
| 271 |
sessions_data = {session.id: count for session, count in orders_data} |
| 272 |
for session in self: |
| 273 |
session.order_count = sessions_data.get(session.id, 0) |
| 274 |
|
| 275 |
@api.depends('picking_ids', 'picking_ids.state') |
| 276 |
def _compute_picking_count(self): |
| 277 |
for session in self: |
| 278 |
session.picking_count = self.env['stock.picking'].search_count([('pos_session_id', 'in', session.ids)]) |
| 279 |
session.failed_pickings = bool(self.env['stock.picking'].search([('pos_session_id', 'in', session.ids), ('state', '!=', 'done')], limit=1)) |
| 280 |
|
| 281 |
def action_stock_picking(self): |
| 282 |
self.ensure_one() |
| 283 |
action = self.env['ir.actions.act_window']._for_xml_id('stock.action_picking_tree_ready') |
| 284 |
action['display_name'] = _('Pickings') |
| 285 |
action['context'] = {} |
| 286 |
action['domain'] = [('id', 'in', self.picking_ids.ids)] |
| 287 |
return action |
| 288 |
|
| 289 |
@api.depends('cash_journal_id') |
| 290 |
def _compute_cash_control(self): |
| 291 |
# Only one cash register is supported by point_of_sale. |
| 292 |
for session in self: |
| 293 |
if session.cash_journal_id: |
| 294 |
session.cash_control = session.config_id.cash_control |
| 295 |
else: |
| 296 |
session.cash_control = False |
| 297 |
|
| 298 |
@api.depends('config_id', 'payment_method_ids') |
| 299 |
def _compute_cash_journal(self): |
| 300 |
# Only one cash register is supported by point_of_sale. |
| 301 |
for session in self: |
| 302 |
cash_journal = session.payment_method_ids.filtered('is_cash_count')[:1].journal_id |
| 303 |
session.cash_journal_id = cash_journal |
| 304 |
|
| 305 |
@api.constrains('config_id') |
| 306 |
def _check_pos_config(self): |
| 307 |
onboarding_creation = self.env.context.get('onboarding_creation', False) |
| 308 |
if not onboarding_creation and self.search_count([ |
| 309 |
('state', '!=', 'closed'), |
| 310 |
('config_id', '=', self.config_id.id), |
| 311 |
('rescue', '=', False) |
| 312 |
]) > 1: |
| 313 |
raise ValidationError(_("Another session is already opened for this point of sale.")) |
| 314 |
|
| 315 |
@api.constrains('start_at') |
| 316 |
def _check_start_date(self): |
| 317 |
for record in self: |
| 318 |
journal = record.config_id.journal_id |
| 319 |
company = journal.company_id |
| 320 |
start_date = record.start_at.date() |
| 321 |
violated_lock_dates = company._get_violated_lock_dates(start_date, True, journal) |
| 322 |
if violated_lock_dates: |
| 323 |
raise ValidationError(_("You cannot create a session starting before: %(lock_date_info)s", |
| 324 |
lock_date_info=self.env['res.company']._format_lock_dates(violated_lock_dates))) |
| 325 |
|
| 326 |
def _check_invoices_are_posted(self): |
| 327 |
unposted_invoices = self._get_closed_orders().sudo().with_company(self.company_id).account_move.filtered(lambda x: x.state != 'posted') |
| 328 |
if unposted_invoices: |
| 329 |
raise UserError(_( |
| 330 |
'You cannot close the POS when invoices are not posted.\nInvoices: %s', |
| 331 |
'\n'.join(f'{invoice.name} - {invoice.state}' for invoice in unposted_invoices) |
| 332 |
)) |
| 333 |
|
| 334 |
@api.model_create_multi |
| 335 |
def create(self, vals_list): |
| 336 |
for vals in vals_list: |
| 337 |
config_id = vals.get('config_id') or self.env.context.get('default_config_id') |
| 338 |
if not config_id: |
| 339 |
raise UserError(_("You should assign a Point of Sale to your session.")) |
| 340 |
|
| 341 |
# journal_id is not required on the pos_config because it does not |
| 342 |
# exists at the installation. If nothing is configured at the |
| 343 |
# installation we do the minimal configuration. Impossible to do in |
| 344 |
# the .xml files as the CoA is not yet installed. |
| 345 |
pos_config = self.env['pos.config'].browse(config_id) |
| 346 |
|
| 347 |
update_stock_at_closing = pos_config.company_id.point_of_sale_update_stock_quantities == "closing" |
| 348 |
|
| 349 |
vals.update({ |
| 350 |
'config_id': config_id, |
| 351 |
'update_stock_at_closing': update_stock_at_closing, |
| 352 |
}) |
| 353 |
|
| 354 |
if self.env.user.has_group('point_of_sale.group_pos_user'): |
| 355 |
sessions = super(PosSession, self.sudo()).create(vals_list) |
| 356 |
else: |
| 357 |
sessions = super().create(vals_list) |
| 358 |
|
| 359 |
sessions.action_pos_session_open() |
| 360 |
return sessions |
| 361 |
|
| 362 |
def unlink(self): |
| 363 |
self.statement_line_ids.unlink() |
| 364 |
return super().unlink() |
| 365 |
|
| 366 |
def action_pos_session_open(self): |
| 367 |
# we only open sessions that haven't already been opened |
| 368 |
for session in self.filtered(lambda session: session.state == 'opening_control'): |
| 369 |
values = {} |
| 370 |
if session.config_id.cash_control and not session.rescue: |
| 371 |
last_session = self.search([('config_id', '=', session.config_id.id), ('id', '!=', session.id)], limit=1) |
| 372 |
session.cash_register_balance_start = last_session.cash_register_balance_end_real # defaults to 0 if lastsession is empty |
| 373 |
session.write(values) |
| 374 |
return True |
| 375 |
|
| 376 |
def get_session_orders(self): |
| 377 |
return self.order_ids.filtered(lambda o: |
| 378 |
not (o.preset_time and o.preset_time.date() > fields.Date.today()) |
| 379 |
) |
| 380 |
|
| 381 |
def action_pos_session_closing_control(self, balancing_account=False, amount_to_balance=0, bank_payment_method_diffs=None): |
| 382 |
bank_payment_method_diffs = bank_payment_method_diffs or {} |
| 383 |
for session in self: |
| 384 |
if any(order.state == 'draft' for order in self.get_session_orders()): |
| 385 |
raise UserError(_("You cannot close the POS while there are still draft orders for the day.")) |
| 386 |
if session.state == 'closed': |
| 387 |
raise UserError(_('This session is already closed.')) |
| 388 |
stop_at = self.stop_at or fields.Datetime.now() |
| 389 |
session.write({'state': 'closing_control', 'stop_at': stop_at}) |
| 390 |
if not session.config_id.cash_control: |
| 391 |
return session.action_pos_session_close(balancing_account, amount_to_balance, bank_payment_method_diffs) |
| 392 |
# If the session is in rescue, we only compute the payments in the cash register |
| 393 |
# It is not yet possible to close a rescue session through the front end, see `close_session_from_ui` |
| 394 |
if session.rescue and session.config_id.cash_control: |
| 395 |
default_cash_payment_method_id = self.payment_method_ids.filtered(lambda pm: pm.type == 'cash')[0] |
| 396 |
orders = self._get_closed_orders() |
| 397 |
total_cash = sum( |
| 398 |
orders.payment_ids.filtered(lambda p: p.payment_method_id == default_cash_payment_method_id).mapped('amount') |
| 399 |
) + self.cash_register_balance_start |
| 400 |
|
| 401 |
session.cash_register_balance_end_real = total_cash |
| 402 |
|
| 403 |
return session.action_pos_session_validate(balancing_account, amount_to_balance, bank_payment_method_diffs) |
| 404 |
|
| 405 |
|
| 406 |
def action_pos_session_validate(self, balancing_account=False, amount_to_balance=0, bank_payment_method_diffs=None): |
| 407 |
bank_payment_method_diffs = bank_payment_method_diffs or {} |
| 408 |
return self.action_pos_session_close(balancing_account, amount_to_balance, bank_payment_method_diffs) |
| 409 |
|
| 410 |
def action_pos_session_close(self, balancing_account=False, amount_to_balance=0, bank_payment_method_diffs=None): |
| 411 |
bank_payment_method_diffs = bank_payment_method_diffs or {} |
| 412 |
# Session without cash payment method will not have a cash register. |
| 413 |
# However, there could be other payment methods, thus, session still |
| 414 |
# needs to be validated. |
| 415 |
return self._validate_session(balancing_account, amount_to_balance, bank_payment_method_diffs) |
| 416 |
|
| 417 |
def _validate_session(self, balancing_account=False, amount_to_balance=0, bank_payment_method_diffs=None): |
| 418 |
bank_payment_method_diffs = bank_payment_method_diffs or {} |
| 419 |
record = self.ensure_one() |
| 420 |
if self.env.user.has_group('point_of_sale.group_pos_user'): |
| 421 |
record = record.sudo() |
| 422 |
data = {} |
| 423 |
if self.get_session_orders().filtered(lambda o: o.state != 'cancel') or self.sudo().statement_line_ids: |
| 424 |
self.cash_real_transaction = sum(self.sudo().statement_line_ids.mapped('amount')) |
| 425 |
if self.state == 'closed': |
| 426 |
raise UserError(_('This session is already closed.')) |
| 427 |
self._check_if_no_draft_orders() |
| 428 |
self._check_invoices_are_posted() |
| 429 |
cash_difference_before_statements = self.cash_register_difference |
| 430 |
if self.update_stock_at_closing: |
| 431 |
self._create_picking_at_end_of_session() |
| 432 |
self._get_closed_orders().filtered(lambda o: not o.is_total_cost_computed)._compute_total_cost_at_session_closing(self.picking_ids.move_ids) |
| 433 |
# when the user is POS, update the record in sudo |
| 434 |
data = record.with_company(record.company_id).with_context( |
| 435 |
check_move_validity=False, skip_invoice_sync=True |
| 436 |
)._create_account_move(balancing_account, amount_to_balance, bank_payment_method_diffs) |
| 437 |
|
| 438 |
balance = sum(record.move_id.line_ids.mapped('balance')) |
| 439 |
try: |
| 440 |
with self.move_id._check_balanced({'records': self.move_id.sudo()}): |
| 441 |
pass |
| 442 |
except UserError: |
| 443 |
# Creating the account move is just part of a big database transaction |
| 444 |
# when closing a session. There are other database changes that will happen |
| 445 |
# before attempting to create the account move, such as, creating the picking |
| 446 |
# records. |
| 447 |
# We don't, however, want them to be committed when the account move creation |
| 448 |
# failed; therefore, we need to roll back this transaction before showing the |
| 449 |
# close session wizard. |
| 450 |
self.env.cr.rollback() |
| 451 |
return self._close_session_action(balance) |
| 452 |
|
| 453 |
self.sudo()._post_statement_difference(cash_difference_before_statements) |
| 454 |
if record.move_id.line_ids: |
| 455 |
record.move_id.with_company(self.company_id)._post() |
| 456 |
# Set the uninvoiced orders' state to 'done' |
| 457 |
self.env['pos.order'].search([('session_id', '=', self.id), ('state', '=', 'paid')]).write({'state': 'done'}) |
| 458 |
else: |
| 459 |
record.move_id.sudo().unlink() |
| 460 |
self.sudo().with_company(self.company_id)._reconcile_account_move_lines(data) |
| 461 |
else: |
| 462 |
self.sudo()._post_statement_difference(self.cash_register_difference) |
| 463 |
|
| 464 |
if self.config_id.order_edit_tracking: |
| 465 |
edited_orders = self.get_session_orders().filtered(lambda o: o.is_edited) |
| 466 |
if len(edited_orders) > 0: |
| 467 |
body = _("Edited order(s) during the session:%s", |
| 468 |
Markup("<br/><ul>%s</ul>") % Markup().join(Markup("<li>%s</li>") % order._get_html_link() for order in edited_orders) |
| 469 |
) |
| 470 |
self.message_post(body=body) |
| 471 |
|
| 472 |
# Make sure to trigger reordering rules |
| 473 |
self.picking_ids.move_ids.sudo()._trigger_scheduler() |
| 474 |
|
| 475 |
self.write({'state': 'closed'}) |
| 476 |
self.env.flush_all() # ensure sale.report is up to date |
| 477 |
return True |
| 478 |
|
| 479 |
def _post_statement_difference(self, amount): |
| 480 |
if amount: |
| 481 |
if self.config_id.cash_control: |
| 482 |
st_line_vals = { |
| 483 |
'journal_id': self.cash_journal_id.id, |
| 484 |
'amount': amount, |
| 485 |
'date': self.statement_line_ids.sorted()[-1:].date or fields.Date.context_today(self), |
| 486 |
'pos_session_id': self.id, |
| 487 |
} |
| 488 |
|
| 489 |
if amount < 0.0: |
| 490 |
if not self.cash_journal_id.loss_account_id: |
| 491 |
raise UserError( |
| 492 |
_('Please go on the %s journal and define a Loss Account. This account will be used to record cash difference.', |
| 493 |
self.cash_journal_id.name)) |
| 494 |
|
| 495 |
st_line_vals['payment_ref'] = _("Cash difference observed during the counting (Loss) - closing") |
| 496 |
st_line_vals['counterpart_account_id'] = self.cash_journal_id.loss_account_id.id |
| 497 |
else: |
| 498 |
# self.cash_register_difference > 0.0 |
| 499 |
if not self.cash_journal_id.profit_account_id: |
| 500 |
raise UserError( |
| 501 |
_('Please go on the %s journal and define a Profit Account. This account will be used to record cash difference.', |
| 502 |
self.cash_journal_id.name)) |
| 503 |
|
| 504 |
st_line_vals['payment_ref'] = _("Cash difference observed during the counting (Profit) - closing") |
| 505 |
st_line_vals['counterpart_account_id'] = self.cash_journal_id.profit_account_id.id |
| 506 |
|
| 507 |
created_line = self.env['account.bank.statement.line'].with_context(no_retrieve_partner=True).create(st_line_vals) |
| 508 |
|
| 509 |
if created_line: |
| 510 |
created_line.move_id.message_post(body=_( |
| 511 |
"Related Session: %(link)s", |
| 512 |
link=self._get_html_link() |
| 513 |
)) |
| 514 |
|
| 515 |
def _close_session_action(self, amount_to_balance): |
| 516 |
# NOTE This can't handle `bank_payment_method_diffs` because there is no field in the wizard that can carry it. |
| 517 |
default_account = self._get_balancing_account() |
| 518 |
wizard = self.env['pos.close.session.wizard'].create({ |
| 519 |
'amount_to_balance': amount_to_balance, |
| 520 |
'account_id': default_account.id, |
| 521 |
'account_readonly': not self.env.user.has_group('account.group_account_readonly'), |
| 522 |
'message': _("There is a difference between the amounts to post and the amounts of the orders, it is probably caused by taxes or accounting configurations changes.") |
| 523 |
}) |
| 524 |
return { |
| 525 |
'name': _("Force Close Session"), |
| 526 |
'type': 'ir.actions.act_window', |
| 527 |
'view_mode': 'form', |
| 528 |
'res_model': 'pos.close.session.wizard', |
| 529 |
'res_id': wizard.id, |
| 530 |
'target': 'new', |
| 531 |
'context': {**self.env.context, 'active_ids': self.ids, 'active_model': 'pos.session'}, |
| 532 |
} |
| 533 |
|
| 534 |
def close_session_from_ui(self, bank_payment_method_diff_pairs=None): |
| 535 |
"""Calling this method will try to close the session. |
| 536 |
|
| 537 |
param bank_payment_method_diff_pairs: list[(int, float)] |
| 538 |
Pairs of payment_method_id and diff_amount which will be used to post |
| 539 |
loss/profit when closing the session. |
| 540 |
|
| 541 |
If successful, it returns {'successful': True} |
| 542 |
Otherwise, it returns {'successful': False, 'message': str, 'redirect': bool}. |
| 543 |
'redirect' is a boolean used to know whether we redirect the user to the back end or not. |
| 544 |
When necessary, error (i.e. UserError, AccessError) is raised which should redirect the user to the back end. |
| 545 |
""" |
| 546 |
bank_payment_method_diffs = dict(bank_payment_method_diff_pairs or []) |
| 547 |
self.ensure_one() |
| 548 |
# Even if this is called in `post_closing_cash_details`, we need to call this here too for case |
| 549 |
# where cash_control = False |
| 550 |
open_order_ids = self.get_session_orders().filtered(lambda o: o.state == 'draft').ids |
| 551 |
check_closing_session = self._cannot_close_session(bank_payment_method_diffs) |
| 552 |
if check_closing_session: |
| 553 |
check_closing_session['open_order_ids'] = open_order_ids |
| 554 |
return check_closing_session |
| 555 |
|
| 556 |
validate_result = self.action_pos_session_closing_control(bank_payment_method_diffs=bank_payment_method_diffs) |
| 557 |
|
| 558 |
# If an error is raised, the user will still be redirected to the back end to manually close the session. |
| 559 |
# If the return result is a dict, this means that normally we have a redirection or a wizard => we redirect the user |
| 560 |
if isinstance(validate_result, dict): |
| 561 |
# imbalance accounting entry |
| 562 |
return { |
| 563 |
'open_order_ids': open_order_ids, |
| 564 |
'successful': False, |
| 565 |
'message': validate_result.get('name'), |
| 566 |
'redirect': True |
| 567 |
} |
| 568 |
|
| 569 |
if self.env.user.email: |
| 570 |
self.post_close_register_message() |
| 571 |
return {'successful': True} |
| 572 |
|
| 573 |
def post_close_register_message(self): |
| 574 |
self.message_post(body=_('Closed Register')) |
| 575 |
|
| 576 |
def update_closing_control_state_session(self, notes): |
| 577 |
# Prevent closing the session again if it was already closed |
| 578 |
if self.state == 'closed': |
| 579 |
raise UserError(_('This session is already closed.')) |
| 580 |
# Prevent the session to be opened again. |
| 581 |
self.write({'state': 'closing_control', 'stop_at': fields.Datetime.now(), 'closing_notes': notes}) |
| 582 |
self._post_cash_details_message('Closing', self.cash_register_balance_end, self.cash_register_difference, notes) |
| 583 |
|
| 584 |
def post_closing_cash_details(self, counted_cash): |
| 585 |
""" |
| 586 |
Calling this method will try store the cash details during the session closing. |
| 587 |
|
| 588 |
:param counted_cash: float, the total cash the user counted from its cash register |
| 589 |
|
| 590 |
If successful, it returns ``{'successful': True}``. |
| 591 |
Otherwise, it returns ``{'successful': False, 'message': str, 'redirect': bool}`` where |
| 592 |
``'redirect'`` is a boolean used to know whether we redirect the user to the back end or not. |
| 593 |
When necessary, error (i.e. UserError, AccessError) is raised which should redirect the user to the back end. |
| 594 |
""" |
| 595 |
self.ensure_one() |
| 596 |
check_closing_session = self._cannot_close_session() |
| 597 |
if check_closing_session: |
| 598 |
open_order_ids = self.get_session_orders().filtered(lambda o: o.state == 'draft').ids |
| 599 |
check_closing_session['open_order_ids'] = open_order_ids |
| 600 |
return check_closing_session |
| 601 |
|
| 602 |
if not self.cash_journal_id: |
| 603 |
# The user is blocked anyway, this user error is mostly for developers that try to call this function |
| 604 |
raise UserError(_("There is no cash register in this session.")) |
| 605 |
|
| 606 |
self.cash_register_balance_end_real = counted_cash |
| 607 |
|
| 608 |
return {'successful': True} |
| 609 |
|
| 610 |
def _create_diff_account_move_for_split_payment_method(self, payment_method, diff_amount): |
| 611 |
self.ensure_one() |
| 612 |
|
| 613 |
get_diff_vals_result = self._get_diff_vals(payment_method.id, diff_amount) |
| 614 |
if not get_diff_vals_result: |
| 615 |
return |
| 616 |
|
| 617 |
source_vals, dest_vals = get_diff_vals_result |
| 618 |
diff_move = self.env['account.move'].create({ |
| 619 |
'journal_id': payment_method.journal_id.id, |
| 620 |
'date': fields.Date.context_today(self), |
| 621 |
'ref': self._get_diff_account_move_ref(payment_method), |
| 622 |
'line_ids': [Command.create(source_vals), Command.create(dest_vals)] |
| 623 |
}) |
| 624 |
diff_move._post() |
| 625 |
|
| 626 |
def _get_diff_account_move_ref(self, payment_method): |
| 627 |
return _('Closing difference in %(payment_method)s (%(session)s)', payment_method=payment_method.name, session=self.name) |
| 628 |
|
| 629 |
def _get_diff_vals(self, payment_method_id, diff_amount, outstanding_account=False): |
| 630 |
payment_method = self.env['pos.payment.method'].browse(payment_method_id) |
| 631 |
diff_compare_to_zero = self.currency_id.compare_amounts(diff_amount, 0) |
| 632 |
source_account = payment_method.outstanding_account_id or outstanding_account |
| 633 |
destination_account = self.env['account.account'] |
| 634 |
|
| 635 |
if (diff_compare_to_zero > 0): |
| 636 |
destination_account = payment_method.journal_id.profit_account_id |
| 637 |
elif (diff_compare_to_zero < 0): |
| 638 |
destination_account = payment_method.journal_id.loss_account_id |
| 639 |
|
| 640 |
if (diff_compare_to_zero == 0 or not source_account): |
| 641 |
return False |
| 642 |
|
| 643 |
amounts = self._update_amounts({'amount': 0, 'amount_converted': 0}, {'amount': diff_amount}, self.stop_at) |
| 644 |
source_vals = self._debit_amounts({'account_id': source_account.id}, amounts['amount'], amounts['amount_converted']) |
| 645 |
dest_vals = self._credit_amounts({'account_id': destination_account.id}, amounts['amount'], amounts['amount_converted']) |
| 646 |
return [source_vals, dest_vals] |
| 647 |
|
| 648 |
def _cannot_close_session(self, bank_payment_method_diffs=None): |
| 649 |
""" |
| 650 |
Add check in this method if you want to return or raise an error when trying to either post cash details |
| 651 |
or close the session. Raising an error will always redirect the user to the back end. |
| 652 |
It should return {'successful': False, 'message': str, 'redirect': bool} if we can't close the session |
| 653 |
""" |
| 654 |
bank_payment_method_diffs = bank_payment_method_diffs or {} |
| 655 |
if any(order.state == 'draft' for order in self.get_session_orders()): |
| 656 |
return {'successful': False, 'message': _("You cannot close the POS while there are still draft orders for the day."), 'redirect': False} |
| 657 |
if self.state == 'closed': |
| 658 |
return { |
| 659 |
'successful': False, |
| 660 |
'type': 'alert', |
| 661 |
'title': 'Session already closed', |
| 662 |
'message': _("The session has been already closed by another User. " |
| 663 |
"All sales completed in the meantime have been saved in a " |
| 664 |
"Rescue Session, which can be reviewed anytime and posted " |
| 665 |
"to Accounting from Point of Sale's dashboard."), |
| 666 |
'redirect': True |
| 667 |
} |
| 668 |
if bank_payment_method_diffs: |
| 669 |
no_loss_account = self.env['account.journal'] |
| 670 |
no_profit_account = self.env['account.journal'] |
| 671 |
for payment_method in self.env['pos.payment.method'].browse(bank_payment_method_diffs.keys()): |
| 672 |
journal = payment_method.journal_id |
| 673 |
compare_to_zero = self.currency_id.compare_amounts(bank_payment_method_diffs.get(payment_method.id), 0) |
| 674 |
if compare_to_zero == -1 and not journal.loss_account_id: |
| 675 |
no_loss_account |= journal |
| 676 |
elif compare_to_zero == 1 and not journal.profit_account_id: |
| 677 |
no_profit_account |= journal |
| 678 |
message = '' |
| 679 |
if no_loss_account: |
| 680 |
message += _("Need loss account for the following journals to post the lost amount: %s\n", ', '.join(no_loss_account.mapped('name'))) |
| 681 |
if no_profit_account: |
| 682 |
message += _("Need profit account for the following journals to post the gained amount: %s", ', '.join(no_profit_account.mapped('name'))) |
| 683 |
if message: |
| 684 |
return {'successful': False, 'message': message, 'redirect': False} |
| 685 |
|
| 686 |
def get_cash_in_out_list(self): |
| 687 |
if not self.env.user.has_group('point_of_sale.group_pos_user'): |
| 688 |
raise AccessError(_("You don't have the access rights to get the cash in/out list.")) |
| 689 |
cash_in_count = 0 |
| 690 |
cash_out_count = 0 |
| 691 |
cash_in_out_list = [] |
| 692 |
for cash_move in self.sudo().statement_line_ids.sorted('create_date'): |
| 693 |
if cash_move.amount > 0: |
| 694 |
cash_in_count += 1 |
| 695 |
name = f'Cash in {cash_in_count}' |
| 696 |
else: |
| 697 |
cash_out_count += 1 |
| 698 |
name = f'Cash out {cash_out_count}' |
| 699 |
cash_in_out_list.append({ |
| 700 |
'name': cash_move.payment_ref or name, |
| 701 |
'amount': cash_move.amount, |
| 702 |
'id': cash_move.id, |
| 703 |
'date': cash_move.create_date, |
| 704 |
'cashier_name': cash_move.partner_id.name, |
| 705 |
}) |
| 706 |
return cash_in_out_list |
| 707 |
|
| 708 |
def get_closing_control_data(self): |
| 709 |
if not self.env.user.has_group('point_of_sale.group_pos_user'): |
| 710 |
raise AccessError(_("You don't have the access rights to get the point of sale closing control data.")) |
| 711 |
self.ensure_one() |
| 712 |
orders = self._get_closed_orders() |
| 713 |
payments = orders.payment_ids.filtered(lambda p: p.payment_method_id.type != "pay_later") |
| 714 |
cash_payment_method_ids = self.payment_method_ids.filtered(lambda pm: pm.type == 'cash') |
| 715 |
default_cash_payment_method_id = cash_payment_method_ids[0] if cash_payment_method_ids else None |
| 716 |
default_cash_payments = payments.filtered(lambda p: p.payment_method_id == default_cash_payment_method_id) if default_cash_payment_method_id else [] |
| 717 |
total_default_cash_payment_amount = sum(default_cash_payments.mapped('amount')) if default_cash_payment_method_id else 0 |
| 718 |
non_cash_payment_method_ids = self.payment_method_ids - default_cash_payment_method_id if default_cash_payment_method_id else self.payment_method_ids |
| 719 |
non_cash_payments_grouped_by_method_id = {pm: orders.payment_ids.filtered(lambda p: p.payment_method_id == pm) for pm in non_cash_payment_method_ids} |
| 720 |
|
| 721 |
cash_in_out_list = self.get_cash_in_out_list() |
| 722 |
|
| 723 |
return { |
| 724 |
'orders_details': { |
| 725 |
'quantity': len(orders), |
| 726 |
'amount': sum(orders.mapped('amount_total')) |
| 727 |
}, |
| 728 |
'opening_notes': self.opening_notes, |
| 729 |
'default_cash_details': { |
| 730 |
'name': default_cash_payment_method_id.name, |
| 731 |
'amount': self.cash_register_balance_start |
| 732 |
+ total_default_cash_payment_amount |
| 733 |
+ sum(self.sudo().statement_line_ids.mapped('amount')), |
| 734 |
'opening': self.cash_register_balance_start, |
| 735 |
'payment_amount': total_default_cash_payment_amount, |
| 736 |
'moves': cash_in_out_list, |
| 737 |
'id': default_cash_payment_method_id.id |
| 738 |
} if default_cash_payment_method_id else {}, |
| 739 |
'non_cash_payment_methods': [{ |
| 740 |
'name': pm.name, |
| 741 |
'amount': sum(non_cash_payments_grouped_by_method_id[pm].mapped('amount')), |
| 742 |
'number': len(non_cash_payments_grouped_by_method_id[pm]), |
| 743 |
'id': pm.id, |
| 744 |
'type': pm.type, |
| 745 |
} for pm in non_cash_payment_method_ids], |
| 746 |
'is_manager': self.env.user.has_group("point_of_sale.group_pos_manager"), |
| 747 |
'amount_authorized_diff': self.config_id.amount_authorized_diff if self.config_id.set_maximum_difference else None |
| 748 |
} |
| 749 |
|
| 750 |
def _create_picking_at_end_of_session(self): |
| 751 |
self.ensure_one() |
| 752 |
lines_grouped_by_dest_location = {} |
| 753 |
picking_type = self.config_id.picking_type_id |
| 754 |
|
| 755 |
if not picking_type or not picking_type.default_location_dest_id: |
| 756 |
session_destination_id = self.env['stock.warehouse']._get_partner_locations()[0].id |
| 757 |
else: |
| 758 |
session_destination_id = picking_type.default_location_dest_id.id |
| 759 |
|
| 760 |
for order in self._get_closed_orders(): |
| 761 |
if order.company_id.anglo_saxon_accounting and order.is_invoiced or order.shipping_date: |
| 762 |
continue |
| 763 |
destination_id = order.partner_id.property_stock_customer.id or session_destination_id |
| 764 |
if destination_id in lines_grouped_by_dest_location: |
| 765 |
lines_grouped_by_dest_location[destination_id] |= order.lines |
| 766 |
else: |
| 767 |
lines_grouped_by_dest_location[destination_id] = order.lines |
| 768 |
|
| 769 |
for location_dest_id, lines in lines_grouped_by_dest_location.items(): |
| 770 |
pickings = self.env['stock.picking']._create_picking_from_pos_order_lines(location_dest_id, lines, picking_type) |
| 771 |
pickings.write({'pos_session_id': self.id, 'origin': self.name}) |
| 772 |
|
| 773 |
def _create_balancing_line(self, data, balancing_account, amount_to_balance): |
| 774 |
if not self.company_id.currency_id.is_zero(amount_to_balance): |
| 775 |
balancing_vals = self._prepare_balancing_line_vals(amount_to_balance, self.move_id, balancing_account) |
| 776 |
MoveLine = data.get('MoveLine') |
| 777 |
MoveLine.create(balancing_vals) |
| 778 |
return data |
| 779 |
|
| 780 |
def _prepare_balancing_line_vals(self, imbalance_amount, move, balancing_account): |
| 781 |
partial_vals = { |
| 782 |
'name': _('Difference at closing PoS session'), |
| 783 |
'account_id': balancing_account.id, |
| 784 |
'move_id': move.id, |
| 785 |
'partner_id': False, |
| 786 |
} |
| 787 |
# `imbalance_amount` is already in terms of company currency so it is the amount_converted |
| 788 |
# param when calling `_credit_amounts`. amount param will be the converted value of |
| 789 |
# `imbalance_amount` from company currency to the session currency. |
| 790 |
imbalance_amount_session = 0 |
| 791 |
if (not self.is_in_company_currency): |
| 792 |
imbalance_amount_session = self.company_id.currency_id._convert(imbalance_amount, self.currency_id, self.company_id, fields.Date.context_today(self)) |
| 793 |
return self._credit_amounts(partial_vals, imbalance_amount_session, imbalance_amount) |
| 794 |
|
| 795 |
def _get_balancing_account(self): |
| 796 |
return ( |
| 797 |
self.company_id.account_default_pos_receivable_account_id |
| 798 |
or self.env['res.partner']._fields['property_account_receivable_id'].get_company_dependent_fallback(self.env['res.partner']) |
| 799 |
or self.env['account.account'] |
| 800 |
) |
| 801 |
|
| 802 |
def _create_account_move(self, balancing_account=False, amount_to_balance=0, bank_payment_method_diffs=None): |
| 803 |
""" Create account.move and account.move.line records for this session. |
| 804 |
|
| 805 |
Side-effects include: |
| 806 |
- setting self.move_id to the created account.move record |
| 807 |
- reconciling cash receivable lines, invoice receivable lines and stock output lines |
| 808 |
""" |
| 809 |
account_move = self.env['account.move'].create({ |
| 810 |
'journal_id': self.config_id.journal_id.id, |
| 811 |
'date': fields.Date.context_today(self), |
| 812 |
'ref': self.name, |
| 813 |
}) |
| 814 |
self.write({'move_id': account_move.id}) |
| 815 |
|
| 816 |
data = {'bank_payment_method_diffs': bank_payment_method_diffs or {}} |
| 817 |
data = self._accumulate_amounts(data) |
| 818 |
data = self._create_non_reconciliable_move_lines(data) |
| 819 |
data = self._create_bank_payment_moves(data) |
| 820 |
data = self._create_pay_later_receivable_lines(data) |
| 821 |
data = self._create_cash_statement_lines_and_cash_move_lines(data) |
| 822 |
data = self._create_invoice_receivable_lines(data) |
| 823 |
data = self._create_stock_valuation_lines(data) |
| 824 |
if balancing_account and amount_to_balance: |
| 825 |
data = self._create_balancing_line(data, balancing_account, amount_to_balance) |
| 826 |
|
| 827 |
return data |
| 828 |
|
| 829 |
def _accumulate_amounts(self, data): |
| 830 |
# Accumulate the amounts for each accounting lines group |
| 831 |
# Each dict maps `key` -> `amounts`, where `key` is the group key. |
| 832 |
# E.g. `combine_receivables_bank` is derived from pos.payment records |
| 833 |
# in the self.order_ids with group key of the `payment_method_id` |
| 834 |
# field of the pos.payment record. |
| 835 |
AccountTax = self.env['account.tax'] |
| 836 |
amounts = lambda: {'amount': 0.0, 'amount_converted': 0.0} |
| 837 |
tax_amounts = lambda: {'amount': 0.0, 'amount_converted': 0.0, 'base_amount': 0.0, 'base_amount_converted': 0.0} |
| 838 |
split_receivables_bank = defaultdict(amounts) |
| 839 |
split_receivables_cash = defaultdict(amounts) |
| 840 |
split_receivables_pay_later = defaultdict(amounts) |
| 841 |
combine_receivables_bank = defaultdict(amounts) |
| 842 |
combine_receivables_cash = defaultdict(amounts) |
| 843 |
combine_receivables_pay_later = defaultdict(amounts) |
| 844 |
combine_invoice_receivables = defaultdict(amounts) |
| 845 |
split_invoice_receivables = defaultdict(amounts) |
| 846 |
sales = defaultdict(amounts) |
| 847 |
taxes = defaultdict(tax_amounts) |
| 848 |
stock_expense = defaultdict(amounts) |
| 849 |
stock_return = defaultdict(amounts) |
| 850 |
stock_valuation = defaultdict(amounts) |
| 851 |
rounding_difference = {'amount': 0.0, 'amount_converted': 0.0} |
| 852 |
# Track the receivable lines of the order's invoice payment moves for reconciliation |
| 853 |
# These receivable lines are reconciled to the corresponding invoice receivable lines |
| 854 |
# of this session's move_id. |
| 855 |
combine_inv_payment_receivable_lines = defaultdict(lambda: self.env['account.move.line']) |
| 856 |
split_inv_payment_receivable_lines = defaultdict(lambda: self.env['account.move.line']) |
| 857 |
pos_receivable_account = self.company_id.account_default_pos_receivable_account_id |
| 858 |
currency_rounding = self.currency_id.rounding |
| 859 |
closed_orders = self._get_closed_orders() |
| 860 |
for order in closed_orders: |
| 861 |
order_is_invoiced = order.is_invoiced |
| 862 |
for payment in order.payment_ids: |
| 863 |
amount = payment.amount |
| 864 |
if float_is_zero(amount, precision_rounding=currency_rounding): |
| 865 |
continue |
| 866 |
date = payment.payment_date |
| 867 |
payment_method = payment.payment_method_id |
| 868 |
is_split_payment = payment.payment_method_id.split_transactions |
| 869 |
payment_type = payment_method.type |
| 870 |
|
| 871 |
# If not pay_later, we create the receivable vals for both invoiced and uninvoiced orders. |
| 872 |
# Separate the split and aggregated payments. |
| 873 |
# Moreover, if the order is invoiced, we create the pos receivable vals that will balance the |
| 874 |
# pos receivable lines from the invoice payments. |
| 875 |
if payment_type != 'pay_later': |
| 876 |
if is_split_payment and payment_type == 'cash': |
| 877 |
split_receivables_cash[payment] = self._update_amounts(split_receivables_cash[payment], {'amount': amount}, date) |
| 878 |
elif not is_split_payment and payment_type == 'cash': |
| 879 |
combine_receivables_cash[payment_method] = self._update_amounts(combine_receivables_cash[payment_method], {'amount': amount}, date) |
| 880 |
elif is_split_payment and payment_type == 'bank': |
| 881 |
split_receivables_bank[payment] = self._update_amounts(split_receivables_bank[payment], {'amount': amount}, date) |
| 882 |
elif not is_split_payment and payment_type == 'bank': |
| 883 |
combine_receivables_bank[payment_method] = self._update_amounts(combine_receivables_bank[payment_method], {'amount': amount}, date) |
| 884 |
|
| 885 |
# Create the vals to create the pos receivables that will balance the pos receivables from invoice payment moves. |
| 886 |
if order_is_invoiced: |
| 887 |
if is_split_payment: |
| 888 |
split_inv_payment_receivable_lines[payment] |= payment.account_move_id.line_ids.filtered(lambda line: line.account_id == pos_receivable_account) |
| 889 |
split_invoice_receivables[payment] = self._update_amounts(split_invoice_receivables[payment], {'amount': payment.amount}, order.date_order) |
| 890 |
else: |
| 891 |
combine_inv_payment_receivable_lines[payment_method] |= payment.account_move_id.line_ids.filtered(lambda line: line.account_id == pos_receivable_account) |
| 892 |
combine_invoice_receivables[payment_method] = self._update_amounts(combine_invoice_receivables[payment_method], {'amount': payment.amount}, order.date_order) |
| 893 |
|
| 894 |
# If pay_later, we create the receivable lines. |
| 895 |
# if split, with partner |
| 896 |
# Otherwise, it's aggregated (combined) |
| 897 |
# But only do if order is *not* invoiced because no account move is created for pay later invoice payments. |
| 898 |
if payment_type == 'pay_later' and not order_is_invoiced: |
| 899 |
if is_split_payment: |
| 900 |
split_receivables_pay_later[payment] = self._update_amounts(split_receivables_pay_later[payment], {'amount': amount}, date) |
| 901 |
elif not is_split_payment: |
| 902 |
combine_receivables_pay_later[payment_method] = self._update_amounts(combine_receivables_pay_later[payment_method], {'amount': amount}, date) |
| 903 |
|
| 904 |
if not order_is_invoiced: |
| 905 |
base_lines = order.with_context(linked_to_pos=True)._prepare_tax_base_line_values() |
| 906 |
AccountTax._add_tax_details_in_base_lines(base_lines, order.company_id) |
| 907 |
AccountTax._round_base_lines_tax_details(base_lines, order.company_id) |
| 908 |
AccountTax._add_accounting_data_in_base_lines_tax_details(base_lines, order.company_id, include_caba_tags=True) |
| 909 |
tax_results = AccountTax._prepare_tax_lines(base_lines, order.company_id) |
| 910 |
total_amount_currency = 0.0 |
| 911 |
for base_line, to_update in tax_results['base_lines_to_update']: |
| 912 |
# Combine sales/refund lines |
| 913 |
sale_vals_dict = self._get_sale_key(base_line) |
| 914 |
sale_key = frozendict(sale_vals_dict) |
| 915 |
total_amount_currency += to_update['amount_currency'] |
| 916 |
sales[sale_key] = self._update_amounts( |
| 917 |
sales[sale_key], |
| 918 |
{ |
| 919 |
'amount': to_update['amount_currency'], |
| 920 |
'amount_converted': to_update['balance'], |
| 921 |
}, |
| 922 |
order.date_order, |
| 923 |
) |
| 924 |
if self.config_id._is_quantities_set(): |
| 925 |
sales[sale_key].setdefault('quantity', 0) |
| 926 |
sales[sale_key]['quantity'] += base_line['quantity'] |
| 927 |
|
| 928 |
# Combine tax lines |
| 929 |
for tax_line in tax_results['tax_lines_to_add']: |
| 930 |
tax_key = ( |
| 931 |
tax_line['account_id'], |
| 932 |
tax_line['tax_repartition_line_id'], |
| 933 |
tuple(tax_line['tax_tag_ids'][0][2]), |
| 934 |
) |
| 935 |
total_amount_currency += tax_line['amount_currency'] |
| 936 |
taxes[tax_key] = self._update_amounts( |
| 937 |
taxes[tax_key], |
| 938 |
{ |
| 939 |
'amount': tax_line['amount_currency'], |
| 940 |
'amount_converted': tax_line['balance'], |
| 941 |
'base_amount': tax_line['tax_base_amount'] |
| 942 |
}, |
| 943 |
order.date_order, |
| 944 |
) |
| 945 |
|
| 946 |
if self.config_id.cash_rounding: |
| 947 |
diff = order.amount_paid + total_amount_currency |
| 948 |
rounding_difference = self._update_amounts(rounding_difference, {'amount': diff}, order.date_order) |
| 949 |
|
| 950 |
# Increasing current partner's customer_rank |
| 951 |
partners = (order.partner_id | order.partner_id.commercial_partner_id) |
| 952 |
partners._increase_rank('customer_rank') |
| 953 |
|
| 954 |
if self.company_id.inventory_valuation == 'real_time': |
| 955 |
all_picking_ids = self.order_ids.filtered(lambda p: not p.is_invoiced and not p.shipping_date).picking_ids.ids + self.picking_ids.filtered(lambda p: not p.pos_order_id).ids |
| 956 |
if all_picking_ids: |
| 957 |
# Combine stock lines |
| 958 |
stock_move_sudo = self.env['stock.move'].sudo() |
| 959 |
stock_moves = stock_move_sudo.search([ |
| 960 |
('picking_id', 'in', all_picking_ids), |
| 961 |
('company_id.inventory_valuation', '=', 'real_time'), |
| 962 |
('product_id.categ_id.property_valuation', '=', 'real_time'), |
| 963 |
('product_id.is_storable', '=', True), |
| 964 |
]) |
| 965 |
for stock_moves_batch in split_every(PREFETCH_MAX, stock_moves._ids, stock_moves.browse): |
| 966 |
for move in stock_moves_batch: |
| 967 |
product_accounts = move.product_id._get_product_accounts() |
| 968 |
exp_key = product_accounts['expense'] |
| 969 |
stock_key = product_accounts['stock_valuation'] |
| 970 |
signed_product_qty = move.quantity |
| 971 |
if move._is_in(): |
| 972 |
signed_product_qty *= -1 |
| 973 |
amount = signed_product_qty * move._get_price_unit() |
| 974 |
stock_expense[exp_key] = self._update_amounts(stock_expense[exp_key], {'amount': amount}, move.picking_id.date_done, force_company_currency=True) |
| 975 |
if move._is_in(): |
| 976 |
stock_return[stock_key] = self._update_amounts(stock_return[stock_key], {'amount': amount}, move.picking_id.date_done, force_company_currency=True) |
| 977 |
else: |
| 978 |
stock_valuation[stock_key] = self._update_amounts(stock_valuation[stock_key], {'amount': amount}, move.picking_id.date_done, force_company_currency=True) |
| 979 |
|
| 980 |
MoveLine = self.env['account.move.line'].with_context(check_move_validity=False, skip_invoice_sync=True) |
| 981 |
|
| 982 |
data.update({ |
| 983 |
'taxes': taxes, |
| 984 |
'sales': sales, |
| 985 |
'stock_expense': stock_expense, |
| 986 |
'split_receivables_bank': split_receivables_bank, |
| 987 |
'combine_receivables_bank': combine_receivables_bank, |
| 988 |
'split_receivables_cash': split_receivables_cash, |
| 989 |
'combine_receivables_cash': combine_receivables_cash, |
| 990 |
'combine_invoice_receivables': combine_invoice_receivables, |
| 991 |
'split_receivables_pay_later': split_receivables_pay_later, |
| 992 |
'combine_receivables_pay_later': combine_receivables_pay_later, |
| 993 |
'stock_return': stock_return, |
| 994 |
'stock_valuation': stock_valuation, |
| 995 |
'combine_inv_payment_receivable_lines': combine_inv_payment_receivable_lines, |
| 996 |
'rounding_difference': rounding_difference, |
| 997 |
'MoveLine': MoveLine, |
| 998 |
'split_invoice_receivables': split_invoice_receivables, |
| 999 |
'split_inv_payment_receivable_lines': split_inv_payment_receivable_lines, |
| 1000 |
}) |
| 1001 |
return data |
| 1002 |
|
| 1003 |
def _create_non_reconciliable_move_lines(self, data): |
| 1004 |
# Create account.move.line records for |
| 1005 |
# - sales |
| 1006 |
# - taxes |
| 1007 |
# - stock expense |
| 1008 |
# - non-cash split receivables (not for automatic reconciliation) |
| 1009 |
# - non-cash combine receivables (not for automatic reconciliation) |
| 1010 |
taxes = data.get('taxes') |
| 1011 |
sales = data.get('sales') |
| 1012 |
stock_expense = data.get('stock_expense') |
| 1013 |
rounding_difference = data.get('rounding_difference') |
| 1014 |
MoveLine = data.get('MoveLine') |
| 1015 |
|
| 1016 |
tax_vals = [self._get_tax_vals(key, amounts['amount'], amounts['amount_converted'], amounts['base_amount_converted']) for key, amounts in taxes.items()] |
| 1017 |
# Check if all taxes lines have account_id assigned. If not, there are repartition lines of the tax that have no account_id. |
| 1018 |
tax_names_no_account = [line['name'] for line in tax_vals if not line['account_id']] |
| 1019 |
if tax_names_no_account: |
| 1020 |
raise UserError(_( |
| 1021 |
'Unable to close and validate the session.\n' |
| 1022 |
'Please set corresponding tax account in each repartition line of the following taxes: \n%s', |
| 1023 |
', '.join(tax_names_no_account) |
| 1024 |
)) |
| 1025 |
rounding_vals = [] |
| 1026 |
|
| 1027 |
if not float_is_zero(rounding_difference['amount'], precision_rounding=self.currency_id.rounding) or not float_is_zero(rounding_difference['amount_converted'], precision_rounding=self.currency_id.rounding): |
| 1028 |
rounding_vals = [self._get_rounding_difference_vals(rounding_difference['amount'], rounding_difference['amount_converted'])] |
| 1029 |
|
| 1030 |
MoveLine.create(tax_vals) |
| 1031 |
move_line_ids = MoveLine.create(list(starmap(self._get_sale_vals, sales.items()))) |
| 1032 |
for key, ml_id in zip(sales.keys(), move_line_ids.ids): |
| 1033 |
sales[key]['move_line_id'] = ml_id |
| 1034 |
MoveLine.create( |
| 1035 |
[self._get_stock_expense_vals(key, amounts['amount'], amounts['amount_converted']) for key, amounts in stock_expense.items()] |
| 1036 |
+ rounding_vals |
| 1037 |
) |
| 1038 |
|
| 1039 |
return data |
| 1040 |
|
| 1041 |
def _create_bank_payment_moves(self, data): |
| 1042 |
combine_receivables_bank = data.get('combine_receivables_bank') |
| 1043 |
split_receivables_bank = data.get('split_receivables_bank') |
| 1044 |
bank_payment_method_diffs = data.get('bank_payment_method_diffs') |
| 1045 |
MoveLine = data.get('MoveLine') |
| 1046 |
payment_method_to_receivable_lines = {} |
| 1047 |
payment_to_receivable_lines = {} |
| 1048 |
for payment_method, amounts in combine_receivables_bank.items(): |
| 1049 |
combine_receivable_line = MoveLine.create(self._get_combine_receivable_vals(payment_method, amounts['amount'], amounts['amount_converted'])) |
| 1050 |
payment_receivable_line = self._create_combine_account_payment(payment_method, amounts, diff_amount=bank_payment_method_diffs.get(payment_method.id) or 0) |
| 1051 |
payment_method_to_receivable_lines[payment_method] = combine_receivable_line | payment_receivable_line |
| 1052 |
|
| 1053 |
for payment, amounts in split_receivables_bank.items(): |
| 1054 |
split_receivable_line = MoveLine.create(self._get_split_receivable_vals(payment, amounts['amount'], amounts['amount_converted'])) |
| 1055 |
payment_receivable_line = self._create_split_account_payment(payment, amounts) |
| 1056 |
payment_to_receivable_lines[payment] = split_receivable_line | payment_receivable_line |
| 1057 |
|
| 1058 |
for bank_payment_method in self.payment_method_ids.filtered(lambda pm: pm.type == 'bank' and pm.split_transactions): |
| 1059 |
self._create_diff_account_move_for_split_payment_method(bank_payment_method, bank_payment_method_diffs.get(bank_payment_method.id) or 0) |
| 1060 |
|
| 1061 |
data['payment_method_to_receivable_lines'] = payment_method_to_receivable_lines |
| 1062 |
data['payment_to_receivable_lines'] = payment_to_receivable_lines |
| 1063 |
return data |
| 1064 |
|
| 1065 |
def _create_pay_later_receivable_lines(self, data): |
| 1066 |
MoveLine = data.get('MoveLine') |
| 1067 |
combine_receivables_pay_later = data.get('combine_receivables_pay_later') |
| 1068 |
split_receivables_pay_later = data.get('split_receivables_pay_later') |
| 1069 |
vals = [] |
| 1070 |
for payment_method, amounts in combine_receivables_pay_later.items(): |
| 1071 |
vals.append(self._get_combine_receivable_vals(payment_method, amounts['amount'], amounts['amount_converted'])) |
| 1072 |
for payment, amounts in split_receivables_pay_later.items(): |
| 1073 |
vals.append(self._get_split_receivable_vals(payment, amounts['amount'], amounts['amount_converted'])) |
| 1074 |
for val in vals: |
| 1075 |
# Entries related to a `pay_later` payment method should not be excluded from follow-ups. |
| 1076 |
val['no_followup'] = False |
| 1077 |
data['pay_later_move_lines'] = MoveLine.create(vals) |
| 1078 |
return data |
| 1079 |
|
| 1080 |
def _create_combine_account_payment(self, payment_method, amounts, diff_amount): |
| 1081 |
outstanding_account = payment_method.outstanding_account_id |
| 1082 |
destination_account = self._get_receivable_account(payment_method) |
| 1083 |
|
| 1084 |
account_payment = self.env['account.payment'].with_context(pos_payment=True).create({ |
| 1085 |
'amount': abs(amounts['amount']), |
| 1086 |
'journal_id': payment_method.journal_id.id, |
| 1087 |
'force_outstanding_account_id': outstanding_account.id, |
| 1088 |
'destination_account_id': destination_account.id, |
| 1089 |
'memo': _('Combine %(payment_method)s POS payments from %(session)s', payment_method=payment_method.name, session=self.name), |
| 1090 |
'pos_payment_method_id': payment_method.id, |
| 1091 |
'pos_session_id': self.id, |
| 1092 |
'company_id': self.company_id.id, |
| 1093 |
}) |
| 1094 |
|
| 1095 |
# In community the outstanding account is computed on the creation of account.payment records |
| 1096 |
accounting_installed = self.env['account.move']._get_invoice_in_payment_state() == 'in_payment' |
| 1097 |
if not account_payment.outstanding_account_id and accounting_installed: |
| 1098 |
account_payment.outstanding_account_id = account_payment._get_outstanding_account(account_payment.payment_type) |
| 1099 |
|
| 1100 |
if float_compare(amounts['amount'], 0, precision_rounding=self.currency_id.rounding) < 0: |
| 1101 |
# revert the accounts because account.payment doesn't accept negative amount. |
| 1102 |
account_payment.write({ |
| 1103 |
'outstanding_account_id': account_payment.destination_account_id, |
| 1104 |
'destination_account_id': account_payment.outstanding_account_id, |
| 1105 |
'payment_type': 'outbound', |
| 1106 |
}) |
| 1107 |
|
| 1108 |
account_payment.action_post() |
| 1109 |
|
| 1110 |
diff_amount_compare_to_zero = self.currency_id.compare_amounts(diff_amount, 0) |
| 1111 |
if diff_amount_compare_to_zero != 0: |
| 1112 |
self._apply_diff_on_account_payment_move(account_payment, payment_method, diff_amount) |
| 1113 |
|
| 1114 |
return account_payment.move_id.line_ids.filtered(lambda line: line.account_id == self._get_receivable_account(payment_method)) |
| 1115 |
|
| 1116 |
def _apply_diff_on_account_payment_move(self, account_payment, payment_method, diff_amount): |
| 1117 |
diff_vals = self._get_diff_vals(payment_method.id, diff_amount, account_payment.outstanding_account_id) |
| 1118 |
if not diff_vals: |
| 1119 |
return |
| 1120 |
source_vals, dest_vals = diff_vals |
| 1121 |
outstanding_line = account_payment.move_id.line_ids.filtered(lambda line: line.account_id.id == source_vals['account_id']) |
| 1122 |
new_balance = outstanding_line.balance + self._amount_converter(diff_amount, self.stop_at, False) |
| 1123 |
new_balance_compare_to_zero = self.currency_id.compare_amounts(new_balance, 0) |
| 1124 |
account_payment.move_id.button_draft() |
| 1125 |
account_payment.move_id.write({ |
| 1126 |
'line_ids': [ |
| 1127 |
Command.create(dest_vals), |
| 1128 |
Command.update(outstanding_line.id, { |
| 1129 |
'debit': new_balance_compare_to_zero > 0 and new_balance or 0.0, |
| 1130 |
'credit': new_balance_compare_to_zero < 0 and -new_balance or 0.0 |
| 1131 |
}) |
| 1132 |
] |
| 1133 |
}) |
| 1134 |
account_payment.write({ |
| 1135 |
'amount': abs(new_balance), |
| 1136 |
}) |
| 1137 |
account_payment.move_id.action_post() |
| 1138 |
|
| 1139 |
def _create_split_account_payment(self, payment, amounts): |
| 1140 |
payment_method = payment.payment_method_id |
| 1141 |
if not payment_method.journal_id: |
| 1142 |
return self.env['account.move.line'] |
| 1143 |
outstanding_account = payment_method.outstanding_account_id |
| 1144 |
accounting_partner = self.env["res.partner"]._find_accounting_partner(payment.partner_id) |
| 1145 |
destination_account = accounting_partner.property_account_receivable_id |
| 1146 |
|
| 1147 |
if float_compare(amounts['amount'], 0, precision_rounding=self.currency_id.rounding) < 0: |
| 1148 |
# revert the accounts because account.payment doesn't accept negative amount. |
| 1149 |
outstanding_account, destination_account = destination_account, outstanding_account |
| 1150 |
|
| 1151 |
account_payment = self.env['account.payment'].create({ |
| 1152 |
'amount': abs(amounts['amount']), |
| 1153 |
'partner_id': accounting_partner.id, |
| 1154 |
'journal_id': payment_method.journal_id.id, |
| 1155 |
'force_outstanding_account_id': outstanding_account.id, |
| 1156 |
'destination_account_id': destination_account.id, |
| 1157 |
'memo': _('%(payment_method)s POS payment of %(partner)s in %(session)s', payment_method=payment_method.name, partner=payment.partner_id.display_name, session=self.name), |
| 1158 |
'pos_payment_method_id': payment_method.id, |
| 1159 |
'pos_session_id': self.id, |
| 1160 |
}) |
| 1161 |
account_payment.action_post() |
| 1162 |
return account_payment.move_id.line_ids.filtered(lambda line: line.account_id == accounting_partner.property_account_receivable_id) |
| 1163 |
|
| 1164 |
def _create_cash_statement_lines_and_cash_move_lines(self, data): |
| 1165 |
# Create the split and combine cash statement lines and account move lines. |
| 1166 |
# `split_cash_statement_lines` maps `journal` -> split cash statement lines |
| 1167 |
# `combine_cash_statement_lines` maps `journal` -> combine cash statement lines |
| 1168 |
# `split_cash_receivable_lines` maps `journal` -> split cash receivable lines |
| 1169 |
# `combine_cash_receivable_lines` maps `journal` -> combine cash receivable lines |
| 1170 |
MoveLine = data.get('MoveLine') |
| 1171 |
split_receivables_cash = data.get('split_receivables_cash') |
| 1172 |
combine_receivables_cash = data.get('combine_receivables_cash') |
| 1173 |
|
| 1174 |
# handle split cash payments |
| 1175 |
split_cash_statement_line_vals = [] |
| 1176 |
split_cash_receivable_vals = [] |
| 1177 |
for payment, amounts in split_receivables_cash.items(): |
| 1178 |
journal_id = payment.payment_method_id.journal_id |
| 1179 |
split_cash_statement_line_vals.append( |
| 1180 |
self._get_split_statement_line_vals( |
| 1181 |
journal_id, |
| 1182 |
amounts['amount'], |
| 1183 |
payment |
| 1184 |
) |
| 1185 |
) |
| 1186 |
split_cash_receivable_vals.append( |
| 1187 |
self._get_split_receivable_vals( |
| 1188 |
payment, |
| 1189 |
amounts['amount'], |
| 1190 |
amounts['amount_converted'] |
| 1191 |
) |
| 1192 |
) |
| 1193 |
# handle combine cash payments |
| 1194 |
combine_cash_statement_line_vals = [] |
| 1195 |
combine_cash_receivable_vals = [] |
| 1196 |
for payment_method, amounts in combine_receivables_cash.items(): |
| 1197 |
if not float_is_zero(amounts['amount'] , precision_rounding=self.currency_id.rounding): |
| 1198 |
combine_cash_statement_line_vals.append( |
| 1199 |
self._get_combine_statement_line_vals( |
| 1200 |
payment_method.journal_id, |
| 1201 |
amounts['amount'], |
| 1202 |
payment_method |
| 1203 |
) |
| 1204 |
) |
| 1205 |
combine_cash_receivable_vals.append( |
| 1206 |
self._get_combine_receivable_vals( |
| 1207 |
payment_method, |
| 1208 |
amounts['amount'], |
| 1209 |
amounts['amount_converted'] |
| 1210 |
) |
| 1211 |
) |
| 1212 |
|
| 1213 |
# create the statement lines and account move lines |
| 1214 |
BankStatementLine = self.env['account.bank.statement.line'].with_context(no_retrieve_partner=True) |
| 1215 |
split_cash_statement_lines = {} |
| 1216 |
combine_cash_statement_lines = {} |
| 1217 |
split_cash_receivable_lines = {} |
| 1218 |
combine_cash_receivable_lines = {} |
| 1219 |
split_cash_statement_lines = BankStatementLine.create(split_cash_statement_line_vals).mapped('move_id.line_ids').filtered(lambda line: line.account_id.account_type == 'asset_receivable') |
| 1220 |
combine_cash_statement_lines = BankStatementLine.create(combine_cash_statement_line_vals).mapped('move_id.line_ids').filtered(lambda line: line.account_id.account_type == 'asset_receivable') |
| 1221 |
split_cash_receivable_lines = MoveLine.create(split_cash_receivable_vals) |
| 1222 |
combine_cash_receivable_lines = MoveLine.create(combine_cash_receivable_vals) |
| 1223 |
|
| 1224 |
data.update( |
| 1225 |
{'split_cash_statement_lines': split_cash_statement_lines, |
| 1226 |
'combine_cash_statement_lines': combine_cash_statement_lines, |
| 1227 |
'split_cash_receivable_lines': split_cash_receivable_lines, |
| 1228 |
'combine_cash_receivable_lines': combine_cash_receivable_lines |
| 1229 |
}) |
| 1230 |
return data |
| 1231 |
|
| 1232 |
def _create_invoice_receivable_lines(self, data): |
| 1233 |
# Create invoice receivable lines for this session's move_id. |
| 1234 |
# Keep reference of the invoice receivable lines because |
| 1235 |
# they are reconciled with the lines in combine_inv_payment_receivable_lines |
| 1236 |
MoveLine = data.get('MoveLine') |
| 1237 |
combine_invoice_receivables = data.get('combine_invoice_receivables') |
| 1238 |
split_invoice_receivables = data.get('split_invoice_receivables') |
| 1239 |
|
| 1240 |
combine_invoice_receivable_vals = defaultdict(list) |
| 1241 |
split_invoice_receivable_vals = defaultdict(list) |
| 1242 |
combine_invoice_receivable_lines = {} |
| 1243 |
split_invoice_receivable_lines = {} |
| 1244 |
for payment_method, amounts in combine_invoice_receivables.items(): |
| 1245 |
combine_invoice_receivable_vals[payment_method].append(self._get_invoice_receivable_vals(amounts['amount'], amounts['amount_converted'])) |
| 1246 |
for payment, amounts in split_invoice_receivables.items(): |
| 1247 |
split_invoice_receivable_vals[payment].append(self._get_invoice_receivable_vals(amounts['amount'], amounts['amount_converted'])) |
| 1248 |
for payment_method, vals in combine_invoice_receivable_vals.items(): |
| 1249 |
receivable_lines = MoveLine.create(vals) |
| 1250 |
combine_invoice_receivable_lines[payment_method] = receivable_lines |
| 1251 |
for payment, vals in split_invoice_receivable_vals.items(): |
| 1252 |
receivable_lines = MoveLine.create(vals) |
| 1253 |
split_invoice_receivable_lines[payment] = receivable_lines |
| 1254 |
|
| 1255 |
data.update({'combine_invoice_receivable_lines': combine_invoice_receivable_lines}) |
| 1256 |
data.update({'split_invoice_receivable_lines': split_invoice_receivable_lines}) |
| 1257 |
return data |
| 1258 |
|
| 1259 |
def _create_stock_valuation_lines(self, data): |
| 1260 |
MoveLine = data.get('MoveLine') |
| 1261 |
stock_valuation = data.get('stock_valuation') |
| 1262 |
stock_return = data.get('stock_return') |
| 1263 |
|
| 1264 |
stock_valuation_vals = defaultdict(list) |
| 1265 |
stock_valuation_lines = {} |
| 1266 |
for stock_moves in [stock_valuation, stock_return]: |
| 1267 |
for account, amounts in stock_moves.items(): |
| 1268 |
stock_valuation_vals[account].append(self._get_stock_valuation_vals(account, amounts['amount'], amounts['amount_converted'])) |
| 1269 |
|
| 1270 |
for stock_valuation_acc, vals in stock_valuation_vals.items(): |
| 1271 |
stock_valuation_lines[stock_valuation_acc] = MoveLine.create(vals) |
| 1272 |
|
| 1273 |
data.update({'stock_valuation_lines': stock_valuation_lines}) |
| 1274 |
return data |
| 1275 |
|
| 1276 |
def _reconcile_account_move_lines(self, data): |
| 1277 |
# reconcile cash receivable lines |
| 1278 |
split_cash_statement_lines = data.get('split_cash_statement_lines') |
| 1279 |
combine_cash_statement_lines = data.get('combine_cash_statement_lines') |
| 1280 |
split_cash_receivable_lines = data.get('split_cash_receivable_lines') |
| 1281 |
combine_cash_receivable_lines = data.get('combine_cash_receivable_lines') |
| 1282 |
combine_inv_payment_receivable_lines = data.get('combine_inv_payment_receivable_lines') |
| 1283 |
split_inv_payment_receivable_lines = data.get('split_inv_payment_receivable_lines') |
| 1284 |
combine_invoice_receivable_lines = data.get('combine_invoice_receivable_lines') |
| 1285 |
split_invoice_receivable_lines = data.get('split_invoice_receivable_lines') |
| 1286 |
stock_output_lines = data.get('stock_output_lines') |
| 1287 |
payment_method_to_receivable_lines = data.get('payment_method_to_receivable_lines') |
| 1288 |
payment_to_receivable_lines = data.get('payment_to_receivable_lines') |
| 1289 |
|
| 1290 |
|
| 1291 |
all_lines = ( |
| 1292 |
split_cash_statement_lines |
| 1293 |
| combine_cash_statement_lines |
| 1294 |
| split_cash_receivable_lines |
| 1295 |
| combine_cash_receivable_lines |
| 1296 |
) |
| 1297 |
all_lines.filtered(lambda line: line.move_id.state != 'posted').move_id._post(soft=False) |
| 1298 |
|
| 1299 |
accounts = all_lines.mapped('account_id') |
| 1300 |
lines_by_account = [all_lines.filtered(lambda l: l.account_id == account and not l.reconciled) for account in accounts if account.reconcile] |
| 1301 |
for lines in lines_by_account: |
| 1302 |
lines.with_context(no_cash_basis=True).reconcile() |
| 1303 |
|
| 1304 |
|
| 1305 |
for payment_method, lines in payment_method_to_receivable_lines.items(): |
| 1306 |
receivable_account = self._get_receivable_account(payment_method) |
| 1307 |
if receivable_account.reconcile: |
| 1308 |
lines.filtered(lambda line: not line.reconciled).with_context(no_cash_basis=True).reconcile() |
| 1309 |
|
| 1310 |
for payment, lines in payment_to_receivable_lines.items(): |
| 1311 |
if payment.partner_id.property_account_receivable_id.reconcile: |
| 1312 |
lines.filtered(lambda line: not line.reconciled).with_context(no_cash_basis=True).reconcile() |
| 1313 |
|
| 1314 |
# Reconcile invoice payments' receivable lines. But we only do when the account is reconcilable. |
| 1315 |
# Though `account_default_pos_receivable_account_id` should be of type receivable, there is currently |
| 1316 |
# no constraint for it. Therefore, it is possible to put set a non-reconcilable account to it. |
| 1317 |
if self.company_id.account_default_pos_receivable_account_id.reconcile: |
| 1318 |
for payment_method in combine_inv_payment_receivable_lines: |
| 1319 |
lines = combine_inv_payment_receivable_lines[payment_method] | combine_invoice_receivable_lines.get(payment_method, self.env['account.move.line']) |
| 1320 |
lines.filtered(lambda line: not line.reconciled).with_context(no_cash_basis=True).reconcile() |
| 1321 |
|
| 1322 |
for payment in split_inv_payment_receivable_lines: |
| 1323 |
lines = split_inv_payment_receivable_lines[payment] | split_invoice_receivable_lines.get(payment, self.env['account.move.line']) |
| 1324 |
lines.filtered(lambda line: not line.reconciled).with_context(no_cash_basis=True).reconcile() |
| 1325 |
|
| 1326 |
return data |
| 1327 |
|
| 1328 |
def _get_rounding_difference_vals(self, amount, amount_converted): |
| 1329 |
if self.config_id.cash_rounding: |
| 1330 |
partial_args = { |
| 1331 |
'name': 'Rounding line', |
| 1332 |
'move_id': self.move_id.id, |
| 1333 |
} |
| 1334 |
if float_compare(0.0, amount, precision_rounding=self.currency_id.rounding) > 0: # loss |
| 1335 |
partial_args['account_id'] = self.config_id.rounding_method.loss_account_id.id |
| 1336 |
return self._debit_amounts(partial_args, -amount, -amount_converted) |
| 1337 |
|
| 1338 |
if float_compare(0.0, amount, precision_rounding=self.currency_id.rounding) < 0: # profit |
| 1339 |
partial_args['account_id'] = self.config_id.rounding_method.profit_account_id.id |
| 1340 |
return self._credit_amounts(partial_args, amount, amount_converted) |
| 1341 |
|
| 1342 |
def _get_split_receivable_vals(self, payment, amount, amount_converted): |
| 1343 |
accounting_partner = self.env["res.partner"]._find_accounting_partner(payment.partner_id) |
| 1344 |
if not accounting_partner: |
| 1345 |
raise UserError(_("You have enabled the \"Identify Customer\" option for %(payment_method)s payment method," |
| 1346 |
"but the order %(order)s does not contain a customer.", |
| 1347 |
payment_method=payment.payment_method_id.name, |
| 1348 |
order=payment.pos_order_id.name)) |
| 1349 |
partial_vals = { |
| 1350 |
'account_id': accounting_partner.property_account_receivable_id.id, |
| 1351 |
'move_id': self.move_id.id, |
| 1352 |
'partner_id': accounting_partner.id, |
| 1353 |
'name': '%s - %s' % (self.name, payment.payment_method_id.name), |
| 1354 |
} |
| 1355 |
return self._debit_amounts(partial_vals, amount, amount_converted) |
| 1356 |
|
| 1357 |
def _get_combine_receivable_vals(self, payment_method, amount, amount_converted): |
| 1358 |
partial_vals = { |
| 1359 |
'account_id': self._get_receivable_account(payment_method).id, |
| 1360 |
'move_id': self.move_id.id, |
| 1361 |
'name': '%s - %s' % (self.name, payment_method.name), |
| 1362 |
'display_type': 'payment_term', |
| 1363 |
} |
| 1364 |
return self._debit_amounts(partial_vals, amount, amount_converted) |
| 1365 |
|
| 1366 |
def _get_invoice_receivable_vals(self, amount, amount_converted): |
| 1367 |
partial_vals = { |
| 1368 |
'account_id': self.company_id.account_default_pos_receivable_account_id.id, |
| 1369 |
'move_id': self.move_id.id, |
| 1370 |
'name': _('From invoice payments'), |
| 1371 |
'display_type': 'payment_term', |
| 1372 |
} |
| 1373 |
return self._credit_amounts(partial_vals, amount, amount_converted) |
| 1374 |
|
| 1375 |
def _get_sale_key(self, base_line): |
| 1376 |
return { |
| 1377 |
# account |
| 1378 |
'account_id': base_line['account_id'].id, |
| 1379 |
# sign |
| 1380 |
'sign': -1 if base_line['is_refund'] else 1, |
| 1381 |
# for taxes |
| 1382 |
'tax_ids': tuple(base_line['record'].tax_ids_after_fiscal_position.flatten_taxes_hierarchy().ids), |
| 1383 |
'base_tag_ids': tuple(base_line['tax_tag_ids'].ids), |
| 1384 |
'product_id': base_line['product_id'].id if self.config_id.is_closing_entry_by_product else False, |
| 1385 |
} |
| 1386 |
|
| 1387 |
def _get_sale_vals(self, key, sale_vals): |
| 1388 |
tax_ids = key['tax_ids'] |
| 1389 |
product_id = key['product_id'] |
| 1390 |
sign = key['sign'] |
| 1391 |
applied_taxes = self.env['account.tax'].browse(tax_ids) |
| 1392 |
if product_id: |
| 1393 |
product = self.env['product.product'].browse(product_id) |
| 1394 |
product_name = product.display_name |
| 1395 |
product_uom = product.uom_id.id |
| 1396 |
else: |
| 1397 |
product_name = "" |
| 1398 |
product_uom = False |
| 1399 |
title = _('Sales') if sign == 1 else _('Refund') |
| 1400 |
name = _('%s untaxed', title) |
| 1401 |
if applied_taxes: |
| 1402 |
name = _('%(title)s %(product_name)s with %(taxes)s', title=title, product_name=product_name, taxes=', '.join([tax.name for tax in applied_taxes])) |
| 1403 |
partial_vals = { |
| 1404 |
'name': name, |
| 1405 |
'account_id': key['account_id'], |
| 1406 |
'move_id': self.move_id.id, |
| 1407 |
'tax_ids': [(6, 0, tax_ids)], |
| 1408 |
'tax_tag_ids': [(6, 0, key['base_tag_ids'])], |
| 1409 |
'product_id': product_id, |
| 1410 |
'display_type': 'product', |
| 1411 |
'product_uom_id': product_uom, |
| 1412 |
'currency_id': self.currency_id.id, |
| 1413 |
'amount_currency': sale_vals['amount'], |
| 1414 |
'balance': sale_vals['amount_converted'], |
| 1415 |
'quantity': sale_vals.get('quantity', 1.00) * key['sign'], |
| 1416 |
} |
| 1417 |
return partial_vals |
| 1418 |
|
| 1419 |
def _get_tax_vals(self, key, amount, amount_converted, base_amount_converted): |
| 1420 |
account_id, repartition_line_id, tag_ids = key |
| 1421 |
tax_rep = self.env['account.tax.repartition.line'].browse(repartition_line_id) |
| 1422 |
tax = tax_rep.tax_id |
| 1423 |
return { |
| 1424 |
'name': tax.name, |
| 1425 |
'account_id': account_id, |
| 1426 |
'move_id': self.move_id.id, |
| 1427 |
'tax_base_amount': abs(base_amount_converted), |
| 1428 |
'tax_repartition_line_id': repartition_line_id, |
| 1429 |
'tax_tag_ids': [(6, 0, tag_ids)], |
| 1430 |
'display_type': 'tax', |
| 1431 |
'currency_id': self.currency_id.id, |
| 1432 |
'amount_currency': amount, |
| 1433 |
'balance': amount_converted, |
| 1434 |
} |
| 1435 |
|
| 1436 |
def _get_stock_expense_vals(self, exp_account, amount, amount_converted): |
| 1437 |
partial_args = {'account_id': exp_account.id, 'move_id': self.move_id.id} |
| 1438 |
return self._debit_amounts(partial_args, amount, amount_converted, force_company_currency=True) |
| 1439 |
|
| 1440 |
def _get_stock_valuation_vals(self, stock_val_account, amount, amount_converted): |
| 1441 |
partial_args = {'account_id': stock_val_account.id, 'move_id': self.move_id.id} |
| 1442 |
return self._credit_amounts(partial_args, amount, amount_converted, force_company_currency=True) |
| 1443 |
|
| 1444 |
def _get_combine_statement_line_vals(self, journal, amount, payment_method): |
| 1445 |
amount_values = self._prepare_statement_line_amount_values(journal, amount) |
| 1446 |
return { |
| 1447 |
'date': fields.Date.context_today(self), |
| 1448 |
'payment_ref': self.name, |
| 1449 |
'pos_session_id': self.id, |
| 1450 |
'journal_id': journal.id, |
| 1451 |
'counterpart_account_id': self._get_receivable_account(payment_method).id, |
| 1452 |
**amount_values |
| 1453 |
} |
| 1454 |
|
| 1455 |
def _get_split_statement_line_vals(self, journal, amount, payment): |
| 1456 |
accounting_partner = self.env["res.partner"]._find_accounting_partner(payment.partner_id) |
| 1457 |
amount_values = self._prepare_statement_line_amount_values(journal, amount) |
| 1458 |
return { |
| 1459 |
'date': fields.Date.context_today(self, timestamp=payment.payment_date), |
| 1460 |
'payment_ref': payment.name, |
| 1461 |
'pos_session_id': self.id, |
| 1462 |
'journal_id': journal.id, |
| 1463 |
'counterpart_account_id': accounting_partner.property_account_receivable_id.id, |
| 1464 |
'partner_id': accounting_partner.id, |
| 1465 |
**amount_values |
| 1466 |
} |
| 1467 |
|
| 1468 |
def _prepare_statement_line_amount_values(self, journal, amount): |
| 1469 |
journal_currency = journal.currency_id or self.company_id.currency_id |
| 1470 |
if journal_currency == self.currency_id: |
| 1471 |
return {'amount': amount} |
| 1472 |
return { |
| 1473 |
'amount': self.currency_id._convert(amount, journal_currency, self.company_id, self.stop_at), |
| 1474 |
'amount_currency': amount, |
| 1475 |
'foreign_currency_id': self.currency_id.id, |
| 1476 |
} |
| 1477 |
|
| 1478 |
def _update_amounts(self, old_amounts, amounts_to_add, date, round=True, force_company_currency=False): |
| 1479 |
"""Responsible for adding `amounts_to_add` to `old_amounts` considering the currency of the session. |
| 1480 |
|
| 1481 |
old_amounts { new_amounts { |
| 1482 |
amount amounts_to_add { amount |
| 1483 |
amount_converted + amount -> amount_converted |
| 1484 |
[base_amount [base_amount] [base_amount |
| 1485 |
base_amount_converted] } base_amount_converted] |
| 1486 |
} } |
| 1487 |
|
| 1488 |
NOTE: |
| 1489 |
- Notice that `amounts_to_add` does not have `amount_converted` field. |
| 1490 |
This function is responsible in calculating the `amount_converted` from the |
| 1491 |
`amount` of `amounts_to_add` which is used to update the values of `old_amounts`. |
| 1492 |
- Values of `amount` and/or `base_amount` should always be in session's currency [1]. |
| 1493 |
- Value of `amount_converted` should be in company's currency |
| 1494 |
|
| 1495 |
[1] Except when `force_company_currency` = True. It means that values in `amounts_to_add` |
| 1496 |
is in company currency. |
| 1497 |
|
| 1498 |
:param dict old_amounts: |
| 1499 |
Amounts to update |
| 1500 |
:param dict amounts_to_add: |
| 1501 |
Amounts used to update the old_amounts |
| 1502 |
:param date date: |
| 1503 |
Date used for conversion |
| 1504 |
:param bool round: |
| 1505 |
Same as round parameter of `res.currency._convert`. |
| 1506 |
Defaults to True because that is the default of `res.currency._convert`. |
| 1507 |
We put it to False if we want to round globally. |
| 1508 |
:param bool force_company_currency: |
| 1509 |
If True, the values in amounts_to_add are in company's currency. |
| 1510 |
Defaults to False because it is only used to anglo-saxon lines. |
| 1511 |
|
| 1512 |
:returns: new amounts combining the values of `old_amounts` and `amounts_to_add`. |
| 1513 |
:rtype: dict |
| 1514 |
""" |
| 1515 |
# make a copy of the old amounts |
| 1516 |
new_amounts = { **old_amounts } |
| 1517 |
|
| 1518 |
amount = amounts_to_add.get('amount') |
| 1519 |
if self.is_in_company_currency or force_company_currency: |
| 1520 |
amount_converted = amount |
| 1521 |
else: |
| 1522 |
amount_converted = self._amount_converter(amount, date, round) |
| 1523 |
|
| 1524 |
# update amount and amount converted |
| 1525 |
new_amounts['amount'] += amount |
| 1526 |
new_amounts['amount_converted'] += amount_converted |
| 1527 |
|
| 1528 |
# consider base_amount if present |
| 1529 |
|
| 1530 |
if amounts_to_add.get('base_amount'): |
| 1531 |
base_amount = amounts_to_add.get('base_amount') |
| 1532 |
|
| 1533 |
# update base_amount and base_amount_converted |
| 1534 |
new_amounts['base_amount'] += base_amount |
| 1535 |
new_amounts['base_amount_converted'] += base_amount |
| 1536 |
|
| 1537 |
return new_amounts |
| 1538 |
|
| 1539 |
def _round_amounts(self, amounts): |
| 1540 |
new_amounts = {} |
| 1541 |
for key, amount in amounts.items(): |
| 1542 |
if key == 'amount_converted': |
| 1543 |
# round the amount_converted using the company currency. |
| 1544 |
new_amounts[key] = self.company_id.currency_id.round(amount) |
| 1545 |
else: |
| 1546 |
new_amounts[key] = self.currency_id.round(amount) |
| 1547 |
return new_amounts |
| 1548 |
|
| 1549 |
def _credit_amounts(self, partial_move_line_vals, amount, amount_converted, force_company_currency=False): |
| 1550 |
""" `partial_move_line_vals` is completed by `credit`ing the given amounts. |
| 1551 |
|
| 1552 |
NOTE Amounts in PoS are in the currency of journal_id in the session.config_id. |
| 1553 |
This means that amount fields in any pos record are actually equivalent to amount_currency |
| 1554 |
in account module. Understanding this basic is important in correctly assigning values for |
| 1555 |
'amount' and 'amount_currency' in the account.move.line record. |
| 1556 |
|
| 1557 |
:param dict partial_move_line_vals: |
| 1558 |
initial values in creating account.move.line |
| 1559 |
:param float amount: |
| 1560 |
amount derived from pos.payment, pos.order, or pos.order.line records |
| 1561 |
:param float amount_converted: |
| 1562 |
converted value of `amount` from the given `session_currency` to company currency |
| 1563 |
|
| 1564 |
:return: complete values for creating 'amount.move.line' record |
| 1565 |
:rtype: dict |
| 1566 |
""" |
| 1567 |
if self.is_in_company_currency or force_company_currency: |
| 1568 |
additional_field = {} |
| 1569 |
else: |
| 1570 |
additional_field = { |
| 1571 |
'amount_currency': -amount, |
| 1572 |
'currency_id': self.currency_id.id, |
| 1573 |
} |
| 1574 |
return { |
| 1575 |
'debit': -amount_converted if amount_converted < 0.0 else 0.0, |
| 1576 |
'credit': amount_converted if amount_converted > 0.0 else 0.0, |
| 1577 |
**partial_move_line_vals, |
| 1578 |
**additional_field, |
| 1579 |
} |
| 1580 |
|
| 1581 |
def _debit_amounts(self, partial_move_line_vals, amount, amount_converted, force_company_currency=False): |
| 1582 |
""" `partial_move_line_vals` is completed by `debit`ing the given amounts. |
| 1583 |
|
| 1584 |
See _credit_amounts docs for more details. |
| 1585 |
""" |
| 1586 |
if self.is_in_company_currency or force_company_currency: |
| 1587 |
additional_field = {} |
| 1588 |
else: |
| 1589 |
additional_field = { |
| 1590 |
'amount_currency': amount, |
| 1591 |
'currency_id': self.currency_id.id, |
| 1592 |
} |
| 1593 |
return { |
| 1594 |
'debit': amount_converted if amount_converted > 0.0 else 0.0, |
| 1595 |
'credit': -amount_converted if amount_converted < 0.0 else 0.0, |
| 1596 |
**partial_move_line_vals, |
| 1597 |
**additional_field, |
| 1598 |
} |
| 1599 |
|
| 1600 |
def _amount_converter(self, amount, date, round): |
| 1601 |
# self should be single record as this method is only called in the subfunctions of self._validate_session |
| 1602 |
return self.currency_id._convert(amount, self.company_id.currency_id, self.company_id, date, round=round) |
| 1603 |
|
| 1604 |
def show_cash_register(self): |
| 1605 |
return { |
| 1606 |
'name': _('Cash register'), |
| 1607 |
'type': 'ir.actions.act_window', |
| 1608 |
'res_model': 'account.bank.statement.line', |
| 1609 |
'view_mode': 'list,kanban', |
| 1610 |
'domain': [('id', 'in', self.statement_line_ids.ids)], |
| 1611 |
} |
| 1612 |
|
| 1613 |
def show_journal_items(self): |
| 1614 |
self.ensure_one() |
| 1615 |
all_related_moves = self._get_related_account_moves() |
| 1616 |
return { |
| 1617 |
'name': _('Journal Items'), |
| 1618 |
'type': 'ir.actions.act_window', |
| 1619 |
'res_model': 'account.move.line', |
| 1620 |
'view_mode': 'list', |
| 1621 |
'view_id':self.env.ref('account.view_move_line_tree').id, |
| 1622 |
'domain': [('id', 'in', all_related_moves.mapped('line_ids').ids)], |
| 1623 |
'context': { |
| 1624 |
'journal_type':'general', |
| 1625 |
'search_default_group_by_move': 1, |
| 1626 |
'group_by':'move_id', 'search_default_posted':1, |
| 1627 |
}, |
| 1628 |
} |
| 1629 |
|
| 1630 |
def _get_other_related_moves(self): |
| 1631 |
# TODO This is not an ideal way to get the diff account.move's for |
| 1632 |
# the session. It would be better if there is a relation field where |
| 1633 |
# these moves are saved. |
| 1634 |
|
| 1635 |
# Unfortunately, the 'ref' of account.move is not indexed, so |
| 1636 |
# we are querying over the account.move.line because its 'ref' is indexed. |
| 1637 |
# And yes, we are only concern for split bank payment methods. |
| 1638 |
diff_lines_ref = [self._get_diff_account_move_ref(pm) for pm in self.payment_method_ids if pm.type == 'bank' and pm.split_transactions] |
| 1639 |
cost_move_lines = ['pos_order_'+str(rec.id) for rec in self._get_closed_orders()] |
| 1640 |
return self.env['account.move.line'].search([('ref', 'in', diff_lines_ref + cost_move_lines)]).mapped('move_id') |
| 1641 |
|
| 1642 |
def _get_related_account_moves(self): |
| 1643 |
pickings = self.picking_ids | self._get_closed_orders().mapped('picking_ids') |
| 1644 |
invoices = self.mapped('order_ids.account_move') |
| 1645 |
invoice_payments = self.mapped('order_ids.payment_ids.account_move_id') |
| 1646 |
stock_account_moves = pickings.move_ids.account_move_id |
| 1647 |
cash_moves = self.statement_line_ids.mapped('move_id') |
| 1648 |
bank_payment_moves = self.bank_payment_ids.mapped('move_id') |
| 1649 |
other_related_moves = self._get_other_related_moves() |
| 1650 |
return invoices | invoice_payments | self.move_id | stock_account_moves | cash_moves | bank_payment_moves | other_related_moves |
| 1651 |
|
| 1652 |
def _get_receivable_account(self, payment_method): |
| 1653 |
"""Returns the default pos receivable account if no receivable_account_id is set on the payment method.""" |
| 1654 |
return payment_method.receivable_account_id or self.company_id.account_default_pos_receivable_account_id |
| 1655 |
|
| 1656 |
def action_show_payments_list(self): |
| 1657 |
return { |
| 1658 |
'name': _('Payments'), |
| 1659 |
'type': 'ir.actions.act_window', |
| 1660 |
'res_model': 'pos.payment', |
| 1661 |
'view_mode': 'list,form', |
| 1662 |
'domain': self._get_captured_payments_domain(), |
| 1663 |
'context': {'search_default_group_by_payment_method': 1} |
| 1664 |
} |
| 1665 |
|
| 1666 |
def _get_captured_payments_domain(self): |
| 1667 |
return [('session_id', 'in', self.ids), ('pos_order_id.state', 'in', ['paid', 'invoiced', 'done'])] |
| 1668 |
|
| 1669 |
def open_frontend_cb(self): |
| 1670 |
"""Open the pos interface with config_id as an extra argument. |
| 1671 |
|
| 1672 |
In vanilla PoS each user can only have one active session, therefore it was not needed to pass the config_id |
| 1673 |
on opening a session. It is also possible to login to sessions created by other users. |
| 1674 |
|
| 1675 |
:returns: dict |
| 1676 |
""" |
| 1677 |
if not self.ids: |
| 1678 |
return {} |
| 1679 |
return self.config_id.open_ui() |
| 1680 |
|
| 1681 |
def _set_opening_control_data(self, cashbox_value: int, notes: str): |
| 1682 |
""" |
| 1683 |
Internal logic for opening the session. |
| 1684 |
Inherit this method to add custom logic before the sequence is assigned. |
| 1685 |
""" |
| 1686 |
self.state = 'opened' |
| 1687 |
self.start_at = fields.Datetime.now() |
| 1688 |
cash_payment_method_ids = self.config_id.payment_method_ids.filtered(lambda pm: pm.is_cash_count) |
| 1689 |
if cash_payment_method_ids: |
| 1690 |
self.opening_notes = notes |
| 1691 |
difference = cashbox_value - self.cash_register_balance_start |
| 1692 |
self._post_cash_details_message('Opening cash', self.cash_register_balance_start, difference, notes) |
| 1693 |
self.cash_register_balance_start = cashbox_value |
| 1694 |
elif notes: |
| 1695 |
message = _('Opening control message: ') |
| 1696 |
message += notes |
| 1697 |
self.message_post(body=plaintext2html(message)) |
| 1698 |
|
| 1699 |
def set_opening_control(self, cashbox_value: int, notes: str): |
| 1700 |
""" |
| 1701 |
Public method to open the session. |
| 1702 |
This calls the internal logic and, if successful, assigns the sequence name. |
| 1703 |
|
| 1704 |
DO NOT INHERIT THIS METHOD. Inherit _set_opening_control_data instead. |
| 1705 |
""" |
| 1706 |
if self.state != 'opening_control': |
| 1707 |
return |
| 1708 |
|
| 1709 |
self._set_opening_control_data(cashbox_value, notes) |
| 1710 |
|
| 1711 |
sequence = self.env['ir.sequence'].with_context( |
| 1712 |
company_id=self.config_id.company_id.id |
| 1713 |
).search([('code', '=', 'pos.session'), ('company_id', 'in', [self.config_id.company_id.id, False])], order='company_id', limit=1) |
| 1714 |
|
| 1715 |
self.name = (self.config_id.name if sequence.prefix == '/' else '') + sequence.next_by_code('pos.session') + (self.name if self.name != '/' else '') |
| 1716 |
|
| 1717 |
def _post_cash_details_message(self, state, expected, difference, notes): |
| 1718 |
message = (state + " difference: " + self.currency_id.format(difference) + '\n' + |
| 1719 |
state + " expected: " + self.currency_id.format(expected) + '\n' + |
| 1720 |
state + " counted: " + self.currency_id.format(expected + difference) + '\n') |
| 1721 |
|
| 1722 |
if notes: |
| 1723 |
message += _('Opening control message: ') |
| 1724 |
message += notes |
| 1725 |
if message: |
| 1726 |
self.message_post(body=plaintext2html(message), email_from=self.env.user.email or "[email protected]") |
| 1727 |
|
| 1728 |
def action_view_order(self): |
| 1729 |
return { |
| 1730 |
'name': _('Orders'), |
| 1731 |
'res_model': 'pos.order', |
| 1732 |
'view_mode': 'list,form', |
| 1733 |
'views': [ |
| 1734 |
(self.env.ref('point_of_sale.view_pos_order_tree_no_session_id').id, 'list'), |
| 1735 |
(self.env.ref('point_of_sale.view_pos_pos_form').id, 'form'), |
| 1736 |
], |
| 1737 |
'type': 'ir.actions.act_window', |
| 1738 |
'domain': [('session_id', 'in', self.ids)], |
| 1739 |
} |
| 1740 |
|
| 1741 |
@api.model |
| 1742 |
def _alert_old_session(self): |
| 1743 |
# If the session is open for more then one week, |
| 1744 |
# log a next activity to close the session. |
| 1745 |
sessions = self.sudo().search([('start_at', '<=', (fields.Datetime.now() - timedelta(days=7))), ('state', '!=', 'closed')]) |
| 1746 |
for session in sessions: |
| 1747 |
if self.env['mail.activity'].search_count([('res_id', '=', session.id), ('res_model', '=', 'pos.session')]) == 0: |
| 1748 |
session.activity_schedule( |
| 1749 |
'point_of_sale.mail_activity_old_session', |
| 1750 |
user_id=session.user_id.id, |
| 1751 |
note=_( |
| 1752 |
"Your PoS Session is open since %(date)s, we advise you to close it and to create a new one.", |
| 1753 |
date=session.start_at, |
| 1754 |
) |
| 1755 |
) |
| 1756 |
|
| 1757 |
def _check_if_no_draft_orders(self): |
| 1758 |
draft_orders = self.get_session_orders().filtered(lambda order: order.state == 'draft') |
| 1759 |
if draft_orders: |
| 1760 |
raise UserError(_( |
| 1761 |
'There are still orders in draft state in the session. ' |
| 1762 |
'Pay or cancel the following orders to validate the session:\n%s', |
| 1763 |
', '.join(draft_orders.mapped('name')) |
| 1764 |
)) |
| 1765 |
return True |
| 1766 |
|
| 1767 |
def _prepare_account_bank_statement_line_vals(self, session, sign, amount, reason, partner_id, extras): |
| 1768 |
return { |
| 1769 |
'pos_session_id': session.id, |
| 1770 |
'journal_id': session.cash_journal_id.id, |
| 1771 |
'amount': sign * amount, |
| 1772 |
'date': fields.Date.context_today(self), |
| 1773 |
'payment_ref': '-'.join([session.name, extras['translatedType'], reason]), |
| 1774 |
'partner_id': partner_id, |
| 1775 |
} |
| 1776 |
|
| 1777 |
def try_cash_in_out(self, _type, amount, reason, partner_id, extras): |
| 1778 |
sign = 1 if _type == 'in' else -1 |
| 1779 |
sessions = self.filtered('cash_journal_id') |
| 1780 |
if not sessions: |
| 1781 |
raise UserError(_("There is no cash payment method for this PoS Session")) |
| 1782 |
|
| 1783 |
vals_list = [ |
| 1784 |
self._prepare_account_bank_statement_line_vals(session, sign, amount, reason, partner_id, extras) |
| 1785 |
for session in sessions |
| 1786 |
] |
| 1787 |
|
| 1788 |
self.env['account.bank.statement.line'].with_context(no_retrieve_partner=True).create(vals_list) |
| 1789 |
|
| 1790 |
def delete_cash_in_out(self, absl_id, partner_id): |
| 1791 |
if not self.env.user.has_group('account.group_account_basic'): |
| 1792 |
raise AccessError(_("You don't have the access rights to delete a cash in/out.")) |
| 1793 |
absl = self.env['account.bank.statement.line'].browse(absl_id) |
| 1794 |
if absl not in self.statement_line_ids: |
| 1795 |
raise AccessError(_("You cannot delete a cash move that is not linked to this session.")) |
| 1796 |
cashier_name = absl.partner_id.name |
| 1797 |
amount = absl.amount |
| 1798 |
action = cashier_name + ': ' + str(amount) |
| 1799 |
absl.unlink() |
| 1800 |
self.log_partner_message(partner_id, action, "CASH_IN_OUT_UNLINK") |
| 1801 |
|
| 1802 |
def _get_attributes_by_ptal_id(self): |
| 1803 |
# performance trick: prefetch fields with search_fetch() and fetch() |
| 1804 |
product_attributes = self.env['product.attribute'].search_fetch( |
| 1805 |
[('create_variant', '=', 'no_variant')], |
| 1806 |
['name', 'display_type'], |
| 1807 |
) |
| 1808 |
product_template_attribute_values = self.env['product.template.attribute.value'].search_fetch( |
| 1809 |
[('attribute_id', 'in', product_attributes.ids)], |
| 1810 |
['attribute_id', 'attribute_line_id', 'product_attribute_value_id', 'price_extra'], |
| 1811 |
) |
| 1812 |
product_template_attribute_values.product_attribute_value_id.fetch(['name', 'is_custom', 'html_color', 'image']) |
| 1813 |
|
| 1814 |
key1 = lambda ptav: (ptav.attribute_line_id.id, ptav.attribute_id.id) |
| 1815 |
key2 = lambda ptav: (ptav.attribute_line_id.id, ptav.attribute_id) |
| 1816 |
res = {} |
| 1817 |
for key, group in groupby(sorted(product_template_attribute_values, key=key1), key=key2): |
| 1818 |
attribute_line_id, attribute = key |
| 1819 |
values = [{**ptav.product_attribute_value_id.read(['name', 'is_custom', 'html_color', 'image'])[0], |
| 1820 |
'price_extra': ptav.price_extra, |
| 1821 |
# id of a value should be from the "product.template.attribute.value" record |
| 1822 |
'id': ptav.id, |
| 1823 |
} for ptav in list(group)] |
| 1824 |
res[attribute_line_id] = { |
| 1825 |
'id': attribute_line_id, |
| 1826 |
'name': attribute.name, |
| 1827 |
'display_type': attribute.display_type, |
| 1828 |
'values': values, |
| 1829 |
'sequence': attribute.sequence, |
| 1830 |
} |
| 1831 |
|
| 1832 |
return res |
| 1833 |
|
| 1834 |
def _get_partners_domain(self): |
| 1835 |
return [] |
| 1836 |
|
| 1837 |
def find_product_by_barcode(self, barcode, config_id): |
| 1838 |
# Kept for backward compatibility. |
| 1839 |
return self.env['product.template'].load_product_from_pos(config_id, [ |
| 1840 |
'|', |
| 1841 |
('product_variant_ids.barcode', '=', barcode), |
| 1842 |
('barcode', '=', barcode), |
| 1843 |
('available_in_pos', '=', True), |
| 1844 |
('sale_ok', '=', True), |
| 1845 |
]) |
| 1846 |
|
| 1847 |
def get_total_discount(self): |
| 1848 |
amount = 0 |
| 1849 |
for line in self.env['pos.order.line'].search([('order_id', 'in', self._get_closed_orders().ids), ('discount', '>', 0)]): |
| 1850 |
amount += line._get_discount_amount() |
| 1851 |
|
| 1852 |
return amount |
| 1853 |
|
| 1854 |
def _get_invoice_total_list(self): |
| 1855 |
invoice_list = [] |
| 1856 |
for order in self.order_ids.filtered(lambda o: o.is_invoiced): |
| 1857 |
invoice = { |
| 1858 |
'total': order.account_move.amount_total_signed, |
| 1859 |
'name': order.account_move.name, |
| 1860 |
'order_ref': order.pos_reference, |
| 1861 |
} |
| 1862 |
invoice_list.append(invoice) |
| 1863 |
|
| 1864 |
return invoice_list |
| 1865 |
|
| 1866 |
def _get_total_invoice(self): |
| 1867 |
amount = 0 |
| 1868 |
for order in self.order_ids.filtered(lambda o: o.is_invoiced): |
| 1869 |
amount += order.amount_paid |
| 1870 |
|
| 1871 |
return amount |
| 1872 |
|
| 1873 |
def log_partner_message(self, partner_id, action, message_type): |
| 1874 |
if message_type == 'ACTION_CANCELLED': |
| 1875 |
body = _('Action cancelled (%s)', action) |
| 1876 |
elif message_type == 'CASH_DRAWER_ACTION': |
| 1877 |
body = _('Cash drawer opened (%s)', action) |
| 1878 |
elif message_type == 'CASH_IN_OUT_UNLINK': |
| 1879 |
body = _('Cash move deleted: %s', action) |
| 1880 |
|
| 1881 |
self.message_post(body=body, author_id=partner_id) |
| 1882 |
|
| 1883 |
def _pos_has_valid_product(self): |
| 1884 |
return self.env['product.product'].sudo().search_count([('available_in_pos', '=', True), ('list_price', '>=', 0), ('id', 'not in', self.env['pos.config']._get_special_products().ids), '|', ('active', '=', False), ('active', '=', True)], limit=1) > 0 |
| 1885 |
|
| 1886 |
def _get_closed_orders(self): |
| 1887 |
return self.order_ids.filtered(lambda o: o.state not in ['draft', 'cancel']) |
| 1888 |
|
| 1889 |
|
| 1890 |
class StockRule(models.Model): |
| 1891 |
_inherit = 'stock.rule' |
| 1892 |
|
| 1893 |
@api.model |
| 1894 |
def _run_scheduler_tasks(self, use_new_cursor=False, company_id=False): |
| 1895 |
super()._run_scheduler_tasks(use_new_cursor=use_new_cursor, company_id=company_id) |
| 1896 |
self.env['pos.session']._alert_old_session() |
| 1897 |
if use_new_cursor: |
| 1898 |
self.env['ir.cron']._commit_progress(1) |
| 1899 |
|
| 1900 |
@api.model |
| 1901 |
def _get_scheduler_tasks_to_do(self): |
| 1902 |
return super()._get_scheduler_tasks_to_do() + 1 |