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

169 lines
8.6 KiB
PHP

<?php
namespace App\Services;
use App\Models\ExternalPayment;
use App\Models\User;
use DateTimeInterface;
use Generator;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use LogicException;
/** Immutable source facts only: no financial calculations, role impersonation or business commands. */
final class PrivateAuditSourceReader
{
/** @param list<string> $families
* @return Generator<int,array<string,mixed>>
*/
public function datasets(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 fontes apenas numa transacção de leitura consistente.');
}
foreach ($scope['families'] as $family) {
foreach (PrivateAuditCatalogue::TABLES[$family] ?? throw new LogicException('Família sem catálogo de fontes.') as $table => $columns) {
yield $this->dataset($actor, $family, $table, explode(' ', $columns));
}
$kinds = PrivateAuditCatalogue::SUPPLY_KINDS[$family];
if ($kinds !== []) {
yield $this->dataset($actor, $family, 'supply_records', explode(' ', PrivateAuditCatalogue::SUPPLY_COLUMNS), $kinds);
}
yield $this->events($actor, $family);
}
}
/** @param list<string> $columns
* @param list<string>|null $kinds
* @return array<string,mixed>
*/
private function dataset(User $actor, string $family, string $table, array $columns, ?array $kinds = null): array
{
$base = ['family' => $family, 'source' => $table, 'file' => 'dados/'.$family.'/'.$table.'.ndjson'];
if (! Schema::hasTable($table)) {
return [...$base, 'state' => 'not_installed', 'columns' => [], 'missing_columns' => $columns, 'rows' => null];
}
$available = Schema::getColumnListing($table);
$included = array_values(array_intersect($columns, $available));
$missing = array_values(array_diff($columns, $available));
$query = $this->query($actor, $table, $available);
if ($kinds !== null) {
$query->whereIn($table.'.kind', $kinds);
$query->where(function ($records) {
$records->where('kind', '!=', 'import_document')->orWhere(function ($documents) {
$documents->whereNull('data->type')->orWhereNotIn('data->type', ['bank_commitment', 'bank_support']);
});
});
}
if ($table === 'workflow_notices') {
$query->whereNotNull('requisition_id');
}
$json = $table === 'supply_records' ? ['data', 'snapshot'] : (PrivateAuditCatalogue::JSON_COLUMNS[$table] ?? []);
foreach (Schema::getColumns($table) as $definition) {
if (in_array($definition['type_name'], ['json', 'jsonb'], true)) {
$json[] = $definition['name'];
}
}
return [...$base, 'state' => $missing === [] ? 'available' : 'legacy_columns', 'columns' => $included, 'missing_columns' => $missing,
'rows' => $this->rows($query, $table, $included, array_values(array_unique($json)))];
}
/** @param list<string> $available */
private function query(User $actor, string $table, array $available): Builder
{
$query = DB::table($table);
if ($table === 'tenants') {
return $query->where('id', $actor->tenant_id);
}
if ($table === 'pa_outbox') {
return $query->join('pa_events', 'pa_events.id', '=', 'pa_outbox.event_id')
->where('pa_events.tenant_id', $actor->tenant_id)->where('pa_events.company_id', 0)->where('pa_events.unit_id', 0);
}
if (! in_array('tenant_id', $available, true)) {
throw new LogicException('Fonte sem âmbito de empresa explícito.');
}
$query->where($table.'.tenant_id', $actor->tenant_id);
if (str_starts_with($table, 'pa_') || str_starts_with($table, 'gl_')) {
// The standalone Compras adapters explicitly use company/unit zero inside the current tenant.
if (! in_array('company_id', $available, true) || ! in_array('unit_id', $available, true)) {
throw new LogicException('Preserve o âmbito do núcleo financeiro comum.');
}
$query->where($table.'.company_id', 0)->where($table.'.unit_id', 0);
}
return $query;
}
/** @param list<string> $columns
* @param list<string> $jsonColumns
* @return Generator<int,array<string,mixed>>
*/
private function rows(Builder $query, string $table, array $columns, array $jsonColumns): Generator
{
if ($columns === []) {
throw new LogicException('Fonte instalada sem campos conhecidos.');
}
$key = in_array('id', $columns, true) ? 'id' : ($table === 'pa_outbox' ? 'event_id' : 'tenant_id');
if ($table === 'external_payments') {
foreach (ExternalPayment::query()->select($columns)->orderBy('id')->lazy(100) as $payment) {
$row = [];
foreach ($columns as $column) {
$value = $payment->getAttribute($column);
$row[$column] = $value instanceof DateTimeInterface ? $value->format('Y-m-d\TH:i:s.uP') : $value;
}
yield app(PrivateAuditRedaction::class)->fields($row);
}
return;
}
foreach ($query->select(array_map(fn ($column) => $table.'.'.$column, $columns))->orderBy($table.'.'.$key)->lazy(100) as $record) {
$row = get_object_vars($record);
foreach ($jsonColumns as $column) {
if (isset($row[$column]) && is_string($row[$column])) {
$row[$column] = json_decode($row[$column], true, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
}
}
yield app(PrivateAuditRedaction::class)->fields($row);
}
}
/** @return array<string,mixed> */
private function events(User $actor, string $family): array
{
$prefixes = match ($family) {
'configuration' => ['organization.', 'company.', 'audit.private_'],
'finance' => ['budget.', 'invoice.', 'payment.', 'expense.', 'payables.', 'ledger.', 'sgf_invoice.'],
'stock' => ['stock.', 'receipt.', 'warehouse.', 'inventory.', 'warehouse_request.', 'replenishment.', 'supply.policy.', 'supply.reservation.', 'supply.delivery.', 'supply.issue.', 'supply.alternative.', 'supply.history.', 'supply.suggestion.'],
'purchasing' => ['requisition.', 'approval.', 'quotation.', 'award.', 'purchase_order.', 'opening.', 'qualification.', 'admission.', 'recommendation.', 'capital.', 'conflict.', 'equipment.', 'investment.', 'urgent.', 'op_order.', 'op_order_policy.', 'op_order_link.', 'import.', 'supply.agreement.', 'supply.contract.', 'supply.import.'],
default => throw new LogicException('Família de eventos desconhecida.'),
};
$columns = ['id', 'tenant_id', 'user_id', 'requisition_id', 'action', 'created_at'];
$query = DB::table('audit_logs')->where('tenant_id', $actor->tenant_id)->where(function ($events) use ($prefixes) {
foreach ($prefixes as $prefix) {
$events->orWhereRaw('substr(action, 1, ?) = ?', [strlen($prefix), $prefix]);
}
});
$rows = function () use ($query, $columns, $family): Generator {
foreach ($query->select([...$columns, ...($family === 'configuration' ? ['before', 'after'] : [])])->orderBy('id')->lazy(100) as $event) {
$row = get_object_vars($event);
if ($family === 'configuration') {
foreach (['before', 'after'] as $field) {
$value = $row[$field] === null ? null : json_decode($row[$field], true, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
$row[$field.'_projected'] = app(PrivateAuditRedaction::class)->configurationEvent($value);
unset($row[$field]);
}
}
yield $row;
}
};
return ['family' => $family, 'source' => 'audit_logs', 'file' => 'dados/'.$family.'/eventos.ndjson', 'state' => 'available',
'columns' => [...$columns, ...($family === 'configuration' ? ['before_projected', 'after_projected'] : [])], 'missing_columns' => [], 'rows' => $rows()];
}
}