Compare commits
88
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af264da8c2 | ||
|
|
6b1ba2fb0b | ||
|
|
a54dfddc41 | ||
|
|
d3d39be20b | ||
|
|
c2215c1362 | ||
|
|
f4b93fbf52 | ||
|
|
88576c4e1e | ||
|
|
05d0482840 | ||
|
|
4d15ad952b | ||
|
|
440f2c2a08 | ||
|
|
ffa10f90e2 | ||
|
|
560b4be1f6 | ||
|
|
8c3b017317 | ||
|
|
3d2ba99c7c | ||
|
|
08f98a7834 | ||
|
|
ae923188a3 | ||
|
|
06a9cc1758 | ||
|
|
58d291a34f | ||
|
|
f28b69c4b1 | ||
|
|
1a10e78ce2 | ||
|
|
06008b9cb9 | ||
|
|
8175b878bd | ||
|
|
0e11aafe23 | ||
|
|
0bae7af478 | ||
|
|
0ca8023772 | ||
|
|
85c31853ac | ||
|
|
31e79fe383 | ||
|
|
1f0891a7b8 | ||
|
|
5c0504b23d | ||
|
|
5e13133a97 | ||
|
|
c2586d7f79 | ||
|
|
a1be595ebd | ||
|
|
53e9e65969 | ||
|
|
cbb4bfa181 | ||
|
|
d2fa3a56c4 | ||
|
|
ac487c65fe | ||
|
|
d8706cc91d | ||
|
|
317403fdf9 | ||
|
|
880f78297d | ||
|
|
af852f2b41 | ||
|
|
a8bcd1facb | ||
|
|
f7a8d02ac0 | ||
|
|
1f32e87123 | ||
|
|
dab745e93c | ||
|
|
f571d434ca | ||
|
|
e0764ef792 | ||
|
|
f59cff4452 | ||
|
|
1d8dccfb70 | ||
|
|
a9cd2ee3a9 | ||
|
|
efa42e511a | ||
|
|
9b716a7d62 | ||
|
|
bbe947dc32 | ||
|
|
fd685137a6 | ||
|
|
c7f3758940 | ||
|
|
8b5543c11f | ||
|
|
baf7ff3ef6 | ||
|
|
6730b6f38a | ||
|
|
f80565addb | ||
|
|
3579f24a89 | ||
|
|
90b161e29d | ||
|
|
37d4087784 | ||
|
|
1e34c23794 | ||
|
|
cf9afca855 | ||
|
|
86da65b3a9 | ||
|
|
0d3220c5ce | ||
|
|
cf161f4250 | ||
|
|
bfcbe2b0b8 | ||
|
|
6cbfc5c6d9 | ||
|
|
95d7a31752 | ||
|
|
db98c23b16 | ||
|
|
4c767b3e80 | ||
|
|
8120c22c7f | ||
|
|
78c86a2eab | ||
|
|
5efebbb40f | ||
|
|
e1dc34bd9a | ||
|
|
8561398744 | ||
|
|
a9ee7bc9e6 | ||
|
|
f93fe34021 | ||
|
|
c21b44ba36 | ||
|
|
71e0c85b0a | ||
|
|
789a50cd8a | ||
|
|
a25bc3649a | ||
|
|
f5efbec22a | ||
|
|
add146dfc9 | ||
|
|
c93f8b59bc | ||
|
|
f31e60dfb7 | ||
|
|
fecc4d208c | ||
|
|
4a3722d341 |
No files matched your search
@@ -6,7 +6,7 @@ Sistema de gestión multisucursal para Beyond (red de sucursales en Puebla, Méx
|
||||
|
||||
## Estado del proyecto
|
||||
|
||||
- Fase actual: **Fase 1 — Arquitectura base COMPLETADA** (13-ago-2026): `beyond_branch` (aprovisionador + aislamiento + gestión acotada de usuarios, ADR-002), `beyond_customer` núcleo (Ficha 360) y `beyond_product_capture` (escaneo-primero de 3 niveles, ADR-003; cámara/UI táctil en Fase 2, OCR diferido al piloto/D5). Además, **Fase 4 — Checador construida por adelanto del cliente** (17-ago-2026: `beyond_attendance_qr`, QR rotativo + cuentas de empleado, spec en `docs/checador.md`). Siguen Fases 2 (Venta y caja), 3 (Inventario) y 5 (BI).
|
||||
- Fase actual: **Fase 1 — Arquitectura base COMPLETADA** (13-ago-2026): `beyond_branch` (aprovisionador + aislamiento + gestión acotada de usuarios, ADR-002), `beyond_customer` núcleo (Ficha 360) y `beyond_product_capture` (escaneo-primero de 3 niveles, ADR-003; cámara/UI táctil en Fase 2, OCR diferido al piloto/D5). Además, **Fase 4 — Checador construida por adelanto del cliente** (17-ago-2026: `beyond_attendance_qr`, QR rotativo + cuentas de empleado, spec en `docs/checador.md`). Siguen Fases 2 (Venta y caja) y 3 (Inventario). Del módulo contractual 5 (BI) están construidos los dos tableros —director y gerente— en `beyond_reports`, sobre las fuentes que ya existían.
|
||||
- Decisiones abiertas: D4 (datos a migrar), D6 (formato de referencia del ticket-prefactura)
|
||||
- Decisiones ya tomadas:
|
||||
- D1 resuelta — **reskin OWL del POS** (ruta híbrida; evidencia en `docs/adr/ADR-001-spike-pos.md`)
|
||||
@@ -24,6 +24,7 @@ Sistema de gestión multisucursal para Beyond (red de sucursales en Puebla, Méx
|
||||
4. **Español** en toda cadena visible al usuario. Código, nombres de campos, modelos y comentarios técnicos en inglés.
|
||||
5. **Nada que corra en la carga de módulos puede impedir el arranque** (ADR-011). Toda tarea de `<function>`, `init()` o hook va envuelta en `ejecutar_en_arranque` (`beyond_base/tools/arranque.py`): si falla, se registra y el sistema levanta. Los datos de módulo **no** escriben sobre modelos con guardias de estado (`pos.config`, `account.tax`, `pos.payment.method`): eso va en una función que detecta la condición y difiere. Una caja de POS abierta ya tumbó producción una vez.
|
||||
6. **Aislamiento por sucursal es sagrado:** cualquier modelo operativo nuevo lleva `branch_id` y su `ir.rule`. Todo cambio de permisos lleva test automatizado (brief, sección 4).
|
||||
7. **No modificar el entorno del desarrollador** (credenciales, bases, configuración, servicios) **sin autorización explícita en el encargo** (23-ago-2026). Si falta acceso, preguntar u operar en stack desechable. Todo cambio de entorno autorizado se reporta con su reversa.
|
||||
|
||||
## Convenciones
|
||||
|
||||
@@ -45,7 +46,10 @@ docker compose exec odoo odoo -d beyond_dev -u MODULO --stop-after-init # actu
|
||||
|
||||
- Base de datos de desarrollo: `beyond_dev`
|
||||
- Addons propios montados en `/mnt/extra-addons` dentro del contenedor
|
||||
- Tests: `docker compose exec odoo odoo -d beyond_dev --test-enable -u MODULO --stop-after-init`
|
||||
- Tests: `./scripts/pruebas.sh` (crea y tira una base desechable `beyond_test`).
|
||||
**No corras la suite contra `beyond_dev`**: `ir.sequence` usa una secuencia de
|
||||
PostgreSQL, que no se revierte con la transacción, así que cada pasada quema
|
||||
números y los códigos de sucursal acaban en S2233.
|
||||
|
||||
## Definición de "hecho" (toda entrega)
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# Imagen de PRUEBAS de Beyond.
|
||||
#
|
||||
# The only thing it adds to the runtime image is a browser. Odoo runs its
|
||||
# JavaScript suites — hoot unit tests AND tours — through browser_js, which
|
||||
# drives a real Chrome in headless mode. Without one, `--test-enable` SKIPS
|
||||
# them silently, and a widget can be dead in the interface while every test
|
||||
# passes. That is not hypothetical: it happened, with the photo menu of
|
||||
# beyond_image_camera.
|
||||
#
|
||||
# NOT the production image and NOT the dev compose: a third artifact, used by
|
||||
# scripts/pruebas.sh and by the CI still pending in docs/despliegue.md.
|
||||
# Producción no lleva navegador.
|
||||
FROM odoo:19@sha256:84d09c623fc78050c2195161b98897995ba68c87aa4212d0ec0f4f3ce88c7610
|
||||
|
||||
USER root
|
||||
|
||||
# Chromium de Playwright, fijado por versión de playwright. Tres candidatos
|
||||
# quedaron descartados por motivos concretos:
|
||||
# · Ubuntu `chromium` / `chromium-browser` en noble es un paquete de
|
||||
# transición a snap (2:1snap1) que no se instala en un contenedor.
|
||||
# · Chrome for Testing publica SOLO linux64 (x86-64), y las máquinas de
|
||||
# desarrollo del proyecto son arm64: no arranca ni con emulación cómoda.
|
||||
# · El repositorio apt de Google sirve siempre «la última», así que la
|
||||
# versión no se puede fijar.
|
||||
# Playwright publica builds de Chromium para arm64 y amd64 bajo la misma
|
||||
# versión, así que ESTE MISMO Dockerfile produce el mismo navegador en la
|
||||
# máquina de desarrollo y en la CI. Se sube a propósito, como el digest.
|
||||
ARG PLAYWRIGHT_VERSION=1.56.0
|
||||
ENV PLAYWRIGHT_BROWSERS_PATH=/opt/navegador
|
||||
|
||||
# python3-websocket: sin él Odoo SALTA las pruebas de navegador en vez de
|
||||
# fallar — el verde silencioso que este archivo existe para eliminar.
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
python3-websocket python3-pip \
|
||||
ca-certificates fonts-liberation \
|
||||
libnss3 libnspr4 libdbus-1-3 libatk1.0-0t64 libatk-bridge2.0-0t64 \
|
||||
libcups2t64 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 \
|
||||
libxfixes3 libxrandr2 libgbm1 libxshmfence1 libasound2t64 \
|
||||
libpango-1.0-0 libcairo2 libatspi2.0-0t64 \
|
||||
&& pip3 install --no-cache-dir --break-system-packages \
|
||||
"playwright==${PLAYWRIGHT_VERSION}" \
|
||||
&& python3 -m playwright install chromium \
|
||||
&& pip3 uninstall -y --break-system-packages playwright \
|
||||
&& apt-get purge -y python3-pip \
|
||||
&& apt-get autoremove -y \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& chmod -R a+rX /opt/navegador
|
||||
|
||||
# Odoo busca el ejecutable por nombre en PATH: google-chrome, chromium,
|
||||
# chromium-browser o google-chrome-stable (odoo/tests/common.py).
|
||||
RUN ln -sf "$(find /opt/navegador -name chrome -type f | head -1)" \
|
||||
/usr/local/bin/google-chrome
|
||||
|
||||
USER odoo
|
||||
@@ -25,9 +25,43 @@ con país México, idioma Español (MX) y moneda MXN.
|
||||
```
|
||||
addons/ Módulos propios (prefijo beyond_)
|
||||
docs/ Brief, ADRs, documentación de integraciones
|
||||
scripts/ Respaldo y restauración
|
||||
scripts/ Respaldo, restauración y suite de pruebas
|
||||
```
|
||||
|
||||
## Pruebas
|
||||
|
||||
La suite corre contra una base **desechable**, creada desde cero en cada corrida
|
||||
y borrada al terminar:
|
||||
|
||||
```bash
|
||||
./scripts/pruebas.sh # los seis módulos propios
|
||||
./scripts/pruebas.sh beyond_base # solo uno (y sus dependencias)
|
||||
./scripts/pruebas.sh --conservar # deja la base viva para investigar
|
||||
```
|
||||
|
||||
Por qué no se corre sobre `beyond_dev`: esa base acumula estado que no tiene
|
||||
que ver con el código (módulos desinstalados, compañías demo sobrantes,
|
||||
impuestos editados a mano), y una línea base que no es cero deja de ser señal.
|
||||
**`beyond_dev` es para mirar pantallas; `beyond_test` es para saber si
|
||||
funciona.**
|
||||
|
||||
Tres cosas que el script hace y que a mano se olvidan:
|
||||
|
||||
- **`--with-demo`**: en Odoo 19 los datos demo están APAGADOS por defecto en
|
||||
bases nuevas. `beyond_dev` los tiene porque se creó desde el gestor de bases
|
||||
con la casilla puesta. Sin la bandera no hay sucursales demo y varios tests
|
||||
fallan buscando una.
|
||||
- **`--test-tags`**: acota la corrida a nuestros módulos. `--test-enable` a
|
||||
secas arrastra los ~3700 tests del core, muchos de ellos tours que no pueden
|
||||
pasar sin navegador en el contenedor.
|
||||
- **Puertos propios (8169/8172)**: el servidor de desarrollo ocupa el 8069 y
|
||||
los tests de HTTP necesitan enlazar algo. Sin esto la corrida muere con
|
||||
"Address already in use" antes del primer test.
|
||||
|
||||
No hay navegador en el contenedor, así que **los tours no se pueden correr**.
|
||||
Las pruebas de interfaz van como unitarias JS (`web.assets_unit_tests`), que sí
|
||||
corren sin navegador.
|
||||
|
||||
## Módulos del sistema (roadmap en BRIEF.md §7)
|
||||
|
||||
| Módulo | Propósito |
|
||||
|
||||
@@ -26,6 +26,7 @@ calcada del sistema Taboada de Collina:
|
||||
'security/ir.model.access.csv',
|
||||
'data/config.xml',
|
||||
'data/cron.xml',
|
||||
'data/arranque_personal.xml',
|
||||
'data/menu_cleanup.xml',
|
||||
'data/personal.xml',
|
||||
'views/checada_templates.xml',
|
||||
@@ -41,9 +42,17 @@ calcada del sistema Taboada de Collina:
|
||||
'beyond_attendance_qr/static/src/kiosco_abrir/kiosco_abrir_dialog.scss',
|
||||
'beyond_attendance_qr/static/src/kiosco_abrir/kiosco_abrir_dialog.js',
|
||||
'beyond_attendance_qr/static/src/kiosco_abrir/kiosco_abrir_dialog.xml',
|
||||
'beyond_attendance_qr/static/src/personal/beyond_equipo.js',
|
||||
'beyond_attendance_qr/static/src/personal/beyond_equipo.xml',
|
||||
'beyond_attendance_qr/static/src/personal/beyond_ficha_personal.js',
|
||||
'beyond_attendance_qr/static/src/personal/beyond_celular_aviso.js',
|
||||
'beyond_attendance_qr/static/src/personal/beyond_ficha_personal.xml',
|
||||
'beyond_attendance_qr/static/src/personal/beyond_personal.scss',
|
||||
],
|
||||
},
|
||||
'demo': [],
|
||||
'demo': [
|
||||
'demo/demo_personal.xml',
|
||||
],
|
||||
'installable': True,
|
||||
'application': False,
|
||||
}
|
||||
@@ -5,6 +5,35 @@ from odoo.addons.portal.controllers.web import Home as PortalHome
|
||||
from odoo.http import request
|
||||
|
||||
|
||||
# Un /odoo PELADO —sin acción en la dirección— es lo que hace que Odoo llame
|
||||
# a _loadDefaultApp, que es donde el otro desarrollador engancha el Menú
|
||||
# Principal (beyond_base). Por eso el destino de quien administra es este y
|
||||
# no una ruta propia: no hace falta tocar su archivo ni adivinar una URL.
|
||||
MENU_PRINCIPAL = '/odoo'
|
||||
RUTAS_DE_BACKEND = ('/odoo', '/web')
|
||||
|
||||
|
||||
def _es_ruta_de_backend(destino):
|
||||
"""¿El destino pendiente es el backend (o ninguno)?
|
||||
|
||||
Sirve para distinguir «vengo de que se me venció la sesión dentro del
|
||||
sistema» de «vengo de un enlace nuestro»: el kiosco manda a login con su
|
||||
token en el redirect, y ESE hay que respetarlo o se pierde la checada.
|
||||
"""
|
||||
if not destino:
|
||||
return True
|
||||
return destino.split('?')[0].rstrip('/').startswith(RUTAS_DE_BACKEND)
|
||||
|
||||
|
||||
def _beyond_administra(uid):
|
||||
"""Quien administra —sucursal o red— y no es una cuenta técnica."""
|
||||
Employee = request.env['hr.employee'].sudo()
|
||||
user = request.env['res.users'].sudo().browse(uid).exists()
|
||||
if not user or Employee._beyond_usuario_protegido(user):
|
||||
return False
|
||||
return user.has_group('beyond_base.beyond_group_admin_sucursal')
|
||||
|
||||
|
||||
def _destino_beyond(uid):
|
||||
"""Ruta propia de un usuario según su NIVEL DE ACCESO (ADR-008), no
|
||||
según el tipo técnico de su cuenta: Colaborador → su panel;
|
||||
@@ -41,7 +70,16 @@ class BeyondHome(PortalHome):
|
||||
"""
|
||||
|
||||
def _login_redirect(self, uid, redirect=None):
|
||||
return super()._login_redirect(uid, redirect=redirect or _destino_beyond(uid))
|
||||
destino = _destino_beyond(uid)
|
||||
if destino:
|
||||
return super()._login_redirect(uid, redirect=redirect or destino)
|
||||
# Quien administra entra SIEMPRE por el Menú Principal, no donde se
|
||||
# quedó: al vencerse la sesión, Odoo guarda la última dirección en el
|
||||
# redirect del login y sin esto se vuelve a caer en la última app.
|
||||
# Un enlace nuestro (kiosco, panel) sí se respeta.
|
||||
if _beyond_administra(uid) and _es_ruta_de_backend(redirect):
|
||||
redirect = MENU_PRINCIPAL
|
||||
return super()._login_redirect(uid, redirect=redirect)
|
||||
|
||||
@http.route()
|
||||
def index(self, *args, **kw):
|
||||
|
||||
@@ -60,7 +60,7 @@ class BeyondClaveController(http.Controller):
|
||||
request.session.authenticate(
|
||||
request.env, {'login': login, 'password': nueva, 'type': 'password'})
|
||||
empleado = self._empleado()
|
||||
request.env['beyond.bitacora'].sudo().registrar(
|
||||
request.env['beyond.bitacora'].sudo()._registrar(
|
||||
'password_cambiada', 'hr.employee', empleado.id or 0,
|
||||
despues={'empleado': empleado.name or usuario.name,
|
||||
'motivo': 'primer acceso' if forzado else 'a petición propia'},
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<odoo>
|
||||
<!-- Tareas de arranque del rediseño de Personal (ADR-018). Corren en
|
||||
cada actualización porque son idempotentes y porque así lo que la
|
||||
base ya instalada necesita entra sola, sin comandos post-despliegue.
|
||||
Las dos van envueltas en ejecutar_en_arranque (ADR-011). -->
|
||||
<function model="beyond.checador.config" name="_beyond_arranque_horas_semana"/>
|
||||
<function model="hr.attendance" name="_beyond_arranque_migrar_revision"/>
|
||||
</odoo>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<data noupdate="1">
|
||||
<!-- Personal de demostración: un caso de cada cosa que la pantalla
|
||||
sabe pintar —trabajando ahora, ya salió, sin entrada hoy, dos
|
||||
jornadas el mismo día por la comida, un cierre automático, quien
|
||||
se pasa de la meta, un admin de sucursal y alguien sin cuenta—.
|
||||
|
||||
Todo en una función porque casi todo son horas relativas a ahora:
|
||||
una fecha fija en un XML deja de significar nada al día
|
||||
siguiente. -->
|
||||
<function model="hr.employee" name="_beyond_demo_personal"/>
|
||||
</data>
|
||||
</odoo>
|
||||
@@ -45,7 +45,7 @@ class BeyondAjuste(models.Model):
|
||||
def create(self, vals_list):
|
||||
ajustes = super().create(vals_list)
|
||||
for ajuste in ajustes:
|
||||
self.env['beyond.bitacora'].registrar(
|
||||
self.env['beyond.bitacora']._registrar(
|
||||
'ajuste_creado', self._name, ajuste.id,
|
||||
despues={'empleado': ajuste.employee_id.name,
|
||||
'minutos': ajuste.minutos, 'motivo': ajuste.motivo},
|
||||
@@ -54,7 +54,7 @@ class BeyondAjuste(models.Model):
|
||||
|
||||
def unlink(self):
|
||||
for ajuste in self:
|
||||
self.env['beyond.bitacora'].registrar(
|
||||
self.env['beyond.bitacora']._registrar(
|
||||
'ajuste_eliminado', self._name, ajuste.id,
|
||||
antes={'empleado': ajuste.employee_id.name,
|
||||
'minutos': ajuste.minutos, 'motivo': ajuste.motivo},
|
||||
|
||||
@@ -67,9 +67,22 @@ class BeyondBitacora(models.Model):
|
||||
raise UserError(_('La bitácora es inmutable: no se puede borrar.'))
|
||||
|
||||
@api.model
|
||||
def registrar(self, accion, entidad, entidad_id, antes=None, despues=None, branch=None):
|
||||
def _registrar(self, accion, entidad, entidad_id, antes=None, despues=None, branch=None):
|
||||
"""Único punto de escritura. Siempre con sudo: la bitácora registra
|
||||
aunque quien dispare la acción no tenga ACL sobre este modelo."""
|
||||
aunque quien dispare la acción no tenga ACL sobre este modelo.
|
||||
|
||||
PRIVADO a propósito (barrido del 26-ago-2026, ADR-019). Se llamaba
|
||||
`registrar`, sin guion bajo, y en Odoo eso significa «llamable por
|
||||
RPC»: cualquiera con sesión —incluida la cuenta portal de un
|
||||
empleado, que ni siquiera puede LEER este modelo— podía escribir un
|
||||
renglón inventado, con la acción, la entidad y el contenido que
|
||||
quisiera. La bitácora existe para poder confiar en lo que dice, y no
|
||||
hace falta poder leerla para poder ensuciarla.
|
||||
|
||||
El guion bajo es la guardia entera: Odoo rechaza por RPC los nombres
|
||||
que empiezan por «_», así que la puerta se cierra sin depender de que
|
||||
nadie se acuerde de comprobar nada.
|
||||
"""
|
||||
return self.sudo().create({
|
||||
'actor_id': self.env.user.id,
|
||||
'accion': accion,
|
||||
|
||||
@@ -4,8 +4,13 @@ import re
|
||||
from odoo import _, api, fields, models
|
||||
from odoo.exceptions import ValidationError
|
||||
|
||||
from odoo.addons.beyond_base.tools.arranque import ejecutar_en_arranque
|
||||
|
||||
HORA_RE = re.compile(r'^([01]\d|2[0-3]):[0-5]\d$')
|
||||
|
||||
# 40 h: lo que estaba en duro antes de que la meta fuera configurable.
|
||||
HORAS_SEMANA_POR_OMISION = 40
|
||||
|
||||
|
||||
class BeyondChecadorConfig(models.TransientModel):
|
||||
"""Configuración del checador para el ADMIN GENERAL, bajo el menú
|
||||
@@ -18,15 +23,49 @@ class BeyondChecadorConfig(models.TransientModel):
|
||||
ventana_inicio = fields.Char(string='Apertura del checado (HH:MM)', required=True)
|
||||
ventana_fin = fields.Char(string='Cierre del checado (HH:MM)', required=True)
|
||||
qr_rotacion_seg = fields.Integer(string='Rotación del QR (segundos)', required=True)
|
||||
# La meta semanal deja de estar en duro (25-ago-2026): es lo que la
|
||||
# pantalla de Equipo compara con las horas de cada persona, y cambiarla
|
||||
# no puede exigir un despliegue.
|
||||
horas_semana = fields.Integer(
|
||||
string='Jornada esperada (horas por semana)', required=True)
|
||||
|
||||
@api.model
|
||||
def default_get(self, fields_list):
|
||||
valores = super().default_get(fields_list)
|
||||
rotacion, inicio, fin = self.env['beyond.checada.token']._config_kiosco()
|
||||
valores.update(ventana_inicio=inicio, ventana_fin=fin,
|
||||
qr_rotacion_seg=rotacion)
|
||||
qr_rotacion_seg=rotacion,
|
||||
horas_semana=self._beyond_horas_semana())
|
||||
return valores
|
||||
|
||||
@api.model
|
||||
def _beyond_horas_semana(self):
|
||||
"""La meta semanal, con su valor por omisión si nadie la ha tocado."""
|
||||
valor = self.env['ir.config_parameter'].sudo().get_param(
|
||||
'beyond_attendance_qr.horas_semana', str(HORAS_SEMANA_POR_OMISION))
|
||||
try:
|
||||
horas = int(valor)
|
||||
except (TypeError, ValueError):
|
||||
return HORAS_SEMANA_POR_OMISION
|
||||
return horas if horas > 0 else HORAS_SEMANA_POR_OMISION
|
||||
|
||||
@api.model
|
||||
def _beyond_arranque_horas_semana(self):
|
||||
"""Deja la meta escrita en las bases que ya existían (ADR-011).
|
||||
|
||||
Sin esto la configuración se abriría con el campo vacío hasta que
|
||||
alguien lo guardara, y la pantalla de Equipo compararía contra nada.
|
||||
"""
|
||||
ejecutar_en_arranque(
|
||||
self.env, 'meta semanal del checador', self._beyond_fijar_horas_semana)
|
||||
|
||||
@api.model
|
||||
def _beyond_fijar_horas_semana(self):
|
||||
icp = self.env['ir.config_parameter'].sudo()
|
||||
if not icp.get_param('beyond_attendance_qr.horas_semana'):
|
||||
icp.set_param('beyond_attendance_qr.horas_semana',
|
||||
str(HORAS_SEMANA_POR_OMISION))
|
||||
|
||||
def action_guardar(self):
|
||||
self.ensure_one()
|
||||
Token = self.env['beyond.checada.token']
|
||||
@@ -37,6 +76,8 @@ class BeyondChecadorConfig(models.TransientModel):
|
||||
'La hora de %s debe tener formato HH:MM (24 horas).', etiqueta))
|
||||
if self.ventana_inicio >= self.ventana_fin:
|
||||
raise ValidationError(_('La apertura debe ser antes del cierre.'))
|
||||
if self.horas_semana <= 0:
|
||||
raise ValidationError(_('La jornada esperada debe ser mayor que cero.'))
|
||||
if self.qr_rotacion_seg < Token.ROTACION_MINIMA_SEG:
|
||||
raise ValidationError(_(
|
||||
'La rotación mínima es de %s segundos.', Token.ROTACION_MINIMA_SEG))
|
||||
@@ -45,9 +86,11 @@ class BeyondChecadorConfig(models.TransientModel):
|
||||
icp.set_param('beyond_attendance_qr.ventana_inicio', self.ventana_inicio)
|
||||
icp.set_param('beyond_attendance_qr.ventana_fin', self.ventana_fin)
|
||||
icp.set_param('beyond_attendance_qr.qr_rotacion_seg', str(self.qr_rotacion_seg))
|
||||
self.env['beyond.bitacora'].registrar(
|
||||
icp.set_param('beyond_attendance_qr.horas_semana', str(self.horas_semana))
|
||||
self.env['beyond.bitacora']._registrar(
|
||||
'config_checador', self._name, self.id,
|
||||
antes=antes,
|
||||
despues={'rotacion': self.qr_rotacion_seg,
|
||||
'inicio': self.ventana_inicio, 'fin': self.ventana_fin})
|
||||
'inicio': self.ventana_inicio, 'fin': self.ventana_fin,
|
||||
'horas_semana': self.horas_semana})
|
||||
return {'type': 'ir.actions.act_window_close'}
|
||||
@@ -22,9 +22,15 @@ class BeyondEmployeePassword(models.TransientModel):
|
||||
# de su(s) sucursal(es).
|
||||
empleado = self.env['hr.employee'].browse(self.employee_id.id)
|
||||
empleado.read(['name'])
|
||||
usuario = empleado.sudo().beyond_portal_user_id
|
||||
if not usuario:
|
||||
raise UserError(_('%s no tiene cuenta del checador.', empleado.name))
|
||||
# Sin cuenta pero CON celular, la cuenta se crea: es una ficha a
|
||||
# medias —creada sin celular y completada después—, y hasta ahora el
|
||||
# asistente se limitaba a decir que no había nada que restablecer,
|
||||
# dejando a esa persona sin poder entrar nunca. Sin celular sí se
|
||||
# para, porque el celular es el usuario y hay que capturarlo antes.
|
||||
if not empleado.sudo().beyond_portal_user_id and not empleado.beyond_celular:
|
||||
raise UserError(_(
|
||||
'%s no tiene celular: captúralo primero, que es su usuario '
|
||||
'para entrar.', empleado.name))
|
||||
# Mismo mecanismo que el alta: la clave que fija otra persona nace
|
||||
# TEMPORAL y el sistema obliga a cambiarla al entrar. Sin esto, quien
|
||||
# restablece podría guardarse la clave y entrar como el empleado
|
||||
|
||||
@@ -94,7 +94,7 @@ class BeyondSolicitud(models.Model):
|
||||
'check_out': str(solicitud.resolucion_salida_ts),
|
||||
'antes': antes}
|
||||
solicitud._marcar_resuelta('autorizada')
|
||||
self.env['beyond.bitacora'].registrar(
|
||||
self.env['beyond.bitacora']._registrar(
|
||||
'solicitud_autorizada', self._name, solicitud.id,
|
||||
despues=dict(despues, tipo=solicitud.tipo,
|
||||
empleado=solicitud.employee_id.name),
|
||||
@@ -115,7 +115,7 @@ class BeyondSolicitud(models.Model):
|
||||
beyond_sistema=True).write({'beyond_estado': 'rechazada'})
|
||||
despues['jornada'] = solicitud.jornada_id.id
|
||||
despues['estado_jornada'] = 'rechazada'
|
||||
self.env['beyond.bitacora'].registrar(
|
||||
self.env['beyond.bitacora']._registrar(
|
||||
'solicitud_rechazada', self._name, solicitud.id,
|
||||
despues=despues, branch=solicitud.branch_id)
|
||||
return True
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
from datetime import timedelta
|
||||
|
||||
from odoo import api, fields, models
|
||||
|
||||
from odoo.addons.beyond_base.tools.arranque import ejecutar_en_arranque
|
||||
|
||||
# Campos cuya edición administrativa se bitacorea (el original nunca se pierde)
|
||||
CAMPOS_AUDITADOS = ('check_in', 'check_out', 'beyond_estado')
|
||||
|
||||
# Una jornada que el cron cierra con más de estas horas no es un olvido
|
||||
# normal: se cierra igual —dejarla abierta es peor— pero se anota, porque un
|
||||
# cierre de treinta horas no puede pasar en silencio por la nómina.
|
||||
LIMITE_ANOMALIA_HORAS = 16
|
||||
|
||||
|
||||
class HrAttendance(models.Model):
|
||||
"""La JORNADA del checador (docs/checador.md §3): hr.attendance nativo
|
||||
@@ -11,18 +20,28 @@ class HrAttendance(models.Model):
|
||||
ediciones. Las jornadas en `revision` no suman."""
|
||||
_inherit = 'hr.attendance'
|
||||
|
||||
# C-019: 'rechazada' = el supervisor atendió el auto-cierre y decidió no
|
||||
# reconocer la jornada. Se distingue de 'revision' (aún pendiente); no
|
||||
# suma horas y sus checadas quedan intactas.
|
||||
# 'revision' se retira (25-ago-2026): ya no hay cola que resuelva nada,
|
||||
# el cron cierra solo y las horas cuentan.
|
||||
#
|
||||
# 'rechazada' SE QUEDA aunque ningún camino nuevo pueda producirlo. Es un
|
||||
# hecho histórico —alguien rechazó esa jornada y esas horas no se
|
||||
# pagaron— y reescribirlo a 'cerrada' falsearía el registro laboral, que
|
||||
# es justo lo que este módulo existe para proteger. Estado en desuso, no
|
||||
# eliminado (ADR-018).
|
||||
beyond_estado = fields.Selection(
|
||||
[('abierta', 'Abierta'), ('cerrada', 'Cerrada'),
|
||||
('revision', 'En revisión'), ('rechazada', 'Rechazada')],
|
||||
('rechazada', 'Rechazada')],
|
||||
string='Estado Beyond', default='abierta', required=True, index=True)
|
||||
beyond_checada_entrada_id = fields.Many2one(
|
||||
'beyond.checada', string='Checada de entrada', ondelete='restrict', readonly=True)
|
||||
beyond_checada_salida_id = fields.Many2one(
|
||||
'beyond.checada', string='Checada de salida', ondelete='restrict', readonly=True)
|
||||
beyond_editada = fields.Boolean(string='Editada por supervisor', default=False)
|
||||
# Cerrada por el cron al fin de la ventana, no por la persona. Las horas
|
||||
# CUENTAN (decisión del cliente, 25-ago-2026): la marca existe para que el
|
||||
# cierre se vea en la ficha, no para descontarlo.
|
||||
beyond_autocerrada = fields.Boolean(
|
||||
string='Cierre automático', default=False, readonly=True, copy=False)
|
||||
# Las horas Beyond son salida − entrada, SIN los descuentos de comida
|
||||
# que worked_hours nativo aplica según el calendario del empleado (regla
|
||||
# Taboada: cualquier descuento es una edición o un ajuste explícito y
|
||||
@@ -59,7 +78,7 @@ class HrAttendance(models.Model):
|
||||
jornadas = super().create(vals_list)
|
||||
if not self.env.context.get('beyond_sistema'):
|
||||
for jornada in jornadas:
|
||||
self.env['beyond.bitacora'].registrar(
|
||||
self.env['beyond.bitacora']._registrar(
|
||||
'jornada_creada_manual', self._name, jornada.id,
|
||||
despues={'empleado': jornada.employee_id.name,
|
||||
'check_in': str(jornada.check_in),
|
||||
@@ -69,33 +88,128 @@ class HrAttendance(models.Model):
|
||||
|
||||
@api.model
|
||||
def _beyond_cron_auto_cierre(self, ahora=None):
|
||||
"""Tarea programada (Taboada §6): al cierre de la ventana horaria,
|
||||
toda jornada que quedó SIN salida pasa a `revision` (deja de contar)
|
||||
y genera una solicitud de auto-cierre para que el supervisor fije la
|
||||
salida real. Idempotente: solo toca jornadas abiertas. `ahora` es
|
||||
inyectable para los tests."""
|
||||
"""Cierra sola la jornada que quedó sin salida (25-ago-2026).
|
||||
|
||||
Antes pasaba a `revision`, no sumaba y esperaba a que un supervisor
|
||||
la resolviera. El cliente decidió que no haya revisión: la jornada se
|
||||
cierra a la hora de FIN de la ventana del checador y **las horas
|
||||
cuentan**, con la advertencia que eso trae —quien olvida marcar
|
||||
salida cobra hasta el cierre— anotada en ADR-018.
|
||||
|
||||
Idempotente: solo mira jornadas abiertas. `ahora` es inyectable para
|
||||
los tests.
|
||||
"""
|
||||
Token = self.env['beyond.checada.token']
|
||||
if Token._ventana_abierta(ahora=ahora):
|
||||
return 0
|
||||
abiertas = self.sudo().search([('beyond_estado', '=', 'abierta')])
|
||||
_rotacion, _inicio, fin = Token._config_kiosco()
|
||||
# active_test=False: dar de baja ARCHIVA a la persona, y una jornada
|
||||
# suya que quedara abierta no la volvería a mirar nadie. Su última
|
||||
# nómina es justo la que no puede salir mal.
|
||||
abiertas = self.sudo().with_context(active_test=False).search(
|
||||
[('beyond_estado', '=', 'abierta')])
|
||||
for jornada in abiertas:
|
||||
jornada.with_context(beyond_sistema=True).write(
|
||||
{'beyond_estado': 'revision'})
|
||||
self.env['beyond.solicitud'].sudo().with_context(
|
||||
beyond_sistema=True).create({
|
||||
'employee_id': jornada.employee_id.id,
|
||||
'tipo': 'autorizar_autocierre',
|
||||
'jornada_id': jornada.id,
|
||||
})
|
||||
self.env['beyond.bitacora'].registrar(
|
||||
cierre = jornada._beyond_hora_de_cierre(fin)
|
||||
horas = (cierre - jornada.check_in).total_seconds() / 3600.0
|
||||
if cierre <= jornada.check_in:
|
||||
# No hay jornada que cerrar: la persona volvió a entrar en el
|
||||
# mismo instante. Se cierra en cero antes que dejarla abierta.
|
||||
cierre = jornada.check_in
|
||||
horas = 0.0
|
||||
jornada.with_context(beyond_sistema=True).write({
|
||||
'check_out': cierre,
|
||||
'beyond_estado': 'cerrada',
|
||||
'beyond_autocerrada': True,
|
||||
})
|
||||
self.env['beyond.bitacora']._registrar(
|
||||
'jornada_auto_cerrada', self._name, jornada.id,
|
||||
despues={'empleado': jornada.employee_id.name,
|
||||
'check_in': str(jornada.check_in)},
|
||||
'check_in': str(jornada.check_in),
|
||||
'check_out': str(cierre),
|
||||
'horas': round(horas, 2)},
|
||||
branch=jornada.branch_id)
|
||||
if horas > LIMITE_ANOMALIA_HORAS:
|
||||
self.env['beyond.bitacora']._registrar(
|
||||
'jornada_auto_cerrada_anomala', self._name, jornada.id,
|
||||
despues={'empleado': jornada.employee_id.name,
|
||||
'horas': round(horas, 2),
|
||||
'limite': LIMITE_ANOMALIA_HORAS},
|
||||
branch=jornada.branch_id)
|
||||
# aprovechar el tick para limpiar tokens vencidos
|
||||
self.env['beyond.checada.token']._limpiar_vencidos()
|
||||
return len(abiertas)
|
||||
|
||||
@api.model
|
||||
def _beyond_arranque_migrar_revision(self):
|
||||
"""Cierra las jornadas que se quedaron esperando una resolución que
|
||||
ya no va a llegar (ADR-011 para que no tumbe el arranque)."""
|
||||
ejecutar_en_arranque(
|
||||
self.env, 'migrar jornadas en revisión', self._beyond_migrar_revision)
|
||||
|
||||
@api.model
|
||||
def _beyond_migrar_revision(self):
|
||||
"""`revision` desaparece: sus jornadas pasan a cerradas.
|
||||
|
||||
No se marcan como autocerradas —no lo fueron, nadie las cerró al fin
|
||||
de la ventana— pero sí queda el rastro en la bitácora de que las
|
||||
cerró esta migración, para que dentro de un año se distingan de un
|
||||
cierre normal.
|
||||
|
||||
Se cierran con el mismo criterio que el cron: el fin de la ventana
|
||||
del día de la entrada. Esas horas pasan a contar, que es la
|
||||
consecuencia de la decisión y está advertida en ADR-018.
|
||||
"""
|
||||
Token = self.env['beyond.checada.token']
|
||||
_rotacion, _inicio, fin = Token._config_kiosco()
|
||||
pendientes = self.sudo().with_context(active_test=False).search(
|
||||
[('beyond_estado', '=', 'revision')])
|
||||
for jornada in pendientes:
|
||||
cierre = jornada.check_out or jornada._beyond_hora_de_cierre(fin)
|
||||
if cierre <= jornada.check_in:
|
||||
cierre = jornada.check_in
|
||||
jornada.with_context(beyond_sistema=True).write({
|
||||
'check_out': cierre, 'beyond_estado': 'cerrada'})
|
||||
self.env['beyond.bitacora']._registrar(
|
||||
'jornada_cerrada_por_migracion', self._name, jornada.id,
|
||||
antes={'beyond_estado': 'revision'},
|
||||
despues={'empleado': jornada.employee_id.name,
|
||||
'check_out': str(cierre),
|
||||
'motivo': 'se retiró el estado «en revisión»'},
|
||||
branch=jornada.branch_id)
|
||||
return len(pendientes)
|
||||
|
||||
def _beyond_hora_de_cierre(self, fin_hhmm):
|
||||
"""El fin de la ventana del día de la ENTRADA, en UTC, sin pisar la
|
||||
jornada siguiente de esa misma persona.
|
||||
|
||||
Si la entrada quedó después de esa hora —solo puede pasar por el
|
||||
puente del kiosco nativo con PIN, que no valida la ventana—, cerrar
|
||||
en su propio día daría una salida anterior a la entrada, que Odoo
|
||||
rechaza y con razón. En ese caso se cierra en el fin de ventana
|
||||
siguiente y la guarda de horas se encarga de que no pase callado.
|
||||
"""
|
||||
import pytz
|
||||
self.ensure_one()
|
||||
tz = pytz.timezone(self.env['beyond.checada.token'].TZ_LOCAL)
|
||||
hora, minuto = (int(parte) for parte in fin_hhmm.split(':'))
|
||||
entrada_local = pytz.utc.localize(self.check_in).astimezone(tz).replace(tzinfo=None)
|
||||
cierre_local = entrada_local.replace(
|
||||
hour=hora, minute=minuto, second=0, microsecond=0)
|
||||
if cierre_local <= entrada_local:
|
||||
cierre_local += timedelta(days=1)
|
||||
cierre = tz.localize(cierre_local).astimezone(pytz.utc).replace(tzinfo=None)
|
||||
|
||||
# Nadie estuvo trabajando después de haber vuelto a entrar. Una
|
||||
# jornada vieja que se quedó abierta puede tener jornadas POSTERIORES
|
||||
# de la misma persona, y cerrarla encima de ellas no solo miente: el
|
||||
# core lo rechaza y el cron entero se caería con la primera.
|
||||
siguiente = self.sudo().with_context(active_test=False).search(
|
||||
[('employee_id', '=', self.employee_id.id),
|
||||
('check_in', '>', self.check_in)], order='check_in asc', limit=1)
|
||||
if siguiente and siguiente.check_in < cierre:
|
||||
return siguiente.check_in
|
||||
return cierre
|
||||
|
||||
def write(self, vals):
|
||||
"""Toda edición administrativa de tiempos/estado queda en bitácora y
|
||||
marca la jornada como editada. Los movimientos del propio sistema
|
||||
@@ -111,7 +225,7 @@ class HrAttendance(models.Model):
|
||||
result = super().write(vals)
|
||||
if auditar:
|
||||
for jornada in self:
|
||||
self.env['beyond.bitacora'].registrar(
|
||||
self.env['beyond.bitacora']._registrar(
|
||||
'jornada_editada', self._name, jornada.id,
|
||||
antes=antes[jornada.id],
|
||||
despues={campo: str(getattr(jornada, campo)) for campo in CAMPOS_AUDITADOS},
|
||||
@@ -120,7 +234,7 @@ class HrAttendance(models.Model):
|
||||
|
||||
def unlink(self):
|
||||
for jornada in self:
|
||||
self.env['beyond.bitacora'].registrar(
|
||||
self.env['beyond.bitacora']._registrar(
|
||||
'jornada_eliminada', self._name, jornada.id,
|
||||
antes={'empleado': jornada.employee_id.name,
|
||||
'check_in': str(jornada.check_in),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
import re
|
||||
from datetime import datetime, time
|
||||
from datetime import datetime, time, timedelta
|
||||
|
||||
import pytz
|
||||
|
||||
@@ -95,11 +95,24 @@ class HrEmployee(models.Model):
|
||||
# C-016/C-027: ciclo de vida de la cuenta. TODA persona dada de alta con
|
||||
# celular (por cualquier puerta) nace PENDIENTE con su cuenta creada;
|
||||
# los empleados programáticos sin celular conservan el default activo.
|
||||
# Dos estados, y ninguno se escribe a mano: se DERIVAN de `active`
|
||||
# (25-ago-2026). «Dar de baja» archiva, y archivar da de baja; con dos
|
||||
# campos escribibles diciendo lo mismo, el más probable de los caminos
|
||||
# —alguien archivando desde el engranaje nativo— los separaba en
|
||||
# silencio. Reincorporar funciona igual: desarchivar devuelve a activo.
|
||||
#
|
||||
# 'pendiente' quedó vestigial el 20-ago (sin auto-registro) y se retira
|
||||
# aquí: al ser calculado almacenado, Odoo recalcula la columna entera en
|
||||
# la actualización y quien lo tuviera queda en 'activo'.
|
||||
beyond_cuenta_estado = fields.Selection(
|
||||
[('pendiente', 'Pendiente de aprobación'),
|
||||
('activo', 'Activo'),
|
||||
('baja', 'Baja')],
|
||||
string='Cuenta Beyond', default='activo', required=True, index=True)
|
||||
[('activo', 'Activo'), ('baja', 'Baja')],
|
||||
string='Cuenta Beyond', compute='_compute_beyond_cuenta_estado',
|
||||
store=True, index=True, readonly=True)
|
||||
|
||||
@api.depends('active')
|
||||
def _compute_beyond_cuenta_estado(self):
|
||||
for employee in self:
|
||||
employee.beyond_cuenta_estado = 'activo' if employee.active else 'baja'
|
||||
# La cuenta de la persona (login = celular, ADR-006). Nace portal; si el
|
||||
# acceso sube a administrador se vuelve interna — misma cuenta.
|
||||
beyond_portal_user_id = fields.Many2one(
|
||||
@@ -113,6 +126,21 @@ class HrEmployee(models.Model):
|
||||
# sincronización de grupos vive en _beyond_sync_acceso.
|
||||
# El valor técnico 'checador' se conserva (cambiarlo migraría datos y
|
||||
# bitácora); la etiqueta visible del nivel básico es "Colaborador".
|
||||
# La interfaz ofrece DOS niveles: solo hay una dirección y ya existe
|
||||
# (decisión del cliente, 25-ago-2026). El valor sigue en el campo —hay
|
||||
# gente que lo tiene— pero no se ofrece; a quien ya lo es se le sigue
|
||||
# viendo el suyo, porque esconder la opción no puede esconder el dato.
|
||||
beyond_acceso_ofrecido = fields.Json(
|
||||
string='Niveles que se ofrecen', compute='_compute_beyond_acceso_ofrecido')
|
||||
|
||||
@api.depends('beyond_acceso')
|
||||
def _compute_beyond_acceso_ofrecido(self):
|
||||
for employee in self:
|
||||
ofrecidos = ['checador', 'admin_sucursal']
|
||||
if employee.beyond_acceso and employee.beyond_acceso not in ofrecidos:
|
||||
ofrecidos.append(employee.beyond_acceso)
|
||||
employee.beyond_acceso_ofrecido = ofrecidos
|
||||
|
||||
beyond_acceso = fields.Selection(
|
||||
[('checador', 'Colaborador (sin acceso al sistema)'),
|
||||
('admin_sucursal', 'Administrador de sucursal'),
|
||||
@@ -147,6 +175,32 @@ class HrEmployee(models.Model):
|
||||
self.ensure_one()
|
||||
return dict(self._fields['beyond_acceso'].selection)[self.beyond_acceso]
|
||||
|
||||
def _beyond_crear_cuenta(self, clave):
|
||||
"""Crea la cuenta del checador de alguien que ya tiene celular.
|
||||
|
||||
El alta normal (C-027) la crea junto con la ficha; esto es para las
|
||||
fichas que quedaron a medias, que las hay: sin cuenta no se puede
|
||||
checar ni restablecer nada, así que la ficha no sirve para lo único
|
||||
que tiene que servir.
|
||||
"""
|
||||
self.ensure_one()
|
||||
celular = self._beyond_normalizar_celular(self.beyond_celular or '')
|
||||
if not celular:
|
||||
return self.env['res.users'].browse()
|
||||
usuario = self.env['res.users'].sudo().create({
|
||||
'name': self.name,
|
||||
'login': celular,
|
||||
'password': clave,
|
||||
'beyond_clave_temporal': True,
|
||||
'group_ids': [(6, 0, [self.env.ref('base.group_portal').id])],
|
||||
})
|
||||
self.sudo().write({'beyond_portal_user_id': usuario.id})
|
||||
self.env['beyond.bitacora']._registrar(
|
||||
'cuenta_creada_desde_ficha', self._name, self.id,
|
||||
despues={'empleado': self.name, 'celular': celular},
|
||||
branch=self.branch_id)
|
||||
return usuario
|
||||
|
||||
def _beyond_usuario_protegido(self, user):
|
||||
protegidos = (self.env.ref('base.group_system')
|
||||
| self.env.ref('base.group_erp_manager'))
|
||||
@@ -171,12 +225,19 @@ class HrEmployee(models.Model):
|
||||
raise ValidationError(_('La contraseña debe tener al menos 8 caracteres.'))
|
||||
usuario = self.sudo().beyond_portal_user_id
|
||||
if not usuario:
|
||||
raise UserError(_('%s no tiene cuenta; captura su celular primero.', self.name))
|
||||
# Con celular y sin cuenta, la cuenta se CREA en vez de mandar a
|
||||
# capturar un celular que ya está capturado. Ese estado existe de
|
||||
# verdad —una ficha creada sin celular a la que se le puso
|
||||
# después— y dejaba «Restablecer contraseña» sin efecto posible.
|
||||
usuario = self._beyond_crear_cuenta(clave)
|
||||
if not usuario:
|
||||
raise UserError(_('%s no tiene celular: captúralo primero, que es '
|
||||
'su usuario para entrar.', self.name))
|
||||
if self._beyond_usuario_protegido(usuario):
|
||||
raise UserError(_('La cuenta de %s es técnica y no se gestiona '
|
||||
'desde la ficha.', self.name))
|
||||
usuario.sudo().write({'password': clave, 'beyond_clave_temporal': True})
|
||||
self.env['beyond.bitacora'].registrar(
|
||||
self.env['beyond.bitacora']._registrar(
|
||||
accion, self._name, self.id,
|
||||
despues={'empleado': self.name}, # jamás la contraseña
|
||||
branch=self.branch_id)
|
||||
@@ -240,12 +301,58 @@ class HrEmployee(models.Model):
|
||||
})
|
||||
vals.update(
|
||||
beyond_portal_user_id=user.id,
|
||||
beyond_cuenta_estado='activo',
|
||||
work_contact_id=user.partner_id.id, # C-017: contacto único
|
||||
)
|
||||
# Todo el mundo tiene cuenta y el celular es su usuario (ADR-006):
|
||||
# quien pertenece a una sucursal no puede nacer sin él. Se comprueba
|
||||
# solo al CREAR y solo con sucursal, para no romper ni las fichas que
|
||||
# ya existen ni los empleados que crea el propio Odoo por su cuenta.
|
||||
if not self.env.su:
|
||||
for vals in vals_list:
|
||||
if vals.get('branch_id') and not vals.get('beyond_celular'):
|
||||
raise UserError(_(
|
||||
'Captura el celular: es su usuario para checar, y sin '
|
||||
'él la persona no puede entrar al sistema.'))
|
||||
|
||||
# El guardia del nivel de acceso también en el ALTA: `write` ya lo
|
||||
# tenía, pero crear a la persona directamente ascendida se saltaba la
|
||||
# comprobación entera. Es la misma promoción por otra puerta.
|
||||
if any(vals.get('beyond_acceso') not in (None, False, 'checador')
|
||||
for vals in vals_list):
|
||||
if not (self.env.su
|
||||
or self.env.user.has_group('beyond_base.beyond_group_admin_general')):
|
||||
raise UserError(_('Solo el administrador general puede dar '
|
||||
'acceso al sistema.'))
|
||||
employees = super().create(vals_list)
|
||||
# Odoo deja guardado en la imagen un SVG con las iniciales y un color
|
||||
# de su paleta HSL. No es una foto: es un marcador de posición que
|
||||
# llenaba la lista de avatares verdes y morados y hacía que la ficha
|
||||
# enseñara «una foto» que nadie había subido. Se limpia al nacer, y
|
||||
# así el widget dibuja su propio vacío en durazno y quien suba una de
|
||||
# verdad la ve reemplazar a nada.
|
||||
# La cuenta nueva hereda la imagen del usuario plantilla —un
|
||||
# monograma de la paleta de Odoo—: se limpia al nacer. Lo que ya
|
||||
# existía no se toca, y por eso la lista no depende de esto sino de
|
||||
# la bandera.
|
||||
# Al nacer, la foto es propia SOLO si venía en el alta. Todo lo demás
|
||||
# que aparezca en la imagen durante la creación —el monograma que
|
||||
# Odoo copia del usuario plantilla al crear la cuenta— no lo subió
|
||||
# nadie, y se limpia.
|
||||
#
|
||||
# Se mira lo que pidió QUIEN CREÓ, no lo que quedó en el registro: al
|
||||
# crear la cuenta hay escrituras posteriores sobre la imagen, y mi
|
||||
# primera versión marcaba la bandera con ellas —treinta de cincuenta
|
||||
# y tres seguían pintando el monograma—.
|
||||
for employee, vals in zip(employees, vals_list):
|
||||
propia = bool(vals.get('image_1920'))
|
||||
if not propia and employee.image_1920:
|
||||
employee.sudo().with_context(beyond_sistema=True).write(
|
||||
{'image_1920': False})
|
||||
if employee.beyond_foto_propia != propia:
|
||||
super(HrEmployee, employee.sudo()).write(
|
||||
{'beyond_foto_propia': propia})
|
||||
for employee in employees.filtered('beyond_portal_user_id'):
|
||||
self.env['beyond.bitacora'].registrar(
|
||||
self.env['beyond.bitacora']._registrar(
|
||||
'empleado_alta', self._name, employee.id,
|
||||
despues={'nombre': employee.name,
|
||||
'celular': employee.beyond_celular,
|
||||
@@ -269,6 +376,12 @@ class HrEmployee(models.Model):
|
||||
'gestiona desde la ficha.', employee.name))
|
||||
if employee.beyond_celular and user.login != employee.beyond_celular:
|
||||
user.sudo().write({'login': employee.beyond_celular})
|
||||
# Quien escribe la imagen es el widget de la ficha (o quien la
|
||||
# quita). Es el único momento en que se sabe que la foto es de la
|
||||
# persona y no el monograma que Odoo copió al crear la cuenta.
|
||||
if 'image_1920' in vals and not self.env.context.get('beyond_sistema'):
|
||||
super(HrEmployee, self).write(
|
||||
{'beyond_foto_propia': bool(vals.get('image_1920'))})
|
||||
if 'beyond_acceso' in vals:
|
||||
self._beyond_sync_acceso()
|
||||
return result
|
||||
@@ -303,7 +416,7 @@ class HrEmployee(models.Model):
|
||||
and not user.branch_ids and employee.branch_id):
|
||||
valores['branch_ids'] = [(6, 0, [employee.branch_id.id])]
|
||||
user.sudo().write(valores)
|
||||
self.env['beyond.bitacora'].registrar(
|
||||
self.env['beyond.bitacora']._registrar(
|
||||
'acceso_cambiado', self._name, employee.id,
|
||||
despues={'empleado': employee.name,
|
||||
'acceso': employee._beyond_etiqueta_acceso()},
|
||||
@@ -338,7 +451,6 @@ class HrEmployee(models.Model):
|
||||
'branch_id': user.branch_ids[:1].id or False,
|
||||
'beyond_portal_user_id': user.id,
|
||||
'work_contact_id': user.partner_id.id,
|
||||
'beyond_cuenta_estado': 'activo',
|
||||
'beyond_acceso': acceso,
|
||||
})
|
||||
if celular:
|
||||
@@ -371,27 +483,34 @@ class HrEmployee(models.Model):
|
||||
# ── Aprobación y baja (solo el admin de su sucursal llega aquí: las
|
||||
# ir.rules de Fase 1 sobre hr.employee ya recortan por sucursal) ────
|
||||
|
||||
def action_beyond_aprobar(self):
|
||||
def action_beyond_baja(self):
|
||||
"""Dar de baja: archivar. Nunca borrar.
|
||||
|
||||
Archivar la saca de las listas y de todo lo que filtra por activos, y
|
||||
la cuenta deja de servir. El historial —checadas, jornadas, ventas—
|
||||
se conserva entero: las FK son restrict a propósito.
|
||||
|
||||
El estado de la cuenta no se escribe aquí: se deriva de `active`.
|
||||
"""
|
||||
for employee in self:
|
||||
if employee.beyond_cuenta_estado != 'pendiente':
|
||||
raise UserError(_('%s no está pendiente de aprobación.', employee.name))
|
||||
employee.write({'beyond_cuenta_estado': 'activo'})
|
||||
self.env['beyond.bitacora'].registrar(
|
||||
'empleado_aprobado', self._name, employee.id,
|
||||
if not employee.active:
|
||||
raise UserError(_('%s ya está dado de baja.', employee.name))
|
||||
employee.action_archive()
|
||||
employee.beyond_portal_user_id.sudo().write({'active': False})
|
||||
self.env['beyond.bitacora']._registrar(
|
||||
'empleado_baja', self._name, employee.id,
|
||||
despues={'nombre': employee.name},
|
||||
branch=employee.branch_id)
|
||||
return True
|
||||
|
||||
def action_beyond_baja(self):
|
||||
def action_beyond_reincorporar(self):
|
||||
"""Volver a dar de alta a quien se dio de baja: pasa, y tiene que
|
||||
dejar la cuenta como estaba."""
|
||||
for employee in self:
|
||||
if employee.beyond_cuenta_estado == 'baja':
|
||||
raise UserError(_('%s ya está dado de baja.', employee.name))
|
||||
employee.write({'beyond_cuenta_estado': 'baja'})
|
||||
# La cuenta se desactiva; el historial de checadas se conserva
|
||||
# (las FKs son restrict: un empleado con historial no se borra).
|
||||
employee.beyond_portal_user_id.sudo().write({'active': False})
|
||||
self.env['beyond.bitacora'].registrar(
|
||||
'empleado_baja', self._name, employee.id,
|
||||
employee.action_unarchive()
|
||||
employee.beyond_portal_user_id.sudo().write({'active': True})
|
||||
self.env['beyond.bitacora']._registrar(
|
||||
'empleado_reincorporado', self._name, employee.id,
|
||||
despues={'nombre': employee.name},
|
||||
branch=employee.branch_id)
|
||||
return True
|
||||
@@ -447,11 +566,619 @@ class HrEmployee(models.Model):
|
||||
'domain': [('employee_id', '=', self.id)],
|
||||
}
|
||||
|
||||
# ══ Lo que la pantalla de Equipo pide al servidor (ADR-018) ══════════
|
||||
# Métodos PÚBLICOS: entran por RPC, así que ninguno usa `sudo()` para
|
||||
# elegir a quién mira. La gente sale de un `search` normal y la ir.rule
|
||||
# de sucursal es la que recorta; lo que no puede leer este usuario no
|
||||
# llega al navegador, que es distinto de no pintarlo (ADR-019).
|
||||
|
||||
@api.model
|
||||
def _beyond_rango(self, periodo, desde=False, hasta=False):
|
||||
"""(desde, hasta, título) del periodo elegido, en fechas locales.
|
||||
|
||||
La semana empieza en LUNES: es como se habla de la semana laboral
|
||||
aquí, y `weekday()` ya cuenta así. El título viaja con el rango
|
||||
porque la columna de la tabla se llama según el periodo —«Horas de
|
||||
la semana», no «Horas semanales» siempre— y decidirlo en el
|
||||
navegador sería tener la regla en dos sitios.
|
||||
"""
|
||||
hoy = fields.Date.context_today(self)
|
||||
if periodo == 'rango' and desde and hasta:
|
||||
return fields.Date.to_date(desde), fields.Date.to_date(hasta), _('Horas del periodo')
|
||||
if periodo == 'hoy':
|
||||
return hoy, hoy, _('Horas de hoy')
|
||||
if periodo == 'mes':
|
||||
return hoy.replace(day=1), hoy, _('Horas del mes')
|
||||
if periodo == 'ano':
|
||||
return hoy.replace(month=1, day=1), hoy, _('Horas del año')
|
||||
return hoy - timedelta(days=hoy.weekday()), hoy, _('Horas de la semana')
|
||||
|
||||
@api.model
|
||||
def _beyond_horas_por_persona(self, empleados, desde, hasta):
|
||||
"""{empleado: horas} en el rango, de una sola consulta agrupada.
|
||||
|
||||
Cuenta lo mismo que `beyond_total_horas` —jornadas cerradas más
|
||||
ajustes— pero acotado al periodo. Que las dos cifras salgan de la
|
||||
misma definición es lo que impide que la ficha y la lista discrepen.
|
||||
"""
|
||||
if not empleados:
|
||||
return {}
|
||||
inicio = datetime.combine(desde, time.min)
|
||||
fin = datetime.combine(hasta, time.max)
|
||||
horas = dict.fromkeys(empleados.ids, 0.0)
|
||||
jornadas = self.env['hr.attendance'].sudo().search([
|
||||
('employee_id', 'in', empleados.ids),
|
||||
('beyond_estado', '=', 'cerrada'),
|
||||
('check_in', '>=', inicio), ('check_in', '<=', fin),
|
||||
])
|
||||
for jornada in jornadas:
|
||||
horas[jornada.employee_id.id] += jornada.beyond_horas
|
||||
ajustes = self.env['beyond.ajuste'].sudo().search([
|
||||
('employee_id', 'in', empleados.ids),
|
||||
('ts', '>=', inicio), ('ts', '<=', fin),
|
||||
])
|
||||
for ajuste in ajustes:
|
||||
horas[ajuste.employee_id.id] += ajuste.minutos / 60.0
|
||||
return horas
|
||||
|
||||
def _beyond_horas_en_curso(self):
|
||||
"""Lo que lleva la jornada abierta hasta AHORA, si hay una.
|
||||
|
||||
Va aparte de las horas del periodo a propósito: las del periodo son
|
||||
las que se pagan y solo cuentan jornadas cerradas (ADR-018). Mezclar
|
||||
las dos haría que la cifra de la pantalla dejara de ser la misma que
|
||||
la de la nómina, que es justo lo que se quiso evitar.
|
||||
"""
|
||||
self.ensure_one()
|
||||
abierta = self.env['hr.attendance'].sudo().search(
|
||||
[('employee_id', '=', self.id), ('check_out', '=', False)],
|
||||
order='check_in desc', limit=1)
|
||||
if not abierta:
|
||||
return 0.0
|
||||
return (fields.Datetime.now() - abierta.check_in).total_seconds() / 3600.0
|
||||
|
||||
beyond_foto_propia = fields.Boolean(
|
||||
string='Foto subida por alguien', default=False, copy=False, readonly=True)
|
||||
|
||||
def _beyond_tiene_foto(self):
|
||||
"""¿La foto la subió alguien, o la horneó Odoo?
|
||||
|
||||
Detectarlo por el contenido NO funciona, y se comprobó: Odoo copia al
|
||||
crear la cuenta la imagen del usuario plantilla, que es un monograma
|
||||
de SU paleta —dorado, verde oscuro— y viaja como PNG de verdad. Mirar
|
||||
los bytes solo cazaba la variante SVG; las demás seguían pintándose
|
||||
como si fueran retratos.
|
||||
|
||||
Así que no se adivina: se APUNTA. El widget de la ficha escribe la
|
||||
imagen, `write` marca la bandera, y la lista dibuja iniciales para
|
||||
todo lo demás. Lo que ya existía se queda con sus iniciales, que es
|
||||
exactamente lo que se pidió: la lista no usa esa imagen.
|
||||
"""
|
||||
self.ensure_one()
|
||||
return bool(self.image_1920) and self.beyond_foto_propia
|
||||
|
||||
def _beyond_estado_del_dia(self):
|
||||
"""trabajando · salió (con su hora) · sin entrada."""
|
||||
self.ensure_one()
|
||||
hoy = self.env['hr.attendance'].sudo().search(
|
||||
[('employee_id', '=', self.id),
|
||||
('check_in', '>=', self._beyond_inicio_de_hoy())],
|
||||
order='check_in desc')
|
||||
if not hoy:
|
||||
return 'sin_entrada', False
|
||||
abierta = hoy.filtered(lambda j: not j.check_out)[:1]
|
||||
if abierta:
|
||||
return 'trabajando', False
|
||||
return 'salio', fields.Datetime.to_string(hoy[0].check_out)
|
||||
|
||||
|
||||
@api.model
|
||||
def _beyond_demo_personal(self):
|
||||
"""Personal de demostración: un caso de cada cosa que la pantalla
|
||||
sabe pintar.
|
||||
|
||||
Va en una función y no en <record> porque casi todo son HORAS
|
||||
relativas a ahora —quién está trabajando, quién ya salió— y una fecha
|
||||
fija en un XML deja de significar nada al día siguiente. Se ejecuta
|
||||
al instalar, que es cuando se cargan los datos demo, y comprueba
|
||||
antes de escribir para no duplicar si se repite.
|
||||
|
||||
Sin los ocho casos la pantalla se demuestra a medias: una lista donde
|
||||
nadie está trabajando y nadie se pasa de la meta no enseña ni el
|
||||
verde, ni el ámbar, ni el «+N h».
|
||||
"""
|
||||
centro = self.env.ref('beyond_branch.demo_branch_centro',
|
||||
raise_if_not_found=False)
|
||||
angelopolis = self.env.ref('beyond_branch.demo_branch_angelopolis',
|
||||
raise_if_not_found=False)
|
||||
if not (centro and angelopolis):
|
||||
return 0
|
||||
|
||||
Attendance = self.env['hr.attendance'].with_context(beyond_sistema=True)
|
||||
ahora = fields.Datetime.now()
|
||||
hoy = ahora.date()
|
||||
|
||||
def persona(nombre, branch, puesto, celular=None, acceso='checador'):
|
||||
existente = self.search([('name', '=', nombre)], limit=1)
|
||||
if existente:
|
||||
return existente
|
||||
valores = {'name': nombre, 'branch_id': branch.id,
|
||||
'department_id': branch.department_id.id,
|
||||
'job_title': puesto, 'beyond_acceso': acceso,
|
||||
'beyond_fecha_ingreso': hoy - timedelta(days=520)}
|
||||
if celular:
|
||||
valores.update(beyond_celular=celular,
|
||||
beyond_clave_inicial='beyond-demo-2026')
|
||||
return self.create(valores)
|
||||
|
||||
def jornada(empleado, dia, hora, horas=None, autocerrada=False):
|
||||
entrada = datetime.combine(dia, time(hour=hora))
|
||||
valores = {'employee_id': empleado.id, 'check_in': entrada}
|
||||
if horas is not None:
|
||||
valores.update(check_out=entrada + timedelta(hours=horas),
|
||||
beyond_estado='cerrada',
|
||||
beyond_autocerrada=autocerrada)
|
||||
# Se comprueba el TRASLAPE, no la igualdad de la entrada: Odoo
|
||||
# rechaza jornadas encimadas de la misma persona, y una demo que
|
||||
# se sembrara dos veces con horarios distintos tumbaría la carga
|
||||
# entera de datos demo en vez de no hacer nada.
|
||||
salida = valores.get('check_out') or entrada + timedelta(hours=12)
|
||||
if Attendance.sudo().search_count([
|
||||
('employee_id', '=', empleado.id),
|
||||
('check_in', '<', salida),
|
||||
'|', ('check_out', '=', False), ('check_out', '>', entrada)]):
|
||||
return
|
||||
Attendance.sudo().create(valores)
|
||||
|
||||
# Trabajando ahora: entró hace tres horas y no ha salido.
|
||||
trabajando = persona('Daniela Ríos', centro, 'Estilista', '2221000001')
|
||||
Attendance.sudo().search([('employee_id', '=', trabajando.id),
|
||||
('check_out', '=', False)]).unlink()
|
||||
Attendance.sudo().create({
|
||||
'employee_id': trabajando.id,
|
||||
'check_in': ahora - timedelta(hours=3)})
|
||||
|
||||
# Ya salió, y además salió a comer: dos renglones el mismo día.
|
||||
comio = persona('Luis Mendoza', centro, 'Barbero', '2221000002')
|
||||
jornada(comio, hoy, 9, horas=3.0)
|
||||
jornada(comio, hoy, 14, horas=4.0)
|
||||
|
||||
# Sin entrada hoy, pero con horas en el periodo: es el caso que
|
||||
# enseña el ámbar SIN que la barra salga vacía.
|
||||
sin_entrada = persona('Carmen Peña', angelopolis, 'Manicurista', '2221000003')
|
||||
for atras in (1, 2):
|
||||
jornada(sin_entrada, hoy - timedelta(days=atras), 10, horas=6.0)
|
||||
|
||||
# Cierre automático: se le olvidó marcar salida anteayer.
|
||||
olvidadiza = persona('Rocío Salas', angelopolis, 'Estilista', '2221000004')
|
||||
jornada(olvidadiza, hoy - timedelta(days=2), 9, horas=11.0, autocerrada=True)
|
||||
|
||||
# Se pasa de la meta. Los días se cuentan desde el LUNES de esta
|
||||
# semana y no «hacia atrás», para que caigan dentro del periodo que
|
||||
# la pantalla enseña por defecto; y lleva además semanas anteriores
|
||||
# para que en «Mes» el «+N h» se vea siempre, sea martes o viernes.
|
||||
maratonista = persona('Jorge Vidal', centro, 'Estilista', '2221000005')
|
||||
lunes = hoy - timedelta(days=hoy.weekday())
|
||||
dia = lunes
|
||||
while dia <= hoy:
|
||||
jornada(maratonista, dia, 8, horas=7.0)
|
||||
jornada(maratonista, dia, 16, horas=5.0)
|
||||
dia += timedelta(days=1)
|
||||
for atras in (7, 8, 9, 10, 11):
|
||||
jornada(maratonista, lunes - timedelta(days=atras), 9, horas=9.0)
|
||||
|
||||
# Admin de sucursal, para que la pastilla de rol tenga qué enseñar.
|
||||
persona('Marisol Cano', angelopolis, 'Gerente', '2221000006',
|
||||
acceso='admin_sucursal')
|
||||
|
||||
# Y alguien sin cuenta y sin foto, que también existe en un salón.
|
||||
persona('Aprendiz Nuevo', centro, 'Aprendiz')
|
||||
|
||||
# Ventas del periodo para quien tiene horas: sin ellas la
|
||||
# productividad y el «$/h» salen en cero en las cuatro tarjetas y no
|
||||
# hay nada que evaluar. Se siembran DESPUÉS de las jornadas, porque
|
||||
# las ventas por hora necesitan las dos cosas.
|
||||
self._beyond_demo_ventas({trabajando: 1450.0, comio: 980.0,
|
||||
sin_entrada: 1720.0, olvidadiza: 640.0,
|
||||
maratonista: 2310.0})
|
||||
self._beyond_demo_retirar_personal_ajeno()
|
||||
return 1
|
||||
|
||||
@api.model
|
||||
def _beyond_demo_ventas(self, por_persona):
|
||||
"""Ventas atribuidas de esta semana, para que productividad tenga qué
|
||||
enseñar (ADR-007: el reparto es en partes iguales por línea)."""
|
||||
Orden = self.env['pos.order'].sudo()
|
||||
Linea = self.env['pos.order.line'].sudo()
|
||||
servicio = self.env['product.product'].sudo().search(
|
||||
[('type', '=', 'service'), ('available_in_pos', '=', True)], limit=1)
|
||||
if not servicio:
|
||||
return
|
||||
# `beyond_empleado_ids` lo declara beyond_pos_theme, que desde el
|
||||
# 27-ago-2026 DEPENDE de este módulo: el orden de carga ya no es una
|
||||
# casualidad, es la única posible, así que en una base recién creada
|
||||
# el campo nunca existe cuando esta función corre. El create reventaba
|
||||
# con «Invalid field» y la excepción tumbaba los datos demo de este
|
||||
# módulo entero — y por arrastre los de todos los que dependen de él,
|
||||
# porque Odoo no carga la demo de un módulo cuyo padre no la tiene.
|
||||
# Sin el campo se siembra la venta sin atribuir: se degrada, no se
|
||||
# cae (ADR-011).
|
||||
atribuye = 'beyond_empleado_ids' in Linea._fields
|
||||
for empleado, monto in por_persona.items():
|
||||
branch = empleado.branch_id
|
||||
if not branch.pos_config_id:
|
||||
continue
|
||||
caja = self.env['pos.session'].sudo().search(
|
||||
[('config_id', '=', branch.pos_config_id.id)], limit=1)
|
||||
if not caja:
|
||||
# Una venta necesita su caja. Se abre aquí y se deja abierta,
|
||||
# que es el estado normal de un salón en horario y el que la
|
||||
# demostración quiere enseñar; cerrarla pediría los cuadres
|
||||
# contables, que no son de esta demo.
|
||||
caja = self.env['pos.session'].sudo().create({
|
||||
'config_id': branch.pos_config_id.id,
|
||||
'user_id': self.env.user.id,
|
||||
})
|
||||
if Orden.search_count([('name', '=', f'Demo Personal {empleado.id}')]):
|
||||
continue
|
||||
orden = Orden.create({
|
||||
'name': f'Demo Personal {empleado.id}',
|
||||
'session_id': caja.id,
|
||||
'company_id': caja.company_id.id,
|
||||
'amount_tax': 0.0, 'amount_total': monto,
|
||||
'amount_paid': monto, 'amount_return': 0.0,
|
||||
})
|
||||
orden.write({'state': 'paid'})
|
||||
valores = {
|
||||
'order_id': orden.id, 'product_id': servicio.id, 'qty': 1,
|
||||
'price_unit': monto, 'price_subtotal': monto,
|
||||
'price_subtotal_incl': monto,
|
||||
}
|
||||
if atribuye:
|
||||
valores['beyond_empleado_ids'] = [(6, 0, empleado.ids)]
|
||||
Linea.create(valores)
|
||||
|
||||
@api.model
|
||||
def _beyond_demo_retirar_personal_ajeno(self):
|
||||
"""Archiva el personal de muestra de Odoo, solo en demo.
|
||||
|
||||
«Abigail Peterson» o «Barty McBly» no trabajan en un salón de Puebla,
|
||||
y como la tabla ordena por nombre eran los primeros renglones de
|
||||
Equipo. Es el mismo problema que el catálogo de muestra en Productos,
|
||||
y se resuelve igual: no se borra nada, se archiva, y solo pasa aquí
|
||||
—esta función vive en los datos demo, que producción no carga—.
|
||||
|
||||
Se archivan y no se retiran de otra forma porque `active` es
|
||||
justamente lo que la pantalla mira: quien está archivado no sale en
|
||||
Equipo, igual que alguien dado de baja.
|
||||
"""
|
||||
ajenos = self.env['ir.model.data'].search([
|
||||
('model', '=', 'hr.employee'),
|
||||
('module', 'not like', 'beyond%'),
|
||||
])
|
||||
personal = self.browse(ajenos.mapped('res_id')).exists()
|
||||
# La cuenta técnica se queda: es la de administración del sistema.
|
||||
tecnica = self.env.ref('base.user_admin', raise_if_not_found=False)
|
||||
if tecnica:
|
||||
personal = personal.filtered(lambda e: e.user_id != tecnica)
|
||||
personal.filtered('active').action_archive()
|
||||
|
||||
@api.model
|
||||
def beyond_equipo_datos(self, periodo='semana', desde=False, hasta=False,
|
||||
branch_ids=False, filtro='todos', busqueda=''):
|
||||
"""La tabla de Equipo: quién, cómo va hoy y cuántas horas lleva."""
|
||||
desde, hasta, titulo = self._beyond_rango(periodo, desde, hasta)
|
||||
meta = self.env['beyond.checador.config']._beyond_horas_semana()
|
||||
general = self.env.user.has_group('beyond_base.beyond_group_admin_general')
|
||||
|
||||
dominio = []
|
||||
if branch_ids:
|
||||
dominio.append(('branch_id', 'in', branch_ids))
|
||||
if busqueda:
|
||||
dominio += ['|', ('name', 'ilike', busqueda),
|
||||
('beyond_celular', 'ilike', busqueda)]
|
||||
empleados = self.search(dominio, order='name')
|
||||
|
||||
horas = self._beyond_horas_por_persona(empleados, desde, hasta)
|
||||
# Los tres estados posibles, para que los contadores SUMEN: antes
|
||||
# eran «todos», «trabajando» y «sin entrada», y quien ya había
|
||||
# entrado y salido no estaba en ninguno. Un contador que no cuadra
|
||||
# obliga a desconfiar de los tres.
|
||||
personas = []
|
||||
cuenta = {'todos': 0, 'trabajando': 0, 'salio': 0, 'sin_entrada': 0}
|
||||
for empleado in empleados:
|
||||
estado, hora_salida = empleado._beyond_estado_del_dia()
|
||||
cuenta['todos'] += 1
|
||||
if estado in cuenta:
|
||||
cuenta[estado] += 1
|
||||
suyas = horas.get(empleado.id, 0.0)
|
||||
# La jornada abierta NO suma en las horas —esas son las que se
|
||||
# pagan, y todavía no ha terminado— pero se dice aparte: quien
|
||||
# está trabajando ahora con «0 h» parece un error, y no lo es.
|
||||
en_curso = empleado._beyond_horas_en_curso()
|
||||
personas.append({
|
||||
'id': empleado.id,
|
||||
'nombre': empleado.name,
|
||||
'celular': empleado.beyond_celular or '',
|
||||
'acceso': empleado.beyond_acceso,
|
||||
# La pastilla de rol solo se dibuja si NO es colaborador: en
|
||||
# una lista donde casi todos lo son, decirlo en cada renglón
|
||||
# es ruido.
|
||||
'acceso_etiqueta': (empleado._beyond_etiqueta_acceso()
|
||||
if empleado.beyond_acceso != 'checador' else ''),
|
||||
'sucursal': empleado.branch_id.name or '',
|
||||
'tiene_foto': empleado._beyond_tiene_foto(),
|
||||
'estado': estado,
|
||||
'hora_salida': hora_salida,
|
||||
'horas': round(suyas, 2),
|
||||
'en_curso': round(en_curso, 2),
|
||||
'meta': meta,
|
||||
# Pasarse de la meta se DICE, no se dibuja llenando más la
|
||||
# barra: una barra llena y otra llenísima se ven igual.
|
||||
'sobre_meta': suyas > meta,
|
||||
})
|
||||
if filtro in ('trabajando', 'salio', 'sin_entrada'):
|
||||
personas = [p for p in personas if p['estado'] == filtro]
|
||||
|
||||
# Los chips de sucursal son de la dirección; a un gerente le sale
|
||||
# solo la suya, y aun así se recorta por la regla y no por el rol.
|
||||
sucursales = self.env['beyond.branch'].search([])
|
||||
return {
|
||||
'periodo': {
|
||||
'clave': periodo,
|
||||
'titulo': titulo,
|
||||
'desde': fields.Date.to_string(desde),
|
||||
'hasta': fields.Date.to_string(hasta),
|
||||
},
|
||||
'meta': meta,
|
||||
'es_admin_general': general,
|
||||
'puede_crear': self.has_access('create'),
|
||||
'sucursales': [{'id': b.id, 'nombre': b.name} for b in sucursales],
|
||||
'filtros': cuenta,
|
||||
'personas': personas,
|
||||
'total': len(personas),
|
||||
}
|
||||
|
||||
@api.model
|
||||
def beyond_resumen_equipo(self, periodo='semana', desde=False, hasta=False):
|
||||
"""«Horas y productividad»: por plaza, y la red entera solo para la
|
||||
dirección. Las ventas salen del MISMO reporte que ve el gerente
|
||||
(beyond.productividad, ADR-007): dos fuentes darían dos números."""
|
||||
desde, hasta, _titulo = self._beyond_rango(periodo, desde, hasta)
|
||||
meta = self.env['beyond.checador.config']._beyond_horas_semana()
|
||||
general = self.env.user.has_group('beyond_base.beyond_group_admin_general')
|
||||
|
||||
empleados = self.search([])
|
||||
horas = self._beyond_horas_por_persona(empleados, desde, hasta)
|
||||
ventas = self._beyond_ventas_por_sucursal(desde, hasta)
|
||||
|
||||
filas, totales = [], {'personas': 0, 'horas': 0.0, 'meta': 0, 'ventas': 0.0}
|
||||
sucursales = self.env['beyond.branch'].search([])
|
||||
# Quien no tiene sucursal contaba en la lista y no en el resumen, y
|
||||
# los dos números no cuadraban sin explicación. Se le da su propia
|
||||
# fila: el hueco de datos se ve en vez de esconderse en una resta.
|
||||
grupos = [(branch, empleados.filtered(lambda e, b=branch: e.branch_id == b))
|
||||
for branch in sucursales]
|
||||
# Sin tarjeta de «sin sucursal»: en producción todo el mundo tiene
|
||||
# una, y la guardia del alta lo sostiene. En una base de desarrollo
|
||||
# puede quedar alguien suelto y entonces el total de la red no
|
||||
# cuadrará con la lista; es un dato roto, no una categoría, y no se
|
||||
# le hace sitio en la pantalla (decisión del cliente, 26-ago-2026).
|
||||
for branch, suyos in grupos:
|
||||
suma = sum(horas.get(e.id, 0.0) for e in suyos)
|
||||
vendido = ventas.get(branch.id, 0.0)
|
||||
filas.append({
|
||||
'branch_id': branch.id,
|
||||
'nombre': branch.name or _('Sin sucursal'),
|
||||
'sin_sucursal': not branch,
|
||||
# Una plaza sin gente no es un cero que llenar: es una plaza
|
||||
# sin gente, y se dice así en vez de ocupar sitio con «0 h de
|
||||
# 0 h · 0 personas».
|
||||
'vacia': not suyos,
|
||||
'personas': len(suyos),
|
||||
'horas': round(suma, 2),
|
||||
'meta': len(suyos) * meta,
|
||||
'ventas': round(vendido, 2),
|
||||
'ventas_por_hora': round(vendido / suma, 2) if suma else 0.0,
|
||||
})
|
||||
totales['personas'] += len(suyos)
|
||||
totales['horas'] += suma
|
||||
totales['meta'] += len(suyos) * meta
|
||||
totales['ventas'] += vendido
|
||||
|
||||
totales['horas'] = round(totales['horas'], 2)
|
||||
totales['ventas'] = round(totales['ventas'], 2)
|
||||
totales['ventas_por_hora'] = (round(totales['ventas'] / totales['horas'], 2)
|
||||
if totales['horas'] else 0.0)
|
||||
return {
|
||||
'sucursales': filas,
|
||||
# El total de la RED es de quien manda en la red. A un gerente no
|
||||
# se le devuelve, ni siquiera para no pintarlo.
|
||||
'organizacion': totales if general else False,
|
||||
}
|
||||
|
||||
@api.model
|
||||
def _beyond_ventas_por_sucursal(self, desde, hasta):
|
||||
"""{sucursal: monto} del periodo. Sin `sudo()`: la ir.rule del
|
||||
reporte es la que decide qué plazas suman."""
|
||||
if 'beyond.productividad' not in self.env:
|
||||
return {}
|
||||
inicio = datetime.combine(desde, time.min)
|
||||
fin = datetime.combine(hasta, time.max)
|
||||
grupos = self.env['beyond.productividad']._read_group(
|
||||
[('fecha', '>=', inicio), ('fecha', '<=', fin)],
|
||||
['branch_id'], ['monto_atribuido:sum'])
|
||||
return {branch.id: monto for branch, monto in grupos}
|
||||
|
||||
|
||||
@api.model
|
||||
def beyond_ficha_datos(self, employee_id, periodo='semana', desde=False, hasta=False):
|
||||
"""Avance, productividad y jornadas de UNA persona.
|
||||
|
||||
Público por RPC, así que lo primero que hace es comprobar que quien
|
||||
pregunta puede leer a esa persona: pedir la ficha por id es lo
|
||||
primero que alguien intentaría (ADR-019).
|
||||
"""
|
||||
empleado = self.browse(employee_id)
|
||||
empleado.check_access('read')
|
||||
desde, hasta, titulo = self._beyond_rango(periodo, desde, hasta)
|
||||
meta = self.env['beyond.checador.config']._beyond_horas_semana()
|
||||
horas = self._beyond_horas_por_persona(empleado, desde, hasta).get(
|
||||
empleado.id, 0.0)
|
||||
return {
|
||||
'avance': {
|
||||
'titulo': titulo,
|
||||
'horas': round(horas, 2),
|
||||
'meta': meta,
|
||||
'sobre_meta': horas > meta,
|
||||
},
|
||||
'productividad': empleado._beyond_productividad(desde, hasta, horas),
|
||||
'jornadas': empleado._beyond_jornadas_del_periodo(desde, hasta),
|
||||
}
|
||||
|
||||
def _beyond_productividad(self, desde, hasta, horas):
|
||||
"""Las MISMAS cifras que el reporte del gerente (ADR-007): se leen de
|
||||
`beyond.productividad`, sin `sudo()`, para que empleado, ficha y
|
||||
reporte no puedan discrepar."""
|
||||
self.ensure_one()
|
||||
vacio = {'ventas': 0.0, 'ticket': 0.0, 'ventas_por_hora': 0.0,
|
||||
'ranking': 0, 'de': 0, 'delta': 0.0, 'dias': []}
|
||||
if 'beyond.productividad' not in self.env:
|
||||
return vacio
|
||||
inicio = datetime.combine(desde, time.min)
|
||||
fin = datetime.combine(hasta, time.max)
|
||||
Productividad = self.env['beyond.productividad']
|
||||
|
||||
grupos = Productividad._read_group(
|
||||
[('employee_id', '=', self.id), ('fecha', '>=', inicio), ('fecha', '<=', fin)],
|
||||
[], ['monto_atribuido:sum', 'ticket_promedio:avg'])
|
||||
ventas, ticket = grupos[0] if grupos else (0.0, 0.0)
|
||||
ventas, ticket = ventas or 0.0, ticket or 0.0
|
||||
|
||||
# Ranking DENTRO de su sucursal: compararse con toda la red no dice
|
||||
# nada cuando las plazas tienen tamaños distintos.
|
||||
del_equipo = Productividad._read_group(
|
||||
[('branch_id', '=', self.branch_id.id),
|
||||
('fecha', '>=', inicio), ('fecha', '<=', fin)],
|
||||
['employee_id'], ['monto_atribuido:sum'])
|
||||
tabla = sorted(((monto or 0.0, emp.id) for emp, monto in del_equipo), reverse=True)
|
||||
posicion = next((i + 1 for i, (_m, eid) in enumerate(tabla) if eid == self.id), 0)
|
||||
|
||||
# Contra el periodo anterior, del mismo largo.
|
||||
largo = (hasta - desde) + timedelta(days=1)
|
||||
anterior = Productividad._read_group(
|
||||
[('employee_id', '=', self.id),
|
||||
('fecha', '>=', datetime.combine(desde - largo, time.min)),
|
||||
('fecha', '<', inicio)],
|
||||
[], ['monto_atribuido:sum'])
|
||||
antes = (anterior[0][0] or 0.0) if anterior else 0.0
|
||||
|
||||
por_dia = {}
|
||||
for registro in Productividad.search(
|
||||
[('employee_id', '=', self.id),
|
||||
('fecha', '>=', inicio), ('fecha', '<=', fin)]):
|
||||
clave = fields.Date.to_string(registro.fecha.date())
|
||||
por_dia[clave] = por_dia.get(clave, 0.0) + registro.monto_atribuido
|
||||
|
||||
return {
|
||||
'ventas': round(ventas, 2),
|
||||
'ticket': round(ticket, 2),
|
||||
'ventas_por_hora': round(ventas / horas, 2) if horas else 0.0,
|
||||
'ranking': posicion,
|
||||
'de': len(tabla),
|
||||
'delta': round(ventas - antes, 2),
|
||||
'dias': [{'dia': d, 'monto': round(m, 2)}
|
||||
for d, m in sorted(por_dia.items())],
|
||||
}
|
||||
|
||||
def _beyond_jornadas_del_periodo(self, desde, hasta):
|
||||
"""Un renglón por PAR entrada/salida, de lo más reciente a lo más
|
||||
viejo. La etiqueta del día va solo en el primero de cada día: salir a
|
||||
comer parte el día en dos renglones, y repetir la fecha en los dos
|
||||
hace pensar que son dos días distintos.
|
||||
|
||||
El acumulado se calcula de lo VIEJO a lo nuevo —es una suma corrida
|
||||
del periodo— y luego se pinta al revés.
|
||||
"""
|
||||
self.ensure_one()
|
||||
inicio = datetime.combine(desde, time.min)
|
||||
fin = datetime.combine(hasta, time.max)
|
||||
jornadas = self.env['hr.attendance'].sudo().search(
|
||||
[('employee_id', '=', self.id),
|
||||
('check_in', '>=', inicio), ('check_in', '<=', fin)],
|
||||
order='check_in asc')
|
||||
|
||||
corrido, filas = 0.0, []
|
||||
for jornada in jornadas:
|
||||
if jornada.beyond_estado == 'abierta':
|
||||
estado = 'abierta'
|
||||
elif jornada.beyond_autocerrada:
|
||||
estado = 'cierre_automatico'
|
||||
elif jornada.beyond_estado == 'rechazada':
|
||||
estado = 'rechazada'
|
||||
else:
|
||||
estado = 'cerrada'
|
||||
corrido += jornada.beyond_horas
|
||||
filas.append({
|
||||
'id': jornada.id,
|
||||
'dia': fields.Date.to_string(jornada.check_in.date()),
|
||||
'entrada': fields.Datetime.to_string(jornada.check_in),
|
||||
'salida': fields.Datetime.to_string(jornada.check_out) if jornada.check_out else '',
|
||||
'sucursal': jornada.branch_id.name or '',
|
||||
'horas': round(jornada.beyond_horas, 2),
|
||||
'acumulado': round(corrido, 2),
|
||||
'estado': estado,
|
||||
})
|
||||
|
||||
filas.reverse()
|
||||
visto = set()
|
||||
for fila in filas:
|
||||
fila['etiqueta_dia'] = fila['dia'] if fila['dia'] not in visto else ''
|
||||
visto.add(fila['dia'])
|
||||
return filas
|
||||
|
||||
@api.model
|
||||
def beyond_celular_disponible(self, celular):
|
||||
"""¿Ese celular ya es de alguien? Se pregunta al SALIR del campo.
|
||||
|
||||
Antes solo tronaba al guardar, con el formulario lleno. El aviso
|
||||
existe para no chocar, no para informar: si el celular es de alguien
|
||||
que este usuario no puede ver, se dice que está ocupado pero NO de
|
||||
quién. Un gerente no tiene por qué enterarse de quién trabaja en otra
|
||||
sucursal por un campo de alta.
|
||||
"""
|
||||
numero = self._beyond_normalizar_celular(celular or '')
|
||||
if not numero:
|
||||
return {'disponible': True, 'mensaje': ''}
|
||||
# La búsqueda es con sudo a propósito: para no chocar hay que mirar
|
||||
# TODA la red, porque el login es único en la base. Lo que se recorta
|
||||
# es lo que se cuenta, no lo que se busca.
|
||||
duenos = self.sudo().with_context(active_test=False).search(
|
||||
[('beyond_celular', '=', numero)], limit=1)
|
||||
if not duenos:
|
||||
return {'disponible': True, 'mensaje': ''}
|
||||
visible = self.search([('id', '=', duenos.id)], limit=1)
|
||||
if visible:
|
||||
return {'disponible': False,
|
||||
'mensaje': _('Ese celular ya es de %s.', duenos.name)}
|
||||
return {'disponible': False,
|
||||
'mensaje': _('Ese celular ya está en uso en otra sucursal.')}
|
||||
|
||||
def beyond_total_horas(self):
|
||||
"""ÚNICA fuente del total de horas (regla §10.6 de Taboada: el
|
||||
backend calcula todo; el frontend jamás). Total = jornadas cerradas
|
||||
+ ajustes; `abierta` y `revision` no suman."""
|
||||
+ ajustes. `abierta` no suma —todavía no ha terminado— y `rechazada`
|
||||
tampoco: alguien decidió no reconocerla y esas horas no se pagaron.
|
||||
La cerrada por el cron SÍ suma, que es la decisión de ADR-018.
|
||||
|
||||
Método PÚBLICO —llamable por RPC— que suma con `sudo()`, así que
|
||||
lleva su comprobación de lectura (barrido del 26-ago-2026, ADR-019).
|
||||
Sin ella bastaba con `browse(id_de_cualquiera).beyond_total_horas()`
|
||||
para saber cuánto trabajó otra persona: el sudo de dentro no mira a
|
||||
quién pertenece el registro de fuera.
|
||||
"""
|
||||
self.ensure_one()
|
||||
self.check_access('read')
|
||||
jornadas = self.env['hr.attendance'].sudo().search([
|
||||
('employee_id', '=', self.id),
|
||||
('beyond_estado', '=', 'cerrada'),
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
/** Part of Beyond. Collina Systems proprietary module. */
|
||||
import { Component, useState } from "@odoo/owl";
|
||||
import { registry } from "@web/core/registry";
|
||||
import { standardFieldProps } from "@web/views/fields/standard_field_props";
|
||||
import { useService } from "@web/core/utils/hooks";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
|
||||
/**
|
||||
* El celular, que además es el usuario de acceso (ADR-006).
|
||||
*
|
||||
* Al SALIR del campo se pregunta al servidor si ya es de alguien. Antes esto
|
||||
* solo tronaba al guardar, con el formulario entero lleno y sin decir de
|
||||
* quién era: el aviso llega ahora, junto al campo, y mientras el número esté
|
||||
* repetido el registro queda marcado como inválido, que es como Odoo impide
|
||||
* guardar.
|
||||
*
|
||||
* Quién sale nombrado en el aviso lo decide el servidor: si el número es de
|
||||
* otra sucursal, dice que está ocupado pero no de quién (ADR-019).
|
||||
*/
|
||||
export class BeyondCelularAviso extends Component {
|
||||
static template = "beyond_attendance_qr.CelularAviso";
|
||||
static props = { ...standardFieldProps };
|
||||
|
||||
setup() {
|
||||
this.orm = useService("orm");
|
||||
this.state = useState({ mensaje: "" });
|
||||
}
|
||||
|
||||
get valor() {
|
||||
return this.props.record.data[this.props.name] || "";
|
||||
}
|
||||
|
||||
onInput(ev) {
|
||||
this.props.record.update({ [this.props.name]: ev.target.value });
|
||||
// Mientras teclea no se le grita: el aviso es al salir del campo.
|
||||
this.state.mensaje = "";
|
||||
}
|
||||
|
||||
async onSalir(ev) {
|
||||
const celular = (ev.target.value || "").trim();
|
||||
if (!celular) {
|
||||
this.state.mensaje = "";
|
||||
return;
|
||||
}
|
||||
const respuesta = await this.orm.call(
|
||||
"hr.employee", "beyond_celular_disponible", [celular]);
|
||||
if (respuesta.disponible) {
|
||||
this.state.mensaje = "";
|
||||
return;
|
||||
}
|
||||
this.state.mensaje = respuesta.mensaje || _t("Ese celular ya está en uso.");
|
||||
this.props.record.setInvalidField(this.props.name);
|
||||
}
|
||||
}
|
||||
|
||||
registry.category("fields").add("beyond_celular_aviso", {
|
||||
component: BeyondCelularAviso,
|
||||
displayName: _t("Celular (usuario de acceso)"),
|
||||
supportedTypes: ["char"],
|
||||
});
|
||||
@@ -0,0 +1,182 @@
|
||||
/** @odoo-module **/
|
||||
|
||||
import { Component, onWillStart, useState } from "@odoo/owl";
|
||||
import { Layout } from "@web/search/layout";
|
||||
import { registry } from "@web/core/registry";
|
||||
import { useService } from "@web/core/utils/hooks";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
|
||||
const ESPERA_BUSQUEDA = 250;
|
||||
|
||||
const PERIODOS = [
|
||||
{ clave: "hoy", etiqueta: _t("Hoy") },
|
||||
{ clave: "semana", etiqueta: _t("Semana") },
|
||||
{ clave: "mes", etiqueta: _t("Mes") },
|
||||
{ clave: "ano", etiqueta: _t("Año") },
|
||||
];
|
||||
|
||||
// Los cuatro, para que los contadores SUMEN: con «todos», «trabajando» y
|
||||
// «sin entrada», quien ya entró y salió no estaba en ninguno y los números
|
||||
// no cuadraban. Un contador que no cuadra obliga a desconfiar de los tres.
|
||||
const FILTROS = [
|
||||
{ clave: "todos", etiqueta: _t("Todos") },
|
||||
{ clave: "trabajando", etiqueta: _t("Trabajando ahora") },
|
||||
{ clave: "salio", etiqueta: _t("Ya salió") },
|
||||
{ clave: "sin_entrada", etiqueta: _t("Sin entrada hoy") },
|
||||
];
|
||||
|
||||
/**
|
||||
* Equipo: quién es, cómo va hoy y cuántas horas lleva en el periodo.
|
||||
*
|
||||
* La lista del diseño trae dos columnas que no son campos —el estado del día
|
||||
* y el avance contra la meta— y un resumen por sucursal, así que por el
|
||||
* criterio de ADR-013 es pantalla propia y no una lista revestida.
|
||||
*
|
||||
* Todo lo que se pinta viene del servidor ya recortado por la ir.rule: a un
|
||||
* gerente no le VIAJA la gente de otra plaza, ni sus horas, ni sus ventas
|
||||
* (ADR-019). Aquí no se filtra nada por rol; solo se dibuja.
|
||||
*/
|
||||
export class BeyondEquipo extends Component {
|
||||
static template = "beyond_attendance_qr.Equipo";
|
||||
static components = { Layout };
|
||||
static props = ["*"];
|
||||
|
||||
setup() {
|
||||
this.orm = useService("orm");
|
||||
this.action = useService("action");
|
||||
this.periodos = PERIODOS;
|
||||
this.filtros = FILTROS;
|
||||
this.state = useState({
|
||||
periodo: "semana",
|
||||
desde: "",
|
||||
hasta: "",
|
||||
branchIds: [],
|
||||
filtro: "todos",
|
||||
busqueda: "",
|
||||
datos: null,
|
||||
resumen: null,
|
||||
cargando: true,
|
||||
});
|
||||
onWillStart(() => this.cargar());
|
||||
}
|
||||
|
||||
async cargar() {
|
||||
this.state.cargando = true;
|
||||
const periodo = this.state.desde && this.state.hasta ? "rango" : this.state.periodo;
|
||||
try {
|
||||
const [datos, resumen] = await Promise.all([
|
||||
this.orm.call("hr.employee", "beyond_equipo_datos", [
|
||||
periodo, this.state.desde || false, this.state.hasta || false,
|
||||
this.state.branchIds.length ? this.state.branchIds : false,
|
||||
this.state.filtro, this.state.busqueda]),
|
||||
this.orm.call("hr.employee", "beyond_resumen_equipo", [
|
||||
periodo, this.state.desde || false, this.state.hasta || false]),
|
||||
]);
|
||||
this.state.datos = datos;
|
||||
this.state.resumen = resumen;
|
||||
} finally {
|
||||
this.state.cargando = false;
|
||||
}
|
||||
}
|
||||
|
||||
get meta() {
|
||||
return this.state.datos ? this.state.datos.meta : 0;
|
||||
}
|
||||
|
||||
async verPeriodo(clave) {
|
||||
this.state.periodo = clave;
|
||||
this.state.desde = "";
|
||||
this.state.hasta = "";
|
||||
await this.cargar();
|
||||
}
|
||||
|
||||
async onRango(campo, ev) {
|
||||
this.state[campo] = ev.target.value;
|
||||
if (this.state.desde && this.state.hasta) {
|
||||
await this.cargar();
|
||||
}
|
||||
}
|
||||
|
||||
async verFiltro(clave) {
|
||||
this.state.filtro = clave;
|
||||
await this.cargar();
|
||||
}
|
||||
|
||||
async alternarSucursal(id) {
|
||||
const dentro = this.state.branchIds.includes(id);
|
||||
this.state.branchIds = dentro
|
||||
? this.state.branchIds.filter((x) => x !== id)
|
||||
: [...this.state.branchIds, id];
|
||||
await this.cargar();
|
||||
}
|
||||
|
||||
onBuscar(ev) {
|
||||
clearTimeout(this._buscando);
|
||||
this.state.busqueda = ev.target.value;
|
||||
this._buscando = setTimeout(() => this.cargar(), ESPERA_BUSQUEDA);
|
||||
}
|
||||
|
||||
cuenta(clave) {
|
||||
return this.state.datos ? this.state.datos.filtros[clave] : 0;
|
||||
}
|
||||
|
||||
iniciales(nombre) {
|
||||
return (nombre || "")
|
||||
.split(/\s+/).filter(Boolean).slice(0, 2)
|
||||
.map((parte) => parte[0].toUpperCase()).join("");
|
||||
}
|
||||
|
||||
fotoDe(persona) {
|
||||
return `/web/image/hr.employee/${persona.id}/image_128`;
|
||||
}
|
||||
|
||||
/** Ancho de la barra. Pasarse NO la llena más: se dice con «+N h». */
|
||||
avance(persona) {
|
||||
if (!persona.meta) {
|
||||
return 0;
|
||||
}
|
||||
return Math.min(100, Math.round((persona.horas / persona.meta) * 100));
|
||||
}
|
||||
|
||||
sobrante(persona) {
|
||||
return Math.round((persona.horas - persona.meta) * 10) / 10;
|
||||
}
|
||||
|
||||
horas(valor) {
|
||||
return `${Math.round(valor * 10) / 10} h`;
|
||||
}
|
||||
|
||||
dinero(valor) {
|
||||
return `$${(valor || 0).toLocaleString("es-MX", {
|
||||
minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
|
||||
}
|
||||
|
||||
hora(iso) {
|
||||
if (!iso) {
|
||||
return "";
|
||||
}
|
||||
// El servidor manda UTC; se pinta en la hora de quien mira.
|
||||
const fecha = new Date(iso.replace(" ", "T") + "Z");
|
||||
return fecha.toLocaleTimeString("es-MX", { hour: "2-digit", minute: "2-digit" });
|
||||
}
|
||||
|
||||
async abrirFicha(persona) {
|
||||
await this.action.doAction("beyond_attendance_qr.action_equipo", {
|
||||
props: { resId: persona.id },
|
||||
viewType: "form",
|
||||
});
|
||||
}
|
||||
|
||||
async nuevo() {
|
||||
await this.action.doAction("beyond_attendance_qr.action_equipo", {
|
||||
viewType: "form",
|
||||
});
|
||||
}
|
||||
|
||||
/** Puerta discreta: la configuración es de la dirección. */
|
||||
async configuracion() {
|
||||
await this.action.doAction("beyond_attendance_qr.action_checador_config");
|
||||
}
|
||||
}
|
||||
|
||||
registry.category("actions").add("beyond_equipo", BeyondEquipo);
|
||||
@@ -0,0 +1,196 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
<t t-name="beyond_attendance_qr.Equipo">
|
||||
<Layout className="'o_beyond_equipo'" display="{ controlPanel: {} }">
|
||||
<t t-set-slot="layout-buttons">
|
||||
<button t-if="state.datos and state.datos.puede_crear" type="button"
|
||||
class="btn beyond_equipo_nuevo" t-on-click="nuevo">
|
||||
Nuevo
|
||||
</button>
|
||||
</t>
|
||||
<div class="beyond_equipo_eje">
|
||||
<!-- ── Resumen: horas y productividad ── -->
|
||||
<t t-if="state.resumen">
|
||||
<div class="beyond_equipo_resumen">
|
||||
<t t-if="state.resumen.organizacion">
|
||||
<div class="beyond_resumen_tarjeta beyond_resumen_red">
|
||||
<span class="beyond_resumen_titulo">Toda la red</span>
|
||||
<span class="beyond_resumen_cifra">
|
||||
<t t-esc="horas(state.resumen.organizacion.horas)"/>
|
||||
<small> de <t t-esc="state.resumen.organizacion.meta"/> h</small>
|
||||
</span>
|
||||
<span class="beyond_resumen_pie">
|
||||
<t t-esc="state.resumen.organizacion.personas"/> personas ·
|
||||
<t t-esc="dinero(state.resumen.organizacion.ventas)"/> ·
|
||||
<t t-esc="dinero(state.resumen.organizacion.ventas_por_hora)"/>/h
|
||||
</span>
|
||||
</div>
|
||||
</t>
|
||||
<t t-foreach="state.resumen.sucursales" t-as="fila" t-key="fila.branch_id">
|
||||
<div class="beyond_resumen_tarjeta"
|
||||
t-att-class="{'beyond_resumen_vacia': fila.vacia}">
|
||||
<span class="beyond_resumen_titulo" t-esc="fila.nombre"/>
|
||||
<t t-if="fila.vacia">
|
||||
<!-- Una plaza sin gente no es un cero que
|
||||
llenar: se dice y se apaga. -->
|
||||
<span class="beyond_resumen_pie">Sin personal asignado</span>
|
||||
</t>
|
||||
<t t-else="">
|
||||
<span class="beyond_resumen_cifra">
|
||||
<t t-esc="horas(fila.horas)"/>
|
||||
<small> de <t t-esc="fila.meta"/> h</small>
|
||||
</span>
|
||||
<span class="beyond_resumen_pie">
|
||||
<t t-esc="fila.personas"/> personas ·
|
||||
<t t-esc="dinero(fila.ventas)"/> ·
|
||||
<t t-esc="dinero(fila.ventas_por_hora)"/>/h
|
||||
</span>
|
||||
</t>
|
||||
</div>
|
||||
</t>
|
||||
</div>
|
||||
</t>
|
||||
|
||||
<!-- ── Controles ── -->
|
||||
<div class="beyond_equipo_controles">
|
||||
<div class="beyond_equipo_periodos">
|
||||
<t t-foreach="periodos" t-as="periodo" t-key="periodo.clave">
|
||||
<button type="button" class="beyond_equipo_periodo"
|
||||
t-att-class="{'beyond_activo': state.periodo === periodo.clave and !state.desde}"
|
||||
t-on-click="() => this.verPeriodo(periodo.clave)"
|
||||
t-esc="periodo.etiqueta"/>
|
||||
</t>
|
||||
<label class="beyond_equipo_rango">
|
||||
Desde
|
||||
<input type="date" t-att-value="state.desde"
|
||||
t-on-change="(ev) => this.onRango('desde', ev)"/>
|
||||
</label>
|
||||
<label class="beyond_equipo_rango">
|
||||
Hasta
|
||||
<input type="date" t-att-value="state.hasta"
|
||||
t-on-change="(ev) => this.onRango('hasta', ev)"/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="beyond_equipo_buscador">
|
||||
<i class="fa fa-search"/>
|
||||
<input type="search" placeholder="Buscar por nombre o celular…"
|
||||
t-on-input="onBuscar"/>
|
||||
</div>
|
||||
<!-- Puerta discreta a la configuración: solo la dirección. -->
|
||||
<button t-if="state.datos and state.datos.es_admin_general"
|
||||
type="button" class="beyond_equipo_engrane"
|
||||
title="Configuración del checador" aria-label="Configuración del checador"
|
||||
t-on-click="configuracion">
|
||||
<i class="fa fa-cog"/>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="beyond_equipo_filtros">
|
||||
<t t-foreach="filtros" t-as="filtro" t-key="filtro.clave">
|
||||
<button type="button" class="beyond_equipo_filtro"
|
||||
t-att-class="{'beyond_activo': state.filtro === filtro.clave}"
|
||||
t-on-click="() => this.verFiltro(filtro.clave)">
|
||||
<t t-esc="filtro.etiqueta"/>
|
||||
<span class="beyond_equipo_cuenta" t-esc="cuenta(filtro.clave)"/>
|
||||
</button>
|
||||
</t>
|
||||
<t t-if="state.datos and state.datos.es_admin_general">
|
||||
<span class="beyond_equipo_separador"/>
|
||||
<t t-foreach="state.datos.sucursales" t-as="sucursal" t-key="sucursal.id">
|
||||
<button type="button" class="beyond_equipo_chip"
|
||||
t-att-class="{'beyond_activo': state.branchIds.includes(sucursal.id)}"
|
||||
t-on-click="() => this.alternarSucursal(sucursal.id)"
|
||||
t-esc="sucursal.nombre"/>
|
||||
</t>
|
||||
</t>
|
||||
</div>
|
||||
|
||||
<!-- ── La tabla ── -->
|
||||
<div class="beyond_equipo_tarjeta">
|
||||
<t t-if="state.cargando and !state.datos">
|
||||
<p class="beyond_equipo_vacio">Cargando…</p>
|
||||
</t>
|
||||
<t t-elif="!state.datos.personas.length">
|
||||
<p class="beyond_equipo_vacio">Nadie aquí con ese criterio.</p>
|
||||
</t>
|
||||
<t t-else="">
|
||||
<div class="beyond_equipo_scroll">
|
||||
<table class="beyond_equipo_tabla">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="beyond_equipo_quien">Persona</th>
|
||||
<th>Sucursal</th>
|
||||
<th>Hoy</th>
|
||||
<th t-esc="state.datos.periodo.titulo"/>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<t t-foreach="state.datos.personas" t-as="persona" t-key="persona.id">
|
||||
<tr t-on-click="() => this.abrirFicha(persona)">
|
||||
<td class="beyond_equipo_quien">
|
||||
<span class="beyond_equipo_retrato">
|
||||
<img t-if="persona.tiene_foto"
|
||||
t-att-src="fotoDe(persona)" alt=""/>
|
||||
<span t-else="" t-esc="iniciales(persona.nombre)"/>
|
||||
</span>
|
||||
<span class="beyond_equipo_identidad">
|
||||
<span class="beyond_equipo_nombre">
|
||||
<t t-esc="persona.nombre"/>
|
||||
<span t-if="persona.acceso_etiqueta"
|
||||
class="beyond_equipo_rol"
|
||||
t-esc="persona.acceso_etiqueta"/>
|
||||
</span>
|
||||
<span class="beyond_equipo_celular"
|
||||
t-esc="persona.celular"/>
|
||||
</span>
|
||||
</td>
|
||||
<td t-esc="persona.sucursal"/>
|
||||
<td>
|
||||
<span class="beyond_equipo_hoy"
|
||||
t-att-class="'beyond_' + persona.estado">
|
||||
<t t-if="persona.estado === 'trabajando'">Trabajando</t>
|
||||
<t t-elif="persona.estado === 'salio'">
|
||||
Salió <t t-esc="hora(persona.hora_salida)"/>
|
||||
</t>
|
||||
<t t-else="">Sin entrada</t>
|
||||
</span>
|
||||
</td>
|
||||
<td class="beyond_equipo_avance">
|
||||
<span class="beyond_equipo_horas">
|
||||
<t t-esc="horas(persona.horas)"/>
|
||||
</span>
|
||||
<!-- La jornada abierta no suma
|
||||
todavía —esas son las horas
|
||||
que se pagan— pero se dice,
|
||||
que si no «Trabajando · 0 h»
|
||||
parece un error. -->
|
||||
<span t-if="persona.en_curso"
|
||||
class="beyond_equipo_en_curso">
|
||||
+<t t-esc="horas(persona.en_curso)"/> en curso
|
||||
</span>
|
||||
<span class="beyond_equipo_barra">
|
||||
<span class="beyond_equipo_relleno"
|
||||
t-attf-style="width: {{ avance(persona) }}%"/>
|
||||
</span>
|
||||
<!-- Pasarse no llena más la barra: se dice. -->
|
||||
<span t-if="persona.sobre_meta"
|
||||
class="beyond_equipo_sobrante">
|
||||
+<t t-esc="sobrante(persona)"/> h
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
</t>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="beyond_equipo_pie">
|
||||
<t t-esc="state.datos.total"/> personas ·
|
||||
Jornada esperada: <t t-esc="meta"/> h por semana
|
||||
</p>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</Layout>
|
||||
</t>
|
||||
</templates>
|
||||
@@ -0,0 +1,113 @@
|
||||
/** Part of Beyond. Collina Systems proprietary module. */
|
||||
import { Component, onWillStart, onWillUpdateProps, useState } from "@odoo/owl";
|
||||
import { registry } from "@web/core/registry";
|
||||
import { useService } from "@web/core/utils/hooks";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
|
||||
/**
|
||||
* El cuerpo de la ficha: avance, productividad y jornadas.
|
||||
*
|
||||
* Va como widget de VISTA y no de campo porque no muestra un campo: muestra
|
||||
* tres cosas que se calculan en el servidor a partir de otros modelos. Una
|
||||
* sola llamada las trae juntas —las tres miran el mismo periodo— y así no
|
||||
* pueden discrepar entre sí.
|
||||
*
|
||||
* La tabla de jornadas es de SOLO LECTURA y sin botones por renglón: el
|
||||
* registro es lo que marcó el QR (ADR-018). La etiqueta del día va solo en
|
||||
* el primero de cada día, que es lo que deja ver de un vistazo que alguien
|
||||
* salió a comer y volvió.
|
||||
*/
|
||||
export class BeyondFichaPersonal extends Component {
|
||||
static template = "beyond_attendance_qr.FichaPersonal";
|
||||
static props = { record: { type: Object, optional: true }, "*": true };
|
||||
|
||||
setup() {
|
||||
this.orm = useService("orm");
|
||||
this.state = useState({ datos: null, periodo: "semana" });
|
||||
onWillStart(() => this.cargar());
|
||||
onWillUpdateProps(() => this.cargar());
|
||||
}
|
||||
|
||||
get resId() {
|
||||
return this.props.record && this.props.record.resId;
|
||||
}
|
||||
|
||||
async cargar() {
|
||||
if (!this.resId) {
|
||||
// Alta: todavía no hay historial que enseñar.
|
||||
this.state.datos = null;
|
||||
return;
|
||||
}
|
||||
this.state.datos = await this.orm.call(
|
||||
"hr.employee", "beyond_ficha_datos", [this.resId, this.state.periodo]);
|
||||
}
|
||||
|
||||
async verPeriodo(clave) {
|
||||
this.state.periodo = clave;
|
||||
await this.cargar();
|
||||
}
|
||||
|
||||
get periodos() {
|
||||
return [
|
||||
{ clave: "hoy", etiqueta: _t("Hoy") },
|
||||
{ clave: "semana", etiqueta: _t("Semana") },
|
||||
{ clave: "mes", etiqueta: _t("Mes") },
|
||||
{ clave: "ano", etiqueta: _t("Año") },
|
||||
];
|
||||
}
|
||||
|
||||
avance() {
|
||||
const a = this.state.datos.avance;
|
||||
return a.meta ? Math.min(100, Math.round((a.horas / a.meta) * 100)) : 0;
|
||||
}
|
||||
|
||||
sobrante() {
|
||||
const a = this.state.datos.avance;
|
||||
return Math.round((a.horas - a.meta) * 10) / 10;
|
||||
}
|
||||
|
||||
horas(valor) {
|
||||
return `${Math.round((valor || 0) * 10) / 10} h`;
|
||||
}
|
||||
|
||||
dinero(valor) {
|
||||
return `$${(valor || 0).toLocaleString("es-MX", {
|
||||
minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
|
||||
}
|
||||
|
||||
hora(iso) {
|
||||
if (!iso) {
|
||||
return "—";
|
||||
}
|
||||
return new Date(iso.replace(" ", "T") + "Z").toLocaleTimeString("es-MX", {
|
||||
hour: "2-digit", minute: "2-digit" });
|
||||
}
|
||||
|
||||
dia(fecha) {
|
||||
if (!fecha) {
|
||||
return "";
|
||||
}
|
||||
return new Date(fecha + "T12:00:00").toLocaleDateString("es-MX", {
|
||||
weekday: "short", day: "numeric", month: "short" });
|
||||
}
|
||||
|
||||
etiquetaEstado(estado) {
|
||||
return {
|
||||
abierta: _t("Abierta"),
|
||||
cerrada: _t("Cerrada"),
|
||||
cierre_automatico: _t("Cierre automático"),
|
||||
rechazada: _t("Rechazada"),
|
||||
}[estado] || estado;
|
||||
}
|
||||
|
||||
/** Alto de la barra de un día, en porcentaje del mejor día. */
|
||||
altoDelDia(monto) {
|
||||
const dias = this.state.datos.productividad.dias;
|
||||
const techo = Math.max(...dias.map((d) => d.monto), 1);
|
||||
return Math.max(4, Math.round((monto / techo) * 100));
|
||||
}
|
||||
}
|
||||
|
||||
registry.category("view_widgets").add("beyond_ficha_personal", {
|
||||
component: BeyondFichaPersonal,
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
<t t-name="beyond_attendance_qr.FichaPersonal">
|
||||
<div class="beyond_ficha_personal" t-if="state.datos">
|
||||
<div class="beyond_ficha_periodos">
|
||||
<t t-foreach="periodos" t-as="periodo" t-key="periodo.clave">
|
||||
<button type="button" class="beyond_equipo_periodo"
|
||||
t-att-class="{'beyond_activo': state.periodo === periodo.clave}"
|
||||
t-on-click="() => this.verPeriodo(periodo.clave)"
|
||||
t-esc="periodo.etiqueta"/>
|
||||
</t>
|
||||
</div>
|
||||
|
||||
<div class="beyond_ficha_bloques">
|
||||
<!-- ── Avance ── -->
|
||||
<div class="beyond_tarjeta beyond_ficha_avance">
|
||||
<span class="beyond_tarjeta_titulo" t-esc="state.datos.avance.titulo"/>
|
||||
<span class="beyond_ficha_cifra">
|
||||
<t t-esc="horas(state.datos.avance.horas)"/>
|
||||
<small> de <t t-esc="state.datos.avance.meta"/> h</small>
|
||||
</span>
|
||||
<span class="beyond_equipo_barra">
|
||||
<span class="beyond_equipo_relleno"
|
||||
t-attf-style="width: {{ avance() }}%"/>
|
||||
</span>
|
||||
<span t-if="state.datos.avance.sobre_meta"
|
||||
class="beyond_equipo_sobrante">+<t t-esc="sobrante()"/> h</span>
|
||||
</div>
|
||||
|
||||
<!-- ── Productividad ── -->
|
||||
<div class="beyond_tarjeta beyond_ficha_productividad">
|
||||
<span class="beyond_tarjeta_titulo">Productividad</span>
|
||||
<span class="beyond_ficha_cifra"
|
||||
t-esc="dinero(state.datos.productividad.ventas)"/>
|
||||
<span class="beyond_ficha_detalle">
|
||||
Ticket promedio <t t-esc="dinero(state.datos.productividad.ticket)"/> ·
|
||||
<t t-esc="dinero(state.datos.productividad.ventas_por_hora)"/> por hora
|
||||
</span>
|
||||
<!-- «Participación», no «vendió»: desde que la atribución
|
||||
es por venta completa (ADR-007 revisado), quien
|
||||
acompaña en un ticket caro sube de puesto sin haberlo
|
||||
vendido. El cálculo se queda; lo que cambia es lo que
|
||||
la etiqueta promete. -->
|
||||
<span class="beyond_ficha_detalle" t-if="state.datos.productividad.de">
|
||||
N.º <t t-esc="state.datos.productividad.ranking"/>
|
||||
de <t t-esc="state.datos.productividad.de"/> por
|
||||
participación en ventas de su sucursal
|
||||
</span>
|
||||
<span class="beyond_ficha_delta"
|
||||
t-att-class="state.datos.productividad.delta >= 0 ? 'beyond_sube' : 'beyond_baja'">
|
||||
<t t-if="state.datos.productividad.delta >= 0">▲</t>
|
||||
<t t-else="">▼</t>
|
||||
<t t-esc="dinero(Math.abs(state.datos.productividad.delta))"/>
|
||||
contra el periodo anterior
|
||||
</span>
|
||||
<div class="beyond_ficha_barras" t-if="state.datos.productividad.dias.length">
|
||||
<t t-foreach="state.datos.productividad.dias" t-as="dia" t-key="dia.dia">
|
||||
<span class="beyond_ficha_dia" t-att-title="dia.dia">
|
||||
<span class="beyond_ficha_columna"
|
||||
t-attf-style="height: {{ altoDelDia(dia.monto) }}%"/>
|
||||
</span>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Jornadas ── -->
|
||||
<div class="beyond_tarjeta beyond_ficha_jornadas">
|
||||
<span class="beyond_tarjeta_titulo">Jornadas</span>
|
||||
<t t-if="!state.datos.jornadas.length">
|
||||
<p class="beyond_ficha_sin_jornadas">Sin jornadas en este periodo.</p>
|
||||
</t>
|
||||
<t t-else="">
|
||||
<div class="beyond_ficha_scroll">
|
||||
<table class="beyond_ficha_tabla">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Día</th>
|
||||
<th>Entrada</th>
|
||||
<th>Salida</th>
|
||||
<th>Sucursal</th>
|
||||
<th>Duración</th>
|
||||
<th>Acumulado</th>
|
||||
<th>Estado</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<t t-foreach="state.datos.jornadas" t-as="jornada"
|
||||
t-key="jornada.id">
|
||||
<tr>
|
||||
<td class="beyond_ficha_etiqueta_dia"
|
||||
t-esc="dia(jornada.etiqueta_dia)"/>
|
||||
<td t-esc="hora(jornada.entrada)"/>
|
||||
<td t-esc="hora(jornada.salida)"/>
|
||||
<td t-esc="jornada.sucursal"/>
|
||||
<td t-esc="horas(jornada.horas)"/>
|
||||
<td t-esc="horas(jornada.acumulado)"/>
|
||||
<td>
|
||||
<span class="beyond_ficha_estado"
|
||||
t-att-class="'beyond_' + jornada.estado"
|
||||
t-esc="etiquetaEstado(jornada.estado)"/>
|
||||
</td>
|
||||
</tr>
|
||||
</t>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</t>
|
||||
|
||||
<t t-name="beyond_attendance_qr.CelularAviso">
|
||||
<div class="beyond_celular_aviso">
|
||||
<input type="tel" class="beyond_celular_campo"
|
||||
t-att-value="valor" t-att-readonly="props.readonly"
|
||||
placeholder="10 dígitos"
|
||||
t-on-input="onInput" t-on-change="onSalir"/>
|
||||
<span t-if="state.mensaje" class="beyond_celular_mensaje"
|
||||
t-esc="state.mensaje"/>
|
||||
</div>
|
||||
</t>
|
||||
</templates>
|
||||
@@ -0,0 +1,676 @@
|
||||
// Personal (ADR-018). Reutiliza los tokens y el eje del Panel General: esta
|
||||
// pantalla vive dentro del panel y no puede elegir su propio margen.
|
||||
//
|
||||
// Colores propios de este diseño, locales al panel por el mismo criterio de
|
||||
// ADR-013 (un color gradúa a token cuando lo pide una SEGUNDA pantalla):
|
||||
// verde de «trabajando», ámbar de «sin entrada» y petróleo del botón de
|
||||
// restablecer.
|
||||
$beyond-personal-verde: #1F6B4A;
|
||||
$beyond-personal-verde-suave: #E6F0E8;
|
||||
$beyond-personal-ambar: #FBF1DC;
|
||||
$beyond-personal-ambar-tinta: #7A5A12;
|
||||
$beyond-personal-petroleo: #2E5C63;
|
||||
$beyond-personal-rojo-suave: #E2CFC6;
|
||||
$beyond-personal-rojo-tinta: #A63A22;
|
||||
|
||||
.o_beyond_equipo {
|
||||
background: $beyond-surface;
|
||||
padding-bottom: 32px;
|
||||
}
|
||||
|
||||
.beyond_equipo_eje {
|
||||
@include beyond-ancho-contenido;
|
||||
padding-top: 20px;
|
||||
}
|
||||
|
||||
.beyond_equipo_nuevo {
|
||||
padding: 10px 22px;
|
||||
border-radius: 999px;
|
||||
background: $beyond-panel-acento;
|
||||
color: #fff;
|
||||
font-weight: 700;
|
||||
|
||||
&:hover { background: $beyond-panel-acento-hover; color: #fff; }
|
||||
}
|
||||
|
||||
// ── Resumen ─────────────────────────────────────────────────────────────
|
||||
.beyond_equipo_resumen {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(230px, 1fr));
|
||||
gap: 12px;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.beyond_resumen_tarjeta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
padding: 16px 18px;
|
||||
background: $beyond-panel-tarjeta;
|
||||
border: 1px solid $beyond-line;
|
||||
border-radius: $beyond-panel-radio-tarjeta;
|
||||
|
||||
&.beyond_resumen_red {
|
||||
background: $beyond-panel-durazno;
|
||||
border-color: transparent;
|
||||
}
|
||||
}
|
||||
|
||||
.beyond_resumen_titulo {
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
letter-spacing: .05em;
|
||||
text-transform: uppercase;
|
||||
color: $beyond-ink-softer;
|
||||
}
|
||||
|
||||
.beyond_resumen_cifra {
|
||||
font-size: 24px;
|
||||
font-weight: 800;
|
||||
color: $beyond-ink;
|
||||
|
||||
small { font-size: 13px; font-weight: 700; color: $beyond-ink-muted; }
|
||||
}
|
||||
|
||||
.beyond_resumen_pie {
|
||||
font-size: 12.5px;
|
||||
color: $beyond-ink-softer;
|
||||
}
|
||||
|
||||
// ── Controles ───────────────────────────────────────────────────────────
|
||||
.beyond_equipo_controles {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.beyond_equipo_periodos {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.beyond_equipo_periodo,
|
||||
.beyond_equipo_filtro,
|
||||
.beyond_equipo_chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
min-height: 38px;
|
||||
padding: 0 16px;
|
||||
border: 1px solid $beyond-line;
|
||||
border-radius: 999px;
|
||||
background: $beyond-panel-tarjeta;
|
||||
color: $beyond-ink-soft;
|
||||
font-weight: 700;
|
||||
|
||||
&:hover { background: $beyond-surface-hover; }
|
||||
|
||||
// Elegido en TINTA, no en naranja: el naranja es de las acciones y el
|
||||
// «Nuevo» es lo único que lo lleva (ADR-013 §10). Con los dos en la
|
||||
// misma pantalla, «pulsa para crear» y «este filtro está puesto» se
|
||||
// decían con el mismo color.
|
||||
&.beyond_activo {
|
||||
border-color: $beyond-panel-elegido;
|
||||
background: $beyond-panel-elegido;
|
||||
color: $beyond-panel-elegido-texto;
|
||||
}
|
||||
}
|
||||
|
||||
.beyond_equipo_cuenta {
|
||||
padding: 1px 8px;
|
||||
border-radius: 999px;
|
||||
background: $beyond-surface-hover;
|
||||
color: $beyond-ink-soft;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.beyond_equipo_filtro.beyond_activo .beyond_equipo_cuenta {
|
||||
background: $beyond-panel-elegido-suave;
|
||||
color: $beyond-panel-elegido-texto;
|
||||
}
|
||||
|
||||
.beyond_equipo_rango {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
color: $beyond-ink-softer;
|
||||
|
||||
input {
|
||||
min-height: 38px;
|
||||
padding: 0 10px;
|
||||
border: 1px solid $beyond-line;
|
||||
border-radius: $beyond-panel-radio-control;
|
||||
background: $beyond-panel-tarjeta;
|
||||
color: $beyond-ink;
|
||||
}
|
||||
}
|
||||
|
||||
.beyond_equipo_buscador {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex: 1 1 220px;
|
||||
max-width: 330px;
|
||||
height: 44px;
|
||||
padding: 0 14px;
|
||||
margin-left: auto;
|
||||
background: $beyond-panel-tarjeta;
|
||||
border: 1px solid $beyond-line;
|
||||
border-radius: 999px;
|
||||
color: $beyond-ink-softer;
|
||||
|
||||
&:focus-within { border-color: $beyond-panel-acento; }
|
||||
|
||||
input {
|
||||
flex: 1;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: $beyond-ink;
|
||||
|
||||
&:focus { outline: none; }
|
||||
}
|
||||
}
|
||||
|
||||
// Discreta a propósito: es una puerta de mantenimiento, no una sección.
|
||||
.beyond_equipo_engrane {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border: 1px solid $beyond-line;
|
||||
border-radius: 50%;
|
||||
background: transparent;
|
||||
color: $beyond-ink-softer;
|
||||
|
||||
&:hover { background: $beyond-surface-hover; color: $beyond-ink; }
|
||||
}
|
||||
|
||||
.beyond_equipo_filtros {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.beyond_equipo_separador {
|
||||
width: 1px;
|
||||
height: 24px;
|
||||
margin: 0 4px;
|
||||
background: $beyond-line;
|
||||
}
|
||||
|
||||
// ── Tabla ───────────────────────────────────────────────────────────────
|
||||
.beyond_equipo_tarjeta {
|
||||
background: $beyond-panel-tarjeta;
|
||||
border-radius: $beyond-panel-radio-ficha;
|
||||
padding: 8px 8px 4px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.beyond_equipo_vacio {
|
||||
margin: 0;
|
||||
padding: 28px;
|
||||
color: $beyond-ink-softer;
|
||||
}
|
||||
|
||||
.beyond_equipo_scroll { overflow-x: auto; }
|
||||
|
||||
.beyond_equipo_tabla {
|
||||
width: 100%;
|
||||
border-collapse: separate;
|
||||
border-spacing: 0;
|
||||
|
||||
th, td {
|
||||
padding: 12px 14px;
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
border-bottom: 1px solid $beyond-line;
|
||||
}
|
||||
|
||||
th {
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
letter-spacing: .04em;
|
||||
text-transform: uppercase;
|
||||
color: $beyond-ink-softer;
|
||||
}
|
||||
|
||||
tbody tr {
|
||||
cursor: pointer;
|
||||
|
||||
&:hover td { background: $beyond-surface-hover; }
|
||||
&:last-child td { border-bottom: 0; }
|
||||
}
|
||||
}
|
||||
|
||||
.beyond_equipo_quien {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.beyond_equipo_retrato {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: none;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 50%;
|
||||
overflow: hidden;
|
||||
background: $beyond-panel-durazno;
|
||||
color: $beyond-panel-acento-pressed;
|
||||
font-size: 14px;
|
||||
font-weight: 800;
|
||||
|
||||
img { width: 100%; height: 100%; object-fit: cover; }
|
||||
}
|
||||
|
||||
.beyond_equipo_identidad {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.beyond_equipo_nombre {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-weight: 800;
|
||||
color: $beyond-ink;
|
||||
}
|
||||
|
||||
// Solo se dibuja si NO es colaborador: en una lista donde casi todos lo son,
|
||||
// repetirlo en cada renglón es ruido.
|
||||
.beyond_equipo_rol {
|
||||
padding: 2px 9px;
|
||||
border-radius: 999px;
|
||||
background: $beyond-panel-durazno;
|
||||
color: $beyond-panel-acento-pressed;
|
||||
font-size: 11.5px;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.beyond_equipo_celular {
|
||||
font-size: 12.5px;
|
||||
color: $beyond-ink-softer;
|
||||
}
|
||||
|
||||
.beyond_equipo_hoy {
|
||||
padding: 4px 12px;
|
||||
border-radius: 999px;
|
||||
font-size: 12.5px;
|
||||
font-weight: 700;
|
||||
|
||||
&.beyond_trabajando {
|
||||
background: $beyond-personal-verde-suave;
|
||||
color: $beyond-personal-verde;
|
||||
}
|
||||
&.beyond_salio {
|
||||
background: $beyond-surface-hover;
|
||||
color: $beyond-ink-soft;
|
||||
}
|
||||
&.beyond_sin_entrada {
|
||||
background: $beyond-personal-ambar;
|
||||
color: $beyond-personal-ambar-tinta;
|
||||
}
|
||||
}
|
||||
|
||||
.beyond_equipo_avance {
|
||||
min-width: 190px;
|
||||
}
|
||||
|
||||
.beyond_equipo_horas {
|
||||
display: inline-block;
|
||||
min-width: 58px;
|
||||
font-weight: 800;
|
||||
color: $beyond-ink;
|
||||
}
|
||||
|
||||
.beyond_equipo_barra {
|
||||
display: inline-block;
|
||||
width: 96px;
|
||||
height: 8px;
|
||||
margin: 0 8px;
|
||||
border-radius: 999px;
|
||||
background: $beyond-surface-active;
|
||||
vertical-align: middle;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.beyond_equipo_relleno {
|
||||
display: block;
|
||||
height: 100%;
|
||||
border-radius: 999px;
|
||||
background: $beyond-personal-verde;
|
||||
}
|
||||
|
||||
// Pasarse de la meta no llena más la barra —una barra llena y otra llenísima
|
||||
// se ven igual—: se dice con «+N h» en durazno.
|
||||
.beyond_equipo_sobrante {
|
||||
padding: 2px 9px;
|
||||
border-radius: 999px;
|
||||
background: $beyond-panel-durazno;
|
||||
color: $beyond-panel-acento-pressed;
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.beyond_equipo_pie {
|
||||
margin: 12px 6px 8px;
|
||||
font-size: 13px;
|
||||
color: $beyond-ink-softer;
|
||||
}
|
||||
|
||||
// ── La ficha de la persona ──────────────────────────────────────────────
|
||||
// Reutiliza .beyond_tarjeta, .beyond_campo y .beyond_chips de la capa del
|
||||
// panel: son las mismas piezas de Sucursales y del Catálogo.
|
||||
body.beyond_panel {
|
||||
.o_beyond_persona_form .o_form_sheet {
|
||||
background: transparent;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.beyond_persona_encabezado {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 18px;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.beyond_persona_retrato {
|
||||
flex: none;
|
||||
width: 96px;
|
||||
}
|
||||
|
||||
.beyond_persona_identidad {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
|
||||
h1 { margin: 0; }
|
||||
input { font-size: 26px; font-weight: 800; color: $beyond-ink; }
|
||||
}
|
||||
|
||||
.beyond_persona_bajo_nombre {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
font-size: 13.5px;
|
||||
color: $beyond-ink-softer;
|
||||
}
|
||||
|
||||
.beyond_persona_estado {
|
||||
padding: 3px 12px;
|
||||
border-radius: 999px;
|
||||
background: $beyond-personal-verde-suave;
|
||||
color: $beyond-personal-verde;
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.beyond_persona_acciones {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
margin-left: auto;
|
||||
|
||||
.btn {
|
||||
min-height: $beyond-panel-tactil;
|
||||
padding: 0 20px;
|
||||
border-radius: 999px;
|
||||
font-weight: 700;
|
||||
}
|
||||
}
|
||||
|
||||
.beyond_boton_clave {
|
||||
background: $beyond-personal-petroleo;
|
||||
color: #fff;
|
||||
|
||||
&:hover { background: darken($beyond-personal-petroleo, 6%); color: #fff; }
|
||||
}
|
||||
|
||||
// Destructivo, pero no rojo de alarma: dar de baja es una operación
|
||||
// normal de un salón, no un accidente.
|
||||
.beyond_boton_baja {
|
||||
background: $beyond-personal-rojo-suave;
|
||||
color: $beyond-personal-rojo-tinta;
|
||||
|
||||
&:hover { background: darken($beyond-personal-rojo-suave, 5%); }
|
||||
}
|
||||
|
||||
.beyond_persona_antiguedad {
|
||||
margin-left: 10px;
|
||||
color: $beyond-ink-muted;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.beyond_ficha_periodos {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.beyond_ficha_bloques {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
|
||||
gap: 18px;
|
||||
margin-bottom: 18px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.beyond_ficha_cifra {
|
||||
font-size: 30px;
|
||||
font-weight: 800;
|
||||
color: $beyond-ink;
|
||||
|
||||
small { font-size: 14px; font-weight: 700; color: $beyond-ink-muted; }
|
||||
}
|
||||
|
||||
.beyond_ficha_detalle {
|
||||
font-size: 13px;
|
||||
color: $beyond-ink-softer;
|
||||
}
|
||||
|
||||
.beyond_ficha_delta {
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
|
||||
&.beyond_sube { color: $beyond-personal-verde; }
|
||||
&.beyond_baja { color: $beyond-panel-rojo; }
|
||||
}
|
||||
|
||||
.beyond_ficha_barras {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
gap: 6px;
|
||||
height: 64px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.beyond_ficha_dia {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
flex: 1;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.beyond_ficha_columna {
|
||||
width: 100%;
|
||||
border-radius: 6px 6px 0 0;
|
||||
background: $beyond-panel-durazno;
|
||||
}
|
||||
|
||||
.beyond_ficha_scroll { overflow-x: auto; }
|
||||
|
||||
.beyond_ficha_tabla {
|
||||
width: 100%;
|
||||
border-collapse: separate;
|
||||
border-spacing: 0;
|
||||
|
||||
th, td {
|
||||
padding: 10px 12px;
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
border-bottom: 1px solid $beyond-line;
|
||||
}
|
||||
|
||||
th {
|
||||
font-size: 11.5px;
|
||||
font-weight: 700;
|
||||
letter-spacing: .04em;
|
||||
text-transform: uppercase;
|
||||
color: $beyond-ink-softer;
|
||||
}
|
||||
|
||||
tbody tr:last-child td { border-bottom: 0; }
|
||||
}
|
||||
|
||||
// La fecha va solo en el primer renglón del día: los siguientes son la
|
||||
// misma jornada partida por la comida.
|
||||
.beyond_ficha_etiqueta_dia {
|
||||
font-weight: 800;
|
||||
color: $beyond-ink;
|
||||
}
|
||||
|
||||
.beyond_ficha_estado {
|
||||
padding: 3px 10px;
|
||||
border-radius: 999px;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
background: $beyond-surface-hover;
|
||||
color: $beyond-ink-soft;
|
||||
|
||||
&.beyond_abierta {
|
||||
background: $beyond-personal-verde-suave;
|
||||
color: $beyond-personal-verde;
|
||||
}
|
||||
&.beyond_cierre_automatico {
|
||||
background: $beyond-personal-ambar;
|
||||
color: $beyond-personal-ambar-tinta;
|
||||
}
|
||||
&.beyond_rechazada {
|
||||
background: $beyond-personal-rojo-suave;
|
||||
color: $beyond-personal-rojo-tinta;
|
||||
}
|
||||
}
|
||||
|
||||
.beyond_ficha_sin_jornadas {
|
||||
margin: 0;
|
||||
color: $beyond-ink-softer;
|
||||
}
|
||||
|
||||
// El celular, con su aviso justo debajo.
|
||||
.beyond_celular_aviso {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.beyond_celular_campo {
|
||||
width: 100%;
|
||||
border: 0;
|
||||
border-bottom: 1px solid $beyond-line;
|
||||
background: transparent;
|
||||
color: $beyond-ink;
|
||||
|
||||
&:focus { outline: none; border-color: $beyond-panel-acento; }
|
||||
}
|
||||
|
||||
.beyond_celular_mensaje {
|
||||
font-size: 12.5px;
|
||||
font-weight: 700;
|
||||
color: $beyond-panel-rojo;
|
||||
}
|
||||
|
||||
// ── Configuración del checador ──
|
||||
.o_beyond_config_checador {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.beyond_config_bloque {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.beyond_config_par {
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Chips de selección ──────────────────────────────────────────────────
|
||||
// El widget de badges del core pinta el elegido con un gris casi igual al de
|
||||
// los demás y un borde de 1px: en pantalla se lee como que el clic no hizo
|
||||
// nada. Aquí el elegido es durazno con su tinta, como el resto de los chips
|
||||
// del panel, y se distingue de un vistazo.
|
||||
body.beyond_panel {
|
||||
.o_field_selection_badge .o_selection_badge {
|
||||
min-height: 40px;
|
||||
padding: 0 18px;
|
||||
border: 1px solid $beyond-line;
|
||||
border-radius: 999px;
|
||||
background: $beyond-panel-tarjeta;
|
||||
color: $beyond-ink-soft;
|
||||
font-size: 13.5px;
|
||||
font-weight: 800;
|
||||
|
||||
&:hover { background: $beyond-surface-hover; }
|
||||
|
||||
// Misma regla dentro de un formulario: el durazno se queda para
|
||||
// identidad —chips de sucursal en una lista, pastilla de rol,
|
||||
// avatares— y la tinta para «esto es lo elegido». Dos idiomas para lo
|
||||
// mismo obligan a aprender cuál toca en cada pantalla.
|
||||
&.active {
|
||||
border-color: $beyond-panel-elegido;
|
||||
background: $beyond-panel-elegido;
|
||||
color: $beyond-panel-elegido-texto;
|
||||
}
|
||||
}
|
||||
|
||||
// Sin el margen de abajo del core: dentro de un .beyond_campo sobra.
|
||||
.o_field_selection_badge > div { margin-bottom: 0 !important; }
|
||||
}
|
||||
|
||||
// Una plaza sin gente se apaga en vez de ocupar sitio con ceros.
|
||||
.beyond_resumen_tarjeta.beyond_resumen_vacia {
|
||||
background: transparent;
|
||||
border-style: dashed;
|
||||
|
||||
.beyond_resumen_titulo, .beyond_resumen_pie { color: $beyond-ink-muted; }
|
||||
}
|
||||
|
||||
// Y quien no tiene sucursal se dice, no se resta en silencio.
|
||||
.beyond_resumen_tarjeta.beyond_resumen_huerfanos {
|
||||
border-color: $beyond-personal-ambar-tinta;
|
||||
background: $beyond-personal-ambar;
|
||||
}
|
||||
|
||||
.beyond_resumen_aviso {
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: $beyond-personal-ambar-tinta;
|
||||
}
|
||||
|
||||
// Lo que lleva la jornada abierta hasta ahora: no suma en las horas del
|
||||
// periodo —esas son las que se pagan— pero se ve.
|
||||
.beyond_equipo_en_curso {
|
||||
margin-left: 6px;
|
||||
padding: 2px 9px;
|
||||
border-radius: 999px;
|
||||
background: $beyond-personal-verde-suave;
|
||||
color: $beyond-personal-verde;
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
from . import test_barrido_publico
|
||||
from . import test_aislamiento
|
||||
from . import test_aterrizaje
|
||||
from . import test_autocierre
|
||||
from . import test_bloque7
|
||||
from . import test_c027_unificacion
|
||||
from . import test_checada_http
|
||||
@@ -15,3 +17,5 @@ from . import test_panel
|
||||
from . import test_personal
|
||||
from . import test_portal_http
|
||||
from . import test_solicitudes
|
||||
from . import test_equipo_datos
|
||||
from . import test_personal_navegador
|
||||
@@ -35,8 +35,8 @@ class TestBeyondChecadorAislamiento(BeyondChecadorCase):
|
||||
'employee_id': cls.emp_b.id, 'tipo': 'olvido_entrada',
|
||||
'propuesta_entrada_ts': '2026-08-10 09:00:00'})
|
||||
Bitacora = cls.env['beyond.bitacora']
|
||||
cls.bitacora_a = Bitacora.registrar('prueba', 'x', 1, branch=cls.branch_a)
|
||||
cls.bitacora_b = Bitacora.registrar('prueba', 'x', 2, branch=cls.branch_b)
|
||||
cls.bitacora_a = Bitacora._registrar('prueba', 'x', 1, branch=cls.branch_a)
|
||||
cls.bitacora_b = Bitacora._registrar('prueba', 'x', 2, branch=cls.branch_b)
|
||||
|
||||
def _record(self, attr):
|
||||
return getattr(self, attr)
|
||||
|
||||
@@ -78,3 +78,46 @@ class TestBeyondAterrizaje(HttpCase):
|
||||
pagina = self._login_web('2225550001', 'clave-aterriza-8')
|
||||
self.assertIn('/odoo', pagina.url)
|
||||
self.assertFalse(pagina.url.endswith('/beyond/mi'))
|
||||
|
||||
def _login_con_redirect(self, login, password, redirect):
|
||||
formulario = self.url_open('/web/login')
|
||||
csrf = re.search(r'name="csrf_token" value="([^"]+)"',
|
||||
formulario.text).group(1)
|
||||
return self.url_open('/web/login', data={
|
||||
'login': login, 'password': password, 'csrf_token': csrf,
|
||||
'redirect': redirect})
|
||||
|
||||
def test_quien_administra_cae_en_el_menu_principal(self):
|
||||
"""Y no donde se quedó: al vencerse la sesión Odoo guarda la última
|
||||
dirección en el redirect del login, y así se volvía a caer en la
|
||||
última app abierta."""
|
||||
pagina = self._login_con_redirect(
|
||||
'2225550002', 'clave-aterriza-8', '/odoo/action-123')
|
||||
self.assertTrue(pagina.url.rstrip('/').endswith('/odoo'),
|
||||
f'aterrizó en {pagina.url}: debía ser el Menú Principal')
|
||||
|
||||
def test_sin_destino_pendiente_tambien_cae_ahi(self):
|
||||
pagina = self._login_web('2225550002', 'clave-aterriza-8')
|
||||
self.assertTrue(pagina.url.rstrip('/').endswith('/odoo'))
|
||||
|
||||
def test_un_enlace_nuestro_sigue_respetandose(self):
|
||||
"""El kiosco manda a login con su token en el redirect: si lo
|
||||
pisáramos, se perdería la checada."""
|
||||
pagina = self._login_con_redirect(
|
||||
'2225550002', 'clave-aterriza-8', '/beyond/mi')
|
||||
self.assertTrue(pagina.url.endswith('/beyond/mi'))
|
||||
|
||||
def test_el_colaborador_no_cambia_de_destino(self):
|
||||
pagina = self._login_con_redirect(
|
||||
'2225550001', 'clave-aterriza-8', '/odoo/action-123')
|
||||
self.assertTrue(pagina.url.endswith('/beyond/mi'),
|
||||
'su panel sigue mandando sobre cualquier backend')
|
||||
|
||||
def test_la_cuenta_tecnica_queda_fuera_de_la_regla(self):
|
||||
"""Soporte sigue el camino nativo: la regla es del nivel de acceso de
|
||||
Beyond, no de cualquiera que administre."""
|
||||
tecnica = self.env.ref('base.user_admin')
|
||||
self.assertTrue(
|
||||
self.env['hr.employee'].sudo()._beyond_usuario_protegido(tecnica),
|
||||
'la cuenta técnica está protegida, así que no se le reescribe el '
|
||||
'destino')
|
||||
@@ -0,0 +1,204 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from odoo.tests import tagged
|
||||
|
||||
from .common import BeyondChecadorCase
|
||||
|
||||
# America/Mexico_City es UTC-6 todo el año (México quitó el horario de verano
|
||||
# en 2022), así que la conversión es una resta y no depende de la fecha.
|
||||
UTC = 6
|
||||
|
||||
# La ventana del checador de estas pruebas: 06:00 a 20:00 locales.
|
||||
VENTANA_INICIO = '06:00'
|
||||
VENTANA_FIN = '20:00'
|
||||
|
||||
|
||||
def local(dia, hora, minuto=0):
|
||||
"""Hora local de Puebla → UTC naive, que es lo que guarda Odoo."""
|
||||
return datetime(2026, 8, dia, hora, minuto) + timedelta(hours=UTC)
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestBeyondCierreAutomatico(BeyondChecadorCase):
|
||||
"""El cierre automático sin revisión (decisión del cliente, 25-ago-2026).
|
||||
|
||||
Antes, la jornada sin salida pasaba a `revision`, no sumaba horas y
|
||||
esperaba a que un supervisor la resolviera. Ahora se cierra sola al fin
|
||||
de la ventana del checador y **las horas cuentan**: quien olvida marcar
|
||||
salida cobra hasta el cierre. Queda marcada para que se vea.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
icp = cls.env['ir.config_parameter'].sudo()
|
||||
icp.set_param('beyond_attendance_qr.ventana_inicio', VENTANA_INICIO)
|
||||
icp.set_param('beyond_attendance_qr.ventana_fin', VENTANA_FIN)
|
||||
|
||||
def _abrir(self, employee, dia, hora, minuto=0):
|
||||
"""Una jornada abierta a una hora concreta, sin pasar por el kiosco."""
|
||||
return self.Attendance.with_context(beyond_sistema=True).create({
|
||||
'employee_id': employee.id,
|
||||
'check_in': local(dia, hora, minuto),
|
||||
})
|
||||
|
||||
def _correr(self, dia, hora):
|
||||
return self.Attendance._beyond_cron_auto_cierre(ahora=local(dia, hora))
|
||||
|
||||
# ── El cierre ──────────────────────────────────────────────────────
|
||||
def test_la_jornada_abierta_se_cierra_al_fin_de_la_ventana(self):
|
||||
jornada = self._abrir(self.emp_c, 10, 10)
|
||||
self._correr(10, 22)
|
||||
self.assertEqual(jornada.check_out, local(10, 20),
|
||||
'se cierra a la hora de fin de la ventana de SU día')
|
||||
self.assertEqual(jornada.beyond_estado, 'cerrada')
|
||||
self.assertTrue(jornada.beyond_autocerrada,
|
||||
'queda marcada para que el cierre se vea')
|
||||
self.assertAlmostEqual(jornada.beyond_horas, 10.0, places=2)
|
||||
|
||||
def test_las_horas_del_cierre_automatico_cuentan(self):
|
||||
"""Es la decisión con efecto en nómina: antes no sumaban."""
|
||||
antes = self.emp_c.beyond_total_horas()
|
||||
self._abrir(self.emp_c, 10, 14)
|
||||
self._correr(10, 22)
|
||||
self.assertAlmostEqual(self.emp_c.beyond_total_horas(), antes + 6.0,
|
||||
places=2)
|
||||
|
||||
def test_una_jornada_ya_cerrada_no_se_toca(self):
|
||||
jornada = self._abrir(self.emp_c, 10, 9)
|
||||
jornada.with_context(beyond_sistema=True).write({
|
||||
'check_out': local(10, 17), 'beyond_estado': 'cerrada'})
|
||||
self._correr(10, 22)
|
||||
self.assertEqual(jornada.check_out, local(10, 17))
|
||||
self.assertFalse(jornada.beyond_autocerrada,
|
||||
'no la cerró el cron, así que no lleva la marca')
|
||||
|
||||
def test_dentro_de_la_ventana_no_cierra_nada(self):
|
||||
"""La gemela del primero: si el cron cerrara siempre, aquel pasaría
|
||||
igual y este es el que lo caza (ADR-016)."""
|
||||
jornada = self._abrir(self.emp_c, 10, 9)
|
||||
self.assertEqual(self._correr(10, 12), 0)
|
||||
self.assertEqual(jornada.beyond_estado, 'abierta')
|
||||
self.assertFalse(jornada.check_out)
|
||||
|
||||
def test_quien_salio_a_comer_solo_autocierra_la_segunda(self):
|
||||
"""Un día puede tener varios renglones. La de la mañana ya cerró
|
||||
cuando se fue a comer; la de la tarde es la que quedó abierta."""
|
||||
manana = self._abrir(self.emp_c, 10, 9)
|
||||
manana.with_context(beyond_sistema=True).write({
|
||||
'check_out': local(10, 14), 'beyond_estado': 'cerrada'})
|
||||
tarde = self._abrir(self.emp_c, 10, 15)
|
||||
|
||||
self._correr(10, 22)
|
||||
|
||||
self.assertEqual(manana.check_out, local(10, 14))
|
||||
self.assertFalse(manana.beyond_autocerrada)
|
||||
self.assertEqual(tarde.check_out, local(10, 20))
|
||||
self.assertTrue(tarde.beyond_autocerrada)
|
||||
|
||||
def test_el_cierre_queda_en_la_bitacora(self):
|
||||
jornada = self._abrir(self.emp_c, 10, 10)
|
||||
self._correr(10, 22)
|
||||
registro = self.env['beyond.bitacora'].sudo().search(
|
||||
[('accion', '=', 'jornada_auto_cerrada'),
|
||||
('entidad_id', '=', jornada.id)], limit=1)
|
||||
self.assertTrue(registro, 'el cierre automático se registra')
|
||||
|
||||
# ── Las dos guardas ────────────────────────────────────────────────
|
||||
def test_una_entrada_posterior_al_fin_cierra_en_la_ventana_siguiente(self):
|
||||
"""Solo el puente del kiosco nativo (PIN) puede abrir una jornada
|
||||
fuera de la ventana. Cerrarla a las 20:00 de su propio día daría una
|
||||
salida ANTERIOR a la entrada."""
|
||||
jornada = self._abrir(self.emp_c, 10, 22)
|
||||
self._correr(11, 23)
|
||||
self.assertEqual(jornada.check_out, local(11, 20),
|
||||
'cierra en el fin de ventana siguiente')
|
||||
self.assertGreater(jornada.check_out, jornada.check_in)
|
||||
|
||||
def test_una_jornada_larguisima_se_cierra_y_se_anota_como_anomalia(self):
|
||||
"""Un cierre de veintitantas horas no puede pasar en silencio por la
|
||||
nómina. Se cierra igual —dejarla abierta es peor— pero queda dicho.
|
||||
|
||||
El caso real es el del puente con PIN: una entrada a las 22:00, fuera
|
||||
de la ventana, que solo puede cerrarse en el fin de ventana del día
|
||||
siguiente."""
|
||||
jornada = self._abrir(self.emp_c, 10, 22)
|
||||
self._correr(11, 23)
|
||||
self.assertTrue(jornada.check_out, 'se cierra igual')
|
||||
self.assertTrue(jornada.beyond_autocerrada)
|
||||
self.assertGreater(jornada.beyond_horas, 16.0)
|
||||
anomalia = self.env['beyond.bitacora'].sudo().search(
|
||||
[('accion', '=', 'jornada_auto_cerrada_anomala'),
|
||||
('entidad_id', '=', jornada.id)], limit=1)
|
||||
self.assertTrue(anomalia, 'una jornada así se anota como anomalía')
|
||||
|
||||
def test_una_jornada_normal_no_se_anota_como_anomalia(self):
|
||||
"""La gemela: si todo cierre se anotara como anómalo, la anotación
|
||||
dejaría de significar algo."""
|
||||
jornada = self._abrir(self.emp_c, 10, 10)
|
||||
self._correr(10, 22)
|
||||
self.assertFalse(self.env['beyond.bitacora'].sudo().search_count(
|
||||
[('accion', '=', 'jornada_auto_cerrada_anomala'),
|
||||
('entidad_id', '=', jornada.id)]))
|
||||
|
||||
def test_la_jornada_de_alguien_dado_de_baja_tambien_se_cierra(self):
|
||||
"""Dar de baja archiva a la persona. Si el cron buscara solo entre
|
||||
empleados activos, la jornada que dejó abierta se quedaría abierta
|
||||
para siempre y su última nómina saldría mal."""
|
||||
jornada = self._abrir(self.emp_c, 10, 11)
|
||||
self.emp_c.action_beyond_baja()
|
||||
self.assertFalse(self.emp_c.active, 'la baja archiva')
|
||||
|
||||
self._correr(10, 22)
|
||||
|
||||
self.assertEqual(jornada.check_out, local(10, 20))
|
||||
self.assertTrue(jornada.beyond_autocerrada)
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestBeyondSalidaAComer(BeyondChecadorCase):
|
||||
"""Salir a comer y volver: dos jornadas limpias el mismo día."""
|
||||
|
||||
def test_entrada_salida_entrada_salida_da_dos_jornadas(self):
|
||||
primera = self._checar(self.emp_c, self.branch_a)['jornada']
|
||||
self._checar(self.emp_c, self.branch_a) # sale a comer
|
||||
segunda = self._checar(self.emp_c, self.branch_a)['jornada']
|
||||
self._checar(self.emp_c, self.branch_a) # sale al final
|
||||
|
||||
self.assertNotEqual(primera, segunda, 'cada par es una jornada')
|
||||
for jornada in (primera, segunda):
|
||||
self.assertEqual(jornada.beyond_estado, 'cerrada')
|
||||
self.assertTrue(jornada.check_in and jornada.check_out)
|
||||
self.assertFalse(jornada.beyond_autocerrada)
|
||||
|
||||
def test_las_horas_del_dia_son_la_suma_de_los_renglones(self):
|
||||
primera = self._checar(self.emp_c, self.branch_a)['jornada']
|
||||
self._checar(self.emp_c, self.branch_a)
|
||||
segunda = self._checar(self.emp_c, self.branch_a)['jornada']
|
||||
self._checar(self.emp_c, self.branch_a)
|
||||
# Las cuatro checadas caen en el mismo segundo, así que las horas se
|
||||
# fijan aquí para que haya algo que sumar (ADR-016, forma nº 3). La
|
||||
# SEGUNDA se mueve primero: alargar la primera encima de una segunda
|
||||
# que todavía empieza en el mismo segundo es un traslape, y el core
|
||||
# lo rechaza con razón.
|
||||
inicio = primera.check_in
|
||||
segunda.with_context(beyond_sistema=True).write({
|
||||
'check_in': inicio + timedelta(hours=5),
|
||||
'check_out': inicio + timedelta(hours=9)})
|
||||
primera.with_context(beyond_sistema=True).write({
|
||||
'check_out': inicio + timedelta(hours=4)})
|
||||
|
||||
self.emp_c.invalidate_recordset(['beyond_horas_totales'])
|
||||
self.assertAlmostEqual(self.emp_c.beyond_horas_totales, 8.0, places=2)
|
||||
|
||||
def test_sin_entrada_hoy_es_falso_desde_la_primera_entrada(self):
|
||||
self.assertTrue(self.emp_c.beyond_sin_entrada_hoy)
|
||||
self._checar(self.emp_c, self.branch_a)
|
||||
self.emp_c.invalidate_recordset(['beyond_sin_entrada_hoy'])
|
||||
self.assertFalse(self.emp_c.beyond_sin_entrada_hoy)
|
||||
# y sigue siendo falso después de salir a comer
|
||||
self._checar(self.emp_c, self.branch_a)
|
||||
self.emp_c.invalidate_recordset(['beyond_sin_entrada_hoy'])
|
||||
self.assertFalse(self.emp_c.beyond_sin_entrada_hoy,
|
||||
'salir a comer no borra que hoy sí entró')
|
||||
@@ -0,0 +1,249 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
from odoo.exceptions import AccessError
|
||||
from odoo.tests import HttpCase, tagged
|
||||
|
||||
from .common import BeyondChecadorCase
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestBarridoSinSesion(HttpCase):
|
||||
"""Qué puede hacer alguien SIN sesión.
|
||||
|
||||
Es el único módulo del sistema con rutas HTTP públicas, así que la
|
||||
pregunta se contesta con pruebas y no leyendo el código: el kiosco emite
|
||||
tokens y valida checadas, y una tablet en la recepción de un salón está
|
||||
tan expuesta como la calle.
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.branch = self.env['beyond.branch'].create({'name': 'Sucursal Barrido'})
|
||||
icp = self.env['ir.config_parameter'].sudo()
|
||||
icp.set_param('beyond_attendance_qr.ventana_inicio', '00:00')
|
||||
icp.set_param('beyond_attendance_qr.ventana_fin', '23:59')
|
||||
|
||||
def _url(self, sufijo=''):
|
||||
return f'/beyond/kiosco/{self.branch.sudo().kiosk_token}{sufijo}'
|
||||
|
||||
def test_sin_sesion_no_se_registra_una_checada(self):
|
||||
"""Lo único que la ruta pública ofrece es el QR. Registrar exige
|
||||
sesión, y sin ella no puede quedar ni un registro."""
|
||||
datos = self.url_open(self._url('/estado')).json()
|
||||
antes = self.env['beyond.checada'].sudo().search_count([])
|
||||
respuesta = self.url_open(datos['checada_url'], data={'tipo': 'entrada'})
|
||||
self.assertEqual(self.env['beyond.checada'].sudo().search_count([]), antes,
|
||||
'FUGA — se registró una checada sin sesión')
|
||||
self.assertNotIn('Registrada', respuesta.text)
|
||||
|
||||
def test_el_json_publico_no_lleva_datos_de_nadie(self):
|
||||
"""La pantalla del kiosco es pública por diseño: lo que se comprueba
|
||||
es que ahí no viaje nada de una persona. Una tablet en recepción no
|
||||
puede decir quién trabaja hoy."""
|
||||
datos = self.url_open(self._url('/estado')).json()
|
||||
self.assertEqual(
|
||||
set(datos), {'abierto', 'rotacion_seg', 'token', 'checada_url',
|
||||
'qr_img', 'expira_en_seg'},
|
||||
'el estado del kiosco cambió de forma: revisa qué se está publicando')
|
||||
crudo = self.url_open(self._url('/estado')).text
|
||||
for empleado in self.env['hr.employee'].sudo().search([], limit=20):
|
||||
self.assertNotIn(empleado.name, crudo)
|
||||
|
||||
def test_la_pantalla_del_kiosco_no_publica_a_su_gente(self):
|
||||
pagina = self.url_open(self._url()).text
|
||||
for empleado in self.env['hr.employee'].sudo().search([], limit=20):
|
||||
self.assertNotIn(empleado.name, pagina,
|
||||
'FUGA — la pantalla pública nombra a alguien')
|
||||
|
||||
def test_el_kiosco_de_una_sucursal_archivada_deja_de_servir(self):
|
||||
"""Cerrar una plaza tiene que apagar su tablet. Si la URL siguiera
|
||||
emitiendo tokens, una sucursal cerrada seguiría aceptando checadas
|
||||
—y esas horas entrarían en una nómina que ya nadie revisa."""
|
||||
self.assertEqual(self.url_open(self._url()).status_code, 200)
|
||||
self.branch.sudo().action_archive()
|
||||
self.assertEqual(self.url_open(self._url()).status_code, 404,
|
||||
'FUGA — el kiosco de una sucursal archivada sigue vivo')
|
||||
self.assertEqual(self.url_open(self._url('/estado')).status_code, 404)
|
||||
|
||||
def test_regenerar_la_url_del_checador_mata_la_anterior(self):
|
||||
"""El token del kiosco es el único secreto de la ruta pública. Si
|
||||
regenerarlo no invalidara el anterior, la URL filtrada seguiría
|
||||
sirviendo y el botón no serviría de nada."""
|
||||
vieja = self._url()
|
||||
self.assertEqual(self.url_open(vieja).status_code, 200)
|
||||
self.branch.sudo().action_regenerate_kiosk_token()
|
||||
self.assertEqual(self.url_open(vieja).status_code, 404,
|
||||
'FUGA — la URL vieja del checador sigue sirviendo')
|
||||
self.assertEqual(self.url_open(self._url()).status_code, 200,
|
||||
'y la nueva tiene que servir')
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestBarridoPorRpc(BeyondChecadorCase):
|
||||
"""Qué puede hacer por RPC quien SÍ tiene sesión pero no debería.
|
||||
|
||||
El patrón que ADR-015 dejó escrito: un `sudo()` sin guardia es una puerta
|
||||
abierta, y la puerta se prueba empujándola.
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.empleada = self.env['hr.employee']._beyond_alta(
|
||||
'Empleada Barrido', '2229998888', 'clave-barrido-8', self.branch_a)
|
||||
self.usuario = self.empleada.beyond_portal_user_id
|
||||
|
||||
def test_un_empleado_no_forja_una_checada_por_rpc(self):
|
||||
"""Sin token no hay checada. Si un empleado pudiera crear el registro
|
||||
a mano, el QR rotativo entero sobraría."""
|
||||
with self.assertRaises(AccessError):
|
||||
self.env['beyond.checada'].with_user(self.usuario).create({
|
||||
'employee_id': self.empleada.id,
|
||||
'branch_id': self.branch_a.id,
|
||||
'tipo': 'entrada',
|
||||
'origen': 'qr',
|
||||
})
|
||||
|
||||
def test_un_empleado_no_lee_las_checadas_de_nadie(self):
|
||||
"""Ni las ajenas ni las propias: la cuenta del checador es PORTAL y
|
||||
no tiene ACL sobre el modelo. Las suyas las sirve el portal con sudo
|
||||
y acotadas a la sesión, que es lo que hace seguro ese sudo."""
|
||||
checada_ajena = self._checar(self.emp_b, self.branch_b)['checada']
|
||||
with self.assertRaises(AccessError):
|
||||
self.env['beyond.checada'].with_user(self.usuario).search([])
|
||||
with self.assertRaises(AccessError):
|
||||
checada_ajena.with_user(self.usuario).read(['ts'])
|
||||
|
||||
def test_un_empleado_no_lee_las_horas_de_otro(self):
|
||||
"""`beyond_total_horas` es público —se puede llamar por RPC— y suma
|
||||
con sudo. Sin una comprobación de lectura sobre el propio registro,
|
||||
cualquiera con sesión pide el total de cualquier persona."""
|
||||
with self.assertRaises(AccessError):
|
||||
self.emp_b.with_user(self.usuario).beyond_total_horas()
|
||||
|
||||
def test_la_bitacora_no_se_escribe_por_rpc(self):
|
||||
"""La bitácora existe para poder confiar en lo que dice. Si cualquiera
|
||||
con sesión pudiera escribir un renglón, dejaría de servir para eso, y
|
||||
no hace falta poder leerla para poder ensuciarla.
|
||||
|
||||
Se afirma sobre la MISMA puerta que usa el cliente web —el gate de
|
||||
nombres de método de la ORM—, no llamando al método desde Python: en
|
||||
Python un guion bajo no impide nada, y una prueba que lo llamara
|
||||
directo diría que no hay guardia cuando sí la hay.
|
||||
"""
|
||||
from odoo.service.model import get_public_method
|
||||
|
||||
bitacora = self.env['beyond.bitacora']
|
||||
with self.assertRaises(AccessError):
|
||||
get_public_method(bitacora, '_registrar')
|
||||
with self.assertRaises(AttributeError):
|
||||
get_public_method(bitacora, 'registrar')
|
||||
|
||||
# Y la escritura por el camino que sí queda abierto —crear el
|
||||
# registro— la corta el ACL.
|
||||
antes = self.env['beyond.bitacora'].sudo().search_count([])
|
||||
with self.assertRaises(AccessError):
|
||||
self.env['beyond.bitacora'].with_user(self.usuario).create({
|
||||
'accion': 'inventada_por_el_empleado',
|
||||
'entidad': 'hr.employee', 'entidad_id': self.emp_b.id,
|
||||
'actor_id': self.usuario.id,
|
||||
})
|
||||
self.assertEqual(self.env['beyond.bitacora'].sudo().search_count([]), antes,
|
||||
'FUGA — se escribió un renglón de bitácora por RPC')
|
||||
|
||||
def test_un_empleado_no_se_ajusta_las_horas(self):
|
||||
"""Los ajustes suman al total; crearlos es del gerente."""
|
||||
with self.assertRaises(AccessError):
|
||||
self.env['beyond.ajuste'].with_user(self.usuario).create({
|
||||
'employee_id': self.empleada.id,
|
||||
'minutos': 600,
|
||||
'motivo': 'me las pongo yo',
|
||||
})
|
||||
|
||||
def test_un_empleado_no_toca_su_propia_jornada(self):
|
||||
"""Editar tiempos es de su gerente, con bitácora. Si el empleado
|
||||
pudiera escribir su hora de salida, el registro dejaría de ser lo que
|
||||
marcó el QR."""
|
||||
jornada = self._checar(self.empleada, self.branch_a)['jornada']
|
||||
with self.assertRaises(AccessError):
|
||||
jornada.with_user(self.usuario).write(
|
||||
{'check_out': jornada.check_in})
|
||||
|
||||
def test_un_empleado_no_regenera_la_url_del_checador(self):
|
||||
with self.assertRaises(AccessError):
|
||||
self.branch_a.with_user(self.usuario).action_regenerate_kiosk_token()
|
||||
|
||||
def test_un_empleado_no_lee_los_tokens_del_kiosco(self):
|
||||
"""Leer el token vigente sería poder checar desde casa."""
|
||||
self._token(self.branch_a)
|
||||
with self.assertRaises(AccessError):
|
||||
self.env['beyond.checada.token'].with_user(self.usuario).search([])
|
||||
|
||||
def test_un_admin_de_sucursal_no_lee_la_bitacora_de_otra_plaza(self):
|
||||
self.env['beyond.bitacora'].sudo()._registrar(
|
||||
'prueba_barrido', 'beyond.branch', self.branch_b.id,
|
||||
despues={'x': 1}, branch=self.branch_b)
|
||||
ajena = self.env['beyond.bitacora'].sudo().search(
|
||||
[('accion', '=', 'prueba_barrido')], limit=1)
|
||||
visibles = self.env['beyond.bitacora'].with_user(self.admin_a).search([])
|
||||
self.assertNotIn(ajena.id, visibles.ids,
|
||||
'FUGA — la bitácora de otra sucursal se lee')
|
||||
|
||||
def test_un_admin_de_sucursal_no_cambia_la_configuracion_del_checador(self):
|
||||
"""La ventana y la rotación gobiernan a toda la red: mover el cierre
|
||||
cambia a qué hora se autocierran las jornadas de TODAS las plazas."""
|
||||
with self.assertRaises(AccessError):
|
||||
self.env['beyond.checador.config'].with_user(self.admin_a).create({
|
||||
'ventana_inicio': '00:00', 'ventana_fin': '23:59',
|
||||
'qr_rotacion_seg': 45,
|
||||
})
|
||||
|
||||
def test_un_empleado_no_le_cambia_la_clave_a_otro(self):
|
||||
"""El asistente de contraseña es del gerente. Por RPC, un empleado no
|
||||
puede ni instanciarlo."""
|
||||
with self.assertRaises(AccessError):
|
||||
self.env['beyond.employee.password'].with_user(self.usuario).create({
|
||||
'employee_id': self.emp_b.id,
|
||||
})
|
||||
|
||||
# ── Las acciones de consecuencia alta, entre sucursales ─────────────
|
||||
def test_un_admin_no_restablece_la_clave_de_otra_plaza(self):
|
||||
"""Es la más grave del módulo: quien fija la contraseña de alguien
|
||||
puede entrar como esa persona y checar por ella. Cruzar de sucursal
|
||||
aquí sería poder inventar la asistencia de una plaza ajena."""
|
||||
ajena = self.env['hr.employee']._beyond_alta(
|
||||
'Empleada De B', '2227776666', 'clave-de-b-88', self.branch_b)
|
||||
asistente = self.env['beyond.employee.password'].with_user(
|
||||
self.admin_a).create({'employee_id': ajena.id,
|
||||
'password': 'nueva-clave-8'})
|
||||
with self.assertRaises(AccessError):
|
||||
asistente.action_apply()
|
||||
|
||||
def test_un_admin_si_restablece_la_de_su_gente(self):
|
||||
"""La gemela: si el candado cortara siempre, la prueba de arriba
|
||||
pasaría igual y el asistente estaría roto sin que nadie se enterara
|
||||
(ADR-016, séptima forma)."""
|
||||
propia = self.env['hr.employee']._beyond_alta(
|
||||
'Empleada De A', '2226665555', 'clave-de-a-88', self.branch_a)
|
||||
self.env['beyond.employee.password'].with_user(self.admin_a).create({
|
||||
'employee_id': propia.id, 'password': 'nueva-clave-8',
|
||||
}).action_apply()
|
||||
self.assertTrue(propia.beyond_portal_user_id.sudo().beyond_clave_temporal,
|
||||
'la clave que fija otra persona nace temporal')
|
||||
|
||||
def test_un_admin_no_da_de_baja_a_alguien_de_otra_plaza(self):
|
||||
ajena = self.env['hr.employee']._beyond_alta(
|
||||
'Otra De B', '2225554443', 'clave-otra-b-8', self.branch_b)
|
||||
with self.assertRaises(AccessError):
|
||||
ajena.with_user(self.admin_a).action_beyond_baja()
|
||||
self.assertEqual(ajena.sudo().beyond_cuenta_estado, 'activo')
|
||||
|
||||
def test_un_admin_no_resuelve_una_solicitud_de_otra_plaza(self):
|
||||
"""El modelo se conserva por el historial (ADR-018) y sus acciones
|
||||
siguen siendo públicas: mientras existan, tienen que seguir acotadas."""
|
||||
jornada = self._checar(self.emp_b, self.branch_b)['jornada']
|
||||
solicitud = self.env['beyond.solicitud'].sudo().create({
|
||||
'employee_id': self.emp_b.id,
|
||||
'tipo': 'autorizar_autocierre',
|
||||
'jornada_id': jornada.id,
|
||||
})
|
||||
with self.assertRaises(AccessError):
|
||||
solicitud.with_user(self.admin_a).action_rechazar()
|
||||
@@ -13,65 +13,6 @@ NOCHE_LOCAL = datetime(2026, 8, 11, 4, 0, 0)
|
||||
MEDIODIA_LOCAL = datetime(2026, 8, 10, 18, 0, 0)
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestBeyondAutoCierre(BeyondChecadorCase):
|
||||
"""C-013: la jornada sin salida al cierre de la ventana pasa a revision
|
||||
(no suma) y espera autorización en la cola."""
|
||||
|
||||
def test_auto_cierre_fuera_de_ventana(self):
|
||||
base = self.emp_a.beyond_total_horas()
|
||||
jornada = self._checar(self.emp_a, self.branch_a)['jornada']
|
||||
cerradas = self.Attendance._beyond_cron_auto_cierre(ahora=NOCHE_LOCAL)
|
||||
self.assertEqual(cerradas, 1)
|
||||
self.assertEqual(jornada.beyond_estado, 'revision')
|
||||
self.assertFalse(jornada.check_out, "la salida real la fija el supervisor")
|
||||
solicitud = self.env['beyond.solicitud'].sudo().search(
|
||||
[('jornada_id', '=', jornada.id)])
|
||||
self.assertEqual(solicitud.tipo, 'autorizar_autocierre')
|
||||
self.assertEqual(solicitud.estado, 'pendiente')
|
||||
self.assertAlmostEqual(self.emp_a.beyond_total_horas(), base, places=2,
|
||||
msg="en revision no suma nada")
|
||||
# y el ciclo completo: el supervisor fija la salida y entonces sí suma
|
||||
solicitud.resolucion_salida_ts = jornada.check_in + timedelta(hours=6)
|
||||
solicitud.with_user(self.admin_a).action_autorizar()
|
||||
self.assertAlmostEqual(self.emp_a.beyond_total_horas(), base + 6.0, places=2)
|
||||
|
||||
def test_dentro_de_ventana_no_toca_nada(self):
|
||||
jornada = self._checar(self.emp_a, self.branch_a)['jornada']
|
||||
cerradas = self.Attendance._beyond_cron_auto_cierre(ahora=MEDIODIA_LOCAL)
|
||||
self.assertEqual(cerradas, 0)
|
||||
self.assertEqual(jornada.beyond_estado, 'abierta')
|
||||
|
||||
def test_idempotente_sin_solicitudes_duplicadas(self):
|
||||
jornada = self._checar(self.emp_a, self.branch_a)['jornada']
|
||||
self.Attendance._beyond_cron_auto_cierre(ahora=NOCHE_LOCAL)
|
||||
self.Attendance._beyond_cron_auto_cierre(ahora=NOCHE_LOCAL)
|
||||
self.assertEqual(self.env['beyond.solicitud'].sudo().search_count(
|
||||
[('jornada_id', '=', jornada.id)]), 1)
|
||||
|
||||
def test_cron_registrado(self):
|
||||
cron = self.env.ref('beyond_attendance_qr.cron_auto_cierre')
|
||||
self.assertTrue(cron.active)
|
||||
self.assertEqual((cron.interval_number, cron.interval_type), (5, 'minutes'))
|
||||
|
||||
def test_limpieza_de_tokens(self):
|
||||
Token = self.env['beyond.checada.token'].sudo()
|
||||
viejo = fields.Datetime.now() - timedelta(days=2)
|
||||
sin_uso = Token.create({'token': uuid.uuid4().hex, 'branch_id': self.branch_a.id,
|
||||
'ventana_ts': viejo, 'expira_ts': viejo})
|
||||
usado = self._token(self.branch_a)
|
||||
self._checar(self.emp_a, self.branch_a, token=usado)
|
||||
Token.env.cr.execute( # envejecer el usado sin pasar por el ORM del token
|
||||
"UPDATE beyond_checada_token SET expira_ts = %s WHERE id = %s",
|
||||
[viejo, usado.id])
|
||||
usado.invalidate_recordset()
|
||||
vigente = self._token(self.branch_b)
|
||||
Token._limpiar_vencidos()
|
||||
self.assertFalse(sin_uso.exists(), "vencido sin uso: se borra")
|
||||
self.assertTrue(usado.exists(), "respaldó una checada: se conserva")
|
||||
self.assertTrue(vigente.exists())
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestBeyondPuentePin(BeyondChecadorCase):
|
||||
"""C-012 respaldo: el PIN del kiosco nativo genera la misma checada
|
||||
@@ -99,9 +40,9 @@ class TestBeyondPuentePin(BeyondChecadorCase):
|
||||
|
||||
def test_pin_exige_cuenta_activa(self):
|
||||
pendiente = self.env['hr.employee']._beyond_alta(
|
||||
'Pin Pendiente', '2221112222', 'clave-segura-8', self.branch_a)
|
||||
pendiente.sudo().beyond_cuenta_estado = 'pendiente'
|
||||
'Pin De Baja', '2221112222', 'clave-segura-8', self.branch_a)
|
||||
pendiente.sudo().action_beyond_baja()
|
||||
with self.assertRaises(ValidationError):
|
||||
pendiente._attendance_action_change()
|
||||
pendiente.sudo()._attendance_action_change()
|
||||
|
||||
|
||||
@@ -93,17 +93,31 @@ class TestBeyondChecadaHttp(HttpCase):
|
||||
self.assertIn('ya venció', r.text,
|
||||
"una foto del QR de hace rato no sirve")
|
||||
|
||||
def test_pendiente_no_registra_por_web(self):
|
||||
"""Las cuentas heredadas en 'pendiente' —el alta nueva ya nace
|
||||
activa— siguen sin poder checar por la web."""
|
||||
pendiente = self.env['hr.employee']._beyond_alta(
|
||||
'Emp Pendiente', '2225554444', 'clave-pend-8', self.branch)
|
||||
pendiente.sudo().beyond_cuenta_estado = 'pendiente'
|
||||
pendiente.beyond_portal_user_id.sudo().beyond_clave_temporal = False
|
||||
def test_una_cuenta_dada_de_baja_no_registra_por_web(self):
|
||||
"""El candado sigue donde estaba; lo que cambió es el estado que lo
|
||||
activa: 'pendiente' se retiró y ahora la cuenta que no checa es la
|
||||
que se dio de baja.
|
||||
|
||||
Se archiva la FICHA y se deja viva la cuenta a propósito: si además
|
||||
se desactivara el usuario —lo que hace «Dar de baja» completo— no
|
||||
podría ni iniciar sesión y el candado no llegaría a ejercitarse.
|
||||
Archivar desde el engranaje nativo produce exactamente este estado, y
|
||||
es el camino por el que la ficha y la cuenta podrían separarse.
|
||||
|
||||
Lo que se afirma es el resultado: la página ya no ofrece el botón de
|
||||
checar y no queda ninguna checada. El mensaje del candado se afirma
|
||||
sobre el modelo, en test_cuentas, que es donde se lee entero.
|
||||
"""
|
||||
de_baja = self.env['hr.employee']._beyond_alta(
|
||||
'Emp De Baja', '2225554444', 'clave-pend-8', self.branch)
|
||||
de_baja.beyond_portal_user_id.sudo().beyond_clave_temporal = False
|
||||
de_baja.sudo().action_archive()
|
||||
self.assertEqual(de_baja.sudo().beyond_cuenta_estado, 'baja')
|
||||
|
||||
self.authenticate('2225554444', 'clave-pend-8')
|
||||
token = self._token_nuevo()
|
||||
pagina = self.url_open(f'/beyond/checada/{token.token}')
|
||||
respuesta = self._post(token, pagina, 'entrada')
|
||||
self.assertIn('pendiente de aprobación', respuesta.text)
|
||||
self.assertNotIn('name="tipo"', pagina.text,
|
||||
'la página no puede ofrecer el botón de checar')
|
||||
self.assertFalse(self.env['beyond.checada'].search_count(
|
||||
[('token_id', '=', token.id)]), "pendiente no registra nada")
|
||||
[('token_id', '=', token.id)]), 'y no queda ninguna checada')
|
||||
@@ -42,16 +42,18 @@ class TestBeyondCuentas(BeyondChecadorCase):
|
||||
self.env['hr.employee']._beyond_alta(
|
||||
'X', '2229990002', 'corta', self.branch_a)
|
||||
|
||||
def test_una_cuenta_no_activa_no_checa(self):
|
||||
"""El candado sobrevive al retiro del auto-registro: las cuentas
|
||||
heredadas en 'pendiente' siguen sin poder checar hasta activarse."""
|
||||
def test_una_cuenta_dada_de_baja_no_checa_y_al_reincorporar_si(self):
|
||||
"""El candado sobrevive al rediseño; lo que cambió es qué lo activa.
|
||||
Y la vuelta importa igual: reincorporar a alguien va a pasar."""
|
||||
empleada = self._registrar_cuenta()
|
||||
empleada.sudo().beyond_cuenta_estado = 'pendiente'
|
||||
with self.assertRaises(ValidationError, msg="pendiente no checa"):
|
||||
self._checar(empleada, self.branch_a)
|
||||
self.assertAlmostEqual(empleada.beyond_total_horas(), 0.0)
|
||||
empleada.with_user(self.admin_a).action_beyond_aprobar()
|
||||
self.assertEqual(empleada.beyond_cuenta_estado, 'activo')
|
||||
empleada.sudo().action_beyond_baja()
|
||||
self.assertEqual(empleada.sudo().beyond_cuenta_estado, 'baja')
|
||||
with self.assertRaises(ValidationError, msg="dada de baja no checa"):
|
||||
self._checar(empleada.sudo(), self.branch_a)
|
||||
self.assertAlmostEqual(empleada.sudo().beyond_total_horas(), 0.0)
|
||||
empleada.sudo().action_beyond_reincorporar()
|
||||
self.assertEqual(empleada.sudo().beyond_cuenta_estado, 'activo')
|
||||
empleada = empleada.sudo()
|
||||
resultado = self._checar(empleada, self.branch_a)
|
||||
self.assertEqual(resultado['tipo'], 'entrada', "activa: ya checa")
|
||||
|
||||
|
||||
@@ -0,0 +1,422 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
from datetime import date, datetime, time, timedelta
|
||||
|
||||
from odoo import fields
|
||||
from odoo.tests import tagged
|
||||
|
||||
from .common import BeyondChecadorCase
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestBeyondEquipoDatos(BeyondChecadorCase):
|
||||
"""Lo que la pantalla de Equipo recibe del servidor.
|
||||
|
||||
Es un método público por RPC, así que el aislamiento se afirma aquí y no
|
||||
en la pantalla: a un admin de sucursal no le puede VIAJAR la gente de
|
||||
otra plaza, ni sus horas, ni sus ventas. Y se afirma con horas y ventas
|
||||
REALES en las dos sucursales: si las dos estuvieran en cero, los dos
|
||||
roles verían lo mismo —nada— y la prueba pasaría sin haber probado el
|
||||
aislamiento (ADR-016, forma nº 3).
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
cls.env['ir.config_parameter'].sudo().set_param(
|
||||
'beyond_attendance_qr.horas_semana', '40')
|
||||
cls.servicio = cls.env['product.product'].create({
|
||||
'name': 'Servicio de equipo', 'type': 'service',
|
||||
'available_in_pos': True, 'list_price': 500.0,
|
||||
})
|
||||
# Las cajas ya las abre el common de la Fase 1: abrir otra para la
|
||||
# misma configuración es un error del core, no del test.
|
||||
cls.caja_a, cls.caja_b = cls.session_a, cls.session_b
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
# Personas SIN historial: emp_a y emp_b arrastran la jornada de ayer
|
||||
# del common, y ayer cae fuera de la semana si hoy es lunes. Una
|
||||
# prueba que dependa del día en que se corre no prueba nada.
|
||||
self.persona_a = self.env['hr.employee'].create({
|
||||
'name': 'Persona Equipo A', 'branch_id': self.branch_a.id,
|
||||
'department_id': self.branch_a.department_id.id})
|
||||
self.persona_b = self.env['hr.employee'].create({
|
||||
'name': 'Persona Equipo B', 'branch_id': self.branch_b.id,
|
||||
'department_id': self.branch_b.department_id.id})
|
||||
# Horas de esta semana en las dos plazas, distintas entre sí.
|
||||
self._jornada(self.persona_a, horas=6.0)
|
||||
self._jornada(self.persona_b, horas=9.0)
|
||||
# Y ventas del periodo, también en las dos, para que haya algo real
|
||||
# que sumar y confundir una plaza con otra tenga consecuencia.
|
||||
self._venta(self.caja_a, 500.0, self.persona_a)
|
||||
self._venta(self.caja_b, 800.0, self.persona_b)
|
||||
|
||||
def _jornada(self, employee, horas, dias_atras=0, hora=6):
|
||||
"""Una jornada en una HORA concreta del día, no «hace tantas horas».
|
||||
|
||||
Odoo rechaza jornadas traslapadas de la misma persona —con razón—,
|
||||
así que si cada prueba cuenta hacia atrás desde ahora, la segunda
|
||||
choca con la primera. Fijando la hora de entrada, cada una se pone
|
||||
en su hueco y el traslape deja de ser una carrera contra el reloj.
|
||||
"""
|
||||
dia = fields.Datetime.now().date() - timedelta(days=dias_atras)
|
||||
entrada = datetime.combine(dia, time(hour=hora))
|
||||
return self.Attendance.sudo().with_context(beyond_sistema=True).create({
|
||||
'employee_id': employee.id,
|
||||
'check_in': entrada,
|
||||
'check_out': entrada + timedelta(hours=horas),
|
||||
'beyond_estado': 'cerrada',
|
||||
})
|
||||
|
||||
def _venta(self, caja, precio, empleado):
|
||||
orden = self.env['pos.order'].sudo().create({
|
||||
'name': f'Orden equipo {caja.id} {precio}',
|
||||
'session_id': caja.id, 'company_id': caja.company_id.id,
|
||||
'amount_tax': 0.0, 'amount_total': precio,
|
||||
'amount_paid': precio, 'amount_return': 0.0,
|
||||
})
|
||||
orden.write({'state': 'paid'})
|
||||
self.env['pos.order.line'].sudo().create({
|
||||
'order_id': orden.id, 'product_id': self.servicio.id, 'qty': 1,
|
||||
'price_unit': precio, 'price_subtotal': precio,
|
||||
'price_subtotal_incl': precio,
|
||||
'beyond_empleado_ids': [(6, 0, empleado.ids)],
|
||||
})
|
||||
return orden
|
||||
|
||||
def _datos(self, user, **kw):
|
||||
return self.env['hr.employee'].with_user(user).beyond_equipo_datos(
|
||||
kw.pop('periodo', 'semana'), kw.pop('desde', False),
|
||||
kw.pop('hasta', False), kw.pop('branch_ids', False),
|
||||
kw.pop('filtro', 'todos'), kw.pop('busqueda', ''))
|
||||
|
||||
# ── Aislamiento ────────────────────────────────────────────────────
|
||||
def test_al_admin_de_sucursal_no_le_viaja_la_gente_de_otra_plaza(self):
|
||||
datos = self._datos(self.admin_a)
|
||||
ids = [p['id'] for p in datos['personas']]
|
||||
self.assertIn(self.emp_a.id, ids, 'la suya sí')
|
||||
self.assertNotIn(self.emp_b.id, ids, 'FUGA — se ve gente de otra plaza')
|
||||
crudo = str(datos)
|
||||
self.assertNotIn(self.emp_b.name, crudo)
|
||||
self.assertNotIn(self.branch_b.name, crudo,
|
||||
'FUGA — hasta el nombre de la otra sucursal viaja')
|
||||
|
||||
def test_el_admin_general_ve_a_los_dos(self):
|
||||
"""La gemela: sin ella, un método que devolviera siempre la lista
|
||||
vacía pasaría la prueba de arriba (ADR-016, séptima forma)."""
|
||||
ids = [p['id'] for p in self._datos(self.admin_general)['personas']]
|
||||
self.assertIn(self.emp_a.id, ids)
|
||||
self.assertIn(self.emp_b.id, ids)
|
||||
|
||||
def test_las_horas_son_las_de_cada_quien(self):
|
||||
por_id = {p['id']: p for p in self._datos(self.admin_general)['personas']}
|
||||
self.assertAlmostEqual(por_id[self.persona_a.id]['horas'], 6.0, places=1)
|
||||
self.assertAlmostEqual(por_id[self.persona_b.id]['horas'], 9.0, places=1)
|
||||
|
||||
def test_los_chips_de_sucursal_son_solo_del_admin_general(self):
|
||||
general = self._datos(self.admin_general)
|
||||
self.assertTrue(general['es_admin_general'])
|
||||
self.assertGreaterEqual(len(general['sucursales']), 2)
|
||||
propio = self._datos(self.admin_a)
|
||||
self.assertFalse(propio['es_admin_general'])
|
||||
self.assertEqual([s['id'] for s in propio['sucursales']], [self.branch_a.id],
|
||||
'y si vinieran, solo las suyas')
|
||||
|
||||
# ── Periodo ────────────────────────────────────────────────────────
|
||||
def test_la_semana_empieza_en_lunes(self):
|
||||
datos = self._datos(self.admin_general, periodo='semana')
|
||||
desde = fields.Date.to_date(datos['periodo']['desde'])
|
||||
self.assertEqual(desde.weekday(), 0, 'lunes')
|
||||
self.assertLessEqual(desde, date.today())
|
||||
|
||||
def test_el_titulo_de_la_columna_sigue_al_periodo(self):
|
||||
"""El mock lo pide explícito: la columna no dice «semanal» fijo."""
|
||||
titulos = {p: self._datos(self.admin_general, periodo=p)['periodo']['titulo']
|
||||
for p in ('hoy', 'semana', 'mes', 'ano')}
|
||||
self.assertEqual(len(set(titulos.values())), 4,
|
||||
f'los cuatro periodos deben titularse distinto: {titulos}')
|
||||
|
||||
def test_el_periodo_acota_las_horas(self):
|
||||
"""Una jornada de hace dos meses no entra en la semana y sí en el año."""
|
||||
self._jornada(self.persona_a, horas=5.0, dias_atras=60)
|
||||
semana = {p['id']: p for p in self._datos(
|
||||
self.admin_general, periodo='semana')['personas']}
|
||||
ano = {p['id']: p for p in self._datos(
|
||||
self.admin_general, periodo='ano')['personas']}
|
||||
self.assertAlmostEqual(semana[self.persona_a.id]['horas'], 6.0, places=1)
|
||||
self.assertAlmostEqual(ano[self.persona_a.id]['horas'], 11.0, places=1)
|
||||
|
||||
def test_un_rango_a_mano_manda_sobre_el_periodo(self):
|
||||
ayer = fields.Date.to_string(date.today() - timedelta(days=1))
|
||||
manana = fields.Date.to_string(date.today() + timedelta(days=1))
|
||||
datos = self._datos(self.admin_general, periodo='rango',
|
||||
desde=ayer, hasta=manana)
|
||||
self.assertEqual(datos['periodo']['desde'], ayer)
|
||||
self.assertEqual(datos['periodo']['hasta'], manana)
|
||||
|
||||
# ── Filtros y estado del día ───────────────────────────────────────
|
||||
def test_los_filtros_traen_su_contador(self):
|
||||
datos = self._datos(self.admin_general)
|
||||
for clave in ('todos', 'trabajando', 'sin_entrada'):
|
||||
self.assertIn(clave, datos['filtros'])
|
||||
self.assertEqual(datos['filtros']['todos'], len(datos['personas']))
|
||||
|
||||
def test_quien_esta_trabajando_ahora_sale_marcado_y_filtrable(self):
|
||||
self.Attendance.sudo().with_context(beyond_sistema=True).create({
|
||||
'employee_id': self.emp_c.id, 'check_in': fields.Datetime.now()})
|
||||
datos = self._datos(self.admin_general)
|
||||
por_id = {p['id']: p for p in datos['personas']}
|
||||
self.assertEqual(por_id[self.emp_c.id]['estado'], 'trabajando')
|
||||
self.assertGreaterEqual(datos['filtros']['trabajando'], 1)
|
||||
|
||||
solo = self._datos(self.admin_general, filtro='trabajando')
|
||||
self.assertTrue(solo['personas'])
|
||||
self.assertTrue(all(p['estado'] == 'trabajando' for p in solo['personas']))
|
||||
|
||||
def test_quien_no_ha_entrado_hoy_tambien(self):
|
||||
datos = self._datos(self.admin_general, filtro='sin_entrada')
|
||||
self.assertTrue(all(p['estado'] == 'sin_entrada' for p in datos['personas']))
|
||||
|
||||
def test_la_busqueda_acota_por_nombre_y_por_celular(self):
|
||||
self.persona_a.sudo().write({'beyond_celular': '2224443333'})
|
||||
por_nombre = self._datos(self.admin_general, busqueda='Persona Equipo A')
|
||||
self.assertEqual([p['id'] for p in por_nombre['personas']], [self.persona_a.id])
|
||||
por_celular = self._datos(self.admin_general, busqueda='4443333')
|
||||
self.assertIn(self.persona_a.id, [p['id'] for p in por_celular['personas']])
|
||||
|
||||
# ── La meta ────────────────────────────────────────────────────────
|
||||
def test_la_meta_sale_de_la_configuracion(self):
|
||||
self.assertEqual(self._datos(self.admin_general)['meta'], 40)
|
||||
self.env['ir.config_parameter'].sudo().set_param(
|
||||
'beyond_attendance_qr.horas_semana', '35')
|
||||
self.assertEqual(self._datos(self.admin_general)['meta'], 35,
|
||||
'la meta es configurable, no está en duro')
|
||||
|
||||
def test_pasarse_de_la_meta_se_dice_y_no_se_dibuja_lleno(self):
|
||||
self._jornada(self.emp_c, horas=45.0, hora=1)
|
||||
persona = {p['id']: p for p in self._datos(
|
||||
self.admin_general)['personas']}[self.emp_c.id]
|
||||
self.assertTrue(persona['sobre_meta'])
|
||||
self.assertGreater(persona['horas'], persona['meta'])
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestBeyondResumenEquipo(TestBeyondEquipoDatos):
|
||||
"""El bloque «Horas y productividad» del encabezado."""
|
||||
|
||||
def _resumen(self, user, **kw):
|
||||
return self.env['hr.employee'].with_user(user).beyond_resumen_equipo(
|
||||
kw.pop('periodo', 'semana'), kw.pop('desde', False),
|
||||
kw.pop('hasta', False))
|
||||
|
||||
def test_el_resumen_de_un_gerente_es_solo_de_su_plaza(self):
|
||||
resumen = self._resumen(self.admin_a)
|
||||
plazas = [f['branch_id'] for f in resumen['sucursales']]
|
||||
self.assertEqual(plazas, [self.branch_a.id],
|
||||
'FUGA — el resumen trae otra sucursal')
|
||||
self.assertNotIn(self.branch_b.name, str(resumen))
|
||||
self.assertFalse(resumen['organizacion'],
|
||||
'el total de la red es de la dirección')
|
||||
|
||||
def test_el_de_la_direccion_trae_la_organizacion_y_las_plazas(self):
|
||||
resumen = self._resumen(self.admin_general)
|
||||
self.assertTrue(resumen['organizacion'])
|
||||
self.assertGreaterEqual(len(resumen['sucursales']), 2)
|
||||
|
||||
def test_las_ventas_del_periodo_son_reales_y_por_plaza(self):
|
||||
"""Se mide el DELTA de una venta nueva y no el total: la base de
|
||||
pruebas trae ventas demo, y afirmar un absoluto sería atarse a
|
||||
cuántas traiga hoy."""
|
||||
antes = {f['branch_id']: f['ventas'] for f in
|
||||
self._resumen(self.admin_general)['sucursales']}
|
||||
self._venta(self.caja_a, 350.0, self.persona_a)
|
||||
despues = {f['branch_id']: f['ventas'] for f in
|
||||
self._resumen(self.admin_general)['sucursales']}
|
||||
self.assertAlmostEqual(
|
||||
despues[self.branch_a.id] - antes[self.branch_a.id], 350.0, places=2)
|
||||
self.assertAlmostEqual(
|
||||
despues[self.branch_b.id] - antes[self.branch_b.id], 0.0, places=2,
|
||||
msg='la venta de una plaza no puede aparecer en la otra')
|
||||
|
||||
def test_las_ventas_por_hora_cuadran_con_lo_que_se_sumo(self):
|
||||
plaza = {f['branch_id']: f for f in
|
||||
self._resumen(self.admin_general)['sucursales']}[self.branch_a.id]
|
||||
self.assertGreater(plaza['horas'], 0, 'sin horas no hay razón que valga')
|
||||
self.assertAlmostEqual(plaza['ventas_por_hora'],
|
||||
plaza['ventas'] / plaza['horas'], places=2)
|
||||
|
||||
def test_la_meta_del_resumen_es_por_persona(self):
|
||||
plaza = {f['branch_id']: f for f in
|
||||
self._resumen(self.admin_general)['sucursales']}[self.branch_a.id]
|
||||
self.assertEqual(plaza['meta'], plaza['personas'] * 40)
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestBeyondCelularDisponible(BeyondChecadorCase):
|
||||
"""El aviso de celular repetido, antes de guardar."""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.ocupada = self.env['hr.employee']._beyond_alta(
|
||||
'Ocupada De A', '2223334444', 'clave-ocupada-8', self.branch_a)
|
||||
self.ajena = self.env['hr.employee']._beyond_alta(
|
||||
'Ajena De B', '2225556666', 'clave-ajena-88', self.branch_b)
|
||||
|
||||
def _consulta(self, user, celular):
|
||||
return self.env['hr.employee'].with_user(user).beyond_celular_disponible(celular)
|
||||
|
||||
def test_un_celular_libre_esta_libre(self):
|
||||
self.assertTrue(self._consulta(self.admin_a, '2229990000')['disponible'])
|
||||
|
||||
def test_uno_ocupado_avisa_y_dice_de_quien(self):
|
||||
respuesta = self._consulta(self.admin_a, '2223334444')
|
||||
self.assertFalse(respuesta['disponible'])
|
||||
self.assertIn('Ocupada De A', respuesta['mensaje'])
|
||||
|
||||
def test_el_numero_se_compara_normalizado(self):
|
||||
"""El celular se guarda en dígitos: si la comparación no normalizara,
|
||||
el mismo número escrito con guiones pasaría por libre y el alta
|
||||
tronaría al guardar, que es justo lo que este aviso evita."""
|
||||
self.assertFalse(self._consulta(self.admin_a, '222-333-4444')['disponible'])
|
||||
|
||||
def test_un_celular_de_otra_plaza_avisa_pero_no_dice_quien(self):
|
||||
"""Está ocupado y hay que decirlo —si no, el alta truena al guardar—,
|
||||
pero un gerente no tiene por qué enterarse de quién trabaja en otra
|
||||
sucursal. El aviso existe para no chocar, no para informar."""
|
||||
respuesta = self._consulta(self.admin_a, '2225556666')
|
||||
self.assertFalse(respuesta['disponible'])
|
||||
self.assertNotIn('Ajena De B', respuesta['mensaje'],
|
||||
'FUGA — el aviso nombra a alguien de otra plaza')
|
||||
|
||||
def test_la_direccion_si_ve_de_quien_es(self):
|
||||
respuesta = self._consulta(self.admin_general, '2225556666')
|
||||
self.assertFalse(respuesta['disponible'])
|
||||
self.assertIn('Ajena De B', respuesta['mensaje'])
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestBeyondFichaDatos(TestBeyondEquipoDatos):
|
||||
"""Lo que la ficha de una persona pide al servidor: avance,
|
||||
productividad y sus jornadas."""
|
||||
|
||||
def _ficha(self, user, employee, periodo='semana'):
|
||||
return self.env['hr.employee'].with_user(user).beyond_ficha_datos(
|
||||
employee.id, periodo)
|
||||
|
||||
def test_un_gerente_no_abre_la_ficha_de_otra_plaza(self):
|
||||
"""El método es público por RPC: pedir la ficha por id es lo primero
|
||||
que alguien intentaría."""
|
||||
from odoo.exceptions import AccessError
|
||||
with self.assertRaises(AccessError):
|
||||
self._ficha(self.admin_a, self.persona_b)
|
||||
|
||||
def test_la_de_su_gente_si_se_abre(self):
|
||||
"""La gemela: si cortara siempre, la de arriba pasaría igual."""
|
||||
ficha = self._ficha(self.admin_a, self.persona_a)
|
||||
self.assertAlmostEqual(ficha['avance']['horas'], 6.0, places=1)
|
||||
self.assertEqual(ficha['avance']['meta'], 40)
|
||||
|
||||
def test_las_jornadas_vienen_una_por_par_y_con_su_estado(self):
|
||||
cerrada = self._jornada(self.persona_a, horas=3.0, hora=16)
|
||||
cerrada.sudo().write({'beyond_autocerrada': True})
|
||||
ficha = self._ficha(self.admin_general, self.persona_a)
|
||||
estados = {j['estado'] for j in ficha['jornadas']}
|
||||
self.assertIn('cierre_automatico', estados,
|
||||
'el cierre automático se distingue de un cierre normal')
|
||||
self.assertTrue(all(j['entrada'] for j in ficha['jornadas']))
|
||||
|
||||
def test_la_etiqueta_del_dia_solo_va_en_el_primer_renglon(self):
|
||||
"""Salir a comer parte el día en dos renglones; repetir la fecha en
|
||||
los dos hace pensar que son dos días."""
|
||||
# Dos renglones del MISMO día, después de la jornada de setUp.
|
||||
self._jornada(self.persona_a, horas=2.0, hora=14)
|
||||
self._jornada(self.persona_a, horas=2.0, hora=17)
|
||||
ficha = self._ficha(self.admin_general, self.persona_a)
|
||||
del_dia = [j for j in ficha['jornadas'] if j['dia'] == ficha['jornadas'][0]['dia']]
|
||||
self.assertGreaterEqual(len(del_dia), 2, 'hacen falta dos renglones del mismo día')
|
||||
self.assertTrue(del_dia[0]['etiqueta_dia'])
|
||||
self.assertFalse(del_dia[1]['etiqueta_dia'],
|
||||
'el segundo renglón del día no repite la fecha')
|
||||
|
||||
def test_el_acumulado_es_una_suma_corrida(self):
|
||||
ficha = self._ficha(self.admin_general, self.persona_a)
|
||||
corrido = 0.0
|
||||
for jornada in reversed(ficha['jornadas']):
|
||||
corrido += jornada['horas']
|
||||
self.assertAlmostEqual(jornada['acumulado'], round(corrido, 2), places=2)
|
||||
|
||||
def test_la_productividad_sale_del_mismo_reporte_que_ve_el_gerente(self):
|
||||
ficha = self._ficha(self.admin_general, self.persona_a)
|
||||
self.assertAlmostEqual(ficha['productividad']['ventas'], 500.0, places=2)
|
||||
self.assertGreater(ficha['productividad']['ventas_por_hora'], 0)
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestBeyondNivelDeAcceso(BeyondChecadorCase):
|
||||
"""Solo hay UNA dirección y ya existe (decisión del cliente, 25-ago-2026).
|
||||
|
||||
La interfaz ofrece dos niveles —Colaborador y Administrador de
|
||||
sucursal—, y quien los cambia es la dirección. Las dos mitades se
|
||||
afirman: que no se ofrezca, y que tampoco se pueda por RPC, que es por
|
||||
donde daría igual lo que ofrezca la pantalla.
|
||||
"""
|
||||
|
||||
def test_la_interfaz_ofrece_dos_niveles_y_no_el_de_direccion(self):
|
||||
empleado = self.env['hr.employee'].create({
|
||||
'name': 'Nivel de prueba', 'branch_id': self.branch_a.id,
|
||||
'department_id': self.branch_a.department_id.id})
|
||||
ofrecidos = empleado.beyond_acceso_ofrecido
|
||||
self.assertIn('checador', ofrecidos)
|
||||
self.assertIn('admin_sucursal', ofrecidos)
|
||||
self.assertNotIn('admin_general', ofrecidos,
|
||||
'la dirección no se otorga desde la interfaz')
|
||||
|
||||
def test_a_quien_ya_es_direccion_se_le_sigue_viendo_su_nivel(self):
|
||||
"""La gemela: esconder la opción no puede esconder el dato. Si a la
|
||||
ficha del director le desapareciera su propio nivel, la pantalla
|
||||
estaría mintiendo sobre lo que hay."""
|
||||
# Con cuenta: dar acceso al sistema exige una, y sin ella el propio
|
||||
# guardia corta antes de llegar a lo que aquí se mira.
|
||||
director = self.env['hr.employee']._beyond_alta(
|
||||
'Dirección de prueba', '2224446666', 'clave-direccion-8', self.branch_a)
|
||||
director.sudo().beyond_acceso = 'admin_general'
|
||||
self.assertIn('admin_general', director.beyond_acceso_ofrecido,
|
||||
'su nivel actual se sigue viendo en su propia ficha')
|
||||
|
||||
def test_un_admin_de_sucursal_no_promueve_a_nadie_por_rpc(self):
|
||||
"""Lo que de verdad cierra la puerta: la pantalla puede ofrecer lo
|
||||
que sea, pero por RPC se escribe el campo directamente."""
|
||||
empleado = self.env['hr.employee'].create({
|
||||
'name': 'Ascenso por RPC', 'branch_id': self.branch_a.id,
|
||||
'department_id': self.branch_a.department_id.id})
|
||||
for nivel in ('admin_sucursal', 'admin_general'):
|
||||
with self.subTest(nivel=nivel):
|
||||
# Puede cortar el guardia del modelo (UserError) o la ir.rule
|
||||
# (AccessError); lo que importa es que corte y que el nivel no
|
||||
# se mueva. `assertRaises` de Odoo no admite una tupla.
|
||||
with self.assertRaises(Exception):
|
||||
empleado.with_user(self.admin_a).write({'beyond_acceso': nivel})
|
||||
empleado.invalidate_recordset(['beyond_acceso'])
|
||||
self.assertEqual(empleado.beyond_acceso, 'checador',
|
||||
'el nivel se movió pese al error')
|
||||
|
||||
def test_tampoco_dandolo_de_alta_ya_promovido(self):
|
||||
"""La otra puerta: si el guardia solo mirara el write, bastaría con
|
||||
crear a la persona ya ascendida."""
|
||||
with self.assertRaises(Exception):
|
||||
self.env['hr.employee'].with_user(self.admin_a).create({
|
||||
'name': 'Nace ascendido', 'branch_id': self.branch_a.id,
|
||||
'department_id': self.branch_a.department_id.id,
|
||||
'beyond_celular': '2224448888',
|
||||
'beyond_clave_inicial': 'clave-ascenso-8',
|
||||
'beyond_acceso': 'admin_general',
|
||||
})
|
||||
|
||||
def test_la_direccion_si_puede(self):
|
||||
"""Y su gemela: si el guardia cortara a todos, promover sería
|
||||
imposible y nadie se enteraría hasta necesitarlo."""
|
||||
empleado = self.env['hr.employee']._beyond_alta(
|
||||
'Sube de nivel', '2224447777', 'clave-sube-888', self.branch_a)
|
||||
empleado.with_user(self.admin_general).write(
|
||||
{'beyond_acceso': 'admin_sucursal'})
|
||||
self.assertEqual(empleado.beyond_acceso, 'admin_sucursal')
|
||||
@@ -17,7 +17,7 @@ class TestBeyondInmutabilidad(BeyondChecadorCase):
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
cls.checada = cls._checar(cls.emp_a, cls.branch_a)['checada']
|
||||
cls.entrada_bitacora = cls.env['beyond.bitacora'].registrar(
|
||||
cls.entrada_bitacora = cls.env['beyond.bitacora']._registrar(
|
||||
'prueba', 'beyond.checada', cls.checada.id, branch=cls.branch_a)
|
||||
|
||||
def test_orm_bloquea_checadas(self):
|
||||
|
||||
@@ -38,6 +38,19 @@ class TestBeyondJornadas(BeyondChecadorCase):
|
||||
self.assertEqual(resultado['checada'].branch_id, self.branch_b)
|
||||
self.assertEqual(resultado['jornada'].branch_id, self.branch_b)
|
||||
|
||||
def test_el_cierre_automatico_si_cuenta(self):
|
||||
"""La gemela del anterior: `rechazada` no suma, pero la jornada que
|
||||
cerró el cron sí. Es la decisión con efecto en nómina de ADR-018 y
|
||||
sin esta prueba «no suma» podría estar tapando a las dos."""
|
||||
self.Attendance.sudo().with_context(beyond_sistema=True).create({
|
||||
'employee_id': self.emp_c.id,
|
||||
'check_in': '2026-08-09 09:00:00',
|
||||
'check_out': '2026-08-09 14:00:00',
|
||||
'beyond_estado': 'cerrada',
|
||||
'beyond_autocerrada': True,
|
||||
})
|
||||
self.assertAlmostEqual(self.emp_c.beyond_total_horas(), 5.0, places=2)
|
||||
|
||||
def test_total_solo_cerradas_mas_ajustes(self):
|
||||
Ajuste = self.env['beyond.ajuste'].sudo()
|
||||
self.assertAlmostEqual(self.emp_c.beyond_total_horas(), 0.0)
|
||||
@@ -49,16 +62,18 @@ class TestBeyondJornadas(BeyondChecadorCase):
|
||||
cerradas = self.Attendance.sudo().search_count([
|
||||
('employee_id', '=', self.emp_c.id), ('beyond_estado', '=', 'cerrada')])
|
||||
self.assertEqual(cerradas, 1)
|
||||
# revision: 8 h trabajadas que NO suman (fecha pasada, sin traslape)
|
||||
jornada_rev = self.Attendance.sudo().with_context(beyond_sistema=True).create({
|
||||
# rechazada: 8 h trabajadas que NO suman. El estado quedó en desuso
|
||||
# —ya nada puede producirlo— pero el histórico se sigue leyendo y
|
||||
# esas horas no se pagaron (ADR-018).
|
||||
jornada_rechazada = self.Attendance.sudo().with_context(beyond_sistema=True).create({
|
||||
'employee_id': self.emp_c.id,
|
||||
'check_in': '2026-08-10 09:00:00',
|
||||
'check_out': '2026-08-10 17:00:00',
|
||||
'beyond_estado': 'revision',
|
||||
'beyond_estado': 'rechazada',
|
||||
})
|
||||
self.assertEqual(jornada_rev.beyond_horas, 8.0)
|
||||
self.assertEqual(jornada_rechazada.beyond_horas, 8.0)
|
||||
self.assertAlmostEqual(self.emp_c.beyond_total_horas(), 0.0, places=2,
|
||||
msg="una jornada en revision NO debe sumar")
|
||||
msg="una jornada rechazada NO debe sumar")
|
||||
# ajustes: suman y restan
|
||||
Ajuste.create({'employee_id': self.emp_c.id, 'minutos': 90, 'motivo': 'Capacitación'})
|
||||
self.assertAlmostEqual(self.emp_c.beyond_total_horas(), 1.5, places=2)
|
||||
|
||||
@@ -10,7 +10,9 @@ RAICES_ADMIN_GENERAL = {
|
||||
'beyond_attendance_qr.menu_kiosco_app',
|
||||
'point_of_sale.menu_point_root',
|
||||
'beyond_branch.menu_beyond_root',
|
||||
'contacts.menu_contacts',
|
||||
# La raíz de Tableros SE QUEDA a propósito: es a donde apunta el botón
|
||||
# del Menú Principal, y ahora cuelgan de ella los tableros de Beyond
|
||||
# (beyond_reports). Lo nativo son sus hijos, ocultos para los roles.
|
||||
'spreadsheet_dashboard.spreadsheet_dashboard_menu_root',
|
||||
'stock.menu_stock_root',
|
||||
# hr.menu_hr_root salió DELIBERADAMENTE (rediseño de Personal): la
|
||||
@@ -20,6 +22,7 @@ PROHIBIDAS = {
|
||||
'account.menu_finance', # brief 5.7
|
||||
'hr_attendance.menu_hr_attendance_root', # sustituido por Beyond → Checador
|
||||
'hr.menu_hr_root', # sustituido por Beyond → Personal
|
||||
'contacts.menu_contacts', # sustituido por Beyond → Clientes
|
||||
'mail.menu_root_discuss', # C-001
|
||||
'base.menu_management', # C-004
|
||||
'base.menu_administration', # C-004
|
||||
@@ -71,7 +74,7 @@ class TestBeyondMenusRol(TransactionCase):
|
||||
visibles = self.env['ir.ui.menu'].with_user(admin)._visible_menu_ids()
|
||||
for xmlid in ('account.menu_finance',
|
||||
'hr_attendance.menu_hr_attendance_root',
|
||||
'hr.menu_hr_root',
|
||||
'hr.menu_hr_root', 'contacts.menu_contacts',
|
||||
'base.menu_management', 'base.menu_administration'):
|
||||
self.assertIn(self.env.ref(xmlid).id, visibles,
|
||||
f"la cuenta técnica debe conservar {xmlid}")
|
||||
@@ -48,11 +48,10 @@ class TestBeyondPanel(BeyondChecadorCase):
|
||||
['ventana_inicio', 'ventana_fin', 'qr_rotacion_seg'])
|
||||
self.assertEqual(valores['ventana_inicio'], '05:15')
|
||||
|
||||
def test_menus_del_panel_solo_para_supervisores(self):
|
||||
menu = self.env.ref('beyond_attendance_qr.menu_checador')
|
||||
def test_la_configuracion_es_solo_del_admin_general(self):
|
||||
"""Lo único que queda del panel operativo del checador, y como puerta
|
||||
discreta (ADR-018)."""
|
||||
Menu = self.env['ir.ui.menu']
|
||||
self.assertIn(menu.id, Menu.with_user(self.admin_a)._visible_menu_ids())
|
||||
self.assertIn(menu.id, Menu.with_user(self.admin_general)._visible_menu_ids())
|
||||
config_menu = self.env.ref('beyond_attendance_qr.menu_checador_config')
|
||||
self.assertNotIn(config_menu.id,
|
||||
Menu.with_user(self.admin_a)._visible_menu_ids(),
|
||||
|
||||
@@ -17,14 +17,31 @@ class TestBeyondPersonal(BeyondChecadorCase):
|
||||
def test_seccion_personal_visible_y_rrhh_nativo_oculto(self):
|
||||
Menu = self.env['ir.ui.menu']
|
||||
visibles = Menu.with_user(self.admin_a)._visible_menu_ids()
|
||||
# Personal se reduce a Equipo (ADR-018): jornadas, solicitudes,
|
||||
# checadas, ajustes, bitácora y productividad salen del menú, y sus
|
||||
# cifras se leen donde significan algo.
|
||||
for xmlid in ('beyond_branch.menu_personal',
|
||||
'beyond_attendance_qr.menu_equipo',
|
||||
'beyond_attendance_qr.menu_hoy',
|
||||
'beyond_attendance_qr.menu_jornadas',
|
||||
'beyond_attendance_qr.menu_checador',
|
||||
'beyond_pos_theme.menu_productividad'):
|
||||
'beyond_attendance_qr.menu_equipo'):
|
||||
self.assertIn(self.env.ref(xmlid).id, visibles,
|
||||
f"el admin de sucursal debe ver {xmlid}")
|
||||
for xmlid in ('beyond_attendance_qr.menu_hoy',
|
||||
'beyond_attendance_qr.menu_jornadas',
|
||||
'beyond_attendance_qr.menu_checador',
|
||||
'beyond_attendance_qr.menu_solicitudes',
|
||||
'beyond_attendance_qr.menu_checadas',
|
||||
'beyond_attendance_qr.menu_ajustes',
|
||||
'beyond_attendance_qr.menu_bitacora',
|
||||
'beyond_pos_theme.menu_productividad'):
|
||||
self.assertFalse(self.env.ref(xmlid, raise_if_not_found=False),
|
||||
f"{xmlid} tenía que salir del menú")
|
||||
# Y su gemela: las ACCIONES se conservan. Quitar el menú no es
|
||||
# borrar el dato, y el historial se sigue pudiendo abrir.
|
||||
for xmlid in ('beyond_attendance_qr.action_checadas',
|
||||
'beyond_attendance_qr.action_bitacora',
|
||||
'beyond_attendance_qr.action_jornadas',
|
||||
'beyond_pos_theme.action_productividad'):
|
||||
self.assertTrue(self.env.ref(xmlid, raise_if_not_found=False),
|
||||
f"{xmlid} no puede desaparecer con su menú")
|
||||
self.assertNotIn(self.env.ref('hr.menu_hr_root').id, visibles,
|
||||
"el RRHH nativo no es para los roles")
|
||||
tecnica = Menu.with_user(self.env.ref('base.user_admin'))._visible_menu_ids()
|
||||
|
||||
@@ -0,0 +1,641 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
from datetime import datetime, time, timedelta
|
||||
|
||||
from odoo import fields
|
||||
from odoo.tests import HttpCase, tagged
|
||||
|
||||
from odoo.addons.beyond_branch.tests.ayudantes_navegador import AYUDANTES
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestPersonalEnNavegador(HttpCase):
|
||||
"""Equipo y la ficha, en un navegador de verdad.
|
||||
|
||||
Con `elementFromPoint` en lo que hay que poder tocar: el renglón, los dos
|
||||
botones de la ficha, los chips y el pie. Un botón tapado tiene las mismas
|
||||
coordenadas que uno visible.
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
sucursal = self.env['beyond.branch'].search(
|
||||
[('pricelist_id', '!=', False)], limit=1)
|
||||
self.persona = self.env['hr.employee'].create({
|
||||
'name': 'AAA Persona de navegador',
|
||||
'branch_id': sucursal.id,
|
||||
'department_id': sucursal.department_id.id,
|
||||
'beyond_celular': '2221110000',
|
||||
# Con celular hay cuenta, y una cuenta nace con contraseña: el
|
||||
# alta lo exige (ADR-008) y sin ella el create truena.
|
||||
'beyond_clave_inicial': 'clave-navegador-8',
|
||||
'job_title': 'Estilista',
|
||||
})
|
||||
# Horas de verdad que pintar: sin ellas la barra sale en cero y no se
|
||||
# distingue de una barra rota (ADR-016, forma nº 3).
|
||||
entrada = datetime.combine(fields.Datetime.now().date(), time(hour=7))
|
||||
self.env['hr.attendance'].sudo().with_context(beyond_sistema=True).create({
|
||||
'employee_id': self.persona.id,
|
||||
'check_in': entrada,
|
||||
'check_out': entrada + timedelta(hours=5),
|
||||
'beyond_estado': 'cerrada',
|
||||
})
|
||||
|
||||
def test_la_pantalla_de_equipo_y_la_ficha(self):
|
||||
self.browser_js(
|
||||
"/odoo",
|
||||
"""
|
||||
(async () => {
|
||||
""" + AYUDANTES + """
|
||||
(await hasta('[data-menu-xmlid="beyond_branch.menu_beyond_root"]')).click();
|
||||
(await hasta('[data-menu-xmlid="beyond_branch.menu_personal"]')).click();
|
||||
await hasta('.o_beyond_equipo');
|
||||
await esperar(2000);
|
||||
|
||||
// ── Equipo ──
|
||||
seVe('.beyond_equipo_buscador input', 'el buscador');
|
||||
seVe('.beyond_equipo_nuevo', 'el botón Nuevo');
|
||||
const filtros = [...document.querySelectorAll('.beyond_equipo_filtro')];
|
||||
const cuentas = {};
|
||||
for (const filtro of filtros) {
|
||||
const marca = filtro.querySelector('.beyond_equipo_cuenta');
|
||||
if (!marca) {
|
||||
throw new Error('un filtro sin contador: «'
|
||||
+ filtro.textContent.trim() + '»');
|
||||
}
|
||||
cuentas[filtro.textContent.trim().replace(/\s*\d+$/, '')] =
|
||||
Number.parseInt(marca.textContent, 10);
|
||||
}
|
||||
// Los contadores tienen que SUMAR. Antes eran tres y quien ya
|
||||
// había entrado y salido no estaba en ninguno: «Todos 10» con
|
||||
// 1 + 7 debajo obliga a desconfiar de los tres números.
|
||||
const suma = Object.entries(cuentas)
|
||||
.filter(([nombre]) => nombre !== 'Todos')
|
||||
.reduce((total, [, n]) => total + n, 0);
|
||||
if (suma !== cuentas['Todos']) {
|
||||
throw new Error('los contadores no cuadran: Todos='
|
||||
+ cuentas['Todos'] + ' y los demás suman ' + suma
|
||||
+ ' (' + JSON.stringify(cuentas) + ')');
|
||||
}
|
||||
seVe('.beyond_equipo_filtro', 'el primer filtro');
|
||||
|
||||
// El resumen y el pie con la jornada esperada.
|
||||
seVe('.beyond_resumen_tarjeta', 'el resumen por sucursal');
|
||||
const pie = document.querySelector('.beyond_equipo_pie');
|
||||
if (!pie || !pie.textContent.includes('Jornada esperada')) {
|
||||
throw new Error('falta el pie con la jornada esperada');
|
||||
}
|
||||
|
||||
// La barra de avance existe y NO se pasa del 100%.
|
||||
const relleno = document.querySelector('.beyond_equipo_relleno');
|
||||
if (!relleno) {
|
||||
throw new Error('ninguna barra de avance dibujada');
|
||||
}
|
||||
const ancho = Number.parseFloat(relleno.style.width);
|
||||
if (!(ancho > 0) || ancho > 100) {
|
||||
throw new Error('la barra mide ' + relleno.style.width);
|
||||
}
|
||||
|
||||
// El renglón es alcanzable y abre la ficha.
|
||||
const fila = document.querySelector('.beyond_equipo_tabla tbody tr');
|
||||
if (!fila) {
|
||||
throw new Error('la tabla de Equipo no trajo a nadie');
|
||||
}
|
||||
const caja = fila.getBoundingClientRect();
|
||||
const encima = document.elementFromPoint(
|
||||
Math.round(caja.left + caja.width / 2),
|
||||
Math.round(caja.top + caja.height / 2));
|
||||
if (!encima || !fila.contains(encima)) {
|
||||
throw new Error('el renglón de Equipo está tapado');
|
||||
}
|
||||
fila.click();
|
||||
await hasta('.o_beyond_persona_form');
|
||||
await esperar(2000);
|
||||
|
||||
// ── La ficha ──
|
||||
seVe('.beyond_persona_encabezado', 'el encabezado de la ficha');
|
||||
seVe('.beyond_boton_baja', '«Dar de baja»');
|
||||
seVe('[name="beyond_celular"] input, .beyond_celular_campo',
|
||||
'el celular editable');
|
||||
// Avance, productividad y jornadas quedan bajo el pliegue en
|
||||
// una ficha con historial. Se desplaza AQUÍ, a la vista y con
|
||||
// su motivo: lo que se afirma es que DESPUÉS de desplazar
|
||||
// están y son alcanzables, no que se vean sin moverse
|
||||
// (ADR-016, forma nº 6).
|
||||
const hoja = document.querySelector('.o_content');
|
||||
hoja.scrollTop = hoja.scrollHeight / 2;
|
||||
await esperar(600);
|
||||
seVe('.beyond_ficha_avance', 'la tarjeta de avance');
|
||||
seVe('.beyond_ficha_productividad', 'la tarjeta de productividad');
|
||||
hoja.scrollTop = hoja.scrollHeight;
|
||||
await esperar(600);
|
||||
seVe('.beyond_ficha_jornadas', 'la tabla de jornadas');
|
||||
|
||||
// Sin botones por renglón en las jornadas: el registro es lo
|
||||
// que marcó el QR y no se edita desde aquí.
|
||||
if (document.querySelector('.beyond_ficha_tabla button')) {
|
||||
throw new Error('apareció un botón en un renglón de jornada');
|
||||
}
|
||||
|
||||
seVe('.beyond_boton_guardar', 'Guardar');
|
||||
seVe('.beyond_boton_descartar', 'Descartar');
|
||||
|
||||
// Y la vuelta a Equipo por la píldora de la miga.
|
||||
const volver = document.querySelector('.o_breadcrumb .breadcrumb-item a');
|
||||
if (!volver) {
|
||||
throw new Error('la ficha no tiene camino de vuelta');
|
||||
}
|
||||
console.log('test successful');
|
||||
})();
|
||||
""", "", login='admin', timeout=180)
|
||||
|
||||
def test_el_aviso_de_celular_repetido(self):
|
||||
"""Se avisa al SALIR del campo, no al guardar con el formulario
|
||||
entero lleno, y el registro queda marcado como inválido para que
|
||||
Guardar no pase."""
|
||||
self.browser_js(
|
||||
"/odoo/action-beyond_attendance_qr.action_equipo/new",
|
||||
"""
|
||||
(async () => {
|
||||
""" + AYUDANTES + """
|
||||
await hasta('.o_beyond_persona_form');
|
||||
await esperar(1500);
|
||||
const campo = document.querySelector('.beyond_celular_campo');
|
||||
if (!campo) {
|
||||
throw new Error('el alta no trae el campo de celular');
|
||||
}
|
||||
campo.value = '2221110000';
|
||||
campo.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
await esperar(1500);
|
||||
const aviso = document.querySelector('.beyond_celular_mensaje');
|
||||
if (!aviso || !aviso.textContent.trim()) {
|
||||
throw new Error('no avisó de que el celular ya es de alguien');
|
||||
}
|
||||
|
||||
// Su gemela, en el mismo guion: con un número libre NO avisa.
|
||||
campo.value = '2229998877';
|
||||
campo.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
await esperar(1500);
|
||||
const despues = document.querySelector('.beyond_celular_mensaje');
|
||||
if (despues && despues.textContent.trim()) {
|
||||
throw new Error('avisa de un celular libre: «'
|
||||
+ despues.textContent.trim() + '»');
|
||||
}
|
||||
// Se descarta antes de terminar: Odoo no deja cerrar una
|
||||
// prueba de navegador con un formulario sucio, y con razón
|
||||
// —al cerrar la página lo guardaría solo—. Lo que se afirma
|
||||
// es que lo tecleado se fue; NO que la pantalla cambie, que
|
||||
// aquí se entró por URL directa y «atrás» no tiene a dónde
|
||||
// volver.
|
||||
document.querySelector('.beyond_boton_descartar').click();
|
||||
await esperar(1500);
|
||||
const limpio = document.querySelector('.beyond_celular_campo');
|
||||
if (limpio && limpio.value) {
|
||||
throw new Error('«Descartar» dejó el celular tecleado: «'
|
||||
+ limpio.value + '»');
|
||||
}
|
||||
console.log('test successful');
|
||||
})();
|
||||
""", "", login='admin', timeout=120)
|
||||
|
||||
def _chips(self, url):
|
||||
"""Cada grupo de chips: alcanzable, la selección cambia al pulsarlo y
|
||||
lo elegido llega al REGISTRO.
|
||||
|
||||
Faltaba en el barrido, y es el control principal del alta: sin chips
|
||||
no se puede dar de alta a nadie. Un chip que se pinta y no escribe es
|
||||
la forma de ADR-016 de afirmar el estado en vez del mecanismo, así
|
||||
que aquí se afirman las tres cosas y la última se comprueba después
|
||||
contra la base.
|
||||
"""
|
||||
self.browser_js(url, """
|
||||
(async () => {
|
||||
""" + AYUDANTES + """
|
||||
await hasta('.o_beyond_persona_form');
|
||||
await esperar(2000);
|
||||
for (const campo of ['branch_id', 'beyond_acceso']) {
|
||||
const grupo = document.querySelector('[name="' + campo + '"]');
|
||||
if (!grupo) {
|
||||
throw new Error('no hay grupo de chips para ' + campo);
|
||||
}
|
||||
const chips = [...grupo.querySelectorAll('.o_selection_badge')];
|
||||
if (chips.length < 2) {
|
||||
throw new Error(campo + ' trae ' + chips.length
|
||||
+ ' chips: no hay entre qué elegir');
|
||||
}
|
||||
// Alcanzable de verdad: un chip tapado tiene las mismas
|
||||
// coordenadas que uno visible.
|
||||
seVe('[name="' + campo + '"] .o_selection_badge',
|
||||
'el primer chip de ' + campo);
|
||||
|
||||
const ultimo = chips[chips.length - 1];
|
||||
const antes = chips.findIndex((c) => c.classList.contains('active'));
|
||||
ultimo.click();
|
||||
await esperar(800);
|
||||
const ahora = [...grupo.querySelectorAll('.o_selection_badge')]
|
||||
.findIndex((c) => c.classList.contains('active'));
|
||||
if (ahora === antes) {
|
||||
throw new Error(campo + ': pulsar un chip no movió la '
|
||||
+ 'selección (seguía en ' + antes + ')');
|
||||
}
|
||||
if (ahora !== chips.length - 1) {
|
||||
throw new Error(campo + ': se marcó el chip ' + ahora
|
||||
+ ' y se pulsó el ' + (chips.length - 1));
|
||||
}
|
||||
// Y se DISTINGUE: si el activo se viera igual que el
|
||||
// resto, para quien mira el clic no habría hecho nada.
|
||||
const activo = grupo.querySelector('.o_selection_badge.active');
|
||||
const otro = grupo.querySelector('.o_selection_badge:not(.active)');
|
||||
const ca = getComputedStyle(activo), co = getComputedStyle(otro);
|
||||
if (ca.backgroundColor === co.backgroundColor
|
||||
&& ca.color === co.color) {
|
||||
throw new Error(campo + ': el chip elegido se ve igual '
|
||||
+ 'que los demás (' + ca.backgroundColor + ')');
|
||||
}
|
||||
}
|
||||
// Y lo elegido se guarda. En el alta hay que ponerle nombre
|
||||
// primero: sin él la validación corta el guardado y lo que
|
||||
// se estaría midiendo es el nombre vacío, no los chips.
|
||||
const escribir = (sel, valor) => {
|
||||
const campo = document.querySelector(sel);
|
||||
if (!campo || campo.value) { return; }
|
||||
campo.value = valor;
|
||||
campo.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
campo.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
};
|
||||
escribir('.o_beyond_persona_form h1 input', 'ZZZ Alta con chips');
|
||||
// Con un nivel de acceso hace falta cuenta, y la cuenta es el
|
||||
// celular más su contraseña (ADR-008): sin ellos el alta se
|
||||
// corta y lo que se estaría midiendo sería eso, no los chips.
|
||||
escribir('.beyond_celular_campo', '2229995544');
|
||||
escribir('[name="beyond_clave_inicial"] input', 'clave-chips-88');
|
||||
await esperar(600);
|
||||
document.querySelector('.beyond_boton_guardar').click();
|
||||
await esperar(2500);
|
||||
console.log('test successful');
|
||||
})();
|
||||
""", "", login='admin', timeout=180)
|
||||
|
||||
def test_los_chips_del_alta_escriben_en_el_registro(self):
|
||||
sucursales = self.env['beyond.branch'].search(
|
||||
[('pricelist_id', '!=', False)], order='id')
|
||||
self.assertGreaterEqual(len(sucursales), 2, 'hacen falta dos para elegir')
|
||||
antes = self.env['hr.employee'].search([])
|
||||
|
||||
self._chips("/odoo/action-beyond_attendance_qr.action_equipo/new")
|
||||
|
||||
nueva = self.env['hr.employee'].search([]) - antes
|
||||
self.assertTrue(nueva, 'el alta con chips no llegó a guardar')
|
||||
self.assertTrue(nueva.branch_id,
|
||||
'la sucursal elegida con los chips no llegó al registro')
|
||||
|
||||
def test_los_chips_de_la_ficha_escriben_en_el_registro(self):
|
||||
otra = self.env['beyond.branch'].search(
|
||||
[('pricelist_id', '!=', False), ('id', '!=', self.persona.branch_id.id)],
|
||||
limit=1)
|
||||
self.assertTrue(otra, 'hace falta una segunda sucursal')
|
||||
|
||||
self._chips(
|
||||
f"/odoo/action-beyond_attendance_qr.action_equipo/{self.persona.id}")
|
||||
|
||||
self.persona.invalidate_recordset(['branch_id'])
|
||||
self.assertNotEqual(self.persona.branch_id, self.env['beyond.branch'],
|
||||
'la ficha se quedó sin sucursal')
|
||||
|
||||
def test_la_foto_se_sube_desde_la_ficha(self):
|
||||
"""La misma foto, el mismo widget y las mismas tres rutas que en
|
||||
Clientes (ADR-013). Se prueba la que se puede automatizar —subir un
|
||||
archivo— hasta el final: que el byte llegue al REGISTRO, no que el
|
||||
menú se dibuje. Un menú que se pinta y no escribe es la forma de
|
||||
ADR-016 de afirmar el estado en vez del mecanismo.
|
||||
|
||||
Se entra por el MENÚ y no por la URL: sin app seleccionada el cliente
|
||||
web no pone la clase `beyond_panel` en el body, y todo el
|
||||
revestimiento del panel —incluido el de este menú— se queda fuera.
|
||||
Medido: por URL el menú sale sin estilos y con 27px de alto.
|
||||
"""
|
||||
# Nace sin imagen: el SVG que Odoo deja guardado —iniciales sobre un
|
||||
# color de su paleta— se limpia al crear, porque no es una foto y
|
||||
# llenaba la lista de avatares verdes y morados.
|
||||
import base64
|
||||
self.assertFalse(self.persona.image_1920,
|
||||
'el avatar generado por Odoo tenía que limpiarse')
|
||||
self.assertFalse(self.persona._beyond_tiene_foto())
|
||||
self.browser_js(
|
||||
"/odoo",
|
||||
"""
|
||||
(async () => {
|
||||
""" + AYUDANTES + """
|
||||
(await hasta('[data-menu-xmlid="beyond_branch.menu_beyond_root"]')).click();
|
||||
(await hasta('[data-menu-xmlid="beyond_branch.menu_personal"]')).click();
|
||||
await hasta('.o_beyond_equipo');
|
||||
await esperar(2000);
|
||||
const buscador = document.querySelector('.beyond_equipo_buscador input');
|
||||
buscador.value = 'AAA Persona de navegador';
|
||||
buscador.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
await esperar(1500);
|
||||
document.querySelector('.beyond_equipo_tabla tbody tr').click();
|
||||
await hasta('.o_beyond_persona_form');
|
||||
await esperar(2000);
|
||||
|
||||
seVe('.beyond_foto', 'la foto de la ficha');
|
||||
document.querySelector('.beyond_foto').click();
|
||||
await esperar(700);
|
||||
const menu = document.querySelector('.beyond_foto_menu');
|
||||
if (!menu) {
|
||||
throw new Error('el menú de la foto no se abre');
|
||||
}
|
||||
// Sin foto son DOS rutas: tomar y subir. «Eliminar» aparece
|
||||
// cuando hay algo que eliminar, y eso se comprueba abajo.
|
||||
const opciones = menu.querySelectorAll('.beyond_foto_opcion');
|
||||
if (opciones.length !== 2) {
|
||||
throw new Error('sin foto, las rutas deben ser dos y hay '
|
||||
+ opciones.length + ': '
|
||||
+ [...opciones].map((o) => o.textContent.trim()).join(' / '));
|
||||
}
|
||||
for (const opcion of opciones) {
|
||||
const c = opcion.getBoundingClientRect();
|
||||
const encima = document.elementFromPoint(
|
||||
Math.round(c.left + c.width / 2),
|
||||
Math.round(c.top + c.height / 2));
|
||||
if (!encima || !opcion.contains(encima)) {
|
||||
throw new Error('la ruta «' + opcion.textContent.trim()
|
||||
+ '» no está alcanzable');
|
||||
}
|
||||
}
|
||||
|
||||
// Subir de verdad: un PNG mínimo, por el input del uploader.
|
||||
const entrada = document.querySelector('.beyond_foto_menu input[type="file"]');
|
||||
if (!entrada) {
|
||||
throw new Error('el menú no trae el campo de archivo');
|
||||
}
|
||||
const png = atob('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJ'
|
||||
+ 'AAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==');
|
||||
const bytes = new Uint8Array(png.length);
|
||||
for (let i = 0; i < png.length; i++) { bytes[i] = png.charCodeAt(i); }
|
||||
const dt = new DataTransfer();
|
||||
dt.items.add(new File([bytes], 'retrato.png', { type: 'image/png' }));
|
||||
entrada.files = dt.files;
|
||||
entrada.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
await esperar(2500);
|
||||
|
||||
// Con foto aparece la tercera ruta: la de quitarla.
|
||||
document.querySelector('.beyond_foto').click();
|
||||
await esperar(700);
|
||||
const conFoto = document.querySelectorAll(
|
||||
'.beyond_foto_menu .beyond_foto_opcion');
|
||||
if (conFoto.length !== 3) {
|
||||
throw new Error('con foto, las rutas deben ser tres y hay '
|
||||
+ conFoto.length);
|
||||
}
|
||||
|
||||
document.querySelector('.beyond_boton_guardar').click();
|
||||
await esperar(2500);
|
||||
console.log('test successful');
|
||||
})();
|
||||
""", "", login='admin', timeout=180)
|
||||
|
||||
self.persona.invalidate_recordset(['image_1920'])
|
||||
crudo = base64.b64decode(self.persona.image_1920)[:64]
|
||||
self.assertNotIn(b'<svg', crudo,
|
||||
'la foto subida no reemplazó al avatar generado')
|
||||
self.assertTrue(self.persona._beyond_tiene_foto(),
|
||||
'y ahora sí hay foto que enseñar')
|
||||
|
||||
def test_el_nivel_de_acceso_se_elige_y_se_guarda(self):
|
||||
"""Pulsar el chip tiene que CAMBIAR EL DATO, no solo la clase.
|
||||
|
||||
La ronda anterior se cerró con «los chips sí funcionan, solo no se
|
||||
veían»: se comprobó que la clase `active` se movía y ahí se paró la
|
||||
comprobación. Mover una clase no es guardar un valor, y esta prueba
|
||||
va hasta la base.
|
||||
"""
|
||||
sucursal = self.env['beyond.branch'].search(
|
||||
[('pricelist_id', '!=', False)], limit=1)
|
||||
persona = self.env['hr.employee'].create({
|
||||
'name': 'AAB Cambia de nivel', 'branch_id': sucursal.id,
|
||||
'department_id': sucursal.department_id.id,
|
||||
'beyond_celular': '2227778888',
|
||||
'beyond_clave_inicial': 'clave-nivel-888'})
|
||||
self.assertEqual(persona.beyond_acceso, 'checador')
|
||||
|
||||
self.browser_js(
|
||||
"/odoo",
|
||||
"""
|
||||
(async () => {
|
||||
""" + AYUDANTES + """
|
||||
(await hasta('[data-menu-xmlid="beyond_branch.menu_beyond_root"]')).click();
|
||||
(await hasta('[data-menu-xmlid="beyond_branch.menu_personal"]')).click();
|
||||
await hasta('.o_beyond_equipo');
|
||||
await esperar(2000);
|
||||
const buscador = document.querySelector('.beyond_equipo_buscador input');
|
||||
buscador.value = 'AAB Cambia de nivel';
|
||||
buscador.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
await esperar(1500);
|
||||
document.querySelector('.beyond_equipo_tabla tbody tr').click();
|
||||
await hasta('.o_beyond_persona_form');
|
||||
await esperar(2000);
|
||||
|
||||
const grupo = document.querySelector('[name="beyond_acceso"]');
|
||||
const chips = [...grupo.querySelectorAll('.o_selection_badge')];
|
||||
// Dos niveles: la dirección no se ofrece (ADR-018).
|
||||
if (chips.length !== 2) {
|
||||
throw new Error('el nivel ofrece ' + chips.length + ' opciones: '
|
||||
+ chips.map((c) => c.textContent.trim()).join(' / '));
|
||||
}
|
||||
const otro = chips.find((c) => !c.classList.contains('active'));
|
||||
const caja = otro.getBoundingClientRect();
|
||||
const encima = document.elementFromPoint(
|
||||
Math.round(caja.left + caja.width / 2),
|
||||
Math.round(caja.top + caja.height / 2));
|
||||
if (!encima || !otro.contains(encima)) {
|
||||
throw new Error('el chip de nivel no está alcanzable');
|
||||
}
|
||||
otro.click();
|
||||
await esperar(900);
|
||||
if (!otro.classList.contains('active')) {
|
||||
throw new Error('el chip pulsado no quedó marcado');
|
||||
}
|
||||
document.querySelector('.beyond_boton_guardar').click();
|
||||
await esperar(3000);
|
||||
console.log('test successful');
|
||||
})();
|
||||
""", "", login='direccion@beyond.example', timeout=180)
|
||||
|
||||
persona.invalidate_recordset(['beyond_acceso'])
|
||||
self.assertEqual(persona.beyond_acceso, 'admin_sucursal',
|
||||
'el nivel elegido con el chip no llegó a la base')
|
||||
|
||||
def test_restablecer_la_clave_de_quien_tiene_celular_sin_cuenta(self):
|
||||
"""Existe de verdad: una ficha creada sin celular a la que se le
|
||||
puso después. Sin cuenta, «Restablecer contraseña» no tenía nada que
|
||||
restablecer y el botón ni siquiera se ofrecía."""
|
||||
sucursal = self.env['beyond.branch'].search(
|
||||
[('pricelist_id', '!=', False)], limit=1)
|
||||
# Así es como se llega a ese estado de verdad: la ficha nace sin
|
||||
# celular —el guardia del alta solo mira las que tienen sucursal— y
|
||||
# alguien se lo pone después. `write` sincroniza el login de una
|
||||
# cuenta que ya existe, pero no crea la que falta.
|
||||
a_medias = self.env['hr.employee'].with_context(beyond_sistema=True).create({
|
||||
'name': 'AAC Sin cuenta', 'branch_id': sucursal.id,
|
||||
'department_id': sucursal.department_id.id})
|
||||
a_medias.write({'beyond_celular': '2226665544'})
|
||||
self.assertFalse(a_medias.beyond_portal_user_id,
|
||||
'así es como aparece una ficha a medias')
|
||||
|
||||
self.env['beyond.employee.password'].create({
|
||||
'employee_id': a_medias.id, 'password': 'clave-nueva-888',
|
||||
}).action_apply()
|
||||
|
||||
a_medias.invalidate_recordset(['beyond_portal_user_id'])
|
||||
self.assertTrue(a_medias.beyond_portal_user_id,
|
||||
'restablecer tenía que dejarle cuenta')
|
||||
self.assertEqual(a_medias.beyond_portal_user_id.login, '2226665544')
|
||||
self.assertTrue(a_medias.beyond_portal_user_id.beyond_clave_temporal,
|
||||
'la clave que fija otra persona nace temporal')
|
||||
|
||||
def test_restablecer_la_clave_de_quien_ya_tenia_cuenta(self):
|
||||
"""La gemela: la ruta normal no puede haberse roto al arreglar la
|
||||
otra."""
|
||||
sucursal = self.env['beyond.branch'].search(
|
||||
[('pricelist_id', '!=', False)], limit=1)
|
||||
completa = self.env['hr.employee']._beyond_alta(
|
||||
'AAD Con cuenta', '2226665533', 'clave-vieja-888', sucursal)
|
||||
completa.beyond_portal_user_id.sudo().beyond_clave_temporal = False
|
||||
|
||||
self.env['beyond.employee.password'].create({
|
||||
'employee_id': completa.id, 'password': 'clave-nueva-888',
|
||||
}).action_apply()
|
||||
|
||||
self.assertTrue(completa.beyond_portal_user_id.sudo().beyond_clave_temporal)
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestRevisionDelCliente(HttpCase):
|
||||
"""Los seis puntos de la revisión, mirados como los mira quien revisa.
|
||||
|
||||
Existe porque la tanda anterior se reportó cerrada sin estarlo: cada
|
||||
arreglo tenía su prueba, y ninguna miraba lo que el cliente iba a ver.
|
||||
Esta entra con la cuenta de la dirección, por el menú, con una lista más
|
||||
larga que la ventana, y afirma los colores CALCULADOS y no que un valor
|
||||
sea distinto de otro.
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
sucursal = self.env['beyond.branch'].search(
|
||||
[('pricelist_id', '!=', False)], limit=1)
|
||||
# Lista más larga que la ventana: sin esto, la prueba del
|
||||
# desplazamiento no tiene nada que desplazar y pasa siempre.
|
||||
for i in range(30):
|
||||
self.env['hr.employee'].create({
|
||||
'name': f'ZZ Plantilla {i:02d}', 'branch_id': sucursal.id,
|
||||
'department_id': sucursal.department_id.id,
|
||||
'beyond_celular': f'22233{i:05d}',
|
||||
'beyond_clave_inicial': 'clave-plantilla-8'})
|
||||
|
||||
def test_los_seis_puntos(self):
|
||||
self.browser_js(
|
||||
"/odoo",
|
||||
"""
|
||||
(async () => {
|
||||
""" + AYUDANTES + """
|
||||
(await hasta('[data-menu-xmlid="beyond_branch.menu_beyond_root"]')).click();
|
||||
(await hasta('[data-menu-xmlid="beyond_branch.menu_personal"]')).click();
|
||||
await hasta('.o_beyond_equipo');
|
||||
await esperar(2500);
|
||||
|
||||
// ── 1 · Avatares en durazno, nunca la imagen horneada ──
|
||||
const retratos = [...document.querySelectorAll('.beyond_equipo_retrato')];
|
||||
const conImagen = retratos.filter((r) => r.querySelector('img'));
|
||||
if (conImagen.length) {
|
||||
throw new Error(conImagen.length + ' de ' + retratos.length
|
||||
+ ' avatares pintan la imagen del registro; el monograma '
|
||||
+ 'que hornea Odoo lleva el color dentro y ninguna hoja '
|
||||
+ 'de estilo lo alcanza');
|
||||
}
|
||||
const bg = getComputedStyle(retratos[0]).backgroundColor;
|
||||
const tinta = getComputedStyle(retratos[0]).color;
|
||||
if (bg !== 'rgb(246, 231, 220)' || tinta !== 'rgb(152, 65, 21)') {
|
||||
throw new Error('el avatar va en durazno #F6E7DC con letra '
|
||||
+ '#984115 y está en ' + bg + ' / ' + tinta);
|
||||
}
|
||||
|
||||
// ── 2 · Naranja = acción · tinta = selección ──
|
||||
const elegido = document.querySelector('.beyond_equipo_filtro.beyond_activo')
|
||||
|| document.querySelector('.beyond_equipo_periodo.beyond_activo');
|
||||
const ce = getComputedStyle(elegido);
|
||||
if (ce.backgroundColor !== 'rgb(35, 32, 29)') {
|
||||
throw new Error('el chip elegido está en ' + ce.backgroundColor
|
||||
+ ' y va en tinta rgb(35, 32, 29)');
|
||||
}
|
||||
if (ce.color !== 'rgb(255, 255, 255)') {
|
||||
throw new Error('el texto del chip elegido va en blanco y está en '
|
||||
+ ce.color);
|
||||
}
|
||||
const nuevo = document.querySelector('.beyond_equipo_nuevo');
|
||||
if (getComputedStyle(nuevo).backgroundColor !== 'rgb(197, 90, 34)') {
|
||||
throw new Error('«Nuevo» es lo único naranja y está en '
|
||||
+ getComputedStyle(nuevo).backgroundColor);
|
||||
}
|
||||
|
||||
// ── 3 · La lista llega hasta el último renglón ──
|
||||
const cont = document.querySelector('.o_content');
|
||||
if (cont.scrollHeight <= cont.clientHeight + 1) {
|
||||
throw new Error('la lista no es más larga que la ventana: '
|
||||
+ 'esta prueba no estaría probando nada');
|
||||
}
|
||||
cont.scrollTop = cont.scrollHeight;
|
||||
await esperar(600);
|
||||
if (cont.scrollTop < 1) {
|
||||
throw new Error('el contenido mide ' + cont.scrollHeight + ' en '
|
||||
+ cont.clientHeight + ' y NO se desplaza');
|
||||
}
|
||||
const filas = document.querySelectorAll('.beyond_equipo_tabla tbody tr');
|
||||
const ultima = filas[filas.length - 1];
|
||||
const cu = ultima.getBoundingClientRect();
|
||||
const encima = document.elementFromPoint(
|
||||
Math.round(cu.left + 80), Math.round(cu.top + cu.height / 2));
|
||||
if (!encima || !ultima.contains(encima)) {
|
||||
throw new Error('el último renglón no se alcanza tras desplazar');
|
||||
}
|
||||
cont.scrollTop = 0;
|
||||
await esperar(400);
|
||||
|
||||
// ── 6 · Sin tarjeta de «Sin sucursal» ──
|
||||
const resumen = [...document.querySelectorAll('.beyond_resumen_titulo')]
|
||||
.map((s) => s.textContent.trim());
|
||||
if (resumen.some((s) => s.includes('Sin sucursal'))) {
|
||||
throw new Error('sigue la tarjeta «Sin sucursal»: ' + resumen.join(' / '));
|
||||
}
|
||||
|
||||
// ── 5 · El botón de la contraseña, en la ficha ──
|
||||
// Se abre una ficha CONOCIDA: el primer renglón depende de
|
||||
// qué haya en la base, y el botón solo aplica a quien tiene
|
||||
// celular —sin él no hay usuario que restablecer—.
|
||||
const buscador = document.querySelector('.beyond_equipo_buscador input');
|
||||
buscador.value = 'ZZ Plantilla 00';
|
||||
buscador.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
await esperar(1500);
|
||||
document.querySelector('.beyond_equipo_tabla tbody tr').click();
|
||||
await hasta('.o_beyond_persona_form');
|
||||
await esperar(2000);
|
||||
seVe('.beyond_boton_clave', '«Restablecer contraseña»');
|
||||
|
||||
// ── 4 · El nivel se puede elegir (que además GUARDA lo
|
||||
// comprueba test_el_nivel_de_acceso_se_elige_y_se_guarda) ──
|
||||
const grupo = document.querySelector('[name="beyond_acceso"]');
|
||||
const chips = [...grupo.querySelectorAll('.o_selection_badge')];
|
||||
if (chips.length !== 2) {
|
||||
throw new Error('el nivel ofrece ' + chips.length + ' opciones');
|
||||
}
|
||||
const otro = chips.find((c) => !c.classList.contains('active'));
|
||||
otro.click();
|
||||
await esperar(800);
|
||||
if (!otro.classList.contains('active')) {
|
||||
throw new Error('el chip de nivel no se puede elegir');
|
||||
}
|
||||
document.querySelector('.beyond_boton_descartar').click();
|
||||
await esperar(1200);
|
||||
console.log('test successful');
|
||||
})();
|
||||
""", "", login='direccion@beyond.example', timeout=240)
|
||||
@@ -36,54 +36,22 @@ class TestBeyondSolicitudes(BeyondChecadorCase):
|
||||
self.assertEqual(str(solicitud.jornada_id.check_in), '2026-08-10 09:30:00',
|
||||
"el supervisor puede corregir la hora propuesta")
|
||||
|
||||
def test_autocierre_autorizado_fija_salida_y_suma(self):
|
||||
def test_una_jornada_rechazada_no_suma(self):
|
||||
"""Lo que sobrevive del flujo de solicitudes.
|
||||
|
||||
La cola ya no existe: el cron cierra solo y nada puede volver a poner
|
||||
una jornada en 'rechazada'. Pero las que quedaron rechazadas siguen
|
||||
ahí —alguien decidió no reconocer esas horas— y lo que hay que
|
||||
proteger es que no empiecen a sumar por accidente. El flujo que las
|
||||
producía se retiró; el hecho que dejó, no."""
|
||||
jornada = self.Attendance.sudo().with_context(beyond_sistema=True).create({
|
||||
'employee_id': self.emp_c.id,
|
||||
'check_in': '2026-08-10 09:00:00',
|
||||
'beyond_estado': 'revision',
|
||||
'check_out': '2026-08-10 17:00:00',
|
||||
'beyond_estado': 'rechazada',
|
||||
})
|
||||
base = self.emp_c.beyond_total_horas()
|
||||
solicitud = self.env['beyond.solicitud'].sudo().create({
|
||||
'employee_id': self.emp_c.id,
|
||||
'tipo': 'autorizar_autocierre',
|
||||
'jornada_id': jornada.id,
|
||||
})
|
||||
with self.assertRaises(UserError, msg="sin salida real no se autoriza"):
|
||||
solicitud.with_user(self.admin_a).action_autorizar()
|
||||
solicitud.resolucion_salida_ts = '2026-08-10 17:00:00'
|
||||
solicitud.with_user(self.admin_a).action_autorizar()
|
||||
self.assertEqual(jornada.beyond_estado, 'cerrada')
|
||||
self.assertTrue(jornada.beyond_editada)
|
||||
self.assertAlmostEqual(self.emp_c.beyond_total_horas(), base + 8.0,
|
||||
msg="al autorizar, la jornada por fin suma")
|
||||
|
||||
def test_rechazo_marca_jornada_rechazada_sin_sumar(self):
|
||||
"""C-019: rechazar distingue la jornada de las que siguen en
|
||||
revisión; no suma, y las checadas quedan intactas."""
|
||||
entrada = self._checar(self.emp_c, self.branch_a)['checada']
|
||||
jornada = self.Attendance.sudo().search(
|
||||
[('beyond_checada_entrada_id', '=', entrada.id)])
|
||||
jornada.with_context(beyond_sistema=True).write({'beyond_estado': 'revision'})
|
||||
base = self.emp_c.beyond_total_horas()
|
||||
solicitud = self.env['beyond.solicitud'].sudo().create({
|
||||
'employee_id': self.emp_c.id,
|
||||
'tipo': 'autorizar_autocierre',
|
||||
'jornada_id': jornada.id,
|
||||
})
|
||||
solicitud.with_user(self.admin_a).action_rechazar()
|
||||
self.assertEqual(solicitud.estado, 'rechazada')
|
||||
self.assertEqual(jornada.beyond_estado, 'rechazada',
|
||||
"atendida y distinguible de 'en revisión'")
|
||||
self.assertAlmostEqual(self.emp_c.beyond_total_horas(), base,
|
||||
msg="rechazada no suma")
|
||||
self.assertTrue(jornada.exists() and entrada.exists(),
|
||||
"la jornada y su checada se conservan")
|
||||
# los filtros separan pendientes de rechazadas
|
||||
pendientes = self.Attendance.sudo().search(
|
||||
[('beyond_estado', '=', 'revision'),
|
||||
('employee_id', '=', self.emp_c.id)])
|
||||
self.assertNotIn(jornada, pendientes,
|
||||
"ya no aparece entre lo pendiente de resolver")
|
||||
self.assertEqual(jornada.beyond_horas, 8.0)
|
||||
self.assertAlmostEqual(self.emp_c.beyond_total_horas(), 0.0, places=2)
|
||||
|
||||
def test_solicitud_resuelta_no_se_reabre(self):
|
||||
solicitud = self._solicitud_olvido(self.emp_c)
|
||||
|
||||
@@ -38,10 +38,6 @@
|
||||
<field name="priority">99</field>
|
||||
<field name="arch" type="xml">
|
||||
<xpath expr="//header" position="inside">
|
||||
<button name="action_beyond_aprobar" type="object"
|
||||
string="Aprobar cuenta Beyond" class="btn-success"
|
||||
invisible="beyond_cuenta_estado != 'pendiente'"
|
||||
groups="beyond_base.beyond_group_admin_sucursal"/>
|
||||
<button name="action_beyond_baja" type="object"
|
||||
string="Dar de baja (Beyond)"
|
||||
invisible="beyond_cuenta_estado == 'baja'"
|
||||
|
||||
@@ -289,16 +289,51 @@
|
||||
<field name="name">beyond.checador.config.form</field>
|
||||
<field name="model">beyond.checador.config</field>
|
||||
<field name="arch" type="xml">
|
||||
<form string="Configuración del checador">
|
||||
<group>
|
||||
<field name="ventana_inicio"/>
|
||||
<field name="ventana_fin"/>
|
||||
<field name="qr_rotacion_seg"/>
|
||||
</group>
|
||||
<div class="text-muted">
|
||||
Fuera de la ventana no se emiten códigos y las jornadas sin
|
||||
salida pasan a revisión. La validez de cada código es la
|
||||
rotación × 2.
|
||||
<!-- Tres cosas y ninguna más: la ventana, la meta y el QR
|
||||
(ADR-018). Revestida como el resto del panel; se abre en
|
||||
diálogo desde la puerta discreta de Equipo. -->
|
||||
<form string="Configuración del checador" class="o_beyond_config_checador">
|
||||
<div class="beyond_config_bloque">
|
||||
<span class="beyond_tarjeta_titulo">Ventana del checado</span>
|
||||
<div class="beyond_config_par">
|
||||
<div class="beyond_campo">
|
||||
<span class="beyond_campo_etiqueta">Abre</span>
|
||||
<field name="ventana_inicio" nolabel="1" placeholder="06:00"/>
|
||||
</div>
|
||||
<div class="beyond_campo">
|
||||
<span class="beyond_campo_etiqueta">Cierra</span>
|
||||
<field name="ventana_fin" nolabel="1" placeholder="20:00"/>
|
||||
</div>
|
||||
</div>
|
||||
<span class="beyond_tarjeta_nota">
|
||||
Fuera de la ventana no se emiten códigos, y la jornada
|
||||
que quedó sin salida se cierra sola a la hora de
|
||||
cierre. Esas horas cuentan.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="beyond_config_bloque">
|
||||
<span class="beyond_tarjeta_titulo">Jornada esperada</span>
|
||||
<div class="beyond_campo">
|
||||
<span class="beyond_campo_etiqueta">Horas por semana</span>
|
||||
<field name="horas_semana" nolabel="1"/>
|
||||
</div>
|
||||
<span class="beyond_tarjeta_nota">
|
||||
Es la meta contra la que se compara el avance de cada
|
||||
persona en Equipo.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="beyond_config_bloque">
|
||||
<span class="beyond_tarjeta_titulo">Código QR</span>
|
||||
<div class="beyond_campo">
|
||||
<span class="beyond_campo_etiqueta">Rotación (segundos)</span>
|
||||
<field name="qr_rotacion_seg" nolabel="1"/>
|
||||
</div>
|
||||
<span class="beyond_tarjeta_nota">
|
||||
Cada código vale el doble de su rotación, para que un
|
||||
escaneo al filo del cambio no muera.
|
||||
</span>
|
||||
</div>
|
||||
<footer>
|
||||
<button name="action_guardar" type="object" string="Guardar"
|
||||
@@ -316,25 +351,20 @@
|
||||
<field name="target">new</field>
|
||||
</record>
|
||||
|
||||
<!-- ══ Menús ══ Personal es el hub de personas (Beyond → Personal):
|
||||
Jornadas cuelga directo (pregunta 3: puntualidad) y el resto del
|
||||
panel operativo queda como submenú Checador. -->
|
||||
<menuitem id="menu_jornadas" name="Jornadas"
|
||||
parent="beyond_branch.menu_personal" action="action_jornadas"
|
||||
sequence="4"
|
||||
groups="beyond_base.beyond_group_admin_sucursal"/>
|
||||
<menuitem id="menu_checador" name="Checador"
|
||||
parent="beyond_branch.menu_personal" sequence="9"
|
||||
groups="beyond_base.beyond_group_admin_sucursal"/>
|
||||
<menuitem id="menu_solicitudes" name="Cola de solicitudes"
|
||||
parent="menu_checador" action="action_solicitudes" sequence="1"/>
|
||||
<menuitem id="menu_checadas" name="Checadas crudas"
|
||||
parent="menu_checador" action="action_checadas" sequence="3"/>
|
||||
<menuitem id="menu_ajustes" name="Ajustes de horas"
|
||||
parent="menu_checador" action="action_ajustes" sequence="4"/>
|
||||
<menuitem id="menu_bitacora" name="Bitácora"
|
||||
parent="menu_checador" action="action_bitacora" sequence="6"/>
|
||||
<!-- ══ Menús ══ (25-ago-2026, ADR-018)
|
||||
De todo el panel operativo del checador solo queda la
|
||||
CONFIGURACIÓN, y como puerta discreta: Personal se reduce a Equipo,
|
||||
que es donde se trabaja. Jornadas, la cola de solicitudes, las
|
||||
checadas crudas, los ajustes y la bitácora salen del menú.
|
||||
|
||||
Sus ACCIONES se conservan a propósito, sin menú: los modelos siguen
|
||||
registrando y el historial se sigue pudiendo abrir con una URL
|
||||
directa o desde otra acción. Quitar el menú no es borrar el dato.
|
||||
|
||||
El submenú «Checador» desaparece con sus hijos: un menú con un solo
|
||||
nieto es un clic de más. -->
|
||||
<menuitem id="menu_checador_config" name="Configuración del checador"
|
||||
parent="menu_checador" action="action_checador_config" sequence="9"
|
||||
parent="beyond_branch.menu_personal" action="action_checador_config"
|
||||
sequence="90"
|
||||
groups="beyond_base.beyond_group_admin_general"/>
|
||||
</odoo>
|
||||
@@ -82,10 +82,135 @@
|
||||
</field>
|
||||
</record>
|
||||
|
||||
|
||||
<!-- ══ La ficha de la persona (ADR-013: arch propio) ══
|
||||
La lista del diseño trae estado del día y avance, y la ficha trae
|
||||
tres bloques que no son campos —avance, productividad y jornadas—,
|
||||
así que ni una ni otra son «la nativa revestida». -->
|
||||
<record id="view_beyond_ficha_empleado" model="ir.ui.view">
|
||||
<field name="name">beyond.ficha.empleado.form</field>
|
||||
<field name="model">hr.employee</field>
|
||||
<field name="arch" type="xml">
|
||||
<form string="Persona" class="o_beyond_persona_form">
|
||||
<sheet>
|
||||
<field name="active" invisible="1"/>
|
||||
<field name="beyond_portal_user_id" invisible="1"/>
|
||||
|
||||
<div class="beyond_persona_encabezado">
|
||||
<field name="image_1920" widget="beyond_image_camera"
|
||||
class="beyond_persona_retrato" nolabel="1"/>
|
||||
<div class="beyond_persona_identidad">
|
||||
<h1><field name="name" nolabel="1"
|
||||
placeholder="Nombre y apellido"/></h1>
|
||||
<div class="beyond_persona_bajo_nombre">
|
||||
<field name="beyond_cuenta_estado" nolabel="1"
|
||||
readonly="1" class="beyond_persona_estado"/>
|
||||
<span class="beyond_persona_dato">
|
||||
<field name="beyond_celular" nolabel="1" readonly="1"/>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="beyond_persona_acciones">
|
||||
<button name="%(action_beyond_employee_password)d"
|
||||
type="action" string="Restablecer contraseña"
|
||||
class="btn beyond_boton_clave"
|
||||
invisible="not beyond_celular"
|
||||
context="{'default_employee_id': id}"/>
|
||||
<button name="action_beyond_baja" type="object"
|
||||
string="Dar de baja"
|
||||
class="btn beyond_boton_baja"
|
||||
invisible="not id or not active"
|
||||
confirm="La persona deja de aparecer en las listas y su cuenta del checador deja de servir. Su historial se conserva entero. ¿Continuar?"/>
|
||||
<button name="action_beyond_reincorporar" type="object"
|
||||
string="Reincorporar" class="btn beyond_boton_clave"
|
||||
invisible="active"/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="beyond_tarjeta beyond_persona_datos">
|
||||
<span class="beyond_tarjeta_titulo">Datos</span>
|
||||
<div class="beyond_campo">
|
||||
<span class="beyond_campo_etiqueta">Celular (es su usuario)</span>
|
||||
<!-- Requerido de entrada: sin celular no hay
|
||||
cuenta, y sin cuenta no se puede checar. -->
|
||||
<field name="beyond_celular" nolabel="1"
|
||||
widget="beyond_celular_aviso" required="1"/>
|
||||
</div>
|
||||
<div class="beyond_campo">
|
||||
<span class="beyond_campo_etiqueta">Puesto</span>
|
||||
<field name="job_title" nolabel="1" placeholder="Estilista, recepción…"/>
|
||||
</div>
|
||||
<div class="beyond_campo">
|
||||
<span class="beyond_campo_etiqueta">Sucursal</span>
|
||||
<field name="branch_id" nolabel="1" class="beyond_chips"
|
||||
widget="selection_badge"/>
|
||||
</div>
|
||||
<div class="beyond_campo">
|
||||
<span class="beyond_campo_etiqueta">Nivel de acceso</span>
|
||||
<!-- Solo la dirección lo cambia: subir a alguien de
|
||||
nivel es dar acceso al sistema. -->
|
||||
<field name="beyond_acceso_ofrecido" invisible="1"/>
|
||||
<!-- Ofrece dos niveles: la dirección no se otorga
|
||||
desde aquí (ADR-018). -->
|
||||
<field name="beyond_acceso" nolabel="1"
|
||||
widget="selection_badge_with_filter"
|
||||
options="{'allowed_selection_field': 'beyond_acceso_ofrecido'}"
|
||||
class="beyond_chips"
|
||||
groups="beyond_base.beyond_group_admin_general"/>
|
||||
<field name="beyond_acceso" nolabel="1" readonly="1"
|
||||
groups="!beyond_base.beyond_group_admin_general"/>
|
||||
</div>
|
||||
<div class="beyond_campo">
|
||||
<span class="beyond_campo_etiqueta">Fecha de ingreso</span>
|
||||
<div>
|
||||
<field name="beyond_fecha_ingreso" nolabel="1" class="oe_inline"/>
|
||||
<span class="beyond_persona_antiguedad">
|
||||
<field name="beyond_antiguedad" nolabel="1" readonly="1"/>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="beyond_campo" invisible="id">
|
||||
<span class="beyond_campo_etiqueta">Contraseña inicial</span>
|
||||
<!-- Se marca requerido en la PANTALLA en vez de
|
||||
cortar el guardado con un mensaje, que es el
|
||||
mismo criterio del aviso de celular repetido:
|
||||
lo que va a hacer falta se dice antes. -->
|
||||
<field name="beyond_clave_inicial" nolabel="1"
|
||||
password="True" placeholder="Mínimo 8 caracteres"
|
||||
required="not id"/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Avance, productividad y jornadas: tres cosas que no son
|
||||
campos y que se piden juntas para que miren el mismo
|
||||
periodo. -->
|
||||
<widget name="beyond_ficha_personal"/>
|
||||
|
||||
<div class="beyond_pie_acciones">
|
||||
<widget name="beyond_form_footer"/>
|
||||
</div>
|
||||
</sheet>
|
||||
</form>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="action_equipo_panel" model="ir.actions.client">
|
||||
<field name="name">Equipo</field>
|
||||
<field name="tag">beyond_equipo</field>
|
||||
</record>
|
||||
|
||||
<record id="action_equipo_form" model="ir.actions.act_window.view">
|
||||
<field name="sequence" eval="2"/>
|
||||
<field name="view_mode">form</field>
|
||||
<field name="view_id" ref="view_beyond_ficha_empleado"/>
|
||||
<field name="act_window_id" ref="action_equipo"/>
|
||||
</record>
|
||||
|
||||
<!-- El menú abre la PANTALLA de equipo; la acción de ventana sigue
|
||||
viva y es la que abre la ficha desde un renglón. -->
|
||||
<menuitem id="menu_equipo" name="Equipo"
|
||||
parent="beyond_branch.menu_personal" action="action_equipo"
|
||||
parent="beyond_branch.menu_personal" action="action_equipo_panel"
|
||||
sequence="1"/>
|
||||
<menuitem id="menu_hoy" name="Hoy: sin entrada"
|
||||
parent="beyond_branch.menu_personal" action="action_hoy_sin_entrada"
|
||||
sequence="2"/>
|
||||
<!-- «Hoy: sin entrada» deja de ser una pantalla propia: es un filtro
|
||||
de Equipo, con su contador (ADR-018). La acción se conserva. -->
|
||||
</odoo>
|
||||
@@ -9,24 +9,31 @@ Cimientos del sistema Beyond (BRIEF §4 y §6):
|
||||
administrador de sucursal y empleado. Las reglas de registro (ir.rule)
|
||||
que aíslan datos por sucursal llegan en Fase 1 junto con beyond_branch.
|
||||
- Branding: nombre "Beyond" de la instancia, identidad visual v1 definida
|
||||
por Collina (paleta y tipografía Manrope autoalojada) y el lanzador de
|
||||
aplicaciones a pantalla completa (ADR-005).
|
||||
por Collina (paleta y tipografía Manrope autoalojada), el lanzador de
|
||||
aplicaciones a pantalla completa (ADR-005) y la pantalla de inicio de
|
||||
sesión, que hereda web.login sin tocar ni el formulario ni la ruta.
|
||||
|
||||
Depende de hr/hr_attendance porque el rol "empleado" se define sobre
|
||||
empleados y asistencias, y las ir.rule de Fase 1 para esos modelos
|
||||
vivirán en este módulo.
|
||||
vivirán en este módulo. Depende de auth_signup (LGPL, el core lo
|
||||
auto-instala igual) para fijar el orden de herencia sobre web.login: el
|
||||
enlace de "¿Olvidaste tu contraseña?" es el suyo, con su condición real.
|
||||
""",
|
||||
'version': '19.0.0.1.0',
|
||||
'category': 'Beyond',
|
||||
'author': 'Collina Systems',
|
||||
'license': 'Other proprietary',
|
||||
'depends': ['base', 'web', 'hr', 'hr_attendance'],
|
||||
'depends': ['base', 'web', 'auth_signup', 'hr', 'hr_attendance'],
|
||||
'data': [
|
||||
'security/beyond_security.xml',
|
||||
'data/branding.xml',
|
||||
'data/bootstrap_admin.xml',
|
||||
'data/menu_cleanup.xml',
|
||||
'data/idioma.xml',
|
||||
'data/silencio_saliente.xml',
|
||||
'data/url_publica.xml',
|
||||
'data/signup.xml',
|
||||
'views/login_templates.xml',
|
||||
],
|
||||
'demo': [
|
||||
'demo/demo_empleados.xml',
|
||||
@@ -36,9 +43,41 @@ vivirán en este módulo.
|
||||
('prepend', 'beyond_base/static/src/scss/beyond_variables.scss'),
|
||||
],
|
||||
'web.assets_backend': [
|
||||
'beyond_base/static/src/scss/beyond_fonts.scss',
|
||||
# La casa compartida va ANTES que quienes la llaman.
|
||||
'beyond_base/static/src/webclient/beyond_casa.xml',
|
||||
'beyond_base/static/src/webclient/beyond_launcher.scss',
|
||||
'beyond_base/static/src/webclient/beyond_launcher.js',
|
||||
'beyond_base/static/src/webclient/beyond_launcher.xml',
|
||||
# Barra superior del Panel General (ADR-013). El SCSS que la
|
||||
# viste NO va aquí sino en beyond_branch, que es el módulo dueño
|
||||
# del panel: beyond_base no puede importar variables de un módulo
|
||||
# que depende de él. La barra solo se enciende dentro de la app
|
||||
# beyond_branch.menu_beyond_root, así que nunca puede quedar sin
|
||||
# estilo.
|
||||
'beyond_base/static/src/webclient/beyond_panel_navbar.js',
|
||||
'beyond_base/static/src/webclient/beyond_panel_navbar.xml',
|
||||
# Widgets de campo reutilizables. Su SCSS vive en beyond_branch
|
||||
# con el resto de los tokens del panel, por el mismo motivo que
|
||||
# el de la barra.
|
||||
'beyond_base/static/src/fields/beyond_image_camera.js',
|
||||
'beyond_base/static/src/fields/beyond_image_camera.xml',
|
||||
'beyond_base/static/src/fields/beyond_al_guardar.js',
|
||||
'beyond_base/static/src/fields/beyond_al_guardar.xml',
|
||||
'beyond_base/static/src/fields/beyond_form_footer.js',
|
||||
'beyond_base/static/src/fields/beyond_form_footer.xml',
|
||||
'beyond_base/static/src/fields/beyond_avatar_initials.js',
|
||||
'beyond_base/static/src/fields/beyond_avatar_initials.xml',
|
||||
],
|
||||
'web.assets_unit_tests': [
|
||||
'beyond_base/static/tests/**/*.test.js',
|
||||
],
|
||||
# The login screen renders before there is a session: it gets the
|
||||
# frontend bundle and nothing else, so the face travels with it.
|
||||
'web.assets_frontend': [
|
||||
'beyond_base/static/src/scss/beyond_fonts.scss',
|
||||
'beyond_base/static/src/login/beyond_login.scss',
|
||||
'beyond_base/static/src/login/beyond_login.js',
|
||||
],
|
||||
},
|
||||
'installable': True,
|
||||
|
||||
@@ -1,7 +1,23 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<!-- Branding mínimo Fase 0: la instancia se llama Beyond. -->
|
||||
<record id="base.main_company" model="res.company">
|
||||
<field name="name">Beyond</field>
|
||||
</record>
|
||||
<!--
|
||||
La empresa matriz se llama Look Capital; la INSTANCIA se llama
|
||||
Beyond (lanzador y pantalla de inicio de sesión). El Panel General
|
||||
muestra el nombre de la compañía bajo el título y lo lee de aquí:
|
||||
res.company.name, nunca escrito en duro.
|
||||
|
||||
ESTE ARCHIVO POSEE EL NOMBRE DE LA COMPAÑÍA. Renombrarla desde
|
||||
Ajustes queda revertido en el siguiente arranque, porque la función
|
||||
corre en cada actualización de módulos. Ajustes es solo de Collina,
|
||||
así que no estorba a nadie del cliente; queda escrito para que a
|
||||
quien lo intente no le parezca un fantasma.
|
||||
|
||||
Va por <function> y no por <record>: base.main_company está marcado
|
||||
noupdate y el core salta en silencio los <record> sobre xmlids
|
||||
noupdate al ACTUALIZAR un módulo — que es justo lo que hace cada
|
||||
arranque en producción. El <record> que vivía aquí solo se aplicó en
|
||||
instalaciones limpias. Mismo mecanismo que data/pricelist_feature.xml
|
||||
de beyond_branch (ADR-009). Ver models/res_company.py.
|
||||
-->
|
||||
<function model="res.company" name="_beyond_arranque_nombre"/>
|
||||
</odoo>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<odoo>
|
||||
<!-- Alta pública cerrada en cada actualización (que en producción corre en
|
||||
cada arranque): /web/signup sin invitación devuelve 404 y un POST sin
|
||||
token no crea usuario. El alta CON invitación no se toca — es la vía
|
||||
del aprovisionador (ADR-008). Ver models/res_users.py. -->
|
||||
<function model="res.users" name="_beyond_arranque_alta_publica"/>
|
||||
</odoo>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<odoo>
|
||||
<!-- Los resúmenes por correo, la cola de SMS y la de cartas físicas
|
||||
quedan apagados en cada actualización (que en producción corre en
|
||||
cada arranque). Llegaron instalados por dependencia y nadie los
|
||||
pidió; el boletín venía activado con la cuenta de dirección entre
|
||||
sus destinatarios. Reversible por parámetro, ver
|
||||
models/ir_cron.py y docs/despliegue.md. -->
|
||||
<function model="ir.cron" name="_beyond_arranque_silencio_saliente"/>
|
||||
</odoo>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<odoo>
|
||||
<!-- La dirección pública queda congelada en cada arranque. De fábrica
|
||||
Odoo la sobrescribe con la dirección desde la que entró el último
|
||||
administrador, y el QR del kiosco se arma con ella: una entrada por
|
||||
la IP en vez del dominio deja a los empleados sin poder checar.
|
||||
Reversible por parámetro, ver models/ir_config_parameter.py. -->
|
||||
<function model="ir.config_parameter" name="_beyond_arranque_url_publica"/>
|
||||
</odoo>
|
||||
@@ -1,2 +1,6 @@
|
||||
from . import ir_config_parameter
|
||||
from . import ir_cron
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
from . import res_company
|
||||
from . import res_lang
|
||||
from . import res_users
|
||||
@@ -0,0 +1,78 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
import logging
|
||||
|
||||
from odoo import api, models
|
||||
|
||||
from odoo.addons.beyond_base.tools.arranque import ejecutar_en_arranque
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
BASE_URL = 'web.base.url'
|
||||
CONGELADOR = 'web.base.url.freeze'
|
||||
|
||||
# Si algún día hay que mover el sistema de dirección, se pone la nueva aquí y
|
||||
# el siguiente arranque la escribe y la vuelve a congelar. Ver docs/despliegue.md.
|
||||
PARAMETRO_URL = 'beyond.url_publica'
|
||||
|
||||
# Escotilla de salida: con esto puesto, el arranque descongela y Odoo vuelve a
|
||||
# su comportamiento de fábrica (adivinar la dirección en cada inicio de sesión).
|
||||
PARAMETRO_LIBRE = 'beyond.url_publica_libre'
|
||||
|
||||
|
||||
class IrConfigParameter(models.Model):
|
||||
_inherit = 'ir.config_parameter'
|
||||
|
||||
@api.model
|
||||
def _beyond_arranque_url_publica(self):
|
||||
"""Entrada desde la carga de módulos (data/url_publica.xml)."""
|
||||
return ejecutar_en_arranque(
|
||||
self.env, 'Dirección pública congelada',
|
||||
self._beyond_congelar_url_publica)
|
||||
|
||||
@api.model
|
||||
def _beyond_congelar_url_publica(self):
|
||||
"""Impide que la dirección pública del sistema cambie sola.
|
||||
|
||||
De fábrica, Odoo sobrescribe `web.base.url` con la dirección desde la
|
||||
que entró el último administrador. Eso no es cosmético aquí: el QR del
|
||||
kiosco se arma con ese valor —`{base}/beyond/checada/{token}`, en
|
||||
`beyond_checada._estado_kiosco`— y también la dirección del kiosco de
|
||||
cada sucursal. Si un administrador entra por la IP en vez de por el
|
||||
dominio, el QR de la pantalla apunta a un sitio que el teléfono del
|
||||
empleado no abre, y nadie puede checar. Operación parada por un
|
||||
inicio de sesión.
|
||||
|
||||
Idempotente y reversible: con `beyond.url_publica_libre` puesto,
|
||||
descongela y deja a Odoo hacer lo suyo.
|
||||
"""
|
||||
params = self.sudo()
|
||||
if params.get_param(PARAMETRO_LIBRE):
|
||||
if params.get_param(CONGELADOR):
|
||||
params.set_param(CONGELADOR, False)
|
||||
_logger.warning(
|
||||
'Beyond · dirección pública descongelada por decisión '
|
||||
'explícita (%s): Odoo vuelve a reescribirla sola en cada '
|
||||
'inicio de sesión de un administrador.', PARAMETRO_LIBRE)
|
||||
return None
|
||||
|
||||
cambios = None
|
||||
deseada = params.get_param(PARAMETRO_URL)
|
||||
actual = params.get_param(BASE_URL)
|
||||
if deseada and deseada != actual:
|
||||
params.set_param(BASE_URL, deseada)
|
||||
_logger.warning(
|
||||
'Beyond · dirección pública cambiada de «%s» a «%s» por el '
|
||||
'parámetro %s.', actual, deseada, PARAMETRO_URL)
|
||||
actual = deseada
|
||||
cambios = actual
|
||||
|
||||
if not params.get_param(CONGELADOR):
|
||||
params.set_param(CONGELADOR, '1')
|
||||
_logger.warning(
|
||||
'Beyond · dirección pública congelada en «%s». Los QR del '
|
||||
'checador se arman con ella, así que ya no cambia sola cuando '
|
||||
'un administrador entra desde otra dirección. Si ese valor no '
|
||||
'es el correcto, ver docs/despliegue.md.', actual)
|
||||
cambios = actual
|
||||
|
||||
return cambios
|
||||
@@ -0,0 +1,201 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
"""Nada sale de Beyond sin que el Director lo haya autorizado.
|
||||
|
||||
Odoo llegó con una docena de canales de salida que nadie pidió: llegaron
|
||||
instalados como dependencia de módulos que sí usamos. El inventario completo
|
||||
—qué manda cada uno, a dónde y con qué frecuencia— está en
|
||||
`docs/inventario_automatismos.md`.
|
||||
|
||||
Aquí se apagan todos, **por dato y en cada arranque**. Apagarlos a mano una
|
||||
vez no sirve: sobrevive en esa base y en ninguna otra, y una actualización
|
||||
puede reactivar los datos del módulo. Es la lección del IVA (ADR-010).
|
||||
|
||||
Para volver a abrir uno, se pone su clave en `beyond.salidas_permitidas`
|
||||
—separadas por coma— y el siguiente arranque lo respeta. No hace falta tocar
|
||||
código ni desplegar. La lista de claves está en SALIDAS, y el procedimiento
|
||||
en `docs/despliegue.md`.
|
||||
"""
|
||||
import logging
|
||||
from collections import namedtuple
|
||||
|
||||
from odoo import api, models
|
||||
|
||||
from odoo.addons.beyond_base.tools.arranque import ejecutar_en_arranque
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# La llave maestra: claves separadas por coma. Vacío = todo apagado.
|
||||
PARAMETRO_PERMITIDAS = 'beyond.salidas_permitidas'
|
||||
|
||||
# Nombres anteriores, honrados para que lo ya documentado siga sirviendo.
|
||||
ALIAS = {
|
||||
'beyond.resumenes_por_correo': ('boletin', 'sms', 'cartas'),
|
||||
'beyond.telemetria_odoo': ('telemetria',),
|
||||
}
|
||||
|
||||
# tipo 'cron' → se desactiva la tarea programada con ese xmlid
|
||||
# tipo 'parametro' → se retira ese parámetro de sistema
|
||||
# tipo 'especial' → lo resuelve un método aparte, abajo
|
||||
Salida = namedtuple('Salida', 'clave etiqueta tipo objetivo')
|
||||
|
||||
SALIDAS = (
|
||||
# --- Correo que se manda solo ---
|
||||
Salida('cola_de_correo', 'Gestor de la cola de correo saliente',
|
||||
'cron', 'mail.ir_cron_mail_scheduler_action'),
|
||||
Salida('boletin', 'Boletín «resumen periódico» con métricas del negocio',
|
||||
'cron', 'digest.ir_cron_digest_scheduler_action'),
|
||||
Salida('recordatorio_logins',
|
||||
'Recordatorio con los logins de empleados que aún no han entrado',
|
||||
'cron', 'auth_signup.ir_cron_auth_signup_send_pending_user_reminder'),
|
||||
Salida('facturas_por_correo', 'Envío automático de facturas por correo',
|
||||
'cron', 'account.ir_cron_account_move_send'),
|
||||
Salida('contratos_por_vencer',
|
||||
'Aviso de contratos y permisos de trabajo por vencer',
|
||||
'cron', 'hr.ir_cron_data_employee_notify_expiring_contract_work_permit'),
|
||||
Salida('certificaciones', 'Actividades por certificaciones faltantes',
|
||||
'cron', 'hr_skills.hr_job_skills_cron_add_certification_activity_to_employees'),
|
||||
|
||||
# --- Otros canales ---
|
||||
Salida('sms', 'Cola de SMS', 'cron', 'sms.ir_cron_sms_scheduler_action'),
|
||||
Salida('cartas', 'Cola de cartas físicas', 'cron', 'snailmail.snailmail_print'),
|
||||
Salida('telemetria', 'Reporte semanal a los servidores de Odoo',
|
||||
'cron', 'mail.ir_cron_module_update_notification'),
|
||||
Salida('push', 'Notificaciones push al navegador',
|
||||
'cron', 'mail.ir_cron_web_push_notification'),
|
||||
Salida('mensajes_programados', 'Publicación de mensajes programados',
|
||||
'cron', 'mail.ir_cron_post_scheduled_message'),
|
||||
Salida('mensajes_programados', 'Notificación de mensajes programados',
|
||||
'cron', 'mail.ir_cron_send_scheduled_message'),
|
||||
|
||||
# --- Puertas que no son tareas programadas ---
|
||||
# El correo de «¿Olvidaste tu contraseña?» se manda con force_send, o sea
|
||||
# que NO pasa por la cola: apagar la cola no lo detiene. Retirar este
|
||||
# parámetro cierra la ruta y, de paso, el enlace desaparece solo de la
|
||||
# pantalla de acceso (`beyond_base/views/login_templates.xml` ya lo pinta
|
||||
# con t-if). Encaja con ADR-008: las contraseñas las entrega el director
|
||||
# en persona.
|
||||
Salida('restablecer_contrasena',
|
||||
'Restablecer contraseña por correo desde la pantalla de acceso',
|
||||
'parametro', 'auth_signup.reset_password'),
|
||||
# Cada usuario interno traía «avisarme por correo» en vez de «avisarme
|
||||
# dentro del sistema». Los avisos de historial también se mandan con
|
||||
# force_send. Con 'inbox' la información no se pierde: llega a la bandeja
|
||||
# de la aplicación.
|
||||
Salida('chatter_por_correo',
|
||||
'Avisos de historial por correo en vez de la bandeja interna',
|
||||
'especial', 'notificacion_interna'),
|
||||
# Mientras exista, cada empleado nuevo entra solo a la lista del boletín.
|
||||
Salida('boletin', 'Suscripción automática de empleados nuevos al boletín',
|
||||
'especial', 'suscripcion_boletin'),
|
||||
# El boletín es un dato aparte de su tarea: apagar solo el cron lo dejaría
|
||||
# armado para el día que alguien reactive la tarea.
|
||||
Salida('boletin', 'Boletines configurados', 'especial', 'boletines'),
|
||||
)
|
||||
|
||||
|
||||
class IrCron(models.Model):
|
||||
_inherit = 'ir.cron'
|
||||
|
||||
@api.model
|
||||
def _beyond_arranque_silencio_saliente(self):
|
||||
"""Entrada desde la carga de módulos (data/silencio_saliente.xml)."""
|
||||
return ejecutar_en_arranque(
|
||||
self.env, 'Comunicación saliente que nadie pidió',
|
||||
self._beyond_silenciar_salidas)
|
||||
|
||||
@api.model
|
||||
def _beyond_salidas_permitidas(self):
|
||||
"""Las claves que el Director autorizó explícitamente."""
|
||||
params = self.env['ir.config_parameter'].sudo()
|
||||
permitidas = {
|
||||
clave.strip()
|
||||
for clave in (params.get_param(PARAMETRO_PERMITIDAS) or '').split(',')
|
||||
if clave.strip()
|
||||
}
|
||||
for parametro, claves in ALIAS.items():
|
||||
if params.get_param(parametro):
|
||||
permitidas.update(claves)
|
||||
return permitidas
|
||||
|
||||
@api.model
|
||||
def _beyond_silenciar_salidas(self):
|
||||
"""Apaga toda salida no autorizada. Idempotente: si ya está apagada,
|
||||
no escribe. Devuelve lo que apagó en esta pasada."""
|
||||
permitidas = self._beyond_salidas_permitidas()
|
||||
apagadas = []
|
||||
for salida in SALIDAS:
|
||||
if salida.clave in permitidas:
|
||||
continue
|
||||
if getattr(self, f'_beyond_apagar_{salida.tipo}')(salida):
|
||||
apagadas.append(salida.etiqueta)
|
||||
|
||||
if apagadas:
|
||||
_logger.warning(
|
||||
'Beyond · silenciada la comunicación saliente que nadie pidió: '
|
||||
'%s. Reversible añadiendo su clave a %s (ver '
|
||||
'docs/despliegue.md).', ', '.join(apagadas), PARAMETRO_PERMITIDAS)
|
||||
if permitidas:
|
||||
_logger.info(
|
||||
'Beyond · salidas autorizadas explícitamente y por tanto '
|
||||
'respetadas: %s.', ', '.join(sorted(permitidas)))
|
||||
return apagadas
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Los tres mecanismos
|
||||
# ------------------------------------------------------------------
|
||||
@api.model
|
||||
def _beyond_apagar_cron(self, salida):
|
||||
tarea = self.env.ref(salida.objetivo, raise_if_not_found=False)
|
||||
if tarea and tarea.sudo().active:
|
||||
tarea.sudo().active = False
|
||||
return True
|
||||
return False
|
||||
|
||||
@api.model
|
||||
def _beyond_apagar_parametro(self, salida):
|
||||
params = self.env['ir.config_parameter'].sudo()
|
||||
if params.get_param(salida.objetivo):
|
||||
# set_param con False borra el parámetro, que es como Odoo
|
||||
# entiende «no».
|
||||
params.set_param(salida.objetivo, False)
|
||||
return True
|
||||
return False
|
||||
|
||||
@api.model
|
||||
def _beyond_apagar_especial(self, salida):
|
||||
return getattr(self, f'_beyond_apagar_{salida.objetivo}')()
|
||||
|
||||
@api.model
|
||||
def _beyond_apagar_suscripcion_boletin(self):
|
||||
params = self.env['ir.config_parameter'].sudo()
|
||||
if params.get_param('digest.default_digest_emails'):
|
||||
params.set_param('digest.default_digest_emails', False)
|
||||
return True
|
||||
return False
|
||||
|
||||
@api.model
|
||||
def _beyond_apagar_boletines(self):
|
||||
if 'digest.digest' not in self.env:
|
||||
return False
|
||||
boletines = self.env['digest.digest'].sudo().search(
|
||||
[('state', '=', 'activated')])
|
||||
if boletines:
|
||||
boletines.write({'state': 'deactivated'})
|
||||
return True
|
||||
return False
|
||||
|
||||
@api.model
|
||||
def _beyond_apagar_notificacion_interna(self):
|
||||
"""Los avisos de historial llegan a la bandeja, no al correo.
|
||||
|
||||
Solo usuarios internos: Odoo exige que los de portal sigan en
|
||||
'email', y de todos modos no tienen bandeja donde recibirlos.
|
||||
"""
|
||||
usuarios = self.env['res.users'].sudo().search([
|
||||
('share', '=', False),
|
||||
('notification_type', '=', 'email'),
|
||||
])
|
||||
if usuarios:
|
||||
usuarios.write({'notification_type': 'inbox'})
|
||||
return True
|
||||
return False
|
||||
@@ -0,0 +1,103 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
import logging
|
||||
|
||||
from odoo import api, models
|
||||
|
||||
from odoo.addons.beyond_base.tools.arranque import ejecutar_en_arranque
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# La empresa matriz se llama Look Capital (24-ago-2026). La INSTANCIA sigue
|
||||
# llamándose Beyond: es el nombre del sistema, no el de la razón social, y
|
||||
# vive en el lanzador y en la pantalla de inicio de sesión. Este archivo
|
||||
# posee el nombre de la compañía; el Panel General lo lee de aquí
|
||||
# (res.company.name) y nunca lo escribe en duro.
|
||||
NOMBRE_COMPANIA = 'Look Capital'
|
||||
|
||||
# Odoo's sample contact details for the main company, written by
|
||||
# base/data/res_users_demo.xml. They are not decoration: the POS receipt
|
||||
# footer prints the company address, VAT, phone, e-mail and website
|
||||
# (point_of_sale OrderReceipt), so a branch that has not been configured
|
||||
# hands the customer a ticket pointing at 8000 Marina Blvd, Brisbane.
|
||||
#
|
||||
# Each field lists every spelling the sample value can have; `website` is
|
||||
# stored normalised, so the value written by the core and the value Odoo
|
||||
# saves are not the same string.
|
||||
#
|
||||
# NOT the company name: that one is owned above and always ends up as
|
||||
# NOMBRE_COMPANIA. NOT country_id or state_id either — clearing those would
|
||||
# change how taxes and addresses behave, which is a decision of its own.
|
||||
DATOS_DE_MUESTRA = {
|
||||
'street': {'8000 Marina Blvd, Suite 300'},
|
||||
'street2': {'Suite 300'},
|
||||
'city': {'Brisbane'},
|
||||
'zip': {'94005'},
|
||||
'phone': {'+1 555-555-5556'},
|
||||
'email': {'info@yourcompany.com'},
|
||||
'website': {'www.example.com', 'http://www.example.com',
|
||||
'https://www.example.com'},
|
||||
}
|
||||
|
||||
|
||||
class ResCompany(models.Model):
|
||||
_inherit = 'res.company'
|
||||
|
||||
@api.model
|
||||
def _beyond_arranque_nombre(self):
|
||||
"""Entrada desde la carga de módulos (data/branding.xml). Va envuelta: una
|
||||
tarea de arranque degrada, nunca tumba el servidor."""
|
||||
return ejecutar_en_arranque(
|
||||
self.env, 'Nombre de la compañía matriz', self._beyond_asegurar_nombre)
|
||||
|
||||
@api.model
|
||||
def _beyond_asegurar_nombre(self):
|
||||
"""Fija el nombre de la compañía matriz.
|
||||
|
||||
Por función y no por <record>: base.main_company está marcado
|
||||
noupdate en ir.model.data, y el core SALTA EN SILENCIO todo <record>
|
||||
sobre un xmlid noupdate cuando el módulo se ACTUALIZA — que es lo que
|
||||
hace cada arranque en producción. El <record> que estuvo aquí hasta
|
||||
hoy solo se aplicó en instalaciones limpias; en cualquier base que
|
||||
haya nacido antes, el nombre quedó como estuviera y nadie se enteró.
|
||||
Mismo mecanismo y misma razón que data/pricelist_feature.xml (ADR-009).
|
||||
|
||||
Idempotente y silenciosa: solo escribe si el nombre difiere. Corre en
|
||||
cada arranque y un write incondicional dejaría rastro en write_date y
|
||||
en el seguimiento del registro en cada despliegue, sin motivo.
|
||||
"""
|
||||
compania = self.env.ref('base.main_company').sudo()
|
||||
if compania.name != NOMBRE_COMPANIA:
|
||||
compania.write({'name': NOMBRE_COMPANIA})
|
||||
self._beyond_limpiar_datos_de_muestra(compania)
|
||||
return True
|
||||
|
||||
@api.model
|
||||
def _beyond_limpiar_datos_de_muestra(self, compania):
|
||||
"""Clear the sample contact details Odoo ships, and only those.
|
||||
|
||||
The POS receipt footer prints the company address and contact block,
|
||||
so an unconfigured deployment gives customers a ticket with Odoo's
|
||||
demo address on it. Empty is the honest state: the footer simply
|
||||
omits every field it does not have.
|
||||
|
||||
The comparison is exact and per field. A value that is not literally
|
||||
one of Odoo's sample strings is real data somebody typed and is never
|
||||
touched — including a real address that happens to be in Brisbane.
|
||||
Idempotent: once cleared there is nothing left to match, so later
|
||||
boots write nothing.
|
||||
|
||||
Deliberately narrow: this does not try to detect "looks like sample
|
||||
data". Guessing would eventually delete a real address, and there is
|
||||
no undo for that.
|
||||
"""
|
||||
borrar = {campo: False
|
||||
for campo, muestras in DATOS_DE_MUESTRA.items()
|
||||
if (compania[campo] or '') in muestras}
|
||||
if borrar:
|
||||
_logger.warning(
|
||||
'Beyond · %s tenía datos de contacto de muestra de Odoo (%s). '
|
||||
'Se vacían: el pie del ticket del punto de venta los imprime. '
|
||||
'Captura los reales en Ajustes cuando los tengas.',
|
||||
compania.name, ', '.join(sorted(borrar)))
|
||||
compania.write(borrar)
|
||||
return borrar
|
||||
@@ -0,0 +1,51 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
from odoo import api, models
|
||||
|
||||
from odoo.addons.beyond_base.tools.arranque import ejecutar_en_arranque
|
||||
|
||||
# auth_signup se instala solo (auto_install) y llega con la puerta abierta: sus
|
||||
# datos ponen auth_signup.invitation_scope en 'b2c' — "Free sign up" —, que deja
|
||||
# /web/signup accesible a cualquiera que teclee la URL. En un ERP de personal de
|
||||
# sucursal eso es un alta de cuenta sin invitación contra el sistema que lleva
|
||||
# la caja. A Beyond se entra dado de alta por la administración (ADR-008).
|
||||
#
|
||||
# Con 'b2b' Odoo cierra las dos puertas por su cuenta: la ruta /web/signup sin
|
||||
# token devuelve 404, y _signup_create_user levanta SignupError si alguien
|
||||
# postea sin invitación. No se toca ni la ruta ni el controlador; se le da al
|
||||
# core el valor con el que ya sabe defenderse.
|
||||
#
|
||||
# El alta CON invitación sigue funcionando, y tiene que seguir: es la vía por la
|
||||
# que el aprovisionador manda el correo de bienvenida al dar de alta a alguien.
|
||||
ALTA_SOLO_POR_INVITACION = 'b2b'
|
||||
|
||||
PARAMETRO_ALTA = 'auth_signup.invitation_scope'
|
||||
|
||||
|
||||
class ResUsers(models.Model):
|
||||
_inherit = 'res.users'
|
||||
|
||||
@api.model
|
||||
def _beyond_arranque_alta_publica(self):
|
||||
"""Entrada desde la carga de módulos (data/signup.xml). Va envuelta: una
|
||||
tarea de arranque degrada, nunca tumba el servidor (ADR-011)."""
|
||||
return ejecutar_en_arranque(
|
||||
self.env, 'Alta pública cerrada', self._beyond_cerrar_alta_publica)
|
||||
|
||||
@api.model
|
||||
def _beyond_cerrar_alta_publica(self):
|
||||
"""Deja el alta pública cerrada en cualquier despliegue.
|
||||
|
||||
Corre en cada actualización del módulo, que en producción corre en cada
|
||||
arranque: el candado no depende de que alguien se acuerde de tocar el
|
||||
interruptor en Ajustes, y una base restaurada o clonada llega cerrada
|
||||
sola. Idempotente: si ya está cerrada no escribe nada.
|
||||
|
||||
Que se reafirme en cada actualización es lo que se quiere. Si el día de
|
||||
mañana Beyond decide abrir el alta pública, la decisión se toma aquí y
|
||||
queda en el repositorio, no en un clic que la siguiente actualización
|
||||
deshace sin que nadie se entere.
|
||||
"""
|
||||
parametros = self.env['ir.config_parameter'].sudo()
|
||||
if parametros.get_param(PARAMETRO_ALTA) != ALTA_SOLO_POR_INVITACION:
|
||||
parametros.set_param(PARAMETRO_ALTA, ALTA_SOLO_POR_INVITACION)
|
||||
return True
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 20 KiB |
@@ -0,0 +1,86 @@
|
||||
/** Part of Beyond. Collina Systems proprietary module. */
|
||||
import { Component } from "@odoo/owl";
|
||||
import { registry } from "@web/core/registry";
|
||||
import { standardFieldProps } from "@web/views/fields/standard_field_props";
|
||||
import { useService } from "@web/core/utils/hooks";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
|
||||
/**
|
||||
* A field the system fills in, never the person.
|
||||
*
|
||||
* BRIEF §5.3 asks that adding a branch be «as easy as adding a row»: the user
|
||||
* types name, address, city and phone, and the provisioner creates the code,
|
||||
* the warehouse, the point of sale and the kiosk URL on save. The design shows
|
||||
* those four columns in the new row as grey legends — «se asigna al guardar» —
|
||||
* and the wording matters less than the fact that THEY ARE NEVER INPUTS. A
|
||||
* readonly field in an editable list renders as an empty cell, which reads as
|
||||
* something the user forgot to fill in.
|
||||
*
|
||||
* This widget renders the value once it exists, and the legend while it does
|
||||
* not. It takes the legend from the view, so the same widget serves «se asigna
|
||||
* al guardar» for a code and «se crea al guardar» for a warehouse.
|
||||
*
|
||||
* <field name="code" widget="beyond_al_guardar"
|
||||
* options="{'leyenda': 'se asigna al guardar'}"/>
|
||||
*
|
||||
* With `copiar` it also offers to copy the value, which is what the kiosk URL
|
||||
* needs in the list: long, truncated, and useless if it cannot be copied.
|
||||
*/
|
||||
export class BeyondAlGuardar extends Component {
|
||||
static template = "beyond_base.AlGuardar";
|
||||
// Declaradas, no solo extraídas: OWL valida las props en desarrollo y
|
||||
// una clave no declarada tumba el componente entero con «unknown key».
|
||||
static props = {
|
||||
...standardFieldProps,
|
||||
leyenda: { type: String, optional: true },
|
||||
copiar: { type: Boolean, optional: true },
|
||||
};
|
||||
|
||||
setup() {
|
||||
this.notification = useService("notification");
|
||||
}
|
||||
|
||||
get valor() {
|
||||
const dato = this.props.record.data[this.props.name];
|
||||
if (!dato) {
|
||||
return "";
|
||||
}
|
||||
// Un many2one llega como registro; lo demás, tal cual.
|
||||
return typeof dato === "object" ? dato.display_name || "" : String(dato);
|
||||
}
|
||||
|
||||
get leyenda() {
|
||||
return this.props.leyenda || _t("se asigna al guardar");
|
||||
}
|
||||
|
||||
get puedeCopiar() {
|
||||
return this.props.copiar && !!this.valor;
|
||||
}
|
||||
|
||||
async copiar() {
|
||||
await navigator.clipboard.writeText(this.valor);
|
||||
this.notification.add(_t("Copiado"), { type: "success" });
|
||||
}
|
||||
}
|
||||
|
||||
registry.category("fields").add("beyond_al_guardar", {
|
||||
component: BeyondAlGuardar,
|
||||
displayName: _t("Lo asigna el sistema"),
|
||||
supportedTypes: ["char", "many2one"],
|
||||
supportedOptions: [
|
||||
{
|
||||
label: _t("Leyenda mientras no hay valor"),
|
||||
name: "leyenda",
|
||||
type: "string",
|
||||
},
|
||||
{
|
||||
label: _t("Ofrecer copiar el valor"),
|
||||
name: "copiar",
|
||||
type: "boolean",
|
||||
},
|
||||
],
|
||||
extractProps: ({ options }) => ({
|
||||
leyenda: options.leyenda,
|
||||
copiar: !!options.copiar,
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
<!-- Una sola raíz, con su clase. Sin ella la plantilla devolvía dos o tres
|
||||
nodos sueltos, el envoltorio de Odoo se quedaba en cero de ancho y el
|
||||
botón de copiar acababa fuera de la celda, recortado e inalcanzable. -->
|
||||
<t t-name="beyond_base.AlGuardar">
|
||||
<div class="beyond_al_guardar">
|
||||
<span t-if="valor" class="beyond_al_guardar_valor" t-att-title="valor" t-esc="valor"/>
|
||||
<span t-else="" class="beyond_al_guardar_leyenda" t-esc="leyenda"/>
|
||||
<button t-if="puedeCopiar" class="beyond_al_guardar_copiar"
|
||||
t-on-click.stop="copiar" title="Copiar" aria-label="Copiar">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" aria-hidden="true">
|
||||
<rect x="8" y="8" width="12" height="12" rx="2.4" stroke="currentColor" stroke-width="1.8"/>
|
||||
<path d="M16 8V5.6A1.6 1.6 0 0 0 14.4 4H5.6A1.6 1.6 0 0 0 4 5.6v8.8A1.6 1.6 0 0 0 5.6 16H8" stroke="currentColor" stroke-width="1.8"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</t>
|
||||
</templates>
|
||||
@@ -0,0 +1,75 @@
|
||||
/** Part of Beyond. Collina Systems proprietary module. */
|
||||
import { Component } from "@odoo/owl";
|
||||
import { registry } from "@web/core/registry";
|
||||
import { imageUrl } from "@web/core/utils/urls";
|
||||
import { standardFieldProps } from "@web/views/fields/standard_field_props";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
|
||||
/**
|
||||
* Photo, or initials on peach when there is none (Panel General design).
|
||||
*
|
||||
* WHY NOT avatar_128. res.partner inherits avatar.mixin, which already draws
|
||||
* an SVG when the record has no photo, so this looked like reinventing the
|
||||
* core. It is not, for two reasons that CSS cannot reach:
|
||||
*
|
||||
* · The mixin writes ONE letter (`name[0]`), and the design asks for two.
|
||||
* · Its background is an HSL colour hashed from name + create_date, and the
|
||||
* text is hardcoded white — inside a base64 SVG served as an <img>. The
|
||||
* colour is baked into the image, so no stylesheet can turn it into the
|
||||
* panel's peach.
|
||||
*
|
||||
* The other way out would be overriding _avatar_generate_svg on res.partner,
|
||||
* which is tempting and shorter. It was not taken because avatar_128 is used
|
||||
* far beyond this screen — the POS among them — and repainting every partner
|
||||
* avatar in the system is a decision for whoever designs those screens, not a
|
||||
* side effect of the customer list.
|
||||
*/
|
||||
export class BeyondAvatarInitials extends Component {
|
||||
static template = "beyond_base.AvatarInitials";
|
||||
static props = { ...standardFieldProps };
|
||||
|
||||
get valor() {
|
||||
return this.props.record.data[this.props.name];
|
||||
}
|
||||
|
||||
get nombre() {
|
||||
const datos = this.props.record.data;
|
||||
return (datos.name || datos.display_name || "").trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* First letter of the first word plus first letter of the last one:
|
||||
* "Alejandro Mcdonald" → "AM". A single word gives a single letter rather
|
||||
* than two from the same word, which reads like a typo.
|
||||
*/
|
||||
get iniciales() {
|
||||
const palabras = this.nombre.split(/\s+/).filter(Boolean);
|
||||
if (!palabras.length) {
|
||||
return "?";
|
||||
}
|
||||
const primera = palabras[0][0];
|
||||
const ultima = palabras.length > 1 ? palabras[palabras.length - 1][0] : "";
|
||||
return (primera + ultima).toUpperCase();
|
||||
}
|
||||
|
||||
get url() {
|
||||
return imageUrl(this.props.record.resModel, this.props.record.resId, this.props.name, {
|
||||
unique: this.props.record.data.write_date,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const beyondAvatarInitials = {
|
||||
component: BeyondAvatarInitials,
|
||||
displayName: _t("Foto o iniciales"),
|
||||
supportedTypes: ["binary"],
|
||||
// name feeds the initials; write_date busts the image cache after a new
|
||||
// photo. Declaring them makes the views load them without each view
|
||||
// having to remember.
|
||||
fieldDependencies: [
|
||||
{ name: "name", type: "char" },
|
||||
{ name: "write_date", type: "datetime" },
|
||||
],
|
||||
};
|
||||
|
||||
registry.category("fields").add("beyond_avatar_initials", beyondAvatarInitials);
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
<t t-name="beyond_base.AvatarInitials">
|
||||
<img t-if="valor" class="beyond_avatar_img" t-att-src="url" t-att-alt="nombre"/>
|
||||
<div t-else="" class="beyond_avatar_iniciales" t-att-title="nombre" t-esc="iniciales"/>
|
||||
</t>
|
||||
</templates>
|
||||
@@ -0,0 +1,61 @@
|
||||
/** Part of Beyond. Collina Systems proprietary module. */
|
||||
import { Component } from "@odoo/owl";
|
||||
import { registry } from "@web/core/registry";
|
||||
import { standardWidgetProps } from "@web/views/widgets/standard_widget_props";
|
||||
|
||||
/**
|
||||
* Explicit «Guardar» and «Descartar» at the foot of a form.
|
||||
*
|
||||
* SAME DECISION AS ADR-012 §6, extended. There the catalogue forms got an
|
||||
* explicit Guardar because "the cloud icon is not evident"; the argument holds
|
||||
* for every screen a non-technical person operates, and the Panel General
|
||||
* design draws both buttons in the footer. Odoo's own save/discard live in the
|
||||
* control panel and only appear once the record is dirty, which is precisely
|
||||
* the thing people do not find.
|
||||
*
|
||||
* The native indicator stays where it is — it cannot be removed and there is
|
||||
* no reason to fight it. These are the ones the design puts in front of the
|
||||
* user.
|
||||
*
|
||||
* Guardar could have been a plain object button, like ADR-012's, because Odoo
|
||||
* saves before running one. Descartar cannot: `special="cancel"` only closes
|
||||
* DIALOGS (view_button_hook.js checks env.dialogData), and an object button
|
||||
* would save the very changes it is meant to throw away. So both live here,
|
||||
* driven by the record itself.
|
||||
*
|
||||
* BOTH GO BACK to where the user came from — the kanban or the list. Staying
|
||||
* on the form after saving leaves no sign that anything happened: the screen
|
||||
* does not move and the only feedback was the cloud icon that this widget
|
||||
* exists to replace. A failed validation is the exception and stays put, with
|
||||
* the native error, because there the screen SHOULD not move.
|
||||
*/
|
||||
export class BeyondFormFooter extends Component {
|
||||
static template = "beyond_base.FormFooter";
|
||||
static props = { ...standardWidgetProps };
|
||||
|
||||
get registro() {
|
||||
return this.props.record;
|
||||
}
|
||||
|
||||
/** Nothing to save or throw away on an untouched record. */
|
||||
get haycambios() {
|
||||
return this.registro.dirty || this.registro.isNew;
|
||||
}
|
||||
|
||||
async guardar() {
|
||||
// save() devuelve falso cuando la validación no pasa: ahí no se va a
|
||||
// ninguna parte, para que el error quede a la vista sobre su campo.
|
||||
if (await this.registro.save()) {
|
||||
this.env.config.historyBack();
|
||||
}
|
||||
}
|
||||
|
||||
async descartar() {
|
||||
await this.registro.discard();
|
||||
this.env.config.historyBack();
|
||||
}
|
||||
}
|
||||
|
||||
registry.category("view_widgets").add("beyond_form_footer", {
|
||||
component: BeyondFormFooter,
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
<t t-name="beyond_base.FormFooter">
|
||||
<div class="beyond_form_footer">
|
||||
<button class="btn beyond_boton_guardar" t-on-click="guardar">Guardar</button>
|
||||
<button class="btn beyond_boton_descartar" t-on-click="descartar">Descartar</button>
|
||||
</div>
|
||||
</t>
|
||||
</templates>
|
||||
@@ -0,0 +1,282 @@
|
||||
/** Part of Beyond. Collina Systems proprietary module. */
|
||||
import { Component, onWillUnmount, useExternalListener, useRef, useState } from "@odoo/owl";
|
||||
import { Dialog } from "@web/core/dialog/dialog";
|
||||
import { registry } from "@web/core/registry";
|
||||
// useExternalListener viene de OWL, NO de @web/core/utils/hooks: importarlo
|
||||
// de ahí devuelve undefined y el diálogo de la cámara revienta al renderizar,
|
||||
// sin decir por qué. Lo cazaron las unitarias en navegador.
|
||||
import { useService } from "@web/core/utils/hooks";
|
||||
import { browser } from "@web/core/browser/browser";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
import { ImageField, imageField } from "@web/views/fields/image/image_field";
|
||||
import { FileUploader } from "@web/views/fields/file_handler";
|
||||
|
||||
/**
|
||||
* Photo field with a camera of its own (BRIEF §5.1).
|
||||
*
|
||||
* Extends the native ImageField instead of replacing it: uploading, clearing,
|
||||
* the URL cache key and the record update all keep working the way every
|
||||
* other image field in Odoo works. What this adds is the menu from the design
|
||||
* and a capture dialog.
|
||||
*
|
||||
* SECURE CONTEXT — the one thing to know before touching this file.
|
||||
* navigator.mediaDevices only exists over https or on localhost. Production
|
||||
* has no TLS yet (docs/despliegue.md), so ON THE BRANCH TABLETS THE CAMERA
|
||||
* DIALOG CANNOT OPEN AT ALL. That is not a bug to fix here; it is an
|
||||
* infrastructure dependency. What this widget does is refuse to show a button
|
||||
* that would throw: "Tomar fotografía" is rendered only when the API is
|
||||
* actually reachable, and "Subir archivo" carries capture="environment", which
|
||||
* makes Android open its own camera app without needing a secure context. The
|
||||
* customer still gets photographed; it just costs one more tap.
|
||||
*/
|
||||
|
||||
const LADO_MAXIMO = 1280;
|
||||
const CALIDAD_JPEG = 0.9;
|
||||
|
||||
/** The native uploader with one more attribute: see the note above. */
|
||||
export class BeyondFileUploader extends FileUploader {
|
||||
static template = "beyond_base.FileUploader";
|
||||
static props = {
|
||||
...FileUploader.props,
|
||||
capture: { type: String, optional: true },
|
||||
};
|
||||
}
|
||||
|
||||
export class BeyondCameraDialog extends Component {
|
||||
static template = "beyond_base.CameraDialog";
|
||||
static components = { Dialog };
|
||||
static props = {
|
||||
close: Function,
|
||||
onCapture: Function,
|
||||
};
|
||||
|
||||
setup() {
|
||||
this.notification = useService("notification");
|
||||
this.video = useRef("video");
|
||||
this.state = useState({
|
||||
listo: false,
|
||||
error: false,
|
||||
variasCamaras: false,
|
||||
// "environment" = trasera. El caso de uso es el mostrador
|
||||
// fotografiando al cliente, no una selfie.
|
||||
camara: "environment",
|
||||
});
|
||||
this.stream = null;
|
||||
this.destruido = false;
|
||||
|
||||
// Releasing the stream is not optional: a camera left running keeps
|
||||
// the tablet's indicator light on and looks like the shop is filming.
|
||||
// onWillUnmount covers the three ways out of this dialog — the X,
|
||||
// Escape and navigating away inside the client — because all three
|
||||
// destroy the component. pagehide covers leaving the page entirely.
|
||||
onWillUnmount(() => {
|
||||
this.destruido = true;
|
||||
this.detener();
|
||||
});
|
||||
useExternalListener(window, "pagehide", () => this.detener());
|
||||
|
||||
this.arrancar();
|
||||
}
|
||||
|
||||
async arrancar() {
|
||||
this.detener();
|
||||
try {
|
||||
this.stream = await browser.navigator.mediaDevices.getUserMedia({
|
||||
video: { facingMode: this.state.camara },
|
||||
audio: false,
|
||||
});
|
||||
} catch {
|
||||
this.state.error = true;
|
||||
return;
|
||||
}
|
||||
// The component may have been destroyed while getUserMedia was
|
||||
// resolving: the user can close the dialog faster than a camera turns
|
||||
// on, and the stream would stay live with nobody left to stop it.
|
||||
if (this.destruido) {
|
||||
this.detener();
|
||||
return;
|
||||
}
|
||||
if (this.video.el) {
|
||||
this.video.el.srcObject = this.stream;
|
||||
// «Listo» es tener FOTOGRAMA, no que la cámara haya respondido.
|
||||
// getUserMedia resuelve antes de que el vídeo tenga dimensiones, y
|
||||
// con el botón habilitado en ese hueco, tocarlo no hacía nada: el
|
||||
// lienzo se dibujaba de un vídeo de 0×0 y la función salía sin
|
||||
// decir por qué.
|
||||
if (!this.video.el.videoWidth) {
|
||||
await new Promise((listo) => {
|
||||
this.video.el.addEventListener("loadedmetadata", listo, { once: true });
|
||||
});
|
||||
}
|
||||
}
|
||||
if (this.destruido) {
|
||||
this.detener();
|
||||
return;
|
||||
}
|
||||
this.state.listo = true;
|
||||
try {
|
||||
const dispositivos = await browser.navigator.mediaDevices.enumerateDevices();
|
||||
this.state.variasCamaras =
|
||||
dispositivos.filter((d) => d.kind === "videoinput").length > 1;
|
||||
} catch {
|
||||
this.state.variasCamaras = false;
|
||||
}
|
||||
}
|
||||
|
||||
detener() {
|
||||
this.stream?.getTracks().forEach((pista) => pista.stop());
|
||||
this.stream = null;
|
||||
if (this.video.el) {
|
||||
this.video.el.srcObject = null;
|
||||
}
|
||||
}
|
||||
|
||||
cambiarCamara() {
|
||||
this.state.camara = this.state.camara === "environment" ? "user" : "environment";
|
||||
this.state.listo = false;
|
||||
this.arrancar();
|
||||
}
|
||||
|
||||
capturar() {
|
||||
const video = this.video.el;
|
||||
if (!video || !this.state.listo) {
|
||||
return;
|
||||
}
|
||||
// Si el vídeo aún no reporta dimensiones, las de la pista sirven:
|
||||
// más vale una foto que un botón que no hace nada.
|
||||
const ajustes = this.stream?.getVideoTracks()[0]?.getSettings() || {};
|
||||
const ancho = video.videoWidth || ajustes.width;
|
||||
const alto = video.videoHeight || ajustes.height;
|
||||
if (!ancho || !alto) {
|
||||
this.notification.add(
|
||||
_t("La cámara todavía no entrega imagen. Inténtalo de nuevo."),
|
||||
{ type: "warning" }
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Scale down to LADO_MAXIMO on the longest side. A tablet camera hands
|
||||
// back several megapixels and the field stores base64 in the record:
|
||||
// full size would make every read of this customer drag the photo.
|
||||
const escala = Math.min(1, LADO_MAXIMO / Math.max(ancho, alto));
|
||||
const lienzo = document.createElement("canvas");
|
||||
lienzo.width = Math.round(ancho * escala);
|
||||
lienzo.height = Math.round(alto * escala);
|
||||
lienzo.getContext("2d").drawImage(video, 0, 0, lienzo.width, lienzo.height);
|
||||
const datos = lienzo.toDataURL("image/jpeg", CALIDAD_JPEG).split(",")[1];
|
||||
this.detener();
|
||||
this.props.onCapture(datos);
|
||||
this.props.close();
|
||||
}
|
||||
}
|
||||
|
||||
export class BeyondImageCamera extends ImageField {
|
||||
static template = "beyond_base.ImageCamera";
|
||||
static components = { ...ImageField.components, FileUploader: BeyondFileUploader };
|
||||
|
||||
setup() {
|
||||
super.setup();
|
||||
this.dialog = useService("dialog");
|
||||
this.notification = useService("notification");
|
||||
this.menu = useState({ abierto: false, fijado: false });
|
||||
}
|
||||
|
||||
/**
|
||||
* True only where the browser can actually open a camera.
|
||||
*
|
||||
* Checking mediaDevices is enough and is the whole test: outside a secure
|
||||
* context (https or localhost) the browser does not merely refuse
|
||||
* getUserMedia — it does not define navigator.mediaDevices at all. Going
|
||||
* through `browser` rather than the global is Odoo's own indirection, and
|
||||
* it is what lets a test take the camera away.
|
||||
*/
|
||||
get camaraDisponible() {
|
||||
return !!browser.navigator.mediaDevices?.getUserMedia;
|
||||
}
|
||||
|
||||
get tieneImagen() {
|
||||
return !!this.props.record.data[this.props.name] && this.state.isValid;
|
||||
}
|
||||
|
||||
mostrarMenu() {
|
||||
this.menu.abierto = true;
|
||||
}
|
||||
|
||||
ocultarMenu() {
|
||||
if (!this.menu.fijado) {
|
||||
this.menu.abierto = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Touch has no hover: a tap pins the menu open, another closes it.
|
||||
*
|
||||
* The second tap has to actually close it. `abierto = fijado || abierto`
|
||||
* looked harmless and was not: once open, the right-hand side kept it
|
||||
* open for ever and the menu could only be dismissed by moving a mouse
|
||||
* the tablet does not have.
|
||||
*/
|
||||
alternarMenu() {
|
||||
this.menu.fijado = !this.menu.fijado;
|
||||
this.menu.abierto = this.menu.fijado;
|
||||
}
|
||||
|
||||
cerrarMenu() {
|
||||
this.menu.fijado = false;
|
||||
this.menu.abierto = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* EL ÚNICO punto por el que la imagen entra al registro.
|
||||
*
|
||||
* Las tres rutas —cámara, archivo y eliminar— terminan aquí, y esa es la
|
||||
* lección de un defecto real: la subida pintaba la imagen sin escribirla,
|
||||
* así que al guardar no quedaba nada, mientras la cámara sí funcionaba.
|
||||
* Dos caminos distintos hacia el mismo dato es una invitación a que uno de
|
||||
* los dos se rompa en silencio.
|
||||
*/
|
||||
escribirImagen(datos) {
|
||||
this.state.isValid = true;
|
||||
return this.props.record.update({ [this.props.name]: datos });
|
||||
}
|
||||
|
||||
/**
|
||||
* La subida pasa por el pipeline nativo (que redimensiona y convierte) y
|
||||
* ese termina escribiendo con record.update, el mismo punto. Lo que se
|
||||
* agrega es cerrar el menú DESPUÉS, nunca antes: cerrarlo al pulsar
|
||||
* desmontaba el FileUploader que acababa de abrir el selector del sistema.
|
||||
*/
|
||||
async onFileUploaded(info) {
|
||||
await super.onFileUploaded(info);
|
||||
this.cerrarMenu();
|
||||
}
|
||||
|
||||
abrirCamara() {
|
||||
this.cerrarMenu();
|
||||
if (!this.camaraDisponible) {
|
||||
// Should be unreachable: the option is not rendered without a
|
||||
// camera. Kept as a spoken failure rather than a silent one.
|
||||
this.notification.add(
|
||||
_t("Este navegador no permite usar la cámara aquí. Usa «Subir archivo»."),
|
||||
{ type: "warning" }
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.dialog.add(BeyondCameraDialog, {
|
||||
onCapture: (datos) => this.escribirImagen(datos),
|
||||
});
|
||||
}
|
||||
|
||||
eliminar() {
|
||||
this.cerrarMenu();
|
||||
this.state.isValid = true;
|
||||
this.escribirImagen(false);
|
||||
}
|
||||
}
|
||||
|
||||
export const beyondImageCamera = {
|
||||
...imageField,
|
||||
component: BeyondImageCamera,
|
||||
displayName: _t("Foto con cámara"),
|
||||
};
|
||||
|
||||
registry.category("fields").add("beyond_image_camera", beyondImageCamera);
|
||||
@@ -0,0 +1,113 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
|
||||
<!-- The native uploader plus one attribute. capture="environment" is what
|
||||
makes Android open its own camera app, and it needs no secure context
|
||||
— which is the whole point while production has no TLS. -->
|
||||
<t t-name="beyond_base.FileUploader" t-inherit="web.FileUploader" t-inherit-mode="primary">
|
||||
<xpath expr="//input[@type='file']" position="attributes">
|
||||
<attribute name="t-att-capture">props.capture or false</attribute>
|
||||
</xpath>
|
||||
</t>
|
||||
|
||||
<t t-name="beyond_base.ImageCamera">
|
||||
<div class="beyond_foto"
|
||||
t-on-mouseenter="mostrarMenu"
|
||||
t-on-mouseleave="ocultarMenu"
|
||||
t-on-click="alternarMenu">
|
||||
<!-- Sin foto NO se pinta el marcador de Odoo (la cámara gris con
|
||||
el signo más, sobre blanco): rompe el durazno del diseño y
|
||||
parece un campo roto. Va el icono propio del mock. -->
|
||||
<img t-if="tieneImagen" class="beyond_foto_img"
|
||||
t-att-alt="imgAlt"
|
||||
t-att-src="this.getUrl(props.previewImage or props.name)"
|
||||
t-on-error.stop="onLoadFailed"/>
|
||||
<div t-else="" class="beyond_foto_vacia">
|
||||
<svg width="108" height="108" viewBox="0 0 48 48" fill="none" aria-hidden="true">
|
||||
<circle cx="24" cy="17" r="8" fill="currentColor" fill-opacity="0.45"/>
|
||||
<path d="M8 41c2.4-8 8.3-11.5 16-11.5S37.6 33 40 41H8Z" fill="currentColor" fill-opacity="0.45"/>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<t t-if="!props.readonly and menu.abierto">
|
||||
<div class="beyond_foto_velo">
|
||||
<svg width="38" height="38" viewBox="0 0 24 24" fill="none" aria-hidden="true">
|
||||
<path d="M4 8.6h3.2l1.4-2.2h6.8l1.4 2.2H20v10.2H4V8.6Z" stroke="#FFFFFF" stroke-width="1.8" stroke-linejoin="round"/>
|
||||
<circle cx="12" cy="13.4" r="3.2" stroke="#FFFFFF" stroke-width="1.8"/>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<div class="beyond_foto_menu" t-on-click.stop="">
|
||||
<!-- Rendered ONLY where the camera can actually open. See
|
||||
the note at the top of beyond_image_camera.js. -->
|
||||
<button t-if="camaraDisponible" class="beyond_foto_opcion"
|
||||
t-on-click="abrirCamara">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true">
|
||||
<path d="M4 8.6h3.2l1.4-2.2h6.8l1.4 2.2H20v10.2H4V8.6Z" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>
|
||||
<circle cx="12" cy="13.4" r="3.2" stroke="currentColor" stroke-width="1.8"/>
|
||||
</svg>
|
||||
<span>Tomar fotografía</span>
|
||||
</button>
|
||||
|
||||
<FileUploader
|
||||
acceptedFileExtensions="'image/*'"
|
||||
capture="'environment'"
|
||||
t-key="props.record.resId"
|
||||
onUploaded.bind="onFileUploaded">
|
||||
<t t-set-slot="toggler">
|
||||
<!-- SIN t-on-click="cerrarMenu": cerrar el menú aquí
|
||||
desmonta el FileUploader que acaba de abrir el
|
||||
selector del sistema, y cuando la persona elige
|
||||
el archivo ya no hay componente que reciba el
|
||||
evento: la imagen no se escribía y al guardar no
|
||||
quedaba nada. El menú se cierra al terminar la
|
||||
subida, en onFileUploaded. -->
|
||||
<button class="beyond_foto_opcion">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true">
|
||||
<path d="M12 16.4V4.8M7.6 9.2 12 4.8l4.4 4.4" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M4.6 15.4v3.2a1.4 1.4 0 0 0 1.4 1.4h12a1.4 1.4 0 0 0 1.4-1.4v-3.2" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>
|
||||
</svg>
|
||||
<span>Subir archivo</span>
|
||||
</button>
|
||||
</t>
|
||||
</FileUploader>
|
||||
|
||||
<button t-if="tieneImagen" class="beyond_foto_opcion beyond_foto_borrar"
|
||||
t-on-click="eliminar">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true">
|
||||
<path d="M5 7h14M9.5 7V4.8h5V7M6.8 7l.9 12.2h8.6L17.2 7" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
<span>Eliminar</span>
|
||||
</button>
|
||||
</div>
|
||||
</t>
|
||||
</div>
|
||||
</t>
|
||||
|
||||
<t t-name="beyond_base.CameraDialog">
|
||||
<Dialog title="'Tomar fotografía'" size="'md'" contentClass="'beyond_camara_dialogo'">
|
||||
<div class="beyond_camara">
|
||||
<t t-if="state.error">
|
||||
<p class="beyond_camara_error">
|
||||
No se pudo abrir la cámara. Puede que el navegador no
|
||||
tenga permiso, o que otra aplicación la esté usando.
|
||||
Cierra este cuadro y usa «Subir archivo».
|
||||
</p>
|
||||
</t>
|
||||
<t t-else="">
|
||||
<video class="beyond_camara_video" t-ref="video"
|
||||
autoplay="autoplay" playsinline="playsinline" muted="muted"/>
|
||||
<p t-if="!state.listo" class="beyond_camara_espera">Encendiendo la cámara…</p>
|
||||
</t>
|
||||
</div>
|
||||
<t t-set-slot="footer">
|
||||
<button class="btn btn-primary" t-att-disabled="!state.listo"
|
||||
t-on-click="capturar">Tomar la foto</button>
|
||||
<button t-if="state.variasCamaras" class="btn btn-secondary"
|
||||
t-on-click="cambiarCamara">Cambiar de cámara</button>
|
||||
<button class="btn btn-secondary" t-on-click="() => props.close()">Cancelar</button>
|
||||
</t>
|
||||
</Dialog>
|
||||
</t>
|
||||
|
||||
</templates>
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Beyond — login v1: the eye that shows the password.
|
||||
*
|
||||
* Core ships this behaviour (web/static/src/public/show_password.js) but it is
|
||||
* bound to a Bootstrap `.input-group` wrapping a `.o_show_password` button with
|
||||
* a Font Awesome icon, and it says nothing to a screen reader. The login screen
|
||||
* uses the design's own pill and its own SVG, so the toggle is rewritten here —
|
||||
* eight lines and the ARIA that core leaves out.
|
||||
*
|
||||
* Deliberately a plain script and not an Interaction: this runs on the page
|
||||
* that precedes the session, where the less machinery involved in reaching the
|
||||
* password field, the better. It touches nothing but the input's `type`.
|
||||
*
|
||||
* Not touched: the form, its action, its method or the csrf_token.
|
||||
*/
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
// Spanish, like every string a user reads (CLAUDE.md).
|
||||
const LABEL_SHOW = "Mostrar contraseña";
|
||||
const LABEL_HIDE = "Ocultar contraseña";
|
||||
|
||||
function setUpPasswordToggle() {
|
||||
const eye = document.querySelector(".beyond_login .beyond_login_eye");
|
||||
const password = document.querySelector(".beyond_login #password");
|
||||
if (!eye || !password) {
|
||||
return;
|
||||
}
|
||||
eye.addEventListener("click", function () {
|
||||
const wasVisible = password.type === "text";
|
||||
password.type = wasVisible ? "password" : "text";
|
||||
eye.setAttribute("aria-pressed", String(!wasVisible));
|
||||
eye.setAttribute("aria-label", wasVisible ? LABEL_SHOW : LABEL_HIDE);
|
||||
// Back to typing where the user left off, not on the button.
|
||||
password.focus();
|
||||
});
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", setUpPasswordToggle);
|
||||
} else {
|
||||
setUpPasswordToggle();
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,500 @@
|
||||
// =============================================================================
|
||||
// Beyond — login v1
|
||||
//
|
||||
// Faithful translation of the signed-off "Iniciar sesión" (login_v1.html).
|
||||
// Every colour, radius, size, gap, duration and font weight below is copied
|
||||
// from that file, unrounded; the rules that have no counterpart there are
|
||||
// marked ENGINEERING and say what they protect against — the design only
|
||||
// covers the nominal case, and this one sits on top of Odoo's real login form.
|
||||
//
|
||||
// SCOPE — everything is nested under .beyond_login / .beyond_login_body. This
|
||||
// file rides web.assets_frontend, which every public page loads (the employee
|
||||
// portal of beyond_attendance_qr among them), so not one rule may escape the
|
||||
// login screen. The QR kiosk is a standalone <html> template that calls no
|
||||
// bundle at all and is out of reach by construction.
|
||||
//
|
||||
// PALETTE — the surfaces and the ink are the identity's own tokens; the design
|
||||
// reuses them exactly. The black is NOT: the design paints the controls
|
||||
// #191613 instead of the brand green, deliberately, so the pre-session screen
|
||||
// reads as the product's cover rather than as another green ERP form. Per the
|
||||
// rule written in scss/beyond_variables.scss ("a colour graduates to a token
|
||||
// when a SECOND screen needs it") that black, the field white, the placeholder
|
||||
// grey and the eye's hover stay local variables here. So does the error
|
||||
// orange, even though it is byte-for-byte the launcher's "Panel General":
|
||||
// same hex, unrelated meaning.
|
||||
// =============================================================================
|
||||
|
||||
// The control black of the login and its hover/pressed states.
|
||||
$beyond-login-ink: #191613;
|
||||
$beyond-login-ink-hover: #33302B;
|
||||
$beyond-login-ink-active: #000000;
|
||||
|
||||
// The brand panel behind the logo — flat black, not the ink above.
|
||||
$beyond-login-brand-bg: #000000;
|
||||
|
||||
// Fields
|
||||
$beyond-login-field-bg: #FFFFFF;
|
||||
$beyond-login-placeholder: #B3ADA3;
|
||||
$beyond-login-eye-hover: #F0EEE8;
|
||||
|
||||
// The focus ring the design draws around a field in focus.
|
||||
$beyond-login-ring: rgba(25, 22, 19, 0.10);
|
||||
|
||||
// Error text. Same hex as $beyond-launcher-panel and unrelated to it.
|
||||
$beyond-login-error: #C55A22;
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Page
|
||||
//
|
||||
// ENGINEERING — the class replaces Odoo's `bg-100` on <body> rather than
|
||||
// joining it (see views/login_templates.xml): the utility paints the body with
|
||||
// !important and there is no point in an override war on a page we own whole.
|
||||
// -----------------------------------------------------------------------------
|
||||
.beyond_login_body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: $beyond-surface;
|
||||
color: $beyond-ink;
|
||||
font-family: $beyond-font-family;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
overflow: hidden; // the design is 100vh with no scroll
|
||||
}
|
||||
|
||||
.beyond_login {
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
background: $beyond-surface;
|
||||
color: $beyond-ink;
|
||||
overflow: hidden;
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Left: the brand panel
|
||||
// ---------------------------------------------------------------------
|
||||
.beyond_login_brand {
|
||||
flex: 1 1 46%;
|
||||
min-width: 0;
|
||||
background: $beyond-login-brand-bg;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 56px;
|
||||
}
|
||||
|
||||
.beyond_login_logo {
|
||||
display: block;
|
||||
// The design says `width: min(360px, 72%)`. Written as a pair because
|
||||
// Sass evaluates a bare min() itself and refuses to compare px with %;
|
||||
// the used width is identical.
|
||||
width: 72%;
|
||||
max-width: 360px;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Right: the form
|
||||
// ---------------------------------------------------------------------
|
||||
.beyond_login_panel {
|
||||
flex: 1 1 54%;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: 40px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.beyond_login_stack {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
max-width: 440px;
|
||||
margin: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 26px;
|
||||
}
|
||||
|
||||
// ENGINEERING — web.login ships two empty `oe_structure` drop zones around
|
||||
// the form. Empty flex children still eat a 26px gap each, so they are
|
||||
// hidden while empty and left alone the moment anything is dropped in.
|
||||
.oe_structure:empty {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.beyond_login_title {
|
||||
font-size: 34px;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.03em;
|
||||
color: $beyond-ink;
|
||||
}
|
||||
|
||||
// The form is a column on the same 26px rhythm as the stack around it, so
|
||||
// title / user / password / CTA / error / signature read as one list.
|
||||
.beyond_login_form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 26px;
|
||||
}
|
||||
|
||||
// ENGINEERING — the database picker is core's, shown only when the server
|
||||
// serves more than one database. It keeps its Bootstrap look (a developer
|
||||
// sees it, an employee never does); all it needs is to stop fighting the
|
||||
// column's own rhythm with a utility margin.
|
||||
.beyond_login_form > .mb-3 {
|
||||
margin-bottom: 0 !important;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Fields
|
||||
// ---------------------------------------------------------------------
|
||||
.beyond_login_field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.beyond_login_field_head {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.beyond_login_label {
|
||||
margin: 0; // ENGINEERING — Bootstrap's reboot puts a margin on <label>
|
||||
font-size: 13px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.02em;
|
||||
color: $beyond-ink-soft;
|
||||
}
|
||||
|
||||
.beyond_login_forgot {
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: $beyond-ink-softer;
|
||||
text-decoration: none;
|
||||
|
||||
// ENGINEERING — the design's global rule is `a { #191613 }` with
|
||||
// `a:hover { #7A736A }`, and this link is already painted the hover
|
||||
// colour, which would leave it with no feedback at all. It uses the
|
||||
// same two colours, the other way round.
|
||||
&:hover {
|
||||
color: $beyond-login-ink;
|
||||
}
|
||||
}
|
||||
|
||||
.beyond_login_input {
|
||||
all: unset;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
padding: 16px 18px;
|
||||
border-radius: 16px;
|
||||
background: $beyond-login-field-bg;
|
||||
border: 1.5px solid $beyond-line;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: $beyond-ink;
|
||||
transition: border-color 140ms ease, box-shadow 140ms ease;
|
||||
|
||||
// Keyboard only, per the project rule — but a text field in focus
|
||||
// always matches :focus-visible, click or Tab, because it is about to
|
||||
// take keystrokes. The design's focus state survives intact.
|
||||
&:focus-visible {
|
||||
border-color: $beyond-login-ink;
|
||||
box-shadow: 0 0 0 4px $beyond-login-ring;
|
||||
}
|
||||
}
|
||||
|
||||
// The password field is a bare input inside a pill that carries the frame,
|
||||
// so that the eye button can live on the same border.
|
||||
.beyond_login_pw {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
padding: 4px 6px 4px 18px;
|
||||
border-radius: 16px;
|
||||
background: $beyond-login-field-bg;
|
||||
border: 1.5px solid $beyond-line;
|
||||
transition: border-color 140ms ease, box-shadow 140ms ease;
|
||||
|
||||
// The design's rule is :focus-within; :has(:focus-visible) is the same
|
||||
// thing restricted to keyboard focus, so the eye button being clicked
|
||||
// does not light the whole pill.
|
||||
&:has(:focus-visible) {
|
||||
border-color: $beyond-login-ink;
|
||||
box-shadow: 0 0 0 4px $beyond-login-ring;
|
||||
}
|
||||
}
|
||||
|
||||
.beyond_login_input_pw {
|
||||
all: unset;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 12px 0;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: $beyond-ink;
|
||||
}
|
||||
|
||||
.beyond_login_input,
|
||||
.beyond_login_input_pw {
|
||||
&::placeholder {
|
||||
color: $beyond-login-placeholder;
|
||||
}
|
||||
}
|
||||
|
||||
.beyond_login_eye {
|
||||
all: unset;
|
||||
position: relative; // ENGINEERING — anchors the touch target below
|
||||
flex: none; // ENGINEERING — the pill must not squeeze it
|
||||
cursor: pointer;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: 12px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: $beyond-ink-softer; // the icon strokes currentColor
|
||||
transition: background 140ms ease, color 140ms ease;
|
||||
|
||||
&:hover {
|
||||
background: $beyond-login-eye-hover;
|
||||
}
|
||||
|
||||
// ENGINEERING — the design paints a 44x44 box; the project floor for a
|
||||
// touch target is 48 (CLAUDE.md, "Norte de diseño"). The painted box
|
||||
// stays 44 and an invisible 48x48 sits centred on it, inside the room
|
||||
// the pill's own padding leaves. Nothing moves, the finger gets 48.
|
||||
&::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
}
|
||||
|
||||
// ENGINEERING — the password is on screen; say so with more than the
|
||||
// characters themselves. Pairs with aria-pressed on the button.
|
||||
&[aria-pressed="true"] {
|
||||
color: $beyond-ink;
|
||||
}
|
||||
|
||||
svg {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Call to action
|
||||
// ---------------------------------------------------------------------
|
||||
// ENGINEERING — core wraps the CTA and everything auth_signup/auth_passkey
|
||||
// bolt onto it in one `oe_login_buttons` div. That div has to survive (it
|
||||
// is their xpath anchor) but it must not be a box, or its contents cannot
|
||||
// be interleaved with the server's messages. `display: contents` dissolves
|
||||
// it: the CTA and the passkey block become items of the form's own column,
|
||||
// on its 26px rhythm, and `order` below can place the message between them
|
||||
// — under the CTA, where the design puts it.
|
||||
.beyond_login_actions {
|
||||
display: contents;
|
||||
}
|
||||
|
||||
.beyond_login_submit {
|
||||
all: unset;
|
||||
cursor: pointer;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
padding: 18px;
|
||||
border-radius: 16px;
|
||||
background: $beyond-login-ink;
|
||||
color: #FFFFFF;
|
||||
text-align: center;
|
||||
font-size: 17px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.01em;
|
||||
transition: background 140ms ease, transform 120ms ease;
|
||||
|
||||
&:hover {
|
||||
background: $beyond-login-ink-hover;
|
||||
}
|
||||
|
||||
&:active {
|
||||
background: $beyond-login-ink-active;
|
||||
transform: translateY(1px);
|
||||
}
|
||||
}
|
||||
|
||||
// ENGINEERING — `all: unset` strips the browser's own focus ring off every
|
||||
// control on this screen, so the keyboard ring has to be put back by hand.
|
||||
// :focus-visible only, so a click leaves no outline. The text fields are
|
||||
// excluded: they light up through the design's own focus state above.
|
||||
.beyond_login_submit,
|
||||
.beyond_login_eye,
|
||||
.beyond_login_forgot,
|
||||
.o_login_auth .list-group-item {
|
||||
&:focus-visible {
|
||||
outline: 3px solid $beyond-login-ink;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Server messages
|
||||
//
|
||||
// Odoo writes these after the POST — "Wrong login/password", the reset
|
||||
// mail confirmation, an access notice. There is no client-side validation
|
||||
// on this screen and no invented copy: whatever the server says, in the
|
||||
// design's voice.
|
||||
//
|
||||
// ENGINEERING — `order` because the design puts the message under the CTA
|
||||
// while web.login emits it above. Visual order follows the design, source
|
||||
// order stays the accessible one (a screen reader meets the error before
|
||||
// the button that produced it).
|
||||
// ---------------------------------------------------------------------
|
||||
.beyond_login_error,
|
||||
.beyond_login_message,
|
||||
.o_caps_lock_warning_text {
|
||||
order: 1;
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
// ...and the passkey block after it, so the message stays glued to the CTA
|
||||
// that produced it instead of being pushed below an alternative way in.
|
||||
.o_login_auth {
|
||||
order: 2;
|
||||
}
|
||||
|
||||
.beyond_login_error,
|
||||
.o_caps_lock_warning_text {
|
||||
color: $beyond-login-error;
|
||||
}
|
||||
|
||||
// Success is the brand green — the only place on this screen it appears.
|
||||
.beyond_login_message {
|
||||
color: $beyond-primary;
|
||||
}
|
||||
|
||||
.o_caps_lock_warning_text {
|
||||
display: block;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Passkeys
|
||||
//
|
||||
// Not in the design, and kept anyway: auth_passkey is installed and this
|
||||
// block is a real way into the system. Dropping it would lock out anyone
|
||||
// who registered a key. Dressed in the field's own clothes instead.
|
||||
// ---------------------------------------------------------------------
|
||||
.o_login_auth {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
|
||||
> em {
|
||||
margin: 0;
|
||||
font-style: normal;
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.04em;
|
||||
color: $beyond-ink-muted;
|
||||
}
|
||||
|
||||
.list-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.list-group-item {
|
||||
all: unset;
|
||||
cursor: pointer;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
// ENGINEERING — core builds this link from a dict and hangs
|
||||
// Bootstrap utilities on it (`py-2`, `d-flex`, `gap-2`), which are
|
||||
// !important. min-height carries the 48px touch floor without
|
||||
// joining an !important war; the horizontal padding is ours
|
||||
// because no utility sets it.
|
||||
min-height: 56px;
|
||||
padding-left: 18px;
|
||||
padding-right: 18px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
border-radius: 16px;
|
||||
background: $beyond-login-field-bg;
|
||||
border: 1.5px solid $beyond-line;
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
color: $beyond-ink;
|
||||
text-align: center;
|
||||
transition: background 140ms ease, border-color 140ms ease;
|
||||
|
||||
&:hover {
|
||||
background: $beyond-surface-hover;
|
||||
border-color: $beyond-ink-softer;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// The signature, at the foot
|
||||
// ---------------------------------------------------------------------
|
||||
.beyond_login_sign {
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.04em;
|
||||
color: $beyond-ink-muted;
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Narrow
|
||||
//
|
||||
// ENGINEERING — the design is one desktop artboard. Below the tablet
|
||||
// breakpoint the 46% black column would leave the form a strip too thin to
|
||||
// fill, so the panel collapses into a short band above the form and the form
|
||||
// takes the whole width. Checked at 768px and at 390px.
|
||||
// -----------------------------------------------------------------------------
|
||||
@media (max-width: 991.98px) {
|
||||
.beyond_login_body {
|
||||
overflow: auto; // stacked, the page is allowed to be taller than the viewport
|
||||
}
|
||||
|
||||
.beyond_login {
|
||||
height: auto;
|
||||
min-height: 100vh;
|
||||
flex-direction: column;
|
||||
overflow: visible;
|
||||
|
||||
.beyond_login_brand {
|
||||
flex: 0 0 auto;
|
||||
padding: 28px 24px;
|
||||
}
|
||||
|
||||
.beyond_login_logo {
|
||||
width: 60%;
|
||||
max-width: 240px;
|
||||
}
|
||||
|
||||
.beyond_login_panel {
|
||||
flex: 1 1 auto;
|
||||
padding: 32px 24px 40px;
|
||||
overflow: visible;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A phone on its side, or a short window: the band would take the screen the
|
||||
// form needs, so the logo goes and the form gets everything.
|
||||
@media (max-width: 991.98px) and (max-height: 520px) {
|
||||
.beyond_login .beyond_login_brand {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// =============================================================================
|
||||
// Manrope, self-hosted — the face of the Beyond identity (ADR-005).
|
||||
//
|
||||
// This block used to live in webclient/beyond_launcher.scss, where it was
|
||||
// reachable only from web.assets_backend. The login screen (C-0xx) is a
|
||||
// PRE-SESSION page: it renders through web.assets_frontend and never receives
|
||||
// a single backend asset, so it could not resolve the family. Rather than
|
||||
// copy six @font-face rules into a second file, they moved here and the file
|
||||
// is listed in both bundles.
|
||||
//
|
||||
// NOT loaded from Google Fonts on purpose: the branch terminals have to keep
|
||||
// working with no internet. These are the same variable woff2 subsets the
|
||||
// design shipped (one file per unicode range, weight axis 500-800), so every
|
||||
// weight the designs use resolves from one file per range.
|
||||
//
|
||||
// The kiosk page (beyond_attendance_qr/views/kiosco_templates.xml) still
|
||||
// restates the two latin ranges inline: it is a standalone <html> template
|
||||
// that calls no bundle at all, so it cannot include this file.
|
||||
// =============================================================================
|
||||
|
||||
// The family token lives with the @font-face rules that make it resolvable —
|
||||
// never on its own in beyond_variables.scss, which is prepended to bundles
|
||||
// (POS) where these files are not served and the promise would be empty.
|
||||
$beyond-font-family: Manrope, ui-sans-serif, system-ui, sans-serif;
|
||||
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 500 800;
|
||||
font-display: swap;
|
||||
src: url('/beyond_base/static/fonts/manrope-cyrillic-ext.woff2') format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 500 800;
|
||||
font-display: swap;
|
||||
src: url('/beyond_base/static/fonts/manrope-cyrillic.woff2') format('woff2');
|
||||
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 500 800;
|
||||
font-display: swap;
|
||||
src: url('/beyond_base/static/fonts/manrope-greek.woff2') format('woff2');
|
||||
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 500 800;
|
||||
font-display: swap;
|
||||
src: url('/beyond_base/static/fonts/manrope-vietnamese.woff2') format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 500 800;
|
||||
font-display: swap;
|
||||
src: url('/beyond_base/static/fonts/manrope-latin-ext.woff2') format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 500 800;
|
||||
font-display: swap;
|
||||
src: url('/beyond_base/static/fonts/manrope-latin.woff2') format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
@@ -21,12 +21,27 @@
|
||||
// of one block on one screen and means nothing outside it. It stays a
|
||||
// local variable in webclient/beyond_launcher.scss. Publishing it in this
|
||||
// bundle would push it into the backend and POS and invite its use as a
|
||||
// semantic colour.
|
||||
// semantic colour. The login v1 error text is that same #C55A22 and it
|
||||
// STILL did not graduate: one hex, two unrelated meanings ("Panel General"
|
||||
// and "something went wrong") is not one token. If a second screen ever
|
||||
// needs an ERROR colour, that is what graduates, under its own name.
|
||||
// · The rule colour graduated (login v1): #DCD8CE was the launcher's
|
||||
// decorative rule under the title and is now also the login's field
|
||||
// borders, so it left beyond_launcher.scss as $beyond-line.
|
||||
// · Launcher v4 added a blue (#3D6A8A, Inventario), two golds (#C69B3A and
|
||||
// #A87F22, Tableros) and three beiges (#F2EEE4/#EAE4D6/#DFD6C2, the radial
|
||||
// ground). NONE graduated: all five are the colour-coding and the ground of
|
||||
// one screen. The login and the kiosk bring their own surfaces; no second
|
||||
// screen has asked for a beige. They stay local in beyond_launcher.scss.
|
||||
//
|
||||
// TYPOGRAPHY — the design uses Manrope. The @font-face rules are declared in
|
||||
// webclient/beyond_launcher.scss because the woff2 files are only wired into
|
||||
// web.assets_backend so far; there is no font-family token here yet on purpose,
|
||||
// a token would promise a face that other bundles (POS) cannot resolve.
|
||||
// TYPOGRAPHY — the designs use Manrope. The @font-face rules and the
|
||||
// $beyond-font-family token live in scss/beyond_fonts.scss, which is listed in
|
||||
// web.assets_backend AND web.assets_frontend (the login screen renders before
|
||||
// the session, from the frontend bundle only). They are deliberately NOT here:
|
||||
// this file is prepended to web._assets_primary_variables, which also feeds
|
||||
// bundles that do not serve the woff2 — the POS — and a family token there
|
||||
// would promise a face that cannot resolve. Ask beyond_fonts.scss for the
|
||||
// family; it ships the face that backs it.
|
||||
// =============================================================================
|
||||
|
||||
// Brand green. The launcher's "Venta" block and its hover/pressed states.
|
||||
@@ -40,6 +55,9 @@ $beyond-kiosco: #8C4A72;
|
||||
$beyond-kiosco-dark: #7C3E64;
|
||||
$beyond-kiosco-darker: #6B3556;
|
||||
|
||||
// Lines. The launcher's rule under the title and the login's field borders.
|
||||
$beyond-line: #DCD8CE;
|
||||
|
||||
// Surfaces
|
||||
$beyond-surface: #F6F5F1; // warm page background
|
||||
$beyond-surface-hover: #ECEAE3; // hover on a surface-coloured control
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
<!--
|
||||
La casa de Beyond, en un solo lugar.
|
||||
|
||||
Vivía dos veces: dibujada en el encabezado del lanzador y, en la barra,
|
||||
como el «fa fa-home» sólido que ADR-005 puso en el botón de apps. Eran
|
||||
dos casas distintas en la misma pantalla, y con el tiempo se habrían
|
||||
separado más. Ahora las dos llaman aquí.
|
||||
|
||||
El tamaño se pasa antes de la llamada; si no, 24.
|
||||
|
||||
<t t-set="tamanoCasa" t-value="38"/>
|
||||
<t t-call="beyond_base.CasaBeyond"/>
|
||||
-->
|
||||
<t t-name="beyond_base.CasaBeyond">
|
||||
<t t-set="lado" t-value="tamanoCasa or 24"/>
|
||||
<svg t-att-width="lado" t-att-height="lado" viewBox="0 0 24 24" fill="none"
|
||||
class="beyond_casa" aria-hidden="true">
|
||||
<path d="M3.2 10.1 12 3.2l8.8 6.9v9.1a1.6 1.6 0 0 1-1.6 1.6H4.8a1.6 1.6 0 0 1-1.6-1.6v-9.1Z"
|
||||
stroke="currentColor" stroke-width="1.7" stroke-linejoin="round"/>
|
||||
<path d="M9.2 20.8v-5.4a2.8 2.8 0 0 1 5.6 0v5.4"
|
||||
stroke="currentColor" stroke-width="1.7" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
</t>
|
||||
</templates>
|
||||
@@ -46,6 +46,16 @@ patch(WebClient.prototype, {
|
||||
* client. Picking a block navigates normally and nothing re-opens.
|
||||
*/
|
||||
async _loadDefaultApp() {
|
||||
// En pantalla chica NO se abre solo. Ahí Odoo no pinta el botón de
|
||||
// apps sino su barra lateral, que ADR-005 dejó intacta a propósito:
|
||||
// el lanzador no es la puerta en un teléfono. Y si se dispara igual,
|
||||
// el estado queda ABIERTO y el lanzador aparece encima en cuanto algo
|
||||
// vuelve a montar el desplegable — que es justo lo que pasa al entrar
|
||||
// al Panel General, donde la barra fuerza la variante de escritorio.
|
||||
// El resultado era una pantalla tapada por el lanzador.
|
||||
if (this.env.services.ui.isSmall) {
|
||||
return super._loadDefaultApp();
|
||||
}
|
||||
this.env.bus.trigger(OPEN_LAUNCHER);
|
||||
const cargada = await super._loadDefaultApp();
|
||||
// Twice on purpose: the app that loads behind grabs focus for its own
|
||||
|
||||
@@ -1,102 +1,110 @@
|
||||
// =============================================================================
|
||||
// C-005/C-006 · Beyond launcher v3 (ADR-005)
|
||||
// C-005/C-006 · Beyond launcher v4 (ADR-005)
|
||||
//
|
||||
// Faithful translation of the signed-off "Menú Principal". Every colour,
|
||||
// radius, size, gap, duration and font weight below comes from that file; the
|
||||
// few rules that have no counterpart there are marked ENGINEERING and explain
|
||||
// what they protect against — the design only covers the nominal case.
|
||||
// Faithful translation of the signed-off "Menú Principal v4". Unlike v3, the
|
||||
// design arrived as real CSS, so every colour, gradient, radius, blur, shadow
|
||||
// and duration below is copied from it rather than reconstructed. The rules
|
||||
// that have no counterpart there are marked ENGINEERING and say what they
|
||||
// protect against — the design is one artboard and this sits on top of Odoo's
|
||||
// real apps dropdown.
|
||||
//
|
||||
// It is still the native apps dropdown, restyled: the popover is forced full
|
||||
// screen with :has() + !important, which beats the inline positioning the
|
||||
// popover service writes. :has() is supported by the target browsers
|
||||
// (BRIEF §8).
|
||||
//
|
||||
// Local, on purpose: the four block colours below are this screen's
|
||||
// colour-coding, not brand colours, so they are NOT tokens in
|
||||
// scss/beyond_variables.scss. That file's rule is that a colour graduates to a
|
||||
// token when a SECOND screen needs it — which is how the purple became
|
||||
// $beyond-kiosco once the kiosk page and the QR dialog started using it. The
|
||||
// blue, gold and grey are new in v3 and no second screen uses them yet.
|
||||
// WHAT CHANGED FROM v3, beyond the paint:
|
||||
// · The solid colour-coded blocks became glass — a white gradient over the
|
||||
// module's own tint over $beyond-surface, with a blurred backdrop, a white
|
||||
// hairline and a shadow in the module's colour. Hover and pressed no
|
||||
// longer swap a hex: they deepen the same tint.
|
||||
// · The title "MENÚ PRINCIPAL" is gone; the header is the house and the rule.
|
||||
// · Contactos left the big blocks and joined Empleados in a new master row
|
||||
// of small buttons.
|
||||
// · Tableros went from grey to gold.
|
||||
// · The catch-all tile row is GONE. See the note over .beyond_launcher_master.
|
||||
// · The five doors are all ONE size (23-aug-2026 artboard). The bottom row
|
||||
// used to give its two blocks half the width each against the top trio's
|
||||
// third; a half-width spacer at each end of it splits the row into the same
|
||||
// three parts, so every door matches and the pair sits centred. Done with
|
||||
// spacers rather than a grid so hover keeps SHOVING: the block under the
|
||||
// cursor widens and its neighbours give way, which no grid track can do.
|
||||
//
|
||||
// PALETTE — the rule in scss/beyond_variables.scss is that a colour graduates
|
||||
// to a token when a SECOND screen needs it. Nothing graduated in v4 and one
|
||||
// thing was re-checked:
|
||||
// · The blue (#3D6A8A) and the two golds (#C69B3A icon, #A87F22 label) are
|
||||
// this screen's colour-coding for Inventario and Tableros. One screen.
|
||||
// · The three beiges of the radial gradient are this screen's ground. The
|
||||
// login and the kiosk have their own; nothing else wants a beige.
|
||||
// · #C55A22 stays local even though the login's error text is the same hex:
|
||||
// same value, unrelated meaning (see beyond_variables.scss).
|
||||
// · The greens, the purple, the inks, $beyond-surface and $beyond-line ARE
|
||||
// tokens and are used as such — the design happens to reuse them exactly.
|
||||
// Two v3 locals died with the redesign: the old grey of Tableros (#55606E) and
|
||||
// the gold of the Contactos block (#A8802C). Neither is referenced any more.
|
||||
// =============================================================================
|
||||
|
||||
// "Panel General"
|
||||
$beyond-launcher-panel: #C55A22;
|
||||
$beyond-launcher-panel-hover: #B14E1B;
|
||||
$beyond-launcher-panel-active: #984115;
|
||||
|
||||
// "Inventario"
|
||||
$beyond-launcher-inventario: #3D6A8A;
|
||||
$beyond-launcher-inventario-hover: #345C79;
|
||||
$beyond-launcher-inventario-active: #2C4E67;
|
||||
|
||||
// "Contactos"
|
||||
$beyond-launcher-contactos: #A8802C;
|
||||
$beyond-launcher-contactos-hover: #957025;
|
||||
$beyond-launcher-contactos-active: #7F5F1F;
|
||||
// "Tableros" — the bars and the word are two different golds in the design.
|
||||
$beyond-launcher-tableros: #C69B3A;
|
||||
$beyond-launcher-tableros-ink: #A87F22;
|
||||
|
||||
// "Tableros"
|
||||
$beyond-launcher-tableros: #55606E;
|
||||
$beyond-launcher-tableros-hover: #4A545F;
|
||||
$beyond-launcher-tableros-active: #3F4750;
|
||||
// The ground: a radial wash from the top centre.
|
||||
$beyond-launcher-bg-alto: #F2EEE4;
|
||||
$beyond-launcher-bg-medio: #EAE4D6;
|
||||
$beyond-launcher-bg-bajo: #DFD6C2;
|
||||
|
||||
// Decorative rule under the title
|
||||
$beyond-launcher-rule: #DCD8CE;
|
||||
// The glass: a white hairline and the sheen that sells the material.
|
||||
$beyond-launcher-vidrio-borde: rgba(255, 255, 255, 0.85);
|
||||
$beyond-launcher-vidrio-alto: rgba(255, 255, 255, 0.95);
|
||||
$beyond-launcher-vidrio-bajo: rgba(255, 255, 255, 0.35);
|
||||
|
||||
$beyond-font-family: Manrope, ui-sans-serif, system-ui, sans-serif;
|
||||
// Manrope and $beyond-font-family now live in scss/beyond_fonts.scss: the login
|
||||
// screen needs the same face from web.assets_frontend, and one copy of six
|
||||
// @font-face rules is enough. That file is listed before this one in
|
||||
// web.assets_backend, so the variable below is already defined here.
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Manrope, self-hosted. NOT loaded from Google Fonts on purpose: the branch
|
||||
// terminals have to keep working with no internet. These are the same variable
|
||||
// woff2 subsets the design shipped (one file per unicode range, weight axis
|
||||
// 500–800), so the four weights the design uses all resolve from one file.
|
||||
// The glass of a block.
|
||||
//
|
||||
// Three stacked layers, exactly as the design writes them: a white gradient on
|
||||
// top for the sheen, the module's tint under it, and $beyond-surface at the
|
||||
// bottom so the stack is opaque. Only the two top layers move between rest,
|
||||
// hover and pressed; the shadow does not change.
|
||||
//
|
||||
// The tint opacities are a parameter and not a constant because the design
|
||||
// gives Tableros a heavier hand (0.20/0.30/0.38 against everyone else's
|
||||
// 0.15/0.24/0.30): the gold is the lightest of the five and needs it to read.
|
||||
// -----------------------------------------------------------------------------
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 500 800;
|
||||
font-display: swap;
|
||||
src: url('/beyond_base/static/fonts/manrope-cyrillic-ext.woff2') format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 500 800;
|
||||
font-display: swap;
|
||||
src: url('/beyond_base/static/fonts/manrope-cyrillic.woff2') format('woff2');
|
||||
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 500 800;
|
||||
font-display: swap;
|
||||
src: url('/beyond_base/static/fonts/manrope-greek.woff2') format('woff2');
|
||||
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 500 800;
|
||||
font-display: swap;
|
||||
src: url('/beyond_base/static/fonts/manrope-vietnamese.woff2') format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 500 800;
|
||||
font-display: swap;
|
||||
src: url('/beyond_base/static/fonts/manrope-latin-ext.woff2') format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 500 800;
|
||||
font-display: swap;
|
||||
src: url('/beyond_base/static/fonts/manrope-latin.woff2') format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
@mixin beyond-vidrio($tinte, $reposo: 0.15, $hover: 0.24, $activo: 0.30) {
|
||||
background:
|
||||
linear-gradient(150deg, rgba(255, 255, 255, 0.60) 0%, rgba(255, 255, 255, 0.22) 100%),
|
||||
linear-gradient(0deg, rgba($tinte, $reposo), rgba($tinte, $reposo)),
|
||||
$beyond-surface;
|
||||
box-shadow:
|
||||
inset 0 1px 0 $beyond-launcher-vidrio-alto,
|
||||
inset 0 -1px 0 $beyond-launcher-vidrio-bajo,
|
||||
0 16px 38px rgba($tinte, $reposo);
|
||||
|
||||
&:hover {
|
||||
background:
|
||||
linear-gradient(150deg, rgba(255, 255, 255, 0.55) 0%, rgba(255, 255, 255, 0.18) 100%),
|
||||
linear-gradient(0deg, rgba($tinte, $hover), rgba($tinte, $hover)),
|
||||
$beyond-surface;
|
||||
}
|
||||
|
||||
&:active {
|
||||
background:
|
||||
linear-gradient(150deg, rgba(255, 255, 255, 0.50) 0%, rgba(255, 255, 255, 0.15) 100%),
|
||||
linear-gradient(0deg, rgba($tinte, $activo), rgba($tinte, $activo)),
|
||||
$beyond-surface;
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
@@ -116,15 +124,57 @@ $beyond-font-family: Manrope, ui-sans-serif, system-ui, sans-serif;
|
||||
border-radius: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: $beyond-surface;
|
||||
background: radial-gradient(120% 90% at 50% 0%,
|
||||
$beyond-launcher-bg-alto 0%,
|
||||
$beyond-launcher-bg-medio 55%,
|
||||
$beyond-launcher-bg-bajo 100%);
|
||||
color: $beyond-ink;
|
||||
font-family: $beyond-font-family;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
// Nothing scrolls: the design absorbs a short viewport in the icons,
|
||||
// which shrink with min(140px, 22vh) inside rows that can squash.
|
||||
overflow: hidden;
|
||||
// Nothing scrolls: the design absorbs a short viewport in the icons, which
|
||||
// shrink with the 22vh cap inside rows that can squash.
|
||||
//
|
||||
// !important like the geometry above, and for the same reason: the popover
|
||||
// service writes `overflow-y: auto` INLINE, next to the top/max-height it
|
||||
// also writes. v3 declared this without !important and quietly lost the
|
||||
// vertical axis — the screen was one short viewport away from scrolling
|
||||
// instead of squashing.
|
||||
overflow: hidden !important;
|
||||
|
||||
// The title block
|
||||
// -------------------------------------------------------------------------
|
||||
// FOCUS — there is none, anywhere on this screen, and that is the design's
|
||||
// decision, not an oversight.
|
||||
//
|
||||
// Leave it alone. It looks like the classic accessibility bug and it is the
|
||||
// first thing a reviewer "fixes"; v4 was signed off with the ring removed
|
||||
// on purpose, so if it needs to come back that is a design change with a
|
||||
// new artboard, not a patch here. Note the cost so the decision stays
|
||||
// informed: this screen cannot be driven by sight with the keyboard. It
|
||||
// still WORKS by keyboard — the dropdown's own arrow/enter navigation is
|
||||
// untouched — you just cannot see where you are.
|
||||
//
|
||||
// The one thing the new artboard does give focus is a brighter hairline on
|
||||
// the block — 0.95 white against the 0.85 at rest. It is faint, but it is
|
||||
// the design's own answer and it is more than v4 had.
|
||||
//
|
||||
// :focus and :focus-visible both, and !important, because the reset has to
|
||||
// beat Bootstrap's .dropdown-item:focus and Odoo's own o-dropdown rules.
|
||||
// -------------------------------------------------------------------------
|
||||
.beyond_block,
|
||||
.beyond_mbtn {
|
||||
&:focus,
|
||||
&:focus-visible {
|
||||
outline: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
.beyond_block:focus {
|
||||
border-color: rgba(255, 255, 255, 0.95);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Header: the house and the rule. v4 dropped the title.
|
||||
// -------------------------------------------------------------------------
|
||||
.beyond_launcher_header {
|
||||
flex: none;
|
||||
display: flex;
|
||||
@@ -132,14 +182,17 @@ $beyond-font-family: Manrope, ui-sans-serif, system-ui, sans-serif;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 22px 22px 10px;
|
||||
}
|
||||
|
||||
.beyond_launcher_title {
|
||||
font-size: 34px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.16em;
|
||||
text-transform: uppercase;
|
||||
// La casa es ahora una plantilla compartida y dibuja con currentColor:
|
||||
// el tono lo pone quien la usa (beyond_base/…/beyond_casa.xml).
|
||||
color: $beyond-ink;
|
||||
|
||||
svg {
|
||||
transition: transform 220ms ease;
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.18);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.beyond_launcher_rule {
|
||||
@@ -147,10 +200,12 @@ $beyond-font-family: Manrope, ui-sans-serif, system-ui, sans-serif;
|
||||
width: 64px;
|
||||
height: 4px;
|
||||
border-radius: 2px;
|
||||
background: $beyond-launcher-rule;
|
||||
background: $beyond-line;
|
||||
}
|
||||
|
||||
// The signature, at the foot
|
||||
// -------------------------------------------------------------------------
|
||||
// The signature, at the foot. v4 moved it from muted grey to full ink.
|
||||
// -------------------------------------------------------------------------
|
||||
.beyond_launcher_brand {
|
||||
flex: none;
|
||||
display: flex;
|
||||
@@ -161,74 +216,67 @@ $beyond-font-family: Manrope, ui-sans-serif, system-ui, sans-serif;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.04em;
|
||||
color: $beyond-ink-muted;
|
||||
color: $beyond-ink;
|
||||
}
|
||||
}
|
||||
|
||||
// ENGINEERING — a row with no apps for this role must not leave a ghost
|
||||
// strip. :has() rather than :empty so template whitespace cannot fool it.
|
||||
// The catch-all row is empty for every Beyond role, so this is what keeps
|
||||
// the screen down to the design's six blocks.
|
||||
.beyond_launcher_band:not(:has(.beyond_block)):not(:has(.beyond_tile)) {
|
||||
// This is what makes the master row disappear for a Beyond role, which is
|
||||
// every role: Contactos and Empleados are behind base.group_system.
|
||||
.beyond_launcher_band:not(:has(.beyond_block)),
|
||||
.beyond_launcher_master:not(:has(.beyond_mbtn)) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
// Two rows of three. Both grow, so the blocks split the height evenly.
|
||||
// -------------------------------------------------------------------------
|
||||
// The two rows
|
||||
//
|
||||
// Both grow, so the blocks split whatever height the header, the master row
|
||||
// and the signature leave behind. Flex and not a grid on purpose: a flex
|
||||
// item can widen past its share, and that is the whole point of the hover
|
||||
// below — the block under the cursor grows and shoves its neighbours aside.
|
||||
// A grid track cannot do that.
|
||||
// -------------------------------------------------------------------------
|
||||
.beyond_launcher_band {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.beyond_launcher_row1,
|
||||
.beyond_launcher_row2 {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.beyond_launcher_row1 { padding: 8px 6px 0; }
|
||||
.beyond_launcher_row2 { padding: 6px 6px 8px; }
|
||||
|
||||
// Catch-all row: fixed height under the blocks, so the six blocks keep
|
||||
// splitting whatever is left.
|
||||
.beyond_launcher_tiles {
|
||||
flex: none;
|
||||
height: 128px;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 0 6px;
|
||||
// ENGINEERING — the row catches every unmapped app, so it can grow
|
||||
// past the viewport. Scrolling sideways keeps them reachable without
|
||||
// breaking the fixed band. Centring is done with auto margins rather
|
||||
// than justify-content on purpose: centred flex content overflows in
|
||||
// BOTH directions, pushing the first tiles off the left edge where
|
||||
// scrolling cannot reach them. Auto margins collapse to 0 once there
|
||||
// is no free space, so the row simply starts at the left.
|
||||
justify-content: flex-start;
|
||||
overflow-x: auto;
|
||||
|
||||
.beyond_tile:first-child { margin-inline-start: auto; }
|
||||
.beyond_tile:last-child { margin-inline-end: auto; }
|
||||
// The bottom row's two blocks would otherwise be half the row each against
|
||||
// the third the three above get — same height, wider box. A half-width
|
||||
// spacer at each end fixes both things at once: 0.5 + 1 + 1 + 0.5 splits
|
||||
// into the same three parts as row 1, so every door is the same size, and
|
||||
// the pair ends up centred. Empty, inert, invisible: no box, no text, no
|
||||
// tab stop; it only holds space, and it yields it back when a neighbour
|
||||
// grows on hover.
|
||||
.beyond_launcher_spacer {
|
||||
flex: 0.5;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
// Reset: DropdownItem renders an <a.dropdown-item>, so Bootstrap's block
|
||||
// layout, padding, colour and nowrap have to go before the design's own
|
||||
// box takes over.
|
||||
// layout, padding, colour and nowrap have to go before the design's own box
|
||||
// takes over. This is the <a> equivalent of the design's `all: unset`.
|
||||
.beyond_block,
|
||||
.beyond_tile {
|
||||
.beyond_mbtn {
|
||||
box-sizing: border-box;
|
||||
display: flex !important;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
width: auto;
|
||||
background: none;
|
||||
border: 0;
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Main band: three colour-coded blocks sharing the width
|
||||
// The blocks
|
||||
// -------------------------------------------------------------------------
|
||||
.beyond_block {
|
||||
flex: 1;
|
||||
@@ -237,20 +285,29 @@ $beyond-font-family: Manrope, ui-sans-serif, system-ui, sans-serif;
|
||||
justify-content: center;
|
||||
gap: 28px;
|
||||
padding: 18px 12px;
|
||||
border: 1.5px solid $beyond-launcher-vidrio-borde;
|
||||
border-radius: 28px;
|
||||
backdrop-filter: blur(16px);
|
||||
transition: flex-grow 220ms ease, background 180ms ease;
|
||||
|
||||
// The block under the cursor takes more of the row and pushes its
|
||||
// neighbours aside. Transitioning flex-grow is what animates the shove:
|
||||
// every sibling gives up width at the same time, spacers included.
|
||||
&:hover,
|
||||
&:active {
|
||||
flex-grow: 1.18;
|
||||
}
|
||||
|
||||
// Keyboard only. A plain :focus also fires on click, and since the QR
|
||||
// block answers in place the launcher stays up with a ring around
|
||||
// whatever the pointer last hit.
|
||||
&:focus-visible {
|
||||
outline: 4px solid $beyond-ink;
|
||||
outline-offset: -6px;
|
||||
svg {
|
||||
flex: 0 1 auto;
|
||||
min-height: 0;
|
||||
max-height: 100%;
|
||||
// The design says `width: min(140px, 22vh)`. Written as a pair
|
||||
// because Sass evaluates a bare min() itself and refuses to compare
|
||||
// px with vh; the used width is identical.
|
||||
width: 140px;
|
||||
max-width: 22vh;
|
||||
height: auto;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -258,83 +315,90 @@ $beyond-font-family: Manrope, ui-sans-serif, system-ui, sans-serif;
|
||||
font-size: 28px;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.02em;
|
||||
color: #FFFFFF;
|
||||
}
|
||||
|
||||
.beyond_block_venta {
|
||||
background: $beyond-primary;
|
||||
|
||||
&:hover { background: $beyond-primary-dark; }
|
||||
&:active { background: $beyond-primary-darker; }
|
||||
@include beyond-vidrio($beyond-primary);
|
||||
.beyond_block_name { color: $beyond-primary; }
|
||||
}
|
||||
|
||||
.beyond_block_panel {
|
||||
background: $beyond-launcher-panel;
|
||||
|
||||
&:hover { background: $beyond-launcher-panel-hover; }
|
||||
&:active { background: $beyond-launcher-panel-active; }
|
||||
@include beyond-vidrio($beyond-launcher-panel);
|
||||
.beyond_block_name { color: $beyond-launcher-panel; }
|
||||
}
|
||||
|
||||
.beyond_block_qr {
|
||||
background: $beyond-kiosco;
|
||||
|
||||
&:hover { background: $beyond-kiosco-dark; }
|
||||
&:active { background: $beyond-kiosco-darker; }
|
||||
@include beyond-vidrio($beyond-kiosco);
|
||||
.beyond_block_name { color: $beyond-kiosco; }
|
||||
}
|
||||
|
||||
.beyond_block_inventario {
|
||||
background: $beyond-launcher-inventario;
|
||||
|
||||
&:hover { background: $beyond-launcher-inventario-hover; }
|
||||
&:active { background: $beyond-launcher-inventario-active; }
|
||||
}
|
||||
|
||||
.beyond_block_contactos {
|
||||
background: $beyond-launcher-contactos;
|
||||
|
||||
&:hover { background: $beyond-launcher-contactos-hover; }
|
||||
&:active { background: $beyond-launcher-contactos-active; }
|
||||
@include beyond-vidrio($beyond-launcher-inventario);
|
||||
.beyond_block_name { color: $beyond-launcher-inventario; }
|
||||
}
|
||||
|
||||
.beyond_block_tableros {
|
||||
background: $beyond-launcher-tableros;
|
||||
|
||||
&:hover { background: $beyond-launcher-tableros-hover; }
|
||||
&:active { background: $beyond-launcher-tableros-active; }
|
||||
@include beyond-vidrio($beyond-launcher-tableros, 0.20, 0.30, 0.38);
|
||||
.beyond_block_name { color: $beyond-launcher-tableros-ink; }
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Catch-all tiles (~132x98, well over the 48px touch floor)
|
||||
// Master row
|
||||
//
|
||||
// Two curated buttons, and only two. v3 ended in a catch-all strip that
|
||||
// rendered every app the launcher had not mapped; v4 replaced it with this,
|
||||
// so the strip is gone. That is a real loss of reach for the technical
|
||||
// account (base.group_system): Facturación, Ajustes, Aplicaciones and
|
||||
// Asistencias no longer have a door on this screen and are reachable only
|
||||
// by URL. Deliberate — the design is the six doors and nothing else — but
|
||||
// written down because it is the kind of thing that gets discovered at the
|
||||
// worst moment.
|
||||
//
|
||||
// Both buttons sit behind base.group_system, so for every Beyond role this
|
||||
// row renders empty and the rule above collapses it.
|
||||
// -------------------------------------------------------------------------
|
||||
.beyond_tile {
|
||||
.beyond_launcher_master {
|
||||
flex: none;
|
||||
width: 132px;
|
||||
padding: 14px 0;
|
||||
gap: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
padding: 2px 6px 6px;
|
||||
}
|
||||
|
||||
.beyond_mbtn {
|
||||
// 124 x ~85: comfortably over the 48px touch floor (CLAUDE.md).
|
||||
width: 124px;
|
||||
padding: 12px 0;
|
||||
border: 1.5px solid transparent;
|
||||
border-radius: 20px;
|
||||
transition: background 140ms ease;
|
||||
gap: 8px;
|
||||
background: none;
|
||||
transition: background 140ms ease, border-color 140ms ease;
|
||||
|
||||
&:hover,
|
||||
&:focus-visible {
|
||||
background: $beyond-surface-hover;
|
||||
&:active {
|
||||
background:
|
||||
linear-gradient(150deg, rgba(255, 255, 255, 0.60) 0%, rgba(255, 255, 255, 0.22) 100%),
|
||||
$beyond-surface;
|
||||
border-color: $beyond-launcher-vidrio-borde;
|
||||
}
|
||||
|
||||
svg {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
}
|
||||
}
|
||||
|
||||
.beyond_tile_name {
|
||||
.beyond_mbtn_name {
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: $beyond-ink-soft;
|
||||
// ENGINEERING — these names are whatever the app is called; clip them
|
||||
// rather than let a long one wrap and push the tile out of the band.
|
||||
// ENGINEERING — the two names are ours and short, but the box is fixed
|
||||
// at 124px; clip rather than let a translation wrap and shove the row.
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.beyond_tile_icon {
|
||||
width: 42px;
|
||||
height: 42px;
|
||||
object-fit: contain;
|
||||
}
|
||||
}
|
||||
@@ -1,41 +1,54 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
<!--
|
||||
C-005/C-006 · Beyond launcher v3 (ADR-005).
|
||||
C-005/C-006 · Beyond launcher v4 (ADR-005).
|
||||
|
||||
Still an extension of the native apps menu, not a new screen: the
|
||||
grid button becomes a house and the dropdown is forced full screen
|
||||
from the stylesheet. Navigation stays native (DropdownItem,
|
||||
onSelected, getMenuItemHref, data-menu-xmlid), so hotkeys, keyboard
|
||||
navigation and group filtering are untouched.
|
||||
Still an extension of the native apps menu, not a new screen: the grid
|
||||
button becomes a house and the dropdown is forced full screen from the
|
||||
stylesheet. Navigation stays native (DropdownItem, onSelected,
|
||||
getMenuItemHref, data-menu-xmlid), so hotkeys, keyboard navigation and
|
||||
group filtering are untouched.
|
||||
|
||||
v3 is the signed-off "Menú Principal": a title, two rows of three
|
||||
equal colour-coded blocks, and the signature at the foot. Blocks are
|
||||
written out one by one rather than looped because each carries its
|
||||
own inline SVG and its own colour.
|
||||
v4 is the signed-off "Menú Principal v4": a header of house + rule, two
|
||||
rows of glass blocks, a master row of two small buttons, and the
|
||||
signature at the foot. Blocks are written out one by one rather than
|
||||
looped because each carries its own inline SVG and its own colour.
|
||||
|
||||
Six blocks cover everything a Beyond role can see: Punto de venta,
|
||||
Panel General, Kiosco, Inventario, Contactos y Tableros. What is not a
|
||||
block lives inside Panel General (Sucursales, Clientes, Catálogo,
|
||||
Precios por sucursal, Captura, Personal, Checador).
|
||||
THE MAP — seven apps, and only seven:
|
||||
|
||||
Under them the row of small tiles stays as a catch-all, and for a
|
||||
Beyond role it is always EMPTY — the stylesheet then hides it and the
|
||||
screen is the design's six blocks, nothing else. It only fills up for
|
||||
Collina's technical account (base.group_system), which is the one that
|
||||
still sees Facturación, Empleados, Asistencias, Aplicaciones y
|
||||
Ajustes: those are hidden from the roles by the menu cleanups, and the
|
||||
launcher is the only app switcher the web client has, so without this
|
||||
row that account would have no way in but typing the URL.
|
||||
Fila 1 Venta point_of_sale.menu_point_root
|
||||
Panel General beyond_branch.menu_beyond_root
|
||||
QR beyond_attendance_qr.menu_kiosco_app
|
||||
Fila 2 Inventario stock.menu_stock_root
|
||||
Tableros spreadsheet_dashboard.…_menu_root
|
||||
Maestro Contactos contacts.menu_contacts
|
||||
Empleados hr.menu_hr_root
|
||||
|
||||
Apps are matched by xmlid string, never imported: a module that is
|
||||
not installed simply never matches (no hard dependency).
|
||||
What is not a door here lives inside Panel General (Sucursales,
|
||||
Clientes, Catálogo, Precios por sucursal, Captura, Personal, Checador).
|
||||
|
||||
WHAT v4 REMOVED, and it matters: v3 ended in a catch-all strip that
|
||||
rendered every installed app the launcher had not mapped, so the
|
||||
technical account (base.group_system) could still reach Facturación,
|
||||
Ajustes, Aplicaciones y Asistencias from here. v4 replaces that strip
|
||||
with the two curated master buttons, so those four now have no door on
|
||||
this screen and are reachable only by URL (/odoo/settings, /odoo/apps).
|
||||
Deliberate; see the note in beyond_launcher.scss.
|
||||
|
||||
Conversaciones (mail.menu_root_discuss) is not mapped and must not be:
|
||||
it sits behind base.group_no_one by data/menu_cleanup.xml (C-001) and
|
||||
only exists in developer mode.
|
||||
|
||||
Apps are matched by xmlid string, never imported: a module that is not
|
||||
installed simply never matches (no hard dependency).
|
||||
-->
|
||||
<t t-name="beyond_base.NavBar.AppsMenu"
|
||||
t-inherit="web.NavBar.AppsMenu"
|
||||
t-inherit-mode="extension">
|
||||
<!-- La misma casa del encabezado del lanzador, no un icono de fuente
|
||||
parecido: son la misma cosa y ahora salen del mismo sitio. -->
|
||||
<xpath expr="//button[@data-hotkey='h']/i" position="replace">
|
||||
<i class="fa fa-home fs-4"/>
|
||||
<t t-call="beyond_base.CasaBeyond"/>
|
||||
</xpath>
|
||||
<!-- The launcher is the home screen: WebClient._loadDefaultApp opens
|
||||
it through this state (beyond_launcher.js). -->
|
||||
@@ -50,7 +63,8 @@
|
||||
</xpath>
|
||||
<xpath expr="//DropdownItem[@t-foreach='apps']" position="replace">
|
||||
<div class="beyond_launcher_header">
|
||||
<span class="beyond_launcher_title">Menú Principal</span>
|
||||
<t t-set="tamanoCasa" t-value="38"/>
|
||||
<t t-call="beyond_base.CasaBeyond"/>
|
||||
<span class="beyond_launcher_rule"/>
|
||||
</div>
|
||||
|
||||
@@ -64,9 +78,9 @@
|
||||
onSelected="() => this.onNavBarDropdownItemSelection(app)"
|
||||
attrs="{ href: getMenuItemHref(app), 'data-menu-xmlid': app.xmlid, 'data-section': app.id }"
|
||||
>
|
||||
<svg width="140" height="140" style="flex: 0 1 auto; min-height: 0; max-height: 100%; width: min(140px, 22vh); height: auto;" viewBox="0 0 48 48" fill="none" aria-hidden="true">
|
||||
<path d="M11 16h26l3.2 25.3A3.5 3.5 0 0 1 36.7 45H11.3a3.5 3.5 0 0 1-3.5-3.7L11 16Z" fill="#FFFFFF"/>
|
||||
<path d="M11 16h13v29H11.3a3.5 3.5 0 0 1-3.5-3.7L11 16Z" fill="#FFFFFF" fill-opacity="0.55"/>
|
||||
<svg viewBox="0 0 48 48" fill="none" aria-hidden="true">
|
||||
<path d="M11 16h26l3.2 25.3A3.5 3.5 0 0 1 36.7 45H11.3a3.5 3.5 0 0 1-3.5-3.7L11 16Z" fill="#0E6B57"/>
|
||||
<path d="M11 16h13v29H11.3a3.5 3.5 0 0 1-3.5-3.7L11 16Z" fill="#0E6B57" fill-opacity="0.55"/>
|
||||
<path d="M16.5 16a7.5 7.5 0 0 1 15 0" stroke="#FFFFFF" stroke-width="4.5" fill="none" stroke-linecap="round"/>
|
||||
</svg>
|
||||
<span class="beyond_block_name">Venta</span>
|
||||
@@ -79,14 +93,21 @@
|
||||
onSelected="() => this.onNavBarDropdownItemSelection(app)"
|
||||
attrs="{ href: getMenuItemHref(app), 'data-menu-xmlid': app.xmlid, 'data-section': app.id }"
|
||||
>
|
||||
<svg width="140" height="140" style="flex: 0 1 auto; min-height: 0; max-height: 100%; width: min(140px, 22vh); height: auto;" viewBox="0 0 48 48" fill="none" aria-hidden="true">
|
||||
<rect x="4" y="8" width="40" height="32" rx="5" fill="#FFFFFF"/>
|
||||
<rect x="9" y="20" width="13" height="15" rx="2.5" fill="#C55A22"/>
|
||||
<rect x="26" y="20" width="13" height="7" rx="2.5" fill="#C55A22" fill-opacity="0.55"/>
|
||||
<rect x="26" y="30" width="13" height="5" rx="2.5" fill="#C55A22" fill-opacity="0.55"/>
|
||||
<rect x="9" y="13" width="30" height="3.5" rx="1.75" fill="#C55A22" fill-opacity="0.35"/>
|
||||
<svg viewBox="0 0 48 48" fill="none" aria-hidden="true">
|
||||
<rect x="4" y="8" width="40" height="32" rx="5" fill="#C55A22"/>
|
||||
<rect x="9" y="20" width="13" height="15" rx="2.5" fill="#FFFFFF"/>
|
||||
<rect x="26" y="20" width="13" height="7" rx="2.5" fill="#FFFFFF" fill-opacity="0.7"/>
|
||||
<rect x="26" y="30" width="13" height="5" rx="2.5" fill="#FFFFFF" fill-opacity="0.7"/>
|
||||
<rect x="9" y="13" width="30" height="3.5" rx="1.75" fill="#FFFFFF" fill-opacity="0.55"/>
|
||||
</svg>
|
||||
<span class="beyond_block_name">Panel General</span>
|
||||
<!-- El único bloque que NO escribe su etiqueta: esta
|
||||
app es nuestra y su menú ya se llama "Panel
|
||||
General" (beyond_branch_views.xml). Los otros
|
||||
seis sí la escriben, a propósito: ahí el
|
||||
lanzador SOBRESCRIBE el nombre real de una app
|
||||
del core ("Venta" por "Punto de venta", "QR" por
|
||||
el nombre largo del checador). -->
|
||||
<span class="beyond_block_name" t-esc="app.name"/>
|
||||
</DropdownItem>
|
||||
</t>
|
||||
<t t-foreach="apps" t-as="app" t-key="app.id">
|
||||
@@ -100,21 +121,24 @@
|
||||
onSelected="() => this.onNavBarDropdownItemSelection(app)"
|
||||
attrs="{ href: getMenuItemHref(app), 'data-menu-xmlid': app.xmlid, 'data-section': app.id }"
|
||||
>
|
||||
<svg width="140" height="140" style="flex: 0 1 auto; min-height: 0; max-height: 100%; width: min(140px, 22vh); height: auto;" viewBox="0 0 48 48" fill="none" aria-hidden="true">
|
||||
<rect x="6" y="4" width="36" height="27" rx="4" fill="#FFFFFF"/>
|
||||
<rect x="21" y="31" width="6" height="8" fill="#FFFFFF" fill-opacity="0.55"/>
|
||||
<rect x="13" y="39" width="22" height="5" rx="2.5" fill="#FFFFFF" fill-opacity="0.55"/>
|
||||
<circle cx="24" cy="17.5" r="4.5" fill="#8C4A72"/>
|
||||
<path d="M31.5 10a10.5 10.5 0 0 1 0 15" stroke="#8C4A72" stroke-width="3" fill="none" stroke-linecap="round"/>
|
||||
<path d="M16.5 10a10.5 10.5 0 0 0 0 15" stroke="#8C4A72" stroke-width="3" fill="none" stroke-linecap="round"/>
|
||||
<svg viewBox="0 0 48 48" fill="none" aria-hidden="true">
|
||||
<rect x="6" y="4" width="36" height="27" rx="4" fill="#8C4A72"/>
|
||||
<rect x="21" y="31" width="6" height="8" fill="#8C4A72" fill-opacity="0.55"/>
|
||||
<rect x="13" y="39" width="22" height="5" rx="2.5" fill="#8C4A72" fill-opacity="0.55"/>
|
||||
<circle cx="24" cy="17.5" r="4.5" fill="#FFFFFF"/>
|
||||
<path d="M31.5 10a10.5 10.5 0 0 1 0 15" stroke="#FFFFFF" stroke-width="3" fill="none" stroke-linecap="round"/>
|
||||
<path d="M16.5 10a10.5 10.5 0 0 0 0 15" stroke="#FFFFFF" stroke-width="3" fill="none" stroke-linecap="round"/>
|
||||
</svg>
|
||||
<span class="beyond_block_name">QR</span>
|
||||
</DropdownItem>
|
||||
</t>
|
||||
</div>
|
||||
|
||||
<!-- Row 2 -->
|
||||
<!-- Row 2. The two half-width spacers are what centre it and what
|
||||
make its blocks the same size as the three above: 0.5 + 1 + 1
|
||||
+ 0.5 is the same three parts row 1 splits. -->
|
||||
<div class="beyond_launcher_band beyond_launcher_row2">
|
||||
<span class="beyond_launcher_spacer"/>
|
||||
<t t-foreach="apps" t-as="app" t-key="app.id">
|
||||
<DropdownItem
|
||||
t-if="app.xmlid === 'stock.menu_stock_root'"
|
||||
@@ -122,32 +146,14 @@
|
||||
onSelected="() => this.onNavBarDropdownItemSelection(app)"
|
||||
attrs="{ href: getMenuItemHref(app), 'data-menu-xmlid': app.xmlid, 'data-section': app.id }"
|
||||
>
|
||||
<svg width="140" height="140" style="flex: 0 1 auto; min-height: 0; max-height: 100%; width: min(140px, 22vh); height: auto;" viewBox="0 0 48 48" fill="none" aria-hidden="true">
|
||||
<path d="M24 5l18 9v20l-18 9-18-9V14l18-9Z" fill="#FFFFFF"/>
|
||||
<path d="M6 14l18 9v20L6 34V14Z" fill="#FFFFFF" fill-opacity="0.55"/>
|
||||
<path d="M6 14l18 9 18-9" stroke="#3D6A8A" stroke-width="2.5"/>
|
||||
<svg viewBox="0 0 48 48" fill="none" aria-hidden="true">
|
||||
<path d="M24 5l18 9v20l-18 9-18-9V14l18-9Z" fill="#3D6A8A"/>
|
||||
<path d="M6 14l18 9v20L6 34V14Z" fill="#3D6A8A" fill-opacity="0.55"/>
|
||||
<path d="M6 14l18 9 18-9" stroke="#FFFFFF" stroke-width="2.5"/>
|
||||
</svg>
|
||||
<span class="beyond_block_name">Inventario</span>
|
||||
</DropdownItem>
|
||||
</t>
|
||||
<t t-foreach="apps" t-as="app" t-key="app.id">
|
||||
<DropdownItem
|
||||
t-if="app.xmlid === 'contacts.menu_contacts'"
|
||||
class="{ 'o_app': true, 'beyond_block': true, 'beyond_block_contactos': true }"
|
||||
onSelected="() => this.onNavBarDropdownItemSelection(app)"
|
||||
attrs="{ href: getMenuItemHref(app), 'data-menu-xmlid': app.xmlid, 'data-section': app.id }"
|
||||
>
|
||||
<svg width="140" height="140" style="flex: 0 1 auto; min-height: 0; max-height: 100%; width: min(140px, 22vh); height: auto;" viewBox="0 0 48 48" fill="none" aria-hidden="true">
|
||||
<rect x="8" y="5" width="32" height="38" rx="6" fill="#FFFFFF"/>
|
||||
<rect x="4" y="13" width="7" height="4" rx="2" fill="#FFFFFF" fill-opacity="0.55"/>
|
||||
<rect x="4" y="22" width="7" height="4" rx="2" fill="#FFFFFF" fill-opacity="0.55"/>
|
||||
<rect x="4" y="31" width="7" height="4" rx="2" fill="#FFFFFF" fill-opacity="0.55"/>
|
||||
<circle cx="24" cy="19" r="5.5" fill="#A8802C"/>
|
||||
<path d="M14.5 34c1.6-5 5-7.6 9.5-7.6s7.9 2.6 9.5 7.6h-19Z" fill="#A8802C"/>
|
||||
</svg>
|
||||
<span class="beyond_block_name">Contactos</span>
|
||||
</DropdownItem>
|
||||
</t>
|
||||
<t t-foreach="apps" t-as="app" t-key="app.id">
|
||||
<DropdownItem
|
||||
t-if="app.xmlid === 'spreadsheet_dashboard.spreadsheet_dashboard_menu_root'"
|
||||
@@ -155,31 +161,53 @@
|
||||
onSelected="() => this.onNavBarDropdownItemSelection(app)"
|
||||
attrs="{ href: getMenuItemHref(app), 'data-menu-xmlid': app.xmlid, 'data-section': app.id }"
|
||||
>
|
||||
<svg width="140" height="140" style="flex: 0 1 auto; min-height: 0; max-height: 100%; width: min(140px, 22vh); height: auto;" viewBox="0 0 48 48" fill="none" aria-hidden="true">
|
||||
<rect x="6" y="27" width="9" height="15" rx="2" fill="#FFFFFF" fill-opacity="0.45"/>
|
||||
<rect x="19" y="17" width="9" height="25" rx="2" fill="#FFFFFF" fill-opacity="0.7"/>
|
||||
<rect x="32" y="7" width="9" height="35" rx="2" fill="#FFFFFF"/>
|
||||
<svg viewBox="0 0 48 48" fill="none" aria-hidden="true">
|
||||
<rect x="6" y="27" width="9" height="15" rx="2" fill="#C69B3A" fill-opacity="0.45"/>
|
||||
<rect x="19" y="17" width="9" height="25" rx="2" fill="#C69B3A" fill-opacity="0.7"/>
|
||||
<rect x="32" y="7" width="9" height="35" rx="2" fill="#C69B3A"/>
|
||||
</svg>
|
||||
<span class="beyond_block_name">Tableros</span>
|
||||
</DropdownItem>
|
||||
</t>
|
||||
<span class="beyond_launcher_spacer"/>
|
||||
</div>
|
||||
|
||||
<!-- Catch-all. Nothing designed goes here: the six blocks above
|
||||
are the screen. Anything else the user can see lands here
|
||||
with its native icon so it stays reachable. -->
|
||||
<div class="beyond_launcher_band beyond_launcher_tiles">
|
||||
<t t-set="beyondBlocks"
|
||||
t-value="['point_of_sale.menu_point_root', 'beyond_branch.menu_beyond_root', 'beyond_attendance_qr.menu_kiosco_app', 'stock.menu_stock_root', 'contacts.menu_contacts', 'spreadsheet_dashboard.spreadsheet_dashboard_menu_root']"/>
|
||||
<!-- Master row. Two curated buttons, both behind base.group_system,
|
||||
so for every Beyond role this renders empty and the stylesheet
|
||||
collapses it. -->
|
||||
<div class="beyond_launcher_master">
|
||||
<t t-foreach="apps" t-as="app" t-key="app.id">
|
||||
<DropdownItem
|
||||
t-if="!beyondBlocks.includes(app.xmlid)"
|
||||
class="{ 'o_app': true, 'beyond_tile': true }"
|
||||
t-if="app.xmlid === 'contacts.menu_contacts'"
|
||||
class="{ 'o_app': true, 'beyond_mbtn': true }"
|
||||
onSelected="() => this.onNavBarDropdownItemSelection(app)"
|
||||
attrs="{ href: getMenuItemHref(app), 'data-menu-xmlid': app.xmlid, 'data-section': app.id }"
|
||||
>
|
||||
<img t-if="app.webIconData" class="beyond_tile_icon" t-att-src="app.webIconData" alt=""/>
|
||||
<span class="beyond_tile_name" t-esc="app.name"/>
|
||||
<svg viewBox="0 0 48 48" fill="none" aria-hidden="true">
|
||||
<rect x="7" y="6" width="34" height="36" rx="5" fill="#23201D"/>
|
||||
<rect x="16" y="6" width="2" height="36" fill="#F6F5F1" fill-opacity="0.35"/>
|
||||
<circle cx="29" cy="20" r="5.5" fill="#F6F5F1"/>
|
||||
<path d="M19 35c1.6-4.8 5.2-7.2 10-7.2S37.4 30.2 39 35H19Z" fill="#F6F5F1"/>
|
||||
</svg>
|
||||
<span class="beyond_mbtn_name">Contactos</span>
|
||||
</DropdownItem>
|
||||
</t>
|
||||
<t t-foreach="apps" t-as="app" t-key="app.id">
|
||||
<DropdownItem
|
||||
t-if="app.xmlid === 'hr.menu_hr_root'"
|
||||
class="{ 'o_app': true, 'beyond_mbtn': true }"
|
||||
onSelected="() => this.onNavBarDropdownItemSelection(app)"
|
||||
attrs="{ href: getMenuItemHref(app), 'data-menu-xmlid': app.xmlid, 'data-section': app.id }"
|
||||
>
|
||||
<svg viewBox="0 0 48 48" fill="none" aria-hidden="true">
|
||||
<circle cx="24" cy="16" r="7.5" fill="#23201D"/>
|
||||
<path d="M9 41c1.7-8 7.6-12.2 15-12.2S37.3 33 39 41H9Z" fill="#23201D"/>
|
||||
<circle cx="10" cy="20" r="4.8" fill="#23201D" fill-opacity="0.45"/>
|
||||
<path d="M1 38c.9-5 4.4-7.7 9.4-7.7V38H1Z" fill="#23201D" fill-opacity="0.45"/>
|
||||
<circle cx="38" cy="20" r="4.8" fill="#23201D" fill-opacity="0.45"/>
|
||||
<path d="M47 38c-.9-5-4.4-7.7-9.4-7.7V38H47Z" fill="#23201D" fill-opacity="0.45"/>
|
||||
</svg>
|
||||
<span class="beyond_mbtn_name">Empleados</span>
|
||||
</DropdownItem>
|
||||
</t>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
/** Part of Beyond. Collina Systems proprietary module. */
|
||||
import { patch } from "@web/core/utils/patch";
|
||||
import { browser } from "@web/core/browser/browser";
|
||||
import { user } from "@web/core/user";
|
||||
import { useBus, useService } from "@web/core/utils/hooks";
|
||||
import { NavBar } from "@web/webclient/navbar/navbar";
|
||||
import { onWillUnmount, useEffect } from "@odoo/owl";
|
||||
|
||||
/**
|
||||
* Barra superior del Panel General (ADR-013).
|
||||
*
|
||||
* Se enciende SOLO dentro de la app beyond_branch.menu_beyond_root; fuera de
|
||||
* ella este archivo no cambia una línea del navbar nativo. Es el mismo
|
||||
* patrón del lanzador (ADR-005): extender por herencia, no construir un
|
||||
* cliente aparte, para no reimplementar navegación, grupos ni atajos.
|
||||
*
|
||||
* LAS PESTAÑAS NO SE ESCRIBEN EN DURO: son los hijos del menú raíz que el
|
||||
* servicio de menús ya devuelve filtrados por grupos (currentAppSections),
|
||||
* así que "Sucursales" desaparece sola para un admin de sucursal y una
|
||||
* sección nueva aparece sin tocar este archivo. Lo único que se empareja por
|
||||
* xmlid es el ícono de cada pestaña (beyond_panel_navbar.xml), y una sección
|
||||
* sin ícono conocido se pinta igual, sin él.
|
||||
*
|
||||
* LA CASA es el botón de apps NATIVO, revestido desde el SCSS. No se agrega
|
||||
* una segunda: ese botón ya abre el lanzador (ADR-005) y conserva el atajo
|
||||
* «h», el foco y la navegación con teclado. Duplicarlo habría sido escribir
|
||||
* de nuevo lo que ya funciona.
|
||||
*/
|
||||
|
||||
// La barra del panel vive en MÁS DE UNA app (enmienda a ADR-013, 27-ago-2026).
|
||||
// Empezó siendo del Panel General y basta con que una segunda la pida para
|
||||
// que deje de poder ser una constante: Tableros la enciende sobre la raíz
|
||||
// nativa de tableros, que ya lleva nuestra acción.
|
||||
const APPS_PANEL = [
|
||||
"beyond_branch.menu_beyond_root",
|
||||
"spreadsheet_dashboard.spreadsheet_dashboard_menu_root",
|
||||
];
|
||||
// Tableros lleva el acento en ORO, no en el naranja del panel. Es una
|
||||
// variante local y no un cambio del panel entero: el naranja es el acento de
|
||||
// Clientes, Sucursales, Catálogo y Personal, y cambiarlo es otro encargo.
|
||||
const APP_ORO = "spreadsheet_dashboard.spreadsheet_dashboard_menu_root";
|
||||
const CLASE_RAIZ = "beyond_panel";
|
||||
const CLASE_ORO = "beyond_panel_oro";
|
||||
|
||||
// Se resuelve una sola vez por carga de página y solo si alguien entra al
|
||||
// panel: saber si el usuario tiene foto propia no es dato de sesión y no
|
||||
// vale una consulta en cada render.
|
||||
let promesaAvatar = null;
|
||||
|
||||
patch(NavBar.prototype, {
|
||||
setup() {
|
||||
super.setup();
|
||||
this.beyondAction = useService("action");
|
||||
this.beyondOrm = useService("orm");
|
||||
this.beyondUser = user;
|
||||
|
||||
// La pestaña activa se deduce de la acción en curso, y el navbar solo
|
||||
// se re-renderiza por cambio de app o de systray. Sin esto, navegar de
|
||||
// Clientes a Catálogo dejaba la rayita naranja en Clientes.
|
||||
useBus(this.env.bus, "ACTION_MANAGER:UI-UPDATED", () => this.render());
|
||||
|
||||
// La clase raíz va en <body> y no en .o_web_client a propósito: los
|
||||
// diálogos de Odoo se portalizan a <body>, y "Mis preferencias" es
|
||||
// uno de ellos. Colgada del cliente, el diálogo habría quedado fuera
|
||||
// del alcance del SCSS del panel.
|
||||
useEffect(
|
||||
() => {
|
||||
document.body.classList.toggle(CLASE_RAIZ, this.beyondEsPanel);
|
||||
document.body.classList.toggle(CLASE_ORO, this.beyondEsOro);
|
||||
if (this.beyondEsPanel) {
|
||||
this.beyondCargarAvatar();
|
||||
}
|
||||
},
|
||||
() => [this.beyondEsPanel, this.beyondEsOro]
|
||||
);
|
||||
onWillUnmount(() => {
|
||||
document.body.classList.remove(CLASE_RAIZ);
|
||||
document.body.classList.remove(CLASE_ORO);
|
||||
});
|
||||
},
|
||||
|
||||
get beyondEsPanel() {
|
||||
return APPS_PANEL.includes(this.currentApp?.xmlid);
|
||||
},
|
||||
|
||||
/** Tableros pinta el mismo panel con el acento en oro. */
|
||||
get beyondEsOro() {
|
||||
return this.currentApp?.xmlid === APP_ORO;
|
||||
},
|
||||
|
||||
/** Nombre de la empresa (res.company.name), nunca escrito en duro. */
|
||||
get beyondEmpresa() {
|
||||
return user.activeCompany?.name || "";
|
||||
},
|
||||
|
||||
/** Inicial del usuario para el avatar de respaldo. */
|
||||
get beyondInicial() {
|
||||
return (user.name || "?").trim().charAt(0).toUpperCase();
|
||||
},
|
||||
|
||||
get beyondAvatarUrl() {
|
||||
return `/web/image/res.users/${user.userId}/avatar_128`;
|
||||
},
|
||||
|
||||
/** True cuando el usuario subió foto propia; si no, se pinta la inicial. */
|
||||
get beyondTieneFoto() {
|
||||
return !!promesaAvatar?.valor;
|
||||
},
|
||||
|
||||
beyondCargarAvatar() {
|
||||
if (promesaAvatar) {
|
||||
return promesaAvatar;
|
||||
}
|
||||
// searchCount y no read de image_128: la respuesta es un número, no
|
||||
// una imagen de decenas de KB que además ya viaja por /web/image.
|
||||
promesaAvatar = this.beyondOrm
|
||||
.searchCount("res.users", [
|
||||
["id", "=", user.userId],
|
||||
["image_128", "!=", false],
|
||||
])
|
||||
.then((cuantos) => {
|
||||
promesaAvatar.valor = cuantos > 0;
|
||||
this.render();
|
||||
})
|
||||
.catch(() => {
|
||||
// Sin el dato se pinta la inicial, que es el diseño de base.
|
||||
promesaAvatar.valor = false;
|
||||
});
|
||||
return promesaAvatar;
|
||||
},
|
||||
|
||||
/**
|
||||
* La sección activa se empareja por la acción en curso: el servicio de
|
||||
* menús sabe cuál es la APP actual, no cuál de sus secciones.
|
||||
*/
|
||||
get beyondSeccionActivaId() {
|
||||
const accionId = this.beyondAction.currentController?.action?.id;
|
||||
if (!accionId) {
|
||||
return null;
|
||||
}
|
||||
const contiene = (seccion) =>
|
||||
seccion.actionID === accionId ||
|
||||
(seccion.childrenTree || []).some(contiene);
|
||||
return this.currentAppSections.find(contiene)?.id ?? null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Una sección sin acción propia (hoy Personal) abre la primera de sus
|
||||
* hijas que sí tenga una. selectMenu del core se rinde en ese caso, y
|
||||
* una pestaña que no hace nada al tocarla se lee como rota.
|
||||
*/
|
||||
beyondAbrirSeccion(seccion) {
|
||||
const conAccion = (nodo) =>
|
||||
nodo.actionID ? nodo : (nodo.childrenTree || []).map(conAccion).find(Boolean);
|
||||
const destino = conAccion(seccion);
|
||||
if (destino) {
|
||||
this.menuService.selectMenu(destino);
|
||||
}
|
||||
},
|
||||
|
||||
async beyondAbrirPreferencias() {
|
||||
// Acción NATIVA de preferencias (res.users.action_get), abierta en
|
||||
// diálogo y revestida por el SCSS del panel. No se reimplementa: el
|
||||
// formulario del core es el que sabe qué campos existen en esta build.
|
||||
const accion = await this.beyondOrm.call("res.users", "action_get");
|
||||
accion.res_id = user.userId;
|
||||
accion.target = "new";
|
||||
accion.name = "Cambiar mis preferencias";
|
||||
this.beyondAction.doAction(accion);
|
||||
},
|
||||
|
||||
beyondCerrarSesion() {
|
||||
browser.location.href = "/web/session/logout?redirect=/";
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,162 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
<!--
|
||||
Barra superior del Panel General (ADR-013).
|
||||
|
||||
Herencia por extensión de web.NavBar: dentro de la app
|
||||
beyond_branch.menu_beyond_root se apagan las secciones y el systray
|
||||
nativos y se enciende esta barra. En cualquier otra app las tres
|
||||
condiciones dan falso y el navbar queda EXACTAMENTE como estaba —
|
||||
ese es el trato de ADR-005 y aquí se repite.
|
||||
|
||||
La casa no aparece en este archivo: es el botón de apps nativo, que
|
||||
ya abre el lanzador, revestido desde beyond_panel.scss.
|
||||
-->
|
||||
<t t-name="beyond_base.NavBar" t-inherit="web.NavBar" t-inherit-mode="extension">
|
||||
|
||||
<!-- El título de la app lo pinta nuestra barra, a la derecha y con el
|
||||
nombre de la empresa debajo. -->
|
||||
<xpath expr="//DropdownItem[@t-esc='currentApp.name']" position="attributes">
|
||||
<attribute name="t-if">!this.ui.isSmall and currentApp and !beyondEsPanel</attribute>
|
||||
</xpath>
|
||||
|
||||
<!-- Las secciones nativas se sustituyen por las pestañas. -->
|
||||
<xpath expr="//t[@t-call='web.NavBar.SectionsMenu']" position="attributes">
|
||||
<attribute name="t-if">currentAppSections.length and !beyondEsPanel</attribute>
|
||||
</xpath>
|
||||
|
||||
<!-- El systray entero: el menú de usuario del panel es el de abajo y
|
||||
no lleva nada más (sin Documentación, Soporte, Atajos ni
|
||||
Odoo.com), que es la decisión del 24-ago. -->
|
||||
<xpath expr="//div[hasclass('o_menu_systray')]" position="attributes">
|
||||
<attribute name="t-if">!beyondEsPanel</attribute>
|
||||
</xpath>
|
||||
|
||||
<xpath expr="//div[hasclass('o_menu_systray')]" position="before">
|
||||
<t t-if="beyondEsPanel">
|
||||
<!-- ══ Pestañas ══
|
||||
Hijos del menú raíz tal como los devuelve el servicio de
|
||||
menús: ya vienen filtrados por grupos. -->
|
||||
<div class="beyond_panel_tabs" role="menu">
|
||||
<t t-foreach="currentAppSections" t-as="seccion" t-key="seccion.id">
|
||||
<button class="beyond_panel_tab"
|
||||
t-att-class="{ beyond_activa: seccion.id === beyondSeccionActivaId }"
|
||||
t-att-data-menu-xmlid="seccion.xmlid"
|
||||
t-att-data-section="seccion.id"
|
||||
t-on-click="() => this.beyondAbrirSeccion(seccion)">
|
||||
<t t-call="beyond_base.PanelTabIcon"/>
|
||||
<span class="beyond_panel_tab_name" t-esc="seccion.name"/>
|
||||
<span class="beyond_panel_tab_rule"/>
|
||||
</button>
|
||||
</t>
|
||||
</div>
|
||||
|
||||
<!-- ══ Título y usuario ══ -->
|
||||
<div class="beyond_panel_right">
|
||||
<div class="beyond_panel_title">
|
||||
<span class="beyond_panel_app" t-esc="currentApp.name"/>
|
||||
<span class="beyond_panel_company" t-esc="beyondEmpresa"/>
|
||||
</div>
|
||||
<Dropdown menuClass="'beyond_panel_usermenu'">
|
||||
<!-- o-dropdown-toggle-custo NO es decorativa. Dropdown
|
||||
agrega «dropdown-toggle» al disparador, y el navbar
|
||||
de Odoo estiliza
|
||||
`.o_main_navbar .dropdown-toggle:not(.o-dropdown-toggle-custo)`
|
||||
con más especificidad (0,3,0) que
|
||||
`body.beyond_panel .beyond_panel_avatar` (0,2,1):
|
||||
el avatar salía transparente y de 63×46 px en vez
|
||||
del cuadro naranja de 34. Esta clase es la salida
|
||||
que el propio core ofrece para no entrar en una
|
||||
guerra de especificidad. -->
|
||||
<button class="beyond_panel_avatar o-dropdown-toggle-custo"
|
||||
t-att-title="beyondUser.name"
|
||||
t-att-aria-label="beyondUser.name">
|
||||
<img t-if="beyondTieneFoto" t-att-src="beyondAvatarUrl" alt=""/>
|
||||
<t t-else="" t-esc="beyondInicial"/>
|
||||
</button>
|
||||
<t t-set-slot="content">
|
||||
<DropdownItem onSelected="() => this.beyondAbrirPreferencias()">
|
||||
<svg width="17" height="17" viewBox="0 0 24 24" fill="none" aria-hidden="true">
|
||||
<circle cx="12" cy="12" r="3.1" stroke="currentColor" stroke-width="1.8"/>
|
||||
<path d="M12 3.4v2.4M12 18.2v2.4M4.6 12H7M17 12h2.4M6.8 6.8l1.7 1.7M15.5 15.5l1.7 1.7M17.2 6.8l-1.7 1.7M8.5 15.5l-1.7 1.7" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>
|
||||
</svg>
|
||||
<span>Mis preferencias</span>
|
||||
</DropdownItem>
|
||||
<DropdownItem class="'beyond_panel_salir'"
|
||||
onSelected="() => this.beyondCerrarSesion()">
|
||||
<svg width="17" height="17" viewBox="0 0 24 24" fill="none" aria-hidden="true">
|
||||
<path d="M14.4 4.2H6.6A1.4 1.4 0 0 0 5.2 5.6v12.8a1.4 1.4 0 0 0 1.4 1.4h7.8" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>
|
||||
<path d="M14.8 12h5M17.4 9.2 20.2 12l-2.8 2.8" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
<span>Cerrar sesión</span>
|
||||
</DropdownItem>
|
||||
</t>
|
||||
</Dropdown>
|
||||
</div>
|
||||
</t>
|
||||
</xpath>
|
||||
</t>
|
||||
|
||||
<!--
|
||||
LA BARRA DEL PANEL TAMBIÉN EN PANTALLA CHICA.
|
||||
|
||||
Odoo cambia a su navbar móvil por debajo de cierto ancho: el botón de
|
||||
apps se vuelve una hamburguesa que abre un panel lateral. Nuestra barra
|
||||
se pintaba igual, así que en móvil salían las dos y se estorbaban.
|
||||
|
||||
Dentro del panel se fuerza la rama de escritorio del menú de apps: la
|
||||
casa y el lanzador, que es pantalla completa y funciona igual en un
|
||||
teléfono. Fuera del panel, el móvil de Odoo queda intacto.
|
||||
-->
|
||||
<t t-name="beyond_base.NavBar.AppsMenu.Panel"
|
||||
t-inherit="web.NavBar.AppsMenu" t-inherit-mode="extension">
|
||||
<xpath expr="//t[@t-if='this.ui.isSmall']" position="attributes">
|
||||
<attribute name="t-if">this.ui.isSmall and !beyondEsPanel</attribute>
|
||||
</xpath>
|
||||
</t>
|
||||
|
||||
<!--
|
||||
Ícono de cada pestaña, emparejado por xmlid como hace el lanzador.
|
||||
Es lo ÚNICO que se empareja en duro: una sección que no esté aquí se
|
||||
pinta igual, solo que sin ícono. Así una sección nueva no desaparece
|
||||
por olvidarse de este archivo.
|
||||
-->
|
||||
<t t-name="beyond_base.PanelTabIcon">
|
||||
<t t-if="seccion.xmlid === 'beyond_reports.menu_tablero_general'">
|
||||
<svg width="17" height="17" viewBox="0 0 24 24" fill="none" aria-hidden="true">
|
||||
<path d="M4 19.2h16" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/>
|
||||
<path d="M6.4 15.6V11M11 15.6V6.4M15.6 15.6v-6" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/>
|
||||
<path d="M19.8 6.6 15 11.4l-3-2.6-3.6 3.4" stroke="currentColor" stroke-width="1.7"
|
||||
stroke-linecap="round" stroke-linejoin="round" opacity="0.45"/>
|
||||
</svg>
|
||||
</t>
|
||||
<t t-elif="seccion.xmlid === 'beyond_customer.menu_beyond_clientes'">
|
||||
<svg width="17" height="17" viewBox="0 0 24 24" fill="none" aria-hidden="true">
|
||||
<rect x="2.8" y="4.6" width="18.4" height="14.8" rx="3.4" stroke="currentColor" stroke-width="1.7"/>
|
||||
<circle cx="8.6" cy="10.6" r="2.3" stroke="currentColor" stroke-width="1.7"/>
|
||||
<path d="M5.5 16.4c.6-1.9 1.7-2.8 3.1-2.8s2.5.9 3.1 2.8" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/>
|
||||
<path d="M15.2 10.2h3.4M15.2 13.8h3.4" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/>
|
||||
</svg>
|
||||
</t>
|
||||
<t t-elif="seccion.xmlid === 'beyond_branch.menu_beyond_branch'">
|
||||
<svg width="17" height="17" viewBox="0 0 24 24" fill="none" aria-hidden="true">
|
||||
<path d="M4 9.6V19a1.4 1.4 0 0 0 1.4 1.4h13.2A1.4 1.4 0 0 0 20 19V9.6" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round"/>
|
||||
<path d="M3 9.6 5.2 4h13.6L21 9.6a2.6 2.6 0 0 1-4.5 1.7 2.6 2.6 0 0 1-4.5 0 2.6 2.6 0 0 1-4.5 0A2.6 2.6 0 0 1 3 9.6Z" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
</t>
|
||||
<t t-elif="seccion.xmlid === 'beyond_branch.menu_beyond_catalogo'">
|
||||
<svg width="17" height="17" viewBox="0 0 24 24" fill="none" aria-hidden="true">
|
||||
<path d="M12 3 20.5 7.5v9L12 21 3.5 16.5v-9L12 3Z" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round"/>
|
||||
<path d="M3.5 7.5 12 12l8.5-4.5M12 12v9" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
</t>
|
||||
<t t-elif="seccion.xmlid === 'beyond_branch.menu_personal'">
|
||||
<svg width="17" height="17" viewBox="0 0 24 24" fill="none" aria-hidden="true">
|
||||
<rect x="3.2" y="6.6" width="17.6" height="13.8" rx="2.2" stroke="currentColor" stroke-width="1.7"/>
|
||||
<path d="M9 6.6V5.2A1.4 1.4 0 0 1 10.4 3.8h3.2A1.4 1.4 0 0 1 15 5.2v1.4" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round"/>
|
||||
<circle cx="12" cy="12.4" r="2.3" stroke="currentColor" stroke-width="1.7"/>
|
||||
<path d="M8.2 18.2c.7-1.7 2-2.5 3.8-2.5s3.1.8 3.8 2.5" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/>
|
||||
</svg>
|
||||
</t>
|
||||
</t>
|
||||
</templates>
|
||||
@@ -0,0 +1,407 @@
|
||||
/** Part of Beyond. Collina Systems proprietary module. */
|
||||
import { expect, test, describe } from "@odoo/hoot";
|
||||
import { click, press, queryAll, queryFirst, setInputFiles } from "@odoo/hoot-dom";
|
||||
import { animationFrame } from "@odoo/hoot-mock";
|
||||
import {
|
||||
defineModels,
|
||||
fields,
|
||||
models,
|
||||
mountView,
|
||||
onRpc,
|
||||
patchWithCleanup,
|
||||
} from "@web/../tests/web_test_helpers";
|
||||
import { browser } from "@web/core/browser/browser";
|
||||
import { defineMailModels } from "@mail/../tests/mail_test_helpers";
|
||||
|
||||
/**
|
||||
* Unit tests for beyond_image_camera.
|
||||
*
|
||||
* The one that matters most is the secure-context one: production has no TLS
|
||||
* yet, so navigator.mediaDevices does not exist on the branch tablets and the
|
||||
* widget must not offer a button that would throw. That is the case a person
|
||||
* cannot easily check by hand — dev runs on localhost, where the camera
|
||||
* always works.
|
||||
*/
|
||||
|
||||
describe.current.tags("desktop");
|
||||
|
||||
// Un modelo propio y NO res.partner: montar una vista sobre res.partner
|
||||
// arrastra la maquinaria de mail (el chatter pide discuss.channel) y las
|
||||
// pruebas mueren antes de llegar al widget. Al widget el modelo le da igual.
|
||||
class BeyondFoto extends models.Model {
|
||||
_name = "beyond.foto";
|
||||
|
||||
name = fields.Char();
|
||||
image_1920 = fields.Binary();
|
||||
|
||||
_records = [
|
||||
{ id: 1, name: "Alejandro Mcdonald", image_1920: "FOTO==" },
|
||||
{ id: 2, name: "Ximena", image_1920: false },
|
||||
];
|
||||
}
|
||||
|
||||
// Montar CUALQUIER formulario despierta la maquinaria de mail (el chatter
|
||||
// pide discuss.channel) aunque la vista no lo lleve, porque mail parchea la
|
||||
// vista de formulario en el bundle de pruebas. Sin esto, todas las pruebas
|
||||
// mueren antes de llegar al widget.
|
||||
defineMailModels();
|
||||
defineModels([BeyondFoto]);
|
||||
|
||||
// Lleva el pie propio a propósito: guardar por ahí es lo que hace una
|
||||
// persona en la ficha, y de paso ejercita el widget del pie.
|
||||
const VISTA = /* xml */ `
|
||||
<form>
|
||||
<field name="image_1920" widget="beyond_image_camera"/>
|
||||
<widget name="beyond_form_footer"/>
|
||||
</form>`;
|
||||
|
||||
/**
|
||||
* Fakes a camera: a REAL MediaStream whose track we can watch.
|
||||
*
|
||||
* It has to be a real one. Assigning a plain object to video.srcObject throws
|
||||
* in Chromium ("the provided value is not of type MediaStream"), which showed
|
||||
* up as an opaque "error in the owl lifecycle" and hid what was really being
|
||||
* tested. A canvas gives us a genuine stream with a genuine track.
|
||||
*/
|
||||
function camaraFalsa({ camaras = 1 } = {}) {
|
||||
const lienzo = document.createElement("canvas");
|
||||
lienzo.width = 4;
|
||||
lienzo.height = 4;
|
||||
const stream = lienzo.captureStream();
|
||||
const pista = stream.getVideoTracks()[0];
|
||||
pista.detenida = false;
|
||||
const detenerReal = pista.stop.bind(pista);
|
||||
pista.stop = () => {
|
||||
pista.detenida = true;
|
||||
detenerReal();
|
||||
};
|
||||
pista.peticiones = [];
|
||||
patchWithCleanup(browser, {
|
||||
navigator: {
|
||||
...browser.navigator,
|
||||
mediaDevices: {
|
||||
getUserMedia: async (restricciones) => {
|
||||
pista.peticiones.push(restricciones?.video?.facingMode);
|
||||
return stream;
|
||||
},
|
||||
enumerateDevices: async () =>
|
||||
Array.from({ length: camaras }, () => ({ kind: "videoinput" })),
|
||||
},
|
||||
},
|
||||
});
|
||||
return pista;
|
||||
}
|
||||
|
||||
/** Takes the camera away, the way an http:// page does. */
|
||||
function sinCamara() {
|
||||
patchWithCleanup(browser, {
|
||||
navigator: { ...browser.navigator, mediaDevices: undefined },
|
||||
});
|
||||
}
|
||||
|
||||
test("el menú de la foto se abre al pasar el mouse y se cierra al salir", async () => {
|
||||
camaraFalsa();
|
||||
await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA });
|
||||
|
||||
expect(".beyond_foto_menu").toHaveCount(0);
|
||||
|
||||
await queryFirst(".beyond_foto").dispatchEvent(new MouseEvent("mouseenter"));
|
||||
await animationFrame();
|
||||
expect(".beyond_foto_menu").toHaveCount(1);
|
||||
|
||||
await queryFirst(".beyond_foto").dispatchEvent(new MouseEvent("mouseleave"));
|
||||
await animationFrame();
|
||||
expect(".beyond_foto_menu").toHaveCount(0);
|
||||
});
|
||||
|
||||
test("el contenedor de la foto no recorta el menú", async () => {
|
||||
// ESTA es la prueba que faltaba. El menú se renderizaba —el t-if pasaba y
|
||||
// el DOM lo tenía— pero el contenedor llevaba overflow:hidden para
|
||||
// redondear la imagen, y el menú cuelga por debajo con top:100%: quedaba
|
||||
// recortado y era inalcanzable. Contar elementos no lo detecta, porque el
|
||||
// nodo está ahí; ni :visible, porque un elemento recortado conserva su
|
||||
// tamaño. Lo que hay que afirmar es que nadie lo recorta.
|
||||
camaraFalsa();
|
||||
await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA });
|
||||
|
||||
await click(".beyond_foto");
|
||||
await animationFrame();
|
||||
|
||||
const menu = queryFirst(".beyond_foto_menu");
|
||||
expect(menu).not.toBe(null);
|
||||
// Solo hasta la hoja del formulario: de ahí para arriba el cliente web
|
||||
// recorta a propósito (.o_form_view y .o_action_manager son sus
|
||||
// contenedores de desplazamiento). Lo que no puede recortar es el propio
|
||||
// widget, que es donde estaba el defecto.
|
||||
// Solo los dos nodos que este widget controla. De ahí para arriba el
|
||||
// cliente web recorta a propósito: .o_form_view y .o_action_manager son
|
||||
// sus contenedores de desplazamiento y siempre llevan overflow:hidden.
|
||||
for (const selector of [".beyond_foto", ".o_field_widget[name=image_1920]"]) {
|
||||
const nodo = queryFirst(selector);
|
||||
if (!nodo) {
|
||||
continue;
|
||||
}
|
||||
const estilo = getComputedStyle(nodo);
|
||||
expect(`${estilo.overflow} ${estilo.overflowY}`).not.toInclude("hidden", {
|
||||
message: `${selector} recorta el menú de la foto`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test("las opciones del menú están a la vista, no solo en el DOM", async () => {
|
||||
// Misma lección que las estadísticas del encabezado: un elemento tapado
|
||||
// tiene las mismas coordenadas que uno visible, y contar nodos no lo
|
||||
// distingue. Aquí ya nos costó una vez —el menú se renderizaba recortado—
|
||||
// así que se pregunta qué hay realmente en ese punto.
|
||||
camaraFalsa();
|
||||
await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA });
|
||||
|
||||
await click(".beyond_foto");
|
||||
await animationFrame();
|
||||
|
||||
for (const opcion of queryAll(".beyond_foto_opcion")) {
|
||||
const caja = opcion.getBoundingClientRect();
|
||||
const encima = document.elementFromPoint(
|
||||
Math.round(caja.left + caja.width / 2),
|
||||
Math.round(caja.top + caja.height / 2)
|
||||
);
|
||||
expect(!!encima?.closest(".beyond_foto_opcion")).toBe(true, {
|
||||
message: `«${opcion.textContent.trim()}» no está a la vista`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test("un toque fija el menú y otro lo suelta (en táctil no hay hover)", async () => {
|
||||
camaraFalsa();
|
||||
await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA });
|
||||
|
||||
await click(".beyond_foto");
|
||||
await animationFrame();
|
||||
expect(".beyond_foto_menu").toHaveCount(1);
|
||||
|
||||
// Fijado: salir con el mouse ya no lo cierra.
|
||||
await queryFirst(".beyond_foto").dispatchEvent(new MouseEvent("mouseleave"));
|
||||
await animationFrame();
|
||||
expect(".beyond_foto_menu").toHaveCount(1);
|
||||
|
||||
await click(".beyond_foto");
|
||||
await animationFrame();
|
||||
expect(".beyond_foto_menu").toHaveCount(0);
|
||||
});
|
||||
|
||||
test("sin cámara no se ofrece «Tomar fotografía», y sí «Subir archivo»", async () => {
|
||||
// Es el caso de las tablets de sucursal mientras producción no tenga TLS:
|
||||
// fuera de contexto seguro el navegador ni siquiera define mediaDevices.
|
||||
sinCamara();
|
||||
await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA });
|
||||
|
||||
await click(".beyond_foto");
|
||||
await animationFrame();
|
||||
|
||||
const opciones = queryAll(".beyond_foto_opcion").map((b) => b.textContent.trim());
|
||||
expect(opciones).not.toInclude("Tomar fotografía");
|
||||
expect(opciones).toInclude("Subir archivo");
|
||||
});
|
||||
|
||||
test("con cámara sí se ofrece «Tomar fotografía»", async () => {
|
||||
camaraFalsa();
|
||||
await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA });
|
||||
|
||||
await click(".beyond_foto");
|
||||
await animationFrame();
|
||||
|
||||
const opciones = queryAll(".beyond_foto_opcion").map((b) => b.textContent.trim());
|
||||
expect(opciones).toInclude("Tomar fotografía");
|
||||
});
|
||||
|
||||
test("«Subir archivo» pide la cámara trasera, no la frontal", async () => {
|
||||
// Coherencia con el diálogo propio: el caso de uso es el mostrador
|
||||
// fotografiando al cliente, no una selfie.
|
||||
sinCamara();
|
||||
await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA });
|
||||
|
||||
await click(".beyond_foto");
|
||||
await animationFrame();
|
||||
|
||||
expect("input[type=file]").toHaveAttribute("capture", "environment");
|
||||
});
|
||||
|
||||
test("«Eliminar» limpia el campo", async () => {
|
||||
camaraFalsa();
|
||||
await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA });
|
||||
|
||||
await click(".beyond_foto");
|
||||
await animationFrame();
|
||||
await click(".beyond_foto_borrar");
|
||||
await animationFrame();
|
||||
|
||||
// Sin imagen no hay nada que borrar: la opción desaparece.
|
||||
expect(".beyond_foto_borrar").toHaveCount(0);
|
||||
});
|
||||
|
||||
test("cerrar el diálogo apaga la cámara", async () => {
|
||||
// Una cámara que se queda encendida deja el testigo del aparato prendido
|
||||
// y parece que el local está grabando.
|
||||
const pista = camaraFalsa();
|
||||
await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA });
|
||||
|
||||
await click(".beyond_foto");
|
||||
await animationFrame();
|
||||
await click(".beyond_foto_opcion"); // «Tomar fotografía»
|
||||
await animationFrame();
|
||||
await animationFrame();
|
||||
expect(".beyond_camara_video").toHaveCount(1);
|
||||
expect(pista.detenida).toBe(false);
|
||||
|
||||
await click(".beyond_camara_dialogo .modal-footer button:contains(Cancelar)");
|
||||
await animationFrame();
|
||||
|
||||
expect(pista.detenida).toBe(true);
|
||||
});
|
||||
|
||||
test("con una sola cámara no se ofrece cambiarla", async () => {
|
||||
camaraFalsa({ camaras: 1 });
|
||||
await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA });
|
||||
|
||||
await click(".beyond_foto");
|
||||
await animationFrame();
|
||||
await click(".beyond_foto_opcion");
|
||||
await animationFrame();
|
||||
await animationFrame();
|
||||
|
||||
const botones = queryAll(".beyond_camara_dialogo .modal-footer .btn").map((b) =>
|
||||
b.textContent.trim()
|
||||
);
|
||||
expect(botones).not.toInclude("Cambiar de cámara");
|
||||
});
|
||||
|
||||
|
||||
test("el diálogo pide la cámara TRASERA por defecto", async () => {
|
||||
// El caso de uso es el mostrador retratando al cliente, no una selfie.
|
||||
const pista = camaraFalsa();
|
||||
await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA });
|
||||
|
||||
await click(".beyond_foto");
|
||||
await animationFrame();
|
||||
await click(".beyond_foto_opcion");
|
||||
await animationFrame();
|
||||
await animationFrame();
|
||||
|
||||
expect(pista.peticiones[0]).toBe("environment");
|
||||
});
|
||||
|
||||
test("el botón de cambio pasa a la cámara frontal", async () => {
|
||||
const pista = camaraFalsa({ camaras: 2 });
|
||||
await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA });
|
||||
|
||||
await click(".beyond_foto");
|
||||
await animationFrame();
|
||||
await click(".beyond_foto_opcion");
|
||||
await animationFrame();
|
||||
await animationFrame();
|
||||
|
||||
await click(".beyond_camara_dialogo .modal-footer button:contains(Cambiar)");
|
||||
await animationFrame();
|
||||
await animationFrame();
|
||||
|
||||
expect(pista.peticiones).toEqual(["environment", "user"]);
|
||||
});
|
||||
|
||||
test("cerrar con Escape también apaga la cámara", async () => {
|
||||
// Cerrar con el teclado es la salida que más se olvida, y una cámara
|
||||
// encendida deja el testigo del aparato prendido.
|
||||
const pista = camaraFalsa();
|
||||
await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA });
|
||||
|
||||
await click(".beyond_foto");
|
||||
await animationFrame();
|
||||
await click(".beyond_foto_opcion");
|
||||
await animationFrame();
|
||||
await animationFrame();
|
||||
expect(".beyond_camara_video").toHaveCount(1);
|
||||
|
||||
await press("Escape");
|
||||
await animationFrame();
|
||||
|
||||
expect(".beyond_camara_dialogo").toHaveCount(0);
|
||||
expect(pista.detenida).toBe(true);
|
||||
});
|
||||
|
||||
/**
|
||||
* Lo que se guarda de verdad.
|
||||
*
|
||||
* Las pruebas de arriba miran el menú; ninguna miraba el REGISTRO. Y ahí
|
||||
* estaba el defecto: subir un archivo pintaba la imagen y no la escribía, así
|
||||
* que al guardar no viajaba. Estas tres afirman lo único que le importa a
|
||||
* quien atiende el mostrador — que la foto quede — por las tres rutas.
|
||||
*/
|
||||
function capturarGuardado() {
|
||||
const guardado = { valores: null };
|
||||
onRpc("beyond.foto", "web_save", ({ args }) => {
|
||||
guardado.valores = args[1];
|
||||
});
|
||||
return guardado;
|
||||
}
|
||||
|
||||
const PIXEL =
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==";
|
||||
|
||||
test("«Tomar fotografía» deja la imagen en el registro al guardar", async () => {
|
||||
camaraFalsa();
|
||||
const guardado = capturarGuardado();
|
||||
await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA });
|
||||
|
||||
await click(".beyond_foto");
|
||||
await animationFrame();
|
||||
await click(".beyond_foto_opcion");
|
||||
await animationFrame();
|
||||
await animationFrame();
|
||||
await click(".beyond_camara_dialogo .modal-footer button:contains(Tomar)");
|
||||
await animationFrame();
|
||||
await click(".beyond_boton_guardar");
|
||||
await animationFrame();
|
||||
|
||||
expect(guardado.valores).not.toBe(null);
|
||||
expect(guardado.valores.image_1920).toBeOfType("string");
|
||||
});
|
||||
|
||||
test("«Subir archivo» deja la imagen en el registro al guardar", async () => {
|
||||
// La ruta que estaba rota: la imagen se pintaba y no se escribía.
|
||||
sinCamara();
|
||||
const guardado = capturarGuardado();
|
||||
await mountView({ type: "form", resModel: "beyond.foto", resId: 2, arch: VISTA });
|
||||
|
||||
await click(".beyond_foto");
|
||||
await animationFrame();
|
||||
await click(".beyond_foto_opcion:contains(Subir)");
|
||||
await animationFrame();
|
||||
await setInputFiles([
|
||||
new File([Uint8Array.from(atob(PIXEL), (c) => c.charCodeAt(0))], "cliente.png", {
|
||||
type: "image/png",
|
||||
}),
|
||||
]);
|
||||
await animationFrame();
|
||||
await animationFrame();
|
||||
await click(".beyond_boton_guardar");
|
||||
await animationFrame();
|
||||
|
||||
expect(guardado.valores).not.toBe(null);
|
||||
expect(guardado.valores.image_1920).toBeOfType("string");
|
||||
});
|
||||
|
||||
test("«Eliminar» deja el campo vacío en el registro al guardar", async () => {
|
||||
// La tercera ruta, que nadie había probado.
|
||||
camaraFalsa();
|
||||
const guardado = capturarGuardado();
|
||||
await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA });
|
||||
|
||||
await click(".beyond_foto");
|
||||
await animationFrame();
|
||||
await click(".beyond_foto_borrar");
|
||||
await animationFrame();
|
||||
await click(".beyond_boton_guardar");
|
||||
await animationFrame();
|
||||
|
||||
expect(guardado.valores).not.toBe(null);
|
||||
expect(guardado.valores.image_1920).toBe(false);
|
||||
});
|
||||
@@ -1,3 +1,11 @@
|
||||
from . import test_idioma
|
||||
from . import test_login
|
||||
from . import test_menu_cleanup
|
||||
from . import test_security_groups
|
||||
from . import test_signup
|
||||
from . import test_panel_navbar
|
||||
from . import test_unitarias_js
|
||||
from . import test_panel_navegador
|
||||
from . import test_silencio_saliente
|
||||
from . import test_url_publica
|
||||
from . import test_plantillas_owl
|
||||
@@ -0,0 +1,149 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
import os
|
||||
import re
|
||||
|
||||
from odoo.tests import HttpCase, tagged
|
||||
|
||||
MODULE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
LOGO_PATH = os.path.join(MODULE_PATH, 'static', 'img', 'logo_login.png')
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestBeyondLogin(HttpCase):
|
||||
"""Pantalla de inicio de sesión (login v1).
|
||||
|
||||
Lo que se protege aquí no es el aspecto — eso se revisa en el navegador —
|
||||
sino que el rediseño no se haya llevado por delante la autenticación: el
|
||||
formulario real de Odoo, su POST, su csrf_token y su redirect siguen
|
||||
donde estaban, y los errores los sigue escribiendo el servidor.
|
||||
"""
|
||||
|
||||
LOGIN = 'prueba.login@beyond.example'
|
||||
CLAVE = 'clave-de-prueba-login-8'
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
# Cuenta propia: la contraseña de admin depende de cada instalación y
|
||||
# una prueba de autenticación no puede apoyarse en ella.
|
||||
self.usuario = self.env['res.users'].create({
|
||||
'name': 'Prueba Login',
|
||||
'login': self.LOGIN,
|
||||
'password': self.CLAVE,
|
||||
})
|
||||
self.pagina = self.url_open('/web/login')
|
||||
self.assertEqual(self.pagina.status_code, 200)
|
||||
self.html = self.pagina.text
|
||||
|
||||
# -- El formulario real ---------------------------------------------------
|
||||
|
||||
def test_el_post_de_odoo_sigue_intacto(self):
|
||||
"""Un <form> de verdad contra /web/login: Enter envía sin JavaScript."""
|
||||
formulario = re.search(r'<form[^>]*class="[^"]*oe_login_form[^"]*"[^>]*>',
|
||||
self.html)
|
||||
self.assertTrue(formulario, "el formulario de Odoo tiene que seguir ahí")
|
||||
etiqueta = formulario.group(0)
|
||||
self.assertIn('action="/web/login"', etiqueta)
|
||||
self.assertIn('method="post"', etiqueta)
|
||||
|
||||
def test_los_campos_que_lee_el_controlador(self):
|
||||
for campo in ('csrf_token', 'login', 'password', 'type', 'redirect'):
|
||||
self.assertIn(f'name="{campo}"', self.html,
|
||||
f"sin name=\"{campo}\" el controlador no autentica")
|
||||
|
||||
def test_el_csrf_token_va_con_valor(self):
|
||||
token = re.search(r'name="csrf_token" value="([^"]+)"', self.html)
|
||||
self.assertTrue(token and token.group(1),
|
||||
"el csrf_token se renderiza vacío: el POST sería rechazado")
|
||||
|
||||
def test_autocompletado_en_los_dos_campos(self):
|
||||
self.assertIn('autocomplete="username"', self.html)
|
||||
self.assertIn('autocomplete="current-password"', self.html)
|
||||
|
||||
def test_el_formulario_se_ve(self):
|
||||
"""web.login lo trae oculto con d-none y deja que el conmutador de
|
||||
usuarios de Odoo 19 decida. Ese conmutador no se usa (ver la plantilla),
|
||||
así que el formulario no puede quedar escondido."""
|
||||
self.assertNotIn('web.user_switch', self.html)
|
||||
formulario = re.search(r'<form[^>]*oe_login_form[^>]*>', self.html).group(0)
|
||||
self.assertNotIn('d-none', formulario)
|
||||
|
||||
# -- El diseño ------------------------------------------------------------
|
||||
|
||||
def test_la_pantalla_es_la_del_diseno(self):
|
||||
self.assertIn('class="beyond_login"', self.html)
|
||||
self.assertIn('beyond_login_brand', self.html)
|
||||
self.assertIn('/beyond_base/static/img/logo_login.png', self.html)
|
||||
self.assertIn('Iniciar sesión', self.html)
|
||||
# La firma es la misma que la del Menú Principal, en inglés y a
|
||||
# propósito (ver views/login_templates.xml).
|
||||
self.assertIn('Powered by Collina Systems', self.html)
|
||||
|
||||
def test_sin_el_envoltorio_de_odoo(self):
|
||||
"""Ni la tarjeta de 300px, ni el logo de la compañía encima, ni el pie
|
||||
con «Gestionar bases de datos» y la marca de Odoo."""
|
||||
self.assertNotIn('/web/binary/company_logo', self.html)
|
||||
self.assertNotIn('/web/database/manager', self.html)
|
||||
self.assertNotIn('utm_medium=auth', self.html)
|
||||
|
||||
def test_el_boton_del_ojo_se_anuncia(self):
|
||||
ojo = re.search(r'<button[^>]*beyond_login_eye[^>]*>', self.html)
|
||||
self.assertTrue(ojo, "falta el botón que muestra la contraseña")
|
||||
self.assertIn('type="button"', ojo.group(0),
|
||||
"sin type=button el ojo enviaría el formulario")
|
||||
self.assertIn('aria-label="Mostrar contraseña"', ojo.group(0))
|
||||
self.assertIn('aria-pressed="false"', ojo.group(0))
|
||||
|
||||
def test_el_enlace_de_contrasena_apunta_a_la_ruta_real(self):
|
||||
"""Es el interruptor de auth_signup, no un adorno: encendido en
|
||||
Ajustes, el enlace existe y lleva a /web/reset_password."""
|
||||
habilitado = self.env['ir.config_parameter'].sudo().get_param(
|
||||
'auth_signup.reset_password')
|
||||
if habilitado:
|
||||
self.assertIn('/web/reset_password', self.html)
|
||||
self.assertIn('¿Olvidaste tu contraseña?', self.html)
|
||||
else:
|
||||
self.assertNotIn('/web/reset_password', self.html)
|
||||
|
||||
def test_sin_alta_por_cuenta_propia(self):
|
||||
"""A Beyond se entra dado de alta por la administración (ADR-008)."""
|
||||
self.assertNotIn('/web/signup', self.html)
|
||||
|
||||
def test_el_logo_pesa_lo_que_debe(self):
|
||||
"""1.2 MB delante de la sesión es inaceptable; el techo es 100 KB."""
|
||||
self.assertTrue(os.path.exists(LOGO_PATH))
|
||||
self.assertLess(os.path.getsize(LOGO_PATH), 100 * 1024)
|
||||
servido = self.url_open('/beyond_base/static/img/logo_login.png')
|
||||
self.assertEqual(servido.status_code, 200)
|
||||
|
||||
# -- Los mensajes los escribe el servidor ---------------------------------
|
||||
|
||||
def _entrar(self, login, password):
|
||||
csrf = re.search(r'name="csrf_token" value="([^"]+)"', self.html).group(1)
|
||||
return self.url_open('/web/login', allow_redirects=False, data={
|
||||
'login': login,
|
||||
'password': password,
|
||||
'csrf_token': csrf,
|
||||
'type': 'password',
|
||||
'redirect': '',
|
||||
})
|
||||
|
||||
def test_credenciales_malas_muestran_el_error_de_odoo(self):
|
||||
respuesta = self._entrar(self.LOGIN, 'esta-no-es-la-contrasena')
|
||||
self.assertEqual(respuesta.status_code, 200, "se queda en el login")
|
||||
self.assertIn('beyond_login_error', respuesta.text,
|
||||
"el mensaje del servidor se pinta con el estilo del diseño")
|
||||
self.assertNotIn('alert alert-danger', respuesta.text,
|
||||
"la caja de alerta de Bootstrap no debe sobrevivir")
|
||||
# El texto es el de Odoo, no uno inventado por la pantalla.
|
||||
error = re.search(r'class="beyond_login_error"[^>]*>(.*?)</p>',
|
||||
respuesta.text, re.S)
|
||||
self.assertTrue(error and error.group(1).strip(),
|
||||
"el hueco del error está vacío")
|
||||
|
||||
def test_credenciales_buenas_redirigen(self):
|
||||
"""No hay pantalla de «Bienvenido»: Odoo redirige y el usuario cae en
|
||||
el Menú Principal."""
|
||||
respuesta = self._entrar(self.LOGIN, self.CLAVE)
|
||||
self.assertIn(respuesta.status_code, (302, 303),
|
||||
"una autenticación correcta sale del login redirigiendo")
|
||||
self.assertNotIn('Bienvenido,', respuesta.text)
|
||||
@@ -0,0 +1,110 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
from lxml import etree
|
||||
|
||||
from odoo.tests import TransactionCase, tagged
|
||||
from odoo.tools.template_inheritance import apply_inheritance_specs
|
||||
|
||||
BUNDLE = 'web.assets_backend'
|
||||
ARCHIVO = 'beyond_panel_navbar.xml'
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestPanelNavbar(TransactionCase):
|
||||
"""La barra del Panel General se injerta en web.NavBar por herencia
|
||||
(ADR-013). El modo de fallo real de una herencia así es que un xpath deje
|
||||
de encontrar su nodo tras un upgrade de Odoo — y entonces la barra
|
||||
desaparece sin un solo error en el servidor.
|
||||
|
||||
Este entorno NO tiene navegador (no hay chromium en el contenedor), así
|
||||
que no se puede correr un tour. Lo que sí se puede es aplicar las mismas
|
||||
especificaciones de herencia con el motor de xpath de Odoo: si un xpath
|
||||
no encuentra su nodo, apply_inheritance_specs levanta, igual que
|
||||
levantaría OWL en el navegador.
|
||||
|
||||
NOTA para quien busque la plantilla: una en modo "extension" NO viaja en
|
||||
los bloques de tipo "templates" del bundle sino en los de tipo
|
||||
"extensions" (AssetsBundle.xml), porque es un parche sobre otra y no una
|
||||
plantilla nueva. Odoo la manda tal cual al navegador y es OWL quien
|
||||
resuelve el xpath allá — por eso el servidor nunca se queja de un xpath
|
||||
roto y por eso hace falta este test. Le pasa igual a la del lanzador.
|
||||
"""
|
||||
|
||||
def _bloques(self):
|
||||
nodos = self.env['ir.qweb']._get_asset_bundle(BUNDLE).xml()
|
||||
return nodos if isinstance(nodos, list) else [nodos]
|
||||
|
||||
def _plantillas(self):
|
||||
"""(elemento, ruta) de cada plantilla NUEVA del bundle del backend."""
|
||||
return [(elemento, ruta or '')
|
||||
for nodo in self._bloques()
|
||||
if isinstance(nodo, dict) and nodo.get('type') == 'templates'
|
||||
for elemento, ruta, _extra in nodo['templates']]
|
||||
|
||||
def _extensiones(self, padre):
|
||||
"""(elemento, ruta) de cada PARCHE declarado sobre `padre`."""
|
||||
return [(elemento, ruta or '')
|
||||
for nodo in self._bloques()
|
||||
if isinstance(nodo, dict) and nodo.get('type') == 'extensions'
|
||||
for elemento, ruta in nodo['extensions'].get(padre, [])]
|
||||
|
||||
def _navbar_base(self):
|
||||
base = [e for e, _r in self._plantillas()
|
||||
if e.get('t-name') == 'web.NavBar' and not e.get('t-inherit')]
|
||||
self.assertTrue(base, "no se encontró la plantilla nativa web.NavBar")
|
||||
return base[0]
|
||||
|
||||
def _herencia_del_panel(self):
|
||||
herencia = [e for e, r in self._extensiones('web.NavBar')
|
||||
if r.endswith(ARCHIVO)]
|
||||
self.assertTrue(
|
||||
herencia,
|
||||
f"{ARCHIVO} no llegó a {BUNDLE}: revisa el manifiesto de beyond_base")
|
||||
# apply_inheritance_specs espera la forma de un arch heredado: un
|
||||
# <data> con las especificaciones dentro. La plantilla del bundle
|
||||
# trae los mismos <xpath> colgando de su <t>, así que se reenvuelven.
|
||||
specs = etree.Element('data')
|
||||
for spec in herencia[0]:
|
||||
specs.append(etree.fromstring(etree.tostring(spec)))
|
||||
return specs
|
||||
|
||||
def test_la_barra_esta_en_el_bundle(self):
|
||||
"""Un olvido en el manifiesto deja la barra fuera sin avisar."""
|
||||
self._herencia_del_panel()
|
||||
iconos = [e for e, _r in self._plantillas()
|
||||
if e.get('t-name') == 'beyond_base.PanelTabIcon']
|
||||
self.assertTrue(iconos, "faltan los íconos de las pestañas")
|
||||
|
||||
def test_los_xpath_del_navbar_encuentran_su_nodo(self):
|
||||
base = self._navbar_base()
|
||||
herencia = self._herencia_del_panel()
|
||||
|
||||
origen = etree.fromstring(etree.tostring(base))
|
||||
# Si un xpath no encuentra su nodo, esto levanta.
|
||||
resultado = apply_inheritance_specs(origen, herencia)
|
||||
texto = etree.tostring(resultado, encoding='unicode')
|
||||
|
||||
self.assertIn('beyond_panel_tabs', texto,
|
||||
"las pestañas no se injertaron en el navbar")
|
||||
self.assertIn('beyond_panel_avatar', texto,
|
||||
"el avatar y su menú no se injertaron en el navbar")
|
||||
self.assertIn('beyond_panel_company', texto,
|
||||
"el nombre de la empresa no se injertó en el navbar")
|
||||
|
||||
def test_lo_nativo_se_apaga_solo_dentro_del_panel(self):
|
||||
"""Fuera de la app Panel General el navbar tiene que quedar intacto:
|
||||
las piezas nativas se apagan con una condición, no se borran."""
|
||||
resultado = apply_inheritance_specs(
|
||||
etree.fromstring(etree.tostring(self._navbar_base())),
|
||||
self._herencia_del_panel())
|
||||
|
||||
systray = resultado.xpath("//div[contains(@class, 'o_menu_systray')]")
|
||||
self.assertTrue(systray, "el systray nativo no debe eliminarse")
|
||||
self.assertEqual(systray[0].get('t-if'), '!beyondEsPanel')
|
||||
|
||||
secciones = resultado.xpath("//t[@t-call='web.NavBar.SectionsMenu']")
|
||||
self.assertTrue(secciones, "las secciones nativas no deben eliminarse")
|
||||
self.assertIn('!beyondEsPanel', secciones[0].get('t-if'))
|
||||
|
||||
marca = resultado.xpath("//DropdownItem[@t-esc='currentApp.name']")
|
||||
self.assertTrue(marca, "el título nativo de la app no debe eliminarse")
|
||||
self.assertIn('!beyondEsPanel', marca[0].get('t-if'))
|
||||
@@ -0,0 +1,419 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
from odoo.tests import HttpCase, tagged
|
||||
|
||||
# El naranja del panel, tal como lo devuelve getComputedStyle.
|
||||
NARANJA = 'rgb(197, 90, 34)'
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestPanelEnNavegador(HttpCase):
|
||||
"""La barra del Panel General, mirada en un navegador de verdad.
|
||||
|
||||
Existe por un defecto que ninguna prueba de servidor podía ver: el avatar
|
||||
se pintaba transparente y de 63×46 px en lugar del cuadro naranja, porque
|
||||
el componente Dropdown le agrega la clase «dropdown-toggle» y el navbar de
|
||||
Odoo la estiliza con más especificidad que nuestro selector. El arch era
|
||||
correcto, el SCSS existía y el resultado estaba mal: solo el navegador
|
||||
puede decirlo.
|
||||
"""
|
||||
|
||||
def test_el_avatar_es_el_cuadro_naranja(self):
|
||||
self.browser_js(
|
||||
"/odoo",
|
||||
"""
|
||||
(async () => {
|
||||
const esperar = (ms) => new Promise(r => setTimeout(r, ms));
|
||||
const hasta = async (sel) => {
|
||||
for (let i = 0; i < 60; i++) {
|
||||
const e = document.querySelector(sel);
|
||||
if (e) return e;
|
||||
await esperar(250);
|
||||
}
|
||||
throw new Error('no apareció ' + sel);
|
||||
};
|
||||
// El lanzador es la primera pantalla (ADR-005): se entra al
|
||||
// panel como entra una persona, no por URL de acción.
|
||||
(await hasta('[data-menu-xmlid="beyond_branch.menu_beyond_root"]')).click();
|
||||
const avatar = await hasta('.beyond_panel_avatar');
|
||||
await esperar(1000);
|
||||
|
||||
const s = getComputedStyle(avatar);
|
||||
if (!document.body.classList.contains('beyond_panel')) {
|
||||
throw new Error('el <body> no lleva la clase del panel');
|
||||
}
|
||||
// La barra es la pieza principal de la pantalla: si vuelve a
|
||||
// encogerse, esto lo dice.
|
||||
const barra = document.querySelector('.o_main_navbar')
|
||||
.getBoundingClientRect();
|
||||
if (barra.height < 70) {
|
||||
throw new Error('la barra superior se encogió: ' + barra.height);
|
||||
}
|
||||
// La casa es la compartida con el lanzador, no un icono de
|
||||
// fuente parecido.
|
||||
const todas = document.querySelectorAll('.beyond_casa');
|
||||
const casa = document.querySelector('.o_navbar_apps_menu button .beyond_casa');
|
||||
if (!casa) {
|
||||
const donde = [...todas].map((c) => c.parentElement.className || c.parentElement.tagName);
|
||||
throw new Error('casas en la página: ' + todas.length + ' en [' + donde.join(' | ') + ']');
|
||||
}
|
||||
if (!casa) {
|
||||
throw new Error('la casa de la barra no es la compartida');
|
||||
}
|
||||
const casaCaja = casa.getBoundingClientRect();
|
||||
const iconoPestana = document.querySelector('.beyond_panel_tab svg')
|
||||
.getBoundingClientRect();
|
||||
// Se mide el RENDER, no la regla: el defecto que esto caza es
|
||||
// que la casa se encoja dentro del botón aunque su ancho esté
|
||||
// declarado, que es lo que pasaba con el relleno heredado.
|
||||
if (casaCaja.width < iconoPestana.width) {
|
||||
throw new Error('la casa pesa menos que un icono de pestaña: '
|
||||
+ Math.round(casaCaja.width) + ' contra '
|
||||
+ Math.round(iconoPestana.width));
|
||||
}
|
||||
if (getComputedStyle(casa).color !== 'rgb(35, 32, 29)') {
|
||||
throw new Error('la casa no va en tinta: '
|
||||
+ getComputedStyle(casa).color);
|
||||
}
|
||||
if (!document.querySelector('.beyond_panel_tabs')) {
|
||||
throw new Error('la barra del panel no tiene pestañas');
|
||||
}
|
||||
if (document.querySelector('.o_menu_systray')) {
|
||||
throw new Error('el systray nativo sigue visible dentro del panel');
|
||||
}
|
||||
if (s.backgroundColor !== '%s') {
|
||||
throw new Error('el avatar no es el cuadro naranja: ' + s.backgroundColor);
|
||||
}
|
||||
// El tope existe para cazar el caso sin estilo, que salía de
|
||||
// 63×46; el cuadro del diseño es de 42.
|
||||
if (parseInt(s.width, 10) > 48 || parseInt(s.height, 10) > 48) {
|
||||
throw new Error('el avatar no conserva su tamaño: ' + s.width + '×' + s.height);
|
||||
}
|
||||
if (s.width !== s.height) {
|
||||
throw new Error('el avatar dejó de ser cuadrado: ' + s.width + '×' + s.height);
|
||||
}
|
||||
|
||||
// En el listado: primero el título de la sección y después
|
||||
// «Nuevo». Se lee dónde estás antes que qué puedes hacer.
|
||||
const migas = document.querySelector('.o_breadcrumb');
|
||||
const nuevo = document.querySelector('.o_control_panel .btn-primary');
|
||||
if (migas && nuevo) {
|
||||
if (nuevo.getBoundingClientRect().left
|
||||
< migas.getBoundingClientRect().right - 1) {
|
||||
throw new Error('«Nuevo» va antes del título en el listado');
|
||||
}
|
||||
}
|
||||
|
||||
// El buscador es UNA barra. La píldora es el contenedor
|
||||
// entero, no el campo: el desplegable de filtros es
|
||||
// HERMANO del campo, así que si el borde va en
|
||||
// .o_searchview el desplegable queda fuera y se ven dos
|
||||
// piezas encimadas. El borde va en la píldora y nada de
|
||||
// lo de dentro lleva caja propia, ni con el foco puesto.
|
||||
const pildora = document.querySelector('.o_cp_searchview');
|
||||
if (pildora) {
|
||||
if (parseFloat(getComputedStyle(pildora).borderTopWidth) <= 0) {
|
||||
throw new Error('la píldora del buscador perdió su borde');
|
||||
}
|
||||
const campo = pildora.querySelector('input');
|
||||
campo.focus();
|
||||
const dentro = [campo, pildora.querySelector('.o_searchview'),
|
||||
pildora.querySelector('.o_searchview_dropdown_toggler')];
|
||||
for (const pieza of dentro) {
|
||||
if (!pieza) { continue; }
|
||||
const cs = getComputedStyle(pieza);
|
||||
const conBorde = parseFloat(cs.borderTopWidth) > 0
|
||||
|| (cs.outlineStyle !== 'none'
|
||||
&& parseFloat(cs.outlineWidth) > 0);
|
||||
if (conBorde) {
|
||||
throw new Error('«' + pieza.className + '» tiene caja '
|
||||
+ 'propia dentro de la píldora: borde '
|
||||
+ cs.borderTopWidth + ', contorno '
|
||||
+ cs.outlineWidth + ' ' + cs.outlineStyle);
|
||||
}
|
||||
}
|
||||
const filtros = pildora.querySelector('.o_searchview_dropdown_toggler');
|
||||
if (filtros) {
|
||||
const caja = pildora.getBoundingClientRect();
|
||||
const suyo = filtros.getBoundingClientRect();
|
||||
if (suyo.right > caja.right + 1 || suyo.left < caja.left - 1) {
|
||||
throw new Error('el desplegable de filtros se sale de '
|
||||
+ 'la píldora: [' + Math.round(suyo.left) + '..'
|
||||
+ Math.round(suyo.right) + '] contra ['
|
||||
+ Math.round(caja.left) + '..'
|
||||
+ Math.round(caja.right) + ']');
|
||||
}
|
||||
}
|
||||
campo.blur();
|
||||
}
|
||||
console.log('test successful');
|
||||
})();
|
||||
""" % NARANJA,
|
||||
"", login='admin', timeout=120)
|
||||
|
||||
def test_la_ficha_del_cliente_tiene_la_forma_del_diseno(self):
|
||||
"""El retrato a la izquierda y los campos A SU LADO.
|
||||
|
||||
Es la comprobación que ninguna prueba de arch puede hacer: los campos
|
||||
pueden estar todos presentes y aun así caer debajo del retrato, que es
|
||||
como se veía cuando la ficha heredaba del formulario de contacto —con
|
||||
media pantalla vacía a la derecha.
|
||||
"""
|
||||
self.browser_js(
|
||||
"/odoo",
|
||||
"""
|
||||
(async () => {
|
||||
const esperar = (ms) => new Promise(r => setTimeout(r, ms));
|
||||
const hasta = async (sel) => {
|
||||
for (let i = 0; i < 60; i++) {
|
||||
const e = document.querySelector(sel);
|
||||
if (e) return e;
|
||||
await esperar(250);
|
||||
}
|
||||
throw new Error('no apareció ' + sel);
|
||||
};
|
||||
(await hasta('[data-menu-xmlid="beyond_branch.menu_beyond_root"]')).click();
|
||||
(await hasta('.o_kanban_record:not(.o_kanban_ghost)')).click();
|
||||
const columna = await hasta('.beyond_cliente_retrato');
|
||||
const foto = await hasta('.beyond_foto');
|
||||
const campos = await hasta('.beyond_cliente_campos');
|
||||
await esperar(1000);
|
||||
|
||||
const r = foto.getBoundingClientRect();
|
||||
const c = campos.getBoundingClientRect();
|
||||
const col = columna.getBoundingClientRect();
|
||||
if (Math.round(col.width) < 180) {
|
||||
throw new Error('la columna del retrato es angosta: ' + col.width);
|
||||
}
|
||||
if (Math.round(r.width) < 180) {
|
||||
throw new Error('la foto no llena su columna: ' + Math.round(r.width)
|
||||
+ ' de ' + Math.round(col.width));
|
||||
}
|
||||
if (Math.abs(r.width / r.height - 0.8) > 0.08) {
|
||||
throw new Error('la foto no guarda la proporción 4:5: '
|
||||
+ Math.round(r.width) + '×' + Math.round(r.height));
|
||||
}
|
||||
if (c.left < r.right) {
|
||||
throw new Error('los campos no están AL LADO del retrato, '
|
||||
+ 'sino debajo (campos.left=' + Math.round(c.left)
|
||||
+ ', retrato.right=' + Math.round(r.right) + ')');
|
||||
}
|
||||
const nombres = [...campos.querySelectorAll('.beyond_campo')].length;
|
||||
if (nombres !== 5) {
|
||||
throw new Error('la columna tiene ' + nombres + ' campos y deben ser 5');
|
||||
}
|
||||
// Las cinco cifras van en la franja del encabezado, entre el
|
||||
// nombre y el paginador, y —lo que de verdad importa— A LA
|
||||
// VISTA: la primera versión medía bien y no se veía, porque el
|
||||
// bloque del paginador se pintaba encima.
|
||||
const tarjetas = document.querySelectorAll('.beyond_ficha_stats .beyond_stat');
|
||||
if (tarjetas.length !== 5) {
|
||||
throw new Error('el encabezado tiene ' + tarjetas.length
|
||||
+ ' tarjetas y deben ser cinco');
|
||||
}
|
||||
const franja = document.querySelector('.o_control_panel');
|
||||
const hoja = document.querySelector('.o_form_sheet');
|
||||
const titulo = document.querySelector('.o_last_breadcrumb_item');
|
||||
const tira = document.querySelector('.beyond_ficha_stats')
|
||||
.getBoundingClientRect();
|
||||
const f = franja.getBoundingClientRect();
|
||||
if (tira.top >= hoja.getBoundingClientRect().top) {
|
||||
throw new Error('la tira quedó dentro de la tarjeta blanca');
|
||||
}
|
||||
if (tira.top < f.top - 1 || tira.bottom > f.bottom + 1) {
|
||||
throw new Error('la tira no cae en la franja del encabezado: '
|
||||
+ 'tira[' + Math.round(tira.top) + '..' + Math.round(tira.bottom)
|
||||
+ '] franja[' + Math.round(f.top) + '..' + Math.round(f.bottom) + ']');
|
||||
}
|
||||
if (tira.left < titulo.getBoundingClientRect().right) {
|
||||
throw new Error('la tira se encima con el título');
|
||||
}
|
||||
const paginador = document.querySelector('.o_pager');
|
||||
if (paginador && tira.right > paginador.getBoundingClientRect().left + 1) {
|
||||
throw new Error('la tira se encima con el paginador');
|
||||
}
|
||||
const centro = document.elementFromPoint(
|
||||
Math.round(tira.left + tira.width / 2),
|
||||
Math.round(tira.top + tira.height / 2));
|
||||
if (!centro || !centro.closest('.beyond_ficha_stats')) {
|
||||
throw new Error('la tira no se ve: en su centro hay '
|
||||
+ (centro ? (centro.className || centro.tagName) : 'nada'));
|
||||
}
|
||||
// A partir de 1200 van en UNA sola línea: partirlas en dos
|
||||
// renglones desordena la franja del encabezado.
|
||||
if (window.innerWidth >= 1200) {
|
||||
const arriba = [...tarjetas].map(
|
||||
(c) => c.getBoundingClientRect().top);
|
||||
if (Math.max(...arriba) - Math.min(...arriba) > 2) {
|
||||
throw new Error('las cinco tarjetas no están alineadas a '
|
||||
+ window.innerWidth + 'px: ' + arriba.map(Math.round).join(', '));
|
||||
}
|
||||
// Un salto de renglón de verdad duplicaría el alto de la
|
||||
// tira respecto al de una tarjeta.
|
||||
const altoTira = document.querySelector('.beyond_ficha_stats')
|
||||
.getBoundingClientRect().height;
|
||||
const altoTarjeta = tarjetas[0].getBoundingClientRect().height;
|
||||
if (altoTira > altoTarjeta * 1.5) {
|
||||
throw new Error('la tira ocupa más de un renglón: '
|
||||
+ Math.round(altoTira) + ' contra ' + Math.round(altoTarjeta));
|
||||
}
|
||||
}
|
||||
|
||||
// Ninguna encimada con su vecina.
|
||||
for (let i = 1; i < tarjetas.length; i++) {
|
||||
const a = tarjetas[i - 1].getBoundingClientRect();
|
||||
const b = tarjetas[i].getBoundingClientRect();
|
||||
if (b.left < a.right - 1 && b.top < a.bottom - 1) {
|
||||
throw new Error('las tarjetas del encabezado se encinan');
|
||||
}
|
||||
}
|
||||
|
||||
// El nombre del cliente comparte eje con «← Clientes».
|
||||
const pastilla = document.querySelector('.o_breadcrumb .breadcrumb-item a')
|
||||
.getBoundingClientRect();
|
||||
const nombre = titulo.getBoundingClientRect();
|
||||
const ejes = Math.abs((pastilla.top + pastilla.bottom) / 2
|
||||
- (nombre.top + nombre.bottom) / 2);
|
||||
if (ejes > 6) {
|
||||
throw new Error('el nombre no está alineado con «← Clientes»: '
|
||||
+ Math.round(ejes) + 'px de diferencia');
|
||||
}
|
||||
if (titulo.textContent.trim().toUpperCase().startsWith('CLIENTES')) {
|
||||
throw new Error('el rótulo «CLIENTES» sigue sobre el nombre');
|
||||
}
|
||||
|
||||
// La tarjeta blanca, centrada EN LA PANTALLA. Medirla contra
|
||||
// su contenedor no sirve: si el contenedor es el que está
|
||||
// descentrado, la tarjeta se ve corrida y la resta da cero.
|
||||
const h = hoja.getBoundingClientRect();
|
||||
// clientWidth y no innerWidth: innerWidth incluye la barra de
|
||||
// desplazamiento, que no forma parte del lienzo, y hacía ver
|
||||
// descentrado lo que estaba centrado por unos 15px.
|
||||
const lienzo = document.documentElement.clientWidth;
|
||||
const izq = h.left;
|
||||
const der = lienzo - h.right;
|
||||
if (Math.abs(izq - der) > 4) {
|
||||
throw new Error('la tarjeta no está centrada: '
|
||||
+ Math.round(izq) + ' a la izquierda y ' + Math.round(der)
|
||||
+ ' a la derecha (lienzo ' + lienzo + ')');
|
||||
}
|
||||
|
||||
// Y alineada con el resto del panel: el título, la barra y la
|
||||
// tarjeta arrancan en el mismo eje.
|
||||
const ejeTitulo = document.querySelector('.o_breadcrumb')
|
||||
.getBoundingClientRect().left;
|
||||
if (Math.abs(h.left - ejeTitulo) > 2) {
|
||||
throw new Error('la tarjeta no comparte eje con el título: '
|
||||
+ Math.round(h.left) + ' contra ' + Math.round(ejeTitulo));
|
||||
}
|
||||
|
||||
// El pie, mirado como se mira todo lo crítico desde el
|
||||
// hallazgo de las estadísticas: no basta con que exista, tiene
|
||||
// que estar A LA VISTA. Un botón de guardar tapado es peor que
|
||||
// uno ausente, porque parece que está.
|
||||
for (const clase of ['beyond_boton_guardar', 'beyond_boton_descartar']) {
|
||||
const boton = document.querySelector('.' + clase);
|
||||
if (!boton) {
|
||||
throw new Error('el pie no tiene ' + clase);
|
||||
}
|
||||
const c = boton.getBoundingClientRect();
|
||||
const encima = document.elementFromPoint(
|
||||
Math.round(c.left + c.width / 2), Math.round(c.top + c.height / 2));
|
||||
if (!encima || !encima.closest('.' + clase)) {
|
||||
throw new Error(clase + ' no se ve: en su centro hay '
|
||||
+ (encima ? (encima.className || encima.tagName) : 'nada'));
|
||||
}
|
||||
}
|
||||
// Se ocultan con CSS, así que siguen en el DOM: lo que se
|
||||
// afirma es que no se VEN.
|
||||
const invisible = (sel) => {
|
||||
const e = document.querySelector(sel);
|
||||
return !e || getComputedStyle(e).display === 'none';
|
||||
};
|
||||
if (!invisible('.o_form_button_create')) {
|
||||
throw new Error('«Nuevo» no va en una ficha: vive en la lista');
|
||||
}
|
||||
if (!invisible('.o_cp_action_menus')) {
|
||||
throw new Error('el engranaje sigue visible en el panel');
|
||||
}
|
||||
const pildora = document.querySelector('.o_breadcrumb .breadcrumb-item a');
|
||||
if (!pildora || getComputedStyle(pildora).borderRadius === '0px') {
|
||||
throw new Error('la miga no es la píldora de vuelta');
|
||||
}
|
||||
// La píldora va sola sobre el fondo del panel: ningún
|
||||
// contenedor suyo puede traer caja blanca ni borde.
|
||||
for (let n = pildora.parentElement;
|
||||
n && !n.classList.contains('o_control_panel');
|
||||
n = n.parentElement) {
|
||||
const s = getComputedStyle(n);
|
||||
const fondo = s.backgroundColor;
|
||||
const opaco = fondo !== 'rgba(0, 0, 0, 0)' && fondo !== 'transparent';
|
||||
if (opaco || parseFloat(s.borderTopWidth) > 0) {
|
||||
throw new Error('la píldora lleva caja detrás: '
|
||||
+ (n.className || n.tagName) + ' → ' + fondo
|
||||
+ ' / borde ' + s.borderTopWidth);
|
||||
}
|
||||
}
|
||||
// La nube y la X nativas serían la misma acción por segunda
|
||||
// vez, y el diseño no las dibuja.
|
||||
const nativos = document.querySelector('.o_form_status_indicator');
|
||||
if (nativos && getComputedStyle(nativos).display !== 'none') {
|
||||
throw new Error('el indicador nativo de guardado sigue visible '
|
||||
+ 'en una ficha que ya tiene pie propio');
|
||||
}
|
||||
console.log('test successful');
|
||||
})();
|
||||
""",
|
||||
"", login='admin', timeout=120)
|
||||
|
||||
def test_guardar_regresa_a_la_lista(self):
|
||||
"""Quedarse en la ficha tras guardar no da señal de que algo pasó: la
|
||||
pantalla no se mueve. Guardar vuelve a donde se venía, con el registro
|
||||
ya visible en la kanban."""
|
||||
self.browser_js(
|
||||
"/odoo",
|
||||
"""
|
||||
(async () => {
|
||||
const esperar = (ms) => new Promise(r => setTimeout(r, ms));
|
||||
const hasta = async (sel) => {
|
||||
for (let i = 0; i < 60; i++) {
|
||||
const e = document.querySelector(sel);
|
||||
if (e) return e;
|
||||
await esperar(250);
|
||||
}
|
||||
throw new Error('no apareció ' + sel);
|
||||
};
|
||||
(await hasta('[data-menu-xmlid="beyond_branch.menu_beyond_root"]')).click();
|
||||
await hasta('.o_kanban_record:not(.o_kanban_ghost)');
|
||||
await esperar(500);
|
||||
const antes = document.querySelectorAll(
|
||||
'.o_kanban_record:not(.o_kanban_ghost)').length;
|
||||
|
||||
// Alta desde la kanban, que es la puerta del diseño.
|
||||
(await hasta('.o_control_panel .btn-primary')).click();
|
||||
const nombre = await hasta('.beyond_campo_titulo input');
|
||||
nombre.value = 'Cliente de prueba del navegador';
|
||||
nombre.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
nombre.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
await esperar(500);
|
||||
|
||||
(await hasta('.beyond_boton_guardar')).click();
|
||||
|
||||
// Debe volver a la kanban, y con una tarjeta más.
|
||||
for (let i = 0; i < 60; i++) {
|
||||
const kanban = document.querySelector('.o_kanban_renderer');
|
||||
if (kanban && !document.querySelector('.beyond_cliente_campos')) {
|
||||
const ahora = document.querySelectorAll(
|
||||
'.o_kanban_record:not(.o_kanban_ghost)').length;
|
||||
if (ahora !== antes + 1) {
|
||||
throw new Error('volvió a la lista pero hay ' + ahora
|
||||
+ ' tarjetas y antes había ' + antes);
|
||||
}
|
||||
console.log('test successful');
|
||||
return;
|
||||
}
|
||||
await esperar(250);
|
||||
}
|
||||
throw new Error('tras guardar seguimos en la ficha');
|
||||
})();
|
||||
""",
|
||||
"", login='admin', timeout=120)
|
||||
@@ -0,0 +1,99 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
"""Guardia contra un fallo que no se ve hasta que alguien toca el botón.
|
||||
|
||||
OWL no evalúa las expresiones de sus plantillas con JavaScript: las compila,
|
||||
y resuelve cada identificador contra el contexto del componente **salvo** los
|
||||
de una lista corta de globales. `Number`, `parseInt`, `JSON`, `document` y
|
||||
compañía NO están en ella, así que `Number(x)` no falla al cargar la página
|
||||
—se compila sin quejarse— sino que sale `undefined` y revienta cuando alguien
|
||||
usa ese control.
|
||||
|
||||
Fue exactamente el bug del selector de sucursales del 27-ago-2026: la
|
||||
pantalla cargaba bien con la sucursal por defecto y tronaba solo al elegir
|
||||
otra, en producción, con un «v2 is not a function» que no dice nada.
|
||||
|
||||
Esta prueba lee las plantillas de todos los módulos `beyond_*` —los de los
|
||||
dos desarrolladores— y falla en la regresión, no en el navegador de alguien.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
|
||||
from lxml import etree
|
||||
|
||||
from odoo.modules.module import get_module_path
|
||||
from odoo.tests import TransactionCase, tagged
|
||||
|
||||
# Los que OWL sí reconoce (owl.js · RESERVED_WORDS). Si un día amplían la
|
||||
# lista, este conjunto es el único lugar que hay que tocar.
|
||||
PERMITIDOS = {
|
||||
'true', 'false', 'NaN', 'null', 'undefined', 'debugger', 'console',
|
||||
'window', 'in', 'instanceof', 'new', 'function', 'return', 'eval', 'void',
|
||||
'Math', 'RegExp', 'Array', 'Object', 'Date', '__globals__',
|
||||
}
|
||||
|
||||
# Los que se cuelan con más facilidad porque en JavaScript normal funcionan.
|
||||
PROHIBIDOS = (
|
||||
'Number', 'String', 'Boolean', 'parseInt', 'parseFloat', 'isNaN',
|
||||
'JSON', 'Set', 'Map', 'Promise', 'Intl', 'Symbol', 'BigInt',
|
||||
'document', 'localStorage', 'sessionStorage', 'fetch', 'alert',
|
||||
'encodeURIComponent', 'decodeURIComponent', 'setTimeout', 'setInterval',
|
||||
)
|
||||
USO = re.compile(r'\b(%s)\s*[(.\[]' % '|'.join(PROHIBIDOS))
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestBeyondPlantillasOwl(TransactionCase):
|
||||
|
||||
def _modulos_beyond(self):
|
||||
nombres = self.env['ir.module.module'].search([
|
||||
('name', '=like', 'beyond_%'),
|
||||
('state', '=', 'installed'),
|
||||
]).mapped('name')
|
||||
return [(nombre, get_module_path(nombre)) for nombre in nombres]
|
||||
|
||||
def _plantillas(self, ruta):
|
||||
estatico = os.path.join(ruta or '', 'static', 'src')
|
||||
for carpeta, _sub, archivos in os.walk(estatico):
|
||||
for archivo in archivos:
|
||||
if archivo.endswith('.xml'):
|
||||
yield os.path.join(carpeta, archivo)
|
||||
|
||||
def test_ninguna_plantilla_llama_a_un_global_que_owl_no_conoce(self):
|
||||
hallazgos = []
|
||||
revisadas = 0
|
||||
for modulo, ruta in self._modulos_beyond():
|
||||
for plantilla in self._plantillas(ruta):
|
||||
revisadas += 1
|
||||
arbol = etree.parse(plantilla)
|
||||
for elemento in arbol.iter():
|
||||
if not isinstance(elemento.tag, str):
|
||||
continue # comentarios
|
||||
for atributo, valor in elemento.attrib.items():
|
||||
# Solo las expresiones: el texto suelto no se compila.
|
||||
if not atributo.startswith('t-'):
|
||||
continue
|
||||
encontrado = USO.search(valor or '')
|
||||
if encontrado:
|
||||
hallazgos.append(
|
||||
f'{modulo} · {os.path.basename(plantilla)} · '
|
||||
f'{atributo}="{valor.strip()[:70]}" usa '
|
||||
f'«{encontrado.group(1)}»')
|
||||
self.assertTrue(revisadas, 'no se revisó ninguna plantilla')
|
||||
self.assertFalse(hallazgos, '\n'.join([
|
||||
'Estas expresiones llaman a un global que OWL no resuelve: se '
|
||||
'compilan sin error y revientan al usarlas. Muévelo al '
|
||||
'componente.', *hallazgos]))
|
||||
|
||||
def test_la_lista_permitida_sigue_siendo_la_de_owl(self):
|
||||
"""Si OWL cambia su lista en una versión nueva, que se entere la
|
||||
regresión y no el navegador de alguien."""
|
||||
ruta = os.path.join(
|
||||
get_module_path('web'), 'static', 'lib', 'owl', 'owl.js')
|
||||
if not os.path.exists(ruta):
|
||||
self.skipTest('no se encontró owl.js en esta instalación')
|
||||
with open(ruta, encoding='utf-8') as fuente:
|
||||
contenido = fuente.read()
|
||||
declarada = re.search(r'RESERVED_WORDS\s*=\s*"([^"]+)"', contenido)
|
||||
self.assertTrue(declarada, 'no se pudo leer la lista de OWL')
|
||||
self.assertEqual(set(declarada.group(1).split(',')), PERMITIDOS,
|
||||
'OWL cambió sus globales: revisa PROHIBIDOS')
|
||||
@@ -35,8 +35,101 @@ class TestBeyondSecurityGroups(TransactionCase):
|
||||
):
|
||||
self.assertEqual(self.env.ref(xmlid).privilege_id, privilege)
|
||||
|
||||
def test_branding_nombre_instancia(self):
|
||||
self.assertEqual(self.env.ref('base.main_company').name, 'Beyond')
|
||||
def test_branding_renombra_una_compania_con_otro_nombre(self):
|
||||
"""La compañía matriz se llama Look Capital (24-ago-2026).
|
||||
|
||||
El test NO comprueba el estado que dejó la instalación: comprueba la
|
||||
función, sobre una compañía que tiene otro nombre. La versión
|
||||
anterior afirmaba el resultado y por eso pasó siempre — el <record>
|
||||
que lo producía nunca se aplicaba al ACTUALIZAR (base.main_company es
|
||||
noupdate) y nadie lo notó, porque en dev la base había nacido limpia.
|
||||
"""
|
||||
compania = self.env.ref('base.main_company')
|
||||
compania.sudo().write({'name': 'Nombre viejo cualquiera'})
|
||||
|
||||
self.env['res.company']._beyond_asegurar_nombre()
|
||||
|
||||
self.assertEqual(
|
||||
compania.name, 'Look Capital',
|
||||
"la función de arranque debe renombrar la compañía matriz aunque "
|
||||
"el módulo se esté ACTUALIZANDO, no instalando")
|
||||
|
||||
def test_branding_no_escribe_si_ya_esta(self):
|
||||
"""Corre en cada arranque de producción: un write incondicional
|
||||
dejaría rastro en write_date y en el seguimiento del registro en cada
|
||||
despliegue, sin motivo."""
|
||||
compania = self.env.ref('base.main_company')
|
||||
compania.sudo().write({'name': 'Look Capital'})
|
||||
self.env.flush_all()
|
||||
marca = '2020-01-01 00:00:00'
|
||||
self.env.cr.execute(
|
||||
"UPDATE res_company SET write_date = %s WHERE id = %s",
|
||||
(marca, compania.id))
|
||||
self.env.invalidate_all()
|
||||
|
||||
self.env['res.company']._beyond_asegurar_nombre()
|
||||
self.env.flush_all()
|
||||
|
||||
self.env.cr.execute(
|
||||
"SELECT write_date FROM res_company WHERE id = %s", (compania.id,))
|
||||
self.assertEqual(
|
||||
self.env.cr.fetchone()[0].strftime('%Y-%m-%d %H:%M:%S'), marca,
|
||||
"el nombre ya era el correcto: no debió escribir")
|
||||
|
||||
def test_datos_de_muestra_se_vacian(self):
|
||||
"""Odoo escribe una dirección de ejemplo en la compañía y el pie del
|
||||
ticket del punto de venta la imprime: un cliente recibiría un
|
||||
comprobante que apunta a 8000 Marina Blvd, Brisbane."""
|
||||
compania = self.env.ref('base.main_company')
|
||||
compania.sudo().write({
|
||||
'street': '8000 Marina Blvd, Suite 300',
|
||||
'city': 'Brisbane',
|
||||
'zip': '94005',
|
||||
'phone': '+1 555-555-5556',
|
||||
'email': 'info@yourcompany.com',
|
||||
'website': 'http://www.example.com',
|
||||
})
|
||||
|
||||
self.env['res.company']._beyond_asegurar_nombre()
|
||||
|
||||
for campo in ('street', 'city', 'zip', 'phone', 'email', 'website'):
|
||||
self.assertFalse(
|
||||
compania[campo],
|
||||
f"{campo} traía el valor de muestra de Odoo y debió vaciarse")
|
||||
|
||||
def test_datos_reales_no_se_tocan(self):
|
||||
"""La comparación es exacta: lo que no sea literalmente uno de los
|
||||
valores de muestra es un dato que alguien capturó. No hay deshacer
|
||||
para una dirección borrada por una heurística."""
|
||||
compania = self.env.ref('base.main_company')
|
||||
reales = {
|
||||
'street': 'Avenida Juárez 1500',
|
||||
'city': 'Puebla',
|
||||
'zip': '72000',
|
||||
'phone': '+52 222 873 3600',
|
||||
'email': 'contacto@lookcapital.mx',
|
||||
'website': 'https://lookcapital.mx',
|
||||
}
|
||||
compania.sudo().write(reales)
|
||||
|
||||
self.env['res.company']._beyond_asegurar_nombre()
|
||||
|
||||
for campo, valor in reales.items():
|
||||
self.assertEqual(compania[campo], valor,
|
||||
f"{campo} era un dato real y no debió tocarse")
|
||||
|
||||
def test_una_ciudad_real_que_se_llama_brisbane_sobrevive(self):
|
||||
"""El caso que la comparación exacta existe para no romper: una
|
||||
dirección de verdad puede coincidir en UN campo con la de muestra."""
|
||||
compania = self.env.ref('base.main_company')
|
||||
compania.sudo().write({'city': 'Brisbane',
|
||||
'street': 'Calle Real 40'})
|
||||
|
||||
self.env['res.company']._beyond_asegurar_nombre()
|
||||
|
||||
self.assertFalse(compania.city, "la ciudad de muestra sí se vacía")
|
||||
self.assertEqual(compania.street, 'Calle Real 40',
|
||||
"la calle real no se toca porque no es de muestra")
|
||||
|
||||
def test_bootstrap_admin_general(self):
|
||||
"""ADR-004: la cuenta que instala queda como Administrador general;
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
from odoo.tests import HttpCase, tagged
|
||||
|
||||
from odoo.addons.beyond_base.models.res_users import (
|
||||
ALTA_SOLO_POR_INVITACION, PARAMETRO_ALTA)
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestBeyondAltaPublica(HttpCase):
|
||||
"""El alta pública está cerrada, y lo está por datos del módulo.
|
||||
|
||||
Quitar el enlace de la pantalla de inicio de sesión no cierra nada: la
|
||||
ruta /web/signup seguía respondiendo a cualquiera que teclease la URL,
|
||||
porque auth_signup se instala con invitation_scope en 'b2c'. El candado
|
||||
vive en data/signup.xml y se reafirma en cada actualización, para que no
|
||||
dependa de un clic en Ajustes ni se pierda al clonar la base.
|
||||
"""
|
||||
|
||||
def _parametro(self):
|
||||
return self.env['ir.config_parameter'].sudo().get_param(PARAMETRO_ALTA)
|
||||
|
||||
def test_el_candado_quedo_puesto(self):
|
||||
self.assertEqual(self._parametro(), ALTA_SOLO_POR_INVITACION)
|
||||
|
||||
def test_el_candado_se_repone_solo(self):
|
||||
"""Alguien lo abre desde Ajustes; la siguiente actualización lo cierra."""
|
||||
self.env['ir.config_parameter'].sudo().set_param(PARAMETRO_ALTA, 'b2c')
|
||||
self.env['res.users']._beyond_cerrar_alta_publica()
|
||||
self.assertEqual(self._parametro(), ALTA_SOLO_POR_INVITACION)
|
||||
|
||||
def test_es_idempotente(self):
|
||||
"""Cerrado y vuelto a cerrar, no escribe ni cambia nada."""
|
||||
self.env['res.users']._beyond_cerrar_alta_publica()
|
||||
self.env['res.users']._beyond_cerrar_alta_publica()
|
||||
self.assertEqual(self._parametro(), ALTA_SOLO_POR_INVITACION)
|
||||
|
||||
# -- La ruta ---------------------------------------------------------------
|
||||
|
||||
def test_signup_sin_invitacion_no_existe(self):
|
||||
"""Con el candado puesto, Odoo ni siquiera sirve el formulario."""
|
||||
respuesta = self.url_open('/web/signup', allow_redirects=False)
|
||||
self.assertEqual(respuesta.status_code, 404,
|
||||
"/web/signup sigue abierta a cualquiera con la URL")
|
||||
|
||||
def test_no_se_puede_registrar_sin_invitacion(self):
|
||||
"""Y un POST directo, saltándose el formulario, tampoco crea cuenta."""
|
||||
correo = 'intruso@beyond.example'
|
||||
pagina = self.url_open('/web/login')
|
||||
csrf = pagina.text.split('name="csrf_token" value="')[1].split('"')[0]
|
||||
respuesta = self.url_open('/web/signup', allow_redirects=False, data={
|
||||
'login': correo,
|
||||
'name': 'Intruso',
|
||||
'password': 'una-contrasena-cualquiera',
|
||||
'confirm_password': 'una-contrasena-cualquiera',
|
||||
'csrf_token': csrf,
|
||||
})
|
||||
self.assertEqual(respuesta.status_code, 404)
|
||||
self.assertFalse(
|
||||
self.env['res.users'].sudo().with_context(active_test=False).search(
|
||||
[('login', '=', correo)]),
|
||||
"se creó una cuenta sin invitación")
|
||||
|
||||
def test_el_alta_con_invitacion_sigue_viva(self):
|
||||
"""El candado cierra la puerta de la calle, no la del aprovisionador:
|
||||
el alta por invitación (ADR-008) tiene que seguir funcionando."""
|
||||
usuario = self.env['res.users'].create({
|
||||
'name': 'Invitada Beyond',
|
||||
'login': 'invitada@beyond.example',
|
||||
})
|
||||
usuario.partner_id.signup_prepare()
|
||||
token = usuario.partner_id.sudo()._generate_signup_token()
|
||||
respuesta = self.url_open('/web/signup?token=%s' % token)
|
||||
self.assertEqual(respuesta.status_code, 200,
|
||||
"una invitación válida dejó de servir el formulario")
|
||||
@@ -0,0 +1,118 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
from odoo.tests import TransactionCase, tagged
|
||||
|
||||
from ..models.ir_cron import ALIAS, PARAMETRO_PERMITIDAS, SALIDAS
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestBeyondSilencioSaliente(TransactionCase):
|
||||
"""Nada sale de Beyond sin autorización explícita. Odoo llegó con doce
|
||||
canales de salida que nadie pidió —correo, SMS, telemetría, push— y una
|
||||
actualización de módulo puede reactivar sus datos, así que el barrido
|
||||
corre en cada arranque."""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.Cron = self.env['ir.cron']
|
||||
self.params = self.env['ir.config_parameter'].sudo()
|
||||
|
||||
def _crons(self):
|
||||
return [t for t in (self.env.ref(s.objetivo, raise_if_not_found=False)
|
||||
for s in SALIDAS if s.tipo == 'cron') if t]
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
def test_apaga_todas_las_salidas(self):
|
||||
self.Cron._beyond_silenciar_salidas()
|
||||
for tarea in self._crons():
|
||||
self.assertFalse(tarea.sudo().active,
|
||||
f'{tarea.cron_name} debería quedar apagada')
|
||||
|
||||
def test_es_idempotente(self):
|
||||
self.Cron._beyond_silenciar_salidas()
|
||||
self.assertFalse(self.Cron._beyond_silenciar_salidas(),
|
||||
'si ya está apagado no vuelve a escribir')
|
||||
|
||||
def test_se_reafirma_si_algo_lo_reactiva(self):
|
||||
"""Una actualización de módulo puede reactivar sus propios datos."""
|
||||
self.Cron._beyond_silenciar_salidas()
|
||||
tarea = self._crons()[0]
|
||||
tarea.sudo().active = True
|
||||
self.assertTrue(self.Cron._beyond_silenciar_salidas())
|
||||
self.assertFalse(tarea.sudo().active)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
def test_la_cola_de_correo_queda_cerrada(self):
|
||||
"""Es la tubería: sin ella, nada encolado sale solo."""
|
||||
self.Cron._beyond_silenciar_salidas()
|
||||
cola = self.env.ref('mail.ir_cron_mail_scheduler_action')
|
||||
self.assertFalse(cola.sudo().active)
|
||||
|
||||
def test_el_restablecer_contrasena_por_correo_queda_cerrado(self):
|
||||
"""Se manda con force_send, o sea que NO pasa por la cola: apagar la
|
||||
cola no lo detendría."""
|
||||
self.params.set_param('auth_signup.reset_password', 'True')
|
||||
self.Cron._beyond_silenciar_salidas()
|
||||
self.assertFalse(self.params.get_param('auth_signup.reset_password'))
|
||||
|
||||
def test_el_historial_avisa_por_dentro_no_por_correo(self):
|
||||
usuario = self.env['res.users'].create({
|
||||
'name': 'Aviso interno', 'login': 'aviso.interno.prueba',
|
||||
'notification_type': 'email'})
|
||||
self.Cron._beyond_silenciar_salidas()
|
||||
self.assertEqual(usuario.notification_type, 'inbox')
|
||||
|
||||
def test_los_de_portal_se_quedan_como_estan(self):
|
||||
"""Odoo exige 'email' para los usuarios de portal: no tienen bandeja."""
|
||||
self.Cron._beyond_silenciar_salidas()
|
||||
portal = self.env['res.users'].sudo().search(
|
||||
[('share', '=', True), ('notification_type', '=', 'inbox')])
|
||||
self.assertFalse(portal, 'no se tocó a los de portal')
|
||||
|
||||
def test_el_boletin_se_desactiva_ademas_de_su_tarea(self):
|
||||
if 'digest.digest' not in self.env:
|
||||
self.skipTest('esta base no trae el módulo de resúmenes')
|
||||
boletin = self.env['digest.digest'].sudo().search([], limit=1)
|
||||
boletin.state = 'activated'
|
||||
self.params.set_param('digest.default_digest_emails', 'True')
|
||||
self.Cron._beyond_silenciar_salidas()
|
||||
self.assertEqual(boletin.state, 'deactivated')
|
||||
self.assertFalse(self.params.get_param('digest.default_digest_emails'),
|
||||
'y un empleado nuevo ya no entra a la lista')
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
def test_una_clave_autorizada_se_respeta(self):
|
||||
self.Cron._beyond_silenciar_salidas()
|
||||
self.params.set_param(PARAMETRO_PERMITIDAS, 'push')
|
||||
push = self.env.ref('mail.ir_cron_web_push_notification')
|
||||
push.sudo().active = True
|
||||
self.Cron._beyond_silenciar_salidas()
|
||||
self.assertTrue(push.sudo().active, 'la clave autorizada manda')
|
||||
|
||||
def test_autorizar_una_no_abre_las_demas(self):
|
||||
self.params.set_param(PARAMETRO_PERMITIDAS, 'push')
|
||||
self.Cron._beyond_silenciar_salidas()
|
||||
self.assertFalse(
|
||||
self.env.ref('mail.ir_cron_mail_scheduler_action').sudo().active)
|
||||
|
||||
def test_varias_claves_separadas_por_coma(self):
|
||||
self.params.set_param(PARAMETRO_PERMITIDAS, 'push, sms ,telemetria')
|
||||
self.assertEqual(
|
||||
self.Cron._beyond_salidas_permitidas(),
|
||||
{'push', 'sms', 'telemetria'}, 'tolera espacios')
|
||||
|
||||
def test_los_parametros_anteriores_siguen_sirviendo(self):
|
||||
"""Lo ya documentado no debe dejar de funcionar."""
|
||||
for parametro, claves in ALIAS.items():
|
||||
self.params.set_param(PARAMETRO_PERMITIDAS, False)
|
||||
self.params.set_param(parametro, '1')
|
||||
self.assertTrue(set(claves) <= self.Cron._beyond_salidas_permitidas())
|
||||
self.params.set_param(parametro, False)
|
||||
|
||||
def test_toda_clave_tiene_una_salida_y_viceversa(self):
|
||||
"""Guardia contra el olvido: si alguien agrega una salida sin clave,
|
||||
o documenta una clave que no apaga nada, esto lo caza."""
|
||||
for salida in SALIDAS:
|
||||
self.assertTrue(salida.clave and salida.etiqueta)
|
||||
self.assertIn(salida.tipo, ('cron', 'parametro', 'especial'))
|
||||
if salida.tipo == 'cron':
|
||||
self.assertIn('.', salida.objetivo, 'debe ser un xmlid')
|
||||
@@ -0,0 +1,32 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
from odoo.tests import HttpCase, tagged
|
||||
|
||||
from odoo.addons.web.tests.test_js import unit_test_error_checker
|
||||
|
||||
# Hoot identifica cada suite por un hash de su ruta. El de «@beyond_base»
|
||||
# selecciona todas las unitarias de este módulo y ninguna ajena, para no
|
||||
# arrastrar las ~3700 del core en cada corrida. El algoritmo es el de
|
||||
# web/tests/test_js.py::HOOTCommon._generate_hash; si algún día cambia, este
|
||||
# test empieza a correr de más, no de menos.
|
||||
SUITE_BEYOND = 'd6e526c1' # @beyond_base
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestBeyondUnitariasJS(HttpCase):
|
||||
"""Corre las unitarias JS de beyond_base en un navegador de verdad.
|
||||
|
||||
Existe porque el runner de hoot vive en el módulo `web`: acotar la suite
|
||||
con --test-tags=/beyond_base lo deja fuera, y entonces las unitarias no se
|
||||
ejecutan y la corrida sale verde sin haberlas mirado. Eso ya nos pasó: el
|
||||
menú de la foto estaba muerto en la interfaz con todas las pruebas en
|
||||
verde.
|
||||
"""
|
||||
|
||||
def test_unitarias_de_beyond(self):
|
||||
self.browser_js(
|
||||
f'/web/tests?headless&loglevel=2&preset=desktop&timeout=15000'
|
||||
f'&id={SUITE_BEYOND}',
|
||||
"", "", login='admin', timeout=1800,
|
||||
success_signal="[HOOT] Test suite succeeded",
|
||||
error_checker=unit_test_error_checker,
|
||||
)
|
||||
@@ -0,0 +1,64 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
from odoo.tests import TransactionCase, tagged
|
||||
|
||||
from ..models.ir_config_parameter import (BASE_URL, CONGELADOR,
|
||||
PARAMETRO_LIBRE, PARAMETRO_URL)
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestBeyondUrlPublica(TransactionCase):
|
||||
"""De fábrica Odoo reescribe la dirección pública con la del último
|
||||
administrador que entró. El QR del kiosco se arma con ese valor, así que
|
||||
una entrada por la IP en vez del dominio deja a los empleados sin poder
|
||||
checar."""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.params = self.env['ir.config_parameter'].sudo()
|
||||
|
||||
def test_queda_congelada(self):
|
||||
self.params.set_param(CONGELADOR, False)
|
||||
self.env['ir.config_parameter']._beyond_congelar_url_publica()
|
||||
self.assertTrue(self.params.get_param(CONGELADOR))
|
||||
|
||||
def test_es_idempotente(self):
|
||||
Param = self.env['ir.config_parameter']
|
||||
Param._beyond_congelar_url_publica()
|
||||
self.assertFalse(Param._beyond_congelar_url_publica(),
|
||||
'si ya está congelada no vuelve a escribir')
|
||||
|
||||
def test_no_inventa_la_direccion(self):
|
||||
"""Congela lo que hay; no adivina ni impone un dominio."""
|
||||
self.params.set_param(CONGELADOR, False)
|
||||
self.params.set_param(BASE_URL, 'https://beyond.example.mx')
|
||||
self.env['ir.config_parameter']._beyond_congelar_url_publica()
|
||||
self.assertEqual(self.params.get_param(BASE_URL),
|
||||
'https://beyond.example.mx')
|
||||
|
||||
def test_mudarse_de_direccion_es_un_parametro(self):
|
||||
Param = self.env['ir.config_parameter']
|
||||
Param._beyond_congelar_url_publica()
|
||||
self.params.set_param(PARAMETRO_URL, 'https://nueva.example.mx')
|
||||
self.assertEqual(Param._beyond_congelar_url_publica(),
|
||||
'https://nueva.example.mx')
|
||||
self.assertEqual(self.params.get_param(BASE_URL),
|
||||
'https://nueva.example.mx')
|
||||
self.assertTrue(self.params.get_param(CONGELADOR), 'y sigue congelada')
|
||||
|
||||
def test_el_qr_del_kiosco_usa_esa_direccion(self):
|
||||
"""Fija por qué esto importa: si el valor cambia, el QR apunta a otro
|
||||
sitio y el teléfono del empleado no abre nada."""
|
||||
self.params.set_param(BASE_URL, 'https://beyond.example.mx')
|
||||
token = self.env['beyond.checada.token'].sudo().search([], limit=1)
|
||||
if not token:
|
||||
self.skipTest('no hay tokens de kiosco en esta base')
|
||||
estado = token._estado_kiosco()
|
||||
self.assertTrue(estado['checada_url'].startswith('https://beyond.example.mx'))
|
||||
|
||||
def test_se_descongela_por_decision_explicita(self):
|
||||
Param = self.env['ir.config_parameter']
|
||||
Param._beyond_congelar_url_publica()
|
||||
self.params.set_param(PARAMETRO_LIBRE, '1')
|
||||
Param._beyond_congelar_url_publica()
|
||||
self.assertFalse(self.params.get_param(CONGELADOR),
|
||||
'Odoo vuelve a su comportamiento de fábrica')
|
||||
@@ -0,0 +1,195 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<!--
|
||||
Beyond — login v1.
|
||||
|
||||
The signed-off "Iniciar sesión" screen, built by inheriting web.login
|
||||
and web.login_layout. No core file is touched and no controller is
|
||||
overridden: the form that posts to /web/login is Odoo's own, kept whole
|
||||
with its action, its method, its csrf_token and its redirect. What
|
||||
changes is the markup around the fields and the shell it renders in.
|
||||
|
||||
Both templates carry priority="99" so they are the LAST arch applied to
|
||||
web.login. auth_signup and auth_passkey also inherit it, and the order
|
||||
has to be a decision rather than a coincidence of module ids: this file
|
||||
replaces the block that auth_signup drops its "Restablecer contraseña"
|
||||
link into, and it can only do that reliably if the link is already
|
||||
there when it runs. beyond_base depends on auth_signup for the same
|
||||
reason (see __manifest__.py).
|
||||
|
||||
THREE THINGS THE DESIGN ASKS FOR THAT ARE NOT HERE, on purpose:
|
||||
|
||||
1. Live validation. The mock decides on its own that the fields are
|
||||
empty and writes its own message. Here every message is the
|
||||
server's, after the POST — a wrong password is Odoo's string,
|
||||
rendered in the design's voice by scss/../login/beyond_login.scss.
|
||||
The only client-side check left is core's own `required`.
|
||||
|
||||
2. The "Bienvenido, X" screen. There is nothing to build: a correct
|
||||
login is a 303 out of /web/login and the browser lands on the Menú
|
||||
Principal (the launcher, ADR-005). The mock needed that screen
|
||||
because it had nowhere to go.
|
||||
|
||||
3. The eye's own logic. It lives in login/beyond_login.js, because the
|
||||
type of an input is not something a template can toggle.
|
||||
|
||||
AND THREE THINGS THE DESIGN DID NOT KNOW ABOUT, decided here:
|
||||
|
||||
- web.user_switch (Odoo 19) is removed. It is the "Choose a user"
|
||||
screen that hides the form behind the last accounts to log in on this
|
||||
browser. On a shop terminal shared by a shift that is a list of
|
||||
colleagues' names and faces on the pre-session screen, and the design
|
||||
has no such state.
|
||||
- The signup link ("¿No tienes una cuenta?") is removed. Beyond staff
|
||||
are provisioned by the branch administrator (ADR-008); nobody signs
|
||||
themselves up. NOTE this only takes the link off this screen — the
|
||||
/web/signup route stays open until `auth_signup.invitation_scope` is
|
||||
set to b2b in Ajustes.
|
||||
- The passkey block (auth_passkey) STAYS. It is not in the design, but
|
||||
it is a real way in, and removing it would lock out anyone who
|
||||
registered a key. It is restyled, not dropped.
|
||||
-->
|
||||
|
||||
<!--
|
||||
The shell. web.login_layout wraps its content in a centred 300px card
|
||||
with the company logo on top and an "Con la tecnología de Odoo" footer
|
||||
under it. The login screen is a full-bleed two-column page, so on this
|
||||
page the card is not overridden, it is not rendered at all.
|
||||
|
||||
`beyond_login` is set by the template below, inside the body of the
|
||||
t-call — QWeb renders that body first and the t-set reaches here. The
|
||||
other pages that share this layout (restablecer contraseña, alta,
|
||||
sesión iniciada) never set it and are left exactly as they were.
|
||||
-->
|
||||
<template id="login_layout_beyond" inherit_id="web.login_layout" priority="99"
|
||||
name="Beyond — envoltura de inicio de sesión">
|
||||
<xpath expr="//t[@t-set='body_classname']" position="attributes">
|
||||
<attribute name="t-value">'beyond_login_body' if beyond_login else 'bg-100'</attribute>
|
||||
</xpath>
|
||||
<xpath expr="//div[hasclass('container')]" position="attributes">
|
||||
<attribute name="t-if">not beyond_login</attribute>
|
||||
</xpath>
|
||||
<xpath expr="//div[hasclass('container')]" position="after">
|
||||
<div t-if="beyond_login" class="beyond_login">
|
||||
<div class="beyond_login_brand">
|
||||
<!--
|
||||
Absolute path on purpose: this page precedes the
|
||||
session and resolves nothing through the backend.
|
||||
20 KB PNG, white type on transparency, from the 1.2 MB
|
||||
JPEG the design shipped.
|
||||
-->
|
||||
<img class="beyond_login_logo" alt="Look Capital"
|
||||
src="/beyond_base/static/img/logo_login.png"/>
|
||||
</div>
|
||||
<div class="beyond_login_panel">
|
||||
<div class="beyond_login_stack">
|
||||
<t t-out="0"/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</xpath>
|
||||
</template>
|
||||
|
||||
<!-- The form itself. -->
|
||||
<template id="login_beyond" inherit_id="web.login" priority="99"
|
||||
name="Beyond — iniciar sesión">
|
||||
|
||||
<!-- Read by the layout above. `disable_footer` takes out the "Gestionar
|
||||
bases de datos" and Odoo branding line under the card. -->
|
||||
<xpath expr="//form[@role='form']" position="before">
|
||||
<t t-set="beyond_login" t-value="True"/>
|
||||
<t t-set="disable_footer" t-value="True"/>
|
||||
<span class="beyond_login_title">Iniciar sesión</span>
|
||||
</xpath>
|
||||
|
||||
<!-- La firma va en inglés en las dos pantallas que la llevan, esta y el
|
||||
Menú Principal (webclient/beyond_launcher.xml). Es una excepción
|
||||
deliberada a la regla 4 de CLAUDE.md — «español en toda cadena
|
||||
visible» —, decidida el 23-ago-2026: es la marca de Collina, no
|
||||
una cadena de la interfaz, y valía más que fuera la misma en
|
||||
ambas que traducida en una y no en la otra. Si cambia, cambian
|
||||
las dos. -->
|
||||
<xpath expr="//form[@role='form']" position="after">
|
||||
<span class="beyond_login_sign">Powered by Collina Systems</span>
|
||||
</xpath>
|
||||
|
||||
<!-- See note 1 at the top of this file. -->
|
||||
<xpath expr="//owl-component[@name='web.user_switch']" position="replace"/>
|
||||
|
||||
<!-- Core hides the form with `d-none` and lets the user switcher decide
|
||||
whether to show it. With the switcher gone the form is the screen,
|
||||
so the class stops being computed. -->
|
||||
<xpath expr="//form[@role='form']" position="attributes">
|
||||
<attribute name="t-attf-class"/>
|
||||
<attribute name="class">oe_login_form beyond_login_form</attribute>
|
||||
</xpath>
|
||||
|
||||
<xpath expr="//div[hasclass('field-login')]" position="replace">
|
||||
<div class="beyond_login_field">
|
||||
<div class="beyond_login_field_head">
|
||||
<label for="login" class="beyond_login_label">Nombre de usuario</label>
|
||||
</div>
|
||||
<!-- name="login" is what /web/login reads. The design calls it
|
||||
"Nombre de usuario" because that is what the staff type;
|
||||
Odoo accepts the login, mail or not. -->
|
||||
<input type="text" name="login" id="login" class="beyond_login_input"
|
||||
t-att-value="login" placeholder="Usuario"
|
||||
required="required" autocapitalize="off" autocomplete="username"
|
||||
t-att-autofocus="'autofocus' if not login else None"/>
|
||||
</div>
|
||||
</xpath>
|
||||
|
||||
<!-- The o_caps_lock_warning class rides along: core's interaction hangs
|
||||
its "¡Bloq Mayús está activado!" off it, which is worth keeping on
|
||||
a screen where you type blind. -->
|
||||
<xpath expr="//div[hasclass('o_caps_lock_warning')]" position="replace">
|
||||
<div class="beyond_login_field o_caps_lock_warning">
|
||||
<div class="beyond_login_field_head">
|
||||
<label for="password" class="beyond_login_label">Contraseña</label>
|
||||
<!-- The real reset route, behind the real switch: Ajustes →
|
||||
"Restablecer contraseña" (auth_signup.reset_password).
|
||||
Off, and the link is not rendered — the same condition
|
||||
core uses, only the copy is the design's. -->
|
||||
<a t-if="reset_password_enabled" class="beyond_login_forgot"
|
||||
t-attf-href="/web/reset_password?{{ keep_query() }}">¿Olvidaste tu contraseña?</a>
|
||||
</div>
|
||||
<div class="beyond_login_pw">
|
||||
<input type="password" name="password" id="password"
|
||||
class="beyond_login_input_pw" placeholder="••••••••••"
|
||||
required="required" autocomplete="current-password"
|
||||
maxlength="4096"
|
||||
t-att-autofocus="'autofocus' if login else None"/>
|
||||
<button type="button" class="beyond_login_eye"
|
||||
aria-label="Mostrar contraseña" aria-pressed="false">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" aria-hidden="true">
|
||||
<path d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12Z"
|
||||
stroke="currentColor" stroke-width="2"/>
|
||||
<circle cx="12" cy="12" r="3.2" stroke="currentColor" stroke-width="2"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</xpath>
|
||||
|
||||
<!-- The server's own messages, stripped of Bootstrap's alert box so the
|
||||
design's 14px/700 can show. The text and the t-if stay core's. -->
|
||||
<xpath expr="//p[hasclass('alert-danger')]" position="attributes">
|
||||
<attribute name="class">beyond_login_error</attribute>
|
||||
</xpath>
|
||||
<xpath expr="//p[hasclass('alert-success')]" position="attributes">
|
||||
<attribute name="class">beyond_login_message</attribute>
|
||||
</xpath>
|
||||
|
||||
<!-- oe_login_buttons is kept in the class list: auth_signup and
|
||||
auth_passkey both hang their arch off it. -->
|
||||
<xpath expr="//div[hasclass('oe_login_buttons')]" position="attributes">
|
||||
<attribute name="class">oe_login_buttons beyond_login_actions</attribute>
|
||||
</xpath>
|
||||
<xpath expr="//div[hasclass('oe_login_buttons')]/button[@type='submit']" position="attributes">
|
||||
<attribute name="class">beyond_login_submit</attribute>
|
||||
</xpath>
|
||||
|
||||
<!-- See the third note at the top of this file. -->
|
||||
<xpath expr="//a[contains(@t-attf-href, '/web/signup')]" position="replace"/>
|
||||
</template>
|
||||
</odoo>
|
||||
@@ -29,19 +29,38 @@ Fase 1 — Arquitectura base (BRIEF §5.3 y §4):
|
||||
'data/hide_pos_catalog_menu.xml',
|
||||
'views/beyond_branch_views.xml',
|
||||
'views/res_users_views.xml',
|
||||
'views/catalogo_views.xml',
|
||||
'views/product_views.xml',
|
||||
'views/matriz_views.xml',
|
||||
'data/backfill.xml',
|
||||
],
|
||||
'assets': {
|
||||
'web.assets_backend': [
|
||||
# Panel General (ADR-013). Las variables van PRIMERO: Odoo compila
|
||||
# el bundle como un solo documento y los tokens del primer archivo
|
||||
# son los que resuelven en los siguientes.
|
||||
'beyond_branch/static/src/panel/beyond_panel_variables.scss',
|
||||
'beyond_branch/static/src/panel/beyond_panel.scss',
|
||||
'beyond_branch/static/src/panel/beyond_prefs.scss',
|
||||
'beyond_branch/static/src/panel/beyond_fields.scss',
|
||||
'beyond_branch/static/src/panel/beyond_sucursales.scss',
|
||||
'beyond_branch/static/src/matriz_precios/matriz_precios.js',
|
||||
'beyond_branch/static/src/matriz_precios/matriz_precios.xml',
|
||||
'beyond_branch/static/src/matriz_precios/matriz_precios.scss',
|
||||
'beyond_branch/static/src/catalogo/beyond_catalogo_hub.js',
|
||||
'beyond_branch/static/src/catalogo/beyond_catalogo_hub.xml',
|
||||
'beyond_branch/static/src/catalogo/beyond_catalogo_matriz.js',
|
||||
'beyond_branch/static/src/catalogo/beyond_catalogo_matriz.xml',
|
||||
'beyond_branch/static/src/catalogo/beyond_precios_inline.js',
|
||||
'beyond_branch/static/src/catalogo/beyond_existencias_inline.js',
|
||||
'beyond_branch/static/src/catalogo/beyond_chips_red.js',
|
||||
'beyond_branch/static/src/catalogo/beyond_inline.xml',
|
||||
'beyond_branch/static/src/catalogo/beyond_catalogo.scss',
|
||||
],
|
||||
},
|
||||
'demo': [
|
||||
'demo/demo_branches.xml',
|
||||
'demo/demo_catalogo.xml',
|
||||
],
|
||||
'installable': True,
|
||||
'application': True,
|
||||
|
||||
@@ -14,4 +14,17 @@
|
||||
<record id="account.menu_finance" model="ir.ui.menu">
|
||||
<field name="group_ids" eval="[(6, 0, [ref('base.group_system')])]"/>
|
||||
</record>
|
||||
|
||||
<!--
|
||||
Y sus hijos que llevan a la lista de contactos sin filtrar. Ocultar la
|
||||
raíz basta para que el árbol no los dibuje, pero siguen siendo menús
|
||||
visibles a nivel de permisos y su acción es alcanzable por dirección
|
||||
directa. A los clientes se llega por Beyond → Clientes y nada más.
|
||||
-->
|
||||
<record id="account.menu_account_customer" model="ir.ui.menu">
|
||||
<field name="group_ids" eval="[(6, 0, [ref('base.group_system')])]"/>
|
||||
</record>
|
||||
<record id="account.menu_account_supplier" model="ir.ui.menu">
|
||||
<field name="group_ids" eval="[(6, 0, [ref('base.group_system')])]"/>
|
||||
</record>
|
||||
</odoo>
|
||||
@@ -2,7 +2,17 @@
|
||||
<odoo>
|
||||
<data noupdate="1">
|
||||
<!-- Códigos cortos de sucursal: S01, S02, ... (el código también se
|
||||
usa como código de almacén, límite de 5 caracteres). -->
|
||||
usa como código de almacén, límite de 5 caracteres).
|
||||
|
||||
NO pongas implementation="no_gap" aquí para que los números no
|
||||
salten: al cambiar de standard a no_gap, ir.sequence.write tira la
|
||||
secuencia de PostgreSQL y se queda con la columna number_next del
|
||||
ORM, que en una secuencia standard nunca se actualizó y vale 1. La
|
||||
siguiente sucursal saldría S01 y chocaría con la que ya existe.
|
||||
Además este bloque es noupdate, así que el cambio no llegaría a las
|
||||
bases ya instaladas: solo abriría una diferencia entre ellas y las
|
||||
nuevas. Si los números saltan, es que alguien corrió los tests
|
||||
contra esa base (ver CLAUDE.md, «Entorno»). -->
|
||||
<record id="seq_beyond_branch_code" model="ir.sequence">
|
||||
<field name="name">Códigos de sucursal Beyond</field>
|
||||
<field name="code">beyond.branch.code</field>
|
||||
|
||||
@@ -17,6 +17,25 @@
|
||||
<field name="phone">+52 222 200 0002</field>
|
||||
</record>
|
||||
|
||||
<!-- Una sucursal archivada, para poder demostrar el estado completo de la
|
||||
pantalla: el ribbon «Archivada», que no aparece en la lista por
|
||||
defecto y que archivar NO borra nada.
|
||||
|
||||
active=False va en el propio <record> y no en una <function> aparte:
|
||||
los archivos demo se cargan con semántica noupdate y convert.py salta
|
||||
los <function> fuera del modo «init», así que en una base que ya
|
||||
existía la sucursal se quedaba activa —y salía en la lista— mientras
|
||||
en una instalación limpia sí se archivaba. Como <field> se aplica al
|
||||
crear el registro, que es cuando importa. El aprovisionador corre
|
||||
igual: lo dispara create, no el estado de active. -->
|
||||
<record id="demo_branch_cerrada" model="beyond.branch">
|
||||
<field name="name">Sucursal Plaza Dorada</field>
|
||||
<field name="street">Av. Juárez 2308</field>
|
||||
<field name="city">Puebla</field>
|
||||
<field name="phone">+52 222 200 0003</field>
|
||||
<field name="active" eval="False"/>
|
||||
</record>
|
||||
|
||||
<record id="beyond_base.demo_empleado_daniela" model="hr.employee">
|
||||
<field name="branch_id" ref="demo_branch_centro"/>
|
||||
</record>
|
||||
@@ -30,6 +49,7 @@
|
||||
<field name="password">beyond-demo-2026</field>
|
||||
<field name="group_ids" eval="[(6, 0, [ref('beyond_base.beyond_group_admin_sucursal')])]"/>
|
||||
<field name="branch_ids" eval="[(6, 0, [ref('demo_branch_centro')])]"/>
|
||||
<field name="image_1920" eval="False"/>
|
||||
</record>
|
||||
|
||||
<!-- C-007: cuenta de Administrador general SIN group_system, para
|
||||
@@ -40,5 +60,23 @@
|
||||
<field name="login">direccion@beyond.example</field>
|
||||
<field name="password">beyond-demo-2026</field>
|
||||
<field name="group_ids" eval="[(6, 0, [ref('beyond_base.beyond_group_admin_general')])]"/>
|
||||
<!-- Sin foto: Odoo copia la del usuario plantilla al crear una cuenta,
|
||||
y esa foto es un monograma de su propia paleta. La barra del panel
|
||||
muestra la foto cuando existe (así lo pide el diseño), así que con
|
||||
ella heredada nunca se veía el avatar naranja con la inicial. -->
|
||||
<field name="image_1920" eval="False"/>
|
||||
</record>
|
||||
|
||||
<!-- Tercera cuenta: el rol Empleado. Faltaba, y sin ella no se puede
|
||||
recorrer a mano lo que ve cada rol —que es la comprobación que el
|
||||
BRIEF §4 pide y la que destapa una pantalla que carga para el
|
||||
director y truena para quien atiende el mostrador. -->
|
||||
<record id="demo_user_empleada" model="res.users">
|
||||
<field name="name">Daniela Torres (demo)</field>
|
||||
<field name="login">daniela@beyond.example</field>
|
||||
<field name="password">beyond-demo-2026</field>
|
||||
<field name="group_ids" eval="[(6, 0, [ref('beyond_base.beyond_group_empleado')])]"/>
|
||||
<field name="branch_ids" eval="[(6, 0, [ref('demo_branch_centro')])]"/>
|
||||
<field name="image_1920" eval="False"/>
|
||||
</record>
|
||||
</odoo>
|
||||
@@ -0,0 +1,93 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<data noupdate="1">
|
||||
<!-- Catálogo de demostración: lo justo para que las tres pantallas
|
||||
del Catálogo se puedan enseñar en dos minutos y para que cada
|
||||
caso del diseño tenga un ejemplo real que mirar.
|
||||
|
||||
Los estados van en el propio <record> y no en <function>: los
|
||||
archivos demo se cargan con semántica noupdate y las funciones se
|
||||
saltan fuera del modo «init», así que en una base ya instalada no
|
||||
correrían. -->
|
||||
|
||||
<!-- De red: se ofrece en todas, mismo precio en todas. -->
|
||||
<record id="demo_producto_shampoo" model="product.template">
|
||||
<field name="name">Shampoo Nutritivo 750 ml</field>
|
||||
<field name="type">consu</field>
|
||||
<field name="is_storable" eval="True"/>
|
||||
<field name="available_in_pos" eval="True"/>
|
||||
<field name="sale_ok" eval="True"/>
|
||||
<field name="list_price">390.0</field>
|
||||
<field name="barcode">7501000200011</field>
|
||||
</record>
|
||||
|
||||
<!-- De red pero con precio distinto por plaza: el caso que la matriz
|
||||
y las tarjetas de la ficha existen para enseñar. -->
|
||||
<record id="demo_producto_tinte" model="product.template">
|
||||
<field name="name">Tinte Profesional</field>
|
||||
<field name="type">consu</field>
|
||||
<field name="is_storable" eval="True"/>
|
||||
<field name="available_in_pos" eval="True"/>
|
||||
<field name="sale_ok" eval="True"/>
|
||||
<field name="list_price">560.0</field>
|
||||
</record>
|
||||
|
||||
<!-- De una sola sucursal: con una plaza la pregunta del precio no
|
||||
aplica, y esta es la ficha donde se ve que no aparece. -->
|
||||
<record id="demo_producto_exclusivo" model="product.template">
|
||||
<field name="name">Mascarilla Exclusiva Centro</field>
|
||||
<field name="type">consu</field>
|
||||
<field name="is_storable" eval="True"/>
|
||||
<field name="available_in_pos" eval="True"/>
|
||||
<field name="sale_ok" eval="True"/>
|
||||
<field name="list_price">720.0</field>
|
||||
<field name="branch_ids" eval="[(6, 0, [ref('demo_branch_centro')])]"/>
|
||||
</record>
|
||||
|
||||
<record id="demo_producto_tratamiento" model="product.template">
|
||||
<field name="name">Tratamiento de Keratina 500 ml</field>
|
||||
<field name="type">consu</field>
|
||||
<field name="is_storable" eval="True"/>
|
||||
<field name="available_in_pos" eval="True"/>
|
||||
<field name="sale_ok" eval="True"/>
|
||||
<field name="list_price">890.0</field>
|
||||
<field name="barcode">7501000200028</field>
|
||||
</record>
|
||||
|
||||
<record id="demo_producto_acondicionador" model="product.template">
|
||||
<field name="name">Acondicionador de Argán 750 ml</field>
|
||||
<field name="type">consu</field>
|
||||
<field name="is_storable" eval="True"/>
|
||||
<field name="available_in_pos" eval="True"/>
|
||||
<field name="sale_ok" eval="True"/>
|
||||
<field name="list_price">420.0</field>
|
||||
<field name="barcode">7501000200035</field>
|
||||
</record>
|
||||
|
||||
<record id="demo_servicio_corte" model="product.template">
|
||||
<field name="name">Corte de dama</field>
|
||||
<field name="type">service</field>
|
||||
<field name="is_storable" eval="False"/>
|
||||
<field name="available_in_pos" eval="True"/>
|
||||
<field name="sale_ok" eval="True"/>
|
||||
<field name="list_price">450.0</field>
|
||||
</record>
|
||||
|
||||
<record id="demo_servicio_keratina" model="product.template">
|
||||
<field name="name">Keratina</field>
|
||||
<field name="type">service</field>
|
||||
<field name="is_storable" eval="False"/>
|
||||
<field name="available_in_pos" eval="True"/>
|
||||
<field name="sale_ok" eval="True"/>
|
||||
<field name="list_price">1800.0</field>
|
||||
<field name="branch_ids"
|
||||
eval="[(6, 0, [ref('demo_branch_centro'), ref('demo_branch_angelopolis')])]"/>
|
||||
</record>
|
||||
|
||||
<!-- Los precios propios y las existencias los siembra una función.
|
||||
La lista de precios de una sucursal la crea el aprovisionador, así
|
||||
que no tiene xmlid al que apuntar desde un <record>; y un quant se
|
||||
escribe con el motor de inventario, no fijando un campo. -->
|
||||
<function model="beyond.branch" name="_beyond_demo_catalogo"/>
|
||||
</data>
|
||||
</odoo>
|
||||
@@ -206,9 +206,133 @@ class BeyondBranch(models.Model):
|
||||
}
|
||||
|
||||
def action_regenerate_kiosk_token(self):
|
||||
"""Rota el token del kiosco. SOLO quien puede administrar la sucursal.
|
||||
|
||||
La comprobación va ANTES del sudo y es la del propio modelo, no un
|
||||
grupo escrito a mano: quien tenga permiso de escritura sobre
|
||||
beyond.branch —hoy, el admin general— puede rotarlo, y la ir.rule
|
||||
decide además sobre CUÁLES registros. Si mañana cambia el ACL, esto
|
||||
lo sigue solo.
|
||||
|
||||
Sin ella, el sudo() dejaba el método abierto a cualquiera que pudiera
|
||||
llamarlo por RPC: el `groups=` del botón es de interfaz y una llamada
|
||||
RPC no pasa por la vista. Un admin de sucursal podía rotar el token de
|
||||
CUALQUIER sucursal —no solo la suya— y dejarla sin checador hasta que
|
||||
alguien notara el cambio y actualizara la tablet.
|
||||
"""
|
||||
self.check_access('write')
|
||||
for branch in self:
|
||||
branch.sudo().kiosk_token = uuid.uuid4().hex
|
||||
|
||||
@api.model
|
||||
def _beyond_demo_catalogo(self):
|
||||
"""Precios propios y existencias de demostración.
|
||||
|
||||
Va en una función y no en <record> por dos razones distintas: la lista
|
||||
de precios de una sucursal la crea el aprovisionador, así que no tiene
|
||||
xmlid al que apuntar; y un quant se escribe con el motor de inventario
|
||||
—`_update_available_quantity`—, no fijando un campo, que lo dejaría
|
||||
sin el movimiento que lo explica.
|
||||
|
||||
Se ejecuta al instalar, que es cuando se cargan los datos demo, y
|
||||
comprueba antes de escribir para no pisar nada si se repite.
|
||||
"""
|
||||
def demo(xmlid):
|
||||
return self.env.ref(f'beyond_branch.{xmlid}', raise_if_not_found=False)
|
||||
|
||||
# Angelópolis cobra más el tinte y menos la keratina; el resto de
|
||||
# plazas hereda el base, que es lo que la matriz pinta en gris.
|
||||
Item = self.env['product.pricelist.item']
|
||||
for producto_xmlid, branch_xmlid, precio in (
|
||||
('demo_producto_tinte', 'demo_branch_angelopolis', 620.0),
|
||||
('demo_servicio_keratina', 'demo_branch_angelopolis', 1650.0)):
|
||||
producto, branch = demo(producto_xmlid), demo(branch_xmlid)
|
||||
if not producto or not branch or not branch.pricelist_id:
|
||||
continue
|
||||
if Item.search_count([('pricelist_id', '=', branch.pricelist_id.id),
|
||||
('product_tmpl_id', '=', producto.id)]):
|
||||
continue
|
||||
Item.create({
|
||||
'pricelist_id': branch.pricelist_id.id,
|
||||
'applied_on': '1_product',
|
||||
'product_tmpl_id': producto.id,
|
||||
'compute_price': 'fixed',
|
||||
'fixed_price': precio,
|
||||
})
|
||||
|
||||
# El inventario es propio desde ADR-015 de Jorem: se siembra con
|
||||
# MOVIMIENTOS, que es lo único que mueve el saldo. Antes esto
|
||||
# escribía quants, y con el cambio la matriz habría salido en ceros.
|
||||
# Dependencia SUAVE: beyond_branch no depende de beyond_inventory, así
|
||||
# que su demo no puede dar por hecho que el modelo exista. En una
|
||||
# instalación limpia este módulo carga antes, y sin la guarda el demo
|
||||
# entero de beyond_branch se caía —con él las sucursales, y con ellas
|
||||
# media suite—. Las existencias las siembra entonces quien pueda:
|
||||
# la prueba que las necesita, o el sembrado a mano en desarrollo.
|
||||
self._beyond_demo_retirar_catalogo_ajeno()
|
||||
if 'beyond.movimiento' not in self.env:
|
||||
return
|
||||
Movimiento = self.env['beyond.movimiento'].sudo()
|
||||
Existencia = self.env['beyond.existencia'].sudo()
|
||||
|
||||
# Las tres formas que la pantalla tiene que saber pintar: con
|
||||
# existencia, en cero y en negativo. Sin las tres, el color de la
|
||||
# píldora no significa nada porque nunca cambia. El cero se consigue
|
||||
# NO sembrando: el tratamiento en Centro y el acondicionador en
|
||||
# Angelópolis se quedan fuera de esta lista a propósito.
|
||||
siembra = [
|
||||
('demo_producto_shampoo', 'demo_branch_centro', 24.0),
|
||||
('demo_producto_shampoo', 'demo_branch_angelopolis', 8.0),
|
||||
('demo_producto_tinte', 'demo_branch_centro', 15.0),
|
||||
# Negativa: se vendió algo que nunca se registró como recibido
|
||||
# (ADR-012 §4). Es señal, no avería.
|
||||
('demo_producto_tinte', 'demo_branch_angelopolis', -3.0),
|
||||
('demo_producto_exclusivo', 'demo_branch_centro', 6.0),
|
||||
('demo_producto_tratamiento', 'demo_branch_angelopolis', 12.0),
|
||||
('demo_producto_acondicionador', 'demo_branch_centro', 30.0),
|
||||
]
|
||||
for producto_xmlid, branch_xmlid, cantidad in siembra:
|
||||
producto, branch = demo(producto_xmlid), demo(branch_xmlid)
|
||||
if not producto or not branch:
|
||||
continue
|
||||
if Existencia.search_count([('product_tmpl_id', '=', producto.id),
|
||||
('branch_id', '=', branch.id)]):
|
||||
continue
|
||||
if cantidad >= 0:
|
||||
Movimiento.beyond_entrada(producto, branch, cantidad,
|
||||
nota='existencia de demostración')
|
||||
else:
|
||||
# La negativa es SEÑAL, no avería (ADR-012 §4): se llega a
|
||||
# ella con un ajuste, que es como se llegaría de verdad.
|
||||
Movimiento.beyond_ajuste(producto, branch, cantidad, 'conteo',
|
||||
nota='existencia de demostración')
|
||||
|
||||
@api.model
|
||||
def _beyond_demo_retirar_catalogo_ajeno(self):
|
||||
"""Saca de la venta el catálogo de muestra de Odoo, solo en demo.
|
||||
|
||||
«Bagel», «Alojamiento en hotel» o «Construcción de muebles» no son de
|
||||
un salón, y son los primeros renglones que se ven en el Catálogo
|
||||
porque la tabla ordena por nombre. Quien mira una demostración
|
||||
entiende que el sistema trae eso dentro, que es justo lo contrario de
|
||||
lo que la demostración quiere decir.
|
||||
|
||||
No se borra nada ni se archiva: se retira de la venta, que es lo que
|
||||
filtran las pantallas del catálogo y la carga del POS. Los productos
|
||||
siguen ahí para lo que los necesite. Y solo pasa aquí: esta función
|
||||
vive en los datos demo, que producción no carga.
|
||||
"""
|
||||
ajenos = self.env['ir.model.data'].search([
|
||||
('model', '=', 'product.template'),
|
||||
('module', 'not like', 'beyond%'),
|
||||
])
|
||||
productos = self.env['product.template'].browse(ajenos.mapped('res_id')).exists()
|
||||
# `available_in_pos` no se toca: el core no deja apagarlo en un
|
||||
# producto que forma parte de un combo, y la muestra de Odoo trae uno.
|
||||
# Con `sale_ok` basta, que es lo que filtran las pantallas del
|
||||
# catálogo Y la carga del punto de venta.
|
||||
productos.filtered('sale_ok').write({'sale_ok': False})
|
||||
|
||||
def _provision(self):
|
||||
"""Deja la sucursal operativa a partir de solo su nombre: almacén,
|
||||
POS con caja de efectivo propia, secuencia de folios, equipo y kiosco.
|
||||
@@ -223,13 +347,22 @@ class BeyondBranch(models.Model):
|
||||
la caja ya cerrada.
|
||||
"""
|
||||
diferido = []
|
||||
# branch.env y NO self.env dentro del bucle: `branch` viene de
|
||||
# self.sudo() y self NO, así que todo lo que se creara con self.env
|
||||
# corría con los permisos del usuario. El aprovisionador se documentó
|
||||
# desde el principio como «corre con sudo: quien da de alta sucursales
|
||||
# no necesita ser gerente técnico de inventario/POS/RRHH», y a medias
|
||||
# no lo era: un administrador general se estrellaba con
|
||||
# «You are not allowed to create 'Sequence'» al crear la sucursal.
|
||||
# No se había visto porque hasta hoy las sucursales solo las habían
|
||||
# creado los datos demo y los tests, ambos como superusuario.
|
||||
for branch in self.sudo():
|
||||
abiertas = branch._beyond_sesiones_abiertas()
|
||||
pendiente = []
|
||||
if not branch.code:
|
||||
branch.code = self.env['ir.sequence'].next_by_code('beyond.branch.code')
|
||||
branch.code = branch.env['ir.sequence'].next_by_code('beyond.branch.code')
|
||||
if not branch.warehouse_id:
|
||||
branch.warehouse_id = self.env['stock.warehouse'].create({
|
||||
branch.warehouse_id = branch.env['stock.warehouse'].create({
|
||||
'name': branch.name,
|
||||
'code': branch.code,
|
||||
'company_id': branch.company_id.id,
|
||||
@@ -247,7 +380,7 @@ class BeyondBranch(models.Model):
|
||||
metodos = (branch.payment_method_id | branch.card_method_id
|
||||
| branch.transfer_method_id)
|
||||
if not branch.pos_config_id:
|
||||
branch.pos_config_id = self.env['pos.config'].create({
|
||||
branch.pos_config_id = branch.env['pos.config'].create({
|
||||
'name': branch.name,
|
||||
'picking_type_id': branch.warehouse_id.pos_type_id.id,
|
||||
'payment_method_ids': [(6, 0, metodos.ids)],
|
||||
@@ -265,7 +398,7 @@ class BeyondBranch(models.Model):
|
||||
elif faltantes:
|
||||
branch.pos_config_id.payment_method_ids = [(4, m.id) for m in faltantes]
|
||||
if not branch.folio_sequence_id:
|
||||
branch.folio_sequence_id = self.env['ir.sequence'].create({
|
||||
branch.folio_sequence_id = branch.env['ir.sequence'].create({
|
||||
'name': _('Folios %s', branch.name),
|
||||
'code': f'beyond.branch.folio.{branch.code}',
|
||||
'prefix': f'{branch.code}-',
|
||||
@@ -273,7 +406,7 @@ class BeyondBranch(models.Model):
|
||||
'company_id': branch.company_id.id,
|
||||
})
|
||||
if not branch.department_id:
|
||||
branch.department_id = self.env['hr.department'].create({
|
||||
branch.department_id = branch.env['hr.department'].create({
|
||||
'name': branch.name,
|
||||
'company_id': branch.company_id.id,
|
||||
'branch_id': branch.id,
|
||||
|
||||
@@ -14,8 +14,13 @@ class BeyondPricelistCopy(models.TransientModel):
|
||||
_name = 'beyond.branch.pricelist.copy'
|
||||
_description = 'Replicar precios de otra sucursal'
|
||||
|
||||
# Editable desde que el asistente se abre en «Precios por sucursal», que
|
||||
# no tiene una plaza activa de la que sacarlo. El readonly nunca fue una
|
||||
# protección —la vista no protege nada fuera de ella—: quien puede
|
||||
# escribir en esa plaza lo decide la ir.rule al aplicar.
|
||||
branch_id = fields.Many2one(
|
||||
'beyond.branch', string='Sucursal destino', required=True, readonly=True)
|
||||
'beyond.branch', string='Sucursal destino', required=True,
|
||||
domain="[('pricelist_id', '!=', False)]")
|
||||
origen_id = fields.Many2one(
|
||||
'beyond.branch', string='Copiar los precios de', required=True,
|
||||
domain="[('id', '!=', branch_id), ('pricelist_id', '!=', False)]")
|
||||
@@ -24,6 +29,69 @@ class BeyondPricelistCopy(models.TransientModel):
|
||||
help='Por defecto solo se agregan los artículos que aún no tienen '
|
||||
'precio propio aquí: lo ya ajustado a mano no se pisa.')
|
||||
|
||||
# ── Qué se va a pisar, dicho antes de pisarlo ───────────────────────
|
||||
beyond_a_copiar = fields.Integer(
|
||||
string='Precios que entran', compute='_compute_beyond_resumen')
|
||||
beyond_a_reemplazar = fields.Integer(
|
||||
string='Precios que se reemplazan', compute='_compute_beyond_resumen')
|
||||
beyond_a_conservar = fields.Integer(
|
||||
string='Precios que se conservan', compute='_compute_beyond_resumen')
|
||||
beyond_resumen = fields.Text(
|
||||
string='Resumen', compute='_compute_beyond_resumen')
|
||||
|
||||
@api.depends('branch_id', 'origen_id', 'reemplazar')
|
||||
def _compute_beyond_resumen(self):
|
||||
"""Esta operación SOBRESCRIBE trabajo hecho a mano, así que antes de
|
||||
aceptarla hay que poder leer qué se va a pisar: cuántos precios, de
|
||||
qué plaza y sobre cuál. Un «¿estás seguro?» no dice nada, y quien lo
|
||||
lee tres veces deja de leerlo.
|
||||
|
||||
Se lee con sudo —comparar entre plazas es trabajo de un gerente y
|
||||
ADR-009 dejó la lectura abierta—; quien puede ESCRIBIR lo sigue
|
||||
decidiendo la ir.rule en `action_apply`.
|
||||
"""
|
||||
Item = self.env['product.pricelist.item'].sudo()
|
||||
for copia in self:
|
||||
destino = copia.branch_id.sudo().pricelist_id
|
||||
origen = copia.origen_id.sudo().pricelist_id
|
||||
if not (destino and origen):
|
||||
copia.beyond_a_copiar = 0
|
||||
copia.beyond_a_reemplazar = 0
|
||||
copia.beyond_a_conservar = 0
|
||||
copia.beyond_resumen = _(
|
||||
'Elige de qué sucursal copiar para ver qué cambiaría.')
|
||||
continue
|
||||
del_origen = set(Item.search([
|
||||
('pricelist_id', '=', origen.id)]).mapped('product_tmpl_id').ids)
|
||||
del_destino = set(Item.search([
|
||||
('pricelist_id', '=', destino.id)]).mapped('product_tmpl_id').ids)
|
||||
coinciden = del_origen & del_destino
|
||||
copia.beyond_a_copiar = len(del_origen - del_destino)
|
||||
copia.beyond_a_reemplazar = len(coinciden) if copia.reemplazar else 0
|
||||
copia.beyond_a_conservar = 0 if copia.reemplazar else len(coinciden)
|
||||
|
||||
lineas = [_(
|
||||
'Entran %(cuantos)s precios nuevos de %(origen)s a %(destino)s.',
|
||||
cuantos=copia.beyond_a_copiar, origen=copia.origen_id.name,
|
||||
destino=copia.branch_id.name)]
|
||||
if not coinciden:
|
||||
lineas.append(_(
|
||||
'%s no tiene todavía ningún precio propio, así que no se '
|
||||
'pisa nada.', copia.branch_id.name))
|
||||
elif copia.reemplazar:
|
||||
lineas.append(_(
|
||||
'SE REEMPLAZAN %(cuantos)s precios que %(destino)s ya tenía '
|
||||
'capturados: los suyos se pierden y quedan los de '
|
||||
'%(origen)s.',
|
||||
cuantos=copia.beyond_a_reemplazar,
|
||||
destino=copia.branch_id.name, origen=copia.origen_id.name))
|
||||
else:
|
||||
lineas.append(_(
|
||||
'Se conservan los %(cuantos)s precios que %(destino)s ya '
|
||||
'tenía capturados: no se pisa nada.',
|
||||
cuantos=copia.beyond_a_conservar, destino=copia.branch_id.name))
|
||||
copia.beyond_resumen = '\n'.join(lineas)
|
||||
|
||||
def action_apply(self):
|
||||
self.ensure_one()
|
||||
destino = self.branch_id.sudo().pricelist_id
|
||||
@@ -31,22 +99,31 @@ class BeyondPricelistCopy(models.TransientModel):
|
||||
if not (destino and origen):
|
||||
raise UserError(_('Alguna de las dos sucursales no tiene lista de '
|
||||
'precios; corre el aprovisionador primero.'))
|
||||
Item = self.env['product.pricelist.item'].sudo()
|
||||
# LEER con sudo y ESCRIBIR sin él, a propósito. Comparar precios entre
|
||||
# plazas es trabajo de un gerente y ADR-009 dejó la lectura abierta;
|
||||
# escribir los de una plaza es de su gerente y de nadie más, y quien
|
||||
# lo decide es la ir.rule de ese mismo ADR.
|
||||
#
|
||||
# Con las dos operaciones bajo sudo, el asistente saltaba la regla
|
||||
# entera: bastaba crearlo por RPC con la sucursal destino que se
|
||||
# quisiera —branch_id es readonly en la VISTA, que no protege nada
|
||||
# fuera de ella— para copiar precios dentro de una plaza ajena.
|
||||
Lectura = self.env['product.pricelist.item'].sudo()
|
||||
existentes = {i.product_tmpl_id.id: i
|
||||
for i in Item.search([('pricelist_id', '=', destino.id)])}
|
||||
for i in Lectura.search([('pricelist_id', '=', destino.id)])}
|
||||
copiados = actualizados = 0
|
||||
for item in Item.search([('pricelist_id', '=', origen.id)]):
|
||||
for item in Lectura.search([('pricelist_id', '=', origen.id)]):
|
||||
actual = existentes.get(item.product_tmpl_id.id)
|
||||
if actual and not self.reemplazar:
|
||||
continue
|
||||
if actual:
|
||||
actual.write({'fixed_price': item.fixed_price})
|
||||
actual.sudo(False).write({'fixed_price': item.fixed_price})
|
||||
actualizados += 1
|
||||
continue
|
||||
item.copy({'pricelist_id': destino.id})
|
||||
item.sudo(False).copy({'pricelist_id': destino.id})
|
||||
copiados += 1
|
||||
if 'beyond.bitacora' in self.env: # dependencia suave del checador
|
||||
self.env['beyond.bitacora'].sudo().registrar(
|
||||
self.env['beyond.bitacora'].sudo()._registrar(
|
||||
'precios_replicados', 'beyond.branch', self.branch_id.id,
|
||||
despues={'origen': self.origen_id.name, 'copiados': copiados,
|
||||
'actualizados': actualizados},
|
||||
|
||||
@@ -7,12 +7,16 @@ from odoo.exceptions import ValidationError
|
||||
# que acota de verdad.
|
||||
LIMITE_ARTICULOS = 200
|
||||
|
||||
# La matriz del catálogo sí pagina: 40 renglones por página, que es lo que se
|
||||
# lee de un vistazo sin desplazarse a ciegas.
|
||||
LIMITE_PAGINA = 40
|
||||
|
||||
|
||||
class ProductTemplate(models.Model):
|
||||
_inherit = 'product.template'
|
||||
|
||||
@api.model
|
||||
def beyond_matriz_datos(self, tipo, busqueda=''):
|
||||
def beyond_matriz_datos(self, tipo, busqueda='', solo_base=False):
|
||||
"""Catálogo × sucursales, para comparar plazas de un vistazo.
|
||||
|
||||
Distingue precio PROPIO de precio HEREDADO: un artículo sin ítem en
|
||||
@@ -33,15 +37,13 @@ class ProductTemplate(models.Model):
|
||||
dominio = [('type', '=', tipo), ('sale_ok', '=', True)]
|
||||
if busqueda:
|
||||
dominio.append(('name', 'ilike', busqueda))
|
||||
if solo_base:
|
||||
dominio.append(('id', 'in', self._beyond_ids_al_precio_base(
|
||||
tipo, sucursales if general else self.env.user.branch_ids)))
|
||||
articulos = self.search(dominio, order='name', limit=LIMITE_ARTICULOS)
|
||||
total = self.search_count(dominio)
|
||||
|
||||
items = self.env['product.pricelist.item'].search([
|
||||
('product_tmpl_id', 'in', articulos.ids),
|
||||
('pricelist_id', 'in', sucursales.pricelist_id.ids),
|
||||
])
|
||||
propios = {(i.product_tmpl_id.id, i.pricelist_id.branch_id.id): i.fixed_price
|
||||
for i in items}
|
||||
propios = self._beyond_precios_propios(articulos, sucursales)
|
||||
|
||||
return {
|
||||
'sucursales': [{
|
||||
@@ -62,6 +64,141 @@ class ProductTemplate(models.Model):
|
||||
'total': total,
|
||||
'mostrados': len(articulos),
|
||||
'simbolo': self.env.company.currency_id.symbol,
|
||||
# Replicar precios es de la dirección: es una operación de
|
||||
# arranque —abrir una plaza nueva— y pisa trabajo hecho.
|
||||
'puede_replicar': general,
|
||||
}
|
||||
|
||||
@api.model
|
||||
def _beyond_ids_al_precio_base(self, tipo, sucursales):
|
||||
"""Artículos que alguna de esas plazas vende al precio base de red.
|
||||
|
||||
Es la pregunta que antes vivía en un botón de la ficha de la sucursal
|
||||
—«qué vende esta plaza al precio base»— convertida en filtro de la
|
||||
tabla. El alcance lo pone quien pregunta: para un gerente son SUS
|
||||
plazas, así que un artículo con precio propio en la suya no le falta
|
||||
aunque le falte a otra; para la dirección basta con que falte en una.
|
||||
|
||||
Se resuelve en el SERVIDOR y no en el navegador porque la tabla tiene
|
||||
tope de artículos: filtrar la página diría «no falta ninguno»
|
||||
habiendo cien fuera.
|
||||
|
||||
Que un artículo no tenga precio propio NO es una carencia (ADR-009):
|
||||
sin precio local se vende al base, que es lo normal. Por eso el filtro
|
||||
se llama como se llama.
|
||||
"""
|
||||
if not sucursales:
|
||||
return []
|
||||
Item = self.env['product.pricelist.item'].sudo()
|
||||
con_precio = {}
|
||||
for lista, ids in Item._read_group(
|
||||
[('pricelist_id', 'in', sucursales.pricelist_id.ids)],
|
||||
['pricelist_id'], ['product_tmpl_id:array_agg']):
|
||||
con_precio[lista.id] = set(ids or [])
|
||||
al_base = set()
|
||||
for branch in sucursales:
|
||||
if not branch.pricelist_id:
|
||||
continue
|
||||
ofrecidos = self.search([
|
||||
('type', '=', tipo), ('sale_ok', '=', True),
|
||||
'|', ('branch_ids', '=', False), ('branch_ids', 'in', branch.id),
|
||||
]).ids
|
||||
al_base |= set(ofrecidos) - con_precio.get(branch.pricelist_id.id, set())
|
||||
return list(al_base)
|
||||
|
||||
@api.model
|
||||
def _beyond_precios_propios(self, articulos, sucursales):
|
||||
"""{(plantilla, sucursal): precio} para las que tienen ítem propio.
|
||||
|
||||
Lo comparten la matriz de precios y la del catálogo: qué se cobra en
|
||||
cada plaza es el mismo dato mirado desde dos pantallas, y si cada una
|
||||
lo calculara por su cuenta acabarían discrepando.
|
||||
"""
|
||||
items = self.env['product.pricelist.item'].search([
|
||||
('product_tmpl_id', 'in', articulos.ids),
|
||||
('pricelist_id', 'in', sucursales.pricelist_id.ids),
|
||||
])
|
||||
return {(i.product_tmpl_id.id, i.pricelist_id.branch_id.id): i.fixed_price
|
||||
for i in items}
|
||||
|
||||
@api.model
|
||||
def _beyond_existencias(self, articulos, sucursales):
|
||||
"""{(plantilla, sucursal): existencia} del inventario PROPIO.
|
||||
|
||||
Leía `stock.quant` con el `branch_id` que le puso ADR-017. Desde
|
||||
ADR-015 de Jorem el inventario vive en `beyond.existencia` y el POS
|
||||
descuenta de ahí: seguir leyendo los quants habría dejado esta
|
||||
pantalla enseñando un saldo que ya nadie mueve, que es peor que no
|
||||
enseñar ninguno.
|
||||
|
||||
Sin `sudo()`: la regla de sucursal de ese modelo es la que recorta,
|
||||
igual que hacía la nuestra.
|
||||
"""
|
||||
if not articulos or not sucursales:
|
||||
return {}
|
||||
if 'beyond.existencia' not in self.env:
|
||||
return {}
|
||||
grupos = self.env['beyond.existencia']._read_group(
|
||||
[('product_tmpl_id', 'in', articulos.ids),
|
||||
('branch_id', 'in', sucursales.ids)],
|
||||
['product_tmpl_id', 'branch_id'], ['cantidad:sum'])
|
||||
return {(articulo.id, branch.id): cantidad
|
||||
for articulo, branch, cantidad in grupos}
|
||||
|
||||
@api.model
|
||||
def beyond_catalogo_datos(self, tipo, busqueda='', offset=0, limit=LIMITE_PAGINA):
|
||||
"""Catálogo × sucursales con precio efectivo Y existencia.
|
||||
|
||||
Es la pantalla de Productos del hub: de un renglón se lee a cuánto se
|
||||
vende y cuánto queda en cada plaza.
|
||||
|
||||
Diferencia deliberada con `beyond_matriz_datos`: **aquí las columnas
|
||||
son las que el usuario puede leer**, sin `sudo()`. En la matriz de
|
||||
precios un gerente ve todas las plazas a propósito, porque comparar
|
||||
precios es parte de su trabajo (ADR-012). Esta pantalla mezcla el
|
||||
precio con la EXISTENCIA, y la existencia de otra plaza no es suya
|
||||
(ADR-017): no basta con no pintarla, la columna no viaja.
|
||||
"""
|
||||
sucursales = self.env['beyond.branch'].search([('pricelist_id', '!=', False)])
|
||||
|
||||
dominio = [('type', '=', tipo), ('sale_ok', '=', True)]
|
||||
if busqueda:
|
||||
dominio.append(('name', 'ilike', busqueda))
|
||||
articulos = self.search(dominio, order='name', offset=offset, limit=limit)
|
||||
|
||||
propios = self._beyond_precios_propios(articulos, sucursales)
|
||||
# Un servicio no lleva inventario por definición (ADR-012 §4): la
|
||||
# píldora no aplica y el dato no se inventa.
|
||||
existencias = ({} if tipo == 'service'
|
||||
else self._beyond_existencias(articulos, sucursales))
|
||||
|
||||
return {
|
||||
'sucursales': [{'id': branch.id, 'nombre': branch.name}
|
||||
for branch in sucursales],
|
||||
'articulos': [{
|
||||
'id': articulo.id,
|
||||
'nombre': articulo.name,
|
||||
'base': articulo.list_price,
|
||||
'celdas': [{
|
||||
'branch_id': branch.id,
|
||||
'precio': propios.get((articulo.id, branch.id), articulo.list_price),
|
||||
'propio': (articulo.id, branch.id) in propios,
|
||||
'existencia': (None if tipo == 'service'
|
||||
else existencias.get((articulo.id, branch.id), 0.0)),
|
||||
} for branch in sucursales],
|
||||
} for articulo in articulos],
|
||||
# Quién puede dar de alta lo dice el servidor, no el navegador.
|
||||
# El catálogo es exclusivo de la dirección (ADR-012 §3), y
|
||||
# preguntarlo por `has_access` en vez de por el nombre del grupo
|
||||
# hace que el botón desaparezca exactamente cuando el alta iba a
|
||||
# ser rechazada, sin una segunda copia de la regla que se pueda
|
||||
# desincronizar.
|
||||
'puede_crear': self.has_access('create'),
|
||||
'total': self.search_count(dominio),
|
||||
'mostrados': len(articulos),
|
||||
'offset': offset,
|
||||
'limite': limit,
|
||||
'simbolo': self.env.company.currency_id.symbol,
|
||||
}
|
||||
|
||||
@api.model
|
||||
|
||||
@@ -89,6 +89,23 @@ class ProductTemplate(models.Model):
|
||||
help='Con una sola sucursal la pregunta del precio no aplica: se '
|
||||
'captura directo.')
|
||||
|
||||
# ── Lo que se captura en el alta y no vive en el producto ───────────
|
||||
# Precios por plaza y existencias iniciales son de OTROS modelos —ítems
|
||||
# de lista de precios y quants—, pero se capturan dentro de la ficha
|
||||
# porque son parte de la misma conversación. Viajan en estos dos campos
|
||||
# y `create` los consume y los vacía: al terminar el alta no queda nada
|
||||
# dentro, y lo que quedó fue escrito donde de verdad vive.
|
||||
|
||||
beyond_precios_alta = fields.Json(
|
||||
string='Precios capturados en el alta', copy=False,
|
||||
help='Solo durante el alta: al guardar se convierten en el precio '
|
||||
'propio de cada sucursal y el campo se vacía.')
|
||||
|
||||
beyond_existencias_alta = fields.Json(
|
||||
string='Existencias iniciales', copy=False,
|
||||
help='Solo al crear: al guardar se hace el ajuste de inventario en '
|
||||
'el almacén de cada sucursal y el campo se vacía.')
|
||||
|
||||
@api.depends('branch_ids')
|
||||
def _compute_beyond_alcance(self):
|
||||
for template in self:
|
||||
@@ -115,27 +132,108 @@ class ProductTemplate(models.Model):
|
||||
a partir de ahí manda la realidad —tener o no precios propios—. Sin
|
||||
este inverse el campo sería de solo lectura y no se podría elegir."""
|
||||
|
||||
def action_beyond_guardar(self):
|
||||
"""El «Guardar» explícito del alta.
|
||||
@api.model
|
||||
def beyond_ficha_precios(self, tmpl_id=False):
|
||||
"""Las tarjetas de precio por sucursal de la ficha.
|
||||
|
||||
Cualquier botón de objeto guarda el registro antes de ejecutarse, así
|
||||
que el trabajo de guardar lo hace Odoo; lo que aporta este método es
|
||||
que la acción sea EVIDENTE —el icono de nube no lo es— y que el
|
||||
siguiente paso venga solo: si el precio es por sucursal, abre la
|
||||
pantalla donde hay que capturarlo.
|
||||
Mismo criterio que la matriz (ADR-012): se ven todas las plazas
|
||||
—comparar es parte del trabajo de un gerente— y solo se edita la
|
||||
propia; la tarjeta ajena lleva candado, y el candado lo decide el
|
||||
servidor, no el navegador.
|
||||
|
||||
`tmpl_id` puede venir vacío: en el alta el artículo todavía no
|
||||
existe y las tarjetas hay que dibujarlas igual, o no habría dónde
|
||||
capturar el precio antes de guardar.
|
||||
"""
|
||||
self.ensure_one()
|
||||
if self.beyond_precio_modo == 'por_sucursal' and self.beyond_varias_sucursales:
|
||||
accion = self.env['ir.actions.act_window']._for_xml_id(
|
||||
'beyond_branch.action_beyond_precios_por_sucursal')
|
||||
accion['context'] = dict(
|
||||
self.env.context, create=True,
|
||||
default_product_tmpl_id=self.id,
|
||||
default_applied_on='1_product',
|
||||
default_compute_price='fixed')
|
||||
accion['domain'] = [('product_tmpl_id', '=', self.id)]
|
||||
return accion
|
||||
return {'type': 'ir.actions.act_window_close'}
|
||||
sucursales = self.env['beyond.branch'].sudo().search(
|
||||
[('pricelist_id', '!=', False)])
|
||||
general = self.env.user.has_group('beyond_base.beyond_group_admin_general')
|
||||
propias = self.env.user.branch_ids.ids
|
||||
|
||||
articulo = self.browse(tmpl_id) if tmpl_id else self.browse()
|
||||
base = articulo.list_price if articulo else 0.0
|
||||
propios = (self._beyond_precios_propios(articulo, sucursales)
|
||||
if articulo else {})
|
||||
|
||||
return {
|
||||
'base': base,
|
||||
'simbolo': self.env.company.currency_id.symbol,
|
||||
'sucursales': [{
|
||||
'id': branch.id,
|
||||
'nombre': branch.name,
|
||||
'editable': general or branch.id in propias,
|
||||
'precio': propios.get((articulo.id, branch.id), base),
|
||||
'propio': (articulo.id, branch.id) in propios,
|
||||
} for branch in sucursales],
|
||||
}
|
||||
|
||||
def _beyond_sucursales_de(self, por_sucursal, para):
|
||||
"""Traduce {id de sucursal: valor} a registros, o explica por qué no.
|
||||
|
||||
Las claves llegan del navegador y se usan para escribir en modelos
|
||||
aislados por sucursal, así que se resuelven contra lo que este
|
||||
usuario puede LEER: una sucursal que no puede ver no puede ser el
|
||||
destino de nada que capture.
|
||||
"""
|
||||
ids = [int(clave) for clave in por_sucursal]
|
||||
sucursales = self.env['beyond.branch'].browse(ids).exists()
|
||||
faltan = set(ids) - set(sucursales.ids)
|
||||
legibles = self.env['beyond.branch'].search([('id', 'in', sucursales.ids)])
|
||||
faltan |= set(sucursales.ids) - set(legibles.ids)
|
||||
if faltan:
|
||||
raise UserError(_(
|
||||
'No se puede capturar %s en una sucursal que no existe o que '
|
||||
'no administras.', para))
|
||||
return legibles
|
||||
|
||||
def _beyond_aplicar_precios_alta(self):
|
||||
for template in self:
|
||||
capturados = template.beyond_precios_alta or {}
|
||||
if not capturados:
|
||||
continue
|
||||
template._beyond_sucursales_de(capturados, _('precios'))
|
||||
for clave, precio in capturados.items():
|
||||
if precio in (None, False, ''):
|
||||
continue
|
||||
# El mismo camino que la matriz: un solo sitio donde se
|
||||
# decide qué es un ítem de lista de precios válido.
|
||||
self.beyond_matriz_guardar(template.id, int(clave), precio)
|
||||
template.beyond_precios_alta = False
|
||||
|
||||
def _beyond_aplicar_existencias_alta(self):
|
||||
for template in self:
|
||||
capturadas = template.beyond_existencias_alta or {}
|
||||
if not capturadas:
|
||||
continue
|
||||
# `is_storable` dejó de servir como criterio: el inventario
|
||||
# propio lo fuerza a falso en TODO producto (ADR-015 de Jorem), y
|
||||
# preguntando por él ningún artículo llevaría existencias. Lo que
|
||||
# decide ahora es el TIPO, que es lo que ese módulo usa
|
||||
# (`_beyond_lleva_inventario`): un servicio no se almacena y un
|
||||
# combo tampoco, porque lo que se descuenta son sus partes.
|
||||
if template.type != 'consu':
|
||||
raise UserError(_(
|
||||
'%s no lleva inventario: no se le pueden poner '
|
||||
'existencias iniciales.', template.name))
|
||||
sucursales = template._beyond_sucursales_de(
|
||||
capturadas, _('existencias'))
|
||||
variante = template.product_variant_id
|
||||
for branch in sucursales:
|
||||
cantidad = capturadas.get(str(branch.id)) or 0.0
|
||||
if not cantidad:
|
||||
continue
|
||||
almacen = branch.warehouse_id.lot_stock_id
|
||||
if not almacen:
|
||||
raise UserError(_(
|
||||
'La sucursal %s no tiene almacén; corre el '
|
||||
'aprovisionador antes de sembrarle existencias.',
|
||||
branch.name))
|
||||
# Siempre en el almacén de una SUCURSAL. Una existencia sin
|
||||
# sucursal no la ve ningún gerente (ADR-017): sería
|
||||
# inventario invisible.
|
||||
self.env['stock.quant']._update_available_quantity(
|
||||
variante, almacen, cantidad)
|
||||
template.beyond_existencias_alta = False
|
||||
|
||||
@api.constrains('type', 'is_storable')
|
||||
def _beyond_check_servicio_sin_inventario(self):
|
||||
@@ -182,6 +280,11 @@ class ProductTemplate(models.Model):
|
||||
de la transacción se encarga del resto.
|
||||
"""
|
||||
templates = super().create(vals_list)
|
||||
templates._beyond_aplicar_precios_alta()
|
||||
# Solo al crear: después el stock entra por Inventario y por Captura
|
||||
# (ADR-012 §7). Si la ficha siguiera sembrando al editar, corregir un
|
||||
# nombre volvería a fijar la existencia.
|
||||
templates._beyond_aplicar_existencias_alta()
|
||||
if not self._beyond_escritura_de_sistema():
|
||||
ajenas = templates.filtered('branch_ids')
|
||||
if ajenas:
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
from odoo import fields, models
|
||||
from odoo import api, fields, models
|
||||
|
||||
|
||||
class StockWarehouse(models.Model):
|
||||
@@ -16,3 +16,57 @@ class StockPicking(models.Model):
|
||||
branch_id = fields.Many2one(
|
||||
related='picking_type_id.warehouse_id.branch_id', string='Sucursal',
|
||||
store=True, index=True)
|
||||
|
||||
|
||||
class StockQuant(models.Model):
|
||||
_inherit = 'stock.quant'
|
||||
|
||||
# El aislamiento de Fase 1 llegaba al almacén y a la transferencia, que
|
||||
# son los envoltorios; lo de dentro —cuánto hay y qué se movió— seguía
|
||||
# abierto a cualquier llamada RPC.
|
||||
#
|
||||
# location_id is required, and stock.location.warehouse_id is a stored
|
||||
# compute, so the related chain is stored and searchable. Quants in
|
||||
# virtual locations (customer, supplier, inventory adjustment) have no
|
||||
# warehouse behind them and therefore no branch: they are nobody's stock
|
||||
# and stay out of reach of the branch admins, which is the intent.
|
||||
branch_id = fields.Many2one(
|
||||
'beyond.branch', related='location_id.warehouse_id.branch_id',
|
||||
string='Sucursal', store=True, index=True)
|
||||
|
||||
|
||||
class StockMove(models.Model):
|
||||
_inherit = 'stock.move'
|
||||
|
||||
branch_id = fields.Many2one(
|
||||
'beyond.branch', string='Sucursal', compute='_compute_beyond_branch',
|
||||
store=True, index=True)
|
||||
|
||||
@api.depends('location_id.warehouse_id.branch_id',
|
||||
'location_dest_id.warehouse_id.branch_id')
|
||||
def _compute_beyond_branch(self):
|
||||
# One end of a move is almost always a virtual location with no
|
||||
# warehouse behind it: an outgoing move carries the branch on its
|
||||
# source, an incoming one on its destination. Taking the first of the
|
||||
# two that resolves covers both without a special case.
|
||||
for move in self:
|
||||
move.branch_id = (move.location_id.warehouse_id.branch_id
|
||||
or move.location_dest_id.warehouse_id.branch_id)
|
||||
|
||||
|
||||
class StockMoveLine(models.Model):
|
||||
_inherit = 'stock.move.line'
|
||||
|
||||
branch_id = fields.Many2one(
|
||||
'beyond.branch', string='Sucursal', compute='_compute_beyond_branch',
|
||||
store=True, index=True)
|
||||
|
||||
@api.depends('location_id.warehouse_id.branch_id',
|
||||
'location_dest_id.warehouse_id.branch_id')
|
||||
def _compute_beyond_branch(self):
|
||||
# Read from its own locations, not from move_id: a move line can
|
||||
# outlive its move (inventory adjustments) and its locations can be
|
||||
# finer than the move's.
|
||||
for line in self:
|
||||
line.branch_id = (line.location_id.warehouse_id.branch_id
|
||||
or line.location_dest_id.warehouse_id.branch_id)
|
||||
@@ -161,6 +161,51 @@
|
||||
<field name="domain_force">[(1, '=', 1)]</field>
|
||||
</record>
|
||||
|
||||
<!-- Existencias y movimientos. Las transferencias ya estaban aisladas,
|
||||
pero el quant, el movimiento y la línea de movimiento no: por RPC se
|
||||
leía cuánto tiene cada plaza y qué salió de ella. El core escribe
|
||||
quants con sudo (_update_available_quantity), así que estas reglas
|
||||
no estorban ni al POS ni a Captura; lo que acotan es la LECTURA, que
|
||||
es justo la vía por la que se fugaba. -->
|
||||
<record id="rule_quant_admin_sucursal" model="ir.rule">
|
||||
<field name="name">Beyond: existencias por sucursal (admin de sucursal)</field>
|
||||
<field name="model_id" ref="stock.model_stock_quant"/>
|
||||
<field name="groups" eval="[(4, ref('beyond_base.beyond_group_admin_sucursal'))]"/>
|
||||
<field name="domain_force">[('branch_id', 'in', user.branch_ids.ids)]</field>
|
||||
</record>
|
||||
<record id="rule_quant_admin_general" model="ir.rule">
|
||||
<field name="name">Beyond: existencias todas (admin general)</field>
|
||||
<field name="model_id" ref="stock.model_stock_quant"/>
|
||||
<field name="groups" eval="[(4, ref('beyond_base.beyond_group_admin_general'))]"/>
|
||||
<field name="domain_force">[(1, '=', 1)]</field>
|
||||
</record>
|
||||
|
||||
<record id="rule_move_admin_sucursal" model="ir.rule">
|
||||
<field name="name">Beyond: movimientos por sucursal (admin de sucursal)</field>
|
||||
<field name="model_id" ref="stock.model_stock_move"/>
|
||||
<field name="groups" eval="[(4, ref('beyond_base.beyond_group_admin_sucursal'))]"/>
|
||||
<field name="domain_force">[('branch_id', 'in', user.branch_ids.ids)]</field>
|
||||
</record>
|
||||
<record id="rule_move_admin_general" model="ir.rule">
|
||||
<field name="name">Beyond: movimientos todos (admin general)</field>
|
||||
<field name="model_id" ref="stock.model_stock_move"/>
|
||||
<field name="groups" eval="[(4, ref('beyond_base.beyond_group_admin_general'))]"/>
|
||||
<field name="domain_force">[(1, '=', 1)]</field>
|
||||
</record>
|
||||
|
||||
<record id="rule_move_line_admin_sucursal" model="ir.rule">
|
||||
<field name="name">Beyond: líneas de movimiento por sucursal (admin de sucursal)</field>
|
||||
<field name="model_id" ref="stock.model_stock_move_line"/>
|
||||
<field name="groups" eval="[(4, ref('beyond_base.beyond_group_admin_sucursal'))]"/>
|
||||
<field name="domain_force">[('branch_id', 'in', user.branch_ids.ids)]</field>
|
||||
</record>
|
||||
<record id="rule_move_line_admin_general" model="ir.rule">
|
||||
<field name="name">Beyond: líneas de movimiento todas (admin general)</field>
|
||||
<field name="model_id" ref="stock.model_stock_move_line"/>
|
||||
<field name="groups" eval="[(4, ref('beyond_base.beyond_group_admin_general'))]"/>
|
||||
<field name="domain_force">[(1, '=', 1)]</field>
|
||||
</record>
|
||||
|
||||
<record id="rule_department_admin_sucursal" model="ir.rule">
|
||||
<field name="name">Beyond: equipos por sucursal (admin de sucursal)</field>
|
||||
<field name="model_id" ref="hr.model_hr_department"/>
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
// Catálogo: el hub de mosaicos y la matriz de productos. Las dos son
|
||||
// acciones cliente, así que no heredan el panel de control revestido y
|
||||
// dibujan su propio encabezado contra el MISMO eje que el resto del panel
|
||||
// (ADR-013): si eligieran su propio margen se notaría al cambiar de pestaña.
|
||||
|
||||
// La clase del Layout cae sobre el propio .o_content, que ya se encarga del
|
||||
// alto y del desplazamiento: aquí solo va el fondo del panel y el aire de
|
||||
// abajo, que si no la última fila queda pegada al borde.
|
||||
.o_beyond_catalogo_hub,
|
||||
.o_beyond_catalogo_matriz {
|
||||
background: $beyond-surface;
|
||||
padding-bottom: 32px;
|
||||
}
|
||||
|
||||
.beyond_hub_eje,
|
||||
.beyond_cat_eje {
|
||||
@include beyond-ancho-contenido;
|
||||
padding-top: 20px;
|
||||
}
|
||||
|
||||
// ── Hub ─────────────────────────────────────────────────────────────────
|
||||
// El título no se dibuja aquí: lo pone la miga del panel de control, igual
|
||||
// que en Clientes y Sucursales. Repetirlo daría dos títulos.
|
||||
.beyond_hub_mosaicos {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.beyond_hub_mosaico {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 6px;
|
||||
padding: 24px;
|
||||
min-height: 180px;
|
||||
text-align: left;
|
||||
background: $beyond-panel-tarjeta;
|
||||
border: 1px solid $beyond-line;
|
||||
border-radius: $beyond-panel-radio-tarjeta;
|
||||
transition: transform .12s ease, box-shadow .12s ease;
|
||||
|
||||
&:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 8px 20px rgba(35, 32, 29, .10);
|
||||
}
|
||||
&:focus-visible {
|
||||
outline: 2px solid $beyond-panel-acento;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.beyond_hub_icono {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: $beyond-panel-tactil;
|
||||
height: $beyond-panel-tactil;
|
||||
margin-bottom: 8px;
|
||||
border-radius: $beyond-panel-radio-control;
|
||||
background: $beyond-panel-durazno;
|
||||
color: $beyond-panel-acento-pressed;
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
.beyond_hub_nombre {
|
||||
font-size: 19px;
|
||||
font-weight: 800;
|
||||
color: $beyond-ink;
|
||||
}
|
||||
|
||||
.beyond_hub_detalle {
|
||||
font-size: 14px;
|
||||
color: $beyond-ink-softer;
|
||||
}
|
||||
|
||||
// ── Matriz de productos ─────────────────────────────────────────────────
|
||||
.beyond_cat_nuevo {
|
||||
padding: 10px 22px;
|
||||
border-radius: 999px;
|
||||
background: $beyond-panel-acento;
|
||||
color: #fff;
|
||||
font-weight: 700;
|
||||
|
||||
&:hover { background: $beyond-panel-acento-hover; color: #fff; }
|
||||
}
|
||||
|
||||
.beyond_cat_controles {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
|
||||
.beyond_cat_buscador {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex: 1 1 260px;
|
||||
max-width: 360px;
|
||||
padding: 0 14px;
|
||||
height: 44px;
|
||||
background: $beyond-panel-tarjeta;
|
||||
border: 1px solid $beyond-line;
|
||||
border-radius: 999px;
|
||||
color: $beyond-ink-softer;
|
||||
|
||||
&:focus-within { border-color: $beyond-panel-acento; }
|
||||
|
||||
input {
|
||||
flex: 1;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: $beyond-ink;
|
||||
|
||||
&:focus { outline: none; }
|
||||
}
|
||||
}
|
||||
|
||||
.beyond_cat_paginador {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin-left: auto;
|
||||
color: $beyond-ink-soft;
|
||||
|
||||
.btn {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
padding: 0;
|
||||
border-radius: 50%;
|
||||
color: $beyond-ink-soft;
|
||||
|
||||
&:disabled { color: $beyond-ink-muted; }
|
||||
}
|
||||
}
|
||||
|
||||
.beyond_cat_rango {
|
||||
font-size: 14px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.beyond_cat_tarjeta {
|
||||
background: $beyond-panel-tarjeta;
|
||||
border-radius: $beyond-panel-radio-ficha;
|
||||
padding: 8px 8px 12px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.beyond_cat_vacio {
|
||||
margin: 0;
|
||||
padding: 28px;
|
||||
color: $beyond-ink-softer;
|
||||
}
|
||||
|
||||
.beyond_cat_scroll { overflow-x: auto; }
|
||||
|
||||
.beyond_cat_tabla {
|
||||
width: 100%;
|
||||
border-collapse: separate;
|
||||
border-spacing: 0;
|
||||
|
||||
th, td {
|
||||
padding: 12px 14px;
|
||||
text-align: right;
|
||||
white-space: nowrap;
|
||||
border-bottom: 1px solid $beyond-line;
|
||||
}
|
||||
|
||||
th {
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
letter-spacing: .04em;
|
||||
text-transform: uppercase;
|
||||
color: $beyond-ink-softer;
|
||||
}
|
||||
|
||||
tbody tr {
|
||||
cursor: pointer;
|
||||
|
||||
&:hover td { background: $beyond-surface-hover; }
|
||||
&:last-child td { border-bottom: 0; }
|
||||
}
|
||||
|
||||
// La columna del artículo se queda fija: con varias plazas se pierde de
|
||||
// vista de qué renglón se está leyendo el precio.
|
||||
.beyond_cat_fija {
|
||||
position: sticky;
|
||||
left: 0;
|
||||
z-index: 1;
|
||||
text-align: left;
|
||||
font-weight: 700;
|
||||
color: $beyond-ink;
|
||||
background: $beyond-panel-tarjeta;
|
||||
}
|
||||
|
||||
thead .beyond_cat_fija { z-index: 2; }
|
||||
|
||||
tbody tr:hover .beyond_cat_fija { background: $beyond-surface-hover; }
|
||||
|
||||
.beyond_cat_base { color: $beyond-ink-softer; }
|
||||
}
|
||||
|
||||
.beyond_cat_celda {
|
||||
.beyond_cat_precio {
|
||||
display: block;
|
||||
color: $beyond-ink;
|
||||
}
|
||||
|
||||
// Heredado del precio base: se ve distinto para no confundirlo con un
|
||||
// precio capturado a propósito (ADR-012).
|
||||
.beyond_heredado {
|
||||
color: $beyond-ink-muted;
|
||||
font-style: italic;
|
||||
}
|
||||
}
|
||||
|
||||
.beyond_cat_pildora {
|
||||
display: inline-block;
|
||||
margin-top: 4px;
|
||||
padding: 2px 10px;
|
||||
border-radius: 999px;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
|
||||
&.beyond_hay {
|
||||
background: $beyond-panel-verde-suave;
|
||||
color: $beyond-panel-verde;
|
||||
}
|
||||
|
||||
// Cero o negativo. El negativo no es avería: dice que se vendió algo que
|
||||
// nunca se registró como recibido (ADR-012 §4).
|
||||
&.beyond_falta {
|
||||
background: $beyond-panel-rojo-suave;
|
||||
color: $beyond-panel-rojo;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Tarjetas por sucursal dentro de la ficha ────────────────────────────
|
||||
// Precios y existencias iniciales se capturan aquí, no en otra pantalla: el
|
||||
// alta era una conversación partida en dos y el segundo paso se olvidaba.
|
||||
.beyond_inline_tarjetas {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));
|
||||
gap: 12px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.beyond_inline_tarjeta {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
padding: 14px 16px;
|
||||
background: $beyond-panel-tarjeta;
|
||||
border: 1px solid $beyond-line;
|
||||
border-radius: $beyond-panel-radio-control;
|
||||
|
||||
&.beyond_bloqueada { background: $beyond-surface; }
|
||||
|
||||
// Confirmación de guardado, igual que en la matriz: la tarjeta se marca
|
||||
// un momento para que no quede duda de que quedó.
|
||||
&.beyond_guardada { border-color: $beyond-panel-verde; }
|
||||
}
|
||||
|
||||
.beyond_inline_plaza {
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: $beyond-ink-soft;
|
||||
|
||||
.fa-lock { color: $beyond-ink-muted; }
|
||||
}
|
||||
|
||||
.beyond_inline_precio {
|
||||
width: 100%;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
font-size: 20px;
|
||||
font-weight: 800;
|
||||
color: $beyond-ink;
|
||||
|
||||
&:focus { outline: none; }
|
||||
|
||||
// Heredado del base: se ve distinto de un precio capturado a propósito.
|
||||
&.beyond_heredado {
|
||||
color: $beyond-ink-muted;
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
|
||||
.beyond_inline_nota {
|
||||
font-size: 12px;
|
||||
color: $beyond-ink-softer;
|
||||
}
|
||||
|
||||
.beyond_inline_marca {
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 12px;
|
||||
color: $beyond-panel-verde;
|
||||
}
|
||||
|
||||
// ── La ficha del catálogo ───────────────────────────────────────────────
|
||||
// Reutiliza las piezas de ficha del panel —.beyond_tarjeta, .beyond_campo,
|
||||
// .beyond_chips—, que ya viven bajo body.beyond_panel: son de la capa del
|
||||
// panel aunque se escribieran para Sucursales.
|
||||
body.beyond_panel {
|
||||
.o_beyond_catalogo_form .o_form_sheet {
|
||||
background: transparent;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.beyond_ficha_encabezado {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 16px;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.beyond_ficha_identidad {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
|
||||
h1 { margin: 0; }
|
||||
input { font-size: 28px; font-weight: 800; color: $beyond-ink; }
|
||||
}
|
||||
|
||||
.beyond_ficha_tipo {
|
||||
width: fit-content;
|
||||
padding: 3px 12px;
|
||||
border-radius: 999px;
|
||||
background: $beyond-panel-durazno;
|
||||
color: $beyond-panel-acento-pressed;
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
letter-spacing: .06em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.beyond_boton_precios {
|
||||
margin-left: auto;
|
||||
flex: none;
|
||||
min-height: $beyond-panel-tactil;
|
||||
padding: 0 20px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid $beyond-panel-acento;
|
||||
background: transparent;
|
||||
color: $beyond-panel-acento;
|
||||
font-weight: 700;
|
||||
|
||||
&:hover {
|
||||
background: $beyond-panel-durazno;
|
||||
color: $beyond-panel-acento-pressed;
|
||||
}
|
||||
}
|
||||
|
||||
.beyond_ficha_secciones {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
// Cada campo cuelga de la opción que lo enciende, con la línea que marca
|
||||
// la subordinación (ADR-012, «Disposición»).
|
||||
.beyond_sangria {
|
||||
margin-left: 6px;
|
||||
padding-left: 16px;
|
||||
border-left: 2px solid $beyond-surface-active;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Dónde se ofrece: chips o «Toda la red» ──────────────────────────────
|
||||
.beyond_chips_red {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.beyond_chip_red {
|
||||
padding: 3px 11px;
|
||||
border-radius: 999px;
|
||||
background: $beyond-panel-durazno;
|
||||
color: $beyond-panel-acento-pressed;
|
||||
font-size: 12.5px;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
// La lista vacía significa «en todas» (ADR-009). En gris, porque no es una
|
||||
// elección que alguien haya tecleado: es el estado normal del catálogo.
|
||||
.beyond_chip_toda_la_red {
|
||||
color: $beyond-ink-muted;
|
||||
font-style: italic;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/** @odoo-module **/
|
||||
|
||||
import { Component } from "@odoo/owl";
|
||||
import { Layout } from "@web/search/layout";
|
||||
import { registry } from "@web/core/registry";
|
||||
import { useService } from "@web/core/utils/hooks";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
|
||||
/**
|
||||
* Catálogo: los tres caminos, en mosaicos.
|
||||
*
|
||||
* Odoo no tiene pantalla de mosaicos, así que esto es una acción cliente.
|
||||
* Lo que NO hace es reimplementar la navegación: cada mosaico abre el menú
|
||||
* hijo que ya existe, con el servicio de menús, para que la pestaña activa,
|
||||
* la miga y la URL directa sigan funcionando igual que si se hubiera hecho
|
||||
* clic en la pestaña.
|
||||
*
|
||||
* Un mosaico cuyo menú no está visible para esta persona no se dibuja: los
|
||||
* permisos ya decidieron y no hay que decidirlos otra vez aquí.
|
||||
*/
|
||||
const MOSAICOS = [
|
||||
{
|
||||
xmlid: "beyond_branch.menu_beyond_catalogo_productos",
|
||||
titulo: _t("Productos"),
|
||||
detalle: _t("Qué se vende y a cuánto en cada sucursal, con su existencia."),
|
||||
icono: "fa-cube",
|
||||
},
|
||||
{
|
||||
xmlid: "beyond_branch.menu_beyond_catalogo_servicios",
|
||||
titulo: _t("Servicios"),
|
||||
detalle: _t("Cortes, tintes y todo lo que no lleva inventario."),
|
||||
icono: "fa-scissors",
|
||||
},
|
||||
{
|
||||
xmlid: "beyond_branch.menu_beyond_matriz_precios",
|
||||
titulo: _t("Precios por sucursal"),
|
||||
detalle: _t("Comparar plazas y capturar el precio de cada una."),
|
||||
icono: "fa-tags",
|
||||
},
|
||||
];
|
||||
|
||||
export class BeyondCatalogoHub extends Component {
|
||||
static template = "beyond_branch.CatalogoHub";
|
||||
// Se monta dentro del Layout del core para tener panel de control y
|
||||
// .o_content: así el revestimiento del panel (ADR-013) aplica igual que
|
||||
// en una vista de Odoo y la miga sigue siendo la del cliente web.
|
||||
static components = { Layout };
|
||||
static props = ["*"];
|
||||
|
||||
setup() {
|
||||
this.menu = useService("menu");
|
||||
this.action = useService("action");
|
||||
this.mosaicos = MOSAICOS.filter((m) => this.menuDe(m.xmlid));
|
||||
}
|
||||
|
||||
menuDe(xmlid) {
|
||||
return this.menu.getAll().find((m) => m.xmlid === xmlid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Se abre la acción del menú hijo SIN limpiar la miga, en vez de
|
||||
* `selectMenu`, que la limpia por ser una navegación de menú.
|
||||
*
|
||||
* Así el hub queda como paso anterior y el cliente web dibuja «← Catálogo»
|
||||
* él solo: la píldora de vuelta del panel es la miga nativa revestida, no
|
||||
* un botón nuestro. Sin esto, la única salida de las tres pantallas era la
|
||||
* pestaña de la barra. La pestaña activa se fija aparte, porque eso sí lo
|
||||
* hacía `selectMenu`.
|
||||
*/
|
||||
async abrir(xmlid) {
|
||||
const destino = this.menuDe(xmlid);
|
||||
if (!destino) {
|
||||
return;
|
||||
}
|
||||
this.menu.setCurrentMenu(destino);
|
||||
await this.action.doAction(destino.actionID, { clearBreadcrumbs: false });
|
||||
}
|
||||
}
|
||||
|
||||
registry.category("actions").add("beyond_catalogo_hub", BeyondCatalogoHub);
|
||||
@@ -0,0 +1,21 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
<t t-name="beyond_branch.CatalogoHub">
|
||||
<Layout className="'o_beyond_catalogo_hub'" display="{ controlPanel: {} }">
|
||||
<div class="beyond_hub_eje">
|
||||
<div class="beyond_hub_mosaicos">
|
||||
<t t-foreach="mosaicos" t-as="mosaico" t-key="mosaico.xmlid">
|
||||
<button type="button" class="beyond_hub_mosaico"
|
||||
t-on-click="() => this.abrir(mosaico.xmlid)">
|
||||
<span class="beyond_hub_icono">
|
||||
<i class="fa" t-att-class="mosaico.icono"/>
|
||||
</span>
|
||||
<span class="beyond_hub_nombre" t-esc="mosaico.titulo"/>
|
||||
<span class="beyond_hub_detalle" t-esc="mosaico.detalle"/>
|
||||
</button>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</Layout>
|
||||
</t>
|
||||
</templates>
|
||||
@@ -0,0 +1,143 @@
|
||||
/** @odoo-module **/
|
||||
|
||||
import { Component, onWillStart, useState } from "@odoo/owl";
|
||||
import { Layout } from "@web/search/layout";
|
||||
import { registry } from "@web/core/registry";
|
||||
import { useService } from "@web/core/utils/hooks";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
|
||||
const POR_PAGINA = 40;
|
||||
const ESPERA_BUSQUEDA = 250;
|
||||
|
||||
/**
|
||||
* Catálogo × sucursales: precio efectivo y existencia en cada plaza.
|
||||
*
|
||||
* Sigue el patrón de la matriz de precios —acción cliente, columna del
|
||||
* artículo fija, una sola llamada por página— con dos diferencias:
|
||||
*
|
||||
* - No se edita aquí. El clic en el renglón abre la ficha del artículo; los
|
||||
* precios se capturan en «Precios por sucursal», que es la pantalla que
|
||||
* trata de eso.
|
||||
* - Pagina de verdad. La matriz de precios corta en 200 y avisa; aquí el
|
||||
* catálogo puede ser largo y se recorre de 40 en 40.
|
||||
*
|
||||
* Las columnas son las que el servidor entrega, no las que el componente
|
||||
* decide: a un gerente de sucursal no le viaja la columna de la plaza ajena
|
||||
* (ADR-017), así que no hay nada que ocultar en el navegador.
|
||||
*/
|
||||
export class BeyondCatalogoMatriz extends Component {
|
||||
static template = "beyond_branch.CatalogoMatriz";
|
||||
static components = { Layout };
|
||||
static props = ["*"];
|
||||
|
||||
setup() {
|
||||
this.orm = useService("orm");
|
||||
this.action = useService("action");
|
||||
this.state = useState({
|
||||
busqueda: "",
|
||||
offset: 0,
|
||||
datos: null,
|
||||
cargando: true,
|
||||
});
|
||||
onWillStart(() => this.cargar());
|
||||
}
|
||||
|
||||
/** Productos por defecto; el mismo componente sirve para servicios. */
|
||||
get tipo() {
|
||||
return this.props.action?.context?.beyond_tipo || "consu";
|
||||
}
|
||||
|
||||
get esServicio() {
|
||||
return this.tipo === "service";
|
||||
}
|
||||
|
||||
get titulo() {
|
||||
return this.esServicio ? _t("Servicios") : _t("Productos");
|
||||
}
|
||||
|
||||
get rango() {
|
||||
const datos = this.state.datos;
|
||||
if (!datos || !datos.mostrados) {
|
||||
return "0";
|
||||
}
|
||||
return `${datos.offset + 1}-${datos.offset + datos.mostrados}`;
|
||||
}
|
||||
|
||||
get hayAnterior() {
|
||||
return this.state.offset > 0;
|
||||
}
|
||||
|
||||
get haySiguiente() {
|
||||
const datos = this.state.datos;
|
||||
return !!datos && datos.offset + datos.mostrados < datos.total;
|
||||
}
|
||||
|
||||
async cargar() {
|
||||
this.state.cargando = true;
|
||||
try {
|
||||
this.state.datos = await this.orm.call(
|
||||
"product.template", "beyond_catalogo_datos",
|
||||
[this.tipo, this.state.busqueda, this.state.offset, POR_PAGINA]);
|
||||
} finally {
|
||||
this.state.cargando = false;
|
||||
}
|
||||
}
|
||||
|
||||
onBuscar(ev) {
|
||||
clearTimeout(this._buscando);
|
||||
this.state.busqueda = ev.target.value;
|
||||
// Vuelve a la primera página: buscar y quedarse en la página 4 de un
|
||||
// resultado de dos páginas deja la pantalla en blanco sin explicación.
|
||||
this.state.offset = 0;
|
||||
this._buscando = setTimeout(() => this.cargar(), ESPERA_BUSQUEDA);
|
||||
}
|
||||
|
||||
async pasar(salto) {
|
||||
this.state.offset = Math.max(0, this.state.offset + salto * POR_PAGINA);
|
||||
await this.cargar();
|
||||
}
|
||||
|
||||
formato(valor, simbolo) {
|
||||
return `${simbolo}${valor.toLocaleString("es-MX", {
|
||||
minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
|
||||
}
|
||||
|
||||
/** Cantidad sin decimales cuando es entera: «7», no «7.00». */
|
||||
cantidad(valor) {
|
||||
return valor.toLocaleString("es-MX", { maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Verde si hay, rojo si no. La existencia negativa es SEÑAL y no error
|
||||
* (ADR-012 §4): dice que se vendió algo que nunca se registró recibido,
|
||||
* así que se pinta como falta, no como avería.
|
||||
*/
|
||||
claseExistencia(existencia) {
|
||||
return existencia > 0 ? "beyond_hay" : "beyond_falta";
|
||||
}
|
||||
|
||||
async abrirFicha(articulo) {
|
||||
const accion = this.esServicio
|
||||
? "beyond_branch.action_beyond_catalogo_servicios"
|
||||
: "beyond_branch.action_beyond_catalogo_productos";
|
||||
await this.action.doAction(accion, {
|
||||
props: { resId: articulo.id },
|
||||
viewType: "form",
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Abre la ficha del catálogo —la conversación de ADR-012—, no un
|
||||
* formulario nativo: la acción de ventana trae atada su vista de
|
||||
* formulario, así que pedirle `viewType: "form"` da la ficha que el
|
||||
* catálogo definió y no la del producto de Odoo.
|
||||
*/
|
||||
async nuevo() {
|
||||
const accion = this.esServicio
|
||||
? "beyond_branch.action_beyond_catalogo_servicios"
|
||||
: "beyond_branch.action_beyond_catalogo_productos";
|
||||
await this.action.doAction(accion, { viewType: "form" });
|
||||
}
|
||||
}
|
||||
|
||||
registry.category("actions").add("beyond_catalogo_matriz", BeyondCatalogoMatriz);
|
||||
@@ -0,0 +1,90 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
<t t-name="beyond_branch.CatalogoMatriz">
|
||||
<Layout className="'o_beyond_catalogo_matriz'" display="{ controlPanel: {} }">
|
||||
<!-- «Nuevo» va en la ranura del panel de control, que es donde el
|
||||
resto del panel lo pone: después del título, nunca antes. -->
|
||||
<t t-set-slot="layout-buttons">
|
||||
<button t-if="state.datos and state.datos.puede_crear" type="button"
|
||||
class="btn beyond_cat_nuevo" t-on-click="nuevo">
|
||||
Nuevo
|
||||
</button>
|
||||
</t>
|
||||
<div class="beyond_cat_eje">
|
||||
<div class="beyond_cat_controles">
|
||||
<div class="beyond_cat_buscador">
|
||||
<i class="fa fa-search"/>
|
||||
<input type="search" placeholder="Buscar por nombre…"
|
||||
t-on-input="onBuscar"/>
|
||||
</div>
|
||||
<div class="beyond_cat_paginador" t-if="state.datos">
|
||||
<span class="beyond_cat_rango">
|
||||
<t t-esc="rango"/> de <t t-esc="state.datos.total"/>
|
||||
</span>
|
||||
<button type="button" class="btn" t-att-disabled="!hayAnterior"
|
||||
aria-label="Página anterior" t-on-click="() => this.pasar(-1)">
|
||||
<i class="fa fa-chevron-left"/>
|
||||
</button>
|
||||
<button type="button" class="btn" t-att-disabled="!haySiguiente"
|
||||
aria-label="Página siguiente" t-on-click="() => this.pasar(1)">
|
||||
<i class="fa fa-chevron-right"/>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="beyond_cat_tarjeta">
|
||||
<t t-if="state.cargando and !state.datos">
|
||||
<p class="beyond_cat_vacio">Cargando…</p>
|
||||
</t>
|
||||
<t t-elif="!state.datos.sucursales.length">
|
||||
<p class="beyond_cat_vacio">
|
||||
No tienes ninguna sucursal asignada, así que no hay
|
||||
columnas que mostrar.
|
||||
</p>
|
||||
</t>
|
||||
<t t-elif="!state.datos.articulos.length">
|
||||
<p class="beyond_cat_vacio">Sin artículos que mostrar.</p>
|
||||
</t>
|
||||
<t t-else="">
|
||||
<div class="beyond_cat_scroll">
|
||||
<table class="beyond_cat_tabla">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="beyond_cat_fija">Artículo</th>
|
||||
<th class="beyond_cat_base">Base de red</th>
|
||||
<t t-foreach="state.datos.sucursales" t-as="sucursal"
|
||||
t-key="sucursal.id">
|
||||
<th t-esc="sucursal.nombre"/>
|
||||
</t>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<t t-foreach="state.datos.articulos" t-as="articulo"
|
||||
t-key="articulo.id">
|
||||
<tr t-on-click="() => this.abrirFicha(articulo)">
|
||||
<td class="beyond_cat_fija" t-esc="articulo.nombre"/>
|
||||
<td class="beyond_cat_base"
|
||||
t-esc="formato(articulo.base, state.datos.simbolo)"/>
|
||||
<t t-foreach="articulo.celdas" t-as="celda"
|
||||
t-key="celda.branch_id">
|
||||
<td class="beyond_cat_celda">
|
||||
<span class="beyond_cat_precio"
|
||||
t-att-class="{'beyond_heredado': !celda.propio}"
|
||||
t-esc="formato(celda.precio, state.datos.simbolo)"/>
|
||||
<span t-if="celda.existencia !== null"
|
||||
class="beyond_cat_pildora"
|
||||
t-att-class="claseExistencia(celda.existencia)"
|
||||
t-esc="cantidad(celda.existencia)"/>
|
||||
</td>
|
||||
</t>
|
||||
</tr>
|
||||
</t>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</Layout>
|
||||
</t>
|
||||
</templates>
|
||||
@@ -0,0 +1,36 @@
|
||||
/** Part of Beyond. Collina Systems proprietary module. */
|
||||
import { Component } from "@odoo/owl";
|
||||
import { registry } from "@web/core/registry";
|
||||
import { standardFieldProps } from "@web/views/fields/standard_field_props";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
|
||||
/**
|
||||
* Dónde se ofrece un artículo: chips de las sucursales, o «Toda la red».
|
||||
*
|
||||
* La lista vacía significa «en todas» (ADR-009), y el widget nativo de
|
||||
* etiquetas la dibuja como una celda en blanco, que se lee como algo que
|
||||
* alguien olvidó llenar. Es el mismo problema que resolvió
|
||||
* `beyond_al_guardar` en Sucursales: un campo vacío no comunica una decisión.
|
||||
*
|
||||
* De solo lectura a propósito: dónde se ofrece un artículo se decide en la
|
||||
* ficha, con la pregunta 1 y su radio, no tecleando en un renglón de lista.
|
||||
*/
|
||||
export class BeyondChipsRed extends Component {
|
||||
static template = "beyond_branch.ChipsRed";
|
||||
static props = { ...standardFieldProps };
|
||||
|
||||
get sucursales() {
|
||||
const dato = this.props.record.data[this.props.name];
|
||||
return dato ? dato.records.map((r) => r.data.display_name) : [];
|
||||
}
|
||||
|
||||
get leyenda() {
|
||||
return _t("Toda la red");
|
||||
}
|
||||
}
|
||||
|
||||
registry.category("fields").add("beyond_chips_red", {
|
||||
component: BeyondChipsRed,
|
||||
displayName: _t("Sucursales o toda la red"),
|
||||
supportedTypes: ["many2many"],
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
/** Part of Beyond. Collina Systems proprietary module. */
|
||||
import { Component, onWillStart, useState } from "@odoo/owl";
|
||||
import { registry } from "@web/core/registry";
|
||||
import { standardFieldProps } from "@web/views/fields/standard_field_props";
|
||||
import { useService } from "@web/core/utils/hooks";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
|
||||
/**
|
||||
* Existencias iniciales, una tarjeta por sucursal.
|
||||
*
|
||||
* Solo aparece al CREAR: lo que se captura aquí es «con cuánto arranca», y al
|
||||
* guardar se convierte en un ajuste de inventario en el almacén de cada
|
||||
* plaza. Después el stock entra por Inventario y por Captura (ADR-012 §7), no
|
||||
* por la ficha: si la ficha siguiera sembrando al editar, corregir un nombre
|
||||
* volvería a fijar la existencia.
|
||||
*
|
||||
* Quién ve qué tarjeta lo decide el servidor, igual que en los precios.
|
||||
*/
|
||||
export class BeyondExistenciasInline extends Component {
|
||||
static template = "beyond_branch.ExistenciasInline";
|
||||
static props = { ...standardFieldProps };
|
||||
|
||||
setup() {
|
||||
this.orm = useService("orm");
|
||||
this.state = useState({ sucursales: [] });
|
||||
onWillStart(() => this.cargar());
|
||||
}
|
||||
|
||||
get capturado() {
|
||||
return this.props.record.data[this.props.name] || {};
|
||||
}
|
||||
|
||||
async cargar() {
|
||||
const datos = await this.orm.call(
|
||||
"product.template", "beyond_ficha_precios", [false]);
|
||||
this.state.sucursales = datos.sucursales;
|
||||
}
|
||||
|
||||
valorDe(sucursal) {
|
||||
const valor = this.capturado[String(sucursal.id)];
|
||||
return valor === undefined ? "" : valor;
|
||||
}
|
||||
|
||||
async onCantidad(sucursal, ev) {
|
||||
const bruto = ev.target.value.trim().replace(",", ".");
|
||||
const capturado = { ...this.capturado };
|
||||
if (bruto === "") {
|
||||
delete capturado[String(sucursal.id)];
|
||||
} else {
|
||||
const valor = Number.parseFloat(bruto);
|
||||
if (Number.isNaN(valor)) {
|
||||
ev.target.value = this.valorDe(sucursal);
|
||||
return;
|
||||
}
|
||||
capturado[String(sucursal.id)] = valor;
|
||||
}
|
||||
await this.props.record.update({ [this.props.name]: capturado });
|
||||
}
|
||||
}
|
||||
|
||||
registry.category("fields").add("beyond_existencias_inline", {
|
||||
component: BeyondExistenciasInline,
|
||||
displayName: _t("Existencias iniciales"),
|
||||
supportedTypes: ["json"],
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
<t t-name="beyond_branch.PreciosInline">
|
||||
<div class="beyond_inline_tarjetas">
|
||||
<t t-foreach="state.sucursales" t-as="sucursal" t-key="sucursal.id">
|
||||
<div class="beyond_inline_tarjeta"
|
||||
t-att-class="{'beyond_guardada': state.guardadas[sucursal.id],
|
||||
'beyond_bloqueada': !sucursal.editable}">
|
||||
<span class="beyond_inline_plaza">
|
||||
<t t-esc="sucursal.nombre"/>
|
||||
<i t-if="!sucursal.editable" class="fa fa-lock ms-1"
|
||||
title="Solo la dirección o su gerente capturan esta sucursal"/>
|
||||
</span>
|
||||
<input t-if="sucursal.editable" type="text"
|
||||
class="beyond_inline_precio"
|
||||
t-att-class="{'beyond_heredado': esHeredado(sucursal)}"
|
||||
t-att-value="valorDe(sucursal)"
|
||||
t-on-change="(ev) => this.onGuardar(sucursal, ev)"/>
|
||||
<span t-else="" class="beyond_inline_precio beyond_heredado"
|
||||
t-esc="valorDe(sucursal)"/>
|
||||
<span class="beyond_inline_nota">
|
||||
<t t-if="esHeredado(sucursal)">hereda el precio base</t>
|
||||
<t t-else="">precio propio</t>
|
||||
</span>
|
||||
<i t-if="state.guardadas[sucursal.id]"
|
||||
class="fa fa-check beyond_inline_marca"/>
|
||||
</div>
|
||||
</t>
|
||||
</div>
|
||||
</t>
|
||||
|
||||
<t t-name="beyond_branch.ExistenciasInline">
|
||||
<div class="beyond_inline_tarjetas">
|
||||
<t t-foreach="state.sucursales" t-as="sucursal" t-key="sucursal.id">
|
||||
<div class="beyond_inline_tarjeta"
|
||||
t-att-class="{'beyond_bloqueada': !sucursal.editable}">
|
||||
<span class="beyond_inline_plaza" t-esc="sucursal.nombre"/>
|
||||
<input t-if="sucursal.editable" type="text" inputmode="decimal"
|
||||
class="beyond_inline_precio" placeholder="0"
|
||||
t-att-value="valorDe(sucursal)"
|
||||
t-on-change="(ev) => this.onCantidad(sucursal, ev)"/>
|
||||
<span t-else="" class="beyond_inline_precio beyond_heredado">—</span>
|
||||
<span class="beyond_inline_nota">con cuánto arranca</span>
|
||||
</div>
|
||||
</t>
|
||||
</div>
|
||||
</t>
|
||||
|
||||
<t t-name="beyond_branch.ChipsRed">
|
||||
<div class="beyond_chips_red">
|
||||
<t t-if="sucursales.length">
|
||||
<t t-foreach="sucursales" t-as="nombre" t-key="nombre">
|
||||
<span class="beyond_chip_red" t-esc="nombre"/>
|
||||
</t>
|
||||
</t>
|
||||
<span t-else="" class="beyond_chip_toda_la_red" t-esc="leyenda"/>
|
||||
</div>
|
||||
</t>
|
||||
</templates>
|
||||
Loaded 100 of 233 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user