migrations/Version20260617130000.php line 1

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace DoctrineMigrations;
  4. use Doctrine\DBAL\Schema\Schema;
  5. use Doctrine\Migrations\AbstractMigration;
  6. /**
  7.  * project_order_expenses.total — persisted canonical positions total.
  8.  *
  9.  * Written on every upsert (ExpenseService::computeExpenseTotal) so the expense
  10.  * list reads the figure directly with no client-side math. This migration adds
  11.  * the column and backfills all existing rows with the same canonical formula:
  12.  *   per position: buying_price > 0 ? (unit / PE) * buying_price : amount
  13.  *   plus delivery_amount; PE (price_unit) null/0 behaves as 1.
  14.  * Mirrors FE Frontend/src/common/utils/PositionPrice (calcPositionLineTotal).
  15.  */
  16. final class Version20260617130000 extends AbstractMigration
  17. {
  18.     public function getDescription(): string
  19.     {
  20.         return 'Add project_order_expenses.total (persisted positions total) + backfill existing rows';
  21.     }
  22.     public function up(Schema $schema): void
  23.     {
  24.         $this->addSql('ALTER TABLE project_order_expenses ADD total NUMERIC(10, 2) DEFAULT NULL');
  25.         $this->addSql('
  26.             UPDATE project_order_expenses e
  27.             SET e.total = (
  28.                 SELECT ROUND(COALESCE(SUM(
  29.                     (CASE
  30.                         WHEN COALESCE(p.buying_price, 0) > 0
  31.                             THEN (p.unit / (CASE WHEN COALESCE(p.price_unit, 0) > 0 THEN p.price_unit ELSE 1 END)) * p.buying_price
  32.                         ELSE CAST(p.amount AS DECIMAL(10, 2))
  33.                     END) + COALESCE(p.delivery_amount, 0)
  34.                 ), 0), 2)
  35.                 FROM project_order_expense_positions p
  36.                 WHERE p.project_order_expense_id = e.id
  37.             )
  38.         ');
  39.     }
  40.     public function down(Schema $schema): void
  41.     {
  42.         $this->addSql('ALTER TABLE project_order_expenses DROP total');
  43.     }
  44. }