455 lines
19 KiB
TypeScript
455 lines
19 KiB
TypeScript
import {
|
|
Head,
|
|
Link,
|
|
router,
|
|
useForm,
|
|
usePage,
|
|
useRemember,
|
|
} from '@inertiajs/react';
|
|
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
|
import { hasPreparationChanges } from '@/lib/requisition-history';
|
|
import type { WorkContextState } from '@/types/work-context';
|
|
import {
|
|
FormErrors,
|
|
Panel,
|
|
PageTitle,
|
|
controlClass,
|
|
} from '@/components/procurement';
|
|
import { InventoryPagination } from '@/components/inventory';
|
|
import { Button } from '@/components/ui/button';
|
|
import { Input } from '@/components/ui/input';
|
|
import type { Page } from '@/types/inventory';
|
|
import { money } from '@/types/procurement';
|
|
|
|
type Invoice = {
|
|
banks?: {
|
|
id: number;
|
|
revision: number;
|
|
label: string;
|
|
currency: string;
|
|
state: string;
|
|
}[];
|
|
currency?: string;
|
|
id: number;
|
|
number: string;
|
|
supplier_id: number;
|
|
supplier_name: string;
|
|
total_minor: number;
|
|
outstanding_minor: number;
|
|
bank_id: number;
|
|
bank_revision: number;
|
|
bank_state: string;
|
|
};
|
|
type Payment = {
|
|
canReview: boolean;
|
|
id: number;
|
|
invoice_id: number;
|
|
created_by: number;
|
|
status: string;
|
|
amount_minor: number;
|
|
currency: string;
|
|
paid_on: string;
|
|
external_reference: string | null;
|
|
evidence_reference: string | null;
|
|
supplier_bank_detail_id: number;
|
|
};
|
|
function Review({ payment }: { payment: Payment }) {
|
|
const identity = `${usePaymentIdentity()}:review:${payment.id}:${payment.status}:${payment.amount_minor}:${payment.supplier_bank_detail_id}:${payment.canReview}`;
|
|
return <ReviewFields key={identity} id={payment.id} identity={identity} />;
|
|
}
|
|
function ReviewFields({ id, identity }: { id: number; identity: string }) {
|
|
const initial = {
|
|
decision: 'confirmed',
|
|
reason: '',
|
|
independently_verified: false,
|
|
};
|
|
const form = useForm(identity, initial);
|
|
const dirty = hasPreparationChanges(initial, form.data);
|
|
const ref = usePreparationDirty(dirty);
|
|
return (
|
|
<form
|
|
ref={ref}
|
|
data-preparation-dirty={dirty ? 'true' : 'false'}
|
|
className="mt-4 grid gap-4"
|
|
onSubmit={(e) => {
|
|
e.preventDefault();
|
|
form.post(`/pagamentos/${id}/conferir`, {
|
|
onSuccess: () => {
|
|
form.setData(initial);
|
|
form.clearErrors();
|
|
router.remember(initial, `${identity}:data`);
|
|
router.remember({}, `${identity}:errors`);
|
|
},
|
|
});
|
|
}}
|
|
>
|
|
<FormErrors errors={form.errors} />
|
|
<label>
|
|
Resultado da conferência
|
|
<select
|
|
className={controlClass}
|
|
value={form.data.decision}
|
|
onChange={(e) => form.setData('decision', e.target.value)}
|
|
>
|
|
<option value="confirmed">Confirmar registo externo</option>
|
|
<option value="rejected">Rejeitar conferência</option>
|
|
</select>
|
|
</label>
|
|
<label>
|
|
Fundamento
|
|
<textarea
|
|
required
|
|
className="w-full rounded border p-3"
|
|
value={form.data.reason}
|
|
onChange={(e) => form.setData('reason', e.target.value)}
|
|
/>
|
|
</label>
|
|
<label className="flex gap-3">
|
|
<input
|
|
required
|
|
type="checkbox"
|
|
checked={form.data.independently_verified}
|
|
onChange={(e) =>
|
|
form.setData('independently_verified', e.target.checked)
|
|
}
|
|
/>
|
|
Conferi a evidência, os valores e os dados bancários de forma
|
|
independente.
|
|
</label>
|
|
<Button disabled={form.processing}>Guardar conferência</Button>
|
|
</form>
|
|
);
|
|
}
|
|
function usePaymentIdentity() {
|
|
const { auth, workContext, organizationAccess } = usePage().props;
|
|
const context = workContext as WorkContextState | null | undefined;
|
|
const access = organizationAccess as { permissions?: string[] } | null;
|
|
return `payments:${auth.user?.tenant_id}:${auth.user?.id}:${context?.active ?? 'legacy'}:${[...(access?.permissions ?? [])].sort().join(',')}`;
|
|
}
|
|
export default function Payments(
|
|
props: Omit<Parameters<typeof PaymentFields>[0], 'identity'>,
|
|
) {
|
|
const identity = `${usePaymentIdentity()}:${props.canManage}:${props.focusInvoiceId ?? 'all'}:${props.focusPaymentId ?? 'all'}`;
|
|
return <PaymentFields key={identity} {...props} identity={identity} />;
|
|
}
|
|
function PaymentFields({
|
|
invoices,
|
|
payments,
|
|
canManage,
|
|
expenseAllocationsReady = false,
|
|
focusPaymentId = null,
|
|
focusInvoiceId = null,
|
|
identity,
|
|
}: {
|
|
identity: string;
|
|
invoices: Invoice[];
|
|
payments: Page<Payment>;
|
|
canManage: boolean;
|
|
expenseAllocationsReady?: boolean;
|
|
focusPaymentId?: number | null;
|
|
focusInvoiceId?: number | null;
|
|
}) {
|
|
const [invoiceId, setInvoiceId] = useRemember(
|
|
focusInvoiceId === null ? '' : String(focusInvoiceId),
|
|
`${identity}:invoice`,
|
|
);
|
|
const selected = invoices.find((i) => String(i.id) === invoiceId);
|
|
const registrationIdentity = `${identity}:registration:${invoiceId}:${selected?.bank_id}:${selected?.bank_revision}:${selected?.bank_state}:${selected?.outstanding_minor}:${selected?.banks?.map((bank) => `${bank.id}.${bank.revision}.${bank.state}`).join(',')}`;
|
|
return (
|
|
<>
|
|
<Head title="Pagamentos externos" />
|
|
<div className="mx-auto grid w-full max-w-6xl gap-6 p-6">
|
|
<PageTitle
|
|
eyebrow="SGC · Finanças"
|
|
title="Pagamentos externos e conferência"
|
|
description="Registe pagamentos já efectuados fora do SGC. O sistema não executa transferências, remessas ou ordens bancárias."
|
|
/>
|
|
<p className="rounded-lg border border-amber-300 p-4 text-sm">
|
|
Desenvolvimento. Apenas a confirmação independente abate o
|
|
saldo da factura; não volta a consumir o orçamento. Dados
|
|
bancários e evidências devem ser conferidos pelas pessoas
|
|
autorizadas.
|
|
</p>
|
|
<Panel title="Saldo das facturas validadas">
|
|
<div className="space-y-4 text-sm">
|
|
{invoices.map((i) => (
|
|
<article key={i.id} className="rounded border p-3">
|
|
<p className="font-semibold">
|
|
{i.number} · {i.supplier_name}
|
|
</p>
|
|
<p>
|
|
Total {money(i.total_minor, i.currency)} ·
|
|
Confirmado{' '}
|
|
{money(
|
|
i.total_minor - i.outstanding_minor,
|
|
i.currency,
|
|
)}{' '}
|
|
· Pendente{' '}
|
|
{money(i.outstanding_minor, i.currency)}
|
|
</p>
|
|
<p>
|
|
{i.outstanding_minor === 0
|
|
? 'Liquidada por registos externos confirmados'
|
|
: 'Saldo por conferir/liquidar'}{' '}
|
|
· Versão bancária{' '}
|
|
{i.bank_revision || 'não registada'} ·{' '}
|
|
{i.bank_state === 'approved'
|
|
? 'Duas validações elegíveis'
|
|
: 'Dados bancários indisponíveis para confirmação'}
|
|
</p>
|
|
{canManage && (
|
|
<Link
|
|
href={`/fornecedores/${i.supplier_id}/dados-bancarios`}
|
|
className="font-semibold text-teal-700"
|
|
>
|
|
Consultar dados bancários →
|
|
</Link>
|
|
)}
|
|
</article>
|
|
))}
|
|
{invoices.length === 0 && (
|
|
<p>Sem facturas validadas nesta empresa.</p>
|
|
)}
|
|
</div>
|
|
</Panel>
|
|
{(focusPaymentId !== null || focusInvoiceId !== null) && (
|
|
<Link
|
|
href="/pagamentos"
|
|
className="font-semibold text-teal-700"
|
|
>
|
|
Ver todos os registos externos
|
|
</Link>
|
|
)}
|
|
{canManage && focusPaymentId === null && (
|
|
<Panel
|
|
title="Registar pagamento externo para conferência"
|
|
description="Uma referência externa identifica um registo por empresa. Use a referência da operação e a evidência do pagamento; não introduza números de conta nestes campos."
|
|
>
|
|
<label className="mb-4 grid gap-1">
|
|
Factura
|
|
<select
|
|
form="external-payment-registration"
|
|
required
|
|
className={controlClass}
|
|
value={invoiceId}
|
|
onChange={(e) => {
|
|
setInvoiceId(e.target.value);
|
|
}}
|
|
>
|
|
<option value="">Seleccionar</option>
|
|
{invoiceId &&
|
|
(!selected ||
|
|
selected.outstanding_minor <= 0) && (
|
|
<option value={invoiceId} disabled>
|
|
Factura seleccionada indisponível ou
|
|
sem saldo
|
|
</option>
|
|
)}
|
|
{invoices
|
|
.filter((i) => i.outstanding_minor > 0)
|
|
.map((i) => (
|
|
<option key={i.id} value={i.id}>
|
|
{i.number} · {i.supplier_name} ·{' '}
|
|
{money(
|
|
i.outstanding_minor,
|
|
i.currency,
|
|
)}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
<RegistrationFields
|
|
key={registrationIdentity}
|
|
identity={registrationIdentity}
|
|
invoiceId={invoiceId}
|
|
selected={selected}
|
|
onSaved={() => setInvoiceId('')}
|
|
/>
|
|
</Panel>
|
|
)}
|
|
{payments.data.map((p) => (
|
|
<div key={p.id} id={`payment-${p.id}`}>
|
|
<Panel
|
|
title={`Registo externo #${p.id} · ${invoices.find((i) => i.id === p.invoice_id)?.number ?? `Factura #${p.invoice_id}`}`}
|
|
>
|
|
<p>
|
|
{money(p.amount_minor, p.currency)} ·{' '}
|
|
{p.paid_on} ·{' '}
|
|
{{
|
|
pending: 'Pendente de conferência',
|
|
confirmed: 'Confirmado',
|
|
rejected: 'Conferência rejeitada',
|
|
}[p.status] ?? p.status}
|
|
</p>
|
|
{p.external_reference && (
|
|
<p className="mt-2 text-sm break-all">
|
|
Referência: {p.external_reference}
|
|
</p>
|
|
)}
|
|
{p.evidence_reference && (
|
|
<p className="text-sm break-all">
|
|
Evidência: {p.evidence_reference}
|
|
</p>
|
|
)}
|
|
{p.canReview && <Review payment={p} />}
|
|
{expenseAllocationsReady &&
|
|
p.status === 'confirmed' && (
|
|
<Link
|
|
className="mt-3 inline-block underline"
|
|
href={`/pagamentos/${p.id}/categorias`}
|
|
>
|
|
Imputação por categoria
|
|
</Link>
|
|
)}
|
|
</Panel>
|
|
</div>
|
|
))}
|
|
<InventoryPagination page={payments} />
|
|
</div>
|
|
</>
|
|
);
|
|
}
|
|
|
|
function RegistrationFields({
|
|
identity,
|
|
invoiceId,
|
|
selected,
|
|
onSaved,
|
|
}: {
|
|
identity: string;
|
|
invoiceId: string;
|
|
selected?: Invoice;
|
|
onSaved: () => void;
|
|
}) {
|
|
const initial = {
|
|
supplier_bank_detail_id: selected?.bank_id ?? 0,
|
|
amount: '',
|
|
paid_on: '',
|
|
external_reference: '',
|
|
evidence_reference: '',
|
|
};
|
|
const form = useForm(identity, initial);
|
|
const dirty = hasPreparationChanges(initial, form.data);
|
|
const ref = usePreparationDirty(dirty);
|
|
return (
|
|
<form
|
|
id="external-payment-registration"
|
|
ref={ref}
|
|
data-preparation-dirty={dirty ? 'true' : 'false'}
|
|
className="grid gap-4"
|
|
onSubmit={(e) => {
|
|
e.preventDefault();
|
|
form.post(`/facturas/${invoiceId}/pagamentos`, {
|
|
onSuccess: () => {
|
|
form.setData(initial);
|
|
form.clearErrors();
|
|
router.remember(initial, `${identity}:data`);
|
|
router.remember({}, `${identity}:errors`);
|
|
onSaved();
|
|
},
|
|
});
|
|
}}
|
|
>
|
|
<FormErrors errors={form.errors} />
|
|
{selected?.banks && (
|
|
<label>
|
|
Conta bancária na moeda da factura
|
|
<select
|
|
className={controlClass}
|
|
required
|
|
value={form.data.supplier_bank_detail_id || ''}
|
|
onChange={(event) =>
|
|
form.setData(
|
|
'supplier_bank_detail_id',
|
|
Number(event.target.value),
|
|
)
|
|
}
|
|
>
|
|
<option value="">Seleccione uma conta validada</option>
|
|
{selected.banks.map((bank) => (
|
|
<option
|
|
key={bank.id}
|
|
value={bank.id}
|
|
disabled={bank.state !== 'approved'}
|
|
>
|
|
{bank.label} ·{' '}
|
|
{bank.state === 'approved'
|
|
? 'Validada'
|
|
: 'Por concluir'}
|
|
</option>
|
|
))}
|
|
</select>
|
|
{selected.banks.length === 0 && (
|
|
<p className="mt-2 text-sm">
|
|
Não há conta disponível na moeda desta factura.
|
|
Consulte os dados bancários do fornecedor.
|
|
</p>
|
|
)}
|
|
</label>
|
|
)}
|
|
{selected && (
|
|
<p className="text-sm">
|
|
Versão bancária seleccionada:{' '}
|
|
{selected.banks?.find(
|
|
(bank) => bank.id === form.data.supplier_bank_detail_id,
|
|
)?.revision ??
|
|
(selected.bank_revision || 'Por seleccionar')}
|
|
. Se os dados mudarem, a confirmação será bloqueada.
|
|
</p>
|
|
)}
|
|
<label>
|
|
Montante do pagamento ({selected?.currency ?? 'MZN'})
|
|
<Input
|
|
required
|
|
inputMode="decimal"
|
|
value={form.data.amount}
|
|
onChange={(e) => form.setData('amount', e.target.value)}
|
|
/>
|
|
</label>
|
|
<label>
|
|
Data efectiva do pagamento
|
|
<Input
|
|
required
|
|
type="date"
|
|
value={form.data.paid_on}
|
|
onChange={(e) => form.setData('paid_on', e.target.value)}
|
|
/>
|
|
</label>
|
|
<label>
|
|
Referência externa da operação
|
|
<Input
|
|
required
|
|
autoComplete="off"
|
|
maxLength={150}
|
|
value={form.data.external_reference}
|
|
onChange={(e) =>
|
|
form.setData('external_reference', e.target.value)
|
|
}
|
|
/>
|
|
</label>
|
|
<label>
|
|
Referência da evidência
|
|
<Input
|
|
required
|
|
autoComplete="off"
|
|
maxLength={1000}
|
|
value={form.data.evidence_reference}
|
|
onChange={(e) =>
|
|
form.setData('evidence_reference', e.target.value)
|
|
}
|
|
/>
|
|
</label>
|
|
<Button
|
|
disabled={
|
|
!selected ||
|
|
selected.outstanding_minor <= 0 ||
|
|
selected.bank_state !== 'approved' ||
|
|
form.processing
|
|
}
|
|
>
|
|
Registar para conferência independente
|
|
</Button>
|
|
</form>
|
|
);
|
|
}
|