@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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++;
|
||||
|
||||
@@ -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,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'])) {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user