environment('testing') && (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:') || ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName()))); } /** @return array */ public function source(User $actor, int $id): array { $payment = ExternalPayment::query()->whereKey($id)->firstOrFail(); $invoice = Invoice::query()->whereIn('purchase_order_id', PurchaseOrder::query()->visibleTo($actor)->select('id'))->whereKey($payment->invoice_id)->firstOrFail(); try { $facts = collect(app(SupplierPayables::class)->readPaymentHistory($actor, $invoice->id))->firstWhere('id', $id); } catch (\DomainException) { abort(409, 'O histórico auditado do pagamento está indeterminado.'); } abort_unless($facts !== null && $facts['status'] === 'confirmed', 409, 'A imputação exige um pagamento confirmado e o seu histórico auditado.'); abort_unless(is_int($facts['amount_minor']) && $facts['amount_minor'] > 0 && is_string($facts['currency']) && preg_match('/^[A-Z]{3}$/D', $facts['currency']) && is_string($facts['reviewed_at']) && trim($facts['reviewed_at']) !== '' && is_int($facts['reviewed_by']) && $facts['reviewed_by'] > 0, 409, 'A confirmação tem dados indeterminados; conserve os originais para conferência.'); $categories = []; foreach ($invoice->items()->orderBy('id')->get() as $item) { $line = DB::table('purchase_order_items')->where('tenant_id', $actor->tenant_id)->where('purchase_order_id', $invoice->purchase_order_id) ->where('id', $item->purchase_order_item_id)->first(['category']); abort_unless($line !== null && is_string($line->category) && trim($line->category) !== '', 409, 'Há linhas da factura sem categoria documental determinada.'); $categories[$line->category] = $line->category; } $categories = array_values($categories); sort($categories, SORT_STRING); abort_unless($categories !== [], 409, 'A factura exige linhas com categorias documentais para esta imputação.'); $source = ['payment' => $facts, 'invoice_id' => $invoice->id, 'invoice_number' => $invoice->getAttribute('number'), 'purchase_order_id' => $invoice->purchase_order_id, 'categories' => $categories]; return [...$source, 'fingerprint' => hash('sha256', json_encode($source, JSON_THROW_ON_ERROR))]; } private function actor(User $actor): User { abort_unless($this->ready(), 503); app(ConflictGuard::class)->lockCompany($actor); $actor = app(CurrentActor::class)->lock($actor); abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403); abort_unless($actor->hasFunctions(['admin', 'finance']) && app(SupplierPayables::class)->can($actor, 'view'), 403); return $actor; } public function current(int $payment): ?SupplyRecord { return SupplyRecord::query()->where('kind', 'expense_allocation')->where('data->payment_id', $payment)->latest('version')->first(); } /** @return array */ public function projection(User $actor, int $payment): array { $record = $this->current($payment); if ($record === null) { return ['state' => 'unallocated', 'allocations' => []]; } if (! $this->ready()) { return ['state' => 'indeterminate', 'allocations' => []]; } try { $source = $this->source($actor, $payment); } catch (HttpExceptionInterface $error) { if (! in_array($error->getStatusCode(), [404, 409], true)) { throw $error; } return ['state' => 'indeterminate', 'allocations' => []]; } if (($record->snapshot['fingerprint'] ?? '') !== $source['fingerprint']) { return ['state' => 'indeterminate', 'allocations' => []]; } $audit = DB::table('audit_logs')->where('tenant_id', $actor->tenant_id)->where('user_id', $record->created_by) ->where('action', 'expense.allocation_recorded')->where('after->record->id', $record->id)->latest('id')->value('after'); $saved = is_string($audit) ? (json_decode($audit, true, 64, JSON_THROW_ON_ERROR)['record'] ?? null) : null; if (! is_array($saved) || ($saved['data'] ?? null) !== $record->data || ($saved['snapshot'] ?? null) !== $record->snapshot || ($saved['version'] ?? null) !== $record->version || ($saved['input_hash'] ?? null) !== $record->input_hash) { return ['state' => 'indeterminate', 'allocations' => []]; } return ['state' => 'allocated', 'allocations' => $record->data['allocations']]; } /** @return array */ public function workspace(User $actor, int $payment): array { return DB::transaction(function () use ($actor, $payment) { $actor = $this->actor($actor); $source = $this->source($actor, $payment); $current = $this->current($payment); $row = fn (SupplyRecord $record) => ['id' => $record->id, 'version' => $record->version, 'reason' => $record->reason, 'data' => ['allocations' => $record->data['allocations']]]; return ['payment' => ['id' => $payment, 'invoice_id' => $source['invoice_id'], 'invoice_number' => $source['invoice_number'], 'amount_minor' => (string) $source['payment']['amount_minor'], 'currency' => $source['payment']['currency']], 'categories' => $source['categories'], 'fingerprint' => $source['fingerprint'], 'current' => $current === null ? null : $row($current), 'history' => SupplyRecord::query()->where('kind', 'expense_allocation')->where('data->payment_id', $payment)->latest('version')->paginate(15)->withQueryString()->through($row), 'canWrite' => $actor->hasFunctions(['finance']), 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id]; }); } /** @param array $input */ public function save(User $actor, int $payment, array $input): SupplyRecord { $data = Validator::make($input, ['operation_key' => 'required|uuid', 'version' => 'required|integer|min:0', 'fingerprint' => ['required', 'regex:/^[a-f0-9]{64}$/D'], 'reason' => 'required|string|min:10|max:4000', 'allocations' => 'required|array|list|min:1|max:100', 'allocations.*' => 'array:category,amount', 'allocations.*.category' => 'required|string|max:255|distinct:strict', 'allocations.*.amount' => ['required', 'string', 'regex:/^\d{1,12}(\.\d{1,2})?$/D']])->validate(); $data['operation_key'] = strtolower($data['operation_key']); $data['version'] = (int) $data['version']; usort($data['allocations'], fn ($a, $b) => strcmp($a['category'], $b['category'])); $hash = hash('sha256', json_encode([$payment, $data], JSON_THROW_ON_ERROR)); return DB::transaction(function () use ($actor, $payment, $data, $hash) { $actor = $this->actor($actor); abort_unless($actor->hasFunctions(['finance']), 403); ExternalPayment::query()->whereKey($payment)->lockForUpdate()->firstOrFail(); $source = $this->source($actor, $payment); $order = PurchaseOrder::query()->whereKey($source['purchase_order_id'])->firstOrFail(); app(OrderPartsAccess::class)->assertProcess($actor, $order, true); abort_unless(hash_equals($source['fingerprint'], $data['fingerprint']), 409, 'As origens mudaram. Reveja a factura e o pagamento.'); $retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first(); if ($retry !== null) { abort_unless($retry->kind === 'expense_allocation' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409); return $retry; } $old = $this->current($payment); abort_unless(($old->version ?? 0) === $data['version'], 409, 'A imputação mudou. Reveja a versão actual.'); $total = BigInteger::zero(); $allocations = []; foreach ($data['allocations'] as $row) { if (! in_array($row['category'], $source['categories'], true)) { throw ValidationException::withMessages(['allocations' => 'Seleccione apenas categorias das linhas desta factura.']); } $minor = BigDecimal::of($row['amount'])->multipliedBy(100)->toBigInteger(); $total = $total->plus($minor); $allocations[] = ['category' => $row['category'], 'amount_minor' => (string) $minor]; } if (! $total->isEqualTo($source['payment']['amount_minor'])) { throw ValidationException::withMessages(['allocations' => 'A soma das imputações deve corresponder exactamente ao pagamento confirmado.']); } $record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'expense_allocation', 'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1, 'state' => 'allocated', 'created_by' => $actor->id, 'data' => ['payment_id' => $payment, 'invoice_id' => $source['invoice_id'], 'currency' => $source['payment']['currency'], 'amount_minor' => (string) $total, 'allocations' => $allocations], 'snapshot' => $source, 'reason' => trim($data['reason']), 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]); app(RequisitionWorkflow::class)->audit($actor, 'expense.allocation_recorded', null, $old?->toArray(), ['record' => $record->toArray()]); return $record; }); } }