import { Head, Link, useForm, usePage } from '@inertiajs/react'; import { useEffect, useRef, type RefObject } from 'react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { FormErrors, PageTitle, Panel } from '@/components/procurement'; import { orderPartDraftKey, orderPartMinor } from '@/lib/order-parts'; import { money } from '@/types/procurement'; type Selection = { award_id: number; items: { quotation_item_id: number; quantity: string }[]; }; type Candidate = { id: number; requisition_id: number; number: string; supplier: string; currency: string; items: { id: number; description: string; remaining: string }[]; }; type Financial = { origin: number; award_id: number; requires_adoption: boolean; version?: number; plan_hash?: string; allocations: { allocation_key: string; line_id: number; centre_id: number; description: string; subtotal: string; total: string; }[]; }; type Preview = { selection: { sources: Selection[] }; can_issue: boolean; financial: Financial[]; prepared: { fingerprint: string; currency: string; subtotal_minor: number; total_minor: number; sources: { requisition_id: number; requisition_number?: string | null; award_id: number; currency: string; items: { description: string; quotation_item_id: number; quantity_offset_milli: number; quantity_milli: number; total_minor: number; }[]; }[]; }; }; type Props = { candidates: { data: Candidate[]; prev_page_url: string | null; next_page_url: string | null; }; preview: Preview | null; }; function useGuard(ref: RefObject, dirty: boolean) { useEffect(() => { const form = ref.current; window.dispatchEvent( new CustomEvent('sgc:context-dirty', { detail: { form, dirty } }), ); return () => { window.dispatchEvent( new CustomEvent('sgc:context-dirty', { detail: { form, dirty: false }, }), ); }; }, [dirty, ref]); } function Adoption({ award }: { award: number }) { const form = useForm({ operation_key: crypto.randomUUID() }); return (

Esta origem ainda não tem distribuição para parcelas. Pode adoptar a reserva já adjudicada, conservando o centro, os valores e o histórico. Uma ordem anterior não é alterada.

Se não existir reserva, complete primeiro o controlo orçamental da origem. A adopção não cria dotação nem saldo.

); } function Prepared({ preview, historyKey, }: { preview: Preview; historyKey: string; }) { const initial = { order_key: crypto.randomUUID(), operation_key: crypto.randomUUID(), budget_sources: preview.financial.map((source) => ({ origin: source.origin, version: source.version ?? 0, plan_hash: source.plan_hash ?? '', allocations: source.allocations.map((row) => ({ allocation_key: row.allocation_key, subtotal: row.subtotal, total: row.total, })), })), }; const form = useForm(historyKey, initial); const ref = useRef(null); const changed = form.data.budget_sources.some((source, i) => source.allocations.some( (row, j) => row.subtotal !== initial.budget_sources[i]?.allocations[j]?.subtotal || row.total !== initial.budget_sources[i]?.allocations[j]?.total, ), ); useGuard(ref, changed); return (

As origens mantêm as suas aprovações. Só as quantidades indicadas são emitidas; a reserva restante fica disponível para as próximas parcelas. Cancelar uma parcela não autoriza a sua repetição.

{ event.preventDefault(); const invalid = form.data.budget_sources.some( (source) => source.allocations.some( (row) => orderPartMinor(row.subtotal) === null || orderPartMinor(row.total) === null, ), ); if (invalid) { form.setError( 'budget_sources', 'Indique montantes válidos, com até duas casas decimais.', ); return; } form.transform((data) => ({ order_key: data.order_key, operation_key: data.operation_key, sources: preview.selection.sources, fingerprint: preview.prepared.fingerprint, budget_sources: data.budget_sources.map( (source) => ({ origin: source.origin, version: source.version, plan_hash: source.plan_hash, allocations: source.allocations.map( (row) => ({ allocation_key: row.allocation_key, subtotal_minor: orderPartMinor( row.subtotal, ), total_minor: orderPartMinor( row.total, ), }), ), }), ), })); form.post('/ordens/parcelas/emitir'); }} > {preview.prepared.sources.map((source, index) => (
{source.requisition_number ?? `Origem #${source.requisition_id}`} {source.items.map((line, i) => (

{line.description}:{' '} {line.quantity_milli / 1000} —{' '} {money(line.total_minor, source.currency)}

))} {preview.financial[index].requires_adoption ? ( ) : ( <>

Confira a imputação em MZN por centro. Quando há vários centros, indique explicitamente os montantes; o sistema não distribui diferenças automaticamente.

{preview.financial[index].allocations.map( (row, position) => (

{row.description} · Centro # {row.centre_id}

), )} )}
))}

Total documental:{' '} {money( preview.prepared.total_minor, preview.prepared.currency, )}

{!preview.can_issue && (

Complete a distribuição de todas as origens antes de emitir. A emissão multimoeda por parcelas ainda não está disponível.

)}

Na emissão voltam a ser verificadas aprovações, quantidades, versões e orçamento. Se a origem tiver mudado, conserve os valores e volte a conferir.

); } export default function Parts({ candidates, preview }: Props) { const actor = usePage().props.auth?.user; const historyKey = `order-parts:${actor?.tenant_id}:${actor?.id}`; const form = useForm<{ sources: Selection[] }>(`${historyKey}:selection`, { sources: [], }); const ref = useRef(null); useGuard(ref, form.data.sources.length > 0); useEffect(() => { if (preview) { const review = document.getElementById('order-parts-review'); review?.scrollIntoView({ block: 'start' }); review?.focus({ preventScroll: true }); } }, [preview]); const draftKey = preview ? orderPartDraftKey(preview.prepared.sources) : ''; return ( <>
Voltar às adjudicações e ordens
{ event.preventDefault(); form.post('/ordens/preparar', { preserveState: true, preserveScroll: true, }); }} >

Escolha apenas as linhas a emitir agora. O saldo de quantidade já inclui as parcelas anteriores, mesmo canceladas. As aprovações e os prazos serão novamente conferidos.

As escolhas ficam conservadas neste navegador para o seu utilizador e empresa. Depois de actualizar a página, volte a conferir para recuperar a preparação actual.

{candidates.data.map((candidate) => { const selected = form.data.sources.find( (source) => source.award_id === candidate.id, ); return (
{candidate.number} ·{' '} {candidate.supplier} ·{' '} {candidate.currency} {candidate.items.map((line) => { const value = selected?.items.find( (item) => item.quotation_item_id === line.id, ); return (
{value && ( )}
); })} Consultar a adjudicação
); })} {candidates.data.length === 0 && (

Não há adjudicações aprovadas disponíveis nesta página.

)}

{form.data.sources.length}{' '} {form.data.sources.length === 1 ? 'origem seleccionada' : 'origens seleccionadas'} , incluindo escolhas de outras páginas.

{preview && ( `${source.plan_hash}:${source.version}`).join(':')}`} preview={preview} historyKey={`${historyKey}:issue:${draftKey}:${preview.financial.map((source) => source.version).join(':')}`} /> )}
); }