Añade beyond_product_capture: alta de productos escaneo-primero (cierra Fase 1)
- Asistente de 3 niveles (BRIEF §5.2): código existente suma stock al almacén de la sucursal; desconocido consulta Open Beauty Facts y autocompleta; sin resultado, mini-formulario de una sola vez que registra el producto global para toda la red con IVA incluido - Open Beauty Facts del lado servidor con timeout y degradación sin red - Respeta el aislamiento: solo sucursales asignadas (con test); creación de producto vía sudo como única vía sancionada al catálogo maestro - Menú raíz Beyond visible ahora para admin de sucursal (la captura vive ahí) - ADR-003: cámara/UI táctil en Fase 2; OCR diferido al piloto (D5, exige imagen Docker propia con tesseract) - Tests con OBF simulado: 6 casos, sin llamadas de red reales Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
52e23843c4
commit
cfae7ea19a
11 files changed
+447
-2
No files matched your search
@@ -71,10 +71,12 @@
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<!-- Raíz visible desde admin de sucursal (la captura de productos vive
|
||||
aquí); Sucursales y Usuarios siguen siendo de admin general. -->
|
||||
<menuitem id="menu_beyond_root" name="Beyond"
|
||||
web_icon="beyond_base,static/description/icon.png"
|
||||
sequence="5"
|
||||
groups="beyond_base.beyond_group_admin_general,base.group_system"/>
|
||||
groups="beyond_base.beyond_group_admin_sucursal,base.group_system"/>
|
||||
<menuitem id="menu_beyond_branch" name="Sucursales"
|
||||
parent="menu_beyond_root" action="action_beyond_branch"
|
||||
sequence="10"
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
from . import wizards
|
||||
@@ -0,0 +1,30 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
{
|
||||
'name': 'Beyond — Captura de productos',
|
||||
'summary': 'Alta de productos escaneo-primero: catálogo existente → Open Beauty Facts → mini-formulario',
|
||||
'description': """
|
||||
Fase 1 — captura asistida de productos (BRIEF §5.2, módulo contractual 1):
|
||||
|
||||
Flujo escaneo-primero de tres niveles desde un solo asistente:
|
||||
|
||||
1. El código existe en el catálogo: suma stock al almacén de la sucursal.
|
||||
2. No existe: se consulta Open Beauty Facts y se autocompleta nombre, marca e imagen para confirmar en un toque.
|
||||
3. Desconocido: mini-formulario de una sola vez; el producto queda registrado para siempre en el catálogo global (todas las sucursales).
|
||||
|
||||
El lector USB/Bluetooth funciona hoy (teclea el código en el campo). La
|
||||
captura por cámara y la experiencia táctil llegan en Fase 2 con el reskin;
|
||||
el respaldo foto+OCR (D5) se valida en el piloto — ver ADR-003.
|
||||
""",
|
||||
'version': '19.0.1.0.0',
|
||||
'category': 'Beyond',
|
||||
'author': 'Collina Systems',
|
||||
'license': 'Other proprietary',
|
||||
'depends': ['beyond_branch', 'stock', 'barcodes'],
|
||||
'data': [
|
||||
'security/ir.model.access.csv',
|
||||
'views/product_capture_views.xml',
|
||||
],
|
||||
'demo': [],
|
||||
'installable': True,
|
||||
'application': False,
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
|
||||
access_product_capture_admin_sucursal,beyond.product.capture (admin sucursal),model_beyond_product_capture,beyond_base.beyond_group_admin_sucursal,1,1,1,1
|
||||
|
@@ -0,0 +1 @@
|
||||
from . import test_capture
|
||||
@@ -0,0 +1,115 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
from unittest.mock import patch
|
||||
|
||||
from odoo.exceptions import AccessError, ValidationError
|
||||
from odoo.tests import tagged
|
||||
|
||||
from odoo.addons.beyond_branch.tests.common import BeyondBranchCase
|
||||
from odoo.addons.beyond_product_capture.wizards.product_capture import BeyondProductCapture
|
||||
|
||||
|
||||
def _sin_red(self, barcode):
|
||||
return None
|
||||
|
||||
|
||||
def _obf_shampoo(self, barcode):
|
||||
return {
|
||||
'name': 'Shampoo Nutritivo',
|
||||
'brand': 'MarcaBella',
|
||||
'quantity': '750 ml',
|
||||
'image_url': '',
|
||||
}
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestBeyondProductCapture(BeyondBranchCase):
|
||||
"""Flujo escaneo-primero (BRIEF §5.2): existe → suma stock; base abierta
|
||||
→ autocompleta; desconocido → mini-formulario global. Sin llamadas de
|
||||
red reales: Open Beauty Facts se simula."""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
cls.producto_existente = cls.env['product.template'].create({
|
||||
'name': 'Acondicionador Reparador',
|
||||
'barcode': '7501000111111',
|
||||
'type': 'consu',
|
||||
'is_storable': True,
|
||||
'available_in_pos': True,
|
||||
'list_price': 250.0,
|
||||
})
|
||||
|
||||
def _wizard(self, user, **vals):
|
||||
vals.setdefault('branch_id', self.branch_a.id)
|
||||
return self.env['beyond.product.capture'].with_user(user).create(vals)
|
||||
|
||||
def _stock_en(self, producto, branch):
|
||||
return self.env['stock.quant'].sudo()._get_available_quantity(
|
||||
producto.product_variant_id, branch.warehouse_id.lot_stock_id)
|
||||
|
||||
def test_nivel_1_existente_suma_stock(self):
|
||||
wizard = self._wizard(self.admin_a, barcode='7501000111111', quantity=5)
|
||||
wizard.action_scan()
|
||||
self.assertEqual(wizard.state, 'found')
|
||||
self.assertEqual(wizard.product_id, self.producto_existente)
|
||||
wizard.action_add_stock()
|
||||
self.assertEqual(self._stock_en(self.producto_existente, self.branch_a), 5.0)
|
||||
# segunda recepción SUMA, no reemplaza
|
||||
wizard2 = self._wizard(self.admin_a, barcode='7501000111111', quantity=3)
|
||||
wizard2.action_scan()
|
||||
wizard2.action_add_stock()
|
||||
self.assertEqual(self._stock_en(self.producto_existente, self.branch_a), 8.0)
|
||||
|
||||
@patch.object(BeyondProductCapture, '_fetch_open_beauty_facts', _obf_shampoo)
|
||||
def test_nivel_2_base_abierta_autocompleta(self):
|
||||
wizard = self._wizard(self.admin_a, barcode='7509999000001', quantity=2,
|
||||
list_price=320.0)
|
||||
wizard.action_scan()
|
||||
self.assertEqual(wizard.state, 'external')
|
||||
self.assertEqual(wizard.name, 'MarcaBella Shampoo Nutritivo 750 ml')
|
||||
wizard.action_create_product()
|
||||
producto = self.env['product.template'].search([('barcode', '=', '7509999000001')])
|
||||
self.assertTrue(producto, "el producto autocompletado debe crearse")
|
||||
self.assertTrue(producto.available_in_pos)
|
||||
self.assertEqual(self._stock_en(producto, self.branch_a), 2.0)
|
||||
|
||||
@patch.object(BeyondProductCapture, '_fetch_open_beauty_facts', _sin_red)
|
||||
def test_nivel_3_desconocido_mini_formulario_global(self):
|
||||
wizard = self._wizard(self.admin_a, barcode='7509999000002', quantity=1)
|
||||
wizard.action_scan()
|
||||
self.assertEqual(wizard.state, 'new', "sin catálogo ni base abierta → mini-formulario")
|
||||
wizard.write({'name': 'Cera Modeladora Artesanal', 'list_price': 180.0})
|
||||
wizard.action_create_product()
|
||||
producto = self.env['product.template'].search([('barcode', '=', '7509999000002')])
|
||||
self.assertTrue(producto)
|
||||
# registrado para siempre y para toda la red: catálogo global,
|
||||
# visible también para el admin de la otra sucursal
|
||||
visible_b = self.env['product.template'].with_user(self.admin_ab).search(
|
||||
[('barcode', '=', '7509999000002')])
|
||||
self.assertTrue(visible_b, "el catálogo es global (BRIEF §4)")
|
||||
# y con el IVA 16% incluido por defecto
|
||||
self.assertIn(self.env.company.account_sale_tax_id, producto.taxes_id)
|
||||
|
||||
@patch.object(BeyondProductCapture, '_fetch_open_beauty_facts', _sin_red)
|
||||
def test_codigo_repetido_no_duplica(self):
|
||||
wizard = self._wizard(self.admin_a, barcode='7501000111111')
|
||||
wizard.action_scan()
|
||||
self.assertEqual(wizard.state, 'found',
|
||||
"un código ya registrado jamás llega al formulario de alta")
|
||||
wizard.write({'state': 'new', 'name': 'Duplicado forzado'})
|
||||
with self.assertRaises(ValidationError):
|
||||
wizard.action_create_product()
|
||||
|
||||
def test_no_captura_en_sucursal_ajena(self):
|
||||
wizard = self._wizard(self.admin_a, barcode='7501000111111',
|
||||
branch_id=self.branch_b.id, quantity=5)
|
||||
wizard.action_scan()
|
||||
with self.assertRaises(AccessError):
|
||||
wizard.action_add_stock()
|
||||
|
||||
def test_admin_general_captura_en_cualquier_sucursal(self):
|
||||
wizard = self._wizard(self.admin_general, barcode='7501000111111',
|
||||
branch_id=self.branch_b.id, quantity=4)
|
||||
wizard.action_scan()
|
||||
wizard.action_add_stock()
|
||||
self.assertEqual(self._stock_en(self.producto_existente, self.branch_b), 4.0)
|
||||
@@ -0,0 +1,63 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<record id="view_beyond_product_capture_form" model="ir.ui.view">
|
||||
<field name="name">beyond.product.capture.form</field>
|
||||
<field name="model">beyond.product.capture</field>
|
||||
<field name="arch" type="xml">
|
||||
<form string="Captura de productos">
|
||||
<group>
|
||||
<group>
|
||||
<field name="state" invisible="1"/>
|
||||
<field name="barcode" readonly="state != 'start'"
|
||||
placeholder="Escanea o teclea el código…"/>
|
||||
<field name="branch_id" options="{'no_create': True}"/>
|
||||
</group>
|
||||
<group>
|
||||
<field name="product_id" invisible="state != 'found'"/>
|
||||
<field name="quantity" invisible="state == 'start'"/>
|
||||
</group>
|
||||
</group>
|
||||
<group invisible="state not in ('external', 'new')">
|
||||
<group>
|
||||
<field name="name" required="state in ('external', 'new')"/>
|
||||
<field name="brand" invisible="state != 'external'"/>
|
||||
<field name="list_price" widget="monetary"/>
|
||||
</group>
|
||||
<group>
|
||||
<field name="image_1920" widget="image" class="oe_avatar" nolabel="1"/>
|
||||
</group>
|
||||
</group>
|
||||
<div class="alert alert-info" role="status" invisible="state != 'external'">
|
||||
Encontrado en la base abierta: revisa los datos y confirma. Quedará
|
||||
registrado una sola vez para todas las sucursales.
|
||||
</div>
|
||||
<div class="alert alert-warning" role="status" invisible="state != 'new'">
|
||||
Código desconocido: mini-formulario de una sola vez. El producto
|
||||
quedará registrado para siempre en el catálogo global.
|
||||
</div>
|
||||
<footer>
|
||||
<button name="action_scan" type="object" string="Buscar"
|
||||
class="btn-primary" invisible="state != 'start'"/>
|
||||
<button name="action_add_stock" type="object" string="Sumar stock"
|
||||
class="btn-primary" invisible="state != 'found'"/>
|
||||
<button name="action_create_product" type="object" string="Crear producto"
|
||||
class="btn-primary" invisible="state not in ('external', 'new')"/>
|
||||
<button string="Cancelar" special="cancel"/>
|
||||
</footer>
|
||||
</form>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="action_beyond_product_capture" model="ir.actions.act_window">
|
||||
<field name="name">Captura de productos</field>
|
||||
<field name="res_model">beyond.product.capture</field>
|
||||
<field name="view_mode">form</field>
|
||||
<field name="target">new</field>
|
||||
</record>
|
||||
|
||||
<menuitem id="menu_beyond_product_capture" name="Captura de productos"
|
||||
parent="beyond_branch.menu_beyond_root"
|
||||
action="action_beyond_product_capture"
|
||||
sequence="15"
|
||||
groups="beyond_base.beyond_group_admin_sucursal"/>
|
||||
</odoo>
|
||||
@@ -0,0 +1 @@
|
||||
from . import product_capture
|
||||
@@ -0,0 +1,166 @@
|
||||
# Part of Beyond. Collina Systems proprietary module.
|
||||
import base64
|
||||
|
||||
import requests
|
||||
|
||||
from odoo import _, api, fields, models
|
||||
from odoo.exceptions import AccessError, ValidationError
|
||||
|
||||
OBF_URL = 'https://world.openbeautyfacts.org/api/v2/product/{barcode}.json'
|
||||
OBF_TIMEOUT = 5 # segundos; sin red se degrada al mini-formulario
|
||||
|
||||
|
||||
class BeyondProductCapture(models.TransientModel):
|
||||
_name = 'beyond.product.capture'
|
||||
_description = 'Captura de productos escaneo-primero'
|
||||
|
||||
state = fields.Selection(
|
||||
[('start', 'Escanear'),
|
||||
('found', 'En catálogo'),
|
||||
('external', 'Encontrado en base abierta'),
|
||||
('new', 'Producto nuevo')],
|
||||
default='start', required=True)
|
||||
barcode = fields.Char(string='Código de barras')
|
||||
branch_id = fields.Many2one(
|
||||
'beyond.branch', string='Sucursal', required=True,
|
||||
default=lambda self: self.env.user.branch_ids[:1])
|
||||
quantity = fields.Float(string='Cantidad recibida', default=1.0)
|
||||
|
||||
product_id = fields.Many2one('product.template', string='Producto', readonly=True)
|
||||
name = fields.Char(string='Nombre')
|
||||
brand = fields.Char(string='Marca')
|
||||
list_price = fields.Float(string='Precio de venta (IVA incluido)')
|
||||
image_1920 = fields.Image(string='Imagen')
|
||||
|
||||
def _check_branch_allowed(self):
|
||||
self.ensure_one()
|
||||
if self.env.user.has_group('beyond_base.beyond_group_admin_general'):
|
||||
return
|
||||
if self.branch_id not in self.env.user.branch_ids:
|
||||
raise AccessError(_('No puedes capturar inventario en una sucursal que no tienes asignada.'))
|
||||
|
||||
# ── Nivel 2: base abierta ────────────────────────────────────────────
|
||||
@api.model
|
||||
def _fetch_open_beauty_facts(self, barcode):
|
||||
"""Consulta Open Beauty Facts. Regresa dict con name/brand/image_url
|
||||
o None (no encontrado, sin red o error): la captura nunca se bloquea
|
||||
por la red, se degrada al mini-formulario."""
|
||||
try:
|
||||
response = requests.get(OBF_URL.format(barcode=barcode), timeout=OBF_TIMEOUT)
|
||||
data = response.json()
|
||||
except (requests.RequestException, ValueError):
|
||||
return None
|
||||
if data.get('status') != 1:
|
||||
return None
|
||||
product = data.get('product') or {}
|
||||
name = product.get('product_name')
|
||||
if not name:
|
||||
return None
|
||||
return {
|
||||
'name': name,
|
||||
'brand': product.get('brands') or '',
|
||||
'quantity': product.get('quantity') or '',
|
||||
'image_url': product.get('image_front_url') or product.get('image_url') or '',
|
||||
}
|
||||
|
||||
@api.model
|
||||
def _fetch_image(self, url):
|
||||
if not url:
|
||||
return False
|
||||
try:
|
||||
response = requests.get(url, timeout=OBF_TIMEOUT)
|
||||
response.raise_for_status()
|
||||
return base64.b64encode(response.content)
|
||||
except requests.RequestException:
|
||||
return False
|
||||
|
||||
# ── Flujo ────────────────────────────────────────────────────────────
|
||||
def action_scan(self):
|
||||
self.ensure_one()
|
||||
if not self.barcode:
|
||||
raise ValidationError(_('Escanea o captura un código de barras.'))
|
||||
producto = self.env['product.template'].search(
|
||||
[('barcode', '=', self.barcode)], limit=1)
|
||||
if producto:
|
||||
# Nivel 1: existe → sumar stock
|
||||
self.write({'state': 'found', 'product_id': producto.id,
|
||||
'name': producto.name})
|
||||
return self._reopen()
|
||||
externo = self._fetch_open_beauty_facts(self.barcode)
|
||||
if externo:
|
||||
# Nivel 2: autocompletar y confirmar
|
||||
nombre = ' '.join(p for p in (externo['brand'], externo['name'],
|
||||
externo['quantity']) if p)
|
||||
self.write({
|
||||
'state': 'external',
|
||||
'name': nombre,
|
||||
'brand': externo['brand'],
|
||||
'image_1920': self._fetch_image(externo['image_url']),
|
||||
})
|
||||
return self._reopen()
|
||||
# Nivel 3: mini-formulario de una sola vez
|
||||
self.write({'state': 'new'})
|
||||
return self._reopen()
|
||||
|
||||
def action_add_stock(self):
|
||||
"""Nivel 1: suma la cantidad recibida al almacén de la sucursal
|
||||
mediante un ajuste de inventario."""
|
||||
self.ensure_one()
|
||||
self._check_branch_allowed()
|
||||
if self.quantity <= 0:
|
||||
raise ValidationError(_('La cantidad recibida debe ser mayor que cero.'))
|
||||
producto = self.product_id
|
||||
if not producto.is_storable:
|
||||
raise ValidationError(_('%s es un servicio: no lleva inventario.', producto.name))
|
||||
self._sumar_stock(producto, self.branch_id, self.quantity)
|
||||
return {'type': 'ir.actions.act_window_close'}
|
||||
|
||||
def action_create_product(self):
|
||||
"""Niveles 2 y 3: crea el producto GLOBAL (catálogo único para todas
|
||||
las sucursales, BRIEF §4) y, si trae cantidad, suma el stock inicial
|
||||
en la sucursal que captura."""
|
||||
self.ensure_one()
|
||||
self._check_branch_allowed()
|
||||
if not self.name:
|
||||
raise ValidationError(_('El producto necesita un nombre.'))
|
||||
existente = self.env['product.template'].search(
|
||||
[('barcode', '=', self.barcode)], limit=1)
|
||||
if existente:
|
||||
raise ValidationError(_(
|
||||
'El código %(barcode)s ya pertenece a "%(name)s".',
|
||||
barcode=self.barcode, name=existente.name))
|
||||
# sudo: la captura es la vía sancionada para alimentar el catálogo
|
||||
# maestro; el admin de sucursal no necesita permisos de catálogo.
|
||||
producto = self.env['product.template'].sudo().create({
|
||||
'name': self.name,
|
||||
'barcode': self.barcode,
|
||||
'type': 'consu',
|
||||
'is_storable': True,
|
||||
'available_in_pos': True,
|
||||
'list_price': self.list_price,
|
||||
'image_1920': self.image_1920 or False,
|
||||
})
|
||||
if self.quantity > 0:
|
||||
self._sumar_stock(producto, self.branch_id, self.quantity)
|
||||
return {'type': 'ir.actions.act_window_close'}
|
||||
|
||||
def _sumar_stock(self, producto, branch, cantidad):
|
||||
ubicacion = branch.warehouse_id.lot_stock_id
|
||||
variante = producto.product_variant_id
|
||||
Quant = self.env['stock.quant'].sudo()
|
||||
actual = Quant._get_available_quantity(variante, ubicacion)
|
||||
quant = Quant.with_context(inventory_mode=True).create({
|
||||
'product_id': variante.id,
|
||||
'location_id': ubicacion.id,
|
||||
'inventory_quantity': actual + cantidad,
|
||||
})
|
||||
quant.action_apply_inventory()
|
||||
|
||||
def _reopen(self):
|
||||
return {
|
||||
'type': 'ir.actions.act_window',
|
||||
'res_model': self._name,
|
||||
'res_id': self.id,
|
||||
'view_mode': 'form',
|
||||
'target': 'new',
|
||||
}
|
||||
Reference in new issue
Block a user