64 lines
3.3 KiB
PHP
64 lines
3.3 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use Illuminate\Database\Connection;
|
|
use Illuminate\Database\Schema\Blueprint;
|
|
use LogicException;
|
|
|
|
/** Single additive schema definition shared by explicit installation and guarded QA. */
|
|
final class BudgetLandedCostSchema
|
|
{
|
|
public static function install(Connection $db): void
|
|
{
|
|
$schema = $db->getSchemaBuilder();
|
|
$tables = ['budget_landed_commands', 'budget_landed_entries'];
|
|
if ($schema->hasTable($tables[0]) || $schema->hasTable($tables[1])) {
|
|
throw new LogicException('Never reinstall or repair landed-cost financial history implicitly.');
|
|
}
|
|
$db->transaction(function () use ($schema, $db, $tables): void {
|
|
$schema->create('budget_landed_commands', function (Blueprint $table): void {
|
|
$table->id();
|
|
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
|
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
|
|
$table->uuid('operation_key');
|
|
$table->uuid('plan_key');
|
|
$table->unsignedInteger('plan_version');
|
|
$table->string('plan_hash', 64);
|
|
$table->string('kind', 20);
|
|
$table->string('payload_hash', 64);
|
|
$table->json('snapshot');
|
|
$table->timestamp('created_at');
|
|
$table->unique(['tenant_id', 'operation_key']);
|
|
$table->index(['tenant_id', 'plan_key', 'id']);
|
|
});
|
|
$schema->create('budget_landed_entries', function (Blueprint $table): void {
|
|
$table->id();
|
|
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
|
$table->foreignId('command_id')->constrained('budget_landed_commands')->restrictOnDelete();
|
|
$table->foreignId('budget_id')->constrained('budgets')->restrictOnDelete();
|
|
$table->string('source_key', 120);
|
|
$table->string('source_kind', 30);
|
|
$table->unsignedBigInteger('source_id');
|
|
$table->unsignedInteger('source_version');
|
|
$table->string('source_revision', 64);
|
|
$table->json('source_snapshot');
|
|
$table->bigInteger('reserved_minor');
|
|
$table->bigInteger('committed_minor');
|
|
$table->bigInteger('consumed_minor');
|
|
$table->unique(['command_id', 'source_key']);
|
|
$table->index(['tenant_id', 'source_key']);
|
|
});
|
|
foreach ($tables as $table) {
|
|
if ($db->getDriverName() === 'pgsql') {
|
|
$db->unprepared('CREATE FUNCTION preserve_'.$table.'() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION \'Preserve landed cost history\'; END $$;');
|
|
$db->statement('CREATE TRIGGER immutable_landed_history BEFORE UPDATE OR DELETE ON '.$table.' FOR EACH ROW EXECUTE FUNCTION preserve_'.$table.'()');
|
|
} else {
|
|
$db->unprepared('CREATE TRIGGER '.$table.'_update BEFORE UPDATE ON '.$table." BEGIN SELECT RAISE(ABORT, 'Preserve landed cost history'); END;");
|
|
$db->unprepared('CREATE TRIGGER '.$table.'_delete BEFORE DELETE ON '.$table." BEGIN SELECT RAISE(ABORT, 'Preserve landed cost history'); END;");
|
|
}
|
|
}
|
|
});
|
|
}
|
|
}
|