feat: consolidar desenvolvimentos do portal InvestMoz
This commit is contained in:
+158
-19
@@ -56,6 +56,55 @@ class VirtualDesk
|
||||
return $case;
|
||||
}
|
||||
|
||||
public function assertOpen(\stdClass $case): void
|
||||
{
|
||||
abort_if($case->closed_at, 409, 'Dossier encerrado. Os registos guardados continuam disponíveis para consulta.');
|
||||
}
|
||||
|
||||
/** @return array<string,int|null> */
|
||||
public function caseActivity(\stdClass $case): array
|
||||
{
|
||||
return ['open_requests' => DB::table('desk_requests')->where('case_id', $case->id)->whereNotIn('status', ['closed', 'cancelled'])->count(),
|
||||
'open_tasks' => Schema::hasColumn('tasks', 'desk_case_id') ? DB::table('tasks')->where('desk_case_id', $case->id)->whereNull('deleted_at')->whereNotIn('status', ['done', 'cancelled'])->count() : null,
|
||||
'pending_payments' => Schema::hasTable('desk_payments') ? DB::table('desk_payments')->whereIn('request_id', DB::table('desk_requests')->where('case_id', $case->id)->select('id'))->whereIn('status', ['pending', 'internal_issue'])->count() : null];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function changeCaseState(User $actor, string $id, array $input): array
|
||||
{
|
||||
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'state' => 'required|in:open,closed', 'reason' => 'required|string|min:3|max:5000', 'client_key' => 'required|uuid'])->validate();
|
||||
$data['version'] = (int) $data['version'];
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data) {
|
||||
$case = $this->case($actor, $id, true, true);
|
||||
abort_unless((int) $case->user_id === $actor->id, 403, 'Só o dono registado do dossier pode encerrá-lo ou reabri-lo.');
|
||||
$replayed = false;
|
||||
foreach (DB::table('desk_events')->where('case_id', $id)->where('action', 'case_state_changed')->get(['actor_id', 'payload']) as $event) {
|
||||
$saved = $this->decode($event->payload);
|
||||
if (($saved['client_key'] ?? null) === $data['client_key']) {
|
||||
abort_unless((int) $event->actor_id === $actor->id && ($saved['operation'] ?? null) === $data, 409, 'Esta operação já foi registada com outros dados.');
|
||||
$replayed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (! $replayed) {
|
||||
abort_unless((int) $case->version === $data['version'], 409, 'O dossier foi actualizado. Confira a versão actual antes de continuar.');
|
||||
$closed = $data['state'] === 'closed';
|
||||
abort_if(($case->closed_at !== null) === $closed, 409, 'O dossier já se encontra nesse estado. Actualize a página.');
|
||||
$before = ['version' => (int) $case->version, 'closed_at' => $case->closed_at];
|
||||
$activity = $this->caseActivity($case);
|
||||
DB::table('desk_cases')->where('id', $id)->update(['closed_at' => $closed ? now() : null, 'version' => $case->version + 1, 'updated_at' => now()]);
|
||||
$case = DB::table('desk_cases')->where('id', $id)->firstOrFail();
|
||||
$this->event($case, $actor, 'case_state_changed', ['client_key' => $data['client_key'], 'operation' => $data, 'reason' => $data['reason'], 'before' => $before, 'after' => ['version' => (int) $case->version, 'closed_at' => $case->closed_at], 'activity' => $activity,
|
||||
'scope' => 'owner_availability_decision_no_child_status_changes_or_official_approval']);
|
||||
}
|
||||
|
||||
return ['id' => $id, 'version' => (int) $case->version, 'closed_at' => $case->closed_at, 'replayed' => $replayed];
|
||||
});
|
||||
}
|
||||
|
||||
public function request(User $actor, string $id, bool $ownerOnly = false, bool $lock = false): \stdClass
|
||||
{
|
||||
$request = DB::table('desk_requests')->where('id', $id)->when($lock, fn ($q) => $q->lockForUpdate())->first();
|
||||
@@ -177,22 +226,33 @@ class VirtualDesk
|
||||
return DB::transaction(function () use ($actor, $caseId, $serviceId, $clientKey, $opportunity) {
|
||||
$case = $this->case($actor, $caseId, true, true);
|
||||
abort_if($case->closed_at, 409, 'Dossier encerrado.');
|
||||
$service = DB::table('desk_service_versions')->where('id', $serviceId)->where('status', 'published')->first();
|
||||
abort_unless($service !== null, 422, 'Versão do serviço indisponível para novos pedidos.');
|
||||
$existing = DB::table('desk_requests')->where('case_id', $caseId)->where('client_key', $clientKey)->first();
|
||||
if ($existing) {
|
||||
abort_unless($existing->service_version_id === $serviceId, 409);
|
||||
|
||||
return $existing;
|
||||
}
|
||||
// Serialize publication and creation against the same edition selection.
|
||||
DB::select('select pg_advisory_xact_lock(261008, 2)');
|
||||
$service = DB::table('desk_service_versions')->where('id', $serviceId)->where('status', 'published')->first();
|
||||
abort_unless($service !== null, 422, 'Versão do serviço indisponível para novos pedidos.');
|
||||
$current = app(DeskServiceAvailability::class)->current()->where('code', $service->code)->first();
|
||||
if (! $current || $current->id !== $serviceId) {
|
||||
throw ValidationException::withMessages(['service_version_id' => 'A versão escolhida não está actualmente disponível para novos pedidos. Actualize a lista e confira o formulário aplicável; os pedidos anteriores mantêm a sua versão.']);
|
||||
}
|
||||
$id = (string) Str::uuid();
|
||||
$base = $this->decode($case->payload);
|
||||
$serviceFields = json_decode($service->definition, true)['fields'];
|
||||
$payload = Arr::only(['title' => $case->title, 'description' => $base['investment']['objective'] ?? ''], array_keys($serviceFields));
|
||||
foreach (array_keys($payload) as $key) {
|
||||
if ($serviceFields[$key]['type'] === 'consent') {
|
||||
unset($payload[$key]);
|
||||
}
|
||||
}
|
||||
if (isset($serviceFields['regime']['options']['unknown'])) {
|
||||
$payload['regime'] = 'unknown';
|
||||
}
|
||||
if (isset($serviceFields['description']) && config('investor-path.enabled') && $case->simulation_id && (int) $case->user_id === $actor->id) {
|
||||
if (isset($serviceFields['description']) && $serviceFields['description']['type'] !== 'consent' && config('investor-path.enabled') && $case->simulation_id && (int) $case->user_id === $actor->id) {
|
||||
$draftRequest = Request::create('/');
|
||||
$draftRequest->setUserResolver(fn () => $actor);
|
||||
$draft = app(SimulationFormDrafts::class)->find($case->simulation_id, $draftRequest);
|
||||
@@ -210,7 +270,7 @@ class VirtualDesk
|
||||
}
|
||||
$payload = app(InvestmentConsumerScope::class)->bind($actor, $caseId, $payload);
|
||||
foreach (['territory_id' => 'territory_id', 'location_source' => 'location_source', 'title' => 'title', 'description' => 'description', 'sector' => 'sector', 'province_id' => 'province_id', 'district_id' => 'district_id', 'admin_post_id' => 'admin_post_id', 'locality_id' => 'locality_id'] as $field => $source) {
|
||||
if (isset($serviceFields[$field],$mapped[$source]) && (empty($payload[$field]) || in_array($field, ['title', 'description'], true) && $context['revision'] > 0)
|
||||
if (isset($serviceFields[$field],$mapped[$source]) && $serviceFields[$field]['type'] !== 'consent' && (empty($payload[$field]) || in_array($field, ['title', 'description'], true) && $context['revision'] > 0)
|
||||
&& Validator::make(['value' => $mapped[$source]], ['value' => $this->fieldRules($serviceFields[$field], false)])->passes()) {
|
||||
$payload[$field] = $mapped[$source];
|
||||
}
|
||||
@@ -269,7 +329,25 @@ class VirtualDesk
|
||||
* @return array<string,mixed> */
|
||||
public function validateFields(array $payload, array $definition, bool $submitting): array
|
||||
{
|
||||
$rules = ['payload' => ['required', 'array:'.implode(',', [...array_keys($definition['fields']), 'country', 'declared_origin_country_code', 'context_reuse', 'context_opportunity', 'context_opportunity_snapshot'])],
|
||||
return $this->validatedPayload($payload, $definition, $submitting, false);
|
||||
}
|
||||
|
||||
/** Incomplete text/number formats can be recovered, but never submitted through this path.
|
||||
* @param array<string,mixed> $payload
|
||||
* @param array<string,mixed> $definition
|
||||
* @return array<string,mixed> */
|
||||
public function checkpointFields(array $payload, array $definition): array
|
||||
{
|
||||
return $this->validatedPayload($payload, $definition, false, true);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload
|
||||
* @param array<string,mixed> $definition
|
||||
* @return array<string,mixed> */
|
||||
private function validatedPayload(array $payload, array $definition, bool $submitting, bool $checkpoint): array
|
||||
{
|
||||
$messages = [];
|
||||
$rules = ['payload' => ['present', 'array:'.implode(',', [...array_keys($definition['fields']), 'country', 'declared_origin_country_code', 'context_reuse', 'context_opportunity', 'context_opportunity_snapshot'])],
|
||||
'payload.context_opportunity' => ['nullable', 'string', 'max:100'],
|
||||
'payload.context_opportunity_snapshot' => ['nullable', 'string', 'max:200000'],
|
||||
'payload.context_reuse' => ['nullable', 'string', 'max:10000'],
|
||||
@@ -278,13 +356,30 @@ class VirtualDesk
|
||||
foreach ($definition['fields'] as $key => $field) {
|
||||
$active = $this->fieldApplies((string) $key, $definition['fields'], $payload);
|
||||
$required = $submitting && ($field['required'] ?? false) && $active;
|
||||
$rules['payload.'.$key] = $this->fieldRules($field, $required);
|
||||
$rules['payload.'.$key] = $this->fieldRules($field, $required, $checkpoint);
|
||||
if ($field['type'] === 'multiselect') {
|
||||
$rules['payload.'.$key.'.*'] = ['required', 'string', 'distinct:strict', Rule::in(array_map('strval', array_keys($field['options'])))];
|
||||
}
|
||||
if ($field['type'] === 'attachment') {
|
||||
$rules['payload.'.$key.'.*'] = ['required', 'string', 'uuid', 'distinct:strict'];
|
||||
$messages['payload.'.$key.'.required'] = 'Seleccione pelo menos um documento em «'.$field['label'].'».';
|
||||
$messages['payload.'.$key.'.max'] = 'Seleccione no máximo '.$field['max_files'].' ficheiro(s) em «'.$field['label'].'».';
|
||||
foreach (['array', 'list'] as $rule) {
|
||||
$messages['payload.'.$key.'.'.$rule] = 'Seleccione os documentos da lista em «'.$field['label'].'».';
|
||||
}
|
||||
foreach (['uuid', 'string', 'distinct'] as $rule) {
|
||||
$messages['payload.'.$key.'.*.'.$rule] = 'Seleccione cada documento autorizado apenas uma vez em «'.$field['label'].'».';
|
||||
}
|
||||
}
|
||||
}
|
||||
$validated = Validator::make(['payload' => $payload], $rules)->validate()['payload'];
|
||||
$validated = Validator::make(['payload' => $payload], $rules, $messages)->validate()['payload'];
|
||||
foreach ($definition['fields'] as $key => $field) {
|
||||
if ($field['type'] === 'select' && isset($validated[$key])) {
|
||||
$validated[$key] = (string) $validated[$key];
|
||||
}
|
||||
if (in_array($field['type'], ['multiselect', 'attachment'], true) && is_array($validated[$key] ?? null)) {
|
||||
sort($validated[$key], SORT_STRING);
|
||||
}
|
||||
if ($field['type'] === 'territory' && ! empty($validated[$key])) {
|
||||
if (! app(InvestmentGeography::class)->publicReferences()->where('id', $validated[$key])->exists()) {
|
||||
throw ValidationException::withMessages(['payload.'.$key => 'Seleccione uma localização disponível no cadastro territorial.']);
|
||||
@@ -302,11 +397,21 @@ class VirtualDesk
|
||||
|
||||
/** @param array<string,mixed> $field
|
||||
* @return list<mixed> */
|
||||
private function fieldRules(array $field, bool $required): array
|
||||
private function fieldRules(array $field, bool $required, bool $checkpoint = false): array
|
||||
{
|
||||
if ($checkpoint && in_array($field['type'], ['number', 'date', 'email', 'url'], true)) {
|
||||
return ['nullable', function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if (! is_string($value) && ! is_int($value) && ! is_float($value)) {
|
||||
$fail('Conserve apenas texto ou um número neste campo do rascunho.');
|
||||
}
|
||||
}, 'max:1000'];
|
||||
}
|
||||
|
||||
return [$required ? 'required' : 'nullable', ...match ($field['type']) {
|
||||
'number' => ['numeric', 'decimal:0,2', 'min:'.($field['min'] ?? 0), 'max:999999999999'], 'date' => ['date_format:Y-m-d'],
|
||||
'select' => [Rule::in(array_keys($field['options']))], 'territory' => ['uuid'],
|
||||
'multiselect' => ['array', 'list', 'max:100'], 'consent' => ['string', Rule::in(['accepted', 'declined'])],
|
||||
'attachment' => ['array', 'list', 'max:'.$field['max_files']],
|
||||
'email' => ['string', 'email', 'max:1000'], 'url' => ['string', 'url:http,https', 'max:1000'],
|
||||
default => ['string', 'max:'.($field['type'] === 'textarea' ? 15000 : 1000)],
|
||||
}];
|
||||
@@ -326,7 +431,10 @@ class VirtualDesk
|
||||
}
|
||||
$parent = $field['when']['field'];
|
||||
$answer = $payload[$parent] ?? null;
|
||||
if (! is_scalar($answer) || (string) $answer !== $field['when']['equals']) {
|
||||
$matches = ($field['when']['operator'] ?? 'equals') === 'contains'
|
||||
? is_array($answer) && in_array($field['when']['equals'], $answer, true)
|
||||
: is_scalar($answer) && (string) $answer === $field['when']['equals'];
|
||||
if (! $matches) {
|
||||
return false;
|
||||
}
|
||||
$ancestors[$key] = true;
|
||||
@@ -349,9 +457,13 @@ class VirtualDesk
|
||||
{
|
||||
$findings = [];
|
||||
$fields = $this->applicableFields($payload, $definition);
|
||||
$financeApplies = isset($fields['investment_amount'], $fields['own_finance'], $fields['other_finance']);
|
||||
$financeApplies = count(array_filter(['investment_amount', 'own_finance', 'other_finance'], fn ($key) => ($fields[$key]['type'] ?? null) === 'number')) === 3;
|
||||
$amounts = array_map(function ($key) use ($payload) {
|
||||
$value = (string) ($payload[$key] ?? '');
|
||||
$raw = $payload[$key] ?? null;
|
||||
if (! is_string($raw) && ! is_int($raw) && ! is_float($raw)) {
|
||||
return null;
|
||||
}
|
||||
$value = (string) $raw;
|
||||
if (! preg_match('/^\d{1,12}(?:\.\d{1,2})?$/', $value)) {
|
||||
return null;
|
||||
}
|
||||
@@ -376,7 +488,7 @@ class VirtualDesk
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, string $id, array $input, bool $submit = false): \stdClass
|
||||
{
|
||||
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'payload' => 'required|array', 'consent' => $submit ? 'accepted' : 'nullable|boolean', 'reason' => 'nullable|string|max:3000', 'context_revision' => 'nullable|integer|min:0', 'context_reviewed' => 'nullable|boolean',
|
||||
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'payload' => 'present|array', 'consent' => $submit ? 'accepted' : 'nullable|boolean', 'reason' => 'nullable|string|max:3000', 'context_revision' => 'nullable|integer|min:0', 'context_reviewed' => 'nullable|boolean',
|
||||
'tool_prefill' => 'nullable|array:draft_id,draft_version,snapshot_sha256', 'tool_prefill.draft_id' => 'required_with:tool_prefill|uuid',
|
||||
'tool_prefill.draft_version' => 'required_with:tool_prefill|integer|min:1', 'tool_prefill.snapshot_sha256' => 'required_with:tool_prefill|string|size:64'])->validate();
|
||||
|
||||
@@ -397,6 +509,7 @@ class VirtualDesk
|
||||
}
|
||||
}
|
||||
$payload = $this->validateFields($data['payload'], $this->definition($request), $submit);
|
||||
$fieldAttachments = app(DeskAttachments::class)->snapshot($request, $payload, $this->definition($request), $submit);
|
||||
if ($request->status !== 'returned' || in_array('context_opportunity', json_decode($request->editable_fields ?? '[]', true), true)) {
|
||||
$payload = app(InvestmentConsumerScope::class)->bind($actor, $request->case_id, $payload, $submit);
|
||||
}
|
||||
@@ -415,10 +528,19 @@ class VirtualDesk
|
||||
throw ValidationException::withMessages(['payload.investment_amount' => $findings[0]['explanation']]);
|
||||
}
|
||||
$case = $this->case($actor, $request->case_id, true, true);
|
||||
abort_if($case->closed_at, 409, 'Dossier encerrado. As respostas guardadas continuam disponíveis para consulta.');
|
||||
if ($submit || ($data['context_reviewed'] ?? false)) {
|
||||
app(InvestorContextConsumers::class)->assertReviewed($actor, $case->id, $data, app(InvestorContextConsumers::class)->requestRevision($request));
|
||||
}
|
||||
$snapshot = ['investment_context' => ['revision' => app(InvestorContext::class)->state($case)['revision']], 'payload' => $payload, 'service_version_id' => $request->service_version_id, 'documents' => DB::table('desk_documents as link')->join('documents as d', 'd.id', '=', 'link.document_id')->where('link.case_id', $case->id)->where(fn ($q) => $q->whereNull('link.request_id')->orWhere('link.request_id', $id))->get(['link.document_id', 'd.sha256', 'd.version_no', 'link.source_reference'])->all(), 'findings' => $findings, 'consent' => $submit, 'source' => config('virtual-desk.source')];
|
||||
$declarations = [];
|
||||
if ($submit) {
|
||||
foreach ($this->definition($request)['fields'] as $key => $field) {
|
||||
if ($field['type'] === 'consent' && $this->fieldApplies($key, $this->definition($request)['fields'], $payload) && in_array($payload[$key] ?? null, ['accepted', 'declined'], true)) {
|
||||
$declarations[$key] = ['label' => $field['label'], 'statement' => $field['statement'], 'statement_sha256' => hash('sha256', $field['statement']), 'answer' => $payload[$key], 'actor_id' => $actor->id, 'declared_at' => now()->toIso8601String(), 'service_version_id' => $request->service_version_id];
|
||||
}
|
||||
}
|
||||
}
|
||||
$snapshot = ['investment_context' => ['revision' => app(InvestorContext::class)->state($case)['revision']], 'payload' => $payload, 'service_version_id' => $request->service_version_id, 'field_declarations' => $declarations, 'field_attachments' => $fieldAttachments, 'documents' => DB::table('desk_documents as link')->join('documents as d', 'd.id', '=', 'link.document_id')->where('link.case_id', $case->id)->where(fn ($q) => $q->whereNull('link.request_id')->orWhere('link.request_id', $id))->get(['link.document_id', 'd.sha256', 'd.version_no', 'link.source_reference'])->all(), 'findings' => $findings, 'consent' => $submit, 'source' => config('virtual-desk.source')];
|
||||
DB::table('desk_revisions')->insert(['request_id' => $id, 'version' => $request->version, 'snapshot' => $this->encode(['payload' => $this->decode($request->payload), 'status' => $request->status, 'submitted_snapshot' => $request->submitted_snapshot ? $this->decode($request->submitted_snapshot) : null])]);
|
||||
$updates = ['payload' => $this->encode($payload), 'version' => $request->version + 1, 'updated_at' => now()];
|
||||
if ($submit) {
|
||||
@@ -442,11 +564,13 @@ class VirtualDesk
|
||||
/** @param array<string,mixed> $data */
|
||||
public function transition(User $actor, string $id, array $data): \stdClass
|
||||
{
|
||||
$data = Validator::make($data, ['version' => 'required|integer|min:1', 'status' => ['required', Rule::in(array_keys(config('virtual-desk.request_states')))], 'reason' => 'required|string|min:3|max:5000', 'editable_fields' => 'nullable|array', 'editable_fields.*' => 'string|max:100'])->validate();
|
||||
$data = Validator::make($data, ['version' => 'required|integer|min:1', 'status' => ['required', Rule::in(array_keys(config('virtual-desk.request_states')))], 'reason' => 'required|string|min:3|max:5000', 'editable_fields' => 'nullable|array', 'editable_fields.*' => 'string|max:100',
|
||||
'return_reason_code' => ['exclude_unless:status,returned', 'nullable', Rule::in(array_keys(config('product-metrics.return_reasons')))]])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data) {
|
||||
$request = $this->request($actor, $id, false, true);
|
||||
$case = $this->case($actor, $request->case_id);
|
||||
$case = $this->case($actor, $request->case_id, false, true);
|
||||
$this->assertOpen($case);
|
||||
abort_unless($request->version === (int) $data['version'], 409);
|
||||
$cancel = $data['status'] === 'cancelled';
|
||||
if ($cancel) {
|
||||
@@ -464,7 +588,12 @@ class VirtualDesk
|
||||
abort_if(array_diff($editable, [...array_keys($this->definition($request)['fields']), 'country', 'declared_origin_country_code']) !== [], 422);
|
||||
DB::table('desk_requests')->where('id', $id)->update(['status' => $data['status'], 'version' => $request->version + 1, 'editable_fields' => json_encode($editable), 'closed_at' => in_array($data['status'], ['closed', 'cancelled'], true) ? now() : null, 'updated_at' => now()]);
|
||||
$request = DB::table('desk_requests')->where('id', $id)->firstOrFail();
|
||||
$this->event($case, $actor, 'request_'.$data['status'], ['reason' => $data['reason'], 'editable_fields' => $editable], $request);
|
||||
$classification = [];
|
||||
if ($data['status'] === 'returned') {
|
||||
$code = $data['return_reason_code'] ?? 'unspecified';
|
||||
$classification = ['return_reason_code' => $code, 'return_reason_label' => config('product-metrics.return_reasons.'.$code), 'return_reason_definition' => config('product-metrics.version')];
|
||||
}
|
||||
$this->event($case, $actor, 'request_'.$data['status'], ['reason' => $data['reason'], 'editable_fields' => $editable, ...$classification], $request);
|
||||
|
||||
return $request;
|
||||
});
|
||||
@@ -475,14 +604,20 @@ class VirtualDesk
|
||||
{
|
||||
$data = Validator::make($data, ['version' => 'required|integer|min:1', 'stage' => ['required', Rule::in(array_keys(config('virtual-desk.steps')))],
|
||||
'status' => ['required', Rule::in(array_keys(config('virtual-desk.step_states')))], 'reason' => 'required|string|min:3|max:3000',
|
||||
'evidence' => 'nullable|string|max:5000', 'document_id' => 'nullable|uuid', 'valid_until' => 'nullable|date_format:Y-m-d', 'exception' => 'nullable|boolean'])->validate();
|
||||
'evidence' => 'nullable|string|max:5000', 'document_id' => 'nullable|uuid', 'document_link_id' => 'nullable|uuid', 'valid_until' => 'nullable|date_format:Y-m-d', 'exception' => 'nullable|boolean'])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data) {
|
||||
$case = $this->case($actor, $id, false, true);
|
||||
abort_unless($this->owns($actor, $case) || app(ScopedPortalAdministration::class)->deskCaseDecision($actor, $case->id), 403);
|
||||
$this->assertOpen($case);
|
||||
abort_unless((int) $case->version === (int) $data['version'], 409);
|
||||
$workflow = json_decode($case->workflow, true, 512, JSON_THROW_ON_ERROR);
|
||||
$current = $workflow[$data['stage']];
|
||||
if ($data['document_link_id'] ?? null) {
|
||||
$link = DB::table('desk_documents')->where('case_id', $id)->where('id', $data['document_link_id'])->first();
|
||||
abort_unless($link && (! ($data['document_id'] ?? null) || $data['document_id'] === $link->document_id), 422, 'Seleccione um suporte associado a este dossier.');
|
||||
$data['document_id'] = $link->document_id;
|
||||
}
|
||||
$decision = in_array($data['status'], ['completed', 'not_applicable'], true);
|
||||
if ($decision) {
|
||||
abort_unless(app(ScopedPortalAdministration::class)->deskCaseDecision($actor, $case->id) && ! $this->owns($actor, $case, false), 403, 'Conclusão documental exige revisão interna por outra pessoa autorizada.');
|
||||
@@ -495,7 +630,9 @@ class VirtualDesk
|
||||
}
|
||||
}
|
||||
if ($data['document_id'] ?? null) {
|
||||
$document = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $id)->where('d.id', $data['document_id'])->whereNull('d.deleted_at')->first(['d.status', 'd.malware_scan_status', 'd.sha256', 'd.malware_scanned_sha256', 'l.valid_until']);
|
||||
$document = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $id)->where('d.id', $data['document_id'])
|
||||
->when($data['document_link_id'] ?? null, fn ($q, $linkId) => $q->where('l.id', $linkId))->whereNull('d.deleted_at')->orderBy('l.created_at')->orderBy('l.id')
|
||||
->first(['d.status', 'd.malware_scan_status', 'd.sha256', 'd.malware_scanned_sha256', 'l.id as link_id', 'l.source_reference', 'l.stage', 'l.valid_until']);
|
||||
abort_unless($document !== null, 422);
|
||||
if ($decision) {
|
||||
abort_unless($document->status === 'active' && $document->malware_scan_status === 'clean' && trim($document->sha256) === $document->malware_scanned_sha256 && (! $document->valid_until || $document->valid_until >= now()->toDateString()), 422, 'Documento ainda não consultável ou expirado.');
|
||||
@@ -521,6 +658,7 @@ class VirtualDesk
|
||||
} while ($changed);
|
||||
}
|
||||
$workflow[$data['stage']] = [...$current, 'status' => $data['status'], 'evidence' => $data['evidence'] ?? null, 'document_id' => $data['document_id'] ?? null,
|
||||
'document_link_id' => $document->link_id ?? null, 'document_source' => isset($document) ? ['source_reference' => $document->source_reference, 'stage' => $document->stage, 'valid_until' => $document->valid_until] : null,
|
||||
'valid_until' => $data['valid_until'] ?? null, 'reason' => $data['reason'], 'reviewed_by' => $actor->id, 'updated_at' => now()->toIso8601String()];
|
||||
DB::table('desk_cases')->where('id', $id)->update(['workflow' => json_encode($workflow), 'version' => $case->version + 1, 'updated_at' => now()]);
|
||||
$case = DB::table('desk_cases')->where('id', $id)->firstOrFail();
|
||||
@@ -535,7 +673,8 @@ class VirtualDesk
|
||||
{
|
||||
$id = (string) Str::uuid();
|
||||
$version = $request->version ?? $case->version;
|
||||
DB::table('desk_events')->insert(['id' => $id, 'case_id' => $case->id, 'request_id' => $request->id ?? null, 'actor_id' => $actor->id, 'action' => $action, 'version' => $version, 'payload' => $this->encode($payload)]);
|
||||
// Use the server event time, not PostgreSQL now() (which is fixed at the enclosing transaction start).
|
||||
DB::table('desk_events')->insert(['id' => $id, 'case_id' => $case->id, 'request_id' => $request->id ?? null, 'actor_id' => $actor->id, 'action' => $action, 'version' => $version, 'payload' => $this->encode($payload), 'created_at' => now()]);
|
||||
DB::table('audit_events')->insert(['source_system' => 'virtual-desk', 'entity_type' => $request ? 'desk_requests' : 'desk_cases', 'entity_id' => $request->id ?? $case->id, 'actor_user_id' => $actor->id, 'action' => $action,
|
||||
'after_data' => json_encode(['event_id' => $id, 'event_version' => 1, 'version' => $version, 'case_id' => $case->id, 'source_hash' => config('virtual-desk.source.sha256')])]);
|
||||
$recipients = [(int) $case->user_id];
|
||||
|
||||
Reference in New Issue
Block a user