2026_02_12_130001_create_spare_parts_view.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. use Illuminate\Database\Migrations\Migration;
  3. use Illuminate\Support\Facades\DB;
  4. return new class extends Migration
  5. {
  6. /**
  7. * Run the migrations.
  8. */
  9. public function up(): void
  10. {
  11. DB::statement("DROP VIEW IF EXISTS spare_parts_view");
  12. DB::statement("
  13. CREATE VIEW spare_parts_view AS
  14. SELECT
  15. sp.*,
  16. COALESCE(spo_agg.physical_stock_without_docs, 0) AS physical_stock_without_docs,
  17. COALESCE(spo_agg.physical_stock_with_docs, 0) AS physical_stock_with_docs,
  18. COALESCE(res_agg.reserved_without_docs, 0) AS reserved_without_docs,
  19. COALESCE(res_agg.reserved_with_docs, 0) AS reserved_with_docs,
  20. (COALESCE(spo_agg.physical_stock_without_docs, 0) - COALESCE(res_agg.reserved_without_docs, 0)) AS quantity_without_docs,
  21. (COALESCE(spo_agg.physical_stock_with_docs, 0) - COALESCE(res_agg.reserved_with_docs, 0)) AS quantity_with_docs,
  22. ((COALESCE(spo_agg.physical_stock_without_docs, 0) - COALESCE(res_agg.reserved_without_docs, 0))
  23. + (COALESCE(spo_agg.physical_stock_with_docs, 0) - COALESCE(res_agg.reserved_with_docs, 0))) AS total_quantity
  24. FROM spare_parts sp
  25. LEFT JOIN (
  26. SELECT
  27. spare_part_id,
  28. SUM(CASE WHEN status = 'in_stock' AND with_documents = 0 THEN available_qty ELSE 0 END) AS physical_stock_without_docs,
  29. SUM(CASE WHEN status = 'in_stock' AND with_documents = 1 THEN available_qty ELSE 0 END) AS physical_stock_with_docs
  30. FROM spare_part_orders
  31. WHERE deleted_at IS NULL
  32. GROUP BY spare_part_id
  33. ) spo_agg ON spo_agg.spare_part_id = sp.id
  34. LEFT JOIN (
  35. SELECT
  36. spare_part_id,
  37. SUM(CASE WHEN status = 'active' AND with_documents = 0 THEN reserved_qty ELSE 0 END) AS reserved_without_docs,
  38. SUM(CASE WHEN status = 'active' AND with_documents = 1 THEN reserved_qty ELSE 0 END) AS reserved_with_docs
  39. FROM reservations
  40. GROUP BY spare_part_id
  41. ) res_agg ON res_agg.spare_part_id = sp.id
  42. WHERE sp.deleted_at IS NULL
  43. ");
  44. }
  45. /**
  46. * Reverse the migrations.
  47. */
  48. public function down(): void
  49. {
  50. DB::statement("DROP VIEW IF EXISTS spare_parts_view");
  51. }
  52. };