material_manage_system/scripts/migrations/006_phase1_backfill.sql
2026-09-16 16:29:04 +08:00

32 lines
1.9 KiB
SQL

INSERT INTO inventory_balances (organization_id, warehouse_id, location_id, material_id, on_hand)
SELECT 1, 1, 1, id, current_stock FROM materials
ON DUPLICATE KEY UPDATE material_id = VALUES(material_id);
INSERT INTO stock_warning_rules (organization_id, warehouse_id, material_id, minimum_available, enabled)
SELECT 1, 1, id, warning_stock, TRUE FROM materials
ON DUPLICATE KEY UPDATE material_id = VALUES(material_id);
ALTER TABLE inbound_orders
ADD COLUMN organization_id BIGINT NOT NULL DEFAULT 1 AFTER id,
ADD COLUMN warehouse_id BIGINT NOT NULL DEFAULT 1 AFTER organization_id,
ADD COLUMN location_id BIGINT NOT NULL DEFAULT 1 AFTER warehouse_id,
ADD CONSTRAINT fk_inbound_orders_org FOREIGN KEY (organization_id) REFERENCES organizations(id) ON DELETE RESTRICT,
ADD CONSTRAINT fk_inbound_orders_warehouse FOREIGN KEY (warehouse_id) REFERENCES warehouses(id) ON DELETE RESTRICT,
ADD CONSTRAINT fk_inbound_orders_location FOREIGN KEY (location_id) REFERENCES warehouse_locations(id) ON DELETE RESTRICT;
ALTER TABLE outbound_orders
ADD COLUMN organization_id BIGINT NOT NULL DEFAULT 1 AFTER id,
ADD COLUMN warehouse_id BIGINT NOT NULL DEFAULT 1 AFTER organization_id,
ADD COLUMN location_id BIGINT NOT NULL DEFAULT 1 AFTER warehouse_id,
ADD CONSTRAINT fk_outbound_orders_org FOREIGN KEY (organization_id) REFERENCES organizations(id) ON DELETE RESTRICT,
ADD CONSTRAINT fk_outbound_orders_warehouse FOREIGN KEY (warehouse_id) REFERENCES warehouses(id) ON DELETE RESTRICT,
ADD CONSTRAINT fk_outbound_orders_location FOREIGN KEY (location_id) REFERENCES warehouse_locations(id) ON DELETE RESTRICT;
SELECT m.id, m.material_code, m.current_stock AS legacy_stock,
COALESCE(SUM(ib.on_hand), 0) AS migrated_stock,
m.current_stock - COALESCE(SUM(ib.on_hand), 0) AS difference
FROM materials m
LEFT JOIN inventory_balances ib ON ib.material_id = m.id
GROUP BY m.id, m.material_code, m.current_stock
HAVING difference <> 0;