ready(); } private function actor(User $actor): User { abort_unless($this->ready(), 503); app(ConflictGuard::class)->lockCompany($actor); $actor = app(CurrentActor::class)->lock($actor); abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403); abort_unless($actor->hasFunctions(['import_read', 'import_prepare', 'import_customs', PurchasingRole::Procurement]), 403); return $actor; } /** @return array */ public function workspace(User $actor, Requisition $request): array { return DB::transaction(function () use ($actor, $request) { $actor = $this->actor($actor); $request = Requisition::query()->visibleTo($actor)->findOrFail($request->id); $rules = app(SupplyPlanning::class)->latest('import_legal_rule')->latest('id') ->paginate(15, ['id', 'record_key', 'version', 'state', 'data', 'snapshot', 'reason'], 'rules_page')->withQueryString(); $rules->through(fn ($rule) => [...$rule->toArray(), 'source_url' => '/requisicoes/'.$request->id.'/base-legal/fontes/'.$rule->snapshot['source_id']]); return ['requisition' => $request->only(['id', 'number']), 'rules' => $rules, 'sources' => SupplyRecord::query()->where('kind', 'import_legal_source')->latest('id') ->paginate(15, ['id', 'data', 'created_at'], 'legal_sources_page')->withQueryString(), 'items' => $request->items()->orderBy('id')->get(['id', 'description']), 'classifications' => app(SupplyPlanning::class)->latest('import_tariff')->where('data->requisition_id', $request->id)->get(['version', 'data']), 'canPropose' => $actor->hasFunctions([PurchasingRole::Procurement]), 'estimates' => app(SupplyPlanning::class)->latest('import_legal_amount')->where('data->requisition_id', $request->id)->get(), 'estimateHistory' => SupplyRecord::query()->where('kind', 'import_legal_amount')->where('data->requisition_id', $request->id)->latest('id') ->paginate(15, ['id', 'record_key', 'version', 'state', 'data', 'snapshot', 'reason'], 'legal_estimates_page')->withQueryString(), 'history' => SupplyRecord::query()->where('kind', 'import_legal_rule')->latest('id') ->paginate(15, ['id', 'record_key', 'version', 'state', 'data', 'reason', 'created_at'], 'legal_history_page')->withQueryString(), 'canManage' => $actor->hasFunctions(['import_customs']), 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id, 'types' => ImportDossier::TYPES]; }); } /** @param array $input */ public function save(User $actor, array $input, ?UploadedFile $file = null): SupplyRecord { $input = array_map(fn ($value) => is_string($value) ? trim($value) : $value, $input); $input['official_url'] = ($input['official_url'] ?? '') === '' ? null : $input['official_url']; $data = Validator::make(['record_key' => null, 'document_types' => [], 'charges' => [], ...$input, 'file' => $file], [ 'operation_key' => 'required|uuid', 'record_key' => 'present|nullable|uuid', 'version' => 'required|integer|min:0', 'action' => 'required|in:source,save,publish,withdraw', 'reason' => 'required|string|min:10|max:4000', 'source_id' => 'nullable|integer|min:1', 'title' => 'required_if:action,save|nullable|string|min:3|max:200', 'official_reference' => 'required_if:action,save,source|nullable|string|min:3|max:1000', 'official_url' => 'nullable|url:http,https|max:2000', 'citation' => 'required_if:action,save|nullable|string|min:3|max:4000', 'valid_from' => 'required_if:action,save|nullable|date_format:Y-m-d', 'valid_until' => 'nullable|date_format:Y-m-d|after_or_equal:valid_from', 'match_code' => 'required_if:action,save|nullable|string|max:40|not_regex:/[\x00-\x1F\x7F]/', 'suggested_code' => 'required_if:action,save|nullable|string|max:40|not_regex:/[\x00-\x1F\x7F]/', 'origin_country' => 'nullable|string|max:120', 'sector' => 'nullable|string|max:160', 'obligations' => 'required_if:action,save|nullable|string|min:3|max:4000', 'document_types' => 'present|array|list|max:14', 'document_types.*' => ['required', 'distinct', Rule::in(array_keys(ImportDossier::TYPES))], 'charges' => 'present|array|list|max:20', 'file' => 'nullable|file|mimes:pdf,jpg,jpeg,png|extensions:pdf,jpg,jpeg,png|max:65536', ])->validate(); unset($data['file']); $data['charges'] = app(ImportLegalAmounts::class)->definitions($data['charges']); $data['operation_key'] = strtolower($data['operation_key']); $checksum = $file === null ? null : hash_file('sha256', $file->getPathname()); $hash = hash('sha256', json_encode([$data, $checksum], JSON_THROW_ON_ERROR)); $newPath = ''; try { return DB::transaction(function () use ($actor, $data, $hash, $file, &$newPath) { $actor = $this->actor($actor); abort_unless($actor->hasFunctions(['import_customs']), 403); $retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first(); if ($retry !== null) { abort_unless($retry->kind === ($data['action'] === 'source' ? 'import_legal_source' : 'import_legal_rule') && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409); return $retry; } if ($data['action'] === 'source') { abort_unless($file !== null && $data['record_key'] === null && (int) $data['version'] === 0 && empty($data['source_id']), 422); $source = $this->storeSource($actor, $data, $file, $hash, $data['operation_key'], $newPath); app(RequisitionWorkflow::class)->audit($actor, 'import.legal_source_recorded', null, null, ['source_id' => $source->id, 'calculations_activated' => false]); return $source; } $old = $data['record_key'] === null ? null : app(SupplyPlanning::class)->latest('import_legal_rule')->where('record_key', $data['record_key'])->firstOrFail(); abort_unless((int) $data['version'] === ($old->version ?? 0), 409, 'A regra mudou. Consulte a versão actual e preserve a preparação.'); $sourceId = $data['source_id'] ?? $old?->snapshot['source_id'] ?? null; if ($data['action'] === 'save') { abort_unless($file !== null || $sourceId !== null, 422, 'Conserve o exemplar oficial antes da publicação.'); if ($file === null) { $existingSource = SupplyRecord::query()->where('kind', 'import_legal_source')->whereKey($sourceId)->firstOrFail(); abort_unless($data['official_reference'] === $existingSource->data['official_reference'] && ($data['official_url'] ?? null) === ($existingSource->data['official_url'] ?? null), 422, 'Uma fonte diferente exige o respectivo exemplar; pode alterar a citação dentro do mesmo exemplar.'); } if ($file !== null) { abort_if(! empty($data['source_id']), 422, 'Seleccione um exemplar existente ou carregue um novo.'); $source = $this->storeSource($actor, $data, $file, $hash, (string) Str::uuid(), $newPath); $sourceId = $source->id; } $payload = array_diff_key($data, array_flip(['operation_key', 'record_key', 'version', 'action', 'reason'])); $state = 'draft'; } else { abort_unless($old !== null && ($data['action'] === 'publish' ? $old->state === 'draft' : $old->state !== 'withdrawn'), 409); abort_unless($file === null && empty($data['source_id']), 422, 'A decisão conserva o exemplar da preparação; altere a fonte numa nova preparação.'); $payload = $old->data; $state = $data['action'] === 'publish' ? 'published' : 'withdrawn'; } $source = SupplyRecord::query()->where('kind', 'import_legal_source')->whereKey($sourceId)->firstOrFail(); app(ImportEvidence::class)->bytes($source); $record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_legal_rule', 'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1, 'state' => $state, 'created_by' => $actor->id, 'data' => $payload, 'snapshot' => ['source_id' => $source->id, 'source_sha256' => $source->snapshot['evidence']['sha256'], 'supersedes' => $old?->id, 'calculations_activated' => false, 'reviewed_by' => $state === 'published' ? $actor->id : null], 'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]); app(RequisitionWorkflow::class)->audit($actor, 'import.legal_'.$data['action'], null, null, ['record_id' => $record->id, 'version' => $record->version, 'state' => $state, 'source_id' => $source->id, 'calculations_activated' => false]); return $record; }); } catch (\Throwable $error) { if ($newPath !== '' && ! SupplyRecord::query()->where('snapshot->evidence->path', $newPath)->exists()) { Storage::disk('local')->delete($newPath); } throw $error; } } /** @param array $data */ private function storeSource(User $actor, array $data, UploadedFile $file, string $hash, string $operation, string &$newPath): SupplyRecord { $key = (string) Str::uuid(); $stored = $file->storeAs('import-legal/'.$actor->tenant_id, $key.'-1.'.$file->extension(), 'local'); abort_unless(is_string($stored) && $file->getSize() > 0, 503); $newPath = $stored; $checksum = hash_file('sha256', $file->getPathname()); abort_unless(is_string($checksum), 503); $source = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_legal_source', 'record_key' => $key, 'version' => 1, 'state' => 'recorded', 'created_by' => $actor->id, 'data' => ['official_reference' => $data['official_reference'], 'official_url' => $data['official_url'] ?? null], 'snapshot' => ['evidence' => ['disk' => 'local', 'path' => $newPath, 'sha256' => $checksum, 'size' => $file->getSize(), 'mime_type' => $file->getMimeType()]], 'reason' => $data['reason'], 'operation_key' => $operation, 'input_hash' => $hash, 'created_at' => now()]); app(ImportEvidence::class)->bytes($source); return $source; } /** @return Builder */ private function published(?string $date = null) { $date ??= today()->toDateString(); return SupplyRecord::query()->where('kind', 'import_legal_rule')->whereIn('id', SupplyRecord::query() ->where('kind', 'import_legal_rule')->whereIn('state', ['published', 'withdrawn']) ->where(fn ($query) => $query->where('state', 'withdrawn')->orWhere('data->valid_from', '<=', $date)) ->selectRaw('MAX(id)')->groupBy('record_key')) ->where('state', 'published'); } /** @return list> */ public function suggestions(User $actor, Requisition $request, string $code, string $origin, string $sector, string $date): array { return DB::transaction(function () use ($actor, $request, $code, $origin, $sector, $date) { $actor = $this->actor($actor); Requisition::query()->visibleTo($actor)->findOrFail($request->id); Validator::make(['date' => $date], ['date' => 'required|date_format:Y-m-d'])->validate(); return array_values($this->published($date)->where('data->match_code', $code)->orderBy('id')->get()->filter(fn ($rule) => $this->applies($rule, $origin, $sector, $date)) ->map(fn ($rule) => ['id' => $rule->id, 'version' => $rule->version, 'data' => $rule->data, 'source_sha256' => $rule->snapshot['source_sha256']])->all()); }); } private function applies(SupplyRecord $rule, string $origin, string $sector, string $date): bool { return $rule->data['valid_from'] <= $date && (($rule->data['valid_until'] ?? null) === null || $rule->data['valid_until'] >= $date) && (empty($rule->data['origin_country']) || mb_strtolower($rule->data['origin_country']) === mb_strtolower(trim($origin))) && (empty($rule->data['sector']) || mb_strtolower($rule->data['sector']) === mb_strtolower(trim($sector))); } /** @return array */ public function freeze(int $id, string $code, string $origin, string $sector, string $date): array { abort_unless($this->ready(), 503); $rule = SupplyRecord::query()->where('kind', 'import_legal_rule')->findOrFail($id); abort_unless($this->published($date)->whereKey($id)->exists(), 409, 'A regra foi substituída, retirada ou ainda não foi publicada para este período. Consulte as fontes preservadas e prepare a versão aplicável.'); abort_unless($rule->data['match_code'] === $code && $this->applies($rule, $origin, $sector, $date), 409, 'A regra não corresponde ao contexto ou ao período indicado.'); $source = SupplyRecord::query()->where('kind', 'import_legal_source')->whereKey($rule->snapshot['source_id'])->firstOrFail(); app(ImportEvidence::class)->bytes($source); return ['id' => $rule->id, 'record_key' => $rule->record_key, 'version' => $rule->version, 'data' => $rule->data, 'source_id' => $source->id, 'source_sha256' => $source->snapshot['evidence']['sha256'], 'context' => ['code' => $code, 'origin_country' => $origin, 'sector' => $sector, 'date' => $date]]; } /** @param array $frozen */ public function changed(array $frozen): bool { if (! $this->ready()) { return true; } $rule = $this->published()->where('record_key', $frozen['record_key'])->first(); if ($rule === null || $rule->id !== $frozen['id'] || ! $this->applies($rule, $frozen['context']['origin_country'], $frozen['context']['sector'], today()->toDateString())) { return true; } try { $source = SupplyRecord::query()->where('kind', 'import_legal_source')->whereKey($rule->snapshot['source_id'])->firstOrFail(); app(ImportEvidence::class)->bytes($source); } catch (HttpExceptionInterface|ModelNotFoundException) { return true; } return false; } public function source(User $actor, Requisition $request, int $id): SupplyRecord { return DB::transaction(function () use ($actor, $request, $id) { $actor = $this->actor($actor); Requisition::query()->visibleTo($actor)->findOrFail($request->id); $source = SupplyRecord::query()->where('kind', 'import_legal_source')->findOrFail($id); app(ImportEvidence::class)->bytes($source); return $source; }); } }