This commit is contained in:
2026-11-02 08:06:45 +02:00
parent e4f520092e
commit 2a4169162b
108 changed files with 3793 additions and 88 deletions
+1
View File
@@ -8,4 +8,5 @@ require_once __DIR__.'/src/PaymentDecisions.php';
require_once __DIR__.'/src/PaymentDecisionSchema.php';
require_once __DIR__.'/src/SupplierSettlements.php';
require_once __DIR__.'/src/SettlementSchema.php';
require_once __DIR__.'/src/ReversalSchema.php';
require_once __DIR__.'/src/SettlementHttp.php';
+87
View File
@@ -0,0 +1,87 @@
<?php
namespace Tempo\Finance\Payables;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/** Explicit QA upgrade; never run automatically on existing demos or operational databases. */
final class ReversalSchema
{
public const TABLES = ['ps_reversal_proposals', 'ps_reversals'];
public static function install(): void
{
$db = DB::connection();
if (! app()->environment('payable-testing') || $db->getDriverName() !== 'pgsql' || $db->getConfig('host') !== '127.0.0.1'
|| ! preg_match('/^(compras_receipts_test_|payable_sgf_)[a-f0-9]{12}$/D', $db->getDatabaseName())
|| $db->selectOne('select current_database() as d')->d !== $db->getDatabaseName()) {
throw new \LogicException('Reversal upgrade requires isolated QA.');
}
foreach (SettlementSchema::TABLES as $table) {
if (! Schema::hasTable($table)) {
throw new \LogicException('Complete settlement schema required.');
}
}
if (array_filter(self::TABLES, fn ($t) => Schema::hasTable($t)) || Schema::hasColumn('ps_proposals', 'allocation_cycle')) {
throw new \LogicException('Upgrade already present or incomplete; no automatic repair.');
}
DB::transaction(function (): void {
Schema::create('ps_reversal_proposals', function (Blueprint $t): void {
$t->id();
foreach (['tenant_id', 'company_id', 'unit_id'] as $field) {
$t->unsignedBigInteger($field);
}
$t->foreignId('allocation_id')->unique()->constrained('ps_allocations');
$t->string('source_revision', 64);
$t->unsignedBigInteger('prepared_by');
$t->string('prepared_person');
$t->text('reason');
$t->timestamp('created_at');
});
Schema::create('ps_reversals', function (Blueprint $t): void {
$t->id();
foreach (['tenant_id', 'company_id', 'unit_id'] as $field) {
$t->unsignedBigInteger($field);
}
$t->foreignId('allocation_id')->unique()->constrained('ps_allocations');
$t->foreignId('proposal_id')->unique()->constrained('ps_reversal_proposals');
$t->foreignId('payment_id')->constrained('ps_payments');
$t->foreignId('obligation_id')->constrained('pa_obligations');
$t->bigInteger('amount_minor');
$t->string('source_revision', 64);
$t->unsignedBigInteger('actor_id');
$t->string('person');
$t->text('reason');
$t->timestamp('created_at');
});
foreach (self::TABLES as $table) {
DB::unprepared("CREATE TRIGGER ps_history_immutable BEFORE UPDATE OR DELETE ON {$table} FOR EACH ROW EXECUTE FUNCTION pa_append_only()");
}
// DB protection of the entire compensation, including context and distinct identities.
DB::unprepared(<<<'SQL'
CREATE FUNCTION ps_reversal_integrity() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM ps_allocations a JOIN ps_reversal_proposals p ON p.allocation_id=a.id
WHERE a.id=NEW.allocation_id AND p.id=NEW.proposal_id
AND (a.tenant_id,a.company_id,a.unit_id)=(NEW.tenant_id,NEW.company_id,NEW.unit_id)
AND (p.tenant_id,p.company_id,p.unit_id)=(NEW.tenant_id,NEW.company_id,NEW.unit_id)
AND a.payment_id=NEW.payment_id AND a.obligation_id=NEW.obligation_id
AND a.amount_minor=NEW.amount_minor AND NEW.amount_minor>0
AND a.source_revision=NEW.source_revision AND p.source_revision=NEW.source_revision
AND p.prepared_by<>NEW.actor_id AND p.prepared_person<>NEW.person
) THEN RAISE EXCEPTION 'Invalid full allocation compensation'; END IF;
RETURN NEW;
END $$;
CREATE TRIGGER ps_reversal_integrity BEFORE INSERT ON ps_reversals FOR EACH ROW EXECUTE FUNCTION ps_reversal_integrity();
ALTER TABLE ps_proposals ADD COLUMN allocation_cycle bigint NOT NULL DEFAULT 0;
ALTER TABLE ps_proposals DROP CONSTRAINT ps_proposals_payment_id_plan_hash_unique;
ALTER TABLE ps_proposals ADD CONSTRAINT ps_proposals_payment_plan_cycle_unique UNIQUE (payment_id,plan_hash,allocation_cycle);
ALTER TABLE ps_allocations DROP CONSTRAINT ps_allocations_payment_id_obligation_id_unique;
ALTER TABLE ps_allocations ADD CONSTRAINT ps_allocations_decision_obligation_unique UNIQUE (decision_id,obligation_id);
SQL);
});
}
}
+11 -2
View File
@@ -2,6 +2,7 @@
namespace Tempo\Finance\Payables;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
@@ -35,6 +36,9 @@ abstract class SettlementHttp extends Controller
return DB::transaction(function () use ($r): array {
$s = app(static::SERVICE);
$user = $r->user();
if (! $user instanceof User) {
abort(401);
}
$settlements = $s->engine($user)->settlements()->listing();
$base = $s->listing($user);
foreach ($base['obligations'] as &$o) {
@@ -43,12 +47,13 @@ abstract class SettlementHttp extends Controller
}
unset($o);
$permissions = [];
foreach (['payment_prepare', 'payment_confirm', 'allocation_prepare', 'allocation_confirm'] as $action) {
foreach (['payment_prepare', 'payment_confirm', 'allocation_prepare', 'allocation_confirm', 'reversal_prepare', 'reversal_confirm'] as $action) {
$permissions[$action] = $s->can($user, $action);
}
return ['synthetic_only' => true, 'obligations' => $base['obligations'], 'payments' => $settlements['payments'],
'allocation_proposals' => $settlements['proposals'], 'allocations' => $settlements['allocations'], 'events' => $settlements['events'],
'reversals_available' => $settlements['reversals_available'], 'reversal_proposals' => $settlements['reversal_proposals'], 'reversals' => $settlements['reversals'],
'permissions' => $permissions, 'current_actor' => $user->id];
});
}
@@ -61,7 +66,11 @@ abstract class SettlementHttp extends Controller
public function page(Request $r): Response
{
$data = $this->data($r);
$settings = ['host' => static::MODE === 'compras' ? 'Compras autónomo' : 'ERP SGF', 'actor' => $r->user()->name,
$user = $r->user();
if (! $user instanceof User) {
abort(401);
}
$settings = ['host' => static::MODE === 'compras' ? 'Compras autónomo' : 'ERP SGF', 'actor' => $user->name,
'csrf' => csrf_token(), 'context' => $r->session()->get('company_context.token'), 'api' => '/api/supplier-payments',
'obligations_url' => static::MODE === 'compras' ? '/obrigacoes-fornecedores' : '/supplier-payables'];
+116 -6
View File
@@ -135,12 +135,33 @@ final class SupplierSettlements
return 0;
}
return (int) $db->table('ps_allocations')->where($scope)->where('obligation_id', $obligation)->sum('amount_minor');
$allocated = (int) $db->table('ps_allocations')->where($scope)->where('obligation_id', $obligation)->sum('amount_minor');
$reversed = $db->getSchemaBuilder()->hasTable('ps_reversals')
? (int) $db->table('ps_reversals')->where($scope)->where('obligation_id', $obligation)->sum('amount_minor') : 0;
return $allocated - $reversed;
}
private function unallocated(\stdClass $payment): int
{
return (int) $payment->amount_minor - (int) $this->q('allocations')->where('payment_id', $payment->id)->sum('amount_minor');
return (int) $payment->amount_minor - (int) $this->q('allocations')->where('payment_id', $payment->id)->sum('amount_minor')
+ ($this->reversalsAvailable() ? (int) $this->q('reversals')->where('payment_id', $payment->id)->sum('amount_minor') : 0);
}
private function reversalsAvailable(): bool
{
if (! method_exists($this->db, 'getSchemaBuilder')) {
throw new \LogicException('A ligação exige consulta explícita do esquema financeiro.');
}
return $this->db->getSchemaBuilder()->hasTable('ps_reversals')
&& $this->db->getSchemaBuilder()->hasTable('ps_reversal_proposals')
&& $this->db->getSchemaBuilder()->hasColumn('ps_proposals', 'allocation_cycle');
}
private function cycle(int $payment): int
{
return $this->reversalsAvailable() ? (int) $this->q('reversals')->where('payment_id', $payment)->max('id') : 0;
}
/** @param array<string,mixed> $data
@@ -148,7 +169,8 @@ final class SupplierSettlements
*/
public function command(string $action, array $data, string $key): array
{
$permissions = ['payment-prepare' => 'payment_prepare', 'payment-decide' => 'payment_confirm', 'allocation-prepare' => 'allocation_prepare', 'allocation-decide' => 'allocation_confirm'];
$permissions = ['payment-prepare' => 'payment_prepare', 'payment-decide' => 'payment_confirm', 'allocation-prepare' => 'allocation_prepare', 'allocation-decide' => 'allocation_confirm',
'reversal-prepare' => 'reversal_prepare', 'reversal-confirm' => 'reversal_confirm'];
if (! isset($permissions[$action]) || ! preg_match('/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/Di', $key)) {
throw new \InvalidArgumentException('Acção ou chave inválida.');
}
@@ -164,6 +186,7 @@ final class SupplierSettlements
$result = match ($action) {
'payment-prepare' => $this->preparePayment($data), 'payment-decide' => $this->decidePayment($data),
'allocation-prepare' => $this->prepareAllocation($data), 'allocation-decide' => $this->decideAllocation($data),
'reversal-prepare' => $this->prepareReversal($data), 'reversal-confirm' => $this->confirmReversal($data),
};
if ($old && Payables::canonical(json_decode($old->result, true, 32, JSON_THROW_ON_ERROR)) !== Payables::canonical($result)) {
throw new \DomainException('Resultado anterior incompatível; não repetir o efeito.');
@@ -283,7 +306,14 @@ final class SupplierSettlements
$this->referenceScope('allocation_aliases', 'reference_key', $this->key($reference));
// Semantic recovery precedes balance checks: an already-applied plan remains recoverable.
$alias = $this->q('allocation_aliases')->where('reference_key', $this->key($reference))->value('proposal_id');
$old = $this->q('proposals')->where(fn ($q) => $q->where('reference_key', $this->key($reference))->orWhere('id', $alias ?? 0)->orWhere(fn ($q) => $q->where('payment_id', $p->id)->where('plan_hash', $hash)))->get();
$old = $this->q('proposals')->where(fn ($q) => $q->where('reference_key', $this->key($reference))->orWhere('id', $alias ?? 0))->get();
if ($old->isEmpty()) {
$semantic = $this->q('proposals')->where('payment_id', $p->id)->where('plan_hash', $hash);
if ($this->reversalsAvailable()) {
$semantic->where('allocation_cycle', $this->cycle((int) $p->id));
}
$old = $semantic->get();
}
if ($old->isNotEmpty()) {
if ($old->count() !== 1 || (int) $old->first()->payment_id !== (int) $p->id || $old->first()->plan_hash !== $hash) {
throw new \DomainException('Referência de afectação incompatível.');
@@ -297,7 +327,8 @@ final class SupplierSettlements
$this->checkPlan($p, $plan, true);
$id = $this->db->table('ps_proposals')->insertGetId($this->scope + ['payment_id' => $p->id, 'reference_key' => $this->key($reference),
'reference' => $reference, 'plan_hash' => $hash, 'plan' => Payables::canonical($plan), 'prepared_by' => $this->actor,
'prepared_person' => $this->person, 'reason' => $reason, 'created_at' => $this->stamp()]);
'prepared_person' => $this->person, 'reason' => $reason, 'created_at' => $this->stamp()]
+ ($this->reversalsAvailable() ? ['allocation_cycle' => $this->cycle((int) $p->id)] : []));
$this->event((int) $p->id, 'supplier_allocation.proposed', ['proposal_id' => $id, 'plan_hash' => $hash]);
return ['proposal_id' => $id];
@@ -316,7 +347,11 @@ final class SupplierSettlements
throw new \DomainException('Montante fora dos limites.');
}
$total += $line['amount_minor'];
if ($checkBalances && ($line['amount_minor'] > $o['balance_minor'] || $this->q('allocations')->where(['payment_id' => $p->id, 'obligation_id' => $o['id']])->exists())) {
$active = $this->q('allocations')->where(['payment_id' => $p->id, 'obligation_id' => $o['id']]);
if ($this->reversalsAvailable()) {
$active->whereNotIn('id', $this->q('reversals')->select('allocation_id'));
}
if ($checkBalances && ($line['amount_minor'] > $o['balance_minor'] || $active->exists())) {
throw new \DomainException('Saldo insuficiente ou ligação pagamento/obrigação já confirmada; sem edição silenciosa.');
}
}
@@ -343,6 +378,9 @@ final class SupplierSettlements
$reason = $this->reason($d['reason']);
$plan = json_decode($proposal->plan, true, 64, JSON_THROW_ON_ERROR);
$old = $this->q('allocation_decisions')->where('proposal_id', $proposal->id)->first();
if (! $old && $d['decision'] === 'confirmed' && $this->reversalsAvailable() && (int) $proposal->allocation_cycle !== $this->cycle((int) $p->id)) {
throw new \DomainException('Ciclo de afectação desactualizado após reversão; prepare uma nova proposta.');
}
$this->checkPlan($p, $plan, ! $old && $d['decision'] === 'confirmed');
if ($old) {
if ($old->decision !== $d['decision'] || $old->reason !== $reason) {
@@ -363,6 +401,75 @@ final class SupplierSettlements
return ['proposal_id' => (int) $proposal->id, 'decision_id' => $id];
}
private function reversible(int $id, mixed $revision): \stdClass
{
if (! $this->reversalsAvailable()) {
throw new \DomainException('Reversões não instaladas neste ensaio.');
}
$a = $this->q('allocations')->where('id', $id)->first() ?? throw new \DomainException('Afectação fora do contexto.');
$p = $this->payment((int) $a->payment_id);
$o = ($this->obligation)((int) $a->obligation_id);
if ($revision !== $a->source_revision || $revision !== $o['source_revision'] || $o['currency'] !== $p->currency || $o['supplier_key'] !== $p->supplier_key) {
throw new \DomainException('Versão ou origem incompatível; reversão pendente de revisão.');
}
return $a;
}
/** @param array<string,mixed> $d
* @return array<string,int>
*/
private function prepareReversal(array $d): array
{
$this->exact($d, ['allocation_id', 'source_revision', 'reason']);
$a = $this->reversible($this->id($d['allocation_id']), $d['source_revision']);
$reason = $this->reason($d['reason']);
$old = $this->q('reversal_proposals')->where('allocation_id', $a->id)->first();
if ($old) {
if ($old->reason !== $reason || $old->source_revision !== $d['source_revision']) {
throw new \DomainException('Reversão já proposta com conteúdo diferente.');
}
return ['proposal_id' => (int) $old->id];
}
$id = $this->db->table('ps_reversal_proposals')->insertGetId($this->scope + ['allocation_id' => $a->id,
'source_revision' => $a->source_revision, 'prepared_by' => $this->actor, 'prepared_person' => $this->person,
'reason' => $reason, 'created_at' => $this->stamp()]);
$this->event((int) $a->payment_id, 'supplier_allocation.reversal_proposed', ['proposal_id' => $id, 'allocation_id' => $a->id]);
return ['proposal_id' => $id];
}
/** @param array<string,mixed> $d
* @return array<string,int>
*/
private function confirmReversal(array $d): array
{
$this->exact($d, ['proposal_id', 'reason']);
if (! $this->reversalsAvailable()) {
throw new \DomainException('Reversões não instaladas neste ensaio.');
}
$proposal = $this->q('reversal_proposals')->where('id', $this->id($d['proposal_id']))->first() ?? throw new \DomainException('Proposta de reversão fora do contexto.');
$a = $this->reversible((int) $proposal->allocation_id, $proposal->source_revision);
$this->independent($proposal);
$reason = $this->reason($d['reason']);
$old = $this->q('reversals')->where('allocation_id', $a->id)->first();
if ($old) {
if ((int) $old->proposal_id !== (int) $proposal->id || $old->reason !== $reason) {
throw new \DomainException('Afectação já revertida; conteúdo incompatível.');
}
return ['proposal_id' => (int) $proposal->id, 'reversal_id' => (int) $old->id];
}
$id = $this->db->table('ps_reversals')->insertGetId($this->scope + ['allocation_id' => $a->id, 'proposal_id' => $proposal->id,
'payment_id' => $a->payment_id, 'obligation_id' => $a->obligation_id, 'amount_minor' => $a->amount_minor,
'source_revision' => $a->source_revision, 'actor_id' => $this->actor, 'person' => $this->person, 'reason' => $reason, 'created_at' => $this->stamp()]);
$this->event((int) $a->payment_id, 'supplier_allocation.reversed', ['proposal_id' => $proposal->id, 'reversal_id' => $id,
'allocation_id' => $a->id, 'amount_minor' => (int) $a->amount_minor]);
return ['proposal_id' => (int) $proposal->id, 'reversal_id' => $id];
}
/** @return array<string,mixed> */
public function listing(): array
{
@@ -377,6 +484,9 @@ final class SupplierSettlements
$proposals = $this->q('proposals')->orderBy('id')->get()->map(fn ($p) => (array) $p + ['decision' => $this->q('allocation_decisions')->where('proposal_id', $p->id)->first()])->all();
return ['synthetic_only' => true, 'payments' => $payments, 'proposals' => $proposals, 'allocations' => $this->q('allocations')->orderBy('id')->get()->all(),
'reversals_available' => $this->reversalsAvailable(),
'reversal_proposals' => $this->reversalsAvailable() ? $this->q('reversal_proposals')->orderBy('id')->get()->all() : [],
'reversals' => $this->reversalsAvailable() ? $this->q('reversals')->orderBy('id')->get()->all() : [],
'events' => $this->q('events')->orderBy('id')->get()->all(), 'current_actor' => $this->actor];
});
}
+12 -2
View File
@@ -19,14 +19,24 @@ body{font:17px system-ui;color:#172f29;background:#f4f6f5;margin:0}main{max-widt
<?php if ($data['permissions']['allocation_prepare'] && $confirmed && $eligible): ?><section><h2>3. Propor afectações</h2><form data-action="allocation-prepare"><label>Pagamento confirmado<select name="payment_id"><?php foreach ($confirmed as $p): ?><option value="<?= $e($p['id']) ?>">#<?= $e($p['id']) ?> · <?= $e($p['fact_reference']) ?> · Por afectar <?= $money($p['unallocated_minor']) ?></option><?php endforeach ?></select></label><label>Referência estável da afectação<input name="reference" required pattern="SIM-[A-Z0-9][A-Z0-9._-]{2,95}" placeholder="SIM-ALLOC-001"></label><div data-lines><div class="line" data-line><label>Obrigação<select data-obligation><?php $options(); ?></select></label><label>Valor a afectar (MZN)<input data-amount required inputmode="decimal" pattern="[0-9]+(\.[0-9]{1,2})?" placeholder="4000.00"></label><button type="button" data-remove>Remover linha</button></div></div><button type="button" data-add>Adicionar outra obrigação</button><label>Fundamento<textarea name="reason" required minlength="3" maxlength="2000"></textarea></label><p>Mesmo fornecedor e moeda. O excedente fica por afectar. Não existe reembolso/crédito automático nem edição de uma afectação confirmada.</p><button>Submeter afectações sem abater saldo</button></form></section><?php endif ?>
<section id="allocation-proposals"><h2>4. Propostas de afectação</h2><p>A proposta não reduz a dívida. Troque para Validar para confirmar a afectação com outra identidade.</p><?php foreach ($data['allocation_proposals'] as $p): ?><article><h3>Proposta #<?= $e($p['id']) ?> · <?= $e($p['reference']) ?> · Pagamento #<?= $e($p['payment_id']) ?></h3><p>Preparador #<?= $e($p['prepared_by']) ?> · <?= $e($p['reason']) ?></p><ul><?php foreach (json_decode($p['plan'], true) as $line): ?><li>Obrigação #<?= $e($line['obligation_id']) ?>: <?= $money($line['amount_minor']) ?> · versão <?= $e($line['source_revision']) ?></li><?php endforeach ?></ul><p>Estado: <?= $p['decision'] ? $e($p['decision']->decision === 'confirmed' ? 'Afectação confirmada' : 'Rejeitada') : 'Proposta — sem efeito no saldo' ?></p>
<?php if ($data['permissions']['allocation_confirm'] && ! $p['decision'] && (int) $p['prepared_by'] !== $data['current_actor']): ?><form data-action="allocation-decide"><input type="hidden" name="proposal_id" value="<?= $e($p['id']) ?>"><label>Decisão<select name="decision"><option value="confirmed">Confirmar estas afectações</option><option value="rejected">Rejeitar</option></select></label><label>Fundamento da decisão<textarea name="reason" required minlength="3" maxlength="2000"></textarea></label><button>Confirmar decisão e revalidar saldos</button></form><?php endif ?></article><?php endforeach ?></section>
<section id="reversals"><h2>5. Reversão integral e nova afectação</h2><p>Propor não altera saldos. Confirmar com outra identidade compensa integralmente a afectação original e volta a disponibilizar esse montante do pagamento. O pagamento continua confirmado: não há cancelamento bancário. Depois, use «Propor afectações» com uma nova referência para corrigir o valor.</p>
<?php if (! ($data['reversals_available'] ?? false)): ?><p>Actualização de reversões ainda não aplicada neste ensaio. Os saldos e o percurso anterior permanecem disponíveis.</p><?php else: ?>
<?php foreach ($data['allocations'] as $a): $reversal = null; $proposal = null; foreach ($data['reversals'] as $r) if ((int) $r->allocation_id === (int) $a->id) $reversal = $r; foreach ($data['reversal_proposals'] as $r) if ((int) $r->allocation_id === (int) $a->id) $proposal = $r; ?>
<article><h3>Afectação #<?= $e($a->id) ?> · Pagamento #<?= $e($a->payment_id) ?> · Obrigação #<?= $e($a->obligation_id) ?></h3><p>Original preservado: <?= $money($a->amount_minor) ?> · Versão <?= $e($a->source_revision) ?></p>
<?php if ($reversal): ?><p>Revertida integralmente por movimento #<?= $e($reversal->id) ?> · <?= $money($reversal->amount_minor) ?> · actor #<?= $e($reversal->actor_id) ?> · <?= $e($reversal->reason) ?></p>
<?php elseif ($proposal): ?><p>Proposta de reversão #<?= $e($proposal->id) ?> · Preparador #<?= $e($proposal->prepared_by) ?> · <?= $e($proposal->reason) ?> · Sem efeito no saldo</p>
<?php if (($data['permissions']['reversal_confirm'] ?? false) && (int) $proposal->prepared_by !== $data['current_actor']): ?><form data-action="reversal-confirm"><input type="hidden" name="proposal_id" value="<?= $e($proposal->id) ?>"><label>Motivo da confirmação independente<textarea name="reason" required minlength="3" maxlength="2000"></textarea></label><button>Confirmar reversão integral de <?= $money($a->amount_minor) ?></button></form><?php endif ?>
<?php elseif ($data['permissions']['reversal_prepare'] ?? false): ?><form data-action="reversal-prepare"><input type="hidden" name="allocation_id" value="<?= $e($a->id) ?>"><input type="hidden" name="source_revision" value="<?= $e($a->source_revision) ?>"><label>Motivo obrigatório da reversão integral<textarea name="reason" required minlength="3" maxlength="2000"></textarea></label><button>Propor reversão integral sem alterar saldo</button></form><?php endif ?>
<?php if ($proposal): ?><details><summary>Proposta original de reversão preservada</summary><pre><?= $e(json_encode($proposal, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) ?></pre></details><?php endif ?></article><?php endforeach ?>
<?php endif ?></section>
<section><h2>Histórico durável</h2><?php foreach ($data['events'] as $event): ?><details><summary>#<?= $e($event->id) ?> · <?= $e($event->kind) ?> · actor #<?= $e($event->actor_id) ?> · <?= $e($event->created_at) ?></summary><pre><?= $e($event->payload) ?></pre></details><?php endforeach ?></section>
<p>Correcções, reversões, reconciliação e novos pagamentos sobre documentos com histórico importado ficam para âmbito próprio. Os originais e as decisões confirmadas não são editados ou apagados.</p>
<p>Reversões parciais, cancelamento bancário, reconciliação e novos pagamentos sobre documentos com histórico importado ficam fora desta entrega. Os originais e as decisões confirmadas não são editados ou apagados.</p>
</main><script>
const settings=<?= json_encode($settings, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_THROW_ON_ERROR) ?>;
document.querySelector('#reload').onclick=()=>location.reload();
for(const selector of document.querySelectorAll('[data-origin]')){const sync=()=>selector.form.elements.source_revision.value=selector.selectedOptions[0]?.dataset.revision??'';selector.onchange=sync;sync();}
for(const form of document.querySelectorAll('[data-action]')){
const add=form.querySelector('[data-add]');if(add){const lines=form.querySelector('[data-lines]');const template=lines.firstElementChild.cloneNode(true);add.onclick=()=>{if(lines.children.length<50)lines.append(template.cloneNode(true));};lines.onclick=e=>{if(e.target.matches('[data-remove]')&&lines.children.length>1)e.target.closest('[data-line]').remove();};}
form.onsubmit=async e=>{e.preventDefault();let body=Object.fromEntries(new FormData(form));for(const key of ['obligation_id','payment_id','proposal_id'])if(key in body)body[key]=Number(body[key]);if(form.dataset.action==='allocation-prepare')body.allocations=[...form.querySelectorAll('[data-line]')].map(line=>{const select=line.querySelector('[data-obligation]');return {obligation_id:Number(select.value),source_revision:select.selectedOptions[0]?.dataset.revision??'',amount:line.querySelector('[data-amount]').value};});const signature=JSON.stringify(body);if(form.dataset.signature!==signature){form.dataset.signature=signature;form.dataset.key=crypto.randomUUID();}const buttons=[...form.querySelectorAll('button')];buttons.forEach(b=>b.disabled=true);document.querySelector('#error').textContent='';document.querySelector('#status').textContent='A processar. Aguarde antes de repetir.';try{const r=await fetch(settings.api+'/'+form.dataset.action,{method:'POST',credentials:'same-origin',headers:{Accept:'application/json','Content-Type':'application/json','X-CSRF-TOKEN':settings.csrf,'X-SGF-Context':settings.context??'','Idempotency-Key':form.dataset.key},body:signature});const d=await r.json();if(!r.ok){document.querySelector('#error').textContent=Object.values(d.errors??{}).flat().join(' ')||d.message||'Não foi possível concluir; consulte o histórico.';document.querySelector('#error').focus();return;}location.hash=form.dataset.action==='allocation-decide'?'obligation-balances':form.dataset.action==='allocation-prepare'?'allocation-proposals':'payments';location.reload();}catch{document.querySelector('#error').textContent='Não foi possível confirmar o resultado. Actualize a consulta e confira o histórico antes de repetir.';document.querySelector('#error').focus();}finally{document.querySelector('#status').textContent='';buttons.forEach(b=>b.disabled=false);}};
form.onsubmit=async e=>{e.preventDefault();let body=Object.fromEntries(new FormData(form));for(const key of ['obligation_id','payment_id','proposal_id','allocation_id'])if(key in body)body[key]=Number(body[key]);if(form.dataset.action==='allocation-prepare')body.allocations=[...form.querySelectorAll('[data-line]')].map(line=>{const select=line.querySelector('[data-obligation]');return {obligation_id:Number(select.value),source_revision:select.selectedOptions[0]?.dataset.revision??'',amount:line.querySelector('[data-amount]').value};});const signature=JSON.stringify(body);if(form.dataset.signature!==signature){form.dataset.signature=signature;form.dataset.key=crypto.randomUUID();}const buttons=[...form.querySelectorAll('button')];buttons.forEach(b=>b.disabled=true);document.querySelector('#error').textContent='';document.querySelector('#status').textContent='A processar. Aguarde antes de repetir.';try{const r=await fetch(settings.api+'/'+form.dataset.action,{method:'POST',credentials:'same-origin',headers:{Accept:'application/json','Content-Type':'application/json','X-CSRF-TOKEN':settings.csrf,'X-SGF-Context':settings.context??'','Idempotency-Key':form.dataset.key},body:signature});const d=await r.json();if(!r.ok){document.querySelector('#error').textContent=Object.values(d.errors??{}).flat().join(' ')||d.message||'Não foi possível concluir; consulte o histórico.';document.querySelector('#error').focus();return;}location.hash=form.dataset.action.startsWith('reversal-')?'reversals':form.dataset.action==='allocation-decide'?'obligation-balances':form.dataset.action==='allocation-prepare'?'allocation-proposals':'payments';location.reload();}catch{document.querySelector('#error').textContent='Não foi possível confirmar o resultado. Actualize a consulta e confira o histórico antes de repetir.';document.querySelector('#error').focus();}finally{document.querySelector('#status').textContent='';buttons.forEach(b=>b.disabled=false);}};
}
</script></body></html>