-- Make definitions local to outlets -- 1. Suppliers ALTER TABLE suppliers ADD COLUMN IF NOT EXISTS outlet_id INT DEFAULT 1; ALTER TABLE suppliers ADD CONSTRAINT fk_suppliers_outlet FOREIGN KEY (outlet_id) REFERENCES outlets(id) ON DELETE CASCADE; -- 2. Categories ALTER TABLE stock_categories ADD COLUMN IF NOT EXISTS outlet_id INT DEFAULT 1; ALTER TABLE stock_categories ADD CONSTRAINT fk_categories_outlet FOREIGN KEY (outlet_id) REFERENCES outlets(id) ON DELETE CASCADE; -- 3. Units ALTER TABLE stock_units ADD COLUMN IF NOT EXISTS outlet_id INT DEFAULT 1; ALTER TABLE stock_units ADD CONSTRAINT fk_units_outlet FOREIGN KEY (outlet_id) REFERENCES outlets(id) ON DELETE CASCADE; -- 4. Items ALTER TABLE stock_items ADD COLUMN IF NOT EXISTS outlet_id INT DEFAULT 1; ALTER TABLE stock_items ADD CONSTRAINT fk_items_outlet FOREIGN KEY (outlet_id) REFERENCES outlets(id) ON DELETE CASCADE; -- 5. Fix SKU Unique Constraint (Global -> Local) -- First, drop the global unique index if it exists. -- We need to know the name. Usually 'sku'. We'll try to drop it. -- MySQL might fail if index doesn't exist, so we use a procedure or just try/catch in PHP? -- For SQL file, we can't easily do try/catch. -- We'll try to drop 'sku' index. If it fails, it fails (user might need to run manually). -- Safest is to just ADD the new one and let the old one be (if duplicate SKUs are allowed across outlets). -- But we want to ALLOW duplicate SKUs across outlets. -- So we MUST drop the unique constraint on `sku`. DROP INDEX sku ON stock_items; -- Re-add as non-unique (just index) or part of composite unique CREATE UNIQUE INDEX unique_sku_outlet ON stock_items (sku, outlet_id); -- 6. Migrate Stock from outlet_stock to stock_items (for Outlet 1) -- We assume current items belong to Outlet 1. UPDATE stock_items si JOIN outlet_stock os ON si.id = os.item_id AND os.outlet_id = 1 SET si.stock_quantity = os.quantity; -- We leave outlet_stock for now, but application logic will switch to stock_items.stock_quantity