diff --git a/addons/beyond_inventory/models/beyond_pantalla.py b/addons/beyond_inventory/models/beyond_pantalla.py index bbacc1c..b043147 100644 --- a/addons/beyond_inventory/models/beyond_pantalla.py +++ b/addons/beyond_inventory/models/beyond_pantalla.py @@ -31,6 +31,7 @@ GRUPO_DIRECTOR = 'beyond_base.beyond_group_admin_general' class BeyondInventarioPantalla(models.AbstractModel): _name = 'beyond.inventario' + _inherit = ['beyond.descarga'] _description = 'Datos de las pantallas de inventario' # ── Alcance ───────────────────────────────────────────────────────── @@ -298,6 +299,110 @@ class BeyondInventarioPantalla(models.AbstractModel): return {'sin_cambio': True} return {'sin_cambio': False, 'quedo': movimiento.resultante} + + # ── 5 · Agotados del mes ──────────────────────────────────────────── + # Distinto de las alertas: la alerta dice qué está bajo HOY; esto dice + # qué se agotó DURANTE el periodo, aunque ya esté repuesto — que es lo + # que revela un problema de abasto recurrente. + + @api.model + def _beyond_mes_limites(self, mes): + """'2026-09' → (primer instante, último instante) del mes.""" + try: + desde = fields.Datetime.to_datetime(f'{mes}-01 00:00:00') + except (TypeError, ValueError): + raise UserError(_('El mes no se entiende: se espera AAAA-MM.')) + if desde.month == 12: + tope = desde.replace(year=desde.year + 1, month=1) + else: + tope = desde.replace(month=desde.month + 1) + return desde, tope + + @api.model + def beyond_agotados(self, mes, branch_id=None): + """Qué se agotó durante el mes en la plaza: la PRIMERA salida que + dejó cada artículo en cero o menos, y si hoy ya está repuesto. + + Se lee del libro con el usuario real: el alcance lo ponen las + ir.rule de los movimientos, y la sucursal la valida + `_beyond_sucursal` — pedir una ajena es un error, no un vacío. + """ + sucursal = self._beyond_sucursal(branch_id) + desde, tope = self._beyond_mes_limites(mes) + quiebres = self.env['beyond.movimiento'].search([ + ('branch_id', '=', sucursal.id), + ('fecha', '>=', desde), ('fecha', '<', tope), + ('cantidad', '<', 0), ('resultante', '<=', 0), + ], order='fecha asc, id asc') + + Existencia = self.env['beyond.existencia'] + filas, vistos = [], set() + for movimiento in quiebres: + articulo = movimiento.product_tmpl_id + if articulo.id in vistos: + continue # el PRIMER quiebre del mes; los demás son eco + vistos.add(articulo.id) + hoy = Existencia.beyond_cantidad_de(articulo, sucursal) + filas.append({ + 'id': articulo.id, + 'nombre': articulo.name, + 'fecha': fields.Datetime.to_string(movimiento.fecha), + 'quedo': movimiento.resultante, + 'hoy': hoy, + 'repuesto': hoy > 0, + }) + filas.sort(key=lambda f: f['fecha']) + return {'sucursal': {'id': sucursal.id, 'nombre': sucursal.name}, + 'mes': mes, 'filas': filas, + 'sucursales': [{'id': b.id, 'nombre': b.name} + for b in self._beyond_sucursales_elegibles()]} + + @api.model + def beyond_agotados_descarga(self, mes, formato, branch_id=None): + """El archivo dice lo mismo que la pantalla: se vuelve a pedir al + servidor, no se recibe del navegador (mismo criterio que el + histórico del punto de venta).""" + if formato not in ('xlsx', 'pdf'): + raise UserError(_('Formato de descarga no reconocido.')) + datos = self.beyond_agotados(mes, branch_id) + contexto = { + 'encabezado': { + 'titulo': _('Beyond · Inventario agotado'), + 'datos': [(_('Mes'), datos['mes']), + (_('Sucursal'), datos['sucursal']['nombre'])], + 'generado': self._beyond_generado(), + 'iva': _('Reporte de existencias: no contiene montos.'), + }, + 'cifras': [ + {'etiqueta': _('Artículos que se agotaron'), + 'texto': str(len(datos['filas'])), + 'valor': len(datos['filas']), 'formato': 'entero'}, + {'etiqueta': _('Siguen sin existencia'), + 'texto': str(sum(1 for f in datos['filas'] if not f['repuesto'])), + 'valor': sum(1 for f in datos['filas'] if not f['repuesto']), + 'formato': 'entero'}, + ], + 'bloques': [{ + 'titulo': _('Se agotaron durante %s', datos['mes']), + 'columnas': [ + {'etiqueta': _('Artículo'), 'formato': 'texto'}, + {'etiqueta': _('Cuándo se agotó'), 'formato': 'texto'}, + {'etiqueta': _('Quedó en'), 'formato': 'decimal'}, + {'etiqueta': _('Existencia hoy'), 'formato': 'decimal'}, + {'etiqueta': _('¿Repuesto?'), 'formato': 'texto'}, + ], + 'filas': [[f['nombre'], f['fecha'], f['quedo'], f['hoy'], + _('Sí') if f['repuesto'] else _('No')] + for f in datos['filas']], + 'grafica': None, + }], + } + return self._beyond_archivo( + contexto, formato, + self._beyond_nombre_archivo( + ['Beyond', 'Agotados', datos['sucursal']['nombre'], + datos['mes']], formato)) + # ── 4 · Historial ─────────────────────────────────────────────────── @api.model diff --git a/addons/beyond_inventory/static/src/inventario/inventario.js b/addons/beyond_inventory/static/src/inventario/inventario.js index ecd09fe..aeddfd6 100644 --- a/addons/beyond_inventory/static/src/inventario/inventario.js +++ b/addons/beyond_inventory/static/src/inventario/inventario.js @@ -45,6 +45,10 @@ export class BeyondInventario extends Component { hayMas: false, // el buscador topó y hay que acotar // ajuste ajuste: null, + // agotados del mes + agotados: null, + mesAgotados: new Date().toISOString().slice(0, 7), + descargando: false, // historial historial: null, historialFiltros: { dias: 30, tipo: "todo", motivo: "todo" }, @@ -117,6 +121,52 @@ export class BeyondInventario extends Component { await this.cargar(); } + async abrirAgotados() { + this.state.pantalla = "agotados"; + await this.cargarAgotados(); + } + + async cargarAgotados() { + this.state.agotados = await this.orm.call( + "beyond.inventario", "beyond_agotados", + [this.state.mesAgotados, this.state.filtros.branch_id]); + } + + async cambiarMesAgotados(ev) { + this.state.mesAgotados = ev.target.value; + await this.cargarAgotados(); + } + + async descargarAgotados(formato) { + if (this.state.descargando) { + return; + } + this.state.descargando = true; + try { + const archivo = await this.orm.call( + "beyond.inventario", "beyond_agotados_descarga", + [this.state.mesAgotados, formato, this.state.filtros.branch_id]); + // El archivo llega en base64 por ORM; el navegador lo guarda + // (mismo camino que el tablero y el histórico del POS). + const binario = atob(archivo.contenido); + const bytes = new Uint8Array(binario.length); + for (let i = 0; i < binario.length; i++) { + bytes[i] = binario.charCodeAt(i); + } + const url = URL.createObjectURL( + new Blob([bytes], { type: archivo.mime })); + const enlace = document.createElement("a"); + enlace.href = url; + enlace.download = archivo.nombre; + document.body.appendChild(enlace); + enlace.click(); + enlace.remove(); + URL.revokeObjectURL(url); + } finally { + this.state.descargando = false; + } + } + async abrirRecepcion() { this.state.recibiendo = []; this.state.nota = ""; diff --git a/addons/beyond_inventory/static/src/inventario/inventario.scss b/addons/beyond_inventory/static/src/inventario/inventario.scss index 3687434..3eb2870 100644 --- a/addons/beyond_inventory/static/src/inventario/inventario.scss +++ b/addons/beyond_inventory/static/src/inventario/inventario.scss @@ -1094,3 +1094,25 @@ body.beyond_panel_azul { &:hover { background: $beyond-panel-azul-inventario-hover; } } } + + .beyond_inventario_agotados_btn { + border: 1px solid $inv-linea; + border-radius: 10px; + padding: 10px 14px; + background: #fff; + i { margin-right: 6px; } + } + .beyond_agotados_mes { + border: 1px solid $inv-linea; + border-radius: 8px; + padding: 8px 10px; + } + .beyond_agotados_relleno { flex: 1; } + .beyond_agotados_descarga { border: 1px solid $inv-linea; } + .beyond_agotados_eje, + .beyond_agotados_fila { + display: grid; + grid-template-columns: 1.6fr 1fr 0.6fr 0.6fr 0.7fr; + gap: 12px; + align-items: center; + } diff --git a/addons/beyond_inventory/static/src/inventario/inventario.xml b/addons/beyond_inventory/static/src/inventario/inventario.xml index 7fe93b2..3b09cb8 100644 --- a/addons/beyond_inventory/static/src/inventario/inventario.xml +++ b/addons/beyond_inventory/static/src/inventario/inventario.xml @@ -72,6 +72,10 @@ t-on-click="abrirRecepcion"> Recibir mercancía +
@@ -139,6 +143,61 @@
+ + +
+ + Agotados del mes + + + + +
+
Cargando…
+
+ + Nada se agotó en este mes + Ningún artículo de + tocó cero durante . +
+
+
+ Artículo + Cuándo se agotó + Quedó en + Hoy + ¿Repuesto? +
+ +
+ + + + + +
+
+
+
+ diff --git a/addons/beyond_inventory/tests/__init__.py b/addons/beyond_inventory/tests/__init__.py index 7c4f6ac..2a5666b 100644 --- a/addons/beyond_inventory/tests/__init__.py +++ b/addons/beyond_inventory/tests/__init__.py @@ -3,3 +3,4 @@ from . import test_pos_descuento from . import test_pantallas from . import test_inventario_navegador from . import test_costo +from . import test_agotados diff --git a/addons/beyond_inventory/tests/test_agotados.py b/addons/beyond_inventory/tests/test_agotados.py new file mode 100644 index 0000000..e0e3c14 --- /dev/null +++ b/addons/beyond_inventory/tests/test_agotados.py @@ -0,0 +1,112 @@ +# Part of Beyond. Collina Systems proprietary module. +"""Agotados del mes: qué tocó cero DURANTE el periodo, aunque hoy esté +repuesto. Distinto de las alertas, que dicen qué está bajo hoy.""" +import base64 +import io + +import openpyxl + +from odoo.exceptions import AccessError, UserError +from odoo.tests import tagged + +from odoo.addons.beyond_branch.tests.common import BeyondBranchCase + + +@tagged('post_install', '-at_install') +class TestBeyondAgotados(BeyondBranchCase): + + def setUp(self): + super().setUp() + # La pantalla exige un usuario con plaza (o dirección): + # el runner no tiene ninguna, y _beyond_sucursal lo corta. + self.Pantalla = self.env['beyond.inventario'].with_user(self.admin_general) + self.Movimiento = self.env['beyond.movimiento'] + self.tinte = self.env['product.template'].create({ + 'name': 'ZZ tinte agotable', 'type': 'consu', 'sale_ok': True}) + self.spray = self.env['product.template'].create({ + 'name': 'ZZ spray sano', 'type': 'consu', 'sale_ok': True}) + + def _mover(self, producto, cantidad, fecha, branch=None): + if cantidad > 0: + return self.Movimiento.beyond_entrada( + producto, branch or self.branch_a, cantidad, fecha=fecha) + movimiento = self.Movimiento.with_context( + ).create({'product_tmpl_id': producto.id, + 'branch_id': (branch or self.branch_a).id, + 'tipo': 'venta', 'cantidad': cantidad, 'fecha': fecha}) + return movimiento + + def test_el_agotado_del_mes_aparece_aunque_ya_este_repuesto(self): + """El caso que las alertas no ven: se agotó el día 10, se repuso el + 20, y hoy la alerta no dice nada — el reporte sí.""" + self._mover(self.tinte, 5, '2026-09-01 10:00:00') + self._mover(self.tinte, -5, '2026-09-10 12:00:00') # toca cero + self._mover(self.tinte, 8, '2026-09-20 10:00:00') # repuesto + datos = self.Pantalla.beyond_agotados('2026-09', self.branch_a.id) + filas = [f for f in datos['filas'] if f['id'] == self.tinte.id] + self.assertEqual(len(filas), 1) + self.assertEqual(filas[0]['fecha'], '2026-09-10 12:00:00') + self.assertTrue(filas[0]['repuesto']) + self.assertEqual(filas[0]['hoy'], 8.0) + + def test_el_primer_quiebre_manda_y_el_eco_no_duplica(self): + """Cayó a cero, siguió vendiéndose en negativo: un renglón, no tres, + y con la fecha del PRIMER quiebre.""" + self._mover(self.tinte, 2, '2026-09-01 10:00:00') + self._mover(self.tinte, -2, '2026-09-05 10:00:00') + self._mover(self.tinte, -1, '2026-09-06 10:00:00') + self._mover(self.tinte, -1, '2026-09-07 10:00:00') + datos = self.Pantalla.beyond_agotados('2026-09', self.branch_a.id) + filas = [f for f in datos['filas'] if f['id'] == self.tinte.id] + self.assertEqual(len(filas), 1) + self.assertEqual(filas[0]['fecha'], '2026-09-05 10:00:00') + self.assertFalse(filas[0]['repuesto']) + + def test_lo_de_otro_mes_y_lo_sano_quedan_fuera(self): + """Las contrapartes: el quiebre de agosto no es de septiembre, y el + artículo que nunca tocó cero no aparece.""" + self._mover(self.tinte, 3, '2026-08-01 10:00:00') + self._mover(self.tinte, -3, '2026-08-15 10:00:00') # agosto + self._mover(self.spray, 9, '2026-09-01 10:00:00') # nunca cae + datos = self.Pantalla.beyond_agotados('2026-09', self.branch_a.id) + ids = {f['id'] for f in datos['filas']} + self.assertNotIn(self.tinte.id, ids, 'agosto no es septiembre') + self.assertNotIn(self.spray.id, ids, 'lo sano no aparece') + agosto = self.Pantalla.beyond_agotados('2026-08', self.branch_a.id) + self.assertIn(self.tinte.id, {f['id'] for f in agosto['filas']}) + + def test_la_plaza_ajena_es_un_error_no_un_vacio(self): + with self.assertRaises(AccessError): + self.Pantalla.with_user(self.admin_a).beyond_agotados( + '2026-09', self.branch_b.id) + + def test_el_mes_malformado_se_rechaza(self): + with self.assertRaises(UserError): + self.Pantalla.beyond_agotados('septiembre', self.branch_a.id) + + def test_el_excel_dice_lo_mismo_que_la_pantalla(self): + """La regla de red del reporte: el archivo se abre y sus filas se + cotejan contra los datos de pantalla — no contra lo que el test + cree que debería decir.""" + self._mover(self.tinte, 5, '2026-09-01 10:00:00') + self._mover(self.tinte, -5, '2026-09-10 12:00:00') + pantalla = self.Pantalla.beyond_agotados('2026-09', self.branch_a.id) + archivo = self.Pantalla.beyond_agotados_descarga( + '2026-09', 'xlsx', self.branch_a.id) + self.assertTrue(archivo['nombre'].startswith('Beyond_Agotados_')) + libro = openpyxl.load_workbook( + io.BytesIO(base64.b64decode(archivo['contenido']))) + hoja = libro[libro.sheetnames[-1]] + celdas = [[c.value for c in fila] for fila in hoja.iter_rows()] + nombres = [f[0] for f in celdas if f and f[0]] + for fila in pantalla['filas']: + self.assertIn(fila['nombre'], nombres, + 'cada renglón de la pantalla está en el archivo') + + def test_el_pdf_sale_y_es_pdf(self): + self._mover(self.tinte, 1, '2026-09-01 10:00:00') + self._mover(self.tinte, -1, '2026-09-02 10:00:00') + archivo = self.Pantalla.beyond_agotados_descarga( + '2026-09', 'pdf', self.branch_a.id) + crudo = base64.b64decode(archivo['contenido']) + self.assertTrue(crudo.startswith(b'%PDF'), 'el contenido es un PDF')