Files
compras/app/Services/PrivateAuditOriginals.php
T
nala 060c119ba1
tests / ci (push) Waiting to run
commit compras2 2811
2026-11-28 15:45:52 +02:00

103 lines
5.5 KiB
PHP

<?php
namespace App\Services;
use App\Models\SupplyRecord;
use App\Models\User;
use Generator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\FilesystemException;
use LogicException;
/** Verified original bytes; bank-specific imports and all People stores are outside this contract. */
final class PrivateAuditOriginals
{
/** @param list<string> $families
* @return Generator<int,array<string,mixed>>
*/
public function files(User $actor, array $families): Generator
{
$scope = app(PrivateAuditAccess::class)->authorise($actor, $families);
$actor = $scope['actor'];
if (DB::transactionLevel() < 1 || (DB::getDriverName() === 'pgsql'
&& (DB::selectOne('SHOW transaction_read_only')->transaction_read_only ?? null) !== 'on')) {
throw new LogicException('Recolher originais na transacção de leitura consistente.');
}
foreach (['purchasing' => ['supplier_documents', 'supplier_id', 'suppliers'], 'stock' => ['receipt_documents', 'goods_receipt_id', 'goods_receipts']] as $family => [$table, $parentColumn, $parent]) {
if (! in_array($family, $scope['families'], true) || ! Schema::hasTable($table)) {
continue;
}
foreach (DB::table($table)->where('tenant_id', $actor->tenant_id)->orderBy('id')->lazy(100) as $document) {
$parentId = $document->{$parentColumn};
abort_unless(DB::table($parent)->where('tenant_id', $actor->tenant_id)->where('id', $parentId)->exists(), 409, 'Preserve a ligação do documento à sua origem.');
$prefix = $actor->tenant_id.'/'.$parentId.'/';
$bytes = $this->bounded($table, $document->path, $prefix, (int) $document->size, $document->sha256);
yield $this->entry($family, $table, (int) $document->id, $document->original_name, $document->mime_type, $bytes);
}
}
$kinds = [];
if (in_array('purchasing', $scope['families'], true)) {
$kinds = ['import_document', 'import_legal_source'];
}
if (in_array('finance', $scope['families'], true)) {
$kinds[] = 'import_cost_doc';
}
if ($kinds === [] || ! Schema::hasTable('supply_records')) {
return;
}
foreach (SupplyRecord::query()->where('tenant_id', $actor->tenant_id)->whereIn('kind', $kinds)->orderBy('id')->lazy(100) as $record) {
if ($record->kind === 'import_document' && in_array($record->data['type'] ?? null, ['bank_commitment', 'bank_support'], true)) {
continue;
}
if ($record->kind !== 'import_legal_source') {
abort_unless(DB::table('purchase_orders')->where('tenant_id', $actor->tenant_id)->where('id', $record->purchase_order_id)->exists(), 409, 'Preserve a origem do documento de importação.');
}
$evidence = $record->snapshot['evidence'] ?? [];
$bytes = app(ImportEvidence::class)->bytes($record);
$family = $record->kind === 'import_cost_doc' ? 'finance' : 'purchasing';
yield $this->entry($family, $record->kind, $record->id, $evidence['original_name'] ?? $evidence['name'] ?? null,
$evidence['mime'] ?? $evidence['mime_type'] ?? null, $bytes);
}
}
private function bounded(string $diskName, string $path, string $prefix, int $size, string $sha): string
{
abort_unless(str_starts_with($path, $prefix) && preg_match('/\A[A-Za-z0-9_-]+\.[A-Za-z0-9]+\z/D', substr($path, strlen($prefix)))
&& $size > 0 && $size <= 2097152 && preg_match('/^[a-f0-9]{64}$/D', $sha), 409, 'Original sem referência verificável.');
$disk = Storage::disk($diskName);
try {
$root = realpath($disk->path(''));
$resolved = realpath($disk->path($path));
$expected = $root === false ? '' : str_replace('\\', '/', $root).'/'.$prefix;
$normal = $resolved === false ? '' : str_replace('\\', '/', $resolved);
$within = PHP_OS_FAMILY === 'Windows' ? str_starts_with(strtolower($normal), strtolower($expected)) : str_starts_with($normal, $expected);
abort_unless($root !== false && $resolved !== false && $within && is_file($resolved) && ! is_link($disk->path($path)), 409, 'Original indisponível no local autorizado.');
$stream = $disk->readStream($path);
abort_unless(is_resource($stream), 409, 'Original indisponível.');
try {
$bytes = stream_get_contents($stream, 2097153);
} finally {
fclose($stream);
}
} catch (FilesystemException) {
abort(409, 'Original indisponível ou alterado.');
}
abort_unless(is_string($bytes) && strlen($bytes) === $size && hash_equals($sha, hash('sha256', $bytes)), 409, 'Original indisponível ou alterado.');
return $bytes;
}
/** @return array<string,mixed> */
private function entry(string $family, string $source, int $id, ?string $name, ?string $mime, string $bytes): array
{
$extension = match ($mime) {
'application/pdf' => 'pdf', 'image/jpeg' => 'jpg', 'image/png' => 'png', default => 'bin',
};
return ['family' => $family, 'source' => $source, 'source_id' => $id, 'original_name' => $name, 'mime_type' => $mime,
'file' => 'originais/'.$family.'/'.$source.'/'.$id.'.'.$extension, 'size' => strlen($bytes), 'sha256' => hash('sha256', $bytes), 'bytes' => $bytes];
}
}