| 1 |
# Part of Odoo. See LICENSE file for full copyright and licensing details. |
| 2 |
|
| 3 |
import logging |
| 4 |
import json |
| 5 |
|
| 6 |
from odoo import http, _ |
| 7 |
from odoo.fields import Domain |
| 8 |
from odoo.http import request |
| 9 |
from odoo.tools import format_amount, file_open |
| 10 |
from odoo.addons.account.controllers.portal import PortalAccount |
| 11 |
from datetime import timedelta, datetime |
| 12 |
|
| 13 |
_logger = logging.getLogger(__name__) |
| 14 |
|
| 15 |
|
| 16 |
class PosController(PortalAccount): |
| 17 |
|
| 18 |
@http.route('/pos/service-worker.js', type='http', auth='user') |
| 19 |
def pos_web_service_worker(self): |
| 20 |
response = request.make_response( |
| 21 |
self._get_pos_service_worker(), |
| 22 |
[ |
| 23 |
('Content-Type', 'text/javascript'), |
| 24 |
('Service-Worker-Allowed', '/pos'), |
| 25 |
], |
| 26 |
) |
| 27 |
return response |
| 28 |
|
| 29 |
def _get_pos_service_worker(self): |
| 30 |
with file_open('point_of_sale/static/src/app/service_worker.js') as f: |
| 31 |
body = f.read() |
| 32 |
return body |
| 33 |
|
| 34 |
# Support old routes for backward compatibility |
| 35 |
@http.route(['/pos/web', '/pos/ui'], type='http', auth='user') |
| 36 |
def old_pos_web(self, config_id=False, from_backend=False, **k): |
| 37 |
return self.pos_web(config_id, from_backend, **k) |
| 38 |
|
| 39 |
@http.route(["/pos/ui/<config_id>", "/pos/ui/<config_id>/<path:subpath>"], auth="user", type='http') |
| 40 |
def pos_web(self, config_id=False, from_backend=False, subpath=None, **k): |
| 41 |
"""Open a pos session for the given config. |
| 42 |
|
| 43 |
The right pos session will be selected to open, if non is open yet a new session will be created. |
| 44 |
|
| 45 |
/pos/ui and /pos/web both can be used to access the POS. On the SaaS, |
| 46 |
/pos/ui uses HTTPS while /pos/web uses HTTP. |
| 47 |
|
| 48 |
:param debug: The debug mode to load the session in. |
| 49 |
:type debug: str. |
| 50 |
:param config_id: id of the config that has to be loaded. |
| 51 |
:type config_id: str. |
| 52 |
:returns: object -- The rendered pos session. |
| 53 |
""" |
| 54 |
is_internal_user = request.env.user._is_internal() |
| 55 |
pos_config = False |
| 56 |
if not is_internal_user: |
| 57 |
return request.not_found() |
| 58 |
domain = [ |
| 59 |
('state', 'in', ['opening_control', 'opened']), |
| 60 |
('user_id', '=', request.session.uid), |
| 61 |
('rescue', '=', False) |
| 62 |
] |
| 63 |
if config_id and request.env['pos.config'].sudo().browse(int(config_id)).exists(): |
| 64 |
domain = Domain.AND([domain, [('config_id', '=', int(config_id))]]) |
| 65 |
pos_config = request.env['pos.config'].sudo().browse(int(config_id)) |
| 66 |
pos_session = request.env['pos.session'].sudo().search(domain, limit=1) |
| 67 |
|
| 68 |
# The same POS session can be opened by a different user => search without restricting to |
| 69 |
# current user. Note: the config must be explicitly given to avoid fallbacking on a random |
| 70 |
# session. |
| 71 |
if not pos_session and config_id: |
| 72 |
domain = [ |
| 73 |
('state', 'in', ['opening_control', 'opened']), |
| 74 |
('rescue', '=', False), |
| 75 |
('config_id', '=', int(config_id)), |
| 76 |
] |
| 77 |
pos_session = request.env['pos.session'].sudo().search(domain, limit=1) |
| 78 |
|
| 79 |
if not pos_config or not pos_config.active or pos_config.has_active_session and not pos_session: |
| 80 |
return request.redirect('/odoo/action-point_of_sale.action_client_pos_menu') |
| 81 |
|
| 82 |
if not pos_config.has_active_session: |
| 83 |
# Acquire an row-level lock on the pos_config record to prevent race conditions |
| 84 |
# This prevents multiple concurrent processes from creating duplicate POS sessions |
| 85 |
request.env.cr.execute( |
| 86 |
"SELECT id FROM pos_config WHERE id = %s FOR UPDATE NOWAIT", |
| 87 |
(pos_config.id,) |
| 88 |
) |
| 89 |
pos_config.open_ui() |
| 90 |
pos_session = request.env['pos.session'].sudo().search(domain, limit=1) |
| 91 |
|
| 92 |
# The POS only works in one company, so we enforce the one of the session in the context |
| 93 |
company = pos_session.company_id |
| 94 |
session_info = request.env['ir.http'].session_info() |
| 95 |
session_info['user_context']['allowed_company_ids'] = company.ids |
| 96 |
session_info['user_companies'] = {'current_company': company.id, 'allowed_companies': {company.id: session_info['user_companies']['allowed_companies'][company.id]}} |
| 97 |
session_info['nomenclature_id'] = pos_session.company_id.nomenclature_id.id |
| 98 |
session_info['fallback_nomenclature_id'] = pos_session.config_id.fallback_nomenclature_id.id |
| 99 |
use_lna = bool(pos_session.env["ir.config_parameter"].get_param("point_of_sale.use_lna")) |
| 100 |
context = { |
| 101 |
'from_backend': 1 if from_backend else 0, |
| 102 |
'use_pos_fake_tours': True if k.get('tours', False) else False, |
| 103 |
'session_info': session_info, |
| 104 |
'pos_session_id': pos_session.id, |
| 105 |
'pos_config_id': pos_session.config_id.id, |
| 106 |
'access_token': pos_session.config_id.access_token, |
| 107 |
'last_data_change': pos_session.config_id.last_data_change.strftime("%Y-%m-%d %H:%M:%S"), |
| 108 |
'urls_to_cache': json.dumps(pos_config._get_url_to_cache(request.session.debug)), |
| 109 |
'use_lna': use_lna, |
| 110 |
} |
| 111 |
response = request.render('point_of_sale.index', context) |
| 112 |
response.headers['Cache-Control'] = 'no-store' |
| 113 |
return response |
| 114 |
|
| 115 |
@http.route(['/pos/ping'], type='jsonrpc', auth='user') |
| 116 |
def pos_ping(self): |
| 117 |
return {'response': 'pong'} |
| 118 |
|
| 119 |
@http.route('/pos/sale_details_report', type='http', auth='user') |
| 120 |
def print_sale_details(self, date_start=False, date_stop=False, **kw): |
| 121 |
r = request.env['report.point_of_sale.report_saledetails'] |
| 122 |
pdf, _ = request.env['ir.actions.report'].with_context(date_start=date_start, date_stop=date_stop)._render_qweb_pdf('point_of_sale.sale_details_report', r) |
| 123 |
pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))] |
| 124 |
return request.make_response(pdf, headers=pdfhttpheaders) |
| 125 |
|
| 126 |
@http.route(['/pos/ticket'], type='http', auth="public", website=True, sitemap=False) |
| 127 |
def invoice_request_screen(self, **kwargs): |
| 128 |
errors = {} |
| 129 |
form_values = {} |
| 130 |
if request.httprequest.method == 'POST': |
| 131 |
for field in ['pos_reference', 'date_order', 'ticket_code']: |
| 132 |
if not kwargs.get(field): |
| 133 |
errors[field] = " " |
| 134 |
else: |
| 135 |
form_values[field] = kwargs.get(field) |
| 136 |
|
| 137 |
if errors: |
| 138 |
errors['generic'] = _("Please fill all the required fields.") |
| 139 |
elif len(form_values['pos_reference']) < 12: |
| 140 |
errors['pos_reference'] = _("The Ticket Number should be at least 12 characters long.") |
| 141 |
else: |
| 142 |
date_order = datetime(*[int(i) for i in form_values['date_order'].split('-')]) |
| 143 |
order = request.env['pos.order'].sudo().search([ |
| 144 |
('pos_reference', '=like', '%' + form_values['pos_reference'].strip().replace('%', r'\%').replace('_', r'\_')), |
| 145 |
('date_order', '>=', date_order - timedelta(days=1)), |
| 146 |
('date_order', '<', date_order + timedelta(days=2)), |
| 147 |
('ticket_code', '=', form_values['ticket_code']), |
| 148 |
], limit=1) |
| 149 |
if order: |
| 150 |
return request.redirect('/pos/ticket/validate?access_token=%s' % (order.access_token)) |
| 151 |
else: |
| 152 |
errors['generic'] = _("No sale order found.") |
| 153 |
|
| 154 |
elif request.httprequest.method == 'GET': |
| 155 |
if kwargs.get('order_uuid'): |
| 156 |
order = self.env['pos.order'].sudo().search([('uuid', '=', kwargs['order_uuid'])], limit=1) |
| 157 |
if order: |
| 158 |
return request.redirect('/pos/ticket/validate?access_token=%s' % (order.access_token)) |
| 159 |
|
| 160 |
return request.render("point_of_sale.ticket_request_with_code", { |
| 161 |
'errors': errors, |
| 162 |
'banner_error': " ".join(errors.values()), |
| 163 |
'form_values': form_values, |
| 164 |
}) |
| 165 |
|
| 166 |
@http.route(['/pos/ticket/validate'], type='http', auth="public", website=True, sitemap=False) |
| 167 |
def show_ticket_validation_screen(self, access_token='', **kwargs): |
| 168 |
def _parse_additional_values(fields, prefix, kwargs): |
| 169 |
""" Parse the values in the kwargs by extracting the ones matching the given fields name. |
| 170 |
:return a dict with the parsed value and the field name as key, and another on with the prefix to |
| 171 |
re-render the form with previous values if needed. |
| 172 |
""" |
| 173 |
res, res_prefixed = {}, {} |
| 174 |
for field in fields: |
| 175 |
key = prefix + field.name |
| 176 |
if key in kwargs: |
| 177 |
val = kwargs.pop(key) |
| 178 |
res[field.name] = val |
| 179 |
res_prefixed[key] = val |
| 180 |
return res, res_prefixed |
| 181 |
|
| 182 |
# If the route is called directly, return a 404 |
| 183 |
if not access_token: |
| 184 |
return request.not_found() |
| 185 |
# Get the order using the access token. We can't use the id in the route because we may not have it yet when the QR code is generated. |
| 186 |
pos_order = request.env['pos.order'].sudo().search([('access_token', '=', access_token)]) |
| 187 |
if not pos_order: |
| 188 |
return request.not_found() |
| 189 |
|
| 190 |
# Set the proper context in case of unauthenticated user accessing |
| 191 |
# from the main company website |
| 192 |
pos_order = pos_order.with_company(pos_order.company_id).with_context(allowed_company_ids=pos_order.company_id.ids) |
| 193 |
|
| 194 |
# If the order was already invoiced, return the invoice directly by forcing the access token so that the non-connected user can see it. |
| 195 |
if pos_order.account_move and pos_order.account_move.is_sale_document(): |
| 196 |
return request.redirect('/my/invoices/%s?access_token=%s' % (pos_order.account_move.id, pos_order.account_move._portal_ensure_token())) |
| 197 |
|
| 198 |
if not request.env['res.company']._with_locked_records(pos_order, allow_raising=False): |
| 199 |
return |
| 200 |
|
| 201 |
# Get the optional extra fields that could be required for a localisation. |
| 202 |
pos_order_country = pos_order.company_id.account_fiscal_country_id |
| 203 |
additional_partner_fields = request.env['res.partner'].get_partner_localisation_fields_required_to_invoice(pos_order_country) |
| 204 |
additional_invoice_fields = request.env['account.move'].get_invoice_localisation_fields_required_to_invoice(pos_order_country) |
| 205 |
|
| 206 |
user_is_connected = not request.env.user._is_public() |
| 207 |
|
| 208 |
# Validate the form by ensuring required fields are filled and the VAT is correct. |
| 209 |
form_values = {'extra_field_values': {}} |
| 210 |
partner = (user_is_connected and request.env.user.partner_id) or pos_order.partner_id |
| 211 |
if kwargs and request.httprequest.method == 'POST': |
| 212 |
form_values.update(kwargs) |
| 213 |
# Extract the additional fields values from the kwargs now as they can't be there when validating the 'regular' partner form. |
| 214 |
partner_values, prefixed_partner_values = _parse_additional_values(additional_partner_fields, 'partner_', kwargs) |
| 215 |
form_values['extra_field_values'].update(prefixed_partner_values) |
| 216 |
# Do the same for invoice values, separately as they are only needed for the invoice creation. |
| 217 |
invoice_values, prefixed_invoice_values = _parse_additional_values(additional_invoice_fields, 'invoice_', kwargs) |
| 218 |
form_values['extra_field_values'].update(prefixed_invoice_values) |
| 219 |
# Check the basic form fields if the user is not connected as we will need these information to create the new user. |
| 220 |
partner, feedback_dict = self._create_or_update_address(partner, **(kwargs | partner_values)) |
| 221 |
form_values.update(feedback_dict) |
| 222 |
missing_fields, error_messages = self._validate_extra_form_details( |
| 223 |
partner_values | invoice_values, |
| 224 |
additional_partner_fields + additional_invoice_fields |
| 225 |
) |
| 226 |
form_values.update({ |
| 227 |
'invalid_field': form_values.get('invalid_fields', []) + list(missing_fields), |
| 228 |
'messages': form_values.get('messages', []) + error_messages |
| 229 |
}) |
| 230 |
if not form_values.get('invalid_fields'): |
| 231 |
return self._get_invoice(partner, invoice_values, pos_order, additional_invoice_fields, kwargs) |
| 232 |
|
| 233 |
elif user_is_connected: |
| 234 |
return self._get_invoice(partner, {}, pos_order, additional_invoice_fields, kwargs) |
| 235 |
|
| 236 |
# Most of the time, the country of the customer will be the same as the order. We can prefill it by default with the country of the company. |
| 237 |
if 'country' not in form_values: |
| 238 |
form_values['country'] = pos_order_country |
| 239 |
|
| 240 |
# Prefill the customer extra values if there is any and an user is connected |
| 241 |
if partner: |
| 242 |
if additional_partner_fields: |
| 243 |
form_values['extra_field_values'] = {'partner_' + field.name: partner[field.name] for field in additional_partner_fields if field.name not in form_values['extra_field_values']} |
| 244 |
|
| 245 |
# This is just to ensure that the user went and filled its information at least once. |
| 246 |
# Another more thorough check is done upon posting the form. |
| 247 |
if not partner.country_id or not partner.street: |
| 248 |
form_values['partner_address'] = False |
| 249 |
else: |
| 250 |
form_values['partner_address'] = partner._display_address() |
| 251 |
|
| 252 |
return request.render("point_of_sale.ticket_validation_screen", { |
| 253 |
**self._prepare_address_form_values(partner, **kwargs), |
| 254 |
'partner': partner, |
| 255 |
'address_url': f'/my/account?redirect=/pos/ticket/validate?access_token={access_token}', |
| 256 |
'user_is_connected': user_is_connected, |
| 257 |
'format_amount': format_amount, |
| 258 |
'env': request.env, |
| 259 |
'pos_order': pos_order, |
| 260 |
'invoice_required_fields': additional_invoice_fields, |
| 261 |
'partner_required_fields': additional_partner_fields, |
| 262 |
'access_token': access_token, |
| 263 |
'invoice_sending_methods': {'email': _("by Email")}, |
| 264 |
**form_values, |
| 265 |
}) |
| 266 |
|
| 267 |
def _validate_extra_form_details(self, addtional_form_values, additional_required_fields): |
| 268 |
""" Ensure that all additional required fields have a value in the data. """ |
| 269 |
missing_fields = set() |
| 270 |
error_messages = [] |
| 271 |
for field in additional_required_fields: |
| 272 |
if field.name not in addtional_form_values or not addtional_form_values[field.name]: |
| 273 |
missing_fields.add(field.name) |
| 274 |
error_messages.append(_("The field %s must be filled.", field.field_description.lower())) |
| 275 |
return missing_fields, error_messages |
| 276 |
|
| 277 |
def _get_invoice(self, partner, invoice_values, pos_order, additional_invoice_fields, kwargs): |
| 278 |
|
| 279 |
pos_order.partner_id = partner |
| 280 |
# Get the required fields for the invoice and add them to the context as default values. |
| 281 |
with_context = {} |
| 282 |
for field in additional_invoice_fields: |
| 283 |
with_context.update({f'default_{field.name}': invoice_values.get(field.name)}) |
| 284 |
# Allowing default values for moves is important for some localizations that would need specific fields to be set on the invoice, such as Mexico. |
| 285 |
pos_order.with_context(with_context).action_pos_order_invoice() |
| 286 |
return request.redirect('/my/invoices/%s?access_token=%s' % (pos_order.account_move.id, pos_order.account_move._portal_ensure_token())) |