commit 30/9
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-09-30 09:05:43 +02:00
parent 67dad461d9
commit 3dc7c5c649
75 changed files with 4123 additions and 107 deletions
@@ -0,0 +1,37 @@
<?php
namespace App\Console\Commands;
use App\Services\Mne\CompatibilityBackfill;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
final class BackfillMneCompatibility extends Command
{
protected $signature = 'mne:backfill-compatibility {--batch=100} {--dry-run : Execute validation and roll back all changes}';
protected $description = 'Reconcile compatibility identifiers without copying canonical business records';
public function handle(CompatibilityBackfill $backfill): int
{
$batch = filter_var($this->option('batch'), FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 1000]]);
if ($batch === false) {
$this->error('Batch must be between 1 and 1000');
return self::FAILURE;
}
if ($this->option('dry-run')) {
DB::beginTransaction();
try {
$counts = $backfill->run($batch);
} finally {
DB::rollBack();
}
$this->line(json_encode(['dry_run' => true, 'rolled_back' => true, 'counts' => $counts], JSON_THROW_ON_ERROR));
} else {
$this->line(json_encode($backfill->run($batch), JSON_THROW_ON_ERROR));
}
return self::SUCCESS;
}
}
@@ -0,0 +1,48 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
final class ReconcileMneCompatibility extends Command
{
protected $signature = 'mne:reconcile-compatibility {--fail-on-difference : Return failure while any reconciliation or activation gate remains open}';
protected $description = 'Read-only compatibility counts, fingerprints and activation blockers';
public function handle(): int
{
$report = DB::transaction(function (): array {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY');
$domains = [];
foreach (['identity' => ['users', 'identity_links', 'user_id'], 'sector' => ['sectors', 'sector_links', 'sector_id'],
'business' => ['existing_businesses', 'business_links', 'legacy_business_id']] as $domain => [$source, $target, $key]) {
$checksums = [];
$stale = 0;
$missing = 0;
foreach (DB::table('public.'.$source)->orderBy('id')->cursor() as $row) {
$checksum = hash('sha256', json_encode((array) $row, JSON_THROW_ON_ERROR));
$checksums[] = $checksum;
$link = DB::table('mne.'.$target)->where($key, $row->id)->first();
$missing += $link === null ? 1 : 0;
$stale += $link !== null && $link->source_checksum !== $checksum ? 1 : 0;
}
$domains[$domain] = ['source_count' => count($checksums), 'link_count' => DB::table('mne.'.$target)->count(),
'pending_count' => DB::table('mne.'.$target)->where('status', '<>', 'active')->count(),
'missing' => $missing, 'stale_checksums' => $stale, 'checksum' => hash('sha256', implode('', $checksums))];
}
$role = DB::selectOne('SELECT rolsuper,rolcreaterole FROM pg_roles WHERE rolname=current_user');
return ['domains' => $domains, 'unresolved_rejections' => DB::table('mne.compatibility_rejections')->whereNull('resolved_at')->count(),
'runtime_is_superuser' => (bool) $role->rolsuper, 'runtime_can_create_roles' => (bool) $role->rolcreaterole,
'canonical_reads_ready' => false, 'canonical_writes_ready' => false,
'blockers' => ['Full canonical response mapping and authorization parity not certified',
'Legacy intake does not capture a sector', 'Runtime privilege separation requires verification with deployment credentials']];
});
$this->line(json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
// This release has no certified canonical adapter: strict gate checks cannot succeed yet.
return $this->option('fail-on-difference') ? self::FAILURE : self::SUCCESS;
}
}
@@ -4,10 +4,14 @@ namespace App\Http\Controllers;
use App\Models\ExistingBusiness;
use App\Models\ExistingBusinessObject;
use App\Models\Sector;
use App\Services\BusinessFormSchema;
use App\Services\ExistingBusinessDrafts;
use App\Services\ExistingBusinessIntake;
use App\Services\ExistingBusinessObjects;
use App\Services\ExistingBusinessVerification;
use App\Services\Mne\BusinessRepository;
use App\Services\Mne\CompatibilityShadow;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
@@ -21,7 +25,7 @@ class ExistingBusinessController extends Controller
public function index(Request $request): Response|JsonResponse
{
$management = $request->is('management/*', 'api/v1/existing-business/review*');
$query = ExistingBusiness::query();
$query = app(BusinessRepository::class)->query();
if ($management) {
Gate::authorize('reviewQueue', ExistingBusiness::class);
$query->where('owner_user_id', '<>', $request->user()->id)->whereIn('status', ['submitted', 'in_review', 'needs_information']);
@@ -36,9 +40,10 @@ class ExistingBusinessController extends Controller
public function show(Request $request, string $id): Response|JsonResponse
{
$business = ExistingBusiness::findOrFail($id);
$business = app(BusinessRepository::class)->find($id);
Gate::authorize('view', $business);
$props = ['record' => $this->record($business), 'canEdit' => $request->user()->can('update', $business),
app(CompatibilityShadow::class)->schedule($id);
$props = ['sectors' => Sector::where('is_active', true)->orderBy('name')->get(['id', 'name']), 'formSchema' => BusinessFormSchema::fields(), 'record' => $this->record($business), 'canEdit' => $request->user()->can('update', $business),
'owner' => $request->user()->can('owns', $business), 'canReview' => $request->user()->can('review', $business),
'modalities' => ExistingBusinessDrafts::MODALITIES,
'objectKinds' => ExistingBusinessObjects::KINDS,
@@ -63,8 +68,8 @@ class ExistingBusinessController extends Controller
public function transition(Request $request, ExistingBusinessIntake $intake, string $id): JsonResponse
{
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1'], 'action' => ['required', 'string'],
'note' => ['required', 'string'], 'review_consent' => ['nullable', 'boolean']]);
$business = $intake->transition($request->user(), $id, $data['version_no'], $data['action'], $data['note'], (bool) ($data['review_consent'] ?? false));
'note' => ['required', 'string'], 'review_consent' => ['nullable', 'boolean'], 'confirmation_code' => ['nullable', 'string', 'max:100']]);
$business = $intake->transition($request->user(), $id, $data['version_no'], $data['action'], $data['note'], (bool) ($data['review_consent'] ?? false), $data['confirmation_code'] ?? null);
return response()->json($this->record($business));
}
@@ -79,12 +84,12 @@ class ExistingBusinessController extends Controller
$saved = $objects->save($request->user(), $id, $request->all(), $object);
return response()->json(['id' => $saved->id, 'verification_status' => 'pending',
'version_no' => ExistingBusiness::findOrFail($id)->version_no], $object ? 200 : 201);
'version_no' => app(BusinessRepository::class)->find($id)->version_no], $object ? 200 : 201);
}
/** @return array<string,mixed> */
private function record(ExistingBusiness $business): array
{
return [...$business->only(['id', 'code', 'modality', 'status', 'classification', 'version_no']), 'payload' => $business->payload];
return [...$business->only(['id', 'code', 'modality', 'status', 'classification', 'version_no', 'sector_id']), 'payload' => $business->payload];
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace App\Jobs;
use App\Services\Mne\LegacyBusinessRepository;
use App\Services\Mne\MneBusinessRepository;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;
final class CompareMneBusiness implements ShouldQueue
{
use Queueable;
public int $tries = 1;
public function __construct(public string $businessId) {}
public function handle(LegacyBusinessRepository $legacy, MneBusinessRepository $canonical): void
{
$start = hrtime(true);
try {
$source = $legacy->find($this->businessId);
$comparison = $canonical->comparison($this->businessId);
$expected = $source->only(['code', 'modality', 'status', 'classification', 'version_no']);
$outcome = $comparison === null ? 'unmapped' : ($expected == $comparison ? 'core_match' : 'divergence');
} catch (\Throwable) {
$outcome = 'comparison_error';
}
// No payloads, query parameters, identifiers or exception messages in telemetry.
Log::info('mne.compatibility.shadow', ['outcome' => $outcome, 'latency_ms' => (hrtime(true) - $start) / 1000000]);
}
}
+3 -1
View File
@@ -5,6 +5,8 @@ namespace App\Providers;
use App\Models\Opportunity;
use App\Models\Sector;
use App\Models\User;
use App\Services\Mne\BusinessRepository;
use App\Services\Mne\CompatibleBusinessRepository;
use Carbon\CarbonImmutable;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
@@ -23,7 +25,7 @@ class AppServiceProvider extends ServiceProvider
*/
public function register(): void
{
//
$this->app->bind(BusinessRepository::class, CompatibleBusinessRepository::class);
}
/**
+80
View File
@@ -0,0 +1,80 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\Validator;
final class BusinessFormSchema
{
/** @return array<string, array{step:int,pt:string,en:string,type:string,max:int,options?:array<string,string>}> */
public static function fields(): array
{
return [
'proponent_type' => ['step' => 1, 'pt' => 'Tipo de proponente', 'en' => 'Applicant type', 'type' => 'select', 'max' => 30, 'options' => ['person' => 'Pessoa / Person', 'organization' => 'Organização / Organization']],
'proponent_name' => ['step' => 1, 'pt' => 'Nome ou denominação', 'en' => 'Name', 'type' => 'text', 'max' => 200],
'tax_identifier' => ['step' => 1, 'pt' => 'NUIT ou identificador', 'en' => 'Tax identifier', 'type' => 'text', 'max' => 50],
'contact_email' => ['step' => 1, 'pt' => 'Email de contacto', 'en' => 'Contact email', 'type' => 'email', 'max' => 254],
'contact_phone' => ['step' => 1, 'pt' => 'Telefone', 'en' => 'Phone', 'type' => 'tel', 'max' => 40],
'country' => ['step' => 1, 'pt' => 'País (código de duas letras)', 'en' => 'Country (two-letter code)', 'type' => 'text', 'max' => 2],
'acting_capacity' => ['step' => 2, 'pt' => 'Qualidade em que actua', 'en' => 'Acting capacity', 'type' => 'select', 'max' => 30, 'options' => ['holder' => 'Titular / Holder', 'representative' => 'Representante / Representative']],
'declared_holder' => ['step' => 2, 'pt' => 'Titular declarado', 'en' => 'Declared holder', 'type' => 'text', 'max' => 200],
'mandate_reference' => ['step' => 2, 'pt' => 'Referência do mandato', 'en' => 'Mandate reference', 'type' => 'text', 'max' => 500],
'mandate_valid_until' => ['step' => 2, 'pt' => 'Validade do mandato', 'en' => 'Mandate expiry', 'type' => 'date', 'max' => 10],
'legitimacy_declaration' => ['step' => 2, 'pt' => 'Declaro legitimidade para esta submissão', 'en' => 'I declare authority to submit', 'type' => 'select', 'max' => 3, 'options' => ['yes' => 'Sim / Yes', 'no' => 'Não / No']],
'title' => ['step' => 3, 'pt' => 'Título proposto', 'en' => 'Proposed title', 'type' => 'text', 'max' => 200],
'description' => ['step' => 3, 'pt' => 'Descrição reservada', 'en' => 'Private description', 'type' => 'textarea', 'max' => 10000],
'declared_reason' => ['step' => 3, 'pt' => 'Motivo e objectivo', 'en' => 'Reason and objective', 'type' => 'textarea', 'max' => 2000],
'valid_until' => ['step' => 3, 'pt' => 'Validade declarada', 'en' => 'Declared expiry', 'type' => 'date', 'max' => 10],
'asking_value' => ['step' => 4, 'pt' => 'Valor pedido', 'en' => 'Asking value', 'type' => 'decimal', 'max' => 24],
'currency' => ['step' => 4, 'pt' => 'Moeda (código de três letras)', 'en' => 'Currency (three-letter code)', 'type' => 'text', 'max' => 3],
'value_nature' => ['step' => 4, 'pt' => 'Natureza do valor', 'en' => 'Value basis', 'type' => 'select', 'max' => 30, 'options' => ['asking' => 'Pedido / Asking', 'indicative' => 'Indicativo / Indicative', 'appraised' => 'Avaliado, sujeito a prova / Appraised, evidence required']],
'equity_percentage' => ['step' => 4, 'pt' => 'Participação disponível (%)', 'en' => 'Available equity (%)', 'type' => 'decimal', 'max' => 8],
'funds_use' => ['step' => 4, 'pt' => 'Utilização dos fundos', 'en' => 'Use of funds', 'type' => 'textarea', 'max' => 2000],
'location_notes' => ['step' => 5, 'pt' => 'Localização declarada (reservada)', 'en' => 'Declared location (private)', 'type' => 'textarea', 'max' => 2000],
'asset_notes' => ['step' => 6, 'pt' => 'Resumo dos activos e direitos declarados', 'en' => 'Declared assets and rights summary', 'type' => 'textarea', 'max' => 2000],
'source_reference' => ['step' => 7, 'pt' => 'Referência da fonte', 'en' => 'Source reference', 'type' => 'textarea', 'max' => 2000],
'document_reference' => ['step' => 7, 'pt' => 'Referências documentais (não são ficheiros validados)', 'en' => 'Document references (not validated files)', 'type' => 'textarea', 'max' => 2000],
];
}
/** @return array<string, array<int,string>> */
public static function rules(): array
{
$rules = [];
foreach (self::fields() as $key => $field) {
$rules['payload.'.$key] = ['nullable', 'string', 'max:'.$field['max']];
if (isset($field['options'])) {
$rules['payload.'.$key][] = 'in:'.implode(',', array_keys($field['options']));
}
}
$rules['payload.contact_email'][] = 'email';
$rules['payload.country'][] = 'regex:/^[A-Z]{2}$/';
$rules['payload.currency'][] = 'regex:/^[A-Z]{3}$/';
$rules['payload.asking_value'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/';
$rules['payload.equity_percentage'][] = 'numeric';
$rules['payload.equity_percentage'][] = 'between:0,100';
foreach (['valid_until', 'mandate_valid_until'] as $date) {
$rules['payload.'.$date][] = 'date_format:Y-m-d';
}
$rules['payload.wizard_version'] = ['nullable', 'in:1'];
$rules['payload.wizard_step'] = ['nullable', 'integer', 'between:1,8'];
$rules['payload.title'] = ['required', 'string', 'max:200'];
return $rules;
}
/** @param array<string,mixed> $payload */
public static function validateSubmission(array $payload): void
{
$rules = [];
foreach (['proponent_type', 'proponent_name', 'tax_identifier', 'contact_email', 'country', 'acting_capacity', 'declared_holder', 'location_notes'] as $field) {
$rules[$field] = ['required'];
}
$rules['legitimacy_declaration'] = ['required', 'in:yes'];
$rules['mandate_reference'] = ['required_if:acting_capacity,representative'];
$rules['mandate_valid_until'] = ['required_if:acting_capacity,representative', 'nullable', 'date_format:Y-m-d', 'after_or_equal:today'];
$rules['currency'] = ['required_with:asking_value'];
$rules['value_nature'] = ['required_with:asking_value'];
Validator::make($payload, $rules)->validate();
}
}
+13 -3
View File
@@ -5,11 +5,13 @@ namespace App\Services;
use App\Models\ExistingBusiness;
use App\Models\ExistingBusinessObject;
use App\Models\User;
use App\Services\Mne\BusinessRepository;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
final class ExistingBusinessDrafts
{
@@ -20,20 +22,25 @@ final class ExistingBusinessDrafts
{
$data = Validator::make($input, [
'modality' => ['required', 'in:'.implode(',', self::MODALITIES)],
'sector_id' => ['sometimes', 'nullable', 'integer', Rule::exists('sectors', 'id')->whereNull('deleted_at')->where('is_active', true)],
'classification' => ['required', 'in:internal,confidential,restricted'],
'version_no' => [$id ? 'required' : 'prohibited', 'integer', 'min:1'],
'reason' => ['required', 'string', 'min:10', 'max:1000'],
'payload' => ['required', 'array:title,description,declared_reason,source_reference,valid_until'],
'payload' => ['required', 'array:'.implode(',', [...array_keys(BusinessFormSchema::fields()), 'wizard_version', 'wizard_step'])],
'payload.title' => ['required', 'string', 'max:200'],
'payload.description' => ['nullable', 'string', 'max:10000'],
'payload.declared_reason' => ['nullable', 'string', 'max:2000'],
'payload.source_reference' => ['nullable', 'string', 'max:2000'],
'payload.valid_until' => ['nullable', 'date_format:Y-m-d'],
...BusinessFormSchema::rules(),
])->validate();
return DB::transaction(function () use ($actor, $id, $data) {
if ($id) {
$business = ExistingBusiness::whereKey($id)->lockForUpdate()->firstOrFail();
$business = app(BusinessRepository::class)->find($id, true);
if (($business->payload['wizard_version'] ?? null) === '1') {
$data['payload']['wizard_version'] = '1';
}
Gate::forUser($actor)->authorize('update', $business);
abort_unless($business->version_no === $data['version_no'], 409, 'O rascunho foi alterado. Recarregue antes de gravar.');
$business->version_no++;
@@ -49,6 +56,9 @@ final class ExistingBusinessDrafts
$business->status = 'draft';
}
$business->fill(['modality' => $data['modality'], 'classification' => $data['classification'], 'payload' => $data['payload']]);
if (array_key_exists('sector_id', $data)) {
$business->sector_id = $data['sector_id'];
}
$business->save();
$this->snapshot($business, $actor, $id ? 'updated' : 'created', $data['reason']);
@@ -60,7 +70,7 @@ final class ExistingBusinessDrafts
{
Validator::make(['reason' => $reason], ['reason' => ['required', 'string', 'min:10', 'max:1000']])->validate();
DB::transaction(function () use ($actor, $id, $version, $reason) {
$business = ExistingBusiness::whereKey($id)->lockForUpdate()->firstOrFail();
$business = app(BusinessRepository::class)->find($id, true);
Gate::forUser($actor)->authorize('delete', $business);
abort_unless($business->version_no === $version, 409);
$business->version_no++;
+21 -3
View File
@@ -3,30 +3,48 @@
namespace App\Services;
use App\Models\ExistingBusiness;
use App\Models\ExistingBusinessObject;
use App\Models\User;
use App\Services\Mne\BusinessRepository;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
final class ExistingBusinessIntake
{
public function transition(User $actor, string $id, int $version, string $action, string $note, bool $consent = false): ExistingBusiness
public function transition(User $actor, string $id, int $version, string $action, string $note, bool $consent = false, ?string $confirmationCode = null): ExistingBusiness
{
Validator::make(compact('action', 'note'), [
'action' => ['required', 'in:submitted,in_review,needs_information,withdrawn'],
'note' => ['required', 'string', 'min:10', 'max:2000'],
])->validate();
return DB::transaction(function () use ($actor, $id, $version, $action, $note, $consent) {
$business = ExistingBusiness::whereKey($id)->lockForUpdate()->firstOrFail();
return DB::transaction(function () use ($actor, $id, $version, $action, $note, $consent, $confirmationCode) {
$business = app(BusinessRepository::class)->find($id, true);
Gate::forUser($actor)->authorize(in_array($action, ['submitted', 'withdrawn'], true) ? 'owns' : 'review', $business);
abort_unless($business->version_no === $version, 409, 'Versão desactualizada.');
$allowed = ['submitted' => ['draft', 'needs_information'], 'in_review' => ['submitted'],
'needs_information' => ['in_review'], 'withdrawn' => ['draft', 'submitted', 'in_review', 'needs_information']];
abort_unless(in_array($business->status, $allowed[$action], true), 409, 'Transição indisponível neste estado.');
if ($action === 'submitted') {
if (($business->payload['wizard_version'] ?? null) === '1') {
BusinessFormSchema::validateSubmission($business->payload);
$requiredKind = ['asset_sale' => 'asset', 'asset_lease' => 'asset', 'real_estate' => 'property',
'agricultural_investment' => 'agricultural_investment', 'land_right' => 'land_right',
'mining_license' => 'license', 'forestry_license' => 'license', 'capital_increase' => 'capital_request',
'participation_sale' => 'participation'][$business->modality] ?? null;
if ($requiredKind !== null && ! ExistingBusinessObject::where('business_id', $business->id)->where('kind', $requiredKind)->exists()) {
throw ValidationException::withMessages(['objects' => 'Declare o elemento aplicável na etapa 6: '.$requiredKind]);
}
Validator::make(['confirmation_code' => $confirmationCode, 'sector_id' => $business->sector_id], [
'confirmation_code' => ['required', Rule::in([$business->code])],
'sector_id' => ['required', Rule::exists('sectors', 'id')->whereNull('deleted_at')->where('is_active', true)],
])->validate();
}
Validator::make([...$business->payload, 'consent' => $consent], [
'description' => ['required', 'string', 'min:30'], 'source_reference' => ['required', 'string', 'min:10'],
'valid_until' => ['required', 'date_format:Y-m-d', 'after_or_equal:today'], 'consent' => ['accepted'],
+2 -2
View File
@@ -2,9 +2,9 @@
namespace App\Services;
use App\Models\ExistingBusiness;
use App\Models\ExistingBusinessObject;
use App\Models\User;
use App\Services\Mne\BusinessRepository;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
@@ -58,7 +58,7 @@ final class ExistingBusinessObjects
Validator::make($data['payload'], $rules)->validate();
return DB::transaction(function () use ($actor, $businessId, $objectId, $data) {
$business = ExistingBusiness::whereKey($businessId)->lockForUpdate()->firstOrFail();
$business = app(BusinessRepository::class)->find($businessId, true);
Gate::forUser($actor)->authorize('update', $business);
abort_unless($business->version_no === $data['version_no'], 409, 'Versão desactualizada.');
abort_if(! $objectId && ExistingBusinessObject::where('business_id', $businessId)->count() >= 100, 422, 'Máximo de 100 elementos por negócio.');
@@ -5,6 +5,7 @@ namespace App\Services;
use App\Models\ExistingBusiness;
use App\Models\ExistingBusinessObject;
use App\Models\User;
use App\Services\Mne\BusinessRepository;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
@@ -34,7 +35,7 @@ final class ExistingBusinessVerification
])->validate();
return DB::transaction(function () use ($actor, $id, $data) {
$business = ExistingBusiness::whereKey($id)->lockForUpdate()->firstOrFail();
$business = app(BusinessRepository::class)->find($id, true);
Gate::forUser($actor)->authorize('review', $business);
abort_unless($business->status === 'in_review' && $business->version_no === $data['version_no'], 409, 'Reabra a versão actual em revisão.');
if (! empty($data['object_id'])) {
+14
View File
@@ -0,0 +1,14 @@
<?php
namespace App\Services\Mne;
use App\Models\ExistingBusiness;
use Illuminate\Database\Eloquent\Builder;
interface BusinessRepository
{
/** @return Builder<ExistingBusiness> */
public function query(): Builder;
public function find(string $id, bool $forUpdate = false): ExistingBusiness;
}
@@ -0,0 +1,73 @@
<?php
namespace App\Services\Mne;
use Illuminate\Support\Facades\DB;
use Ramsey\Uuid\Uuid;
final class CompatibilityBackfill
{
/** @return array<string, int> */
public function run(int $batchSize = 100): array
{
$counts = [];
foreach (['identity' => ['users', 'identity_links', 'user_id'], 'sector' => ['sectors', 'sector_links', 'sector_id'],
'business' => ['existing_businesses', 'business_links', 'legacy_business_id']] as $domain => [$source, $target, $key]) {
// Start again on each invocation to detect edits behind a previous checkpoint.
$last = null;
$processed = 0;
do {
$batch = DB::transaction(function () use ($domain, $source, $target, $key, $last, $processed, $batchSize) {
DB::select('SELECT pg_advisory_xact_lock(290926,170004)');
$query = DB::table('public.'.$source)->orderBy('id')->limit($batchSize)->lockForUpdate();
if ($last !== null) {
$query->where('id', '>', $last);
}
$rows = $query->get();
$checksums = [];
foreach ($rows as $row) {
$checksum = hash('sha256', json_encode((array) $row, JSON_THROW_ON_ERROR));
$checksums[] = $checksum;
$stableId = (string) Uuid::uuid5(Uuid::NAMESPACE_URL, 'investmoz:'.$domain.':'.$row->id);
$data = ['id' => $stableId, $key => $row->id, 'source_system' => 'public.'.$source,
'source_checksum' => $checksum, 'status' => 'pending'];
if ($domain === 'sector') {
$data['canonical_sector_id'] = $stableId;
$data['source_code'] = $row->slug;
$data['status'] = $row->is_active && $row->deleted_at === null ? 'active' : 'pending';
}
$existing = DB::table('mne.'.$target)->where($key, $row->id)->first();
if (! $existing) {
DB::table('mne.'.$target)->insert($data);
} elseif ($existing->source_checksum !== $checksum) {
// Changed sources invalidate previous reconciliation; never activate by inference.
DB::table('mne.'.$target)->where($key, $row->id)->update(['source_checksum' => $checksum, 'status' => 'pending']);
}
if ($domain !== 'sector' && (! $existing || $existing->status !== 'active' || $existing->source_checksum !== $checksum)) {
DB::table('mne.compatibility_rejections')->upsert([[
'id' => $stableId, 'domain' => $domain, 'source_key' => (string) $row->id,
'code' => 'CANONICAL_MAPPING_REQUIRED', 'cause' => 'Explicit canonical mapping and reconciliation required',
'resolved_at' => null, 'resolution' => null,
]], ['domain', 'source_key', 'code'], ['cause', 'resolved_at', 'resolution']);
}
}
if ($rows->isNotEmpty() || $processed === 0) {
DB::table('mne.compatibility_checkpoints')->updateOrInsert(['domain' => $domain], [
'last_key' => $rows->isEmpty() ? $last : (string) $rows->last()->id,
'processed' => $processed + $rows->count(), 'checksum' => hash('sha256', implode('', $checksums)), 'updated_at' => now(),
]);
}
return $rows;
});
$processed += $batch->count();
if ($batch->isNotEmpty()) {
$last = $batch->last()->id;
}
} while ($batch->count() === $batchSize);
$counts[$domain] = $processed;
}
return $counts;
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace App\Services\Mne;
use App\Jobs\CompareMneBusiness;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
final class CompatibilityShadow
{
/** Invoke only after authorization; optional comparison must never affect the response. */
public function schedule(string $businessId): void
{
if (! config('existing-business.compatibility_shadow', false)) {
return;
}
try {
$control = DB::transaction(fn () => DB::table('mne.compatibility_controls')->where('capability', 'shadow')->first());
if (! $control || ! $control->enabled || (hexdec(substr(hash('sha256', $businessId), 0, 6)) % 100) >= $control->percentage) {
return;
}
$connection = (string) config('existing-business.shadow_queue', 'database');
if (config('queue.connections.'.$connection.'.driver') !== 'database') {
Log::info('mne.compatibility.shadow', ['outcome' => 'async_queue_required']);
return;
}
CompareMneBusiness::dispatch($businessId)->onConnection($connection)->onQueue('mne-shadow')->afterCommit();
} catch (\Throwable) {
Log::info('mne.compatibility.shadow', ['outcome' => 'dispatch_error']);
}
}
}
@@ -0,0 +1,23 @@
<?php
namespace App\Services\Mne;
use App\Models\ExistingBusiness;
use Illuminate\Database\Eloquent\Builder;
final class CompatibleBusinessRepository implements BusinessRepository
{
public function __construct(private LegacyBusinessRepository $legacy) {}
/** @return Builder<ExistingBusiness> */
public function query(): Builder
{
return $this->legacy->query();
}
public function find(string $id, bool $forUpdate = false): ExistingBusiness
{
// No configuration can transfer writes or bypass existing policies.
return $this->legacy->find($id, $forUpdate);
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace App\Services\Mne;
use Illuminate\Support\Facades\DB;
final class IdentityResolver
{
public function resolve(int $userId): ?string
{
$id = DB::table('mne.identity_links as l')->join('mne.parties as p', 'p.id', '=', 'l.party_id')
->join('public.users as u', 'u.id', '=', 'l.user_id')
->where('l.user_id', $userId)->where('l.status', 'active')->where('p.party_type', 'person')
->whereNull('p.deleted_at')->where('l.valid_from', '<=', now())
->where(fn ($q) => $q->whereNull('l.valid_until')->orWhere('l.valid_until', '>', now()))
->value('l.party_id');
return is_string($id) ? $id : null;
}
}
@@ -0,0 +1,25 @@
<?php
namespace App\Services\Mne;
use App\Models\ExistingBusiness;
use Illuminate\Database\Eloquent\Builder;
final class LegacyBusinessRepository implements BusinessRepository
{
/** @return Builder<ExistingBusiness> */
public function query(): Builder
{
return ExistingBusiness::query();
}
public function find(string $id, bool $forUpdate = false): ExistingBusiness
{
$query = $this->query()->whereKey($id);
if ($forUpdate) {
$query->lockForUpdate();
}
return $query->firstOrFail();
}
}
@@ -0,0 +1,25 @@
<?php
namespace App\Services\Mne;
use Illuminate\Support\Facades\DB;
/** Read-only comparison adapter. Does not hydrate a legacy model or grant authority. */
final class MneBusinessRepository
{
/** @return array<string, mixed>|null */
public function comparison(string $legacyId): ?array
{
$row = DB::table('mne.business_links as l')
->join('mne.existing_businesses as b', 'b.id', '=', 'l.canonical_business_id')
->join('mne.business_modalities as m', 'm.id', '=', 'b.modality_id')
->join('mne.workflow_states as s', 's.id', '=', 'b.status_id')
->join('mne.data_classifications as c', 'c.id', '=', 'b.confidentiality_id')
->where('l.legacy_business_id', $legacyId)->where('l.status', 'active')
->where('l.valid_from', '<=', now())->where(fn ($q) => $q->whereNull('l.valid_until')->orWhere('l.valid_until', '>', now()))
->whereNull('b.deleted_at')->first(['b.public_code as code', 'm.code as modality', 's.code as status',
'c.code as classification', 'b.version as version_no']);
return $row ? (array) $row : null;
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Services\Mne;
use Illuminate\Support\Facades\DB;
final class SectorResolver
{
public const VERSION = 1;
public function resolve(int $legacyId): ?string
{
$id = DB::table('mne.sector_links as l')->join('public.sectors as s', 's.id', '=', 'l.sector_id')
->where('l.sector_id', $legacyId)->where('l.resolver_version', self::VERSION)
->where('l.status', 'active')->where('s.is_active', true)->whereNull('s.deleted_at')
->whereColumn('l.source_code', 's.slug')->where('l.valid_from', '<=', now())
->where(fn ($q) => $q->whereNull('l.valid_until')->orWhere('l.valid_until', '>', now()))
->value('l.canonical_sector_id');
return is_string($id) ? $id : null;
}
}
+108
View File
@@ -0,0 +1,108 @@
<?php
namespace App\Support;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
abstract class SkillsEducationMigration extends Migration
{
protected int $block;
/** @var list<string> */
protected array $tables;
public function up(): void
{
if (DB::getDriverName() !== 'pgsql') {
throw new \RuntimeException('PostgreSQL 17 with existing PostGIS/pgcrypto required.');
}
DB::select("SELECT pg_advisory_xact_lock(hashtextextended('skills_edu:migrations',0))");
DB::statement("SET LOCAL TIME ZONE 'UTC'");
$version = (int) DB::selectOne("SELECT current_setting('server_version_num') AS n")->n;
if ($version < 170000 || $version >= 180000 || DB::table('pg_extension')->whereIn('extname', ['pgcrypto', 'postgis'])->count() !== 2) {
throw new \RuntimeException('Expected PostgreSQL 17 and extensions managed by existing migrations.');
}
foreach (['users' => 'bigint', 'sectors' => 'bigint', 'skills' => 'uuid', 'occupations' => 'uuid', 'courses' => 'uuid', 'training_providers' => 'uuid',
'organizations' => 'uuid', 'projects' => 'uuid', 'economic_clusters' => 'uuid', 'development_corridors' => 'uuid', 'investment_zones' => 'uuid',
'geo_locations' => 'uuid', 'labour_demands' => 'uuid', 'education_investment_proposals' => 'uuid', 'documents' => 'uuid', 'consents' => 'uuid'] as $table => $type) {
$actual = DB::selectOne("SELECT format_type(atttypid,atttypmod) AS type FROM pg_attribute WHERE attrelid=to_regclass(?) AND attname='id' AND NOT attisdropped", ['public.'.$table]);
if (! $actual || $actual->type !== $type) {
throw new \RuntimeException('Unexpected master identifier: public.'.$table);
}
}
if ($this->block === 1) {
if (DB::selectOne("SELECT to_regnamespace('skills_edu') AS id")->id !== null) {
throw new \RuntimeException('Unregistered skills_edu schema exists; reconcile before migration.');
}
DB::statement('CREATE SCHEMA skills_edu');
DB::unprepared('CREATE FUNCTION skills_edu.set_updated_at() RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog AS $$ BEGIN NEW.updated_at := now(); RETURN NEW; END $$');
} else {
$predecessor = match ($this->block) {
2 => 'occupation_skills', 3 => 'institutional_candidate_registrations', 4 => 'institutional_authorisations',
5 => 'human_resource_need_certifications', 6 => 'profile_need_matches',
default => throw new \RuntimeException('Unknown skills education migration block'),
};
if (DB::selectOne('SELECT to_regclass(?) AS id', ['skills_edu.'.$predecessor])->id === null) {
throw new \RuntimeException('Missing previous skills_edu block: '.$predecessor);
}
}
$sql = file_get_contents(database_path('sql/skills-education/'.sprintf('%02d', $this->block).'.sql'));
if ($sql === false) {
throw new \RuntimeException('Versioned SQL block missing');
}
if (DB::connection()->getPdo()->exec($sql) === false) {
throw new \RuntimeException('Versioned SQL block failed');
}
DB::unprepared(<<<'SQL'
DO $indexes$
DECLARE fk record;
BEGIN
FOR fk IN SELECT c.conrelid,c.conkey,c.conname,t.relname,
(SELECT string_agg(quote_ident(a.attname),', ' ORDER BY k.p) FROM unnest(c.conkey) WITH ORDINALITY k(n,p)
JOIN pg_attribute a ON a.attrelid=c.conrelid AND a.attnum=k.n) AS cols
FROM pg_constraint c JOIN pg_class t ON t.oid=c.conrelid JOIN pg_namespace ns ON ns.oid=t.relnamespace
WHERE ns.nspname='skills_edu' AND c.contype='f'
LOOP
IF NOT EXISTS (SELECT 1 FROM pg_index i JOIN pg_class x ON x.oid=i.indexrelid JOIN pg_am am ON am.oid=x.relam
WHERE i.indrelid=fk.conrelid AND i.indisvalid AND i.indisready AND i.indpred IS NULL AND am.amname='btree'
AND i.indnkeyatts>=cardinality(fk.conkey)
AND ARRAY(SELECT n FROM unnest(i.indkey::smallint[]) WITH ORDINALITY k(n,p) WHERE p<=cardinality(fk.conkey) ORDER BY p)=fk.conkey)
THEN EXECUTE format('CREATE INDEX %I ON skills_edu.%I (%s)','se_fk_'||md5(fk.relname||fk.conname),fk.relname,fk.cols);
END IF;
END LOOP;
END $indexes$;
SQL);
if ($this->block === 6) {
DB::unprepared(<<<'SQL'
CREATE FUNCTION skills_edu.reject_audit_mutation() RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog AS $$
BEGIN RAISE EXCEPTION 'Skills education audit is append-only' USING ERRCODE='23514'; END $$;
CREATE TRIGGER immutable_skills_education_audit BEFORE UPDATE OR DELETE OR TRUNCATE ON skills_edu.audit_events
FOR EACH STATEMENT EXECUTE FUNCTION skills_edu.reject_audit_mutation();
SQL);
}
}
public function down(): void
{
DB::select("SELECT pg_advisory_xact_lock(hashtextextended('skills_edu:migrations',0))");
foreach ($this->tables as $table) {
if (DB::table('skills_edu.'.$table)->exists()) {
throw new \RuntimeException('Skills education data exists; destructive rollback refused: '.$table);
}
}
foreach (array_reverse($this->tables) as $table) {
DB::statement('DROP TABLE skills_edu.'.$table.' RESTRICT');
}
if ($this->block === 6) {
DB::statement('DROP FUNCTION skills_edu.reject_audit_mutation() RESTRICT');
}
if ($this->block === 3) {
DB::statement('DROP FUNCTION skills_edu.validate_consent_dates() RESTRICT');
}
if ($this->block === 1) {
DB::statement('DROP FUNCTION skills_edu.set_updated_at() RESTRICT');
DB::statement('DROP SCHEMA skills_edu RESTRICT');
}
}
}