getSchemaBuilder(); if ($schema->hasTable('purchase_order_sources') || $schema->hasColumn('purchase_orders', 'order_key') || ! $schema->hasTable('budget_order_commands')) { throw new LogicException('Install the optional financial schema first; do not reinstall or repair a partial host schema automatically.'); } $db->transaction(function () use ($db, $schema): void { $schema->table('purchase_orders', function (Blueprint $table): void { $table->dropUnique(['requisition_id']); $table->dropUnique(['purchase_award_id']); $table->uuid('order_key')->nullable(); $table->string('order_payload_hash', 64)->nullable(); $table->unsignedInteger('order_source_count')->nullable(); $table->unique(['tenant_id', 'order_key']); }); $schema->table('purchase_order_items', function (Blueprint $table): void { $table->foreignId('quotation_item_id')->nullable()->constrained()->restrictOnDelete(); $table->unsignedBigInteger('quantity_offset_milli')->nullable(); }); $schema->create('purchase_order_sources', function (Blueprint $table): void { $table->id(); $table->foreignId('tenant_id')->constrained()->restrictOnDelete(); $table->foreignId('purchase_order_id')->constrained()->restrictOnDelete(); $table->foreignId('requisition_id')->constrained()->restrictOnDelete(); $table->foreignId('purchase_award_id')->constrained()->restrictOnDelete(); $table->foreignId('quotation_id')->constrained()->restrictOnDelete(); $table->json('snapshot'); $table->unique(['purchase_order_id', 'requisition_id']); }); if ($db->getDriverName() === 'pgsql') { $db->statement('CREATE TRIGGER distribution_history_guard BEFORE UPDATE OR DELETE ON purchase_order_sources FOR EACH ROW EXECUTE FUNCTION sgc_distribution_history_guard()'); $db->unprepared(<<<'SQL' CREATE FUNCTION sgc_order_parts_header_guard() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF OLD.order_key IS NOT NULL THEN IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'Preserve partial order history'; END IF; IF (to_jsonb(NEW) - 'number' - 'status') IS DISTINCT FROM (to_jsonb(OLD) - 'number' - 'status') THEN RAISE EXCEPTION 'Preserve the frozen partial order'; END IF; ELSIF TG_OP = 'UPDATE' AND NEW.order_key IS NOT NULL THEN RAISE EXCEPTION 'Do not relabel an issued legacy order'; END IF; IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; RETURN NEW; END $$; CREATE TRIGGER order_parts_header_guard BEFORE UPDATE OR DELETE ON purchase_orders FOR EACH ROW EXECUTE FUNCTION sgc_order_parts_header_guard(); CREATE TRIGGER order_parts_line_guard BEFORE UPDATE OR DELETE ON purchase_order_items FOR EACH ROW WHEN (OLD.quotation_item_id IS NOT NULL) EXECUTE FUNCTION sgc_distribution_history_guard(); SQL); } }); } }