diff --git a/addons/beyond_branch/__manifest__.py b/addons/beyond_branch/__manifest__.py index b71effd..103f7e0 100644 --- a/addons/beyond_branch/__manifest__.py +++ b/addons/beyond_branch/__manifest__.py @@ -27,6 +27,7 @@ Fase 1 — Arquitectura base (BRIEF §5.3 y §4): 'data/pricelist_feature.xml', 'views/beyond_branch_views.xml', 'views/res_users_views.xml', + 'views/product_views.xml', 'data/backfill.xml', ], 'demo': [ diff --git a/addons/beyond_branch/models/product_models.py b/addons/beyond_branch/models/product_models.py index e4d5663..b015427 100644 --- a/addons/beyond_branch/models/product_models.py +++ b/addons/beyond_branch/models/product_models.py @@ -1,5 +1,7 @@ # Part of Beyond. Collina Systems proprietary module. -from odoo import fields, models +from odoo import _, api, fields, models +from odoo.exceptions import UserError +from odoo.fields import Domain class ProductPricelist(models.Model): @@ -16,3 +18,88 @@ class ProductPricelist(models.Model): branch_id = fields.Many2one( 'beyond.branch', string='Sucursal', readonly=True, copy=False, index=True, ondelete='set null') + + +class ProductTemplate(models.Model): + """Per-branch availability over a single, global catalogue (ADR-009). + + The catalogue is never duplicated: a product exists once for the whole + network and this field says where it is offered. It lives on the template + rather than on a services model on purpose — today only services need it, + but nothing rules out a product exclusive to one plaza. + """ + _inherit = 'product.template' + + branch_ids = fields.Many2many( + 'beyond.branch', 'product_template_beyond_branch_rel', + 'product_tmpl_id', 'branch_id', string='Disponible en', + help='Sucursales donde se ofrece. Vacío = disponible en toda la red.') + + @api.model + def _beyond_branch_domain(self, config): + """Availability filter for one point of sale. Empty branch_ids means + the whole network, so it must survive the filter.""" + branch = config.branch_id + if not branch: + return [] + return ['|', ('branch_ids', '=', False), ('branch_ids', 'in', branch.ids)] + + @api.model + def _load_pos_data_domain(self, data, config): + """What each POS loads into its catalogue, cut on the server.""" + return super()._load_pos_data_domain(data, config) + \ + self._beyond_branch_domain(config) + + @api.model + def load_product_from_pos(self, config_id, domain, offset=0, limit=0): + """The "search more" path builds its domain in the browser, so the + same cut has to be applied here too or a cashier could reach a + product their branch does not offer.""" + extra = self._beyond_branch_domain(self.env['pos.config'].browse(config_id)) + if extra: + domain = Domain(domain) & Domain(extra) + return super().load_product_from_pos(config_id, domain, offset, limit) + + @api.model + def beyond_create_service(self, name, branch_ids=None, list_price=0.0, + branch_prices=None): + """Engine behind the service-creation UI that comes later (ADR-009). + + :param name: service name. + :param branch_ids: branches where it is offered; empty = whole network. + :param list_price: network base price. + :param branch_prices: {branch_id: price} for the branches that charge + something else; written as items of that branch's own list. + :return: the created product.template. + """ + branch_ids = list(branch_ids or []) + branch_prices = {int(k): v for k, v in (branch_prices or {}).items()} + if branch_ids: + fuera = set(branch_prices) - set(branch_ids) + if fuera: + nombres = self.env['beyond.branch'].browse(sorted(fuera)).mapped('name') + raise UserError(_( + 'No puedes fijar un precio en una sucursal donde el ' + 'servicio no se ofrece: %s', ', '.join(nombres))) + template = self.create({ + 'name': name, + 'type': 'service', + 'list_price': list_price, + 'sale_ok': True, + 'available_in_pos': True, + 'branch_ids': [(6, 0, branch_ids)], + }) + for branch_id, price in branch_prices.items(): + branch = self.env['beyond.branch'].browse(branch_id) + if not branch.pricelist_id: + raise UserError(_( + 'La sucursal %s no tiene lista de precios; corre el ' + 'aprovisionador antes de fijarle precios.', branch.name)) + self.env['product.pricelist.item'].create({ + 'pricelist_id': branch.pricelist_id.id, + 'applied_on': '1_product', + 'product_tmpl_id': template.id, + 'compute_price': 'fixed', + 'fixed_price': price, + }) + return template diff --git a/addons/beyond_branch/tests/__init__.py b/addons/beyond_branch/tests/__init__.py index 5db0891..b79c12d 100644 --- a/addons/beyond_branch/tests/__init__.py +++ b/addons/beyond_branch/tests/__init__.py @@ -1,3 +1,4 @@ from . import test_isolation from . import test_provisioner from . import test_pricelist +from . import test_disponibilidad diff --git a/addons/beyond_branch/tests/test_disponibilidad.py b/addons/beyond_branch/tests/test_disponibilidad.py new file mode 100644 index 0000000..81869d2 --- /dev/null +++ b/addons/beyond_branch/tests/test_disponibilidad.py @@ -0,0 +1,121 @@ +# Part of Beyond. Collina Systems proprietary module. +from odoo.exceptions import UserError +from odoo.tests import TransactionCase, tagged + + +@tagged('post_install', '-at_install') +class TestBeyondDisponibilidad(TransactionCase): + """ADR-009: catálogo global, disponibilidad por sucursal. Vacío = red.""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.Branch = cls.env['beyond.branch'] + cls.puebla = cls.Branch.create({'name': 'Sucursal Puebla Disp'}) + cls.cdmx = cls.Branch.create({'name': 'Sucursal CDMX Disp'}) + cls.Template = cls.env['product.template'] + # load_product_from_pos (el "buscar más" del POS) lee la sesión en + # curso para resolver las listas de precios; sin sesión no corre. + for branch in (cls.puebla, cls.cdmx): + cls.env['pos.session'].create({ + 'config_id': branch.pos_config_id.id, + 'user_id': cls.env.user.id, + }) + + def _cargados(self, branch): + """Los product.template que el POS de esa sucursal cargaría.""" + config = branch.pos_config_id + dominio = self.Template._load_pos_data_domain({}, config) + return self.Template.search(dominio) + + def test_sin_sucursales_es_toda_la_red(self): + producto = self.Template.create({ + 'name': 'Shampoo de Red', 'available_in_pos': True}) + self.assertFalse(producto.branch_ids) + self.assertIn(producto, self._cargados(self.puebla)) + self.assertIn(producto, self._cargados(self.cdmx)) + + def test_servicio_de_una_sola_sucursal(self): + servicio = self.Template.create({ + 'name': 'Corte Exclusivo Puebla', 'type': 'service', + 'available_in_pos': True, 'branch_ids': [(6, 0, self.puebla.ids)]}) + self.assertIn(servicio, self._cargados(self.puebla)) + self.assertNotIn(servicio, self._cargados(self.cdmx), + 'CDMX no ofrece este servicio y no debe cargarlo') + + def test_el_corte_es_del_servidor_tambien_al_buscar_mas(self): + """El buscador del POS arma su dominio en el navegador; el filtro + tiene que aplicarse igual del lado del servidor.""" + servicio = self.Template.create({ + 'name': 'Tinte Exclusivo Puebla', 'type': 'service', + 'available_in_pos': True, 'branch_ids': [(6, 0, self.puebla.ids)]}) + dominio_del_cliente = [('name', 'ilike', 'Tinte Exclusivo')] + encontrados_cdmx = self.Template.load_product_from_pos( + self.cdmx.pos_config_id.id, dominio_del_cliente) + ids_cdmx = [p['id'] for p in encontrados_cdmx['product.template']] + self.assertNotIn(servicio.id, ids_cdmx) + encontrados_puebla = self.Template.load_product_from_pos( + self.puebla.pos_config_id.id, dominio_del_cliente) + ids_puebla = [p['id'] for p in encontrados_puebla['product.template']] + self.assertIn(servicio.id, ids_puebla) + + def test_catalogo_sigue_siendo_uno_solo(self): + """La disponibilidad no duplica el producto: es el mismo registro + para toda la red.""" + servicio = self.Template.create({ + 'name': 'Servicio Unico', 'type': 'service', + 'branch_ids': [(6, 0, self.puebla.ids)]}) + self.assertEqual( + self.Template.search_count([('name', '=', 'Servicio Unico')]), 1) + servicio.branch_ids = [(4, self.cdmx.id)] + self.assertEqual( + self.Template.search_count([('name', '=', 'Servicio Unico')]), 1) + + +@tagged('post_install', '-at_install') +class TestBeyondAltaDeServicio(TransactionCase): + """Motor de alta de servicio, listo para la UI que viene después.""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.Branch = cls.env['beyond.branch'] + cls.puebla = cls.Branch.create({'name': 'Sucursal Puebla Alta'}) + cls.cdmx = cls.Branch.create({'name': 'Sucursal CDMX Alta'}) + cls.Template = cls.env['product.template'] + + def test_alta_completa_con_precios_por_sucursal(self): + servicio = self.Template.beyond_create_service( + 'Manicure Premium', + branch_ids=[self.puebla.id, self.cdmx.id], + list_price=350.0, + branch_prices={self.cdmx.id: 420.0}, + ) + self.assertEqual(servicio.type, 'service') + self.assertTrue(servicio.available_in_pos, 'debe poder venderse en el POS') + self.assertEqual(set(servicio.branch_ids.ids), + {self.puebla.id, self.cdmx.id}) + variante = servicio.product_variant_id + self.assertAlmostEqual( + self.puebla.pricelist_id._get_product_price(variante, 1.0), 350.0, + msg='Puebla se queda en el precio base de red') + self.assertAlmostEqual( + self.cdmx.pricelist_id._get_product_price(variante, 1.0), 420.0) + + def test_alta_sin_sucursales_es_toda_la_red(self): + servicio = self.Template.beyond_create_service( + 'Peinado Estándar', list_price=200.0) + self.assertFalse(servicio.branch_ids) + variante = servicio.product_variant_id + for branch in (self.puebla, self.cdmx): + self.assertAlmostEqual( + branch.pricelist_id._get_product_price(variante, 1.0), 200.0) + + def test_precio_en_sucursal_donde_no_se_ofrece_rebota(self): + with self.assertRaises(UserError): + self.Template.beyond_create_service( + 'Servicio Mal Configurado', + branch_ids=[self.puebla.id], + list_price=100.0, + branch_prices={self.cdmx.id: 150.0}, + ) diff --git a/addons/beyond_branch/views/product_views.xml b/addons/beyond_branch/views/product_views.xml new file mode 100644 index 0000000..d8609a1 --- /dev/null +++ b/addons/beyond_branch/views/product_views.xml @@ -0,0 +1,18 @@ + + + + + product.template.form.beyond.branch + product.template + + + + + + + +