Selector de rango en la caja: deslizador acotado con monto editable
Tres servicios de la lista de Puebla no tienen un precio sino un piso y un techo (peinado social $600–$1,250, diseño intermedio $180–$220, diseño full $250–$450). Estaban cargados al mínimo como precio fijo, la pantalla no decía que pudiera ser más, y la captura libre no tenía tope: nada impedía teclear $5,000 (pendiente #32 del libro). Decisión del 4-sep-2026: opción C — deslizador que avanza en el paso del servicio, con el monto en una ventana editable; a mano se admite cualquier monto, pero SOLO dentro del rango. Paso $50 en los tres por instrucción del cliente ("$50 siempre"); el paso es un campo por servicio, así que cambiar el del diseño intermedio a $10 es un dato, no código. Tres piezas: - beyond_branch: `beyond_precio_min/max/paso` en product.template, campos de RED (CAMPOS_ESTRUCTURALES, mismo candado que el precio base). Rango activo cuando max > 0; el precio base debe caer dentro —es lo que la caja prellena— y viajan al POS por _load_pos_data_fields. - beyond_pos_theme (UI): diálogo OWL sobre `addLineToCurrentOrder`, la puerta única por la que entran el clic en la tarjeta y el buscador. Cancelar no agrega; confirmar fija `price_unit`, que el core marca manual y no fusiona — dos peinados pueden costar distinto. El deslizador pega el último tramo al techo: con rango 180–220 y paso 50 el elemento nativo dejaría el máximo inalcanzable. - beyond_pos_theme (guardia): constraint en pos.order.line. El deslizador es pintura; `sync_from_ui` recibe lo que le manden —el modo precio del teclado numérico incluido— y un precio fuera del rango se rechaza en el servidor. Las devoluciones quedan exentas: copian el precio del ticket original y deben seguirlo aunque el rango cambie después. Pruebas, todas vistas en rojo (se apagaron los dos guardias y se quitó el disabled del XML; cada sabotaje lo atrapó su prueba): - Modelo: rango válido, sin máximo no se exige nada, max>min, paso obligatorio, base dentro del rango, y el candado de red (gerente bloqueado, dirección no). El test-censo de CAMPOS_ESTRUCTURALES exigió cubrir los tres campos, como está diseñado para hacer. - Cobro por la MISMA puerta que la caja (`sync_from_ui`, con atribución): dentro del rango cobra ($600, $850, $1,250), fuera se rechaza ($5,000, $12, $599, $1,250.01), y la contraparte — sin rango el precio sigue libre, para que un guardia que rechazara todo no pase por bueno. - Lo que solo existe en el navegador, por el patrón sancionado del POS (guardia que lee el código, como test_theme_assets): assets en el bundle, deslizador con min/max/paso, ventana editable, confirmar apagado fuera del rango, y el parche colgado de la puerta única respetando un price_unit ya fijado. Los rangos ya están puestos en beyond_dev por ID externo (BEY-SERV-040/ 086/087). En beyond_prod se cargan igual cuando se decida; el libro (pendiente #32) queda por actualizar en su rama. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
613b68b8bb
commit
bf33a68e5c
12 files changed
+494
No files matched your search
@@ -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
|
||||
@@ -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']
|
||||
@@ -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
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
@@ -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',
|
||||
],
|
||||
},
|
||||
|
||||
@@ -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']
|
||||
@@ -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);
|
||||
},
|
||||
});
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
|
||||
<!-- El deslizador para acercarse, el número para afinar (decisión C,
|
||||
4-sep-2026). El botón de confirmar se apaga fuera del rango: la
|
||||
captura a mano admite cualquier monto, pero solo entre el piso y
|
||||
el techo del servicio. -->
|
||||
<t t-name="beyond_pos_theme.SelectorRango">
|
||||
<Dialog title="props.producto.display_name" size="'md'"
|
||||
contentClass="'beyond_rango_dialogo'">
|
||||
<div class="beyond_rango">
|
||||
<div class="beyond_rango_monto input-group input-group-lg mb-3">
|
||||
<span class="input-group-text">$</span>
|
||||
<input type="text" inputmode="decimal"
|
||||
class="form-control beyond_rango_entrada beyond_num"
|
||||
t-att-value="state.texto"
|
||||
t-on-input="escribir"/>
|
||||
</div>
|
||||
<input type="range" class="form-range beyond_rango_deslizador"
|
||||
t-att-min="minimo" t-att-max="maximo" t-att-step="paso"
|
||||
t-att-value="montoDeslizador"
|
||||
t-on-input="deslizar"/>
|
||||
<div class="beyond_rango_topes d-flex justify-content-between">
|
||||
<span class="beyond_num" t-esc="env.utils.formatCurrency(minimo)"/>
|
||||
<span class="beyond_num" t-esc="env.utils.formatCurrency(maximo)"/>
|
||||
</div>
|
||||
<p class="beyond_rango_aviso text-danger mb-0"
|
||||
t-att-class="{ invisible: dentroDelRango }"
|
||||
t-esc="aviso || ' '"/>
|
||||
</div>
|
||||
<t t-set-slot="footer">
|
||||
<button class="btn btn-primary btn-lg beyond_rango_confirmar"
|
||||
t-att-disabled="!dentroDelRango"
|
||||
t-on-click="confirmar">Agregar</button>
|
||||
<button class="btn btn-secondary btn-lg"
|
||||
t-on-click="props.close">Cancelar</button>
|
||||
</t>
|
||||
</Dialog>
|
||||
</t>
|
||||
</templates>
|
||||
@@ -3,3 +3,4 @@ from . import test_c025_ciclo_completo
|
||||
from . import test_theme_assets
|
||||
from . import test_descuento
|
||||
from . import test_contrato_pos
|
||||
from . import test_selector_rango
|
||||
@@ -0,0 +1,122 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
"""El rango de precio, por donde entra de verdad: `sync_from_ui`.
|
||||
|
||||
En la caja el deslizador acota el monto, pero eso es pintura — el modo
|
||||
precio del teclado numérico, una extensión o un payload a mano mandan lo
|
||||
que quieran. El guardia vive en la línea de la orden, y estas pruebas lo
|
||||
ejercitan con el MISMO método que llama el punto de venta al cobrar, no
|
||||
creando la línea por el ORM (regla «la prueba entra por la misma puerta»).
|
||||
"""
|
||||
import uuid as uuid_lib
|
||||
|
||||
from odoo.exceptions import ValidationError
|
||||
from odoo.modules.module import get_manifest
|
||||
from odoo.tests import tagged
|
||||
from odoo.tools import file_open
|
||||
|
||||
from odoo.addons.beyond_branch.tests.common import BeyondBranchCase
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestBeyondSelectorRangoAlCobrar(BeyondBranchCase):
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.peinado = self.env['product.template'].create({
|
||||
'name': 'Peinado social de prueba', '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})
|
||||
self.corte = self.env['product.template'].create({
|
||||
'name': 'Corte sin rango', 'type': 'service', 'sale_ok': True,
|
||||
'available_in_pos': True, 'list_price': 510.0})
|
||||
# La atribución es obligatoria al cobrar (ADR-007): sin quién
|
||||
# atendió, el guardia de la orden rechaza ANTES de llegar al rango.
|
||||
self.estilista = self.env['hr.employee'].create({
|
||||
'name': 'Estilista de prueba', 'branch_id': self.branch_a.id})
|
||||
|
||||
def _cobrar(self, plantilla, precio):
|
||||
"""Una venta como la manda la caja de verdad."""
|
||||
marca = str(uuid_lib.uuid4())
|
||||
self.env['pos.order'].sync_from_ui([{
|
||||
'name': f'Orden {marca}', 'session_id': self.session_a.id,
|
||||
'company_id': self.session_a.company_id.id,
|
||||
'amount_tax': 0.0, 'amount_total': precio,
|
||||
'amount_paid': precio, 'amount_return': 0.0,
|
||||
'lines': [[0, 0, {
|
||||
'product_id': plantilla.product_variant_id.id, 'qty': 1,
|
||||
'price_unit': precio, 'price_subtotal': precio,
|
||||
'price_subtotal_incl': precio,
|
||||
'beyond_empleado_ids': [(6, 0, self.estilista.ids)],
|
||||
}]],
|
||||
'payment_ids': [[0, 0, {
|
||||
'payment_method_id':
|
||||
self.session_a.config_id.branch_id.payment_method_id.id,
|
||||
'amount': precio}]],
|
||||
'uuid': marca, 'last_order_preparation_change': '{}',
|
||||
}])
|
||||
return self.env['pos.order'].search([('uuid', '=', marca)], limit=1)
|
||||
|
||||
def test_dentro_del_rango_se_cobra(self):
|
||||
for precio in (600.0, 850.0, 1250.0):
|
||||
with self.subTest(precio=precio):
|
||||
orden = self._cobrar(self.peinado, precio)
|
||||
self.assertEqual(orden.lines.price_unit, precio)
|
||||
|
||||
def test_fuera_del_rango_se_rechaza(self):
|
||||
"""El pendiente #32 del libro: nada impedía teclear $5,000 — o $12."""
|
||||
for precio in (5000.0, 12.0, 599.0, 1250.01):
|
||||
with self.subTest(precio=precio):
|
||||
with self.assertRaises(ValidationError):
|
||||
self._cobrar(self.peinado, precio)
|
||||
|
||||
def test_sin_rango_el_precio_sigue_libre(self):
|
||||
"""La contraparte: el guardia solo aplica a quien tiene rango. Sin
|
||||
esto, un guardia que rechazara todo pasaría por bueno (ADR-016)."""
|
||||
orden = self._cobrar(self.corte, 5000.0)
|
||||
self.assertEqual(orden.lines.price_unit, 5000.0)
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestBeyondSelectorRangoEnLaCaja(BeyondBranchCase):
|
||||
"""Lo que solo existe en el navegador, vigilado leyendo el código: el
|
||||
patrón sancionado del proyecto para el POS (test_theme_assets). Un tour
|
||||
del POS no existe aún en el repo; si algún día lo hay, esto se convierte
|
||||
en pantalla de verdad."""
|
||||
|
||||
def _fuente(self, ruta):
|
||||
with file_open(ruta) as handle:
|
||||
return handle.read()
|
||||
|
||||
def test_los_assets_del_selector_estan_en_el_bundle(self):
|
||||
bundle = get_manifest('beyond_pos_theme')['assets'].get(
|
||||
'point_of_sale._assets_pos', [])
|
||||
for sufijo in ('js', 'xml', 'scss'):
|
||||
self.assertIn(
|
||||
f'beyond_pos_theme/static/src/selector_rango/selector_rango.{sufijo}',
|
||||
bundle)
|
||||
|
||||
def test_el_dialogo_tiene_deslizador_y_ventana_editable(self):
|
||||
"""Decisión C del 4-sep: deslizador en pasos + monto editable."""
|
||||
plantilla = self._fuente(
|
||||
'beyond_pos_theme/static/src/selector_rango/selector_rango.xml')
|
||||
self.assertIn('type="range"', plantilla)
|
||||
for atributo in ('t-att-min="minimo"', 't-att-max="maximo"',
|
||||
't-att-step="paso"'):
|
||||
self.assertIn(atributo, plantilla)
|
||||
self.assertIn('inputmode="decimal"', plantilla,
|
||||
'la ventana editable del monto')
|
||||
self.assertIn('t-att-disabled="!dentroDelRango"', plantilla,
|
||||
'confirmar se apaga fuera del rango')
|
||||
|
||||
def test_la_puerta_es_la_unica_de_agregar_lineas(self):
|
||||
"""El parche cuelga de `addLineToCurrentOrder`, que es por donde
|
||||
pasan el clic en la tarjeta y el buscador; y respeta un precio ya
|
||||
fijado (`price_unit` en vals) para no preguntar dos veces."""
|
||||
codigo = self._fuente(
|
||||
'beyond_pos_theme/static/src/selector_rango/selector_rango.js')
|
||||
self.assertIn('patch(PosStore.prototype', codigo)
|
||||
self.assertIn('async addLineToCurrentOrder(', codigo)
|
||||
self.assertIn('beyond_precio_max > 0', codigo)
|
||||
self.assertIn('"price_unit" in vals', codigo)
|
||||
self.assertIn('return; // cancelado', codigo)
|
||||
Reference in new issue
Block a user