- 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>
167 lines
6.9 KiB
Python
167 lines
6.9 KiB
Python
# 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',
|
|
}
|