novas funcionalidades dos formulario
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-02 11:13:37 +02:00
parent a6afb4e97a
commit 4f35313d06
104 changed files with 7653 additions and 178 deletions
@@ -0,0 +1,401 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
private const BUSINESS_STATUSES = [
'draft', 'submitted', 'in_review', 'needs_information', 'withdrawn',
'triage', 'information_pending', 'review', 'approval_l1', 'approval_l2',
'approved', 'published', 'suspended', 'rejected', 'cancelled', 'archived',
];
private const INTEREST_STATUSES = [
'received', 'qualification', 'pending', 'referred', 'contact_accepted',
'due_diligence', 'negotiation', 'refused', 'converted', 'cancelled', 'closed',
'in_review', 'reviewed', 'qualified', 'contacted', 'submitted',
];
public function up(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('Marketplace extension requires PostgreSQL with PostGIS.');
}
Schema::table('existing_businesses', function (Blueprint $table) {
$table->string('public_title', 180)->nullable();
$table->string('public_slug', 220)->nullable();
$table->string('activity_code', 60)->nullable();
$table->string('stage', 40)->nullable();
$table->text('objective')->nullable();
$table->char('currency', 3)->nullable();
$table->decimal('amount_min', 20, 2)->nullable();
$table->decimal('amount_max', 20, 2)->nullable();
$table->decimal('available_percentage', 5, 2)->nullable();
$table->text('funds_use')->nullable();
$table->timestampTz('submitted_at')->nullable();
$table->timestampTz('published_at')->nullable();
$table->timestampTz('expires_at')->nullable();
$table->string('next_action', 180)->nullable();
$table->timestampTz('next_action_due_at')->nullable();
$table->foreignId('assigned_to')->nullable();
});
DB::statement('ALTER TABLE existing_businesses ADD CONSTRAINT existing_businesses_assigned_to_fk FOREIGN KEY (assigned_to) REFERENCES users(id) ON DELETE SET NULL');
DB::statement(<<<'SQL'
DO $$
DECLARE constraint_row record;
BEGIN
FOR constraint_row IN
SELECT conname
FROM pg_constraint
WHERE conrelid = 'public.existing_businesses'::regclass
AND contype = 'c'
AND pg_get_constraintdef(oid) LIKE '%status%'
AND pg_get_constraintdef(oid) LIKE '%draft%'
LOOP
EXECUTE format('ALTER TABLE public.existing_businesses DROP CONSTRAINT %I', constraint_row.conname);
END LOOP;
END $$;
SQL);
DB::statement("ALTER TABLE existing_businesses ADD CONSTRAINT existing_businesses_status_check CHECK (status IN ('".implode("','", self::BUSINESS_STATUSES)."'))");
DB::statement("ALTER TABLE existing_business_reviews DROP CONSTRAINT existing_business_reviews_action_check, ADD CONSTRAINT existing_business_reviews_action_check CHECK (action IN ('created','updated','archived','object_added','object_updated','verification','submitted','triage','in_review','needs_information','approval_l1','approval_l2','approved','published','rejected','withdrawn'))");
DB::statement('ALTER TABLE existing_businesses ADD CONSTRAINT existing_businesses_amount_min_check CHECK (amount_min IS NULL OR amount_min >= 0)');
DB::statement('ALTER TABLE existing_businesses ADD CONSTRAINT existing_businesses_amount_max_check CHECK (amount_max IS NULL OR amount_min IS NULL OR amount_max >= amount_min)');
DB::statement('ALTER TABLE existing_businesses ADD CONSTRAINT existing_businesses_percentage_check CHECK (available_percentage IS NULL OR available_percentage BETWEEN 0 AND 100)');
DB::statement('ALTER TABLE existing_businesses ADD CONSTRAINT existing_businesses_currency_check CHECK ((amount_min IS NULL AND amount_max IS NULL) OR currency IS NOT NULL)');
DB::statement("ALTER TABLE existing_businesses ADD CONSTRAINT existing_businesses_published_check CHECK (status <> 'published' OR (published_at IS NOT NULL AND public_slug IS NOT NULL))");
DB::statement("ALTER TABLE existing_businesses ADD CONSTRAINT existing_businesses_public_slug_check CHECK (public_slug IS NULL OR public_slug ~ '^[a-z0-9]+(?:-[a-z0-9]+)*$')");
DB::statement('CREATE UNIQUE INDEX existing_businesses_public_slug_uq ON existing_businesses(public_slug) WHERE public_slug IS NOT NULL');
DB::statement('CREATE INDEX existing_businesses_queue_idx ON existing_businesses(status,assigned_to,next_action_due_at) WHERE deleted_at IS NULL');
Schema::table('investors', function (Blueprint $table) {
$table->jsonb('investment_sectors')->nullable();
$table->jsonb('investment_geographies')->nullable();
$table->text('investment_strategy')->nullable();
$table->unsignedInteger('investment_horizon_months')->nullable();
$table->decimal('ticket_min', 20, 2)->nullable();
$table->decimal('ticket_max', 20, 2)->nullable();
$table->char('ticket_currency', 3)->nullable();
});
DB::statement('ALTER TABLE investors ADD CONSTRAINT investors_ticket_range_check CHECK (ticket_max IS NULL OR ticket_min IS NULL OR ticket_max >= ticket_min)');
DB::statement('ALTER TABLE investors ADD CONSTRAINT investors_ticket_min_check CHECK (ticket_min IS NULL OR ticket_min >= 0)');
DB::statement('ALTER TABLE investors ADD CONSTRAINT investors_ticket_max_check CHECK (ticket_max IS NULL OR ticket_max >= 0)');
DB::statement('ALTER TABLE investors ADD CONSTRAINT investors_ticket_currency_check CHECK ((ticket_min IS NULL AND ticket_max IS NULL) OR ticket_currency IS NOT NULL)');
Schema::table('interest_requests', function (Blueprint $table) {
$table->foreignUuid('existing_business_id')->nullable();
$table->foreignUuid('investor_id')->nullable();
$table->string('modality', 50)->nullable();
$table->decimal('requested_percentage', 5, 2)->nullable();
$table->decimal('ticket_min', 20, 2)->nullable();
$table->decimal('ticket_max', 20, 2)->nullable();
$table->char('ticket_currency', 3)->nullable();
$table->foreignId('assigned_to')->nullable();
$table->string('next_action', 180)->nullable();
$table->timestampTz('next_action_due_at')->nullable();
});
DB::statement('ALTER TABLE interest_requests ADD CONSTRAINT interest_requests_existing_business_fk FOREIGN KEY (existing_business_id) REFERENCES existing_businesses(id) ON DELETE RESTRICT');
DB::statement('ALTER TABLE interest_requests ADD CONSTRAINT interest_requests_investor_fk FOREIGN KEY (investor_id) REFERENCES investors(id) ON DELETE SET NULL');
DB::statement('ALTER TABLE interest_requests ADD CONSTRAINT interest_requests_assigned_to_fk FOREIGN KEY (assigned_to) REFERENCES users(id) ON DELETE SET NULL');
DB::statement('ALTER TABLE interest_requests ADD CONSTRAINT interest_requests_single_target_check CHECK (num_nonnulls(opportunity_id, existing_business_id) <= 1)');
DB::statement('ALTER TABLE interest_requests ADD CONSTRAINT interest_requests_percentage_check CHECK (requested_percentage IS NULL OR requested_percentage BETWEEN 0 AND 100)');
DB::statement('ALTER TABLE interest_requests ADD CONSTRAINT interest_requests_ticket_min_check CHECK (ticket_min IS NULL OR ticket_min >= 0)');
DB::statement('ALTER TABLE interest_requests ADD CONSTRAINT interest_requests_ticket_max_check CHECK (ticket_max IS NULL OR ticket_max >= 0)');
DB::statement('ALTER TABLE interest_requests ADD CONSTRAINT interest_requests_ticket_range_check CHECK (ticket_max IS NULL OR ticket_min IS NULL OR ticket_max >= ticket_min)');
DB::statement('ALTER TABLE interest_requests ADD CONSTRAINT interest_requests_ticket_currency_check CHECK ((ticket_min IS NULL AND ticket_max IS NULL) OR ticket_currency IS NOT NULL)');
DB::statement("ALTER TABLE interest_requests ADD CONSTRAINT interest_requests_status_check CHECK (status IN ('".implode("','", self::INTEREST_STATUSES)."'))");
Schema::table('interest_requests', fn (Blueprint $table) => $table->index(['existing_business_id', 'status'], 'interest_requests_business_status_idx'));
DB::statement('CREATE INDEX interest_requests_queue_idx ON interest_requests(status,assigned_to,next_action_due_at) WHERE deleted_at IS NULL');
DB::statement('ALTER TABLE interest_requests ADD CONSTRAINT interest_requests_business_modality_required_check CHECK (existing_business_id IS NULL OR modality IS NOT NULL)');
DB::statement("CREATE UNIQUE INDEX interest_business_email_modality_uq ON interest_requests(existing_business_id,lower(email),modality) WHERE existing_business_id IS NOT NULL AND deleted_at IS NULL AND status NOT IN ('refused','converted','cancelled','closed')");
Schema::table('consents', function (Blueprint $table) {
$table->foreignId('opportunity_id')->nullable();
$table->foreignUuid('existing_business_id')->nullable();
$table->foreignId('interest_request_id')->nullable();
$table->string('policy_version', 40)->nullable();
$table->char('technical_fingerprint_hash', 64)->nullable();
});
DB::statement('ALTER TABLE consents ADD CONSTRAINT consents_opportunity_fk FOREIGN KEY (opportunity_id) REFERENCES opportunities(id) ON DELETE SET NULL');
DB::statement('ALTER TABLE consents ADD CONSTRAINT consents_existing_business_fk FOREIGN KEY (existing_business_id) REFERENCES existing_businesses(id) ON DELETE RESTRICT');
DB::statement('ALTER TABLE consents ADD CONSTRAINT consents_interest_request_fk FOREIGN KEY (interest_request_id) REFERENCES interest_requests(id) ON DELETE RESTRICT');
DB::statement('ALTER TABLE consents ADD CONSTRAINT consents_subject_target_check CHECK (num_nonnulls(opportunity_id, existing_business_id, interest_request_id) <= 1)');
DB::statement(<<<'SQL'
ALTER TABLE consents ADD CONSTRAINT consents_fingerprint_check CHECK (technical_fingerprint_hash IS NULL OR technical_fingerprint_hash ~ '^[0-9a-f]{64}$')
SQL);
Schema::table('existing_business_objects', function (Blueprint $table) {
$table->string('asset_type', 50)->nullable();
$table->decimal('area', 18, 4)->nullable();
$table->string('area_unit', 20)->nullable();
$table->string('occupancy_status', 40)->nullable();
$table->string('condition_status', 40)->nullable();
});
DB::statement('ALTER TABLE existing_business_objects ADD CONSTRAINT existing_business_objects_area_check CHECK (area IS NULL OR area >= 0)');
Schema::table('documents', function (Blueprint $table) {
$table->unsignedBigInteger('size_bytes')->nullable();
$table->string('issuer', 180)->nullable();
$table->date('issued_on')->nullable();
$table->date('valid_until')->nullable();
$table->foreignId('uploaded_by')->nullable();
});
DB::statement('ALTER TABLE documents ADD CONSTRAINT documents_uploaded_by_fk FOREIGN KEY (uploaded_by) REFERENCES users(id) ON DELETE SET NULL');
DB::statement('ALTER TABLE documents ADD CONSTRAINT documents_size_bytes_check CHECK (size_bytes IS NULL OR size_bytes > 0)');
DB::statement('ALTER TABLE documents ADD CONSTRAINT documents_valid_dates_check CHECK (valid_until IS NULL OR issued_on IS NULL OR valid_until >= issued_on)');
Schema::table('tasks', function (Blueprint $table) {
$table->foreignUuid('existing_business_id')->nullable()->constrained('existing_businesses')->restrictOnDelete();
$table->foreignId('interest_request_id')->nullable()->constrained('interest_requests')->restrictOnDelete();
$table->string('task_type', 60)->nullable();
$table->unsignedSmallInteger('priority')->default(3);
$table->timestampTz('completed_at')->nullable();
$table->string('outcome', 80)->nullable();
});
DB::statement('ALTER TABLE tasks ADD CONSTRAINT tasks_single_aggregate_check CHECK (num_nonnulls(opportunity_id, existing_business_id, interest_request_id) <= 1)');
DB::statement('ALTER TABLE tasks ADD CONSTRAINT tasks_priority_range_check CHECK (priority BETWEEN 1 AND 5)');
DB::statement('CREATE INDEX tasks_existing_business_idx ON tasks(existing_business_id,due_at) WHERE existing_business_id IS NOT NULL');
DB::statement('CREATE INDEX tasks_interest_request_idx ON tasks(interest_request_id,due_at) WHERE interest_request_id IS NOT NULL');
Schema::table('outbox_events', function (Blueprint $table) {
$table->string('idempotency_key', 120)->nullable()->unique();
$table->unsignedInteger('attempts')->default(0);
$table->timestampTz('failed_at')->nullable();
$table->text('last_error')->nullable();
});
$this->createBusinessLocations();
$this->createBusinessRights();
$this->createBusinessDocumentLinks();
$this->createWorkflowTransitions();
$this->createExternalRecordLinks();
}
public function down(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('Marketplace extension rollback requires PostgreSQL.');
}
$this->refuseRollbackWithData();
DB::statement('DROP TRIGGER IF EXISTS existing_business_locations_hierarchy_trigger ON existing_business_locations');
DB::statement('DROP FUNCTION IF EXISTS enforce_existing_business_location_hierarchy()');
DB::statement('DROP TABLE IF EXISTS external_record_links RESTRICT');
DB::statement('DROP TABLE IF EXISTS business_workflow_transitions RESTRICT');
DB::statement('DROP TABLE IF EXISTS existing_business_document_links RESTRICT');
DB::statement('DROP TABLE IF EXISTS existing_business_rights RESTRICT');
DB::statement('DROP TABLE IF EXISTS existing_business_locations RESTRICT');
Schema::table('outbox_events', function (Blueprint $table) {
$table->dropUnique('outbox_events_idempotency_key_unique');
$table->dropColumn(['idempotency_key', 'attempts', 'failed_at', 'last_error']);
});
DB::statement('DROP INDEX tasks_existing_business_idx');
DB::statement('DROP INDEX tasks_interest_request_idx');
DB::statement('ALTER TABLE tasks DROP CONSTRAINT tasks_single_aggregate_check, DROP CONSTRAINT tasks_priority_range_check');
Schema::table('tasks', function (Blueprint $table) {
$table->dropForeign(['existing_business_id']);
$table->dropForeign(['interest_request_id']);
});
Schema::table('tasks', fn (Blueprint $table) => $table->dropColumn(['existing_business_id', 'interest_request_id', 'task_type', 'priority', 'completed_at', 'outcome']));
DB::statement('ALTER TABLE documents DROP CONSTRAINT documents_uploaded_by_fk, DROP CONSTRAINT documents_size_bytes_check, DROP CONSTRAINT documents_valid_dates_check');
Schema::table('documents', fn (Blueprint $table) => $table->dropColumn(['size_bytes', 'issuer', 'issued_on', 'valid_until', 'uploaded_by']));
DB::statement('ALTER TABLE existing_business_objects DROP CONSTRAINT existing_business_objects_area_check');
Schema::table('existing_business_objects', fn (Blueprint $table) => $table->dropColumn(['asset_type', 'area', 'area_unit', 'occupancy_status', 'condition_status']));
DB::statement('ALTER TABLE consents DROP CONSTRAINT consents_opportunity_fk, DROP CONSTRAINT consents_existing_business_fk, DROP CONSTRAINT consents_interest_request_fk, DROP CONSTRAINT consents_subject_target_check, DROP CONSTRAINT consents_fingerprint_check');
Schema::table('consents', fn (Blueprint $table) => $table->dropColumn(['opportunity_id', 'existing_business_id', 'interest_request_id', 'policy_version', 'technical_fingerprint_hash']));
Schema::table('interest_requests', fn (Blueprint $table) => $table->dropIndex('interest_requests_business_status_idx'));
DB::statement('DROP INDEX interest_requests_queue_idx');
DB::statement('DROP INDEX interest_business_email_modality_uq');
DB::statement('ALTER TABLE interest_requests DROP CONSTRAINT interest_requests_business_modality_required_check, DROP CONSTRAINT interest_requests_existing_business_fk, DROP CONSTRAINT interest_requests_investor_fk, DROP CONSTRAINT interest_requests_assigned_to_fk, DROP CONSTRAINT interest_requests_single_target_check, DROP CONSTRAINT interest_requests_percentage_check, DROP CONSTRAINT interest_requests_ticket_min_check, DROP CONSTRAINT interest_requests_ticket_max_check, DROP CONSTRAINT interest_requests_ticket_range_check, DROP CONSTRAINT interest_requests_ticket_currency_check, DROP CONSTRAINT interest_requests_status_check');
Schema::table('interest_requests', fn (Blueprint $table) => $table->dropColumn([
'existing_business_id', 'investor_id', 'modality', 'requested_percentage', 'ticket_min', 'ticket_max', 'ticket_currency', 'assigned_to', 'next_action', 'next_action_due_at',
]));
DB::statement('ALTER TABLE investors DROP CONSTRAINT investors_ticket_range_check, DROP CONSTRAINT investors_ticket_min_check, DROP CONSTRAINT investors_ticket_max_check, DROP CONSTRAINT investors_ticket_currency_check');
Schema::table('investors', fn (Blueprint $table) => $table->dropColumn([
'investment_sectors', 'investment_geographies', 'investment_strategy', 'investment_horizon_months', 'ticket_min', 'ticket_max', 'ticket_currency',
]));
DB::statement('ALTER TABLE existing_businesses DROP CONSTRAINT existing_businesses_assigned_to_fk, DROP CONSTRAINT existing_businesses_amount_min_check, DROP CONSTRAINT existing_businesses_amount_max_check, DROP CONSTRAINT existing_businesses_percentage_check, DROP CONSTRAINT existing_businesses_currency_check, DROP CONSTRAINT existing_businesses_published_check');
DB::statement('DROP INDEX existing_businesses_public_slug_uq');
DB::statement('ALTER TABLE existing_businesses DROP CONSTRAINT existing_businesses_public_slug_check');
DB::statement('DROP INDEX existing_businesses_queue_idx');
DB::statement("ALTER TABLE existing_business_reviews DROP CONSTRAINT existing_business_reviews_action_check, ADD CONSTRAINT existing_business_reviews_action_check CHECK (action IN ('submitted','in_review','needs_information','withdrawn'))");
DB::statement("ALTER TABLE existing_businesses DROP CONSTRAINT existing_businesses_status_check, ADD CONSTRAINT existing_businesses_status_check CHECK (status IN ('draft','submitted','in_review','needs_information','withdrawn'))");
Schema::table('existing_businesses', fn (Blueprint $table) => $table->dropColumn([
'public_title', 'public_slug', 'activity_code', 'stage', 'objective', 'currency', 'amount_min', 'amount_max', 'available_percentage', 'funds_use', 'submitted_at', 'published_at', 'expires_at', 'next_action', 'next_action_due_at', 'assigned_to',
]));
}
private function createBusinessLocations(): void
{
Schema::create('existing_business_locations', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('existing_business_id')->constrained('existing_businesses')->cascadeOnDelete();
$table->foreignUuid('province_id')->nullable()->constrained('geo_locations')->restrictOnDelete();
$table->foreignUuid('district_id')->nullable()->constrained('geo_locations')->restrictOnDelete();
$table->foreignUuid('admin_post_id')->nullable()->constrained('geo_locations')->restrictOnDelete();
$table->foreignUuid('locality_id')->nullable()->constrained('geo_locations')->restrictOnDelete();
$table->string('precision_level', 20)->default('district');
$table->boolean('is_primary')->default(false);
$table->boolean('is_public')->default(false);
$table->timestampsTz();
});
DB::statement('ALTER TABLE existing_business_locations ADD COLUMN geom geometry(Geometry,4326)');
DB::statement("ALTER TABLE existing_business_locations ADD CONSTRAINT existing_business_locations_precision_check CHECK (precision_level IN ('province','district','admin_post','locality','exact'))");
DB::statement('ALTER TABLE existing_business_locations ADD CONSTRAINT existing_business_locations_geom_check CHECK (geom IS NULL OR (ST_SRID(geom)=4326 AND NOT ST_IsEmpty(geom) AND ST_IsValid(geom)))');
DB::statement("ALTER TABLE existing_business_locations ADD CONSTRAINT existing_business_locations_precision_target_check CHECK ((precision_level <> 'province' OR province_id IS NOT NULL) AND (precision_level <> 'district' OR district_id IS NOT NULL) AND (precision_level <> 'admin_post' OR admin_post_id IS NOT NULL) AND (precision_level <> 'locality' OR locality_id IS NOT NULL) AND (precision_level <> 'exact' OR geom IS NOT NULL))");
DB::statement('CREATE UNIQUE INDEX existing_business_primary_location_uq ON existing_business_locations(existing_business_id) WHERE is_primary');
DB::statement('CREATE INDEX existing_business_locations_gist ON existing_business_locations USING gist(geom)');
DB::unprepared(<<<'SQL'
CREATE FUNCTION enforce_existing_business_location_hierarchy() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE province_parent uuid; district_parent uuid; post_parent uuid;
BEGIN
IF NEW.province_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM geo_locations WHERE id=NEW.province_id AND location_type='province' AND deleted_at IS NULL) THEN RAISE EXCEPTION 'Invalid province reference'; END IF;
IF NEW.district_id IS NOT NULL THEN
SELECT parent_id INTO province_parent FROM geo_locations WHERE id=NEW.district_id AND location_type='district' AND deleted_at IS NULL;
IF province_parent IS NULL OR (NEW.province_id IS NOT NULL AND province_parent<>NEW.province_id) THEN RAISE EXCEPTION 'Invalid district/province relationship'; END IF;
END IF;
IF NEW.admin_post_id IS NOT NULL THEN
SELECT parent_id INTO district_parent FROM geo_locations WHERE id=NEW.admin_post_id AND location_type='admin_post' AND deleted_at IS NULL;
IF district_parent IS NULL OR (NEW.district_id IS NOT NULL AND district_parent<>NEW.district_id) THEN RAISE EXCEPTION 'Invalid administrative post/district relationship'; END IF;
END IF;
IF NEW.locality_id IS NOT NULL THEN
SELECT parent_id INTO post_parent FROM geo_locations WHERE id=NEW.locality_id AND location_type='locality' AND deleted_at IS NULL;
IF post_parent IS NULL OR (NEW.admin_post_id IS NOT NULL AND post_parent<>NEW.admin_post_id) THEN RAISE EXCEPTION 'Invalid locality/administrative post relationship'; END IF;
END IF;
RETURN NEW;
END $$;
CREATE TRIGGER existing_business_locations_hierarchy_trigger BEFORE INSERT OR UPDATE OF province_id,district_id,admin_post_id,locality_id ON existing_business_locations FOR EACH ROW EXECUTE FUNCTION enforce_existing_business_location_hierarchy();
SQL);
}
private function createBusinessRights(): void
{
Schema::create('existing_business_rights', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('existing_business_id')->constrained('existing_businesses')->restrictOnDelete();
$table->foreignUuid('business_object_id')->nullable()->constrained('existing_business_objects')->restrictOnDelete();
$table->string('right_type', 50);
$table->string('reference', 120)->nullable();
$table->string('issuer', 180)->nullable();
$table->date('valid_from')->nullable();
$table->date('valid_until')->nullable();
$table->timestampTz('verified_at')->nullable();
$table->text('confidential_payload')->nullable();
$table->timestampsTz();
});
DB::statement('ALTER TABLE existing_business_rights ADD CONSTRAINT existing_business_rights_valid_dates_check CHECK (valid_until IS NULL OR valid_from IS NULL OR valid_until >= valid_from)');
DB::statement('CREATE INDEX existing_business_rights_business_idx ON existing_business_rights(existing_business_id)');
}
private function createBusinessDocumentLinks(): void
{
Schema::create('existing_business_document_links', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('existing_business_id')->nullable()->constrained('existing_businesses')->restrictOnDelete();
$table->foreignId('interest_request_id')->nullable()->constrained('interest_requests')->restrictOnDelete();
$table->foreignUuid('document_id')->constrained('documents')->restrictOnDelete();
$table->foreignId('uploaded_by')->nullable()->constrained('users')->nullOnDelete();
$table->timestampsTz();
$table->unique(['existing_business_id', 'document_id'], 'existing_business_document_uq');
$table->unique(['interest_request_id', 'document_id'], 'interest_request_document_uq');
});
DB::statement('ALTER TABLE existing_business_document_links ADD CONSTRAINT existing_business_document_target_check CHECK (num_nonnulls(existing_business_id, interest_request_id)=1)');
}
private function createWorkflowTransitions(): void
{
Schema::create('business_workflow_transitions', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('existing_business_id')->nullable()->constrained('existing_businesses')->restrictOnDelete();
$table->foreignId('interest_request_id')->nullable()->constrained('interest_requests')->restrictOnDelete();
$table->string('from_status', 40)->nullable();
$table->string('to_status', 40);
$table->foreignId('actor_id')->nullable()->constrained('users')->nullOnDelete();
$table->text('reason')->nullable();
$table->uuid('correlation_id');
$table->jsonb('metadata')->default('{}');
$table->timestampTz('created_at')->useCurrent();
});
DB::statement('ALTER TABLE business_workflow_transitions ADD CONSTRAINT business_workflow_transition_target_check CHECK (num_nonnulls(existing_business_id, interest_request_id)=1)');
DB::statement('CREATE INDEX business_workflow_history_idx ON business_workflow_transitions(existing_business_id,created_at) WHERE existing_business_id IS NOT NULL');
DB::statement('CREATE INDEX interest_workflow_history_idx ON business_workflow_transitions(interest_request_id,created_at) WHERE interest_request_id IS NOT NULL');
}
private function createExternalRecordLinks(): void
{
Schema::create('external_record_links', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('existing_business_id')->nullable()->constrained('existing_businesses')->restrictOnDelete();
$table->foreignId('interest_request_id')->nullable()->constrained('interest_requests')->restrictOnDelete();
$table->foreignUuid('investor_id')->nullable()->constrained('investors')->restrictOnDelete();
$table->string('crm_system', 40);
$table->string('remote_id', 120);
$table->timestampTz('last_synced_at')->nullable();
$table->char('sync_hash', 64)->nullable();
$table->timestampsTz();
$table->unique(['crm_system', 'remote_id']);
});
DB::statement('ALTER TABLE external_record_links ADD CONSTRAINT external_record_target_check CHECK (num_nonnulls(existing_business_id, interest_request_id, investor_id)=1)');
DB::statement('CREATE UNIQUE INDEX external_record_business_crm_uq ON external_record_links(existing_business_id,crm_system) WHERE existing_business_id IS NOT NULL');
DB::statement('CREATE UNIQUE INDEX external_record_interest_crm_uq ON external_record_links(interest_request_id,crm_system) WHERE interest_request_id IS NOT NULL');
DB::statement('CREATE UNIQUE INDEX external_record_investor_crm_uq ON external_record_links(investor_id,crm_system) WHERE investor_id IS NOT NULL');
DB::statement(<<<'SQL'
ALTER TABLE external_record_links ADD CONSTRAINT external_record_sync_hash_check CHECK (sync_hash IS NULL OR sync_hash ~ '^[0-9a-f]{64}$')
SQL);
}
private function refuseRollbackWithData(): void
{
foreach (['existing_business_locations', 'existing_business_rights', 'existing_business_document_links', 'business_workflow_transitions', 'external_record_links'] as $table) {
if (DB::table($table)->exists()) {
throw new RuntimeException('Marketplace extension contains data; reconcile records before rollback.');
}
}
if (DB::table('existing_businesses')->whereIn('status', array_diff(self::BUSINESS_STATUSES, ['draft', 'submitted', 'in_review', 'needs_information', 'withdrawn']))->exists()
|| DB::table('existing_businesses')->where(function ($query) {
$query->whereNotNull('public_title')->orWhereNotNull('public_slug')->orWhereNotNull('activity_code')->orWhereNotNull('stage')->orWhereNotNull('objective')
->orWhereNotNull('currency')->orWhereNotNull('amount_min')->orWhereNotNull('amount_max')->orWhereNotNull('available_percentage')
->orWhereNotNull('funds_use')->orWhereNotNull('submitted_at')->orWhereNotNull('published_at')->orWhereNotNull('expires_at')
->orWhereNotNull('next_action')->orWhereNotNull('next_action_due_at')->orWhereNotNull('assigned_to');
})->exists()
|| DB::table('interest_requests')->where(function ($query) {
$query->whereNotNull('existing_business_id')->orWhereNotNull('investor_id')->orWhereNotNull('modality')
->orWhereNotNull('requested_percentage')->orWhereNotNull('ticket_min')->orWhereNotNull('ticket_max')
->orWhereNotNull('ticket_currency')->orWhereNotNull('assigned_to')->orWhereNotNull('next_action')->orWhereNotNull('next_action_due_at');
})->exists()
|| DB::table('documents')->where(function ($query) {
$query->whereNotNull('size_bytes')->orWhereNotNull('issuer')->orWhereNotNull('issued_on')->orWhereNotNull('valid_until')->orWhereNotNull('uploaded_by');
})->exists()
|| DB::table('tasks')->where(function ($query) {
$query->whereNotNull('existing_business_id')->orWhereNotNull('interest_request_id')->orWhereNotNull('task_type')
->orWhere('priority', '<>', 3)->orWhereNotNull('completed_at')->orWhereNotNull('outcome');
})->exists()
|| DB::table('outbox_events')->where(function ($query) {
$query->whereNotNull('idempotency_key')->orWhere('attempts', '<>', 0)->orWhereNotNull('failed_at')->orWhereNotNull('last_error');
})->exists()
|| DB::table('investors')->where(function ($query) {
$query->whereNotNull('investment_sectors')->orWhereNotNull('investment_geographies')->orWhereNotNull('investment_strategy')
->orWhereNotNull('investment_horizon_months')->orWhereNotNull('ticket_min')->orWhereNotNull('ticket_max')->orWhereNotNull('ticket_currency');
})->exists()
|| DB::table('existing_business_objects')->where(function ($query) {
$query->whereNotNull('asset_type')->orWhereNotNull('area')->orWhereNotNull('area_unit')->orWhereNotNull('occupancy_status')->orWhereNotNull('condition_status');
})->exists()
|| DB::table('consents')->where(function ($query) {
$query->whereNotNull('opportunity_id')->orWhereNotNull('existing_business_id')->orWhereNotNull('interest_request_id')
->orWhereNotNull('policy_version')->orWhereNotNull('technical_fingerprint_hash');
})->exists()) {
throw new RuntimeException('Marketplace extension fields contain data; reconcile records before rollback.');
}
}
};
@@ -0,0 +1,131 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('Reference catalogs require PostgreSQL.');
}
Schema::create('reference_catalog_versions', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('catalog_code', 60);
$table->unsignedInteger('version_no');
$table->string('locale', 10)->default('pt-MZ');
$table->string('source_system', 100);
$table->string('source_version', 100);
$table->text('source_reference');
$table->char('source_sha256', 64)->nullable();
$table->date('valid_from')->nullable();
$table->date('valid_to')->nullable();
$table->string('status', 16)->default('draft');
$table->timestampsTz();
$table->unique(['catalog_code', 'version_no', 'locale'], 'reference_catalog_version_uq');
$table->index(['catalog_code', 'status', 'valid_from', 'valid_to'], 'reference_catalog_current_idx');
});
DB::statement("ALTER TABLE reference_catalog_versions ADD CONSTRAINT reference_catalog_version_check CHECK (version_no > 0 AND (valid_to IS NULL OR valid_from IS NULL OR valid_to > valid_from) AND status IN ('draft','published','retired') AND (source_sha256 IS NULL OR source_sha256 ~ '^[0-9a-f]{64}$'))");
DB::statement("CREATE UNIQUE INDEX reference_catalog_one_published_uq ON reference_catalog_versions(catalog_code, locale) WHERE status='published'");
Schema::create('authorities', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('catalog_version_id')->constrained('reference_catalog_versions')->restrictOnDelete();
$table->foreignUuid('organization_id')->constrained('organizations')->restrictOnDelete();
$table->foreignUuid('jurisdiction_id')->nullable()->constrained('geo_locations')->restrictOnDelete();
$table->string('code', 100);
$table->string('authority_type', 60);
$table->string('label_pt_mz', 255);
$table->text('source_reference');
$table->unsignedInteger('version_no')->default(1);
$table->date('valid_from');
$table->date('valid_to')->nullable();
$table->string('status', 16)->default('draft');
$table->timestampsTz();
$table->unique(['catalog_version_id', 'code'], 'authorities_catalog_code_uq');
$table->index(['jurisdiction_id', 'status', 'valid_from', 'valid_to'], 'authorities_jurisdiction_status_idx');
$table->index(['authority_type', 'status'], 'authorities_type_status_idx');
});
DB::statement('ALTER TABLE authorities ADD CONSTRAINT authorities_check CHECK (version_no > 0 AND (valid_to IS NULL OR valid_to > valid_from))');
DB::statement("ALTER TABLE authorities ADD CONSTRAINT authorities_status_check CHECK (status IN ('draft','published','retired'))");
Schema::create('economic_activities', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('catalog_version_id')->constrained('reference_catalog_versions')->restrictOnDelete();
$table->uuid('parent_id')->nullable();
$table->foreignId('sector_id')->constrained('sectors')->restrictOnDelete();
$table->string('code', 100);
$table->string('label_pt_mz', 255);
$table->text('description_pt_mz')->nullable();
$table->unsignedInteger('version_no')->default(1);
$table->date('valid_from');
$table->date('valid_to')->nullable();
$table->string('status', 16)->default('published');
$table->timestampsTz();
$table->unique(['catalog_version_id', 'code'], 'economic_activities_catalog_code_uq');
$table->unique(['catalog_version_id', 'id'], 'economic_activities_version_id_uq');
$table->unique('sector_id', 'economic_activities_sector_uq');
$table->index(['parent_id', 'status', 'label_pt_mz'], 'economic_activities_parent_status_idx');
$table->index(['status', 'valid_from', 'valid_to'], 'economic_activities_validity_idx');
});
DB::statement('ALTER TABLE economic_activities ADD CONSTRAINT economic_activities_parent_same_version_fk FOREIGN KEY (catalog_version_id, parent_id) REFERENCES economic_activities(catalog_version_id, id) ON DELETE RESTRICT');
DB::statement('ALTER TABLE economic_activities ADD CONSTRAINT economic_activities_check CHECK (version_no > 0 AND (valid_to IS NULL OR valid_to > valid_from))');
DB::statement("ALTER TABLE economic_activities ADD CONSTRAINT economic_activities_status_check CHECK (status IN ('draft','published','retired'))");
DB::unprepared(<<<'SQL'
CREATE OR REPLACE FUNCTION public.investmoz_guard_reference_catalog_mutation() RETURNS trigger
LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$
BEGIN
IF TG_OP = 'DELETE' AND OLD.status = 'published' THEN
RAISE EXCEPTION 'Published reference catalog entries are immutable' USING ERRCODE = '42501';
END IF;
IF TG_OP = 'UPDATE' AND OLD.status = 'published' THEN
IF NEW.status <> 'retired'
OR NEW.valid_to IS NULL
OR (to_jsonb(NEW) - ARRAY['status','valid_to','updated_at'])
IS DISTINCT FROM
(to_jsonb(OLD) - ARRAY['status','valid_to','updated_at']) THEN
RAISE EXCEPTION 'Published reference catalog entries are immutable; publish a new version' USING ERRCODE = '42501';
END IF;
END IF;
IF TG_OP = 'DELETE' THEN
RETURN OLD;
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER reference_catalog_version_immutable BEFORE UPDATE OR DELETE ON public.reference_catalog_versions
FOR EACH ROW EXECUTE FUNCTION public.investmoz_guard_reference_catalog_mutation();
CREATE TRIGGER authority_catalog_entry_immutable BEFORE UPDATE OR DELETE ON public.authorities
FOR EACH ROW EXECUTE FUNCTION public.investmoz_guard_reference_catalog_mutation();
CREATE TRIGGER economic_activity_catalog_entry_immutable BEFORE UPDATE OR DELETE ON public.economic_activities
FOR EACH ROW EXECUTE FUNCTION public.investmoz_guard_reference_catalog_mutation();
SQL);
}
public function down(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('Reference catalog rollback requires PostgreSQL.');
}
if (Schema::hasTable('authorities') && DB::table('authorities')->exists()) {
throw new RuntimeException('Authority references exist; preserve them before rolling back reference catalogs.');
}
if (Schema::hasTable('economic_activities') && DB::table('economic_activities')->exists()) {
throw new RuntimeException('Economic activities exist; preserve them before rolling back reference catalogs.');
}
Schema::dropIfExists('economic_activities');
Schema::dropIfExists('authorities');
Schema::dropIfExists('reference_catalog_versions');
DB::statement('DROP FUNCTION IF EXISTS public.investmoz_guard_reference_catalog_mutation() RESTRICT');
}
};
@@ -0,0 +1,220 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
private const TABLES = [
'simulation_audit_events', 'simulation_idempotency', 'simulation_jobs', 'simulation_reports',
'simulation_obligations', 'simulation_result_sources', 'simulation_results', 'simulation_scenarios',
'simulations', 'questionnaire_versions',
];
public function up(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('Simulation execution requires PostgreSQL.');
}
DB::unprepared(<<<'SQL'
CREATE TABLE public.questionnaire_versions (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
code text NOT NULL,
version_no integer NOT NULL CHECK (version_no > 0),
locale text NOT NULL DEFAULT 'pt-MZ',
schema_snapshot jsonb NOT NULL,
status text NOT NULL DEFAULT 'draft' CHECK (status IN ('draft','published','retired')),
valid_from date,
valid_to date,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (code, version_no, locale),
CHECK (valid_to IS NULL OR valid_from IS NULL OR valid_to > valid_from)
);
INSERT INTO public.questionnaire_versions (id, code, version_no, locale, schema_snapshot, status, valid_from)
VALUES ('61000100-0000-4000-8000-000000000001', 'user-entered-arithmetic', 1, 'pt-MZ',
'{"inputs":{"base":{"type":"decimal","minimum":0},"rate":{"type":"decimal","minimum":0,"maximum":100},"reduction":{"type":"decimal","minimum":0,"maximum":100,"default":0}},"rate_origin":"user_input","currency":null}'::jsonb,
'published', DATE '2026-10-01');
CREATE TABLE public.simulations (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
questionnaire_version_id uuid REFERENCES public.questionnaire_versions(id) ON DELETE RESTRICT,
owner_user_id bigint REFERENCES public.users(id) ON DELETE RESTRICT,
organization_id uuid REFERENCES public.organizations(id) ON DELETE RESTRICT,
anonymous_token_hash char(64),
version_no integer NOT NULL DEFAULT 1 CHECK (version_no > 0),
status text NOT NULL DEFAULT 'queued' CHECK (status IN ('queued','running','completed','failed','cancelled')),
input_snapshot jsonb NOT NULL,
result_snapshot jsonb,
calculation_snapshot jsonb,
error_code text,
deleted_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
CHECK ((owner_user_id IS NOT NULL)::integer + (anonymous_token_hash IS NOT NULL)::integer = 1),
CHECK (anonymous_token_hash IS NULL OR anonymous_token_hash ~ '^[0-9a-f]{64}$')
);
CREATE INDEX simulations_owner_created_idx ON public.simulations(owner_user_id, created_at DESC) WHERE deleted_at IS NULL;
CREATE INDEX simulations_org_created_idx ON public.simulations(organization_id, created_at DESC) WHERE deleted_at IS NULL;
CREATE TABLE public.simulation_scenarios (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
simulation_id uuid NOT NULL REFERENCES public.simulations(id) ON DELETE CASCADE,
code text NOT NULL,
label text NOT NULL,
version_no integer NOT NULL DEFAULT 1 CHECK (version_no > 0),
parameters jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (simulation_id, code)
);
CREATE TABLE public.simulation_results (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
simulation_id uuid NOT NULL REFERENCES public.simulations(id) ON DELETE CASCADE,
scenario_id uuid NOT NULL REFERENCES public.simulation_scenarios(id) ON DELETE RESTRICT,
engine_version text NOT NULL,
result_snapshot jsonb NOT NULL,
result_sha256 char(64) NOT NULL CHECK (result_sha256 ~ '^[0-9a-f]{64}$'),
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (scenario_id, engine_version)
);
CREATE TABLE public.simulation_result_sources (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
result_id uuid NOT NULL REFERENCES public.simulation_results(id) ON DELETE CASCADE,
source_type text NOT NULL,
source_id text NOT NULL,
source_version text NOT NULL,
source_snapshot jsonb NOT NULL,
source_sha256 char(64) NOT NULL CHECK (source_sha256 ~ '^[0-9a-f]{64}$'),
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (result_id, source_type, source_id, source_version)
);
CREATE TABLE public.simulation_obligations (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
simulation_id uuid NOT NULL REFERENCES public.simulations(id) ON DELETE CASCADE,
scenario_id uuid REFERENCES public.simulation_scenarios(id) ON DELETE RESTRICT,
code text NOT NULL,
label text NOT NULL,
source_reference text,
source_version text,
status text NOT NULL DEFAULT 'indicative' CHECK (status IN ('indicative','confirmed','dismissed')),
snapshot jsonb NOT NULL DEFAULT '{}'::jsonb,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (simulation_id, code)
);
CREATE TABLE public.simulation_reports (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
simulation_id uuid NOT NULL REFERENCES public.simulations(id) ON DELETE CASCADE,
version_no integer NOT NULL DEFAULT 1 CHECK (version_no > 0),
status text NOT NULL DEFAULT 'queued' CHECK (status IN ('queued','ready','failed')),
report_snapshot jsonb,
report_sha256 char(64),
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
CHECK (report_sha256 IS NULL OR report_sha256 ~ '^[0-9a-f]{64}$'),
UNIQUE (simulation_id, version_no)
);
CREATE TABLE public.simulation_jobs (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
simulation_id uuid NOT NULL REFERENCES public.simulations(id) ON DELETE CASCADE,
job_type text NOT NULL CHECK (job_type IN ('execute','report')),
status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','running','succeeded','failed')),
attempts smallint NOT NULL DEFAULT 0 CHECK (attempts BETWEEN 0 AND 3),
available_at timestamptz NOT NULL DEFAULT now(),
started_at timestamptz,
finished_at timestamptz,
error_code text,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (simulation_id, job_type)
);
CREATE TABLE public.simulation_idempotency (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
scope_hash char(64) NOT NULL CHECK (scope_hash ~ '^[0-9a-f]{64}$'),
key_hash char(64) NOT NULL CHECK (key_hash ~ '^[0-9a-f]{64}$'),
payload_hash char(64) NOT NULL CHECK (payload_hash ~ '^[0-9a-f]{64}$'),
simulation_id uuid REFERENCES public.simulations(id) ON DELETE RESTRICT,
response_snapshot jsonb,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (scope_hash, key_hash)
);
CREATE TABLE public.simulation_audit_events (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
simulation_id uuid NOT NULL REFERENCES public.simulations(id) ON DELETE RESTRICT,
actor_user_id bigint REFERENCES public.users(id) ON DELETE RESTRICT,
action text NOT NULL,
correlation_id uuid NOT NULL,
data jsonb NOT NULL DEFAULT '{}'::jsonb,
occurred_at timestamptz NOT NULL DEFAULT now()
);
CREATE OR REPLACE FUNCTION public.investmoz_reject_simulation_audit_change() RETURNS trigger
LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$
BEGIN RAISE EXCEPTION 'Simulation audit is append-only' USING ERRCODE = '42501'; END;
$$;
CREATE TRIGGER simulation_audit_immutable BEFORE UPDATE OR DELETE ON public.simulation_audit_events FOR EACH ROW EXECUTE FUNCTION public.investmoz_reject_simulation_audit_change();
CREATE OR REPLACE FUNCTION public.investmoz_reject_simulation_snapshot_change() RETURNS trigger
LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$
BEGIN RAISE EXCEPTION 'Published simulation snapshots are immutable' USING ERRCODE = '42501'; END;
$$;
CREATE TRIGGER questionnaire_version_immutable BEFORE UPDATE OR DELETE ON public.questionnaire_versions FOR EACH ROW
WHEN (OLD.status = 'published') EXECUTE FUNCTION public.investmoz_reject_simulation_snapshot_change();
CREATE TRIGGER simulation_result_immutable BEFORE UPDATE OR DELETE ON public.simulation_results FOR EACH ROW EXECUTE FUNCTION public.investmoz_reject_simulation_snapshot_change();
CREATE TRIGGER simulation_result_source_immutable BEFORE UPDATE OR DELETE ON public.simulation_result_sources FOR EACH ROW EXECUTE FUNCTION public.investmoz_reject_simulation_snapshot_change();
CREATE TRIGGER simulation_report_immutable BEFORE UPDATE OR DELETE ON public.simulation_reports FOR EACH ROW
WHEN (OLD.status = 'ready') EXECUTE FUNCTION public.investmoz_reject_simulation_snapshot_change();
SQL);
$tables = array_diff(self::TABLES, ['simulations', 'simulation_audit_events', 'simulation_idempotency', 'questionnaire_versions']);
foreach ($tables as $table) {
$simulationId = $table === 'simulation_result_sources'
? '(SELECT parent.simulation_id FROM public.simulation_results parent WHERE parent.id = result_id)'
: ($table === 'simulations' ? 'id' : 'simulation_id');
$readAccess = "EXISTS (SELECT 1 FROM public.simulations s WHERE s.id = {$simulationId} AND ((s.organization_id IS NULL AND s.owner_user_id IS NOT NULL AND s.owner_user_id = NULLIF(current_setting('app.actor_user_id', true), '')::bigint) OR (s.organization_id IS NOT NULL AND EXISTS (SELECT 1 FROM public.memberships m WHERE m.organization_id = s.organization_id AND m.user_id = NULLIF(current_setting('app.actor_user_id', true), '')::bigint AND m.deleted_at IS NULL)) OR (s.anonymous_token_hash IS NOT NULL AND s.anonymous_token_hash = NULLIF(current_setting('app.simulation_token_hash', true), ''))))";
$writeAccess = "EXISTS (SELECT 1 FROM public.simulations s WHERE s.id = {$simulationId} AND ((s.organization_id IS NULL AND s.owner_user_id IS NOT NULL AND s.owner_user_id = NULLIF(current_setting('app.actor_user_id', true), '')::bigint) OR (s.organization_id IS NOT NULL AND EXISTS (SELECT 1 FROM public.memberships m WHERE m.organization_id = s.organization_id AND m.user_id = NULLIF(current_setting('app.actor_user_id', true), '')::bigint AND m.deleted_at IS NULL AND m.role IN ('admin','manager','officer'))) OR (s.anonymous_token_hash IS NOT NULL AND s.anonymous_token_hash = NULLIF(current_setting('app.simulation_token_hash', true), ''))) )";
DB::statement("ALTER TABLE public.{$table} ENABLE ROW LEVEL SECURITY");
DB::statement("ALTER TABLE public.{$table} FORCE ROW LEVEL SECURITY");
DB::statement("CREATE POLICY {$table}_read_policy ON public.{$table} FOR SELECT USING ({$readAccess})");
DB::statement("CREATE POLICY {$table}_write_policy ON public.{$table} FOR ALL USING ({$writeAccess}) WITH CHECK ({$writeAccess})");
}
foreach (['simulation_idempotency', 'simulation_audit_events'] as $table) {
DB::statement("ALTER TABLE public.{$table} ENABLE ROW LEVEL SECURITY");
DB::statement("ALTER TABLE public.{$table} FORCE ROW LEVEL SECURITY");
}
DB::statement('ALTER TABLE public.simulations ENABLE ROW LEVEL SECURITY');
DB::statement('ALTER TABLE public.simulations FORCE ROW LEVEL SECURITY');
DB::statement("CREATE POLICY simulations_read_policy ON public.simulations FOR SELECT USING (((organization_id IS NULL AND owner_user_id IS NOT NULL AND owner_user_id = NULLIF(current_setting('app.actor_user_id', true), '')::bigint) OR (organization_id IS NOT NULL AND EXISTS (SELECT 1 FROM public.memberships m WHERE m.organization_id = simulations.organization_id AND m.user_id = NULLIF(current_setting('app.actor_user_id', true), '')::bigint AND m.deleted_at IS NULL)) OR (anonymous_token_hash IS NOT NULL AND anonymous_token_hash = NULLIF(current_setting('app.simulation_token_hash', true), ''))) AND deleted_at IS NULL)");
$simulationWrite = "((organization_id IS NULL AND owner_user_id IS NOT NULL AND owner_user_id = NULLIF(current_setting('app.actor_user_id', true), '')::bigint) OR (organization_id IS NOT NULL AND EXISTS (SELECT 1 FROM public.memberships m WHERE m.organization_id = simulations.organization_id AND m.user_id = NULLIF(current_setting('app.actor_user_id', true), '')::bigint AND m.deleted_at IS NULL AND m.role IN ('admin','manager','officer'))) OR (anonymous_token_hash IS NOT NULL AND anonymous_token_hash = NULLIF(current_setting('app.simulation_token_hash', true), '')))";
DB::statement("CREATE POLICY simulations_write_policy ON public.simulations FOR ALL USING ({$simulationWrite}) WITH CHECK ({$simulationWrite})");
DB::statement('ALTER TABLE public.questionnaire_versions ENABLE ROW LEVEL SECURITY');
DB::statement('ALTER TABLE public.questionnaire_versions FORCE ROW LEVEL SECURITY');
DB::statement("CREATE POLICY questionnaire_published_read ON public.questionnaire_versions FOR SELECT USING (status = 'published')");
DB::statement("CREATE POLICY simulation_idempotency_actor ON public.simulation_idempotency USING (scope_hash = encode(digest(COALESCE(NULLIF(current_setting('app.actor_user_id', true), ''), NULLIF(current_setting('app.simulation_token_hash', true), ''), 'anonymous'), 'sha256'), 'hex')) WITH CHECK (scope_hash = encode(digest(COALESCE(NULLIF(current_setting('app.actor_user_id', true), ''), NULLIF(current_setting('app.simulation_token_hash', true), ''), 'anonymous'), 'sha256'), 'hex'))");
DB::statement("CREATE POLICY simulation_audit_read ON public.simulation_audit_events FOR SELECT USING (EXISTS (SELECT 1 FROM public.simulations s WHERE s.id = simulation_id AND s.owner_user_id = NULLIF(current_setting('app.actor_user_id', true), '')::bigint))");
DB::statement("CREATE POLICY simulation_audit_insert ON public.simulation_audit_events FOR INSERT WITH CHECK (actor_user_id IS NOT DISTINCT FROM NULLIF(current_setting('app.actor_user_id', true), '')::bigint AND EXISTS (SELECT 1 FROM public.simulations s WHERE s.id = simulation_id AND ((s.organization_id IS NULL AND s.owner_user_id IS NOT NULL AND s.owner_user_id = NULLIF(current_setting('app.actor_user_id', true), '')::bigint) OR (s.organization_id IS NOT NULL AND EXISTS (SELECT 1 FROM public.memberships m WHERE m.organization_id = s.organization_id AND m.user_id = NULLIF(current_setting('app.actor_user_id', true), '')::bigint AND m.deleted_at IS NULL AND m.role IN ('admin','manager','officer'))) OR (s.anonymous_token_hash IS NOT NULL AND s.anonymous_token_hash = NULLIF(current_setting('app.simulation_token_hash', true), '')))))");
}
public function down(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('Simulation execution rollback requires PostgreSQL.');
}
foreach (self::TABLES as $table) {
if (Schema::hasTable($table)) {
DB::statement("ALTER TABLE public.{$table} DISABLE ROW LEVEL SECURITY");
$query = DB::table($table);
if ($table === 'questionnaire_versions') {
$query->where('id', '<>', '61000100-0000-4000-8000-000000000001');
}
if ($query->exists()) {
throw new RuntimeException("Cannot rollback simulation execution: {$table} contains data.");
}
}
}
foreach (self::TABLES as $table) {
Schema::dropIfExists($table);
}
DB::statement('DROP FUNCTION IF EXISTS public.investmoz_reject_simulation_audit_change() RESTRICT');
DB::statement('DROP FUNCTION IF EXISTS public.investmoz_reject_simulation_snapshot_change() RESTRICT');
}
};
@@ -0,0 +1,60 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('Simulation form drafts require PostgreSQL.');
}
DB::unprepared(<<<'SQL'
CREATE TABLE public.simulation_form_drafts (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
owner_user_id bigint REFERENCES public.users(id) ON DELETE RESTRICT,
anonymous_token_hash char(64),
version_no integer NOT NULL DEFAULT 1 CHECK (version_no > 0),
create_key_hash char(64) NOT NULL CHECK (create_key_hash ~ '^[0-9a-f]{64}$'),
create_payload_hash char(64) NOT NULL CHECK (create_payload_hash ~ '^[0-9a-f]{64}$'),
snapshot_sha256 char(64) NOT NULL CHECK (snapshot_sha256 ~ '^[0-9a-f]{64}$'),
personal_snapshot text NOT NULL,
economic_snapshot text NOT NULL,
deleted_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
CHECK ((owner_user_id IS NOT NULL)::integer + (anonymous_token_hash IS NOT NULL)::integer = 1),
CHECK (anonymous_token_hash IS NULL OR anonymous_token_hash ~ '^[0-9a-f]{64}$')
);
CREATE UNIQUE INDEX simulation_form_drafts_owner_active_unique ON public.simulation_form_drafts(owner_user_id)
WHERE owner_user_id IS NOT NULL AND deleted_at IS NULL;
CREATE UNIQUE INDEX simulation_form_drafts_token_active_unique ON public.simulation_form_drafts(anonymous_token_hash)
WHERE anonymous_token_hash IS NOT NULL AND deleted_at IS NULL;
ALTER TABLE public.simulation_form_drafts ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.simulation_form_drafts FORCE ROW LEVEL SECURITY;
CREATE POLICY simulation_form_drafts_read ON public.simulation_form_drafts FOR SELECT
USING (deleted_at IS NULL AND ((owner_user_id IS NOT NULL AND owner_user_id = NULLIF(current_setting('app.actor_user_id', true), '')::bigint)
OR (anonymous_token_hash IS NOT NULL AND anonymous_token_hash = NULLIF(current_setting('app.simulation_token_hash', true), ''))));
CREATE POLICY simulation_form_drafts_write ON public.simulation_form_drafts FOR ALL
USING (deleted_at IS NULL AND ((owner_user_id IS NOT NULL AND owner_user_id = NULLIF(current_setting('app.actor_user_id', true), '')::bigint)
OR (anonymous_token_hash IS NOT NULL AND anonymous_token_hash = NULLIF(current_setting('app.simulation_token_hash', true), ''))))
WITH CHECK ((owner_user_id IS NOT NULL AND owner_user_id = NULLIF(current_setting('app.actor_user_id', true), '')::bigint)
OR (anonymous_token_hash IS NOT NULL AND anonymous_token_hash = NULLIF(current_setting('app.simulation_token_hash', true), '')));
SQL);
}
public function down(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('Simulation form draft rollback requires PostgreSQL.');
}
DB::statement('ALTER TABLE public.simulation_form_drafts DISABLE ROW LEVEL SECURITY');
if (DB::table('simulation_form_drafts')->exists()) {
throw new RuntimeException('Cannot rollback simulation form drafts while draft data exists.');
}
Schema::dropIfExists('simulation_form_drafts');
}
};
+1 -13
View File
@@ -2,11 +2,8 @@
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
class DatabaseSeeder extends Seeder
{
@@ -24,15 +21,6 @@ class DatabaseSeeder extends Seeder
}
$this->call(InvestMozReferenceSeeder::class);
// User::factory(10)->create();
User::firstOrCreate(
['email' => 'test@example.com'],
[
'name' => 'Test User',
'password' => Hash::make(Str::random(48)),
],
);
$this->call(LocalTestUserSeeder::class);
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Seeder;
class LocalTestUserSeeder extends Seeder
{
/**
* Create or reset the documented local development account.
*/
public function run(): void
{
if (! app()->environment(['local', 'testing'])) {
return;
}
$user = User::firstOrNew(['email' => 'test@example.com']);
$user->forceFill([
'name' => 'Test User',
'password' => 'password',
'email_verified_at' => now(),
'two_factor_secret' => null,
'two_factor_recovery_codes' => null,
'two_factor_confirmed_at' => null,
])->save();
}
}
@@ -14,6 +14,7 @@ class ProductionReferenceSeeder extends Seeder
InvestmentAreaSeeder::class,
InvestmentReferenceSeeder::class,
TerritoryReferenceSeeder::class,
ReferenceCatalogSeeder::class,
InvestmentPortfolioSeeder::class,
]);
}
+128
View File
@@ -0,0 +1,128 @@
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use RuntimeException;
class ReferenceCatalogSeeder extends Seeder
{
private const CATALOG_IDS = [
'authorities' => 'a1000000-0000-4000-8000-000000000001',
'jurisdictions' => 'a1000000-0000-4000-8000-000000000002',
'economic-activities' => 'a1000000-0000-4000-8000-000000000003',
];
/** @var array<string,string> */
private const ACTIVITY_IDS = [
'agronegocio' => 'a2000000-0000-4000-8000-000000000001',
'energia' => 'a2000000-0000-4000-8000-000000000002',
'turismo' => 'a2000000-0000-4000-8000-000000000003',
'infraestruturas' => 'a2000000-0000-4000-8000-000000000004',
'economia-azul' => 'a2000000-0000-4000-8000-000000000005',
'mercado-financeiro' => 'a2000000-0000-4000-8000-000000000006',
];
public function run(): void
{
$territory = json_decode(File::get(database_path('data/territory-locations.json')), true, 512, JSON_THROW_ON_ERROR);
if (! is_array($territory) || ! is_array($territory['records'] ?? null) || ! is_int($territory['source_version'] ?? null)) {
throw new RuntimeException('Territorial catalog source is malformed.');
}
if (! is_string($territory['records_sha256'] ?? null)
|| ! hash_equals($territory['records_sha256'], hash('sha256', json_encode($territory['records'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)))
|| DB::table('geo_locations')->where('source_system', 'cartografia-workbook')->where('data_classification', 'public')->count() !== count($territory['records'])) {
throw new RuntimeException('Territorial catalog version does not match its verified seed records.');
}
DB::transaction(function () use ($territory): void {
DB::select('SELECT pg_advisory_xact_lock(20261001, 300100)');
$this->catalogVersion('authorities', 1, 'authority-register-pending-source', 'pending-authority-source',
'Awaiting an approved authority source; no institution or mandate is inferred.', null, null, 'draft');
$this->catalogVersion('jurisdictions', $territory['source_version'], 'cartografia-workbook', (string) $territory['source_version'],
'database/data/territory-locations.json', $territory['source_sha256'], null, 'published');
$activities = DB::table('sectors')->whereIn('slug', array_keys(self::ACTIVITY_IDS))->orderBy('slug')->get(['id', 'name', 'slug']);
if ($activities->count() !== count(self::ACTIVITY_IDS)) {
throw new RuntimeException('The curated sector source is incomplete; economic activity seed aborted.');
}
$canonical = $activities->map(fn ($row) => ['code' => $row->slug, 'label_pt_mz' => $row->name])->values()->all();
$activityChecksum = hash('sha256', json_encode($canonical, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
$versionId = $this->catalogVersion('economic-activities', 1, 'investmoz-curated', 'sector-seeder-v1',
'database/seeders/SectorSeeder.php; seed is a portal grouping, not an official activity classification.',
$activityChecksum, '2026-10-01', 'published');
foreach ($activities as $activity) {
$expected = [
'id' => self::ACTIVITY_IDS[$activity->slug],
'catalog_version_id' => $versionId,
'parent_id' => null,
'sector_id' => $activity->id,
'code' => $activity->slug,
'label_pt_mz' => $activity->name,
'description_pt_mz' => null,
'version_no' => 1,
'valid_from' => '2026-10-01',
'valid_to' => null,
'status' => 'published',
];
$existing = DB::table('economic_activities')->where('catalog_version_id', $versionId)->where('code', $activity->slug)->first();
if ($existing) {
foreach ($expected as $column => $value) {
if ((string) $existing->{$column} !== (string) $value) {
throw new RuntimeException('Economic activity differs from its versioned seed: '.$activity->slug);
}
}
continue;
}
DB::table('economic_activities')->insert([...$expected, 'created_at' => now(), 'updated_at' => now()]);
}
});
}
private function catalogVersion(
string $code,
int $version,
string $source,
string $sourceVersion,
string $reference,
?string $checksum,
?string $validFrom,
string $status,
): string {
$id = self::CATALOG_IDS[$code];
$expected = [
'id' => $id,
'catalog_code' => $code,
'version_no' => $version,
'locale' => 'pt-MZ',
'source_system' => $source,
'source_version' => $sourceVersion,
'source_reference' => $reference,
'source_sha256' => $checksum,
'valid_from' => $validFrom,
'valid_to' => null,
'status' => $status,
];
$existing = DB::table('reference_catalog_versions')->where('catalog_code', $code)->where('version_no', $version)->where('locale', 'pt-MZ')->first();
if ($existing) {
foreach ($expected as $column => $value) {
if ((string) $existing->{$column} !== (string) $value) {
throw new RuntimeException('Reference catalog version differs from its packaged source: '.$code);
}
}
return $id;
}
DB::table('reference_catalog_versions')->insert([...$expected, 'created_at' => now(), 'updated_at' => now()]);
return $id;
}
}