Files
compras/app/Services/ImportCostDocumentHealth.php
T
nala dc73540558
tests / ci (push) Waiting to run
commit melhorias compras6
2026-11-23 06:37:16 +02:00

99 lines
4.6 KiB
PHP

<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use LogicException;
/** Aggregate, bounded technical inspection; never repairs, discloses or removes evidence. */
final class ImportCostDocumentHealth
{
/** @return array<string,mixed> */
public function inspect(int $limit = 1000): array
{
abort_unless(app()->runningInConsole() && ! auth()->check() && ! request()->hasSession(), 403);
if ($limit < 1 || $limit > 10000) {
throw new LogicException('Limite fora do intervalo permitido.');
}
return DB::transaction(function () use ($limit): array {
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
}
$result = ['checked_at' => now()->toIso8601String(), 'ok' => false, 'complete' => false,
'documents_checked' => 0, 'files_checked' => 0, 'missing' => 0, 'altered' => 0,
'invalid_reference' => 0, 'unreferenced' => 0, 'reasons' => []];
$disk = Storage::disk('local');
$records = DB::table('supply_records')->where('kind', 'import_cost_doc')->orderBy('id')->limit($limit + 1)->get();
$limited = $records->count() > $limit;
$root = realpath($disk->path(''));
foreach ($records->take($limit) as $record) {
$result['documents_checked']++;
$snapshot = json_decode($record->snapshot, true, 64, JSON_THROW_ON_ERROR);
$evidence = $snapshot['evidence'] ?? [];
$prefix = 'import-costs/'.$record->tenant_id.'/'.$record->purchase_order_id.'/';
$path = $evidence['path'] ?? null;
if (($evidence['disk'] ?? null) !== 'local' || ! is_string($path)
|| ! preg_match('/^[a-f0-9-]{36}$/D', $record->record_key)
|| ! preg_match('/^'.preg_quote($prefix.$record->record_key.'-'.$record->version, '/').'\.(pdf|jpg|jpeg|png)$/D', $path)
|| ! is_int($evidence['size'] ?? null) || $evidence['size'] < 1 || $evidence['size'] > 2097152
|| ! is_string($evidence['sha256'] ?? null) || ! preg_match('/^[a-f0-9]{64}$/D', $evidence['sha256'])
|| ! DB::table('purchase_orders')->where('tenant_id', $record->tenant_id)->where('id', $record->purchase_order_id)->exists()) {
$result['invalid_reference']++;
continue;
}
$resolved = realpath($disk->path($path));
if ($resolved === false || ! is_file($resolved)) {
$result['missing']++;
continue;
}
$absolute = str_replace('\\', '/', $resolved);
$boundary = $root === false ? null : str_replace('\\', '/', $root).'/import-costs/';
if ($boundary === null || ! (PHP_OS_FAMILY === 'Windows'
? str_starts_with(strtolower($absolute), strtolower($boundary)) : str_starts_with($absolute, $boundary))) {
$result['invalid_reference']++;
continue;
}
if (filesize($resolved) !== $evidence['size']) {
$result['altered']++;
continue;
}
$checksum = hash_file('sha256', $resolved);
if (! is_string($checksum) || ! hash_equals($evidence['sha256'], $checksum)) {
$result['altered']++;
}
}
foreach ($disk->getDriver()->listContents('import-costs', true) as $entry) {
if (! $entry->isFile()) {
continue;
}
if ($result['files_checked'] >= $limit) {
$limited = true;
break;
}
$result['files_checked']++;
if (! DB::table('supply_records')->where('kind', 'import_cost_doc')->where('snapshot->evidence->path', $entry->path())->exists()) {
$result['unreferenced']++;
}
}
foreach (['missing', 'altered', 'invalid_reference', 'unreferenced'] as $reason) {
if ($result[$reason] > 0) {
$result['reasons'][] = $reason;
}
}
if ($limited) {
$result['reasons'][] = 'limit_reached';
}
$result['complete'] = ! $limited;
$result['ok'] = $result['reasons'] === [];
return $result;
});
}
}