commit de compras
This commit is contained in:
@@ -1,8 +1,10 @@
|
||||
<?php
|
||||
require_once __DIR__.'/src/Payables.php';
|
||||
require_once __DIR__.'/src/ReceiptReader.php';
|
||||
require_once __DIR__.'/src/Workspace.php';
|
||||
require_once __DIR__.'/src/PayablesSchema.php';
|
||||
require_once __DIR__.'/src/HistoricalPayments.php';
|
||||
require_once __DIR__.'/src/HistoricalCapture.php';
|
||||
require_once __DIR__.'/src/HistorySchema.php';
|
||||
require_once __DIR__.'/src/PaymentDecisions.php';
|
||||
require_once __DIR__.'/src/PaymentDecisionSchema.php';
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
namespace Tempo\Finance\Payables;
|
||||
|
||||
/** Validated value confined to one scoped read window; never a command history source. */
|
||||
final readonly class HistoricalCapture
|
||||
{
|
||||
private function __construct(private array $scope,private array $source,private array $capture) {}
|
||||
public static function fromPayments(array $scope,array $source,array $payments):self
|
||||
{
|
||||
return new self($scope,$source,HistoricalPayments::capture($source,$payments));
|
||||
}
|
||||
public function forSource(array $scope,array $source):array
|
||||
{
|
||||
if($scope!==$this->scope||($source!==$this->source&&$source!==($this->source+['revision'=>Payables::revision($this->source),'missing'=>Payables::missing($this->source)])))throw new \DomainException('Captura histórica fora da origem, versão ou contexto da janela.');
|
||||
return $this->capture;
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,8 @@ final class Payables
|
||||
public const VERSION = 'COMMON-PAYABLE-SOURCE-SIM-v1';
|
||||
|
||||
public function __construct(private ConnectionInterface $db, private int $actor, private string $person, private array $scope,
|
||||
private \Closure $authorize, private \Closure $loadSource, private ?\Closure $loadHistory = null, private ?\Closure $authorizeRead = null) {}
|
||||
private \Closure $authorize, private \Closure $loadSource, private ?\Closure $loadHistory = null, private ?\Closure $authorizeRead = null,
|
||||
private ?\Closure $authorizeSettlementRead = null) {}
|
||||
|
||||
public static function canonical(array $data): string
|
||||
{
|
||||
@@ -129,7 +130,12 @@ final class Payables
|
||||
throw new \DomainException('Passagem de histórico não activada nesta instalação.');
|
||||
}
|
||||
|
||||
return HistoricalPayments::capture($source, ($this->loadHistory)($source['local_id']));
|
||||
$history = ($this->loadHistory)($source['local_id']);
|
||||
if ($history instanceof HistoricalCapture) {
|
||||
if (! $availabilityChecked) throw new \DomainException('Capturas de janela são apenas de leitura; comandos exigem histórico actual.');
|
||||
return $history->forSource($this->scope, $source);
|
||||
}
|
||||
return HistoricalPayments::capture($source, $history);
|
||||
}
|
||||
|
||||
private function eligibility(array $source, bool $historical): array
|
||||
@@ -176,6 +182,10 @@ final class Payables
|
||||
$compatible ? [] : ['Origem ou histórico divergente; saldo não presumido.'])];
|
||||
}
|
||||
|
||||
public function receipt(string $key):?array
|
||||
{
|
||||
return ReceiptReader::read($this->db,'recognition',$this->scope,$this->actor,$key,$this->authorizeRead);
|
||||
}
|
||||
public function settlements(): SupplierSettlements
|
||||
{
|
||||
return new SupplierSettlements($this->db, $this->actor, $this->person, $this->scope, $this->authorize, function (int $id): array {
|
||||
@@ -195,7 +205,7 @@ final class Payables
|
||||
|
||||
return $position + ['supplier_key' => hash('sha256', self::canonical([$source['instance'], $source['company'], $source['supplier_id']])),
|
||||
'supplier_name' => $source['supplier_name']];
|
||||
});
|
||||
}, $this->authorizeSettlementRead);
|
||||
}
|
||||
|
||||
public function positionForSource(int $local): ?array
|
||||
@@ -345,14 +355,14 @@ final class Payables
|
||||
}
|
||||
|
||||
/** Bounded source window with independent proposal/event pages; commands never use these snapshots. */
|
||||
public function listingPage(array $localSources, int $proposalPage = 1, int $eventPage = 1, int $perPage = 25): array
|
||||
public function listingPage(array $localSources, int $proposalPage = 1, int $eventPage = 1, int $perPage = 25, bool $withEvidence = true): array
|
||||
{
|
||||
if (count($localSources) > 100 || ! in_array($perPage, [25, 100], true) || $proposalPage < 1 || $eventPage < 1
|
||||
|| array_filter($localSources, fn ($id) => ! is_int($id) || $id < 1)) {
|
||||
throw new \InvalidArgumentException('Janela de leitura financeira inválida.');
|
||||
}
|
||||
|
||||
return $this->db->transaction(function () use ($localSources, $proposalPage, $eventPage, $perPage) {
|
||||
return $this->db->transaction(function () use ($localSources, $proposalPage, $eventPage, $perPage, $withEvidence) {
|
||||
$this->authorizeRead === null ? ($this->authorize)('view') : ($this->authorizeRead)();
|
||||
$documents = []; $current = [];
|
||||
foreach ($localSources as $id) {
|
||||
@@ -376,6 +386,7 @@ final class Payables
|
||||
$origin = $origins->get($obligation->source_id);
|
||||
return $this->position($obligation, $origin ? ($current[$origin->source_key] ?? null) : null, $page);
|
||||
})->all();
|
||||
if (! $withEvidence) return ['synthetic_only' => true, 'documents' => $documents, 'obligations' => $positions];
|
||||
$proposals = $this->q('proposals')->whereIn('source_id', $sources())->orderByDesc('id')->paginate($perPage, ['*'], 'proposal_page', $proposalPage);
|
||||
$events = $this->q('events')->whereIn('source_id', $sources())->orderByDesc('id')->paginate($perPage, ['*'], 'event_page', $eventPage);
|
||||
$meta = fn ($p) => ['page' => $p->currentPage(), 'last_page' => $p->lastPage(), 'total' => $p->total(), 'per_page' => $p->perPage()];
|
||||
@@ -387,6 +398,12 @@ final class Payables
|
||||
});
|
||||
}
|
||||
|
||||
/** Same position calculation, without loading presentation-only proposal/event pages. */
|
||||
public function positionsPage(array $localSources): array
|
||||
{
|
||||
return $this->listingPage($localSources, 1, 1, 100, false);
|
||||
}
|
||||
|
||||
public function listing(array $localSources): array
|
||||
{
|
||||
return $this->db->transaction(function () use ($localSources) {
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
namespace Tempo\Finance\Payables;
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
final class ReceiptReader
|
||||
{
|
||||
public static function read(ConnectionInterface $db,string $domain,array $scope,int $actor,string $key,?\Closure $authorize):?array
|
||||
{
|
||||
$table=match($domain){'recognition'=>'pa_commands','settlement'=>'ps_commands',default=>throw new \InvalidArgumentException('Domínio de comprovativo inválido.')};
|
||||
if(!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('Chave de pedido inválida.');
|
||||
if($authorize===null)throw new \DomainException('Consulta sem autorização própria de leitura.');
|
||||
return $db->transaction(function()use($db,$table,$domain,$scope,$actor,$key,$authorize){$authorize();if(!$db->getSchemaBuilder()->hasTable($table))throw new \DomainException('Comprovativos deste domínio indisponíveis.');$r=$db->table($table)->where($scope)->where('actor_id',$actor)->where('command_key',$key)->first();return $r?['domain'=>$domain,'command_key'=>$r->command_key,'recorded_at'=>$r->created_at,'request_hash'=>$r->request_hash,'result'=>json_decode($r->result,true,128,JSON_THROW_ON_ERROR),'historical_receipt_only'=>true,'operation_executed'=>false]:null;});
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,19 @@ abstract class SettlementHttp extends Controller
|
||||
|
||||
protected const SERVICE = '';
|
||||
|
||||
/** Host-specific document navigation; the native legacy composition keeps its existing contract. */
|
||||
protected function obligationOptions(Request $request): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/** Null preserves the native host's existing listing. */
|
||||
protected function settlementOptions(Request $request): ?array
|
||||
{
|
||||
return null;
|
||||
}
|
||||
protected function ledgerSettings(Request $request):array { return []; }
|
||||
|
||||
protected function guard(): void
|
||||
{
|
||||
$db = DB::connection();
|
||||
@@ -32,18 +45,40 @@ abstract class SettlementHttp extends Controller
|
||||
private function data(Request $r): array
|
||||
{
|
||||
$this->guard();
|
||||
$options = $this->obligationOptions($r);
|
||||
$paymentOptions = $this->settlementOptions($r);
|
||||
$own = DB::transactionLevel() === 0;
|
||||
|
||||
return DB::transaction(function () use ($r): array {
|
||||
return DB::transaction(function () use ($r, $options, $paymentOptions, $own): array {
|
||||
if ($own && static::MODE === 'sgf' && $paymentOptions !== null) DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
$s = app(static::SERVICE);
|
||||
$user = $r->user();
|
||||
if (! $user instanceof User) {
|
||||
abort(401);
|
||||
}
|
||||
$settlements = $s->engine($user)->settlements()->listing();
|
||||
$base = $s->listing($user);
|
||||
$engine = $s->engine($user)->settlements();
|
||||
try {
|
||||
$settlements = $paymentOptions === null ? $engine->listing() : $engine->listingPage($paymentOptions);
|
||||
} catch (\DomainException $e) {
|
||||
if ($paymentOptions === null) throw $e;
|
||||
abort(403, $e->getMessage());
|
||||
}
|
||||
$base = static::MODE === 'sgf' ? $s->listing($user, $options) : $s->listing($user);
|
||||
$proposals = null; $sources = null;
|
||||
if (static::MODE === 'sgf' && $base['obligations']) {
|
||||
$scope = array_intersect_key($base['obligations'][0], array_flip(['tenant_id', 'company_id', 'unit_id']));
|
||||
abort_unless(count($scope) === 3, 409, 'Âmbito da obrigação incompleto.');
|
||||
foreach ($base['obligations'] as $o) abort_unless(array_intersect_key($o, $scope) === $scope, 409, 'Âmbito de obrigações divergente.');
|
||||
// Recognition refers to one exact proposal, not whichever versions happen to be on the first evidence page.
|
||||
$proposals = DB::table('pa_proposals')->where($scope)->whereIn('id', array_column($base['obligations'], 'proposal_id'))->get()->keyBy('id');
|
||||
$sources = DB::table('pa_sources')->where($scope)->whereIn('id', array_column($base['obligations'], 'source_id'))->get()->keyBy('id');
|
||||
}
|
||||
foreach ($base['obligations'] as &$o) {
|
||||
$proposal = $base['proposals']->first(fn ($p) => (int) $p->id === (int) $o['proposal_id']);
|
||||
$proposal = $proposals === null ? $base['proposals']->first(fn ($p) => (int) $p->id === (int) $o['proposal_id']) : $proposals->get($o['proposal_id']);
|
||||
if (static::MODE === 'sgf' && $proposal && ((int) $proposal->source_id !== (int) $o['source_id'] || $proposal->source_revision !== $o['source_revision'])) $proposal = null;
|
||||
$o['origin_snapshot'] = $proposal ? json_decode($proposal->snapshot, true, 64, JSON_THROW_ON_ERROR) : null;
|
||||
$source = $sources?->get($o['source_id']);
|
||||
if ($source) $o['evidence_url'] = '/supplier-payables?'.http_build_query(['source' => $source->local_source_id], '', '&', PHP_QUERY_RFC3986);
|
||||
}
|
||||
unset($o);
|
||||
$permissions = [];
|
||||
@@ -54,7 +89,9 @@ abstract class SettlementHttp extends Controller
|
||||
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];
|
||||
'permissions' => $permissions, 'current_actor' => $user->id]
|
||||
+ (static::MODE === 'sgf' ? ['obligation_pagination' => $base['pagination']['documents'], 'obligation_query' => $base['listing_query']] : [])
|
||||
+ (isset($settlements['pagination']) ? ['settlement_pagination' => $settlements['pagination'], 'settlement_query' => array_replace($base['listing_query'], $settlements['listing_query'])] : []);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -73,8 +110,11 @@ abstract class SettlementHttp extends Controller
|
||||
$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'];
|
||||
if (static::MODE === 'sgf' && isset($data['obligation_query']['source'])) {
|
||||
$settings['obligations_url'] .= '?'.http_build_query(['source' => $data['obligation_query']['source']], '', '&', PHP_QUERY_RFC3986);
|
||||
}
|
||||
|
||||
return response(Workspace::settlements($data, $settings))->header('Cache-Control', 'no-store');
|
||||
return response(Workspace::settlements($data, $settings+$this->ledgerSettings($r)))->header('Cache-Control', 'no-store');
|
||||
}
|
||||
|
||||
public function command(Request $r, string $action): JsonResponse
|
||||
|
||||
@@ -12,15 +12,20 @@ final class SupplierSettlements
|
||||
* @param array<string,int> $scope
|
||||
* @param \Closure(string):void $authorize
|
||||
* @param \Closure(int):array<string,mixed> $obligation
|
||||
* @param null|\Closure():void $authorizeRead Explicit host authority for paged payment reads; never used by commands.
|
||||
*/
|
||||
public function __construct(private ConnectionInterface $db, private int $actor, private string $person,
|
||||
private array $scope, private \Closure $authorize, private \Closure $obligation) {}
|
||||
private array $scope, private \Closure $authorize, private \Closure $obligation, private ?\Closure $authorizeRead = null) {}
|
||||
|
||||
private function q(string $table): Builder
|
||||
{
|
||||
return $this->db->table('ps_'.$table)->where($this->scope);
|
||||
}
|
||||
|
||||
public function receipt(string $key):?array
|
||||
{
|
||||
return ReceiptReader::read($this->db,'settlement',$this->scope,$this->actor,$key,$this->authorizeRead);
|
||||
}
|
||||
private function stamp(): string
|
||||
{
|
||||
return date('Y-m-d H:i:s');
|
||||
@@ -489,7 +494,86 @@ final class SupplierSettlements
|
||||
return ['proposal_id' => (int) $proposal->id, 'reversal_id' => $id];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
/** Bounded read windows. Commands keep the original fresh balance and version checks.
|
||||
* @param array<string,mixed> $options
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function listingPage(array $options = []): array
|
||||
{
|
||||
$defaults = ['payments_page' => 1, 'allocation_proposals_page' => 1, 'allocations_page' => 1, 'payment_events_page' => 1,
|
||||
'payment_per_page' => 25, 'payment_q' => '', 'payment_state' => 'all'];
|
||||
if (array_diff(array_keys($options), [...array_keys($defaults), 'payment'])) throw new \InvalidArgumentException('Filtro financeiro desconhecido.');
|
||||
$o = array_replace($defaults, $options);
|
||||
$o['payment_q'] ??= '';
|
||||
foreach (['payments_page', 'allocation_proposals_page', 'allocations_page', 'payment_events_page', 'payment_per_page', 'payment'] as $key) {
|
||||
if (! array_key_exists($key, $o)) continue;
|
||||
$value = filter_var($o[$key], FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
||||
if ($value === false || is_bool($o[$key]) || ($key === 'payment_per_page' ? ! in_array($value, [25, 100], true) : ($key !== 'payment' && $value > 100000))) throw new \InvalidArgumentException('Página ou pagamento inválido.');
|
||||
$o[$key] = $value;
|
||||
}
|
||||
if (! is_string($o['payment_q']) || mb_strlen($o['payment_q']) > 100 || ! in_array($o['payment_state'], ['all', 'proposed', 'confirmed', 'rejected'], true)) throw new \InvalidArgumentException('Pesquisa ou estado inválido.');
|
||||
$o['payment_q'] = trim($o['payment_q']);
|
||||
|
||||
$own = $this->db->transactionLevel() === 0;
|
||||
return $this->db->transaction(function () use ($o, $own): array {
|
||||
if ($own && $this->authorizeRead !== null) $this->db->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
if ($this->authorizeRead !== null) ($this->authorizeRead)();
|
||||
else ($this->authorize)('payments_view');
|
||||
$root = $this->q('payments');
|
||||
if (isset($o['payment'])) {
|
||||
if (! (clone $root)->where('id', $o['payment'])->exists()) throw new \DomainException('Pagamento indisponível neste contexto.');
|
||||
$root->where('id', $o['payment']);
|
||||
}
|
||||
if ($o['payment_q'] !== '') {
|
||||
$needle = '%'.str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $o['payment_q']).'%';
|
||||
$root->where('fact_reference', 'ilike', $needle);
|
||||
}
|
||||
if ($o['payment_state'] !== 'all') {
|
||||
$state = $o['payment_state'];
|
||||
$method = $state === 'proposed' ? 'whereNotExists' : 'whereExists';
|
||||
$root->$method(function ($q) use ($state) {
|
||||
$q->selectRaw('1')->from('ps_payment_decisions')->where($this->scope)->whereColumn('ps_payment_decisions.payment_id', 'ps_payments.id');
|
||||
if ($state !== 'proposed') $q->where('decision', $state);
|
||||
});
|
||||
}
|
||||
$matching = fn () => (clone $root)->select('id');
|
||||
$size = $o['payment_per_page'];
|
||||
$payments = (clone $root)->orderByDesc('id')->paginate($size, ['*'], 'payments_page', $o['payments_page']);
|
||||
$ids = array_map(fn ($p) => $p->id, $payments->items());
|
||||
$decisions = $this->q('payment_decisions')->whereIn('payment_id', $ids)->get()->keyBy('payment_id');
|
||||
$reversible = $this->reversalsAvailable();
|
||||
$allocated = $this->q('allocations')->whereIn('payment_id', $ids)->selectRaw('payment_id, sum(amount_minor) AS amount')->groupBy('payment_id')->pluck('amount', 'payment_id');
|
||||
$reversed = $reversible ? $this->q('reversals')->whereIn('payment_id', $ids)->selectRaw('payment_id, sum(amount_minor) AS amount')->groupBy('payment_id')->pluck('amount', 'payment_id') : collect();
|
||||
$positions = array_map(function ($p) use ($decisions, $allocated, $reversed) {
|
||||
$decision = $decisions->get($p->id);
|
||||
return (array) $p + ['decision' => $decision, 'state' => $decision?->decision ?? 'proposed',
|
||||
'unallocated_minor' => $decision?->decision === 'confirmed' ? (int) $p->amount_minor - (int) $allocated->get($p->id, 0) + (int) $reversed->get($p->id, 0) : null,
|
||||
'reconciliation' => 'not_implemented'];
|
||||
}, $payments->items());
|
||||
$proposals = $this->q('proposals')->whereIn('payment_id', $matching())->orderByDesc('id')->paginate($size, ['*'], 'allocation_proposals_page', $o['allocation_proposals_page']);
|
||||
$proposalDecisions = $this->q('allocation_decisions')->whereIn('proposal_id', array_map(fn ($p) => $p->id, $proposals->items()))->get()->keyBy('proposal_id');
|
||||
$plans = array_map(fn ($p) => (array) $p + ['decision' => $proposalDecisions->get($p->id)], $proposals->items());
|
||||
$allocations = $this->q('allocations')->whereIn('payment_id', $matching())->orderByDesc('id')->paginate($size, ['*'], 'allocations_page', $o['allocations_page']);
|
||||
$allocationIds = array_map(fn ($a) => $a->id, $allocations->items());
|
||||
$origins = $this->db->table('pa_obligations AS o')->join('pa_sources AS s', 's.id', '=', 'o.source_id')
|
||||
->whereIn('o.id', array_map(fn ($a) => $a->obligation_id, $allocations->items()));
|
||||
foreach ($this->scope as $key => $value) $origins->where('o.'.$key, $value)->whereColumn('s.'.$key, 'o.'.$key);
|
||||
$origins = $origins->get(['o.id', 's.local_source_id'])->keyBy('id');
|
||||
foreach ($allocations->items() as $a) $a->local_source_id = $origins->get($a->obligation_id)?->local_source_id;
|
||||
$events = $this->q('events')->whereIn('payment_id', $matching())->orderByDesc('id')->paginate($size, ['*'], 'payment_events_page', $o['payment_events_page']);
|
||||
$meta = fn ($p) => ['page' => $p->currentPage(), 'last_page' => $p->lastPage(), 'total' => $p->total(), 'per_page' => $p->perPage()];
|
||||
return ['synthetic_only' => true, 'payments' => $positions, 'proposals' => $plans, 'allocations' => $allocations->items(), 'events' => $events->items(),
|
||||
'reversals_available' => $reversible,
|
||||
'reversal_proposals' => $reversible ? $this->q('reversal_proposals')->whereIn('allocation_id', $allocationIds)->orderBy('id')->get()->all() : [],
|
||||
'reversals' => $reversible ? $this->q('reversals')->whereIn('allocation_id', $allocationIds)->orderBy('id')->get()->all() : [],
|
||||
'pagination' => ['payments' => $meta($payments), 'allocation_proposals' => $meta($proposals), 'allocations' => $meta($allocations), 'payment_events' => $meta($events)],
|
||||
'listing_query' => $o, 'current_actor' => $this->actor];
|
||||
});
|
||||
}
|
||||
|
||||
/** Legacy composition; deliberately unchanged until that host opts into the bounded reader.
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function listing(): array
|
||||
{
|
||||
return $this->db->transaction(function (): array {
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
<style>body{font:16px system-ui;background:#f3f6f5;color:#142b28;margin:0}main{max-width:1100px;margin:auto;padding:24px}header,section{background:white;padding:24px;margin:18px 0;border:1px solid #d5e0dc;border-radius:12px}h1{font-size:28px}h2{font-size:20px}.notice{padding:16px;background:#fff2cc}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px}label{display:block;margin:12px 0}select,textarea,button{font:inherit;padding:10px;max-width:100%}textarea{display:block;width:90%}button{background:#125a4b;color:white;border:0;border-radius:6px;cursor:pointer}button:disabled{opacity:.5}table{border-collapse:collapse;width:100%}td,th{text-align:left;padding:12px;border-bottom:1px solid #ddd}.scroll{overflow:auto}.amount{font-size:26px;font-weight:bold}pre{white-space:pre-wrap;overflow-wrap:anywhere}a{color:#125a4b}</style></head><body><main>
|
||||
<header><?php if(session()->get('payables_demo_entry')): ?><p><a href="/demo">Trocar função ou sair da demonstração</a></p><?php endif ?><a href="<?= $e($settings['return_url']??'/') ?>">← <?= $e($settings['return_label']??'Voltar à aplicação') ?></a><p><?= $e($settings['host']) ?> · <?= $e($settings['actor']) ?></p><h1>Obrigações a fornecedores</h1><p><?= $e($settings['organisation']) ?></p><p class="notice">ENSAIO SINTÉTICO — SEM UTILIZAÇÃO REAL. Documento, dívida, pagamento e contabilidade são factos distintos. Este percurso reconhece o principal e, quando activado, preserva o histórico existente.</p><p>Fornecedor, montantes e conferência são reutilizados da factura. Vencimento desconhecido não é substituído por uma data ou zero dias de atraso.</p></header>
|
||||
<?php if(isset($data['history_receipt_notice'])): ?><p class="notice"><?= $e($data['history_receipt_notice']) ?></p><?php endif ?>
|
||||
<?php $pageNav=function(string $key)use($data,$settings,$e){if(!isset($data['pagination'][$key]))return;$p=$data['pagination'][$key];$param=['documents'=>'page','proposals'=>'proposal_page','events'=>'event_page'][$key];echo '<nav aria-label="Paginação '.$e($key).'"><p>Página '.$e($p['page']).' de '.$e($p['last_page']).' · '.$e($p['total']).' registos</p>';foreach([-1=>'Anterior',1=>'Seguinte'] as $delta=>$label){$target=$p['page']+$delta;if($target<1||$target>$p['last_page'])continue;$query=array_replace($data['listing_query'],[$param=>$target]);if($key==='documents'){$query['proposal_page']=1;$query['event_page']=1;}$url=($settings['page_url']??'/supplier-payables').'?'.http_build_query($query,'','&',PHP_QUERY_RFC3986);echo '<a href="'.$e($url).'">'.$label.'</a> ';}echo '</nav>';}; ?>
|
||||
<?php if(isset($data['pagination'])): ?><section><h2>Filtrar documentos</h2><form method="get" action="<?= $e($settings['page_url']??'/supplier-payables') ?>"><label>Número ou fornecedor<input name="q" maxlength="100" value="<?= $e($data['listing_query']['q']) ?>"></label><label>Reconhecimento<select name="recognition"><?php foreach(['all'=>'Todos','recognised'=>'Reconhecidos','unrecognised'=>'Por reconhecer'] as $v=>$label): ?><option value="<?= $e($v) ?>" <?= $data['listing_query']['recognition']===$v?'selected':'' ?>><?= $e($label) ?></option><?php endforeach ?></select></label><label>Documentos por página<select name="per_page"><?php foreach([25,100] as $size): ?><option value="<?= $size ?>" <?= $data['listing_query']['per_page']===$size?'selected':'' ?>><?= $size ?></option><?php endforeach ?></select></label><button>Aplicar filtros</button></form><p>Obrigações, propostas e eventos abaixo pertencem aos documentos desta página. A pesquisa e o estado são aplicados antes da paginação.</p></section><?php endif ?>
|
||||
<?php if($data['payments_available']??false): ?><p><a href="/supplier-payments">Pagamentos e afectações sintéticas — sem execução bancária</a></p><?php endif ?><p id="status" role="status"></p><p id="error" role="alert"></p><button id="reload">Actualizar consulta</button>
|
||||
<?php if(isset($settings['report_url'])): ?><p><a href="<?= $e($settings['report_url'].'?'.http_build_query(array_intersect_key($data['listing_query'],array_flip(['q','source'])),'','&',PHP_QUERY_RFC3986)) ?>">Relatório das obrigações reconhecidas abrangidas pelo filtro</a></p><?php endif ?>
|
||||
<?php if(isset($data['listing_query']['source'])): ?><p>Conferência da origem #<?= $e($data['listing_query']['source']) ?>. <a href="<?= $e($settings['page_url']??'/supplier-payables') ?>">Consultar todas as origens</a></p><?php endif ?>
|
||||
<?php $pageNav=function(string $key)use($data,$settings,$e){if(!isset($data['pagination'][$key]))return;$p=$data['pagination'][$key];$param=['documents'=>'page','proposals'=>'proposal_page','events'=>'event_page'][$key];$label=['documents'=>'documentos','proposals'=>'propostas','events'=>'histórico'][$key];echo '<nav aria-label="Paginação '.$e($label).'"><p>Página '.$e($p['page']).' de '.$e($p['last_page']).' · '.$e($p['total']).' registos</p>';foreach([-1=>'Anterior',1=>'Seguinte'] as $delta=>$label){$target=$p['page']+$delta;if($target<1||$target>$p['last_page'])continue;$query=array_replace($data['listing_query'],[$param=>$target]);if($key==='documents'){$query['proposal_page']=1;$query['event_page']=1;}$url=($settings['page_url']??'/supplier-payables').'?'.http_build_query($query,'','&',PHP_QUERY_RFC3986);echo '<a href="'.$e($url).'">'.$label.'</a> ';}echo '</nav>';}; ?>
|
||||
<?php if(isset($data['pagination'])): ?><section><h2>Filtrar documentos</h2><form method="get" action="<?= $e($settings['page_url']??'/supplier-payables') ?>"><?php foreach(['invoice','source'] as $focus): if(isset($data['listing_query'][$focus])): ?><input type="hidden" name="<?= $focus ?>" value="<?= $e($data['listing_query'][$focus]) ?>"><?php endif; endforeach ?><label>Número ou fornecedor<input name="q" maxlength="100" value="<?= $e($data['listing_query']['q']) ?>"></label><label>Reconhecimento<select name="recognition"><?php foreach(['all'=>'Todos','recognised'=>'Reconhecidos','unrecognised'=>'Por reconhecer'] as $v=>$label): ?><option value="<?= $e($v) ?>" <?= $data['listing_query']['recognition']===$v?'selected':'' ?>><?= $e($label) ?></option><?php endforeach ?></select></label><label>Documentos por página<select name="per_page"><?php foreach([25,100] as $size): ?><option value="<?= $size ?>" <?= $data['listing_query']['per_page']===$size?'selected':'' ?>><?= $size ?></option><?php endforeach ?></select></label><button>Aplicar filtros</button></form><p>Obrigações, propostas e eventos abaixo pertencem aos documentos desta página. A pesquisa e o estado são aplicados antes da paginação.</p></section><?php endif ?>
|
||||
<?php if($data['payments_available']??false): ?><p><a href="<?= $e('/supplier-payments'.(isset($data['listing_query']['source'])?'?'.http_build_query(['source'=>$data['listing_query']['source']],'','&',PHP_QUERY_RFC3986):'')) ?>">Pagamentos e afectações sintéticas — sem execução bancária</a></p><?php endif ?><p id="status" role="status"></p><p id="error" role="alert"></p><button id="reload">Actualizar consulta</button>
|
||||
<section><h2>Facturas de origem</h2><div class="scroll"><table><thead><tr><th>Documento</th><th>Fornecedor</th><th>Base</th><th>Imposto documental</th><th>Total</th><th>Conferência / revisão</th></tr></thead><tbody>
|
||||
<?php foreach($data['documents'] as $d): ?><tr><td><?= $e($d['number']??'Indeterminado') ?></td><td><?= $e($d['supplier_name']??'Indeterminado') ?></td><td><?= isset($d['subtotal_minor'])?$money($d['subtotal_minor']):'Indeterminado' ?></td><td><?= isset($d['tax_minor'])?$money($d['tax_minor']):'Indeterminado' ?></td><td><?= isset($d['total_minor'])?$money($d['total_minor']):'Indeterminado' ?></td><td><?= $e($d['status']) ?><details><summary>Origem e pendências</summary><pre><?= $e(json_encode($d,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE)) ?></pre></details></td></tr><?php endforeach ?>
|
||||
<?php foreach($data['documents'] as $d): ?><tr><td><?= $e($d['number']??'Indeterminado') ?><?php if(($settings['document_filter']??null)==='source'): ?><p><a href="<?= $e(($settings['page_url']??'/supplier-payables').'?'.http_build_query(['source'=>$d['local_id']],'','&',PHP_QUERY_RFC3986)) ?>">Conferir evidências desta origem</a></p><?php endif ?></td><td><?= $e($d['supplier_name']??'Indeterminado') ?></td><td><?= isset($d['subtotal_minor'])?$money($d['subtotal_minor']):'Indeterminado' ?></td><td><?= isset($d['tax_minor'])?$money($d['tax_minor']):'Indeterminado' ?></td><td><?= isset($d['total_minor'])?$money($d['total_minor']):'Indeterminado' ?></td><td><?= $e($d['status']) ?><details><summary>Origem e pendências</summary><pre><?= $e(json_encode($d,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE)) ?></pre></details></td></tr><?php endforeach ?>
|
||||
</tbody></table></div><?php $pageNav('documents'); ?></section>
|
||||
<?php if($data['permissions']['prepare']): ?><section><h2>Preparar a obrigação</h2><form data-action="prepare"><label>Factura existente<select name="id"><?php foreach($data['documents'] as $d): ?><option value="<?= $e($d['local_id']) ?>"><?= $e($d['number']) ?> · <?= $money($d['total_minor']) ?></option><?php endforeach ?></select></label><label>Fundamento<textarea name="reason" required minlength="3" maxlength="2000">Proposta sintética com base na factura conferida.</textarea></label><p>Sem edição de fornecedor, valor ou imposto. Vencimento mantém-se desconhecido neste recorte.</p><button>Preparar da origem</button></form></section><?php endif ?>
|
||||
<?php $historyDocuments=array_filter($data['documents'],fn($d)=>($d['payment_count']??0)>0); if(($data['history_import_available']??false)&&$data['permissions']['prepare']&&$historyDocuments): ?><section><h2>Incorporar factura com pagamentos anteriores</h2><p>Preserva o principal integral e liga os pagamentos originais uma única vez. Só os confirmados reduzem o saldo; pendentes e rejeitados mantêm o seu estado. Não executa nem confirma pagamentos.</p><form data-action="prepare_history"><label>Factura com histórico<select name="id"><?php foreach($historyDocuments as $d): ?><option value="<?= $e($d['local_id']) ?>"><?= $e($d['number']) ?> · <?= $money($d['total_minor']) ?></option><?php endforeach ?></select></label><label>Fundamento<textarea name="reason" required minlength="3" maxlength="2000">Passagem de responsabilidade com preservação dos pagamentos históricos.</textarea></label><button>Preparar passagem com histórico</button></form></section><?php endif ?>
|
||||
@@ -21,6 +23,7 @@
|
||||
<p>Sem execução de novos pagamentos, cobrança, efeitos de stock, novo consumo orçamental ou lançamento automático. A passagem de histórico não confirma pagamentos pendentes.</p>
|
||||
</main><script>
|
||||
const settings=<?= json_encode($settings,JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_THROW_ON_ERROR) ?>;
|
||||
if(settings.ledger_flow_url){const button=document.createElement('button');button.textContent='Conferir percurso até ao lançamento';document.querySelector('#status').before(button);button.onclick=async()=>{button.disabled=true;try{const r=await fetch('/api/context',{method:'POST',credentials:'same-origin',headers:{Accept:'application/json','Content-Type':'application/json','X-CSRF-TOKEN':settings.csrf},body:JSON.stringify({...settings.ledger_flow_scope,module_id:'accounting'})});const data=await r.json();if(!r.ok)throw Error(data.message||'Módulo indisponível.');location.assign(settings.ledger_flow_url);}catch(e){document.querySelector('#error').textContent=e.message;button.disabled=false;}};}
|
||||
document.querySelector('#reload').onclick=()=>location.reload();
|
||||
for(const form of document.querySelectorAll('form[data-action]'))form.onsubmit=async event=>{event.preventDefault();const body=Object.fromEntries(new FormData(form));body.id=Number(body.id);const signature=JSON.stringify(body);if(form.dataset.signature!==signature){form.dataset.signature=signature;form.dataset.key=crypto.randomUUID();}const button=form.querySelector('button');button.disabled=true;document.querySelector('#error').textContent='';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:JSON.stringify(body)});const d=await r.json();if(!r.ok)throw new Error(d.message??Object.values(d.errors??{}).flat().join(' '));if(d.state==='conflict'){document.querySelector('#error').textContent=d.reason+' Consulte o histórico.';return;}location.reload();}catch(e){document.querySelector('#error').textContent=e.message;}finally{button.disabled=false;}};
|
||||
</script></body></html>
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
<?php if (! isset($data['settlement_pagination'])) return; ?>
|
||||
<section id="allocation-history"><h2>Afectações confirmadas</h2>
|
||||
<?php foreach($data['allocations'] as $a): ?><article><h3>Afectação #<?= $e($a->id) ?></h3><p><a href="<?= $e($paymentFocusUrl((int)$a->payment_id)) ?>">Pagamento #<?= $e($a->payment_id) ?></a> · Obrigação #<?= $e($a->obligation_id) ?> · <?= $money($a->amount_minor) ?> · <?= $e($a->created_at) ?></p><p>Versão de origem <?= $e($a->source_revision) ?>. O original mantém-se no histórico mesmo quando existe reversão.</p>
|
||||
<?php if($a->local_source_id!==null): ?><p><a href="<?= $e('/supplier-payables?'.http_build_query(['source'=>$a->local_source_id],'','&',PHP_QUERY_RFC3986)) ?>">Conferir origem e reconhecimento</a></p><?php endif ?></article><?php endforeach ?>
|
||||
<?php if(!$data['allocations']): ?><p>Sem afectações confirmadas nesta janela.</p><?php endif ?>
|
||||
<?php $settlementNav('allocations'); ?></section>
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
$settlementNav = static function (string $key) use ($data, $e): void {
|
||||
if (! isset($data['settlement_pagination'][$key])) return;
|
||||
$p = $data['settlement_pagination'][$key];
|
||||
$param = ['payments' => 'payments_page', 'allocation_proposals' => 'allocation_proposals_page', 'allocations' => 'allocations_page', 'payment_events' => 'payment_events_page'][$key];
|
||||
$anchor = ['payments' => 'payments', 'allocation_proposals' => 'allocation-proposals', 'allocations' => 'allocation-history', 'payment_events' => 'payment-history'][$key];
|
||||
$label = ['payments' => 'pagamentos', 'allocation_proposals' => 'propostas de afectação', 'allocations' => 'afectações confirmadas', 'payment_events' => 'eventos de pagamentos'][$key];
|
||||
echo '<nav aria-label="Paginação de '.$e($label).'"><p>Página '.$e($p['page']).' de '.$e($p['last_page']).' · '.$e($p['total']).' registos</p>';
|
||||
foreach ([-1 => 'Anterior', 1 => 'Seguinte'] as $delta => $text) {
|
||||
$target = $p['page'] + $delta;
|
||||
if ($target < 1 || $target > $p['last_page']) continue;
|
||||
$query = array_replace($data['settlement_query'], [$param => $target]);
|
||||
echo '<a href="'.$e('/supplier-payments?'.http_build_query($query, '', '&', PHP_QUERY_RFC3986).'#'.$anchor).'">'.$text.'</a> ';
|
||||
}
|
||||
echo '</nav>';
|
||||
};
|
||||
$paymentFocusUrl = static function (int $id) use ($data): string {
|
||||
$query = array_replace($data['settlement_query'], ['payment' => $id, 'payment_state' => 'all', 'payment_q' => '',
|
||||
'payments_page' => 1, 'allocation_proposals_page' => 1, 'allocations_page' => 1, 'payment_events_page' => 1]);
|
||||
return '/supplier-payments?'.http_build_query($query, '', '&', PHP_QUERY_RFC3986).'#payments';
|
||||
};
|
||||
if (! isset($data['settlement_pagination'])) return;
|
||||
$sq = $data['settlement_query'];
|
||||
?>
|
||||
<section><h2>Filtrar pagamentos e histórico</h2><form method="get" action="/supplier-payments">
|
||||
<?php foreach($data['obligation_query'] as $name=>$value): ?><input type="hidden" name="<?= $e($name) ?>" value="<?= $e($value) ?>"><?php endforeach ?>
|
||||
<?php if(isset($sq['payment'])): ?><input type="hidden" name="payment" value="<?= $e($sq['payment']) ?>"><?php endif ?>
|
||||
<label>Referência do pagamento<input name="payment_q" maxlength="100" value="<?= $e($sq['payment_q']) ?>"></label>
|
||||
<label>Estado do pagamento<select name="payment_state"><?php foreach(['all'=>'Todos','proposed'=>'Propostos','confirmed'=>'Confirmados','rejected'=>'Rejeitados'] as $value=>$label): ?><option value="<?= $value ?>" <?= $sq['payment_state']===$value?'selected':'' ?>><?= $label ?></option><?php endforeach ?></select></label>
|
||||
<label>Registos por página<select name="payment_per_page"><?php foreach([25,100] as $size): ?><option value="<?= $size ?>" <?= $sq['payment_per_page']===$size?'selected':'' ?>><?= $size ?></option><?php endforeach ?></select></label><button>Aplicar filtros ao histórico</button></form>
|
||||
<p>Estes filtros abrangem pagamentos, propostas de afectação, afectações e eventos. Cada lista tem paginação própria. Os filtros de documentos escolhem as obrigações e não restringem este histórico. Os montantes por afectar incluem todo o histórico do pagamento, também fora da página.</p>
|
||||
<?php if(isset($sq['payment'])): $all=$sq; unset($all['payment']); foreach(['payments_page','allocation_proposals_page','allocations_page','payment_events_page'] as $key)$all[$key]=1; ?><p>Conferência do pagamento #<?= $e($sq['payment']) ?> · <a href="<?= $e('/supplier-payments?'.http_build_query($all,'','&',PHP_QUERY_RFC3986)) ?>">Consultar outros pagamentos</a></p><?php endif ?>
|
||||
</section>
|
||||
@@ -12,13 +12,27 @@ body{font:17px system-ui;color:#172f29;background:#f4f6f5;margin:0}main{max-widt
|
||||
</style></head><body><main>
|
||||
<header><a href="<?= $e($settings['obligations_url']) ?>">← Obrigações a fornecedores</a> · <a href="/demo?next=payments">Trocar função ou sair</a><p><?= $e($settings['host']) ?> · <?= $e($settings['actor']) ?></p><h1>Pagamentos e afectações a fornecedores</h1><p class="notice"><strong>ENSAIO SINTÉTICO — SEM MOVIMENTAÇÃO DE DINHEIRO.</strong> Propor não confirma; confirmar um pagamento não abate automaticamente uma dívida. Só uma afectação confirmada reduz o saldo. Não há execução bancária, reconciliação, stock, orçamento adicional ou lançamento contabilístico.</p><p>As referências de pagamento e evidência são artificiais e começam por SIM-. Não introduza dados bancários ou comprovativos reais.</p></header>
|
||||
<p id="status" role="status"></p><p id="error" role="alert" tabindex="-1"></p><button id="reload">Actualizar consulta</button>
|
||||
<section id="obligation-balances"><h2>Obrigações e saldo por liquidar</h2><div class="scroll"><table><thead><tr><th>Origem / fornecedor</th><th>Principal</th><th>Afectado neste percurso</th><th>Saldo</th><th>Vencimento</th></tr></thead><tbody><?php foreach ($data['obligations'] as $o): ?><tr><td>#<?= $e($o['id']) ?> · <?= $e($o['origin_snapshot']['number'] ?? '') ?><br><?= $e($o['origin_snapshot']['supplier_name'] ?? '') ?><br>Versão <?= $e($o['source_revision']) ?> · Validador #<?= $e($o['recognised_by']) ?><details><summary>Versão e decisão</summary><pre><?= $e(json_encode($o, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) ?></pre></details></td><td><?= $money($o['principal_minor']) ?></td><td><?= $money($o['allocated_payments_minor']) ?></td><td><?= $money($o['balance_minor']) ?><?= $o['source_conflict'] ? ' — origem divergente' : '' ?></td><td>Pendente<br>Atraso indeterminado<br>Dias de atraso: sem valor</td></tr><?php endforeach ?></tbody></table></div><?php if (! $data['obligations']): ?><p>Reconheça primeiro a obrigação no percurso existente. Não é criada uma dívida por registar um pagamento.</p><?php endif ?></section>
|
||||
<?php require __DIR__.'/settlement-navigation.php'; ?>
|
||||
<?php if(isset($data['obligation_pagination'])): $op=$data['obligation_pagination']; $oq=$data['obligation_query']; ?>
|
||||
<section><h2>Escolher origens para conferência</h2><form method="get" action="/supplier-payments">
|
||||
<?php foreach(array_diff_key($data['settlement_query']??[], $oq) as $name=>$value): ?><input type="hidden" name="<?= $e($name) ?>" value="<?= $e($value) ?>"><?php endforeach ?>
|
||||
<?php if(isset($oq['source'])): ?><input type="hidden" name="source" value="<?= $e($oq['source']) ?>"><?php endif ?>
|
||||
<label>Número ou fornecedor<input name="q" maxlength="100" value="<?= $e($oq['q']) ?>"></label>
|
||||
<label>Reconhecimento<select name="recognition"><?php foreach(['all'=>'Todos','recognised'=>'Reconhecidos','unrecognised'=>'Por reconhecer'] as $value=>$label): ?><option value="<?= $value ?>" <?= $oq['recognition']===$value?'selected':'' ?>><?= $label ?></option><?php endforeach ?></select></label>
|
||||
<label>Documentos por página<select name="per_page"><?php foreach([25,100] as $size): ?><option value="<?= $size ?>" <?= $oq['per_page']===$size?'selected':'' ?>><?= $size ?></option><?php endforeach ?></select></label><button>Aplicar filtros</button></form>
|
||||
<p>A selecção de obrigações abaixo acompanha esta página de documentos. O histórico de pagamentos e afectações mantém a sua consulta própria; os filtros de documentos não o restringem.</p>
|
||||
<?php if(isset($oq['source'])): $allSources=array_replace($data['settlement_query']??$oq,['page'=>1,'proposal_page'=>1,'event_page'=>1,'q'=>'','recognition'=>'all']); unset($allSources['source']); ?><p>Origem #<?= $e($oq['source']) ?> · <a href="<?= $e('/supplier-payments?'.http_build_query($allSources,'','&',PHP_QUERY_RFC3986)) ?>">Consultar todas as origens</a></p><?php endif ?>
|
||||
<nav aria-label="Paginação de origens para pagamentos"><p>Página <?= $e($op['page']) ?> de <?= $e($op['last_page']) ?> · <?= $e($op['total']) ?> documentos</p>
|
||||
<?php foreach([-1=>'Anterior',1=>'Seguinte'] as $delta=>$label): $target=$op['page']+$delta; if($target<1||$target>$op['last_page'])continue; $query=array_replace($data['settlement_query']??$oq,['page'=>$target,'proposal_page'=>1,'event_page'=>1]); ?><a href="<?= $e('/supplier-payments?'.http_build_query($query,'','&',PHP_QUERY_RFC3986)) ?>"><?= $label ?></a> <?php endforeach ?></nav></section>
|
||||
<?php endif ?>
|
||||
<section id="obligation-balances"><h2>Obrigações e saldo por liquidar</h2><div class="scroll"><table><thead><tr><th>Origem / fornecedor</th><th>Principal</th><th>Afectado neste percurso</th><th>Saldo</th><th>Vencimento</th></tr></thead><tbody><?php foreach ($data['obligations'] as $o): ?><tr><td>#<?= $e($o['id']) ?> · <?= $e($o['origin_snapshot']['number'] ?? '') ?><br><?= $e($o['origin_snapshot']['supplier_name'] ?? '') ?><?php if(isset($o['evidence_url'])): ?><p><a href="<?= $e($o['evidence_url']) ?>">Conferir origem, propostas e histórico</a></p><?php endif ?><br>Versão <?= $e($o['source_revision']) ?> · Validador #<?= $e($o['recognised_by']) ?><details><summary>Versão e decisão</summary><pre><?= $e(json_encode($o, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) ?></pre></details></td><td><?= $money($o['principal_minor']) ?></td><td><?= $money($o['allocated_payments_minor']) ?></td><td><?= $money($o['balance_minor']) ?><?= $o['source_conflict'] ? ' — origem divergente' : '' ?></td><td>Pendente<br>Atraso indeterminado<br>Dias de atraso: sem valor</td></tr><?php endforeach ?></tbody></table></div><?php if (! $data['obligations']): ?><p>Reconheça primeiro a obrigação no percurso existente. Não é criada uma dívida por registar um pagamento.</p><?php endif ?></section>
|
||||
<?php if ($data['permissions']['payment_prepare'] && $eligible): ?><section><h2>1. Propor pagamento sintético</h2><form data-action="payment-prepare"><label>Obrigação de referência / fornecedor<select name="obligation_id" data-origin><?php $options(); ?></select></label><input type="hidden" name="source_revision"><label>Montante do pagamento (MZN)<input name="amount" required inputmode="decimal" pattern="[0-9]+(\.[0-9]{1,2})?" placeholder="4000.00"></label><input type="hidden" name="currency" value="MZN"><label>Data factual do pagamento simulado<input type="date" name="paid_on" required></label><label>Referência estável do facto<input name="fact_reference" required pattern="SIM-[A-Z0-9][A-Z0-9._-]{2,95}" placeholder="SIM-PAY-001"></label><label>Evidência artificial de origem<input name="evidence_reference" required pattern="SIM-[A-Z0-9][A-Z0-9._-]{2,95}" placeholder="SIM-EVID-001"></label><label>Fundamento<textarea name="reason" required minlength="3" maxlength="2000"></textarea></label><button>Propor sem afectar dívida</button></form></section><?php endif ?>
|
||||
<section id="payments"><h2>2. Pagamentos propostos e decisões</h2><p>A confirmação exige outra identidade. Depois de confirmar, troque para Preparar para propor a afectação; a dívida ainda não foi reduzida.</p><?php foreach ($data['payments'] as $p): ?><article><h3>Pagamento #<?= $e($p['id']) ?> · <?= $e($p['fact_reference']) ?></h3><p><?= $money($p['amount_minor']) ?> · Data simulada <?= $e($p['paid_on']) ?> · Estado: <?= $e(['proposed'=>'Proposto','confirmed'=>'Confirmado em ensaio','rejected'=>'Rejeitado'][$p['state']]) ?></p><p>Por afectar: <?= $money($p['unallocated_minor']) ?> · Reconciliação bancária: não implementada.</p><details><summary>Preparação e evidência preservadas</summary><pre><?= $e($p['snapshot']) ?></pre><?php if ($p['decision']): ?><pre><?= $e(json_encode($p['decision'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) ?></pre><?php endif ?></details>
|
||||
<?php if ($data['permissions']['payment_confirm'] && ! $p['decision'] && (int) $p['prepared_by'] !== $data['current_actor']): ?><form data-action="payment-decide"><input type="hidden" name="payment_id" value="<?= $e($p['id']) ?>"><label>Decisão explícita<select name="decision"><option value="confirmed">Confirmar com evidência sintética</option><option value="rejected">Rejeitar</option></select></label><label>Evidência artificial da conferência<input name="evidence_reference" required pattern="SIM-[A-Z0-9][A-Z0-9._-]{2,95}" placeholder="SIM-CONF-001"></label><label>Fundamento da conferência<textarea name="reason" required minlength="3" maxlength="2000"></textarea></label><button>Registar decisão independente</button></form><?php endif ?></article><?php endforeach ?><?php if (! $data['payments']): ?><p>Sem pagamentos propostos neste contexto.</p><?php endif ?></section>
|
||||
<section id="payments"><h2>2. Pagamentos propostos e decisões</h2><p>A confirmação exige outra identidade. Depois de confirmar, troque para Preparar para propor a afectação; a dívida ainda não foi reduzida.</p><?php foreach ($data['payments'] as $p): ?><article><h3>Pagamento #<?= $e($p['id']) ?> · <?= $e($p['fact_reference']) ?></h3><p><?= $money($p['amount_minor']) ?> · Data simulada <?= $e($p['paid_on']) ?> · Estado: <?= $e(['proposed'=>'Proposto','confirmed'=>'Confirmado em ensaio','rejected'=>'Rejeitado'][$p['state']]) ?></p><?php if(isset($data['settlement_pagination'])): ?><p><a href="<?= $e($paymentFocusUrl((int)$p['id'])) ?>">Conferir este pagamento e as suas evidências</a></p><?php endif ?><p>Por afectar: <?= $money($p['unallocated_minor']) ?> · Reconciliação bancária: não implementada.</p><details><summary>Preparação e evidência preservadas</summary><pre><?= $e($p['snapshot']) ?></pre><?php if ($p['decision']): ?><pre><?= $e(json_encode($p['decision'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) ?></pre><?php endif ?></details>
|
||||
<?php if ($data['permissions']['payment_confirm'] && ! $p['decision'] && (int) $p['prepared_by'] !== $data['current_actor']): ?><form data-action="payment-decide"><input type="hidden" name="payment_id" value="<?= $e($p['id']) ?>"><label>Decisão explícita<select name="decision"><option value="confirmed">Confirmar com evidência sintética</option><option value="rejected">Rejeitar</option></select></label><label>Evidência artificial da conferência<input name="evidence_reference" required pattern="SIM-[A-Z0-9][A-Z0-9._-]{2,95}" placeholder="SIM-CONF-001"></label><label>Fundamento da conferência<textarea name="reason" required minlength="3" maxlength="2000"></textarea></label><button>Registar decisão independente</button></form><?php endif ?></article><?php endforeach ?><?php if (! $data['payments']): ?><p>Sem pagamentos propostos nesta janela.</p><?php endif ?><?php $settlementNav('payments'); ?></section>
|
||||
<?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="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><?php if(isset($data['settlement_pagination'])): ?><p><a href="<?= $e($paymentFocusUrl((int)$p['payment_id'])) ?>">Conferir pagamento de origem</a></p><?php endif ?><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 ?><?php $settlementNav('allocation_proposals'); ?></section>
|
||||
<?php require __DIR__.'/settlement-allocations.php'; ?>
|
||||
<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; ?>
|
||||
@@ -29,10 +43,11 @@ body{font:17px system-ui;color:#172f29;background:#f4f6f5;margin:0}main{max-widt
|
||||
<?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>
|
||||
<section id="payment-history"><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><?php if(isset($data['settlement_pagination'])): ?><p><a href="<?= $e($paymentFocusUrl((int)$event->payment_id)) ?>">Conferir pagamento #<?= $e($event->payment_id) ?></a></p><?php endif ?><pre><?= $e($event->payload) ?></pre></details><?php endforeach ?><?php $settlementNav('payment_events'); ?></section>
|
||||
<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) ?>;
|
||||
if(settings.ledger_cycle_url){const button=document.createElement('button');button.textContent='Conferir contabilização e período QA';document.querySelector('main').prepend(button);button.onclick=async()=>{button.disabled=true;try{if(settings.ledger_scope){const r=await fetch('/api/context',{method:'POST',credentials:'same-origin',headers:{Accept:'application/json','Content-Type':'application/json','X-CSRF-TOKEN':settings.csrf},body:JSON.stringify({...settings.ledger_scope,module_id:'accounting'})});if(!r.ok)throw Error('Módulo contabilístico indisponível.');}location.assign(settings.ledger_cycle_url);}catch(e){document.querySelector('#error').textContent=e.message;button.disabled=false;}};}
|
||||
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]')){
|
||||
|
||||
Reference in New Issue
Block a user