diff --git a/pos/migrations/v4.0_multi_branch.sql b/pos/migrations/v4.0_multi_branch.sql index fb83f4a..4ea5850 100644 --- a/pos/migrations/v4.0_multi_branch.sql +++ b/pos/migrations/v4.0_multi_branch.sql @@ -230,6 +230,13 @@ ALTER TABLE cfdi_queue ALTER COLUMN sale_id DROP NOT NULL; CREATE OR REPLACE FUNCTION update_inventory_stock() RETURNS TRIGGER AS $$ BEGIN + -- Skip operations that are not tied to a specific branch. + -- Per-branch stock tracking requires a branch_id; without it we can't + -- assign the stock to any location. + IF NEW.branch_id IS NULL THEN + RETURN NEW; + END IF; + INSERT INTO inventory_stock (inventory_id, branch_id, stock) VALUES (NEW.inventory_id, NEW.branch_id, NEW.quantity) ON CONFLICT (inventory_id, branch_id) DO UPDATE diff --git a/pos/services/pos_engine.py b/pos/services/pos_engine.py index 9609791..86a2665 100644 --- a/pos/services/pos_engine.py +++ b/pos/services/pos_engine.py @@ -193,9 +193,23 @@ def process_sale(conn, sale_data): amount_paid = float(sale_data.get('amount_paid', 0)) payment_details = sale_data.get('payment_details', []) notes = sale_data.get('notes') - branch_id = _safe_g('branch_id') + branch_id = sale_data.get('branch_id') or _safe_g('branch_id') employee_id = _safe_g('employee_id') + # Fallback to the main branch if none resolved (e.g. token without branch_id) + if not branch_id: + cur.execute("SELECT id FROM branches WHERE is_main = true AND is_active = true LIMIT 1") + row = cur.fetchone() + if row: + branch_id = row[0] + else: + cur.execute("SELECT id FROM branches WHERE is_active = true ORDER BY id LIMIT 1") + row = cur.fetchone() + branch_id = row[0] if row else None + + if not branch_id: + raise ValueError("No hay sucursal activa disponible para registrar la venta") + # ── Multi-currency support ─────────────────────────────────────────── currency = sale_data.get('currency', 'MXN') if currency not in ('MXN', 'USD'):