feat: verify active opportunity management and prepare versioned resources
This commit is contained in:
@@ -32,7 +32,7 @@ class OpportunityResources
|
||||
return 'opportunity_'.($kind === 'locations' ? 'location_drafts' : $kind);
|
||||
}
|
||||
|
||||
/** @return list<object> */
|
||||
/** @return list<\stdClass> */
|
||||
public function listing(int $opportunityId, string $kind): array
|
||||
{
|
||||
$query = DB::table($this->table($kind))->where('opportunity_id', $opportunityId)->orderBy('created_at')->orderBy('id');
|
||||
@@ -44,11 +44,11 @@ class OpportunityResources
|
||||
}
|
||||
}
|
||||
|
||||
return $rows;
|
||||
return array_values($rows);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, int $opportunityId, string $kind, array $input, ?UploadedFile $file = null, ?string $id = null): object
|
||||
public function save(User $actor, int $opportunityId, string $kind, array $input, ?UploadedFile $file = null, ?string $id = null): \stdClass
|
||||
{
|
||||
abort_unless($actor->can('manage-portal'), 403);
|
||||
abort_unless($this->installed(), 503);
|
||||
@@ -56,7 +56,7 @@ class OpportunityResources
|
||||
$data = Validator::make($input, [
|
||||
'etag' => 'required|string|size:64', 'version' => ($id ? 'required' : 'nullable').'|integer|min:1',
|
||||
'creation_key' => ($id ? 'nullable' : 'required').'|uuid', 'reason' => 'required|string|min:20|max:1000',
|
||||
'payload' => 'required|array',
|
||||
'payload' => 'present|array',
|
||||
])->validate();
|
||||
$payload = $this->validatePayload($kind, $data['payload'], $opportunityId);
|
||||
$stored = null;
|
||||
@@ -73,6 +73,14 @@ class OpportunityResources
|
||||
abort_if($id && ! $record, 404);
|
||||
abort_if($record && ($record->deleted_at || (int) $record->version !== (int) $data['version']), 409, 'Recurso alterado ou eliminado; preserve o preenchimento e reveja a versão.');
|
||||
$resourceId = $id ?? $data['creation_key'];
|
||||
if ($record && $kind === 'images' && ! $file) {
|
||||
$previous = json_decode($record->payload, true);
|
||||
foreach (['derivatives', 'derived_from_sha256', 'processing_status'] as $computed) {
|
||||
if (isset($previous[$computed])) {
|
||||
$payload[$computed] = $previous[$computed];
|
||||
}
|
||||
}
|
||||
}
|
||||
abort_if(! $id && DB::table($table)->where('id', $resourceId)->exists(), 409, 'Esta criação já foi registada; recupere o recurso existente.');
|
||||
$active = DB::table($table)->where('opportunity_id', $opportunityId)->whereNull('deleted_at');
|
||||
abort_if(! $id && $active->count() >= ($kind === 'locations' ? 50 : ($kind === 'images' ? 20 : 100)), 422, 'Limite de recursos atingido.');
|
||||
@@ -81,7 +89,7 @@ class OpportunityResources
|
||||
foreach ($others as $other) {
|
||||
$otherPayload = json_decode($other->payload, true);
|
||||
$keys = ['province_id', 'district_id', 'admin_post_id', 'locality_id', 'role', 'operational_unit'];
|
||||
abort_if(array_intersect_key($payload, array_flip($keys)) == array_intersect_key($otherPayload, array_flip($keys)), 422, 'Esta localização, papel e unidade já existem.');
|
||||
abort_if(array_map(fn ($key) => $payload[$key] ?? null, $keys) === array_map(fn ($key) => $otherPayload[$key] ?? null, $keys), 422, 'Esta localização, papel e unidade já existem.');
|
||||
abort_if(($payload['is_primary'] ?? false) && ($otherPayload['is_primary'] ?? false), 422, 'Já existe localização principal; altere a anterior antes de escolher outra.');
|
||||
}
|
||||
}
|
||||
@@ -99,7 +107,7 @@ class OpportunityResources
|
||||
throw ValidationException::withMessages(['file' => 'Os mesmos bytes já estão ligados a esta oportunidade; recupere o recurso, sem duplicar.']);
|
||||
}
|
||||
$original = Storage::disk('local')->get($stored);
|
||||
abort_unless(Storage::disk('local')->put($stored, Crypt::encryptString($original)), 500, 'Falha ao cifrar original.');
|
||||
abort_unless(Storage::disk('local')->put($stored, Crypt::encryptString($original)) === true, 500, 'Falha ao cifrar original.');
|
||||
DB::table('documents')->insert(['id' => $documentId, 'source_system' => 'opportunity-resources', 'file_name' => basename($file->getClientOriginalName()), 'media_type' => $file->getMimeType(), 'storage_key' => $stored, 'storage_encryption' => 'laravel', 'sha256' => $hash, 'status' => 'quarantined', 'data_classification' => 'restricted', 'size_bytes' => $file->getSize(), 'uploaded_by' => $actor->id]);
|
||||
}
|
||||
$values = ['payload' => json_encode($payload, JSON_THROW_ON_ERROR), 'version' => $record ? $record->version + 1 : 1, 'updated_at' => now()];
|
||||
@@ -115,9 +123,6 @@ class OpportunityResources
|
||||
$this->audit($actor, $kind, $record, $after, $data['reason'], 'saved');
|
||||
$opportunity->management_version++;
|
||||
$opportunity->save();
|
||||
if ($documentId) {
|
||||
ScanDocumentForMalware::dispatch($documentId)->afterCommit();
|
||||
}
|
||||
|
||||
return $after;
|
||||
});
|
||||
@@ -128,6 +133,14 @@ class OpportunityResources
|
||||
throw $error;
|
||||
}
|
||||
|
||||
if ($documentId) {
|
||||
try {
|
||||
ScanDocumentForMalware::dispatch($documentId)->afterCommit();
|
||||
} catch (\Throwable) {
|
||||
DB::table('documents')->where('id', $documentId)->where('malware_scan_status', '!=', 'clean')->update(['status' => 'quarantined', 'malware_scan_status' => 'failed', 'malware_failure_reason' => 'queue_dispatch_failed', 'updated_at' => now()]);
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
@@ -135,16 +148,18 @@ class OpportunityResources
|
||||
public function lifecycle(User $actor, int $opportunityId, string $kind, string $id, array $input): void
|
||||
{
|
||||
abort_unless($actor->can('manage-portal'), 403);
|
||||
abort_unless($this->installed(), 503);
|
||||
$data = Validator::make($input, ['etag' => 'required|string|size:64', 'version' => 'required|integer|min:1', 'action' => 'required|in:delete,restore', 'reason' => 'required|string|min:20|max:1000', 'confirm' => 'required|accepted'])->validate();
|
||||
DB::transaction(function () use ($actor, $opportunityId, $kind, $id, $data) {
|
||||
$opportunity = $this->lock($opportunityId, $data['etag']);
|
||||
$table = $this->table($kind);
|
||||
$record = DB::table($table)->where('id', $id)->where('opportunity_id', $opportunityId)->lockForUpdate()->first();
|
||||
abort_unless($record, 404);
|
||||
abort_unless($record !== null, 404);
|
||||
abort_if((int) $record->version !== (int) $data['version'], 409, 'Versão alterada.');
|
||||
abort_if(($data['action'] === 'delete') === ($record->deleted_at !== null), 409, 'Estado já alterado.');
|
||||
$payload = json_decode($record->payload, true);
|
||||
if ($data['action'] === 'restore') {
|
||||
abort_if(DB::table($table)->where('opportunity_id', $opportunityId)->whereNull('deleted_at')->count() >= ($kind === 'locations' ? 50 : ($kind === 'images' ? 20 : 100)), 422, 'Limite de recursos ativos atingido; reconcilie antes de restaurar.');
|
||||
$this->validatePayload($kind, $payload, $opportunityId);
|
||||
// Restoration never silently reclaims a primary/cover/order occupied by another resource.
|
||||
if ($kind === 'images') {
|
||||
@@ -153,6 +168,11 @@ class OpportunityResources
|
||||
}
|
||||
if ($kind === 'locations') {
|
||||
$payload['is_primary'] = false;
|
||||
$keys = ['province_id', 'district_id', 'admin_post_id', 'locality_id', 'role', 'operational_unit'];
|
||||
foreach (DB::table($table)->where('opportunity_id', $opportunityId)->whereNull('deleted_at')->get() as $other) {
|
||||
$otherPayload = json_decode($other->payload, true);
|
||||
abort_if(array_map(fn ($key) => $payload[$key] ?? null, $keys) === array_map(fn ($key) => $otherPayload[$key] ?? null, $keys), 422, 'Outra localização ocupa esta combinação; reconcilie antes de restaurar.');
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($kind === 'locations' && $data['action'] === 'delete') {
|
||||
@@ -160,6 +180,11 @@ class OpportunityResources
|
||||
abort_if((json_decode($image->payload, true)['location_id'] ?? null) === $id, 422, 'Uma imagem usa esta localização; corrija a ligação antes de excluir.');
|
||||
}
|
||||
}
|
||||
if ($kind === 'documents' && $data['action'] === 'delete') {
|
||||
foreach (DB::table('opportunity_images')->where('opportunity_id', $opportunityId)->whereNull('deleted_at')->get() as $image) {
|
||||
abort_if((json_decode($image->payload, true)['rights_document_id'] ?? null) === $id, 422, 'Uma imagem depende deste comprovativo; corrija a ligação antes de excluir.');
|
||||
}
|
||||
}
|
||||
DB::table($table)->where('id', $id)->update(['deleted_at' => $data['action'] === 'delete' ? now() : null, 'version' => $record->version + 1, 'payload' => json_encode($payload), 'updated_at' => now()]);
|
||||
$this->audit($actor, $kind, $record, DB::table($table)->where('id', $id)->first(), $data['reason'], $data['action']);
|
||||
$opportunity->management_version++;
|
||||
@@ -224,7 +249,7 @@ class OpportunityResources
|
||||
if (! $size || $size[0] < 400 || $size[1] < 400) {
|
||||
throw ValidationException::withMessages(['file' => 'Imagem inválida ou inferior a 400 × 400 píxeis.']);
|
||||
}
|
||||
$bytes = file_get_contents($file->getRealPath());
|
||||
$bytes = file_get_contents($file->getRealPath()) ?: '';
|
||||
if (preg_match('/<\?(?:php|=)|<script\b/i', $bytes) || (str_contains($bytes, 'acTL') && $file->getMimeType() === 'image/png') || (str_contains($bytes, 'ANIM') && $file->getMimeType() === 'image/webp')) {
|
||||
throw ValidationException::withMessages(['file' => 'Imagem animada ou com conteúdo executável não permitida.']);
|
||||
}
|
||||
@@ -248,8 +273,8 @@ class OpportunityResources
|
||||
return [$key, $id];
|
||||
}
|
||||
|
||||
private function audit(User $actor, string $kind, ?object $before, object $after, string $reason, string $action): void
|
||||
private function audit(User $actor, string $kind, ?\stdClass $before, \stdClass $after, string $reason, string $action): void
|
||||
{
|
||||
DB::table('audit_events')->insert(['source_system' => 'opportunity-resources', 'entity_type' => $kind, 'actor_user_id' => $actor->id, 'action' => $action, 'data_classification' => 'restricted', 'before_data' => json_encode(['snapshot' => Crypt::encryptString(json_encode($before))]), 'after_data' => json_encode(['opportunity_id' => $after->opportunity_id, 'resource_id' => $after->id, 'version' => $after->version, 'reason' => Crypt::encryptString($reason), 'snapshot' => Crypt::encryptString(json_encode($after))])]);
|
||||
DB::table('audit_events')->insert(['source_system' => 'opportunity-resources', 'entity_type' => $kind, 'actor_user_id' => $actor->id, 'action' => $action, 'data_classification' => 'restricted', 'before_data' => json_encode(['snapshot' => Crypt::encryptString(json_encode($before, JSON_THROW_ON_ERROR))]), 'after_data' => json_encode(['opportunity_id' => $after->opportunity_id, 'resource_id' => $after->id, 'version' => $after->version, 'reason' => Crypt::encryptString($reason), 'snapshot' => Crypt::encryptString(json_encode($after, JSON_THROW_ON_ERROR))])]);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user