fix(pos): prevent null branch_id errors during sales
- process_sale now falls back to main branch when g.branch_id is missing - Accept branch_id from request body as override - Make update_inventory_stock trigger skip operations with NULL branch_id - Applied updated trigger to all active tenant DBs
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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'):
|
||||
|
||||
Reference in New Issue
Block a user