$families * @return Generator> */ 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 $columns * @param list|null $kinds * @return array */ 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 $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 $columns * @param list $jsonColumns * @return Generator> */ 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 */ 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()]; } }