import { MigrationInterface, QueryRunner, Table, TableForeignKey } from 'typeorm'; /** * Create the freight.last_mile table — one row per booking's last-mile * (terminal → door) leg, with payment split and an optional assigned vehicle. */ export class CreateLastMile1810000000001 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise { const exists = await queryRunner.hasTable('freight.last_mile'); if (exists) return; await queryRunner.createTable( new Table({ name: 'freight.last_mile', columns: [ { name: 'id', type: 'uuid', isPrimary: true, default: 'gen_random_uuid()', }, { name: 'booking_id', type: 'uuid', isNullable: false }, { name: 'status', type: 'varchar', length: '30', default: `'PAYMENT_PENDING'`, isNullable: false, }, { name: 'advanced_payment', type: 'numeric', precision: 14, scale: 2, default: 0, isNullable: false, }, { name: 'remaining_payment', type: 'numeric', precision: 14, scale: 2, default: 0, isNullable: false, }, { name: 'estimated_km', type: 'numeric', precision: 10, scale: 2, isNullable: true, }, { name: 'exact_km', type: 'numeric', precision: 10, scale: 2, isNullable: true, }, { name: 'vehicle_id', type: 'uuid', isNullable: true }, { name: 'created_at', type: 'timestamptz', default: 'now()' }, { name: 'updated_at', type: 'timestamptz', default: 'now()' }, { name: 'deleted_at', type: 'timestamptz', isNullable: true }, ], }), true, ); await queryRunner.createForeignKey( 'freight.last_mile', new TableForeignKey({ columnNames: ['booking_id'], referencedTableName: 'freight.bookings', referencedColumnNames: ['id'], onDelete: 'CASCADE', }), ); await queryRunner.createForeignKey( 'freight.last_mile', new TableForeignKey({ columnNames: ['vehicle_id'], referencedTableName: 'freight.vehicles', referencedColumnNames: ['id'], onDelete: 'SET NULL', }), ); await queryRunner.query( `CREATE INDEX "IDX_last_mile_booking_id" ON "freight"."last_mile" ("booking_id")`, ); await queryRunner.query( `CREATE INDEX "IDX_last_mile_status" ON "freight"."last_mile" ("status")`, ); await queryRunner.query( `CREATE INDEX "IDX_last_mile_vehicle_id" ON "freight"."last_mile" ("vehicle_id")`, ); } public async down(queryRunner: QueryRunner): Promise { const exists = await queryRunner.hasTable('freight.last_mile'); if (exists) { await queryRunner.dropTable('freight.last_mile'); } } }