@@ -1,3 +1,5 @@
|
||||
import { RequisitionApprovalSettings } from '@/components/requisition-approval-settings';
|
||||
import type { RequisitionApprovalPlan } from '@/components/requisition-approval-settings';
|
||||
import { CompanyDetailsSettings } from '@/components/company-details-settings';
|
||||
import type { CompanyDetails } from '@/components/company-details-settings';
|
||||
import { CompanyAdministrativeLocation } from '@/components/administrative-location';
|
||||
@@ -169,6 +171,8 @@ function Assignment({
|
||||
);
|
||||
}
|
||||
export default function Parameters({
|
||||
approvalLevels,
|
||||
approvalLevelsReady = false,
|
||||
companyDetails,
|
||||
companyDetailsReady,
|
||||
ready,
|
||||
@@ -195,6 +199,8 @@ export default function Parameters({
|
||||
workContextConfiguration,
|
||||
enabledWorkContexts = [],
|
||||
}: {
|
||||
approvalLevels?: RequisitionApprovalPlan | null;
|
||||
approvalLevelsReady?: boolean;
|
||||
companyDetails: CompanyDetails | null;
|
||||
companyDetailsReady: boolean;
|
||||
ready: boolean;
|
||||
@@ -307,6 +313,13 @@ export default function Parameters({
|
||||
tasks={workflowTasks}
|
||||
/>
|
||||
)}
|
||||
<RequisitionApprovalSettings
|
||||
plan={approvalLevels}
|
||||
ready={approvalLevelsReady}
|
||||
profiles={profiles}
|
||||
costCenters={costCenters}
|
||||
version={version}
|
||||
/>
|
||||
<CompanyDetailsSettings
|
||||
details={companyDetails}
|
||||
ready={companyDetailsReady && ready}
|
||||
|
||||
@@ -1,5 +1,17 @@
|
||||
import { Head, Link, router, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
Head,
|
||||
Link,
|
||||
router,
|
||||
useForm,
|
||||
usePage,
|
||||
useRemember,
|
||||
} from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import BudgetDistributionFields, {
|
||||
type BudgetDistributionInput,
|
||||
type BudgetDistributionOption,
|
||||
} from '@/components/budget-distribution-fields';
|
||||
import {
|
||||
FormErrors,
|
||||
PageTitle,
|
||||
@@ -14,6 +26,7 @@ import type { Page } from '@/types/inventory';
|
||||
|
||||
type Source = {
|
||||
id: number;
|
||||
requisition_item_id?: number;
|
||||
description: string;
|
||||
unit: string;
|
||||
unit_price_minor: number;
|
||||
@@ -67,6 +80,7 @@ export default function Invoices({
|
||||
currency?: string;
|
||||
supplier: string;
|
||||
items: Source[];
|
||||
budgetDistributionOptions?: BudgetDistributionOption[] | null;
|
||||
}[];
|
||||
canManage: boolean;
|
||||
focusInvoiceId?: number | null;
|
||||
@@ -89,17 +103,31 @@ export default function Invoices({
|
||||
event_on: string;
|
||||
}[];
|
||||
}) {
|
||||
const [orderId, setOrderId] = useState(
|
||||
const actor = usePage().props.auth?.user;
|
||||
const historyKey = `invoice-preparation:${actor?.tenant_id}:${actor?.id}:${focusOrderId ?? 'all'}`;
|
||||
const [orderId, setOrderId] = useRemember(
|
||||
focusOrderId === null ? '' : String(focusOrderId),
|
||||
`${historyKey}:order`,
|
||||
);
|
||||
const [validationError, setValidationError] = useState('');
|
||||
const [validating, setValidating] = useState<number | null>(null);
|
||||
const form = useForm({
|
||||
const initialData = {
|
||||
number: '',
|
||||
issued_on: '',
|
||||
subtotal: '',
|
||||
tax: '',
|
||||
total: '',
|
||||
reason: '',
|
||||
budget_distribution_preparation: (
|
||||
orders.find((source) => source.id === focusOrderId)
|
||||
?.budgetDistributionOptions ?? []
|
||||
).map(({ allocation_key, line_id, centre_id }) => ({
|
||||
allocation_key,
|
||||
line_id,
|
||||
centre_id,
|
||||
subtotal: '',
|
||||
total: '',
|
||||
})) as BudgetDistributionInput[],
|
||||
items: (orders
|
||||
.find((source) => source.id === focusOrderId)
|
||||
?.items.map((line) => ({
|
||||
@@ -109,8 +137,29 @@ export default function Invoices({
|
||||
unit_price: (line.unit_price_minor / 100).toFixed(2),
|
||||
tax_rate: String(line.tax_rate),
|
||||
})) ?? []) as Line[],
|
||||
});
|
||||
};
|
||||
const form = useForm(historyKey, initialData);
|
||||
const formElement = useRef<HTMLFormElement>(null);
|
||||
const dirty = hasPreparationChanges(initialData, form.data);
|
||||
useEffect(() => {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('sgc:context-dirty', {
|
||||
detail: { form: formElement.current, dirty },
|
||||
}),
|
||||
);
|
||||
}, [dirty]);
|
||||
const order = orders.find((o) => String(o.id) === orderId);
|
||||
const activeLineIds = form.data.items
|
||||
.filter((line) => line.quantity !== '')
|
||||
.map(
|
||||
(line) =>
|
||||
order?.items.find(
|
||||
(source) => source.id === line.purchase_order_item_id,
|
||||
)?.requisition_item_id,
|
||||
);
|
||||
const activeAllocations = form.data.budget_distribution_preparation.filter(
|
||||
(row) => activeLineIds.includes(row.line_id),
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<Head title="Facturas" />
|
||||
@@ -190,11 +239,19 @@ export default function Invoices({
|
||||
description="Reutilize a encomenda e indique os dados novos do documento do fornecedor. Unidade, preço e IVA vêm da encomenda; os totais do documento continuam a exigir coincidência exacta e conferência independente."
|
||||
>
|
||||
<form
|
||||
ref={formElement}
|
||||
className="grid gap-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.transform((d) => ({
|
||||
...d,
|
||||
budget_distribution_preparation:
|
||||
d.budget_distribution_preparation.filter(
|
||||
(row) =>
|
||||
activeLineIds.includes(
|
||||
row.line_id,
|
||||
),
|
||||
),
|
||||
items: d.items
|
||||
.filter((l) => l.quantity !== '')
|
||||
.map(
|
||||
@@ -224,6 +281,30 @@ export default function Invoices({
|
||||
value={orderId}
|
||||
onChange={(e) => {
|
||||
setOrderId(e.target.value);
|
||||
form.setData('reason', '');
|
||||
form.setData(
|
||||
'budget_distribution_preparation',
|
||||
(
|
||||
orders.find(
|
||||
(source) =>
|
||||
String(source.id) ===
|
||||
e.target.value,
|
||||
)?.budgetDistributionOptions ??
|
||||
[]
|
||||
).map(
|
||||
({
|
||||
allocation_key,
|
||||
line_id,
|
||||
centre_id,
|
||||
}) => ({
|
||||
allocation_key,
|
||||
line_id,
|
||||
centre_id,
|
||||
subtotal: '',
|
||||
total: '',
|
||||
}),
|
||||
),
|
||||
);
|
||||
form.setData(
|
||||
'items',
|
||||
orders
|
||||
@@ -371,6 +452,42 @@ export default function Invoices({
|
||||
</label>
|
||||
),
|
||||
)}
|
||||
{order?.budgetDistributionOptions != null && (
|
||||
<div className="space-y-3">
|
||||
{order.currency !== 'MZN' && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/ordens/${order.id}/reafectacao`}
|
||||
>
|
||||
Conferir ou reafectar compromisso em
|
||||
MZN
|
||||
</Link>
|
||||
)}
|
||||
<BudgetDistributionFields
|
||||
options={
|
||||
order.budgetDistributionOptions
|
||||
}
|
||||
rows={activeAllocations}
|
||||
reason={form.data.reason}
|
||||
onReason={(value) =>
|
||||
form.setData('reason', value)
|
||||
}
|
||||
onChange={(rows) =>
|
||||
form.setData(
|
||||
'budget_distribution_preparation',
|
||||
form.data.budget_distribution_preparation.map(
|
||||
(row) =>
|
||||
rows.find(
|
||||
(changed) =>
|
||||
changed.allocation_key ===
|
||||
row.allocation_key,
|
||||
) ?? row,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<Button disabled={!orderId || form.processing}>
|
||||
Registar para conferência independente
|
||||
</Button>
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import { Head, Link, useForm, usePage } from '@inertiajs/react';
|
||||
import BudgetDistributionFields, {
|
||||
type BudgetDistributionOption,
|
||||
} from '@/components/budget-distribution-fields';
|
||||
import AgreementOrderBindings, {
|
||||
type OrderAgreementBinding,
|
||||
type OrderAgreementOption,
|
||||
@@ -19,11 +22,12 @@ import { money, roleLabels, date } from '@/types/procurement';
|
||||
import type { MatrixRow, PurchaseAward } from '@/types/purchase';
|
||||
|
||||
type Props = {
|
||||
budgetDistributionOptions?: BudgetDistributionOption[] | null;
|
||||
agreementOrderLimitsReady?: boolean;
|
||||
agreementOptions?: OrderAgreementOption[];
|
||||
agreementLines?: OrderAgreementLine[];
|
||||
agreementSearch?: string;
|
||||
requisition: { id: number; number: string };
|
||||
requisition: { id: number; number: string; process_version?: number };
|
||||
comparison: {
|
||||
rows: MatrixRow[];
|
||||
ready: boolean;
|
||||
@@ -50,17 +54,51 @@ export default function Award({
|
||||
agreementOptions = [],
|
||||
agreementLines = [],
|
||||
agreementSearch = '',
|
||||
budgetDistributionOptions = null,
|
||||
}: Props) {
|
||||
const selection = useForm({
|
||||
quotation_id: '',
|
||||
justification: '',
|
||||
delivery_date: '',
|
||||
delivery_location: '',
|
||||
});
|
||||
const actor = usePage().props.auth?.user;
|
||||
const selection = useForm(
|
||||
`award-selection:${actor?.tenant_id}:${actor?.id}:${requisition.id}:${requisition.process_version ?? 0}`,
|
||||
{
|
||||
quotation_id: '',
|
||||
justification: '',
|
||||
delivery_date: '',
|
||||
delivery_location: '',
|
||||
...(budgetDistributionOptions === null
|
||||
? {}
|
||||
: {
|
||||
budget_distribution_preparation:
|
||||
budgetDistributionOptions.map(
|
||||
({
|
||||
allocation_key,
|
||||
line_id,
|
||||
centre_id,
|
||||
subtotal,
|
||||
total,
|
||||
}) => ({
|
||||
allocation_key,
|
||||
line_id,
|
||||
centre_id,
|
||||
subtotal,
|
||||
total,
|
||||
}),
|
||||
),
|
||||
reason: '',
|
||||
}),
|
||||
},
|
||||
);
|
||||
const decision = useForm({ decision: 'approved', comment: '' });
|
||||
const issue = useForm({
|
||||
agreement_bindings: [] as OrderAgreementBinding[],
|
||||
});
|
||||
const selectedQuote = comparison.rows.find(
|
||||
(row) => String(row.id) === selection.data.quotation_id,
|
||||
);
|
||||
const selectedReference =
|
||||
selectedQuote?.reference_amounts ??
|
||||
(selectedQuote && (selectedQuote.currency ?? 'MZN') === 'MZN'
|
||||
? selectedQuote
|
||||
: null);
|
||||
return (
|
||||
<>
|
||||
<Head title={`Adjudicação · ${requisition.number}`} />
|
||||
@@ -81,9 +119,12 @@ export default function Award({
|
||||
/>
|
||||
<div className="rounded-xl border border-amber-200 bg-amber-50 p-5 text-sm text-amber-900 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-100">
|
||||
Ambiente de desenvolvimento: os documentos não autorizam
|
||||
compras reais. O orçamento ainda não é verificado. Excepções
|
||||
à regra preservada neste processo ou à maior pontuação
|
||||
exigem um circuito próprio de revisão.
|
||||
compras reais.{' '}
|
||||
{budgetDistributionOptions === null
|
||||
? 'O orçamento ainda não é verificado.'
|
||||
: 'O saldo de cada parcela é conferido no controlo orçamental.'}{' '}
|
||||
Excepções à regra preservada neste processo ou à maior
|
||||
pontuação exigem um circuito próprio de revisão.
|
||||
</div>
|
||||
<Panel
|
||||
title="Comparação actual"
|
||||
@@ -201,12 +242,14 @@ export default function Award({
|
||||
className={controlClass}
|
||||
required
|
||||
value={selection.data.quotation_id}
|
||||
onChange={(e) =>
|
||||
onChange={(e) => {
|
||||
selection.setData(
|
||||
'quotation_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
);
|
||||
if (budgetDistributionOptions !== null)
|
||||
selection.setData('reason', '');
|
||||
}}
|
||||
>
|
||||
<option value="">
|
||||
Seleccione uma proposta no topo
|
||||
@@ -233,6 +276,37 @@ export default function Award({
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
{budgetDistributionOptions !== null &&
|
||||
selection.data.quotation_id !== '' && (
|
||||
<div className="space-y-3">
|
||||
<p>
|
||||
{selectedReference
|
||||
? `Referência da proposta em MZN: sem IVA ${money(selectedReference.subtotal_minor, 'MZN')} · total ${money(selectedReference.total_minor, 'MZN')}. Confira as parcelas abaixo.`
|
||||
: 'Referência em MZN indisponível. Confira a proposta e a taxa congelada.'}
|
||||
</p>
|
||||
<BudgetDistributionFields
|
||||
options={budgetDistributionOptions}
|
||||
rows={
|
||||
selection.data
|
||||
.budget_distribution_preparation ??
|
||||
[]
|
||||
}
|
||||
onChange={(rows) =>
|
||||
selection.setData(
|
||||
'budget_distribution_preparation',
|
||||
rows,
|
||||
)
|
||||
}
|
||||
reason={selection.data.reason ?? ''}
|
||||
onReason={(value) =>
|
||||
selection.setData(
|
||||
'reason',
|
||||
value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="award-justification">
|
||||
Justificação da adjudicação
|
||||
@@ -297,7 +371,11 @@ export default function Award({
|
||||
</p>
|
||||
<Button
|
||||
disabled={
|
||||
selection.processing || !comparison.ready
|
||||
selection.processing ||
|
||||
!comparison.ready ||
|
||||
(budgetDistributionOptions !== null &&
|
||||
selectedQuote !== undefined &&
|
||||
selectedReference === null)
|
||||
}
|
||||
>
|
||||
Registar adjudicação para aprovação
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import { Head, Link, useForm, usePage } from '@inertiajs/react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import BudgetDistributionFields, {
|
||||
type BudgetDistributionOption,
|
||||
} from '@/components/budget-distribution-fields';
|
||||
import { FormErrors, PageTitle, Panel } from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { money } from '@/types/procurement';
|
||||
|
||||
export default function Amendment({
|
||||
order,
|
||||
options,
|
||||
planHash,
|
||||
version,
|
||||
history,
|
||||
}: {
|
||||
order: { id: number; number: string; currency: string };
|
||||
options: BudgetDistributionOption[];
|
||||
planHash: string;
|
||||
version: number;
|
||||
history: {
|
||||
kind: string;
|
||||
created_at: string;
|
||||
created_by: number;
|
||||
version: number | null;
|
||||
reason: string | null;
|
||||
allocations: {
|
||||
allocation_key: string;
|
||||
line_id: number;
|
||||
centre_id: number;
|
||||
subtotal_minor: number;
|
||||
total_minor: number;
|
||||
}[];
|
||||
}[];
|
||||
}) {
|
||||
const actor = usePage().props.auth?.user;
|
||||
const initial = {
|
||||
operation_key: crypto.randomUUID(),
|
||||
expected_plan_hash: planHash,
|
||||
reason: '',
|
||||
budget_distribution_preparation: options.map(
|
||||
({ allocation_key, line_id, centre_id, subtotal, total }) => ({
|
||||
allocation_key,
|
||||
line_id,
|
||||
centre_id,
|
||||
subtotal,
|
||||
total,
|
||||
}),
|
||||
),
|
||||
};
|
||||
const form = useForm(
|
||||
`distribution-amendment:${actor?.tenant_id}:${actor?.id}:${order.id}:${planHash}`,
|
||||
initial,
|
||||
);
|
||||
const formElement = useRef<HTMLFormElement>(null);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
useEffect(() => {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('sgc:context-dirty', {
|
||||
detail: { form: formElement.current, dirty },
|
||||
}),
|
||||
);
|
||||
}, [dirty]);
|
||||
return (
|
||||
<>
|
||||
<Head title={`Reafectação · ${order.number}`} />
|
||||
<div className="mx-auto flex w-full max-w-5xl flex-col gap-6 p-5 lg:p-8">
|
||||
<PageTitle
|
||||
eyebrow="Finanças"
|
||||
title="Reafectar compromisso em MZN"
|
||||
description={`${order.number} · Documento em ${order.currency} · Versão ${version}`}
|
||||
/>
|
||||
<p>
|
||||
Confira a imputação exigida pela conversão cumulativa da
|
||||
factura parcial. Os totais documentais e a taxa congelada
|
||||
permanecem preservados. A alteração exige saldo disponível e
|
||||
conserva os valores já consumidos.
|
||||
</p>
|
||||
<FormErrors errors={form.errors} />
|
||||
<form
|
||||
ref={formElement}
|
||||
className="space-y-5"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
form.post(`/ordens/${order.id}/reafectacao`);
|
||||
}}
|
||||
>
|
||||
<BudgetDistributionFields
|
||||
options={options}
|
||||
rows={form.data.budget_distribution_preparation}
|
||||
onChange={(rows) =>
|
||||
form.setData(
|
||||
'budget_distribution_preparation',
|
||||
rows,
|
||||
)
|
||||
}
|
||||
reason={form.data.reason}
|
||||
onReason={(reason) => form.setData('reason', reason)}
|
||||
/>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button disabled={form.processing}>
|
||||
Confirmar nova versão
|
||||
</Button>
|
||||
<Button variant="outline" asChild>
|
||||
<Link href={`/ordens/${order.id}`}>
|
||||
Voltar à ordem
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
<Panel title="Histórico preservado">
|
||||
{history.map((event, index) => (
|
||||
<details key={index} className="border-b py-3">
|
||||
<summary>
|
||||
{event.version === null
|
||||
? event.kind
|
||||
: `Reafectação · versão ${event.version}`}{' '}
|
||||
· {event.created_at} · Interveniente #
|
||||
{event.created_by}
|
||||
</summary>
|
||||
{event.reason && <p>{event.reason}</p>}
|
||||
<ul>
|
||||
{event.allocations.map((row) => (
|
||||
<li key={row.allocation_key}>
|
||||
Artigo #{row.line_id} · Centro #
|
||||
{row.centre_id} · Sem IVA:{' '}
|
||||
{money(row.subtotal_minor)} · Total:{' '}
|
||||
{money(row.total_minor)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
))}
|
||||
</Panel>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -49,14 +49,14 @@ export default function Orders({
|
||||
{order.number}
|
||||
</Link>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{
|
||||
order.snapshot.requisition
|
||||
.number
|
||||
}
|
||||
{order.snapshot.requisition
|
||||
?.number ??
|
||||
'Referência não preservada no original'}
|
||||
</p>
|
||||
</td>
|
||||
<td className="pr-4">
|
||||
{order.snapshot.supplier.name}
|
||||
{order.snapshot.supplier?.name ??
|
||||
'Fornecedor não preservado no original'}
|
||||
</td>
|
||||
<td className="pr-4">
|
||||
{date(order.issued_at)}
|
||||
|
||||
@@ -26,6 +26,7 @@ type Props = {
|
||||
decisions: {
|
||||
area: string;
|
||||
role: string;
|
||||
role_label?: string | null;
|
||||
decision: string;
|
||||
actor: string | null;
|
||||
date: string | null;
|
||||
@@ -60,6 +61,7 @@ const events: Record<string, string> = {
|
||||
'opening.recorded': 'Versão da acta de abertura registada',
|
||||
'requisition.created': 'Requisição criada',
|
||||
'requisition.updated': 'Requisição actualizada',
|
||||
'requisition.allocations_prepared': 'Distribuição preparada',
|
||||
'requisition.submitted': 'Requisição submetida',
|
||||
'requisition.revision_created': 'Revisão criada em novo processo',
|
||||
'approval.approved': 'Etapa da estimativa aprovada',
|
||||
@@ -80,6 +82,12 @@ const events: Record<string, string> = {
|
||||
'budget.award': 'Reserva ajustada à adjudicação',
|
||||
'budget.commit': 'Compromisso registado',
|
||||
'budget.release': 'Reserva libertada',
|
||||
'budget.distribution_reserve': 'Reserva distribuída registada',
|
||||
'budget.distribution_award': 'Distribuição da adjudicação confirmada',
|
||||
'budget.distribution_commit': 'Compromisso distribuído registado',
|
||||
'budget.distribution_release': 'Reserva distribuída libertada',
|
||||
'budget.distribution_cancel': 'Compromisso distribuído cancelado',
|
||||
'budget.distribution_amended': 'Compromisso reafectado por Finanças',
|
||||
'cancellation.requested': 'Cancelamento solicitado',
|
||||
'cancellation.approved': 'Cancelamento aprovado',
|
||||
'cancellation.rejected': 'Cancelamento rejeitado',
|
||||
@@ -217,7 +225,8 @@ export default function PurchaseProcess({
|
||||
<div className="flex flex-wrap justify-between gap-2">
|
||||
<strong className="font-medium">
|
||||
{decision.area} ·{' '}
|
||||
{roleLabels[decision.role] ??
|
||||
{decision.role_label ??
|
||||
roleLabels[decision.role] ??
|
||||
decision.role}
|
||||
</strong>
|
||||
<span>
|
||||
|
||||
@@ -28,12 +28,81 @@ export default function OrderShow({
|
||||
order,
|
||||
history,
|
||||
orderCancellation,
|
||||
snapshotComplete = true,
|
||||
}: {
|
||||
order: PurchaseOrder;
|
||||
history: History[];
|
||||
orderCancellation?: OrderCancellationState;
|
||||
snapshotComplete?: boolean;
|
||||
}) {
|
||||
const snapshot = order.snapshot;
|
||||
if (!snapshotComplete) {
|
||||
return (
|
||||
<>
|
||||
<Head title={order.number} />
|
||||
<div className="mx-auto grid w-full max-w-6xl min-w-0 gap-6 p-5 lg:p-8">
|
||||
<PageTitle
|
||||
eyebrow="Compras"
|
||||
title={order.number}
|
||||
description="Consulta dos dados preservados na emissão."
|
||||
/>
|
||||
<Panel title="Documento original incompleto">
|
||||
<p>
|
||||
Este documento não conserva todos os elementos da
|
||||
emissão. Os dados disponíveis são apresentados sem
|
||||
reconstruir condições ou aprovações a partir dos
|
||||
cadastros actuais.
|
||||
</p>
|
||||
<dl className="mt-4 grid gap-3 text-sm">
|
||||
<div>
|
||||
<dt>Fornecedor preservado</dt>
|
||||
<dd>
|
||||
{snapshot.supplier?.name ??
|
||||
'Não registado no original'}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Emissão</dt>
|
||||
<dd>{date(order.issued_at)}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Total com IVA</dt>
|
||||
<dd>
|
||||
{money(order.total_minor, order.currency)}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p className="mt-4">
|
||||
Confira o documento de origem antes de o utilizar
|
||||
como comprovativo completo.
|
||||
</p>
|
||||
</Panel>
|
||||
<Panel title="Artigos preservados">
|
||||
<ul className="grid gap-3">
|
||||
{order.items.map((item) => (
|
||||
<li key={item.id} className="break-words">
|
||||
{item.description} · {item.quantity}{' '}
|
||||
{item.unit} ·{' '}
|
||||
{money(item.total_minor, order.currency)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Panel>
|
||||
<a
|
||||
className="underline"
|
||||
href={`/ordens/${order.id}/imprimir`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Imprimir os dados preservados
|
||||
</a>
|
||||
<Link className="underline" href="/ordens">
|
||||
Voltar às ordens
|
||||
</Link>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<Head title={order.number} />
|
||||
|
||||
@@ -10,6 +10,10 @@ import { Button } from '@/components/ui/button';
|
||||
import { date, statusLabels } from '@/types/procurement';
|
||||
import { ProcurementOperationalInsights } from '@/components/procurement-operational-insights';
|
||||
import type { ProcurementInsights } from '@/components/procurement-operational-insights';
|
||||
import {
|
||||
ProcurementPayableInsights,
|
||||
type PayableInsights,
|
||||
} from '@/components/procurement-payable-insights';
|
||||
|
||||
type Row = {
|
||||
id: number;
|
||||
@@ -43,6 +47,7 @@ export default function ProcurementReports({
|
||||
departments,
|
||||
generatedAt,
|
||||
insights,
|
||||
payableInsights,
|
||||
}: {
|
||||
records: {
|
||||
data: Row[];
|
||||
@@ -57,6 +62,7 @@ export default function ProcurementReports({
|
||||
departments: { id: number; name: string }[];
|
||||
generatedAt: string;
|
||||
insights?: ProcurementInsights;
|
||||
payableInsights?: PayableInsights | null;
|
||||
}) {
|
||||
const form = useForm({
|
||||
search: filters.search ?? '',
|
||||
@@ -101,6 +107,12 @@ export default function ProcurementReports({
|
||||
withoutOrderHref={`/relatorios?${orderParams}`}
|
||||
/>
|
||||
)}
|
||||
{payableInsights && (
|
||||
<ProcurementPayableInsights
|
||||
data={payableInsights}
|
||||
exportHref={`/relatorios/obrigacoes.csv?${params}`}
|
||||
/>
|
||||
)}
|
||||
<Panel
|
||||
title="Filtrar requisições"
|
||||
description="O período refere-se à criação da requisição. Os resultados respeitam o seu acesso à empresa e ao departamento."
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
import { Head, Link, useForm, usePage } from '@inertiajs/react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import {
|
||||
FormErrors,
|
||||
PageTitle,
|
||||
Panel,
|
||||
controlClass,
|
||||
} from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { money } from '@/types/procurement';
|
||||
import type { Requisition } from '@/types/procurement';
|
||||
|
||||
type Allocation = {
|
||||
allocation_key: string;
|
||||
line_id: number;
|
||||
centre_id: number;
|
||||
subtotal_minor: number;
|
||||
total_minor: number;
|
||||
};
|
||||
const decimal = (value: number) =>
|
||||
`${Math.floor(value / 100)}.${String(value % 100).padStart(2, '0')}`;
|
||||
|
||||
export default function Distributions({
|
||||
requisition: r,
|
||||
centres,
|
||||
preparation,
|
||||
}: {
|
||||
requisition: Omit<Requisition, 'items'> & {
|
||||
items: (Requisition['items'][number] & { id: number })[];
|
||||
};
|
||||
centres: { id: number; code: string; name: string }[];
|
||||
preparation: { allocations: Allocation[]; reason: string } | null;
|
||||
}) {
|
||||
const actor = usePage().props.auth?.user;
|
||||
const initial = {
|
||||
operation_key: crypto.randomUUID(),
|
||||
process_version: r.process_version,
|
||||
reason: '',
|
||||
budget_distribution_preparation: (preparation?.allocations ?? []).map(
|
||||
(row) => ({
|
||||
allocation_key: row.allocation_key,
|
||||
line_id: row.line_id,
|
||||
centre_id: row.centre_id,
|
||||
subtotal: decimal(row.subtotal_minor),
|
||||
total: decimal(row.total_minor),
|
||||
}),
|
||||
),
|
||||
};
|
||||
const form = useForm(
|
||||
`distribution:${actor?.tenant_id}:${actor?.id}:${r.id}:${r.process_version}`,
|
||||
initial,
|
||||
);
|
||||
const formElement = useRef<HTMLFormElement>(null);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
useEffect(() => {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('sgc:context-dirty', {
|
||||
detail: { form: formElement.current, dirty },
|
||||
}),
|
||||
);
|
||||
}, [dirty]);
|
||||
const rows = form.data.budget_distribution_preparation;
|
||||
return (
|
||||
<>
|
||||
<Head title={`Distribuição · ${r.number}`} />
|
||||
<div className="mx-auto flex w-full max-w-5xl flex-col gap-6 p-5 lg:p-8">
|
||||
<PageTitle
|
||||
eyebrow="Requisição de compra"
|
||||
title="Distribuir por centros de custo"
|
||||
description={r.number}
|
||||
/>
|
||||
<p>
|
||||
Indique os valores de cada artigo por centro. As parcelas
|
||||
devem corresponder exactamente ao valor sem IVA e ao total
|
||||
do artigo. Guardar prepara a distribuição; a reserva ocorre
|
||||
ao submeter o pedido.
|
||||
</p>
|
||||
<FormErrors errors={form.errors} />
|
||||
<form
|
||||
ref={formElement}
|
||||
className="flex flex-col gap-6"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
form.post(`/requisicoes/${r.id}/distribuicoes`);
|
||||
}}
|
||||
>
|
||||
{r.items.map((line) => (
|
||||
<Panel key={line.id} title={line.description}>
|
||||
<p>
|
||||
Sem IVA: {money(line.subtotal_minor)} · Total:{' '}
|
||||
{money(line.total_minor)}
|
||||
</p>
|
||||
{rows.map((row, index) =>
|
||||
row.line_id !== line.id ? null : (
|
||||
<fieldset
|
||||
key={row.allocation_key}
|
||||
className="my-4 grid gap-3 rounded border p-3 sm:grid-cols-3"
|
||||
>
|
||||
<legend>
|
||||
Parcela{' '}
|
||||
{
|
||||
rows.filter(
|
||||
(item, i) =>
|
||||
i <= index &&
|
||||
item.line_id ===
|
||||
line.id,
|
||||
).length
|
||||
}
|
||||
</legend>
|
||||
<label>
|
||||
Centro de custo
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={row.centre_id || ''}
|
||||
onChange={(event) =>
|
||||
form.setData(
|
||||
'budget_distribution_preparation',
|
||||
rows.map((item, i) =>
|
||||
i === index
|
||||
? {
|
||||
...item,
|
||||
centre_id:
|
||||
Number(
|
||||
event
|
||||
.target
|
||||
.value,
|
||||
),
|
||||
}
|
||||
: item,
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Seleccione
|
||||
</option>
|
||||
{centres.map((centre) => (
|
||||
<option
|
||||
key={centre.id}
|
||||
value={centre.id}
|
||||
>
|
||||
{centre.code} ·{' '}
|
||||
{centre.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{(['subtotal', 'total'] as const).map(
|
||||
(field) => (
|
||||
<label key={field}>
|
||||
{field === 'subtotal'
|
||||
? 'Sem IVA (MZN)'
|
||||
: 'Total (MZN)'}
|
||||
<input
|
||||
required
|
||||
inputMode="decimal"
|
||||
pattern="[0-9]+([.][0-9]{1,2})?"
|
||||
className={controlClass}
|
||||
value={row[field]}
|
||||
onChange={(event) =>
|
||||
form.setData(
|
||||
'budget_distribution_preparation',
|
||||
rows.map(
|
||||
(
|
||||
item,
|
||||
i,
|
||||
) =>
|
||||
i ===
|
||||
index
|
||||
? {
|
||||
...item,
|
||||
[field]:
|
||||
event
|
||||
.target
|
||||
.value,
|
||||
}
|
||||
: item,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
),
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
form.setData(
|
||||
'budget_distribution_preparation',
|
||||
rows.filter(
|
||||
(_, i) => i !== index,
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
Remover parcela
|
||||
</Button>
|
||||
</fieldset>
|
||||
),
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={rows.length >= 500}
|
||||
onClick={() =>
|
||||
form.setData(
|
||||
'budget_distribution_preparation',
|
||||
[
|
||||
...rows,
|
||||
{
|
||||
allocation_key:
|
||||
crypto.randomUUID(),
|
||||
line_id: line.id,
|
||||
centre_id: 0,
|
||||
subtotal: '',
|
||||
total: '',
|
||||
},
|
||||
],
|
||||
)
|
||||
}
|
||||
>
|
||||
Adicionar parcela
|
||||
</Button>
|
||||
</Panel>
|
||||
))}
|
||||
<label>
|
||||
Motivo da distribuição
|
||||
<textarea
|
||||
required
|
||||
minLength={10}
|
||||
maxLength={4000}
|
||||
className={controlClass}
|
||||
value={form.data.reason}
|
||||
onChange={(event) =>
|
||||
form.setData('reason', event.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<p className="text-sm">
|
||||
Se os artigos ou valores forem alterados, será
|
||||
necessário conferir novamente a distribuição. Use ponto
|
||||
para separar os centavos. Nenhuma diferença será
|
||||
compensada automaticamente.
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button disabled={form.processing || rows.length === 0}>
|
||||
Guardar distribuição
|
||||
</Button>
|
||||
<Button asChild variant="outline">
|
||||
<Link href={`/requisicoes/${r.id}`}>
|
||||
Voltar ao pedido
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Head, Link, useForm, usePage } from '@inertiajs/react';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { Plus, Save, Trash2 } from 'lucide-react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import {
|
||||
@@ -100,7 +101,10 @@ export default function RequisitionForm({
|
||||
catalogue?: CatalogueOptions;
|
||||
incompleteDraftsAvailable?: boolean;
|
||||
}) {
|
||||
const ready = usePage().props.internalRequisitionReady === true;
|
||||
const page = usePage();
|
||||
const ready = page.props.internalRequisitionReady === true;
|
||||
const actor = page.props.auth?.user;
|
||||
const historyKey = `requisition:${String(actor?.tenant_id ?? 'none')}:${actor?.id ?? 'none'}:${requisition?.id ?? 'new'}:${requisition?.process_version ?? 0}`;
|
||||
const prepared = requisition?.draft_input?.values;
|
||||
const preparedLines = prepared?.items?.map(
|
||||
(row) =>
|
||||
@@ -113,7 +117,7 @@ export default function RequisitionForm({
|
||||
]),
|
||||
) as Line,
|
||||
);
|
||||
const form = useForm({
|
||||
const initialData = {
|
||||
operation_key: ready ? crypto.randomUUID() : null,
|
||||
process_version: requisition?.process_version ?? null,
|
||||
cost_center_id:
|
||||
@@ -149,15 +153,17 @@ export default function RequisitionForm({
|
||||
production_area: i.production_area ?? '',
|
||||
downtime_started_at: i.downtime_started_at?.slice(0, 16) ?? '',
|
||||
})) ?? [emptyLine(defaultTaxRate)],
|
||||
});
|
||||
};
|
||||
const form = useForm(historyKey, initialData);
|
||||
const preparationDirty = hasPreparationChanges(initialData, form.data);
|
||||
const formElement = useRef<HTMLFormElement>(null);
|
||||
useEffect(() => {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('sgc:context-dirty', {
|
||||
detail: { form: formElement.current, dirty: form.isDirty },
|
||||
detail: { form: formElement.current, dirty: preparationDirty },
|
||||
}),
|
||||
);
|
||||
}, [form.isDirty]);
|
||||
}, [preparationDirty]);
|
||||
const changeLine = (index: number, field: keyof Line, value: string) =>
|
||||
form.setData(
|
||||
'items',
|
||||
@@ -319,7 +325,7 @@ export default function RequisitionForm({
|
||||
</Panel>
|
||||
<Panel
|
||||
title="Artigos e serviços"
|
||||
description="Preços em MZN. Indique a taxa de IVA aplicável; o valor inicial de 0% deve ser revisto por Finanças."
|
||||
description="Preços em MZN. Confira a taxa de IVA aplicável a cada artigo antes de submeter."
|
||||
>
|
||||
<div className="space-y-5">
|
||||
{catalogue?.ready && (
|
||||
|
||||
@@ -26,6 +26,13 @@ const actions: Record<string, string> = {
|
||||
'requisition.automatically_created':
|
||||
'Rascunho de reposição criado automaticamente',
|
||||
'requisition.updated': 'Rascunho actualizado',
|
||||
'requisition.allocations_prepared': 'Distribuição preparada',
|
||||
'budget.distribution_reserve': 'Reserva distribuída registada',
|
||||
'budget.distribution_award': 'Distribuição da adjudicação confirmada',
|
||||
'budget.distribution_commit': 'Compromisso distribuído registado',
|
||||
'budget.distribution_release': 'Reserva distribuída libertada',
|
||||
'budget.distribution_cancel': 'Compromisso distribuído cancelado',
|
||||
'budget.distribution_amended': 'Compromisso reafectado por Finanças',
|
||||
'requisition.submitted': 'Pedido submetido',
|
||||
'approval.approved': 'Etapa aprovada',
|
||||
'approval.rejected': 'Pedido rejeitado',
|
||||
@@ -44,10 +51,13 @@ export default function Show({
|
||||
automaticSource,
|
||||
approvalRouting,
|
||||
canRefreshRouting = false,
|
||||
canPrepareDistributions = false,
|
||||
}: {
|
||||
canPrepareDistributions?: boolean;
|
||||
requisition: Requisition;
|
||||
canRefreshRouting?: boolean;
|
||||
approvalRouting?: {
|
||||
label?: string | null;
|
||||
status: string;
|
||||
step_id: number | null;
|
||||
role: string | null;
|
||||
@@ -150,6 +160,13 @@ export default function Show({
|
||||
}
|
||||
/>
|
||||
<FormErrors errors={submission.errors} />
|
||||
{canPrepareDistributions && (
|
||||
<Button asChild variant="outline">
|
||||
<Link href={`/requisicoes/${r.id}/distribuicoes`}>
|
||||
Distribuir por centros de custo
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
{automaticSource && (
|
||||
<Panel title="Origem na reposição automática">
|
||||
<p>
|
||||
@@ -584,9 +601,11 @@ export default function Show({
|
||||
>
|
||||
<p className="text-sm">
|
||||
Etapa:{' '}
|
||||
{roleLabels[
|
||||
approvalRouting.role ?? ''
|
||||
] ?? approvalRouting.role}
|
||||
{approvalRouting.label ??
|
||||
roleLabels[
|
||||
approvalRouting.role ?? ''
|
||||
] ??
|
||||
approvalRouting.role}
|
||||
.
|
||||
</p>
|
||||
{canRefreshRouting && (
|
||||
@@ -702,7 +721,9 @@ export default function Show({
|
||||
</span>
|
||||
<div>
|
||||
<p className="text-sm font-medium">
|
||||
{roleLabels[s.role]}
|
||||
{s.routing?.name ??
|
||||
roleLabels[s.role] ??
|
||||
s.role}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{s.decision === 'pending'
|
||||
|
||||
@@ -28,13 +28,16 @@ const statuses: Record<string, string> = {
|
||||
issued: 'Emitida',
|
||||
active: 'Activo',
|
||||
inactive: 'Inactivo',
|
||||
confirmed: 'Confirmada',
|
||||
};
|
||||
export default function ProcurementSearch({
|
||||
term,
|
||||
groups,
|
||||
invoiceSearchAvailable = false,
|
||||
}: {
|
||||
term: string;
|
||||
groups: Group[];
|
||||
invoiceSearchAvailable?: boolean;
|
||||
}) {
|
||||
const form = useForm({ q: term });
|
||||
return (
|
||||
@@ -48,7 +51,7 @@ export default function ProcurementSearch({
|
||||
/>
|
||||
<Panel
|
||||
title="Pesquisa transversal de Compras"
|
||||
description="Pesquise requisições, ordens, fornecedores, recepções, equipamentos, artigos e armazéns por referência, necessidade, nome, código ou NUIT. Esta entrega ainda não pesquisa Pessoas, facturas, conteúdo de anexos ou arquivos externos."
|
||||
description={`Pesquise requisições, ordens, fornecedores, recepções, equipamentos, artigos e armazéns por referência, necessidade, nome, código ou NUIT.${invoiceSearchAvailable ? ' Pode também procurar facturas de fornecedor pelo número, dentro do seu acesso financeiro.' : ''} A pesquisa não inclui Pessoas, conteúdo de anexos ou arquivos externos.`}
|
||||
>
|
||||
<form
|
||||
className="flex flex-wrap items-end gap-3"
|
||||
@@ -79,6 +82,13 @@ export default function ProcurementSearch({
|
||||
<Button disabled={form.processing}>Pesquisar</Button>
|
||||
</form>
|
||||
<FormErrors errors={form.errors} />
|
||||
{invoiceSearchAvailable && (
|
||||
<p className="mt-3 text-sm text-muted-foreground">
|
||||
Os resultados de facturas mostram a referência e o
|
||||
estado. Abra a factura para consultar os valores e
|
||||
documentos autorizados.
|
||||
</p>
|
||||
)}
|
||||
</Panel>
|
||||
{term.trim().length < 2 && (
|
||||
<p role="status">
|
||||
|
||||
@@ -15,6 +15,7 @@ type Props = {
|
||||
id: number;
|
||||
reference: string;
|
||||
role: string;
|
||||
role_label?: string | null;
|
||||
kind: string;
|
||||
outcome: string | null;
|
||||
current_status: string;
|
||||
@@ -135,7 +136,9 @@ export default function Notices({
|
||||
href={notice.href}
|
||||
>
|
||||
{notice.reference} ·{' '}
|
||||
{roleLabels[notice.role] ?? notice.role}
|
||||
{notice.role_label ??
|
||||
roleLabels[notice.role] ??
|
||||
notice.role}
|
||||
</Link>
|
||||
{notice.kind === 'outcome' && (
|
||||
<p className="mt-2 text-sm">
|
||||
|
||||
Reference in New Issue
Block a user