diff --git a/.gitignore b/.gitignore index da89117..16de40f 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,6 @@ backups/ *.sql.gz .idea/ .vscode/ + +# Respaldos con timestamp del catálogo: andamio de sesión, no van al repo +*.respaldo-*.xlsx diff --git a/Beyond_catalogo_productos_para_carga_2.xlsx b/Beyond_catalogo_productos_para_carga_2.xlsx new file mode 100644 index 0000000..7ad0c8d Binary files /dev/null and b/Beyond_catalogo_productos_para_carga_2.xlsx differ diff --git a/addons/beyond_branch/models/__init__.py b/addons/beyond_branch/models/__init__.py index 2cfbcf6..6fa023f 100644 --- a/addons/beyond_branch/models/__init__.py +++ b/addons/beyond_branch/models/__init__.py @@ -5,6 +5,7 @@ from . import hr_models from . import pos_models from . import product_matriz from . import product_models +from . import product_rango from . import res_groups from . import res_users from . import stock_models diff --git a/addons/beyond_branch/models/product_rango.py b/addons/beyond_branch/models/product_rango.py new file mode 100644 index 0000000..fa927c0 --- /dev/null +++ b/addons/beyond_branch/models/product_rango.py @@ -0,0 +1,78 @@ +# Part of Beyond. Collina Systems proprietary module. +"""Price range for services that have a floor and a ceiling, not a price. + +Three services of the Puebla list are like this (peinado social $600-$1,250, +diseño intermedio $180-$220, diseño full $250-$450). They were loaded at the +range minimum as if it were a fixed price, and the register offered nothing: +charging the $1,250 hairdo relied on the cashier remembering to raise it by +hand, and the free capture had no ceiling — nothing prevented typing $5,000. + +The range lives on the product (network data, like the base price): the POS +opens a slider dialog when the product has one, and the server rejects any +line priced outside it. A range is active when `beyond_precio_max > 0`. +""" +from odoo import _, api, fields, models +from odoo.exceptions import ValidationError + +from .product_models import CAMPOS_ESTRUCTURALES + +# The range governs what every register in the network may charge: same +# criterion as list_price (ADR-009), so only the general admin moves it. +CAMPOS_ESTRUCTURALES.update( + {'beyond_precio_min', 'beyond_precio_max', 'beyond_precio_paso'}) + + +class ProductTemplate(models.Model): + _inherit = 'product.template' + + beyond_precio_min = fields.Float( + string='Precio mínimo del rango', default=0.0, + help='Piso del rango de cobro, con IVA incluido. Solo cuenta si el ' + 'máximo está definido.') + beyond_precio_max = fields.Float( + string='Precio máximo del rango', default=0.0, + help='Techo del rango de cobro, con IVA incluido. En cero, el ' + 'artículo se cobra a precio fijo y nada de esto aplica.') + beyond_precio_paso = fields.Float( + string='Paso del selector', default=0.0, + help='De cuánto en cuánto avanza el deslizador de la caja. La ' + 'captura a mano admite cualquier monto dentro del rango.') + + def _beyond_tiene_rango(self): + self.ensure_one() + return self.beyond_precio_max > 0 + + @api.constrains('beyond_precio_min', 'beyond_precio_max', + 'beyond_precio_paso', 'list_price') + def _check_beyond_rango(self): + for template in self: + if not template._beyond_tiene_rango(): + continue + if template.beyond_precio_min < 0: + raise ValidationError(_('El mínimo del rango no puede ser negativo.')) + if template.beyond_precio_max <= template.beyond_precio_min: + raise ValidationError(_( + 'El máximo del rango (%(maximo)s) tiene que ser mayor que ' + 'el mínimo (%(minimo)s).', + maximo=template.beyond_precio_max, + minimo=template.beyond_precio_min)) + if template.beyond_precio_paso <= 0: + raise ValidationError(_( + 'Un artículo con rango necesita el paso del selector.')) + # The base price is what the register pre-fills: outside the + # range, the very first line would already violate the range. + if not (template.beyond_precio_min <= template.list_price + <= template.beyond_precio_max): + raise ValidationError(_( + 'El precio base (%(precio)s) tiene que caer dentro del ' + 'rango %(minimo)s–%(maximo)s: es el monto con el que la ' + 'caja arranca.', + precio=template.list_price, + minimo=template.beyond_precio_min, + maximo=template.beyond_precio_max)) + + @api.model + def _load_pos_data_fields(self, config): + """The register needs the range to open the slider and bound it.""" + return super()._load_pos_data_fields(config) + [ + 'beyond_precio_min', 'beyond_precio_max', 'beyond_precio_paso'] diff --git a/addons/beyond_branch/tests/__init__.py b/addons/beyond_branch/tests/__init__.py index df33a13..4c5c2ea 100644 --- a/addons/beyond_branch/tests/__init__.py +++ b/addons/beyond_branch/tests/__init__.py @@ -22,3 +22,4 @@ from . import test_anchos from . import test_aterrizaje_panel from . import test_ajustes_caja from . import test_varias_cajas +from . import test_precio_rango diff --git a/addons/beyond_branch/tests/test_catalogo.py b/addons/beyond_branch/tests/test_catalogo.py index d599271..ce1dda4 100644 --- a/addons/beyond_branch/tests/test_catalogo.py +++ b/addons/beyond_branch/tests/test_catalogo.py @@ -187,6 +187,10 @@ class TestBeyondCatalogoFronteraEstructural(BeyondBranchCase): # sirve un artículo y cuándo avisar, se deciden una vez para toda # la red. 'beyond_uso': 'insumo', 'beyond_minimo': 99.0, + # El rango de cobro también gobierna la red entera: quien lo + # mueve mueve lo que toda caja puede cobrar. + 'beyond_precio_min': 100.0, 'beyond_precio_max': 900.0, + 'beyond_precio_paso': 25.0, } self.assertEqual( set(valores) | {'list_price', 'branch_ids'}, CAMPOS_ESTRUCTURALES, diff --git a/addons/beyond_branch/tests/test_precio_rango.py b/addons/beyond_branch/tests/test_precio_rango.py new file mode 100644 index 0000000..d23492c --- /dev/null +++ b/addons/beyond_branch/tests/test_precio_rango.py @@ -0,0 +1,64 @@ +# Part of Beyond. Collina Systems proprietary module. +"""El rango de precio en el catálogo: campos de red, con sus candados.""" +from odoo.exceptions import ValidationError +from odoo.tests import tagged + +from .common import BeyondBranchCase + + +@tagged('post_install', '-at_install') +class TestBeyondPrecioRango(BeyondBranchCase): + + def _servicio(self, **valores): + base = {'name': 'Peinado con rango', 'type': 'service', + 'sale_ok': True, 'available_in_pos': True, + 'list_price': 600.0, 'beyond_precio_min': 600.0, + 'beyond_precio_max': 1250.0, 'beyond_precio_paso': 50.0} + base.update(valores) + return self.env['product.template'].create(base) + + def test_un_rango_valido_se_guarda(self): + servicio = self._servicio() + self.assertTrue(servicio._beyond_tiene_rango()) + + def test_sin_maximo_no_hay_rango_y_nada_se_exige(self): + """El caso normal del catálogo: 103 de 106 artículos no tienen + rango, y no deben cargar con sus reglas.""" + fijo = self._servicio(beyond_precio_min=0, beyond_precio_max=0, + beyond_precio_paso=0) + self.assertFalse(fijo._beyond_tiene_rango()) + + def test_el_maximo_tiene_que_superar_al_minimo(self): + with self.assertRaises(ValidationError): + self._servicio(beyond_precio_min=1250.0, beyond_precio_max=600.0) + + def test_un_rango_sin_paso_se_rechaza(self): + with self.assertRaises(ValidationError): + self._servicio(beyond_precio_paso=0) + + def test_el_precio_base_tiene_que_caer_dentro(self): + """El base es lo que la caja prellena: fuera del rango, la primera + línea ya lo violaría.""" + with self.assertRaises(ValidationError): + self._servicio(list_price=500.0) + with self.assertRaises(ValidationError): + self._servicio(list_price=1300.0) + + def test_el_rango_es_campo_de_red(self): + """Quien mueve el rango mueve lo que TODA la red puede cobrar: mismo + candado que el precio base (CAMPOS_ESTRUCTURALES). El gerente de + sucursal no lo toca; la dirección sí.""" + servicio = self._servicio() + with self.assertRaises(ValidationError): + servicio.with_user(self.admin_a).write({'beyond_precio_max': 2000.0}) + servicio.with_user(self.admin_general).write({'beyond_precio_max': 2000.0}) + self.assertEqual(servicio.beyond_precio_max, 2000.0) + + def test_el_rango_viaja_a_la_caja(self): + """Sin estos campos en la carga del POS, el deslizador no tendría + con qué acotarse.""" + config = self.branch_a.pos_config_ids[:1] or self.env['pos.config'].search([], limit=1) + campos = self.env['product.template']._load_pos_data_fields(config) + for campo in ('beyond_precio_min', 'beyond_precio_max', + 'beyond_precio_paso'): + self.assertIn(campo, campos) diff --git a/addons/beyond_pos_theme/__manifest__.py b/addons/beyond_pos_theme/__manifest__.py index c8a7da1..9903fc1 100644 --- a/addons/beyond_pos_theme/__manifest__.py +++ b/addons/beyond_pos_theme/__manifest__.py @@ -84,6 +84,9 @@ El veredicto del spike está en docs/adr/ADR-001-spike-pos.md. 'beyond_pos_theme/static/src/camara/camara_pos.js', 'beyond_pos_theme/static/src/camara/camara_pos.xml', 'beyond_pos_theme/static/src/descuento/descuento.js', + 'beyond_pos_theme/static/src/selector_rango/selector_rango.js', + 'beyond_pos_theme/static/src/selector_rango/selector_rango.xml', + 'beyond_pos_theme/static/src/selector_rango/selector_rango.scss', 'beyond_pos_theme/static/src/descuento/descuento.xml', ], }, diff --git a/addons/beyond_pos_theme/models/pos_order_line.py b/addons/beyond_pos_theme/models/pos_order_line.py index ece6c79..6053647 100644 --- a/addons/beyond_pos_theme/models/pos_order_line.py +++ b/addons/beyond_pos_theme/models/pos_order_line.py @@ -48,6 +48,33 @@ class PosOrderLine(models.Model): self.order_id._beyond_autorizar_descuento() return resultado + # ── El rango de precio se hace valer aquí ─────────────────────────── + # En la caja el deslizador acota el monto, pero eso es pintura: + # `sync_from_ui` recibe lo que le manden — el modo precio del teclado + # numérico, una extensión futura, un payload a mano. Un artículo con + # rango no se cobra fuera de él, y punto. + + @api.constrains('price_unit', 'product_id') + def _check_beyond_precio_en_rango(self): + for line in self: + template = line.product_id.product_tmpl_id + if not template._beyond_tiene_rango(): + continue + if line.refunded_orderline_id: + # Una devolución copia el precio de la venta original: si + # aquel entró en rango, este también; y si el rango cambió + # después, la devolución debe seguir al ticket, no al rango. + continue + precio = line.currency_id.round(line.price_unit) \ + if line.currency_id else line.price_unit + minimo, maximo = template.beyond_precio_min, template.beyond_precio_max + if not (minimo - 0.005 <= precio <= maximo + 0.005): + raise ValidationError(_( + '%(articulo)s se cobra entre %(minimo)s y %(maximo)s; ' + 'el ticket trae %(precio)s.', + articulo=template.name, minimo=minimo, maximo=maximo, + precio=line.price_unit)) + @api.model def _load_pos_data_fields(self, config): return super()._load_pos_data_fields(config) + ['beyond_empleado_ids'] diff --git a/addons/beyond_pos_theme/static/src/product_card/product_card.js b/addons/beyond_pos_theme/static/src/product_card/product_card.js index bf62a14..5732e46 100644 --- a/addons/beyond_pos_theme/static/src/product_card/product_card.js +++ b/addons/beyond_pos_theme/static/src/product_card/product_card.js @@ -33,6 +33,21 @@ patch(ProductCard.prototype, { return this.beyondEsServicio ? "por servicio" : "por pieza"; }, + /** + * Un servicio con rango no tiene UN precio, y pintar el mínimo a secas + * comunica que ese es el precio: la cajera no sabe que puede costar más + * hasta tocarlo, y una cotización por teléfono sale mal. La tarjeta + * enseña el rango completo; el monto exacto se decide en el selector. + */ + get beyondRango() { + const template = this.props.product; + if (!template || !(template.beyond_precio_max > 0)) { + return false; + } + const formato = this.env.utils.formatCurrency; + return `${formato(template.beyond_precio_min)} – ${formato(template.beyond_precio_max)}`; + }, + get beyondPrice() { const template = this.props.product; if (!template) { diff --git a/addons/beyond_pos_theme/static/src/selector_rango/selector_rango.js b/addons/beyond_pos_theme/static/src/selector_rango/selector_rango.js new file mode 100644 index 0000000..5f7800c --- /dev/null +++ b/addons/beyond_pos_theme/static/src/selector_rango/selector_rango.js @@ -0,0 +1,125 @@ +/** @odoo-module **/ + +import { Component, useState } from "@odoo/owl"; +import { Dialog } from "@web/core/dialog/dialog"; +import { PosStore } from "@point_of_sale/app/services/pos_store"; +import { makeAwaitable } from "@point_of_sale/app/utils/make_awaitable_dialog"; +import { patch } from "@web/core/utils/patch"; +import { _t } from "@web/core/l10n/translation"; + +/** + * Selector de rango: el precio de estos servicios no es un número sino un + * piso y un techo (peinado social $600–$1,250). Decisión del 4-sep-2026: + * deslizador que avanza en el paso del servicio, con el monto en una + * ventana editable — el gesto para acercarse, el número para afinar. La + * captura a mano admite cualquier monto, pero SOLO dentro del rango: el + * $5,000 tecleado por error era el pendiente #32 del libro. + * + * El rango viaja en el producto (`beyond_precio_min/max/paso`, campos de + * red como el precio base) y el servidor lo vuelve a comprobar al cobrar: + * este diálogo es la comodidad, no la garantía. + */ +export class BeyondSelectorRango extends Component { + static template = "beyond_pos_theme.SelectorRango"; + static components = { Dialog }; + static props = { producto: Object, getPayload: Function, close: Function }; + + setup() { + // Arranca en el precio base, que la carga dejó en el mínimo del + // rango: subirlo es un acto deliberado del cajero. + this.state = useState({ texto: String(this.props.producto.list_price) }); + } + + get minimo() { + return this.props.producto.beyond_precio_min; + } + + get maximo() { + return this.props.producto.beyond_precio_max; + } + + get paso() { + return this.props.producto.beyond_precio_paso; + } + + /** La coma vale como punto, como en el diálogo de descuento. */ + get monto() { + const valor = parseFloat(String(this.state.texto).replace(",", ".")); + return isNaN(valor) ? NaN : valor; + } + + get dentroDelRango() { + const monto = this.monto; + return !isNaN(monto) && this.minimo <= monto && monto <= this.maximo; + } + + /** Lo que el deslizador enseña: el monto acotado, para que arrastrar + * desde un monto tecleado fuera de paso no dé saltos raros. */ + get montoDeslizador() { + const monto = this.monto; + if (isNaN(monto)) { + return this.minimo; + } + return Math.min(Math.max(monto, this.minimo), this.maximo); + } + + get aviso() { + if (this.dentroDelRango) { + return ""; + } + return _t("Entre %(minimo)s y %(maximo)s", { + minimo: this.env.utils.formatCurrency(this.minimo), + maximo: this.env.utils.formatCurrency(this.maximo), + }); + } + + deslizar(ev) { + // El deslizador avanza en el paso, pero el techo se alcanza SIEMPRE: + // con rango 180–220 y paso 50 el elemento nativo dejaría el máximo + // inalcanzable (min + n·paso se pasa), así que el último tramo se + // pega al techo. + let valor = parseFloat(ev.target.value); + if (valor + this.paso > this.maximo) { + valor = ev.target.value >= ev.target.max ? this.maximo : valor; + } + this.state.texto = String(valor); + } + + escribir(ev) { + this.state.texto = ev.target.value; + } + + confirmar() { + if (!this.dentroDelRango) { + return; + } + this.props.getPayload(this.monto); + this.props.close(); + } +} + +patch(PosStore.prototype, { + /** + * La puerta única: el clic en la tarjeta, el buscador y cualquier + * extensión que agregue líneas pasan por aquí. Si el producto tiene + * rango y nadie fijó ya un precio, se pregunta; cancelar no agrega. + */ + async addLineToCurrentOrder(vals, opts = {}, configure = true) { + let template = vals.product_tmpl_id; + if (typeof template === "number") { + template = this.data.models["product.template"].get(template); + } + if (configure && template?.beyond_precio_max > 0 && !("price_unit" in vals)) { + const monto = await makeAwaitable(this.dialog, BeyondSelectorRango, { + producto: template, + }); + if (monto === undefined) { + return; // cancelado: no se agrega nada + } + // `price_unit` explícito: el core lo marca price_type "manual" y + // no fusiona la línea — dos peinados pueden costar distinto. + vals = { ...vals, price_unit: monto }; + } + return super.addLineToCurrentOrder(vals, opts, configure); + }, +}); diff --git a/addons/beyond_pos_theme/static/src/selector_rango/selector_rango.scss b/addons/beyond_pos_theme/static/src/selector_rango/selector_rango.scss new file mode 100644 index 0000000..bba0ece --- /dev/null +++ b/addons/beyond_pos_theme/static/src/selector_rango/selector_rango.scss @@ -0,0 +1,28 @@ +/* Part of Beyond. Collina Systems proprietary module. + El selector de rango: táctil primero. El deslizador y su pulgar van + gruesos (≥48px de zona de toque, brief §3) y el monto se lee grande. */ +.beyond_rango { + .beyond_rango_entrada { + font-size: 1.6rem; + text-align: center; + } + .beyond_rango_deslizador { + height: 3rem; // zona de toque, no solo la línea + &::-webkit-slider-thumb { + width: 2rem; + height: 2rem; + margin-top: -0.85rem; // centrado sobre la pista fina + } + &::-moz-range-thumb { + width: 2rem; + height: 2rem; + } + } + .beyond_rango_topes { + color: $caja-tinta-suave; + font-size: 0.95rem; + } + .beyond_rango_aviso.invisible { + visibility: hidden; // reserva el renglón: el diálogo no salta + } +} diff --git a/addons/beyond_pos_theme/static/src/selector_rango/selector_rango.xml b/addons/beyond_pos_theme/static/src/selector_rango/selector_rango.xml new file mode 100644 index 0000000..f118f51 --- /dev/null +++ b/addons/beyond_pos_theme/static/src/selector_rango/selector_rango.xml @@ -0,0 +1,40 @@ + + + + + + +
+
+ $ + +
+ +
+ + +
+

+

+ + + + +
+
+
diff --git a/addons/beyond_pos_theme/static/src/xml/product_card.xml b/addons/beyond_pos_theme/static/src/xml/product_card.xml index 4e5a8c7..49dadb0 100644 --- a/addons/beyond_pos_theme/static/src/xml/product_card.xml +++ b/addons/beyond_pos_theme/static/src/xml/product_card.xml @@ -29,7 +29,12 @@ - + +