diff --git a/db/README.md b/db/README.md index 77729ed..b828dc6 100644 --- a/db/README.md +++ b/db/README.md @@ -19,6 +19,7 @@ 15. `db/migrations/0019_allow_multiple_open_stock_lots.sql` 16. `db/migrations/0020_include_stock_adjustments_in_balance.sql` 17. `db/migrations/0021_stock_lot_activation_selection.sql` +18. `db/migrations/0022_backfill_stock_lot_activation_selection.sql` ## Beispielausfuehrung diff --git a/db/migrations/0022_backfill_stock_lot_activation_selection.sql b/db/migrations/0022_backfill_stock_lot_activation_selection.sql new file mode 100644 index 0000000..32349d3 --- /dev/null +++ b/db/migrations/0022_backfill_stock_lot_activation_selection.sql @@ -0,0 +1,25 @@ +BEGIN; + +WITH qualified AS ( + SELECT + sl.id, + sl.product_id, + COUNT(*) OVER (PARTITION BY sl.product_id) AS qualified_count + FROM stock_lot sl + INNER JOIN v_stock_lot_balance v ON v.stock_lot_id = sl.id + WHERE sl.status = 'open' + AND NULLIF(TRIM(sl.lot_number), '') IS NOT NULL + AND sl.manufacturer_party_id IS NOT NULL + AND NULLIF(TRIM(sl.manufacturer_lot_number), '') IS NOT NULL + AND sl.mfg_date IS NOT NULL + AND sl.expiry_date IS NOT NULL + AND sl.purchase_date IS NOT NULL + AND v.qty_net > 0 +) +UPDATE stock_lot sl +SET next_active = TRUE, updated_at = NOW() +FROM qualified q +WHERE sl.id = q.id + AND q.qualified_count = 1; + +COMMIT;