@@ -1,5 +1,8 @@
|
||||
import { useProcurementPreparationIdentity } from '@/hooks/use-procurement-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { useEffect, useId, useState } from 'react';
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { FormErrors, controlClass } from '@/components/procurement';
|
||||
|
||||
@@ -218,25 +221,47 @@ export function AdministrativeLocation({
|
||||
);
|
||||
}
|
||||
|
||||
export function CompanyAdministrativeLocation({
|
||||
geography,
|
||||
}: {
|
||||
export function CompanyAdministrativeLocation(props: {
|
||||
geography: GeographyDescription;
|
||||
}) {
|
||||
const form = useForm({
|
||||
const identity = useProcurementPreparationIdentity(
|
||||
`company-location:${JSON.stringify(props.geography?.reference ?? null)}`,
|
||||
);
|
||||
return (
|
||||
<CompanyLocationFields key={identity} {...props} identity={identity} />
|
||||
);
|
||||
}
|
||||
function CompanyLocationFields({
|
||||
geography,
|
||||
identity,
|
||||
}: {
|
||||
identity: string;
|
||||
geography: GeographyDescription;
|
||||
}) {
|
||||
const initial = {
|
||||
geography_reference:
|
||||
geography?.reference ?? (null as GeographyReference | null),
|
||||
expected_reference: geography?.reference ?? null,
|
||||
});
|
||||
useEffect(() => {
|
||||
form.setData('expected_reference', geography?.reference ?? null);
|
||||
}, [geography]);
|
||||
};
|
||||
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="space-y-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
form.post('/empresa/localizacao', { preserveScroll: true });
|
||||
form.post('/empresa/localizacao', {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
router.remember(initial, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { useProcurementPreparationIdentity } from '@/hooks/use-procurement-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { Panel, FormErrors, controlClass } from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
@@ -14,20 +17,30 @@ export type AiPlan = {
|
||||
max_output_tokens: number;
|
||||
};
|
||||
|
||||
export function AiPlanSettings({
|
||||
export function AiPlanSettings(
|
||||
props: Omit<Parameters<typeof AiPlanFields>[0], 'identity'>,
|
||||
) {
|
||||
const identity = useProcurementPreparationIdentity(
|
||||
`ai-plan:${props.version}:${props.ready}`,
|
||||
);
|
||||
return <AiPlanFields key={identity} {...props} identity={identity} />;
|
||||
}
|
||||
function AiPlanFields({
|
||||
plan,
|
||||
domains,
|
||||
scopes,
|
||||
version,
|
||||
ready,
|
||||
identity,
|
||||
}: {
|
||||
identity: string;
|
||||
plan: AiPlan;
|
||||
domains: Record<string, string>;
|
||||
scopes: Record<string, string>;
|
||||
version: number;
|
||||
ready: boolean;
|
||||
}) {
|
||||
const form = useForm({
|
||||
const initial = {
|
||||
version,
|
||||
provider: plan.provider,
|
||||
model: plan.model,
|
||||
@@ -38,7 +51,16 @@ export function AiPlanSettings({
|
||||
max_input_bytes: plan.max_input_bytes,
|
||||
max_output_tokens: plan.max_output_tokens,
|
||||
reason: '',
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty);
|
||||
const clearPreparation = () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
router.remember(initial, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
};
|
||||
function choices(
|
||||
field: 'domains' | 'data_scopes',
|
||||
labels: Record<string, string>,
|
||||
@@ -76,10 +98,13 @@ export function AiPlanSettings({
|
||||
<p>Instalação da configuração pendente.</p>
|
||||
) : (
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="space-y-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
form.post('/administracao/parametrizacao/ai_plan', {
|
||||
onSuccess: clearPreparation,
|
||||
preserveScroll: true,
|
||||
});
|
||||
}}
|
||||
|
||||
@@ -1,21 +1,50 @@
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { useBudgetPreparationIdentity } from '@/hooks/use-budget-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { FormErrors, controlClass } from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
|
||||
export function ReinforcementProposal({ budgetId }: { budgetId: number }) {
|
||||
const form = useForm({ reference: '', amount: '', reason: '' });
|
||||
const identity = `${useBudgetPreparationIdentity()}:reinforcement:${budgetId}`;
|
||||
return (
|
||||
<ProposalFields
|
||||
key={identity}
|
||||
budgetId={budgetId}
|
||||
identity={identity}
|
||||
/>
|
||||
);
|
||||
}
|
||||
function ProposalFields({
|
||||
budgetId,
|
||||
identity,
|
||||
}: {
|
||||
budgetId: number;
|
||||
identity: string;
|
||||
}) {
|
||||
const initial = { reference: '', amount: '', reason: '' };
|
||||
const form = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty);
|
||||
return (
|
||||
<details className="mt-4 rounded-lg border p-4">
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
Propor reforço desta dotação
|
||||
</summary>
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="mt-4 grid gap-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post(`/orcamentos/${budgetId}/reforcos`, {
|
||||
onSuccess: () => form.reset(),
|
||||
onSuccess: () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
router.remember(initial, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -61,13 +90,29 @@ export function ReinforcementProposal({ budgetId }: { budgetId: number }) {
|
||||
);
|
||||
}
|
||||
export function ReinforcementReview({ id }: { id: number }) {
|
||||
const form = useForm({ decision: 'approved', reason: '' });
|
||||
const identity = `${useBudgetPreparationIdentity()}:reinforcement-review:${id}`;
|
||||
return <ReviewFields key={identity} id={id} identity={identity} />;
|
||||
}
|
||||
function ReviewFields({ id, identity }: { id: number; identity: string }) {
|
||||
const initial = { decision: 'approved', reason: '' };
|
||||
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-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post(`/reforcos/${id}/decidir`);
|
||||
form.post(`/reforcos/${id}/decidir`, {
|
||||
onSuccess: () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
router.remember(initial, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { useProcurementPreparationIdentity } from '@/hooks/use-procurement-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { FormErrors, Panel, controlClass } from '@/components/procurement';
|
||||
|
||||
@@ -89,16 +92,28 @@ function Fields({
|
||||
);
|
||||
}
|
||||
|
||||
export function CompanyDetailsSettings({
|
||||
export function CompanyDetailsSettings(
|
||||
props: Omit<Parameters<typeof CompanyDetailsFields>[0], 'identity'>,
|
||||
) {
|
||||
const identity = useProcurementPreparationIdentity(
|
||||
`company-details:${props.version}:${props.ready}`,
|
||||
);
|
||||
return (
|
||||
<CompanyDetailsFields key={identity} {...props} identity={identity} />
|
||||
);
|
||||
}
|
||||
function CompanyDetailsFields({
|
||||
details,
|
||||
ready,
|
||||
version,
|
||||
identity,
|
||||
}: {
|
||||
identity: string;
|
||||
details: CompanyDetails | null;
|
||||
ready: boolean;
|
||||
version: number;
|
||||
}) {
|
||||
const form = useForm({
|
||||
const initial = {
|
||||
...(Object.fromEntries(
|
||||
Object.keys(identityFields).map((key) => [
|
||||
key,
|
||||
@@ -109,7 +124,16 @@ export function CompanyDetailsSettings({
|
||||
establishments: details?.establishments ?? [],
|
||||
version,
|
||||
reason: '',
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty);
|
||||
const clearPreparation = () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
router.remember(initial, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
};
|
||||
return (
|
||||
<Panel
|
||||
title="Dados da empresa"
|
||||
@@ -122,13 +146,18 @@ export function CompanyDetailsSettings({
|
||||
</p>
|
||||
) : (
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="space-y-6"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.transform((values) => ({ ...values, version }));
|
||||
form.post(
|
||||
'/administracao/parametrizacao/company_details',
|
||||
{ preserveScroll: true },
|
||||
{
|
||||
preserveScroll: true,
|
||||
onSuccess: clearPreparation,
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { useProcurementPreparationIdentity } from '@/hooks/use-procurement-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { Panel, FormErrors, controlClass } from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
@@ -9,21 +12,40 @@ export type IntelligencePolicy = {
|
||||
people_brief: boolean;
|
||||
};
|
||||
|
||||
export function IntelligenceSettings({
|
||||
export function IntelligenceSettings(
|
||||
props: Omit<Parameters<typeof IntelligenceFields>[0], 'identity'>,
|
||||
) {
|
||||
const identity = useProcurementPreparationIdentity(
|
||||
`intelligence:${props.version}:${props.ready}:${props.policy.revision}`,
|
||||
);
|
||||
return <IntelligenceFields key={identity} {...props} identity={identity} />;
|
||||
}
|
||||
function IntelligenceFields({
|
||||
policy,
|
||||
version,
|
||||
ready,
|
||||
identity,
|
||||
}: {
|
||||
identity: string;
|
||||
policy: IntelligencePolicy;
|
||||
version: number;
|
||||
ready: boolean;
|
||||
}) {
|
||||
const form = useForm({
|
||||
const initial = {
|
||||
version,
|
||||
procurement_brief: policy.procurement_brief,
|
||||
people_brief: policy.people_brief,
|
||||
reason: '',
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty);
|
||||
const clearPreparation = () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
router.remember(initial, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
};
|
||||
return (
|
||||
<Panel title="Inteligência e sínteses com fontes">
|
||||
<div className="space-y-4 text-sm">
|
||||
@@ -44,12 +66,17 @@ export function IntelligenceSettings({
|
||||
</p>
|
||||
) : (
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="space-y-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
form.post(
|
||||
'/administracao/parametrizacao/intelligence',
|
||||
{ preserveScroll: true },
|
||||
{
|
||||
onSuccess: clearPreparation,
|
||||
preserveScroll: true,
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useState } from 'react';
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { router, useForm, useRemember } from '@inertiajs/react';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { useInventoryPreparationIdentity } from '@/hooks/use-inventory-preparation-identity';
|
||||
import { FormErrors, controlClass } from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
@@ -12,8 +14,16 @@ type Props = {
|
||||
data?: Record<string, string | number | boolean | null>;
|
||||
};
|
||||
|
||||
function Confirm({ props, choice }: { props: Props; choice: Choice }) {
|
||||
const form = useForm({
|
||||
function Confirm({
|
||||
props,
|
||||
choice,
|
||||
identity,
|
||||
}: {
|
||||
props: Props;
|
||||
choice: Choice;
|
||||
identity: string;
|
||||
}) {
|
||||
const initial = {
|
||||
operation_key: crypto.randomUUID(),
|
||||
record_key: props.record.record_key,
|
||||
version: props.record.version,
|
||||
@@ -25,13 +35,29 @@ function Confirm({ props, choice }: { props: Props; choice: Choice }) {
|
||||
? { event_on: props.today ?? '', evidence: '' }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
};
|
||||
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-3 grid gap-3 md:grid-cols-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post(props.route);
|
||||
form.post(props.route, {
|
||||
onSuccess: () => {
|
||||
const next = {
|
||||
...initial,
|
||||
operation_key: crypto.randomUUID(),
|
||||
};
|
||||
form.setData(next);
|
||||
form.clearErrors();
|
||||
router.remember(next, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
@@ -88,10 +114,23 @@ function Confirm({ props, choice }: { props: Props; choice: Choice }) {
|
||||
}
|
||||
|
||||
export function InventoryEventActions(props: Props) {
|
||||
const [selected, setSelected] = useState(
|
||||
props.choices.length === 1 ? props.choices[0].value : '',
|
||||
const data = JSON.stringify(
|
||||
Object.entries(props.data ?? {}).sort(([a], [b]) => a.localeCompare(b)),
|
||||
);
|
||||
const identity = useInventoryPreparationIdentity(
|
||||
`${props.route}:${props.record.record_key}:${props.record.version}:${props.choices
|
||||
.map((choice) => choice.value)
|
||||
.sort()
|
||||
.join(',')}:${data}`,
|
||||
);
|
||||
if (props.choices.length === 0) return null;
|
||||
return <EventFields key={identity} props={props} identity={identity} />;
|
||||
}
|
||||
function EventFields({ props, identity }: { props: Props; identity: string }) {
|
||||
const [selected, setSelected] = useRemember(
|
||||
props.choices.length === 1 ? props.choices[0].value : '',
|
||||
`${identity}:action`,
|
||||
);
|
||||
const choice = props.choices.find((option) => option.value === selected);
|
||||
return (
|
||||
<details className="mt-4">
|
||||
@@ -118,7 +157,12 @@ export function InventoryEventActions(props: Props) {
|
||||
</label>
|
||||
)}
|
||||
{choice && (
|
||||
<Confirm key={choice.value} props={props} choice={choice} />
|
||||
<Confirm
|
||||
key={choice.value}
|
||||
props={props}
|
||||
choice={choice}
|
||||
identity={`${identity}:${choice.value}`}
|
||||
/>
|
||||
)}
|
||||
</details>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { Link, router, useForm } from '@inertiajs/react';
|
||||
import { useProcurementPreparationIdentity } from '@/hooks/use-procurement-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { Panel, FormErrors, controlClass } from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
@@ -8,18 +11,29 @@ export type OrderCancellationState = {
|
||||
canRequest: boolean;
|
||||
};
|
||||
|
||||
export default function OrderCancellationRequest({
|
||||
type Props = { orderId: number; state: OrderCancellationState };
|
||||
export default function OrderCancellationRequest(props: Props) {
|
||||
const identity = useProcurementPreparationIdentity(
|
||||
`order-cancellation:${props.orderId}:${props.state.enabled}:${props.state.state}:${props.state.canRequest}`,
|
||||
);
|
||||
return <CancellationFields key={identity} {...props} identity={identity} />;
|
||||
}
|
||||
function CancellationFields({
|
||||
orderId,
|
||||
state,
|
||||
}: {
|
||||
orderId: number;
|
||||
state: OrderCancellationState;
|
||||
}) {
|
||||
const form = useForm({
|
||||
identity,
|
||||
}: Props & { identity: string }) {
|
||||
const initial = {
|
||||
operation_key: crypto.randomUUID(),
|
||||
reason: '',
|
||||
evidence: '',
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(
|
||||
dirty,
|
||||
state.enabled && state.canRequest && state.state === 'issued',
|
||||
);
|
||||
if (!state.enabled && state.state === 'issued') return null;
|
||||
return (
|
||||
<Panel title="Estado operacional e cancelamento">
|
||||
@@ -42,10 +56,23 @@ export default function OrderCancellationRequest({
|
||||
<details className="mt-4 rounded border p-3">
|
||||
<summary>Pedir cancelamento integral</summary>
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="mt-4 space-y-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
form.post(`/ordens/${orderId}/cancelamento`);
|
||||
form.post(`/ordens/${orderId}/cancelamento`, {
|
||||
onSuccess: () => {
|
||||
const next = {
|
||||
...initial,
|
||||
operation_key: crypto.randomUUID(),
|
||||
};
|
||||
form.setData(next);
|
||||
form.clearErrors();
|
||||
router.remember(next, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
|
||||
@@ -5,6 +5,7 @@ export type DeliveryInsights = {
|
||||
coverage: Record<string, number>;
|
||||
pending_lines: number;
|
||||
unknown_lines: number;
|
||||
unverified_receipt_lines: number;
|
||||
records: {
|
||||
data: {
|
||||
id: number;
|
||||
@@ -12,6 +13,7 @@ export type DeliveryInsights = {
|
||||
state: string;
|
||||
pending_lines: number;
|
||||
unknown_lines: number;
|
||||
unverified_receipt_lines: number;
|
||||
late_days: number | null;
|
||||
quality_pending: boolean;
|
||||
href: string;
|
||||
@@ -92,6 +94,13 @@ export function ProcurementDeliveryInsights({
|
||||
determinar. Não são presumidas datas a partir da necessidade do
|
||||
requisitante.
|
||||
</p>
|
||||
{data.unverified_receipt_lines > 0 && (
|
||||
<p className="mt-2 text-sm">
|
||||
{data.unverified_receipt_lines} linha(s) com datas de
|
||||
recepção ou quantidades por conferir. Abra a ordem para
|
||||
verificar os documentos antes de concluir o atraso.
|
||||
</p>
|
||||
)}
|
||||
{data.records.data.length === 0 && (
|
||||
<p className="mt-3">Sem ordens nesta selecção.</p>
|
||||
)}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useId, type ReactNode } from 'react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { openJourneyHelp } from '@/components/journey-help';
|
||||
import { recoveryHints } from '@/lib/journey-help';
|
||||
import { focusFormError } from '@/lib/form-error-focus';
|
||||
import { date, money, statusLabels } from '@/types/procurement';
|
||||
import type { Requisition } from '@/types/procurement';
|
||||
|
||||
@@ -228,7 +229,13 @@ export function RequisitionTable({ rows }: { rows: Requisition[] }) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function FormErrors({ errors }: { errors: Record<string, string> }) {
|
||||
export function FormErrors({
|
||||
errors,
|
||||
targets = {},
|
||||
}: {
|
||||
errors: Record<string, string>;
|
||||
targets?: Record<string, string>;
|
||||
}) {
|
||||
if (!Object.keys(errors).length) return null;
|
||||
const hints = recoveryHints(Object.keys(errors));
|
||||
return (
|
||||
@@ -239,7 +246,22 @@ export function FormErrors({ errors }: { errors: Record<string, string> }) {
|
||||
<p className="mb-1 font-medium">Verifique os dados:</p>
|
||||
<ul className="list-inside list-disc">
|
||||
{Object.entries(errors).map(([key, value]) => (
|
||||
<li key={key}>{value}</li>
|
||||
<li key={key}>
|
||||
{targets[key] ? (
|
||||
<a
|
||||
className="underline focus-visible:ring-2 focus-visible:ring-ring"
|
||||
href={`#${targets[key]}`}
|
||||
onClick={(event) => {
|
||||
if (focusFormError(targets[key]))
|
||||
event.preventDefault();
|
||||
}}
|
||||
>
|
||||
{value}
|
||||
</a>
|
||||
) : (
|
||||
value
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{hints.length > 0 && (
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { router, useForm, usePage } from '@inertiajs/react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { FormErrors, controlClass } from '@/components/procurement';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
|
||||
export function QuotationEvaluationForm({
|
||||
requisitionId,
|
||||
quotationId,
|
||||
}: {
|
||||
requisitionId: number;
|
||||
quotationId: number;
|
||||
}) {
|
||||
const actor = usePage().props.auth?.user;
|
||||
const historyKey = `quotation-evaluation:${actor?.tenant_id}:${actor?.id}:${requisitionId}:${quotationId}`;
|
||||
const initial = {
|
||||
quality: '5',
|
||||
history: '5',
|
||||
payment: '5',
|
||||
comment: '',
|
||||
no_conflict: false,
|
||||
};
|
||||
const evaluation = useForm(historyKey, initial);
|
||||
const ref = usePreparationDirty(evaluation.isDirty);
|
||||
return (
|
||||
<form
|
||||
ref={ref}
|
||||
className="mt-5 space-y-4 border-t pt-5"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
evaluation.post(`/cotacoes/${quotationId}/avaliar`, {
|
||||
onSuccess: () => {
|
||||
evaluation.reset();
|
||||
router.remember(initial, `${historyKey}:data`);
|
||||
router.remember({}, `${historyKey}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={evaluation.errors} />
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
{(
|
||||
[
|
||||
['quality', 'Qualidade técnica'],
|
||||
['history', 'Histórico (5 para novo)'],
|
||||
['payment', 'Condições de pagamento'],
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<div className="space-y-2" key={key}>
|
||||
<Label htmlFor={`evaluation-${quotationId}-${key}`}>
|
||||
{label} · 0 a 10
|
||||
</Label>
|
||||
<Input
|
||||
id={`evaluation-${quotationId}-${key}`}
|
||||
type="number"
|
||||
min="0"
|
||||
max="10"
|
||||
step="0.01"
|
||||
required
|
||||
value={evaluation.data[key]}
|
||||
onChange={(event) =>
|
||||
evaluation.setData(key, event.target.value)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<label className="grid gap-2 text-sm">
|
||||
Fundamento da avaliação
|
||||
<textarea
|
||||
className={`${controlClass} h-24 py-3`}
|
||||
required
|
||||
minLength={10}
|
||||
maxLength={2000}
|
||||
value={evaluation.data.comment}
|
||||
onChange={(event) =>
|
||||
evaluation.setData('comment', event.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex items-start gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
required
|
||||
checked={evaluation.data.no_conflict}
|
||||
onChange={(event) =>
|
||||
evaluation.setData('no_conflict', event.target.checked)
|
||||
}
|
||||
/>
|
||||
Declaro não ter conflito de interesses e confirmo a minha
|
||||
avaliação independente.
|
||||
</label>
|
||||
<Button disabled={evaluation.processing}>Registar avaliação</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { useProcurementPreparationIdentity } from '@/hooks/use-procurement-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { FormErrors, Panel, controlClass } from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
@@ -30,22 +33,37 @@ export function ExchangeSummary({ basis }: { basis: ExchangeBasis }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function QuotationExchangePanel({
|
||||
type Props = {
|
||||
requisitionId: number;
|
||||
processVersion?: number;
|
||||
rates: ExchangeBasis[];
|
||||
canRecord: boolean;
|
||||
};
|
||||
export function QuotationExchangePanel(props: Props) {
|
||||
const identity = useProcurementPreparationIdentity(
|
||||
`quotation-exchange:${props.requisitionId}:${props.processVersion ?? 0}:${props.canRecord}`,
|
||||
);
|
||||
return <ExchangeFields key={identity} {...props} identity={identity} />;
|
||||
}
|
||||
function ExchangeFields({
|
||||
requisitionId,
|
||||
rates,
|
||||
canRecord,
|
||||
}: {
|
||||
requisitionId: number;
|
||||
rates: ExchangeBasis[];
|
||||
canRecord: boolean;
|
||||
}) {
|
||||
const form = useForm({
|
||||
identity,
|
||||
}: Props & { identity: string }) {
|
||||
const initial = {
|
||||
operation_id: crypto.randomUUID(),
|
||||
currency: '',
|
||||
rate: '',
|
||||
quoted_on: '',
|
||||
source: '',
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(
|
||||
{ ...initial, operation_id: '' },
|
||||
{ ...form.data, operation_id: '' },
|
||||
);
|
||||
const ref = usePreparationDirty(dirty, canRecord);
|
||||
return (
|
||||
<Panel
|
||||
title="Taxas de câmbio do processo"
|
||||
@@ -68,6 +86,8 @@ export function QuotationExchangePanel({
|
||||
)}
|
||||
{canRecord && (
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="mt-5 space-y-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
@@ -76,11 +96,14 @@ export function QuotationExchangePanel({
|
||||
{
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
form.reset();
|
||||
form.setData(
|
||||
'operation_id',
|
||||
crypto.randomUUID(),
|
||||
);
|
||||
const next = {
|
||||
...initial,
|
||||
operation_id: crypto.randomUUID(),
|
||||
};
|
||||
form.setData(next);
|
||||
form.clearErrors();
|
||||
router.remember(next, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Panel } from '@/components/procurement';
|
||||
import { exactMinorAmount } from '@/components/procurement-payable-insights';
|
||||
|
||||
export type FrozenAccountAssignment = {
|
||||
version: number;
|
||||
snapshot: { line: { description: string } };
|
||||
data: {
|
||||
allocations: {
|
||||
account: { id: number; code: string; label: string };
|
||||
subtotal_minor: string;
|
||||
total_minor: string;
|
||||
}[];
|
||||
};
|
||||
};
|
||||
export default function RequisitionAccountSummary({
|
||||
records,
|
||||
}: {
|
||||
records?: Record<string, FrozenAccountAssignment>;
|
||||
}) {
|
||||
if (!records || Object.keys(records).length === 0) return null;
|
||||
return (
|
||||
<Panel
|
||||
title="Contas da necessidade original"
|
||||
description="Imputação da requisição conservada na emissão. As parcelas originais não representam valores contabilizados nem um rateio desta ordem parcial."
|
||||
>
|
||||
{Object.entries(records).map(([id, row]) => (
|
||||
<section key={id} className="mb-4">
|
||||
<h3 className="font-semibold">
|
||||
{row.snapshot.line.description} · Versão {row.version}
|
||||
</h3>
|
||||
<ul>
|
||||
{row.data.allocations.map((part) => (
|
||||
<li key={part.account.id} className="break-words">
|
||||
{part.account.code} · {part.account.label} ·
|
||||
Base sem IVA:{' '}
|
||||
{exactMinorAmount(part.subtotal_minor, 'MZN')} ·
|
||||
Total:{' '}
|
||||
{exactMinorAmount(part.total_minor, 'MZN')}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
))}
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { useProcurementPreparationIdentity } from '@/hooks/use-procurement-preparation-identity';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { FormErrors, Panel, controlClass } from '@/components/procurement';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
|
||||
type SavedLevel = {
|
||||
name: string;
|
||||
@@ -33,14 +36,24 @@ const newLevel = () => ({
|
||||
cost_center_ids: [] as number[],
|
||||
});
|
||||
|
||||
export function RequisitionApprovalSettings({
|
||||
export function RequisitionApprovalSettings(
|
||||
props: Omit<Parameters<typeof ApprovalFields>[0], 'identity'>,
|
||||
) {
|
||||
const identity = useProcurementPreparationIdentity(
|
||||
`approval-settings:${props.version}:${props.plan?.revision ?? 0}:${props.ready}`,
|
||||
);
|
||||
return <ApprovalFields key={identity} {...props} identity={identity} />;
|
||||
}
|
||||
function ApprovalFields({
|
||||
plan,
|
||||
ready,
|
||||
profiles,
|
||||
costCenters,
|
||||
version,
|
||||
categoryOptions = {},
|
||||
identity,
|
||||
}: {
|
||||
identity: string;
|
||||
plan?: RequisitionApprovalPlan | null;
|
||||
ready: boolean;
|
||||
profiles: Profile[];
|
||||
@@ -48,7 +61,7 @@ export function RequisitionApprovalSettings({
|
||||
version: number;
|
||||
categoryOptions?: Record<string, string>;
|
||||
}) {
|
||||
const form = useForm({
|
||||
const initial = {
|
||||
version,
|
||||
enabled: plan?.enabled ?? false,
|
||||
reason: '',
|
||||
@@ -62,10 +75,13 @@ export function RequisitionApprovalSettings({
|
||||
procurement_categories: level.procurement_categories ?? [],
|
||||
cost_center_ids: level.cost_center_ids,
|
||||
})) ?? [],
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const eligibleProfiles = profiles.filter((profile) =>
|
||||
profile.permissions.includes('requisition_approve'),
|
||||
);
|
||||
const preparationRef = usePreparationDirty(dirty, ready);
|
||||
const change = (
|
||||
index: number,
|
||||
values: Partial<ReturnType<typeof newLevel>>,
|
||||
@@ -88,6 +104,8 @@ export function RequisitionApprovalSettings({
|
||||
</p>
|
||||
) : (
|
||||
<form
|
||||
ref={preparationRef}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="space-y-5"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
@@ -111,7 +129,18 @@ export function RequisitionApprovalSettings({
|
||||
}));
|
||||
form.post(
|
||||
'/administracao/parametrizacao/approval_levels',
|
||||
{ preserveScroll: true },
|
||||
{
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
router.remember(
|
||||
initial,
|
||||
`${identity}:data`,
|
||||
);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
@@ -417,6 +446,37 @@ export function RequisitionApprovalSettings({
|
||||
>
|
||||
Acrescentar nível
|
||||
</Button>
|
||||
{categoryOptions.capital_equipment && (
|
||||
<div className="space-y-2 rounded border p-3">
|
||||
<p className="text-sm">
|
||||
Para a direcção da maquinaria, prepare um nível
|
||||
aplicável a qualquer valor e centro de custo.
|
||||
Escolha os perfis da empresa com competência de
|
||||
aprovação e confirme a ordem das etapas antes de
|
||||
guardar o plano.
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={form.data.levels.length >= 5}
|
||||
onClick={() =>
|
||||
form.setData('levels', [
|
||||
...form.data.levels,
|
||||
{
|
||||
...newLevel(),
|
||||
name: 'Direcção para maquinaria',
|
||||
scope: 'company',
|
||||
procurement_categories: [
|
||||
'capital_equipment',
|
||||
],
|
||||
},
|
||||
])
|
||||
}
|
||||
>
|
||||
Preparar nível de direcção para maquinaria
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<label
|
||||
className="grid gap-2 text-sm"
|
||||
htmlFor="approval-plan-reason"
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
import { useState } from 'react';
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { Send } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
import { exactMinorAmount } from '@/components/procurement-payable-insights';
|
||||
import { roleLabels } from '@/types/procurement';
|
||||
import { FormErrors } from '@/components/procurement';
|
||||
|
||||
export type SubmissionPreview =
|
||||
| {
|
||||
state: 'planned';
|
||||
process_version: number | null;
|
||||
subtotal_minor: string;
|
||||
total_minor: string;
|
||||
approval_amount_minor: string;
|
||||
includes_tax: boolean;
|
||||
provisional_rules: boolean;
|
||||
import_basis: boolean;
|
||||
steps: { role: string; label: string | null }[];
|
||||
}
|
||||
| { state: 'unavailable' | 'incomplete'; message: string };
|
||||
|
||||
export function SubmissionPreviewDetails({
|
||||
number,
|
||||
preview,
|
||||
}: {
|
||||
number: string;
|
||||
preview: SubmissionPreview | null;
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-4 text-sm">
|
||||
<p className="font-medium">{number}</p>
|
||||
{preview?.state === 'planned' ? (
|
||||
<>
|
||||
<dl className="grid gap-2">
|
||||
<div>
|
||||
<dt>Total do pedido com IVA</dt>
|
||||
<dd className="font-semibold">
|
||||
{exactMinorAmount(preview.total_minor, 'MZN')}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>
|
||||
Base prevista para aprovação{' '}
|
||||
{preview.includes_tax ? 'com IVA' : 'sem IVA'}
|
||||
</dt>
|
||||
<dd>
|
||||
{exactMinorAmount(
|
||||
preview.approval_amount_minor,
|
||||
'MZN',
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
{preview.import_basis && (
|
||||
<p>
|
||||
A base de aprovação inclui a estimativa de
|
||||
importação preservada no pedido.
|
||||
</p>
|
||||
)}
|
||||
{preview.provisional_rules && (
|
||||
<p>
|
||||
As regras da empresa estão assinaladas como
|
||||
provisórias.
|
||||
</p>
|
||||
)}
|
||||
<div>
|
||||
<p className="font-medium">Percurso previsto</p>
|
||||
<ol className="list-inside list-decimal">
|
||||
{preview.steps?.map((step) => (
|
||||
<li key={step.role}>
|
||||
{step.label ||
|
||||
roleLabels[step.role] ||
|
||||
'Perfil definido pela empresa'}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<p role="status">
|
||||
{preview?.message ||
|
||||
'O percurso não está disponível nesta apresentação. O servidor verificará os requisitos ao submeter.'}
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Ao confirmar, envia este pedido para aprovação. O servidor volta
|
||||
a verificar os dados, a versão, os acessos e o orçamento; esta
|
||||
conferência não cria reservas nem aprovações.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Parent keys this component by request/version, so a new cycle cannot reuse an old command. */
|
||||
export function RequisitionSubmissionAction({
|
||||
id,
|
||||
number,
|
||||
version,
|
||||
ready,
|
||||
preview,
|
||||
}: {
|
||||
id: number;
|
||||
number: string;
|
||||
version: number | null;
|
||||
ready: boolean;
|
||||
preview: SubmissionPreview | null;
|
||||
}) {
|
||||
const form = useForm({
|
||||
operation_key: ready ? crypto.randomUUID() : null,
|
||||
process_version: version,
|
||||
});
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<FormErrors errors={form.errors} />
|
||||
<RequisitionSubmissionConfirmation
|
||||
number={number}
|
||||
preview={preview}
|
||||
processing={form.processing}
|
||||
errors={Object.values(form.errors)}
|
||||
onConfirm={(close) =>
|
||||
form.post(`/requisicoes/${id}/submeter`, {
|
||||
onSuccess: close,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function RequisitionSubmissionConfirmation({
|
||||
number,
|
||||
preview,
|
||||
processing,
|
||||
errors,
|
||||
onConfirm,
|
||||
}: {
|
||||
number: string;
|
||||
preview: SubmissionPreview | null;
|
||||
processing: boolean;
|
||||
errors: string[];
|
||||
onConfirm: (close: () => void) => void;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button disabled={processing}>
|
||||
<Send className="size-4" />
|
||||
Submeter para aprovação
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-h-[90dvh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Conferir submissão</DialogTitle>
|
||||
<DialogDescription>
|
||||
Reveja o total e o percurso previsto antes de confirmar.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<SubmissionPreviewDetails number={number} preview={preview} />
|
||||
{errors.length > 0 && (
|
||||
<ul
|
||||
role="alert"
|
||||
className="space-y-1 text-sm text-destructive"
|
||||
>
|
||||
{errors.map((error, index) => (
|
||||
<li key={index}>{error}</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setOpen(false)}>
|
||||
Voltar ao pedido
|
||||
</Button>
|
||||
<Button
|
||||
disabled={
|
||||
processing ||
|
||||
(preview !== null && preview.state !== 'planned')
|
||||
}
|
||||
onClick={() => onConfirm(() => setOpen(false))}
|
||||
>
|
||||
{processing ? 'A submeter…' : 'Confirmar e submeter'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { useRef } from 'react';
|
||||
import { useProcurementPreparationIdentity } from '@/hooks/use-procurement-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { Link, router, useForm, useRemember } from '@inertiajs/react';
|
||||
import { Panel, controlClass } from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
@@ -139,32 +141,69 @@ function PlanFields({
|
||||
);
|
||||
}
|
||||
function MeasureCard({
|
||||
scope,
|
||||
...props
|
||||
}: Omit<Parameters<typeof MeasureFields>[0], 'identity'> & { scope: string }) {
|
||||
const m = props.measure;
|
||||
const identity = `${scope}:record:${m.id}:${m.version}:${m.status}:${m.canPlan}:${m.canExecute}:${m.canReview}`;
|
||||
return <MeasureFields key={identity} {...props} identity={identity} />;
|
||||
}
|
||||
function MeasureFields({
|
||||
measure: m,
|
||||
base,
|
||||
people,
|
||||
names,
|
||||
today,
|
||||
identity,
|
||||
}: {
|
||||
identity: string;
|
||||
measure: Measure;
|
||||
base: string;
|
||||
people: Person[];
|
||||
names: Record<number, string>;
|
||||
today: string;
|
||||
}) {
|
||||
const plan = useForm({
|
||||
const initialPlan = {
|
||||
version: m.version,
|
||||
title: m.title,
|
||||
description: m.description,
|
||||
responsible_id: String(m.responsible_id),
|
||||
due_on: m.due_on,
|
||||
reason: '',
|
||||
});
|
||||
const progress = useForm({
|
||||
};
|
||||
const plan = useForm(`${identity}:plan`, initialPlan);
|
||||
const initialProgress = {
|
||||
version: m.version,
|
||||
result: m.result ?? '',
|
||||
evidence: m.evidence ?? '',
|
||||
});
|
||||
const decision = useForm({ version: m.version, reason: '' });
|
||||
};
|
||||
const progress = useForm(`${identity}:progress`, initialProgress);
|
||||
const initialDecision = { version: m.version, reason: '' };
|
||||
const decision = useForm(`${identity}:decision`, initialDecision);
|
||||
const planDirty = hasPreparationChanges(initialPlan, plan.data);
|
||||
const planRef = usePreparationDirty(planDirty, m.canPlan);
|
||||
const progressDirty = hasPreparationChanges(initialProgress, progress.data);
|
||||
const progressRef = usePreparationDirty(progressDirty, m.canExecute);
|
||||
const reviewDirty = hasPreparationChanges(initialDecision, decision.data);
|
||||
const reviewRef = usePreparationDirty(reviewDirty, m.canReview);
|
||||
const clearPlan = () => {
|
||||
plan.setData(initialPlan);
|
||||
plan.clearErrors();
|
||||
router.remember(initialPlan, `${identity}:plan:data`);
|
||||
router.remember({}, `${identity}:plan:errors`);
|
||||
};
|
||||
const clearProgress = () => {
|
||||
progress.setData(initialProgress);
|
||||
progress.clearErrors();
|
||||
router.remember(initialProgress, `${identity}:progress:data`);
|
||||
router.remember({}, `${identity}:progress:errors`);
|
||||
};
|
||||
const clearDecision = () => {
|
||||
decision.setData(initialDecision);
|
||||
decision.clearErrors();
|
||||
router.remember(initialDecision, `${identity}:decision:data`);
|
||||
router.remember({}, `${identity}:decision:errors`);
|
||||
};
|
||||
const url = `${base}/${m.id}`;
|
||||
const overdue = m.status !== 'closed' && m.due_on < today;
|
||||
return (
|
||||
@@ -217,12 +256,15 @@ function MeasureCard({
|
||||
Alterar plano, responsável ou prazo
|
||||
</summary>
|
||||
<form
|
||||
ref={planRef}
|
||||
data-preparation-dirty={planDirty ? 'true' : 'false'}
|
||||
className="mt-4 space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
plan.post(url + '/plan', {
|
||||
preserveState: 'errors',
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
onSuccess: clearPlan,
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -253,12 +295,15 @@ function MeasureCard({
|
||||
)}
|
||||
{m.canExecute && (
|
||||
<form
|
||||
ref={progressRef}
|
||||
data-preparation-dirty={progressDirty ? 'true' : 'false'}
|
||||
className="space-y-4 print:hidden"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
progress.post(url + '/progress', {
|
||||
preserveState: 'errors',
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
onSuccess: clearProgress,
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -301,8 +346,9 @@ function MeasureCard({
|
||||
}
|
||||
onClick={() =>
|
||||
progress.post(url + '/submit', {
|
||||
preserveState: 'errors',
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
onSuccess: clearProgress,
|
||||
})
|
||||
}
|
||||
>
|
||||
@@ -312,7 +358,12 @@ function MeasureCard({
|
||||
</form>
|
||||
)}
|
||||
{m.canReview && (
|
||||
<div className="space-y-3 print:hidden">
|
||||
<form
|
||||
ref={reviewRef}
|
||||
data-preparation-dirty={reviewDirty ? 'true' : 'false'}
|
||||
onSubmit={(event) => event.preventDefault()}
|
||||
className="space-y-3 print:hidden"
|
||||
>
|
||||
<Errors errors={decision.errors} />
|
||||
<label className="block space-y-1">
|
||||
Fundamentação da conferência
|
||||
@@ -328,20 +379,23 @@ function MeasureCard({
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button
|
||||
type="button"
|
||||
disabled={
|
||||
decision.processing ||
|
||||
decision.data.reason.trim().length < 10
|
||||
}
|
||||
onClick={() =>
|
||||
decision.post(url + '/close', {
|
||||
preserveState: 'errors',
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
onSuccess: clearDecision,
|
||||
})
|
||||
}
|
||||
>
|
||||
Confirmar encerramento
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={
|
||||
decision.processing ||
|
||||
@@ -349,34 +403,63 @@ function MeasureCard({
|
||||
}
|
||||
onClick={() =>
|
||||
decision.post(url + '/return', {
|
||||
preserveState: 'errors',
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
onSuccess: clearDecision,
|
||||
})
|
||||
}
|
||||
>
|
||||
Devolver para correcção
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
export default function SupplierImprovements({
|
||||
export default function SupplierImprovements(
|
||||
props: Omit<Parameters<typeof ImprovementContent>[0], 'identity'>,
|
||||
) {
|
||||
const identity = useProcurementPreparationIdentity(
|
||||
`supplier-improvements:${props.evaluationId}:${props.data.ready}:${props.data.canCreate}:${props.reportOnly}`,
|
||||
);
|
||||
return <ImprovementContent key={identity} {...props} identity={identity} />;
|
||||
}
|
||||
function ImprovementContent({
|
||||
data,
|
||||
evaluationId,
|
||||
names,
|
||||
reportOnly,
|
||||
generatedAt,
|
||||
identity,
|
||||
}: {
|
||||
identity: string;
|
||||
data: ImprovementData;
|
||||
evaluationId: number;
|
||||
names: Record<number, string>;
|
||||
reportOnly: boolean;
|
||||
generatedAt: string;
|
||||
}) {
|
||||
const create = useForm(freshPlan);
|
||||
const operation = useRef<string | null>(null);
|
||||
const initialCreate = freshPlan;
|
||||
const create = useForm(`${identity}:create`, initialCreate);
|
||||
const [operation, setOperation] = useRemember(
|
||||
crypto.randomUUID(),
|
||||
`${identity}:operation`,
|
||||
);
|
||||
const createDirty = hasPreparationChanges(initialCreate, create.data);
|
||||
const createRef = usePreparationDirty(
|
||||
createDirty,
|
||||
data.canCreate && !reportOnly,
|
||||
);
|
||||
const clearCreate = () => {
|
||||
create.setData(initialCreate);
|
||||
create.clearErrors();
|
||||
router.remember(initialCreate, `${identity}:create:data`);
|
||||
router.remember({}, `${identity}:create:errors`);
|
||||
const nextOperation = crypto.randomUUID();
|
||||
setOperation(nextOperation);
|
||||
router.remember(nextOperation, `${identity}:operation`);
|
||||
};
|
||||
const base = `/fornecedores/avaliacoes/${evaluationId}/medidas`;
|
||||
const overdue = data.records.filter(
|
||||
(m) => m.status !== 'closed' && m.due_on < data.today,
|
||||
@@ -416,6 +499,7 @@ export default function SupplierImprovements({
|
||||
)}
|
||||
{data.records.map((m) => (
|
||||
<MeasureCard
|
||||
scope={identity}
|
||||
key={`${m.id}-${m.version}`}
|
||||
measure={m}
|
||||
base={base}
|
||||
@@ -430,18 +514,21 @@ export default function SupplierImprovements({
|
||||
Adicionar medida de melhoria
|
||||
</summary>
|
||||
<form
|
||||
ref={createRef}
|
||||
data-preparation-dirty={
|
||||
createDirty ? 'true' : 'false'
|
||||
}
|
||||
className="mt-4 space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
operation.current ??=
|
||||
crypto.randomUUID();
|
||||
create.transform((values) => ({
|
||||
...values,
|
||||
operation_key: operation.current,
|
||||
operation_key: operation,
|
||||
}));
|
||||
create.post(base, {
|
||||
preserveState: 'errors',
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
onSuccess: clearCreate,
|
||||
});
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { useRef } from 'react';
|
||||
import { useProcurementPreparationIdentity } from '@/hooks/use-procurement-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { Link, router, useForm, useRemember } from '@inertiajs/react';
|
||||
import { Panel, controlClass } from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
@@ -131,26 +133,52 @@ function Fields({
|
||||
);
|
||||
}
|
||||
function ResponseCard({
|
||||
scope,
|
||||
...props
|
||||
}: Omit<Parameters<typeof ResponseFields>[0], 'identity'> & { scope: string }) {
|
||||
const r = props.record;
|
||||
const identity = `${scope}:record:${r.id}:${r.version}:${r.status}:${r.canEdit}:${r.canReview}`;
|
||||
return <ResponseFields key={identity} {...props} identity={identity} />;
|
||||
}
|
||||
function ResponseFields({
|
||||
record: r,
|
||||
base,
|
||||
names,
|
||||
identity,
|
||||
}: {
|
||||
identity: string;
|
||||
record: Record;
|
||||
base: string;
|
||||
names: { [key: number]: string };
|
||||
}) {
|
||||
const edit = useForm({ version: r.version, payload: r.payload });
|
||||
const submit = useForm({ version: r.version });
|
||||
const review = useForm({
|
||||
const initialEdit = { version: r.version, payload: r.payload };
|
||||
const edit = useForm(`${identity}:edit`, initialEdit);
|
||||
const submit = useForm(`${identity}:submit`, { version: r.version });
|
||||
const initialReview = {
|
||||
version: r.version,
|
||||
outcome: '',
|
||||
reason: '',
|
||||
follow_up: '',
|
||||
response_reference: '',
|
||||
});
|
||||
};
|
||||
const review = useForm(`${identity}:review`, initialReview);
|
||||
const clearEdit = () => {
|
||||
edit.setData(initialEdit);
|
||||
edit.clearErrors();
|
||||
router.remember(initialEdit, `${identity}:edit:data`);
|
||||
router.remember({}, `${identity}:edit:errors`);
|
||||
};
|
||||
const clearReview = () => {
|
||||
review.setData(initialReview);
|
||||
review.clearErrors();
|
||||
router.remember(initialReview, `${identity}:review:data`);
|
||||
router.remember({}, `${identity}:review:errors`);
|
||||
};
|
||||
const url = `${base}/${r.id}`;
|
||||
const dirty =
|
||||
JSON.stringify(edit.data.payload) !== JSON.stringify(r.payload);
|
||||
const dirty = hasPreparationChanges(initialEdit, edit.data);
|
||||
const editRef = usePreparationDirty(dirty, r.canEdit);
|
||||
const reviewDirty = hasPreparationChanges(initialReview, review.data);
|
||||
const reviewRef = usePreparationDirty(reviewDirty, r.canReview);
|
||||
return (
|
||||
<article
|
||||
id={`contraditorio-${r.id}`}
|
||||
@@ -165,12 +193,15 @@ function ResponseCard({
|
||||
</p>
|
||||
{r.canEdit ? (
|
||||
<form
|
||||
ref={editRef}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="space-y-4 print:hidden"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
edit.post(url + '/save', {
|
||||
preserveState: 'errors',
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
onSuccess: clearEdit,
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -196,7 +227,7 @@ function ResponseCard({
|
||||
}
|
||||
onClick={() =>
|
||||
submit.post(url + '/submit', {
|
||||
preserveState: 'errors',
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
})
|
||||
}
|
||||
@@ -253,7 +284,12 @@ function ResponseCard({
|
||||
</div>
|
||||
)}
|
||||
{r.canReview && (
|
||||
<div className="space-y-4 print:hidden">
|
||||
<form
|
||||
ref={reviewRef}
|
||||
data-preparation-dirty={reviewDirty ? 'true' : 'false'}
|
||||
onSubmit={(event) => event.preventDefault()}
|
||||
className="space-y-4 print:hidden"
|
||||
>
|
||||
<Errors errors={review.errors} />
|
||||
<label className="block space-y-1">
|
||||
Conclusão
|
||||
@@ -312,6 +348,7 @@ function ResponseCard({
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button
|
||||
type="button"
|
||||
disabled={
|
||||
review.processing ||
|
||||
!review.data.outcome ||
|
||||
@@ -320,14 +357,16 @@ function ResponseCard({
|
||||
onClick={() => {
|
||||
review.transform((values) => values);
|
||||
review.post(url + '/decide', {
|
||||
preserveState: 'errors',
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
onSuccess: clearReview,
|
||||
});
|
||||
}}
|
||||
>
|
||||
Registar conclusão da análise
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={
|
||||
review.processing ||
|
||||
@@ -339,34 +378,63 @@ function ResponseCard({
|
||||
reason: values.reason,
|
||||
}));
|
||||
review.post(url + '/return', {
|
||||
preserveState: 'errors',
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
onSuccess: clearReview,
|
||||
});
|
||||
}}
|
||||
>
|
||||
Devolver para completar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
export default function SupplierResponses({
|
||||
export default function SupplierResponses(
|
||||
props: Omit<Parameters<typeof ResponseContent>[0], 'identity'>,
|
||||
) {
|
||||
const identity = useProcurementPreparationIdentity(
|
||||
`supplier-responses:${props.evaluationId}:${props.data.ready}:${props.data.canCreate}:${props.reportOnly}`,
|
||||
);
|
||||
return <ResponseContent key={identity} {...props} identity={identity} />;
|
||||
}
|
||||
function ResponseContent({
|
||||
data,
|
||||
evaluationId,
|
||||
names,
|
||||
reportOnly,
|
||||
generatedAt,
|
||||
identity,
|
||||
}: {
|
||||
identity: string;
|
||||
data: ResponseData;
|
||||
evaluationId: number;
|
||||
names: { [key: number]: string };
|
||||
reportOnly: boolean;
|
||||
generatedAt: string;
|
||||
}) {
|
||||
const create = useForm({ payload: empty });
|
||||
const operation = useRef<string | null>(null);
|
||||
const initialCreate = { payload: empty };
|
||||
const create = useForm(`${identity}:create`, initialCreate);
|
||||
const [operation, setOperation] = useRemember(
|
||||
crypto.randomUUID(),
|
||||
`${identity}:operation`,
|
||||
);
|
||||
const createDirty = hasPreparationChanges(initialCreate, create.data);
|
||||
const createRef = usePreparationDirty(
|
||||
createDirty,
|
||||
data.canCreate && !reportOnly,
|
||||
);
|
||||
const clearCreate = () => {
|
||||
create.setData(initialCreate);
|
||||
create.clearErrors();
|
||||
router.remember(initialCreate, `${identity}:create:data`);
|
||||
router.remember({}, `${identity}:create:errors`);
|
||||
const nextOperation = crypto.randomUUID();
|
||||
setOperation(nextOperation);
|
||||
router.remember(nextOperation, `${identity}:operation`);
|
||||
};
|
||||
const base = `/fornecedores/avaliacoes/${evaluationId}/contraditorios`;
|
||||
return (
|
||||
<Panel title="Contraditório do fornecedor">
|
||||
@@ -392,6 +460,7 @@ export default function SupplierResponses({
|
||||
)}
|
||||
{data.records.map((r) => (
|
||||
<ResponseCard
|
||||
scope={identity}
|
||||
key={`${r.id}-${r.version}`}
|
||||
record={r}
|
||||
base={base}
|
||||
@@ -404,18 +473,21 @@ export default function SupplierResponses({
|
||||
Registar documento recebido
|
||||
</summary>
|
||||
<form
|
||||
ref={createRef}
|
||||
data-preparation-dirty={
|
||||
createDirty ? 'true' : 'false'
|
||||
}
|
||||
className="mt-4 space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
operation.current ??=
|
||||
crypto.randomUUID();
|
||||
create.transform((values) => ({
|
||||
...values,
|
||||
operation_key: operation.current,
|
||||
operation_key: operation,
|
||||
}));
|
||||
create.post(base, {
|
||||
preserveState: 'errors',
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
onSuccess: clearCreate,
|
||||
});
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -2,6 +2,10 @@ import { router, usePage } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { protectDepartures } from '@/lib/unsaved-navigation';
|
||||
import {
|
||||
connectedDirtyForms,
|
||||
markPreparationDirty,
|
||||
} from '@/lib/preparation-forms';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -18,7 +22,7 @@ export function WorkContextChange() {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
useEffect(() => {
|
||||
dirty.current.clear();
|
||||
dirty.current = new Set(connectedDirtyForms(dirty.current));
|
||||
}, [page.url]);
|
||||
useEffect(() => {
|
||||
const formChanged = (event: Event) => {
|
||||
@@ -27,6 +31,7 @@ export function WorkContextChange() {
|
||||
!(event.detail.form instanceof HTMLFormElement)
|
||||
)
|
||||
return;
|
||||
markPreparationDirty(event.detail.form, !!event.detail.dirty);
|
||||
if (event.detail.dirty) dirty.current.add(event.detail.form);
|
||||
else dirty.current.delete(event.detail.form);
|
||||
};
|
||||
@@ -37,13 +42,16 @@ export function WorkContextChange() {
|
||||
input instanceof HTMLTextAreaElement ||
|
||||
input instanceof HTMLSelectElement
|
||||
) {
|
||||
if (input.form) dirty.current.add(input.form);
|
||||
if (input.form) {
|
||||
markPreparationDirty(input.form, true);
|
||||
dirty.current.add(input.form);
|
||||
}
|
||||
}
|
||||
};
|
||||
const offDepartures = protectDepartures(
|
||||
(submittedForm) =>
|
||||
[...dirty.current].some(
|
||||
(form) => form.isConnected && form !== submittedForm,
|
||||
connectedDirtyForms(dirty.current).some(
|
||||
(form) => form !== submittedForm,
|
||||
),
|
||||
(proceed) => {
|
||||
destination.current = proceed;
|
||||
@@ -53,7 +61,11 @@ export function WorkContextChange() {
|
||||
);
|
||||
const saved = (event: Event) => {
|
||||
if (!(event instanceof CustomEvent)) return;
|
||||
if (event.detail.success) dirty.current.delete(event.detail.form);
|
||||
if (event.detail.success) {
|
||||
dirty.current.delete(event.detail.form);
|
||||
if (event.detail.form instanceof HTMLFormElement)
|
||||
markPreparationDirty(event.detail.form, false);
|
||||
}
|
||||
if (!pending.current || event.detail.form !== savingForm.current)
|
||||
return;
|
||||
if (event.detail.success) {
|
||||
@@ -108,9 +120,7 @@ export function WorkContextChange() {
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button
|
||||
onClick={() => {
|
||||
const forms = [...dirty.current].filter(
|
||||
(form) => form.isConnected,
|
||||
);
|
||||
const forms = connectedDirtyForms(dirty.current);
|
||||
if (forms.length !== 1) {
|
||||
setMessage(
|
||||
'Existem alterações em vários formulários. Cancele a mudança e guarde cada formulário antes de continuar.',
|
||||
@@ -141,6 +151,10 @@ export function WorkContextChange() {
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
for (const form of connectedDirtyForms(
|
||||
dirty.current,
|
||||
))
|
||||
markPreparationDirty(form, false);
|
||||
dirty.current.clear();
|
||||
pending.current = false;
|
||||
setOpen(false);
|
||||
|
||||
@@ -1,18 +1,34 @@
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { useProcurementPreparationIdentity } from '@/hooks/use-procurement-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { FormErrors, Panel, controlClass } from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import type { WorkContextState } from '@/types/work-context';
|
||||
|
||||
export function WorkContextSettings({
|
||||
export function WorkContextSettings(
|
||||
props: Omit<Parameters<typeof WorkContextFields>[0], 'identity'>,
|
||||
) {
|
||||
const identity = useProcurementPreparationIdentity(
|
||||
`work-contexts:${props.version}:${[...props.context.purchased].sort().join(',')}`,
|
||||
);
|
||||
return <WorkContextFields key={identity} {...props} identity={identity} />;
|
||||
}
|
||||
function WorkContextFields({
|
||||
context,
|
||||
enabled,
|
||||
version,
|
||||
identity,
|
||||
}: {
|
||||
identity: string;
|
||||
context: WorkContextState;
|
||||
enabled: string[];
|
||||
version: number;
|
||||
}) {
|
||||
const form = useForm({ version, enabled, reason: '', confirm: false });
|
||||
const initial = { version, enabled, reason: '', confirm: false };
|
||||
const form = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty);
|
||||
return (
|
||||
<Panel title="Áreas e opções do produto">
|
||||
<p className="mb-4 text-sm">
|
||||
@@ -29,11 +45,19 @@ export function WorkContextSettings({
|
||||
</p>
|
||||
)}
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post('/administracao/parametrizacao/work_contexts', {
|
||||
preserveState: 'errors',
|
||||
preserveState: true,
|
||||
onSuccess: () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
router.remember(initial, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { usePage } from '@inertiajs/react';
|
||||
import type { WorkContextState } from '@/types/work-context';
|
||||
|
||||
export function useBudgetPreparationIdentity() {
|
||||
const { auth, workContext, organizationAccess } = usePage().props;
|
||||
const context = workContext as WorkContextState | null | undefined;
|
||||
const access = organizationAccess as { permissions?: string[] } | null;
|
||||
const permissions = [...(access?.permissions ?? [])].sort().join(',');
|
||||
return `budgets:${auth.user?.tenant_id}:${auth.user?.id}:${context?.active ?? 'legacy'}:${permissions}`;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { usePage } from '@inertiajs/react';
|
||||
import type { WorkContextState } from '@/types/work-context';
|
||||
|
||||
export function useConflictPreparationIdentity() {
|
||||
const { auth, workContext, organizationAccess } = usePage().props;
|
||||
const context = workContext as WorkContextState | null | undefined;
|
||||
const access = organizationAccess as { permissions?: string[] } | null;
|
||||
return `conflicts:${auth.user?.tenant_id}:${auth.user?.id}:${context?.active ?? 'legacy'}:${[...(access?.permissions ?? [])].sort().join(',')}`;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { usePage } from '@inertiajs/react';
|
||||
import type { WorkContextState } from '@/types/work-context';
|
||||
|
||||
export function useInventoryPreparationIdentity(scope: string) {
|
||||
const { auth, workContext, actorId } = usePage().props;
|
||||
const context = workContext as WorkContextState | null | undefined;
|
||||
const actor = typeof actorId === 'number' ? actorId : auth.user?.id;
|
||||
return `inventory-events:${auth.user?.tenant_id}:${actor}:${context?.active ?? 'legacy'}:${scope}`;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { markPreparationDirty } from '@/lib/preparation-forms';
|
||||
|
||||
/** Publish preparation state to the existing context/departure guard; never save business data. */
|
||||
export function usePreparationDirty(dirty: boolean, visible = true) {
|
||||
const ref = useRef<HTMLFormElement>(null);
|
||||
useEffect(() => {
|
||||
const form = ref.current;
|
||||
if (!form) return;
|
||||
markPreparationDirty(form, visible && dirty);
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('sgc:context-dirty', {
|
||||
detail: { form, dirty: visible && dirty },
|
||||
}),
|
||||
);
|
||||
return () => {
|
||||
markPreparationDirty(form, false);
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('sgc:context-dirty', {
|
||||
detail: { form, dirty: false },
|
||||
}),
|
||||
);
|
||||
};
|
||||
}, [dirty, visible]);
|
||||
return ref;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { usePage } from '@inertiajs/react';
|
||||
import type { WorkContextState } from '@/types/work-context';
|
||||
|
||||
export function useProcurementPreparationIdentity(scope: string) {
|
||||
const { auth, workContext, organizationAccess } = usePage().props;
|
||||
const context = workContext as WorkContextState | null | undefined;
|
||||
const access = organizationAccess as { permissions?: string[] } | null;
|
||||
return `procurement-preparations:${auth?.user?.tenant_id}:${auth?.user?.id}:${context?.active ?? 'legacy'}:${[...(access?.permissions ?? [])].sort().join(',')}:${scope}`;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
export function focusFormError(id: string): boolean {
|
||||
const target = document.getElementById(id);
|
||||
if (!target) return false;
|
||||
let ancestor = target.parentElement;
|
||||
while (ancestor) {
|
||||
if (ancestor.tagName === 'DETAILS') ancestor.setAttribute('open', '');
|
||||
ancestor = ancestor.parentElement;
|
||||
}
|
||||
target.focus();
|
||||
target.scrollIntoView({ block: 'center', behavior: 'auto' });
|
||||
return true;
|
||||
}
|
||||
@@ -37,6 +37,57 @@ function topic(
|
||||
}
|
||||
|
||||
export const journeyHelp: JourneyHelp[] = [
|
||||
topic(
|
||||
'urgent-review-policy',
|
||||
'Designar a revisão posterior das urgências',
|
||||
['organization/urgent-review-policy'],
|
||||
'Designar os perfis da direcção de Compras que devem registar a revisão dos ciclos urgentes concluídos.',
|
||||
[
|
||||
'Confira os perfis existentes da empresa e seleccione os responsáveis.',
|
||||
'Indique o motivo e guarde uma versão da designação.',
|
||||
],
|
||||
[
|
||||
'A designação não concede funções ou acessos. É necessária a função de Compras, atribuição válida e acesso ao pedido.',
|
||||
'A revisão fica disponível depois da decisão final, incluindo rejeição ou expiração; não substitui as aprovações.',
|
||||
],
|
||||
'Se não existirem intervenientes elegíveis, confira os perfis, as atribuições e o contexto de trabalho com os mecanismos administrativos existentes.',
|
||||
'Abra as revisões das urgências para conferir a cobertura.',
|
||||
),
|
||||
topic(
|
||||
'urgent-reviews',
|
||||
'Conferir e registar a revisão posterior das urgências',
|
||||
['requisitions/urgent-reviews', 'requisitions/urgent-review'],
|
||||
'Rever o ciclo urgente concluído e preservar conclusões e correcções por versão.',
|
||||
[
|
||||
'Seleccione um ciclo por rever e confira o desfecho, a necessidade original e as decisões conservadas.',
|
||||
'Registe as conclusões apenas com o perfil designado e função actualmente válidos.',
|
||||
'Confira o histórico; uma correcção cria outra versão.',
|
||||
],
|
||||
[
|
||||
'Um ciclo expirado conserva os seus dados mesmo que o pedido seja novamente preparado ou submetido.',
|
||||
'A revisão não altera a decisão, a reserva, o compromisso, o stock, facturas ou pagamentos.',
|
||||
'Origem indeterminada exige conferência e não é apresentada como revista.',
|
||||
],
|
||||
'Se a origem ou a versão mudar, confira os dados actuais e prepare a versão expressamente. As notas anteriores permanecem preservadas.',
|
||||
'Regresse às tarefas para continuar as intervenções pendentes.',
|
||||
),
|
||||
topic(
|
||||
'requisition-accounts',
|
||||
'Atribuir contas às linhas da requisição',
|
||||
['requisitions/accounts'],
|
||||
'Conservar a imputação explícita da necessidade ao plano de contas comum de Compras.',
|
||||
[
|
||||
'Seleccione a linha e pesquise as contas de movimento por código ou designação.',
|
||||
'Adicione as contas e indique as parcelas sem IVA e totais, sem rateio automático.',
|
||||
'Confira os valores, indique o motivo e guarde a versão.',
|
||||
],
|
||||
[
|
||||
'As parcelas devem coincidir exactamente com os montantes da linha.',
|
||||
'Alterações da linha ou da distribuição exigem nova conferência. A imputação não cria lançamentos ou pagamentos.',
|
||||
],
|
||||
'Se a origem ou a versão mudar, confira a linha e as contas actuais; as versões anteriores permanecem no histórico.',
|
||||
'Regresse à requisição para concluir as restantes verificações antes de submeter.',
|
||||
),
|
||||
topic(
|
||||
'expense-allocation',
|
||||
'Imputar despesa confirmada por categoria',
|
||||
@@ -63,6 +114,7 @@ export const journeyHelp: JourneyHelp[] = [
|
||||
[
|
||||
'Indique os minutos corridos até à expiração de cada nível aplicável.',
|
||||
'Quando necessários, configure lembrete e escalamento antes da expiração; escolha expressamente os perfis destinatários do escalamento.',
|
||||
'Para urgências, pode indicar prazos próprios reduzidos. Conserve os alertas da etapa com valores explícitos; sem essa configuração aplicam-se os prazos gerais.',
|
||||
'Fundamente e guarde a política. Confira a versão actual antes de substituir uma preparação desactualizada.',
|
||||
],
|
||||
[
|
||||
@@ -84,7 +136,7 @@ export const journeyHelp: JourneyHelp[] = [
|
||||
'Se o pedido lhe foi devolvido, reveja o rascunho e submeta novamente quando estiver preparado.',
|
||||
],
|
||||
[
|
||||
'As decisões e os valores anteriores ficam preservados no histórico.',
|
||||
'Nos ciclos anteriores, confira autor, data e fundamento das decisões, documento original e regras preservadas. O valor usado no encaminhamento pode incluir uma base adicional de importação; as aprovações anteriores não substituem as da nova submissão.',
|
||||
'A nova submissão exige novas aprovações e uma nova reserva; não reutiliza aprovações do ciclo anterior.',
|
||||
'Apenas os intervenientes com acesso actual podem consultar ou executar as acções apresentadas.',
|
||||
],
|
||||
@@ -465,6 +517,7 @@ export const journeyHelp: JourneyHelp[] = [
|
||||
'O CSV de processos e o CSV da posição financeira têm conteúdos distintos; escolha a exportação correspondente à conferência pretendida.',
|
||||
'Na despesa, o período refere-se à confirmação dos pagamentos. A tabela de fornecedores tem paginação própria e o CSV inclui todos os grupos autorizados.',
|
||||
'Confira as associações contratuais conservadas na emissão; os montantes são totais de ordens operacionais e não pagamentos.',
|
||||
'Nas entregas, compare as recepções físicas com as datas acordadas conservadas em cada origem. Use os filtros e o CSV próprio para conferir atrasos e informação indeterminada.',
|
||||
],
|
||||
[
|
||||
'Os saldos financeiros são os actuais na data de geração; não são saldos históricos do período filtrado.',
|
||||
@@ -931,6 +984,8 @@ export const journeyHelp: JourneyHelp[] = [
|
||||
],
|
||||
[
|
||||
'Quando a pesquisa financeira estiver disponível para o seu perfil, procure facturas pelo número; os resultados apresentam apenas referência e estado. Os valores e documentos são consultados na própria factura.',
|
||||
'Quando disponíveis no seu acesso, procure acordos e contratos pela referência ou pelo nome do fornecedor preservado. Os resultados usam a versão actual e abrem o registo no módulo de fornecimento; versões anteriores permanecem no respectivo histórico.',
|
||||
'Quando disponíveis, procure requisições internas pela referência RA, destino ou nome do requisitante preservado. O estado acompanha os eventos de autorização, entrega e recepção, sem transformar o pedido interno numa compra.',
|
||||
'A pesquisa não inclui Pessoas, conteúdo dos anexos ou arquivos externos.',
|
||||
'Nenhum resultado significa ausência no âmbito e nos critérios actuais; não comprova eliminação de registos.',
|
||||
],
|
||||
@@ -973,6 +1028,8 @@ export const journeyHelp: JourneyHelp[] = [
|
||||
[
|
||||
'Defina filtros de data, acção ou utilizador.',
|
||||
'Confira o âmbito e a ordem dos eventos.',
|
||||
'Na consulta de eventos, indique a referência exacta da requisição e combine acção, utilizador e período. O CSV conserva esses critérios e inclui todos os resultados, independentemente da página.',
|
||||
'Quando já tem acesso ao processo, a ligação permite conferir o documento e as regras no respectivo histórico. A competência de metadados, por si só, não abre esse conteúdo.',
|
||||
'Exporte apenas a informação disponibilizada ao seu perfil.',
|
||||
],
|
||||
[
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
export function markPreparationDirty(
|
||||
form: HTMLFormElement,
|
||||
dirty: boolean,
|
||||
): void {
|
||||
form.setAttribute('data-preparation-dirty', dirty ? 'true' : 'false');
|
||||
}
|
||||
|
||||
/** Recover restored preparations even when their effect ran before the guard subscribed. */
|
||||
export function connectedDirtyForms(
|
||||
tracked: Iterable<HTMLFormElement>,
|
||||
root: Pick<Document, 'querySelectorAll'> = document,
|
||||
): HTMLFormElement[] {
|
||||
return [
|
||||
...new Set([
|
||||
...tracked,
|
||||
...root.querySelectorAll<HTMLFormElement>(
|
||||
'form[data-preparation-dirty="true"]',
|
||||
),
|
||||
]),
|
||||
].filter(
|
||||
(form) =>
|
||||
form.isConnected &&
|
||||
form.getAttribute('data-preparation-dirty') !== 'false',
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { ReceiptProgress } from '@/types/inventory';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
|
||||
export function receiptPreparationKey(
|
||||
tenant: number | null | undefined,
|
||||
actor: number | undefined,
|
||||
order: number,
|
||||
progress: ReceiptProgress,
|
||||
): string {
|
||||
const source = [...progress.lines]
|
||||
.sort((a, b) => a.id - b.id)
|
||||
.map((line) =>
|
||||
[
|
||||
line.id,
|
||||
line.ordered_milli,
|
||||
line.received_milli,
|
||||
line.accepted_milli,
|
||||
line.rejected_milli,
|
||||
line.delivery_pending_milli,
|
||||
line.acceptance_pending_milli,
|
||||
line.supplier_returned_milli ?? 0,
|
||||
line.effective_accepted_milli ?? line.accepted_milli,
|
||||
].join(':'),
|
||||
)
|
||||
.join('~');
|
||||
return `receipt-preparation:${tenant}:${actor}:${order}:${source}`;
|
||||
}
|
||||
|
||||
export function receiptPreparationChanged(
|
||||
initial: Record<string, unknown>,
|
||||
current: Record<string, unknown>,
|
||||
): boolean {
|
||||
const { idempotency_key: _initialKey, ...original } = initial;
|
||||
const { idempotency_key: _currentKey, ...preparation } = current;
|
||||
return hasPreparationChanges(original, preparation);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
type EstimateLine = { quantity: string; unit_price: string; tax_rate: string };
|
||||
|
||||
function units(value: string, scale: number, maximum: bigint): bigint | null {
|
||||
if (!new RegExp(`^\\d+(?:\\.\\d{1,${scale}})?$`).test(value)) return null;
|
||||
const [whole, fraction = ''] = value.split('.');
|
||||
const digits =
|
||||
`${whole}${fraction.padEnd(scale, '0')}`.replace(/^0+/, '') || '0';
|
||||
if (digits.length > maximum.toString().length) return null;
|
||||
const result = BigInt(digits);
|
||||
return result <= maximum ? result : null;
|
||||
}
|
||||
|
||||
/** Presentation only: the server remains authoritative when saving. */
|
||||
export function requisitionEstimate(lines: EstimateLine[]): string | null {
|
||||
if (lines.length === 0) return null;
|
||||
let total = 0n;
|
||||
for (const line of lines) {
|
||||
const quantity = units(line.quantity, 3, 1000000000n);
|
||||
const price = units(line.unit_price, 2, 10000000000n);
|
||||
const rate = units(line.tax_rate, 2, 10000n);
|
||||
if (
|
||||
quantity === null ||
|
||||
quantity === 0n ||
|
||||
price === null ||
|
||||
price === 0n ||
|
||||
rate === null
|
||||
)
|
||||
return null;
|
||||
const subtotal = (quantity * price + 500n) / 1000n;
|
||||
const tax = (subtotal * rate + 5000n) / 10000n;
|
||||
total += subtotal + tax;
|
||||
}
|
||||
return total.toString();
|
||||
}
|
||||
@@ -10,12 +10,14 @@ import { Button } from '@/components/ui/button';
|
||||
|
||||
type Props = {
|
||||
filters: {
|
||||
request_reference?: string | null;
|
||||
action?: string;
|
||||
actor_id?: number | string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
page?: number;
|
||||
};
|
||||
requestContext?: { number: string; href: string } | null;
|
||||
events: {
|
||||
data: {
|
||||
id: number;
|
||||
@@ -31,8 +33,13 @@ type Props = {
|
||||
};
|
||||
};
|
||||
|
||||
export default function AuditMetadata({ filters, events }: Props) {
|
||||
export default function AuditMetadata({
|
||||
filters,
|
||||
events,
|
||||
requestContext = null,
|
||||
}: Props) {
|
||||
const form = useForm({
|
||||
request_reference: filters.request_reference ?? '',
|
||||
action: filters.action ?? '',
|
||||
actor_id: String(filters.actor_id ?? ''),
|
||||
from: filters.from ?? '',
|
||||
@@ -57,6 +64,17 @@ export default function AuditMetadata({ filters, events }: Props) {
|
||||
description="Metadados registados na empresa. Esta consulta não concede acesso ao conteúdo dos processos."
|
||||
/>
|
||||
<Panel title="Consulta e exportação">
|
||||
{requestContext && (
|
||||
<p className="mb-3 text-sm">
|
||||
<Link
|
||||
href={requestContext.href}
|
||||
className="underline"
|
||||
>
|
||||
Consultar o processo e o histórico de{' '}
|
||||
{requestContext.number}
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm">
|
||||
Os eventos são apresentados pela ordem de registo,
|
||||
incluindo os mais antigos. A exportação inclui todos os
|
||||
@@ -80,6 +98,20 @@ export default function AuditMetadata({ filters, events }: Props) {
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
<label>
|
||||
Referência exacta da requisição
|
||||
<input
|
||||
className={controlClass}
|
||||
maxLength={100}
|
||||
value={form.data.request_reference}
|
||||
onChange={(event) =>
|
||||
form.setData(
|
||||
'request_reference',
|
||||
event.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Acção exacta
|
||||
<input
|
||||
|
||||
@@ -14,6 +14,9 @@ import {
|
||||
} from '@/components/budget-reinforcements';
|
||||
import { InventoryPagination } from '@/components/inventory';
|
||||
import type { Page } from '@/types/inventory';
|
||||
import { useBudgetPreparationIdentity } from '@/hooks/use-budget-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
|
||||
type Budget = {
|
||||
id: number;
|
||||
@@ -32,11 +35,20 @@ type Budget = {
|
||||
approved_total_minor: number;
|
||||
kind: string;
|
||||
};
|
||||
export default function Budgets({
|
||||
export default function Budgets(
|
||||
props: Omit<Parameters<typeof BudgetFields>[0], 'identity'>,
|
||||
) {
|
||||
const identity = useBudgetPreparationIdentity();
|
||||
return <BudgetFields key={identity} {...props} identity={identity} />;
|
||||
}
|
||||
|
||||
function BudgetFields({
|
||||
centers,
|
||||
budgets,
|
||||
reinforcements,
|
||||
identity,
|
||||
}: {
|
||||
identity: string;
|
||||
centers: { id: number; code: string; name: string }[];
|
||||
budgets: Budget[];
|
||||
reinforcements: Page<{
|
||||
@@ -52,14 +64,17 @@ export default function Budgets({
|
||||
}>;
|
||||
}) {
|
||||
const { auth } = usePage().props;
|
||||
const form = useForm({
|
||||
const initial = {
|
||||
cost_center_id: '',
|
||||
year: new Date().getFullYear(),
|
||||
amount: '',
|
||||
reason: '',
|
||||
includes_tax: '',
|
||||
kind: '',
|
||||
});
|
||||
};
|
||||
const form = useForm(`${identity}:allocation`, initial);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty);
|
||||
return (
|
||||
<>
|
||||
<Head title="Orçamentos" />
|
||||
@@ -82,6 +97,8 @@ export default function Budgets({
|
||||
description="Outra pessoa de Administração ou Finanças deve aprovar. A dotação inicial é preservada; reforços têm aprovação própria."
|
||||
>
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="grid gap-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -89,7 +106,20 @@ export default function Budgets({
|
||||
...data,
|
||||
includes_tax: data.includes_tax === '1',
|
||||
}));
|
||||
form.post('/orcamentos');
|
||||
form.post('/orcamentos', {
|
||||
onSuccess: () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
router.remember(
|
||||
initial,
|
||||
`${identity}:allocation:data`,
|
||||
);
|
||||
router.remember(
|
||||
{},
|
||||
`${identity}:allocation:errors`,
|
||||
);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { Head, useForm } from '@inertiajs/react';
|
||||
import { useProcurementPreparationIdentity } from '@/hooks/use-procurement-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { Head, router, useForm } from '@inertiajs/react';
|
||||
import {
|
||||
TableViewport,
|
||||
FormErrors,
|
||||
@@ -27,23 +30,48 @@ type Props = {
|
||||
roles: { value: string; label: string }[];
|
||||
};
|
||||
|
||||
export default function CompanyPage({
|
||||
export default function CompanyPage(props: Props) {
|
||||
const identity = useProcurementPreparationIdentity(
|
||||
`company-team:${props.company.id}`,
|
||||
);
|
||||
return <CompanyFields key={identity} {...props} identity={identity} />;
|
||||
}
|
||||
function CompanyFields({
|
||||
company,
|
||||
departments,
|
||||
costCenters,
|
||||
users,
|
||||
roles,
|
||||
}: Props) {
|
||||
const department = useForm({ name: '' });
|
||||
const center = useForm({ department_id: '', code: '', name: '' });
|
||||
const user = useForm({
|
||||
identity,
|
||||
}: Props & { identity: string }) {
|
||||
const initialDepartment = { name: '' };
|
||||
const department = useForm(`${identity}:department`, initialDepartment);
|
||||
const initialCenter = { department_id: '', code: '', name: '' };
|
||||
const center = useForm(`${identity}:center`, initialCenter);
|
||||
const initialUser = {
|
||||
name: '',
|
||||
email: '',
|
||||
department_id: '',
|
||||
purchasing_role: 'requester',
|
||||
password: '',
|
||||
password_confirmation: '',
|
||||
};
|
||||
const user = useForm(`${identity}:user`, initialUser).dontRemember(
|
||||
'password',
|
||||
'password_confirmation',
|
||||
);
|
||||
const departmentDirty = hasPreparationChanges(
|
||||
initialDepartment,
|
||||
department.data,
|
||||
);
|
||||
const departmentRef = usePreparationDirty(departmentDirty);
|
||||
const centerDirty = hasPreparationChanges(initialCenter, center.data);
|
||||
const centerRef = usePreparationDirty(centerDirty);
|
||||
const userDirty = hasPreparationChanges(initialUser, {
|
||||
...initialUser,
|
||||
...user.data,
|
||||
});
|
||||
const userRef = usePreparationDirty(userDirty);
|
||||
return (
|
||||
<>
|
||||
<Head title="Empresa e equipa" />
|
||||
@@ -69,11 +97,27 @@ export default function CompanyPage({
|
||||
))}
|
||||
</div>
|
||||
<form
|
||||
ref={departmentRef}
|
||||
data-preparation-dirty={
|
||||
departmentDirty ? 'true' : 'false'
|
||||
}
|
||||
className="space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
department.post('/empresa/departamentos', {
|
||||
onSuccess: () => department.reset(),
|
||||
onSuccess: () => {
|
||||
department.setData(initialDepartment);
|
||||
department.clearErrors();
|
||||
|
||||
router.remember(
|
||||
initialDepartment,
|
||||
`${identity}:department:data`,
|
||||
);
|
||||
router.remember(
|
||||
{},
|
||||
`${identity}:department:errors`,
|
||||
);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -115,11 +159,27 @@ export default function CompanyPage({
|
||||
))}
|
||||
</div>
|
||||
<form
|
||||
ref={centerRef}
|
||||
data-preparation-dirty={
|
||||
centerDirty ? 'true' : 'false'
|
||||
}
|
||||
className="space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
center.post('/empresa/centros-de-custo', {
|
||||
onSuccess: () => center.reset(),
|
||||
onSuccess: () => {
|
||||
center.setData(initialCenter);
|
||||
center.clearErrors();
|
||||
|
||||
router.remember(
|
||||
initialCenter,
|
||||
`${identity}:center:data`,
|
||||
);
|
||||
router.remember(
|
||||
{},
|
||||
`${identity}:center:errors`,
|
||||
);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -214,12 +274,30 @@ export default function CompanyPage({
|
||||
</table>
|
||||
</TableViewport>
|
||||
<form
|
||||
ref={userRef}
|
||||
data-preparation-dirty={userDirty ? 'true' : 'false'}
|
||||
className="mt-6 space-y-4 border-t pt-5"
|
||||
autoComplete="off"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
user.post('/empresa/utilizadores', {
|
||||
onSuccess: () => user.reset(),
|
||||
onSuccess: () => {
|
||||
user.setData(initialUser);
|
||||
user.clearErrors();
|
||||
const {
|
||||
password: _password,
|
||||
password_confirmation: _confirmation,
|
||||
...remembered
|
||||
} = initialUser;
|
||||
router.remember(
|
||||
remembered,
|
||||
`${identity}:user:data`,
|
||||
);
|
||||
router.remember(
|
||||
{},
|
||||
`${identity}:user:errors`,
|
||||
);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -270,7 +348,7 @@ export default function CompanyPage({
|
||||
: undefined
|
||||
}
|
||||
required
|
||||
value={user.data[field.key]}
|
||||
value={user.data[field.key] ?? ''}
|
||||
onChange={(e) =>
|
||||
user.setData(
|
||||
field.key,
|
||||
@@ -330,6 +408,10 @@ export default function CompanyPage({
|
||||
etapa as contas são criadas pelo administrador;
|
||||
convites por email ficam para uma próxima etapa.
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
As palavras-passe não são conservadas ao sair deste
|
||||
ecrã.
|
||||
</p>
|
||||
<Button disabled={user.processing}>
|
||||
Criar utilizador
|
||||
</Button>
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { useProcurementPreparationIdentity } from '@/hooks/use-procurement-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
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';
|
||||
import type { GeographyDescription } from '@/components/administrative-location';
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import { Head, Link, router, useForm, useRemember } from '@inertiajs/react';
|
||||
import { AiPlanSettings } from '@/components/ai-plan-settings';
|
||||
import type { AiPlan } from '@/components/ai-plan-settings';
|
||||
import { IntelligenceSettings } from '@/components/intelligence-settings';
|
||||
@@ -86,20 +89,28 @@ function Assignment({
|
||||
version: number;
|
||||
}) {
|
||||
const assigned = members.filter((m) => m.user_id === person.id);
|
||||
const form = useForm({
|
||||
const identity = useProcurementPreparationIdentity(
|
||||
`company-assignment:${person.id}:${version}`,
|
||||
);
|
||||
const initial = {
|
||||
version,
|
||||
user_id: person.id,
|
||||
profile_ids: assigned.map((m) => m.profile_id),
|
||||
maintenance: assigned.some((m) => m.maintenance),
|
||||
expires_at: '',
|
||||
reason: '',
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty);
|
||||
return (
|
||||
<details className="rounded border p-4">
|
||||
<summary className="cursor-pointer font-medium">
|
||||
{person.name} · {person.email} · {assigned.length} perfil(is)
|
||||
</summary>
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="mt-4 space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -110,8 +121,14 @@ function Assignment({
|
||||
: null,
|
||||
}));
|
||||
form.post(base + '/assign', {
|
||||
preserveState: 'errors',
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
router.remember(initial, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -171,7 +188,15 @@ function Assignment({
|
||||
</details>
|
||||
);
|
||||
}
|
||||
export default function Parameters({
|
||||
export default function Parameters(
|
||||
props: Omit<Parameters<typeof ParameterFields>[0], 'identity'>,
|
||||
) {
|
||||
const identity = useProcurementPreparationIdentity(
|
||||
`company-parameters:${props.version}:${props.active}:${props.ready}`,
|
||||
);
|
||||
return <ParameterFields key={identity} {...props} identity={identity} />;
|
||||
}
|
||||
function ParameterFields({
|
||||
approvalLevels,
|
||||
approvalLevelsReady = false,
|
||||
expiryReady = false,
|
||||
@@ -201,7 +226,9 @@ export default function Parameters({
|
||||
aiDataScopes = {},
|
||||
workContextConfiguration,
|
||||
enabledWorkContexts = [],
|
||||
identity,
|
||||
}: {
|
||||
identity: string;
|
||||
approvalLevels?: RequisitionApprovalPlan | null;
|
||||
approvalLevelsReady?: boolean;
|
||||
expiryReady?: boolean;
|
||||
@@ -238,14 +265,15 @@ export default function Parameters({
|
||||
default_tax_rate: string;
|
||||
};
|
||||
}) {
|
||||
const profile = useForm({
|
||||
version,
|
||||
id: '',
|
||||
name: '',
|
||||
permissions: [] as string[],
|
||||
work_contexts: [] as string[],
|
||||
});
|
||||
const user = useForm({
|
||||
const [selectedProfileId, setSelectedProfileId] = useRemember(
|
||||
'',
|
||||
`${identity}:selected-profile`,
|
||||
);
|
||||
const selectedProfile = profiles.find(
|
||||
(row) => String(row.id) === selectedProfileId,
|
||||
);
|
||||
const profileIdentity = `${identity}:profile:${selectedProfileId || 'new'}`;
|
||||
const initialUser = {
|
||||
version,
|
||||
name: '',
|
||||
email: '',
|
||||
@@ -254,29 +282,109 @@ export default function Parameters({
|
||||
department_id: '',
|
||||
profile_ids: [] as number[],
|
||||
reason: '',
|
||||
};
|
||||
const user = useForm(`${identity}:user`, initialUser).dontRemember(
|
||||
'password',
|
||||
'password_confirmation',
|
||||
);
|
||||
const userDirty = hasPreparationChanges(initialUser, {
|
||||
...initialUser,
|
||||
...user.data,
|
||||
});
|
||||
const activate = useForm({ version, confirm: false, reason: '' });
|
||||
const rules = useForm({
|
||||
const userRef = usePreparationDirty(userDirty);
|
||||
const clearUser = () => {
|
||||
user.setData(initialUser);
|
||||
user.clearErrors();
|
||||
const {
|
||||
password: _password,
|
||||
password_confirmation: _confirmation,
|
||||
...remembered
|
||||
} = initialUser;
|
||||
router.remember(remembered, `${identity}:user:data`);
|
||||
router.remember({}, `${identity}:user:errors`);
|
||||
};
|
||||
const initialActivate = { version, confirm: false, reason: '' };
|
||||
const activate = useForm(`${identity}:activate`, initialActivate);
|
||||
const activateDirty = hasPreparationChanges(initialActivate, activate.data);
|
||||
const activateRef = usePreparationDirty(activateDirty);
|
||||
const clearActivate = () => {
|
||||
activate.setData(initialActivate);
|
||||
activate.clearErrors();
|
||||
router.remember(initialActivate, `${identity}:activate:data`);
|
||||
router.remember({}, `${identity}:activate:errors`);
|
||||
};
|
||||
const initialRules = {
|
||||
version,
|
||||
first_limit: companyRules.first_limit,
|
||||
second_limit: companyRules.second_limit,
|
||||
includes_tax: companyRules.includes_tax,
|
||||
reason: '',
|
||||
});
|
||||
const department = useForm({ name: '' });
|
||||
const tax = useForm({
|
||||
};
|
||||
const rules = useForm(`${identity}:rules`, initialRules);
|
||||
const rulesDirty = hasPreparationChanges(initialRules, rules.data);
|
||||
const rulesRef = usePreparationDirty(rulesDirty);
|
||||
const clearRules = () => {
|
||||
rules.setData(initialRules);
|
||||
rules.clearErrors();
|
||||
router.remember(initialRules, `${identity}:rules:data`);
|
||||
router.remember({}, `${identity}:rules:errors`);
|
||||
};
|
||||
const initialDepartment = { name: '' };
|
||||
const department = useForm(`${identity}:department`, initialDepartment);
|
||||
const departmentDirty = hasPreparationChanges(
|
||||
initialDepartment,
|
||||
department.data,
|
||||
);
|
||||
const departmentRef = usePreparationDirty(departmentDirty);
|
||||
const clearDepartment = () => {
|
||||
department.setData(initialDepartment);
|
||||
department.clearErrors();
|
||||
router.remember(initialDepartment, `${identity}:department:data`);
|
||||
router.remember({}, `${identity}:department:errors`);
|
||||
};
|
||||
const initialTax = {
|
||||
version,
|
||||
default_tax_rate: companyRules.default_tax_rate,
|
||||
reason: '',
|
||||
});
|
||||
const center = useForm({ department_id: '', code: '', name: '' });
|
||||
const comparison = useForm({
|
||||
};
|
||||
const tax = useForm(`${identity}:tax`, initialTax);
|
||||
const taxDirty = hasPreparationChanges(initialTax, tax.data);
|
||||
const taxRef = usePreparationDirty(taxDirty);
|
||||
const clearTax = () => {
|
||||
tax.setData(initialTax);
|
||||
tax.clearErrors();
|
||||
router.remember(initialTax, `${identity}:tax:data`);
|
||||
router.remember({}, `${identity}:tax:errors`);
|
||||
};
|
||||
const initialCenter = { department_id: '', code: '', name: '' };
|
||||
const center = useForm(`${identity}:center`, initialCenter);
|
||||
const centerDirty = hasPreparationChanges(initialCenter, center.data);
|
||||
const centerRef = usePreparationDirty(centerDirty);
|
||||
const clearCenter = () => {
|
||||
center.setData(initialCenter);
|
||||
center.clearErrors();
|
||||
router.remember(initialCenter, `${identity}:center:data`);
|
||||
router.remember({}, `${identity}:center:errors`);
|
||||
};
|
||||
const initialComparison = {
|
||||
version,
|
||||
minimum_proposals: comparisonPolicy.minimum_proposals,
|
||||
minimum_evaluators: comparisonPolicy.minimum_evaluators,
|
||||
weights: { ...comparisonPolicy.weights },
|
||||
reason: '',
|
||||
});
|
||||
};
|
||||
const comparison = useForm(`${identity}:comparison`, initialComparison);
|
||||
const comparisonDirty = hasPreparationChanges(
|
||||
initialComparison,
|
||||
comparison.data,
|
||||
);
|
||||
const comparisonRef = usePreparationDirty(comparisonDirty);
|
||||
const clearComparison = () => {
|
||||
comparison.setData(initialComparison);
|
||||
comparison.clearErrors();
|
||||
router.remember(initialComparison, `${identity}:comparison:data`);
|
||||
router.remember({}, `${identity}:comparison:errors`);
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<Head title="Parametrização da aplicação" />
|
||||
@@ -364,12 +472,17 @@ export default function Parameters({
|
||||
</p>
|
||||
{!active && (
|
||||
<form
|
||||
ref={activateRef}
|
||||
data-preparation-dirty={
|
||||
activateDirty ? 'true' : 'false'
|
||||
}
|
||||
className="mt-4 space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
activate.post(base + '/activate', {
|
||||
preserveState: 'errors',
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
onSuccess: clearActivate,
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -453,12 +566,17 @@ export default function Parameters({
|
||||
conflito de interesses.
|
||||
</p>
|
||||
<form
|
||||
ref={comparisonRef}
|
||||
data-preparation-dirty={
|
||||
comparisonDirty ? 'true' : 'false'
|
||||
}
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
comparison.post(base + '/comparison', {
|
||||
preserveState: 'errors',
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
onSuccess: clearComparison,
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -588,12 +706,17 @@ export default function Parameters({
|
||||
descontos unitários incidem antes do IVA.
|
||||
</p>
|
||||
<form
|
||||
ref={taxRef}
|
||||
data-preparation-dirty={
|
||||
taxDirty ? 'true' : 'false'
|
||||
}
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
tax.post(base + '/tax', {
|
||||
preserveState: 'errors',
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
onSuccess: clearTax,
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -647,12 +770,17 @@ export default function Parameters({
|
||||
anteriores.
|
||||
</p>
|
||||
<form
|
||||
ref={rulesRef}
|
||||
data-preparation-dirty={
|
||||
rulesDirty ? 'true' : 'false'
|
||||
}
|
||||
className="grid gap-4 sm:grid-cols-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
rules.post(base + '/rules', {
|
||||
preserveState: 'errors',
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
onSuccess: clearRules,
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -739,210 +867,38 @@ export default function Parameters({
|
||||
key={p.id}
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
profile.setData({
|
||||
version,
|
||||
id: String(p.id),
|
||||
name: p.name,
|
||||
permissions: p.permissions,
|
||||
work_contexts:
|
||||
p.work_contexts ?? [],
|
||||
})
|
||||
setSelectedProfileId(String(p.id))
|
||||
}
|
||||
>
|
||||
{p.name}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<form
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
profile.transform((values) => ({
|
||||
...values,
|
||||
id: values.id || null,
|
||||
}));
|
||||
profile.post(base + '/profile', {
|
||||
preserveState: 'errors',
|
||||
preserveScroll: true,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={profile.errors} />
|
||||
<label className="block space-y-1">
|
||||
Nome do perfil
|
||||
<input
|
||||
required
|
||||
maxLength={120}
|
||||
className={controlClass}
|
||||
value={profile.data.name}
|
||||
onChange={(e) =>
|
||||
profile.setData(
|
||||
'name',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
{workContextConfiguration && (
|
||||
<fieldset className="space-y-2">
|
||||
<legend className="font-medium">
|
||||
Contextos autorizados deste perfil
|
||||
</legend>
|
||||
<p className="text-sm">
|
||||
A associação não acrescenta
|
||||
permissões funcionais nem opções
|
||||
contratadas.
|
||||
</p>
|
||||
{Object.entries(
|
||||
workContextConfiguration.options,
|
||||
).map(([key, option]) => (
|
||||
<label
|
||||
className="flex items-center gap-2"
|
||||
key={key}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={profile.data.work_contexts.includes(
|
||||
key,
|
||||
)}
|
||||
onChange={(e) =>
|
||||
profile.setData(
|
||||
'work_contexts',
|
||||
e.target.checked
|
||||
? [
|
||||
...profile
|
||||
.data
|
||||
.work_contexts,
|
||||
key,
|
||||
]
|
||||
: profile.data.work_contexts.filter(
|
||||
(value) =>
|
||||
value !==
|
||||
key,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
{option.areaLabel} ·{' '}
|
||||
{option.label}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
)}
|
||||
<fieldset className="grid gap-3 sm:grid-cols-2">
|
||||
<legend className="mb-2 font-medium">
|
||||
Tarefas e permissões do perfil
|
||||
</legend>
|
||||
{Object.entries(permissions).map(
|
||||
([key, label]) => (
|
||||
<label
|
||||
key={key}
|
||||
className="flex items-center gap-2 text-sm"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={profile.data.permissions.includes(
|
||||
key,
|
||||
)}
|
||||
onChange={(e) =>
|
||||
profile.setData(
|
||||
'permissions',
|
||||
e.target.checked
|
||||
? [
|
||||
...profile
|
||||
.data
|
||||
.permissions,
|
||||
key,
|
||||
]
|
||||
: profile.data.permissions.filter(
|
||||
(p) =>
|
||||
p !==
|
||||
key,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<span>
|
||||
{label}
|
||||
<span className="mt-1 block text-xs text-muted-foreground">
|
||||
{(
|
||||
workflowTasks[
|
||||
key
|
||||
] ?? []
|
||||
).map((task) => (
|
||||
<span
|
||||
className="block"
|
||||
key={task.key}
|
||||
>
|
||||
{task.label}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
),
|
||||
)}
|
||||
</fieldset>
|
||||
<div className="rounded-md border p-4 text-sm">
|
||||
<p className="font-medium">
|
||||
Tarefas associadas a este perfil no
|
||||
workflow
|
||||
</p>
|
||||
<p className="mt-2 text-muted-foreground">
|
||||
Seleccione as tarefas nas permissões
|
||||
acima e atribua o perfil às pessoas. O
|
||||
contexto, departamento, equipa do
|
||||
processo, validade do acesso e
|
||||
independência continuam a limitar cada
|
||||
intervenção. Administração, por si só,
|
||||
não autoriza decisões de compras. Estas
|
||||
associações não alteram o percurso
|
||||
aprovado.
|
||||
</p>
|
||||
{profile.data.permissions.length === 0 ? (
|
||||
<p className="mt-3">
|
||||
Sem tarefas seleccionadas.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="mt-3 list-disc space-y-1 pl-5">
|
||||
{profile.data.permissions
|
||||
.flatMap(
|
||||
(permission) =>
|
||||
workflowTasks[
|
||||
permission
|
||||
] ?? [],
|
||||
)
|
||||
.map((task) => (
|
||||
<li key={task.key}>
|
||||
{task.label}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
<ActionBar>
|
||||
<Button disabled={profile.processing}>
|
||||
{profile.data.id
|
||||
? 'Actualizar perfil'
|
||||
: 'Criar perfil'}
|
||||
</Button>
|
||||
{selectedProfileId && !selectedProfile ? (
|
||||
<p>
|
||||
Perfil seleccionado indisponível.{' '}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
profile.setData({
|
||||
version,
|
||||
id: '',
|
||||
name: '',
|
||||
permissions: [],
|
||||
work_contexts: [],
|
||||
})
|
||||
}
|
||||
onClick={() => setSelectedProfileId('')}
|
||||
>
|
||||
Novo perfil
|
||||
</Button>
|
||||
</ActionBar>
|
||||
</form>
|
||||
</p>
|
||||
) : (
|
||||
<ProfileEditor
|
||||
key={profileIdentity}
|
||||
identity={profileIdentity}
|
||||
source={selectedProfile}
|
||||
version={version}
|
||||
permissions={permissions}
|
||||
workflowTasks={workflowTasks}
|
||||
workContextConfiguration={
|
||||
workContextConfiguration
|
||||
}
|
||||
onNew={() => setSelectedProfileId('')}
|
||||
/>
|
||||
)}
|
||||
</Panel>
|
||||
<Panel title="Utilizadores e atribuições">
|
||||
<div className="space-y-3">
|
||||
@@ -961,17 +917,17 @@ export default function Parameters({
|
||||
Criar utilizador
|
||||
</summary>
|
||||
<form
|
||||
ref={userRef}
|
||||
data-preparation-dirty={
|
||||
userDirty ? 'true' : 'false'
|
||||
}
|
||||
className="mt-4 grid gap-4 sm:grid-cols-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
user.post(base + '/user', {
|
||||
preserveState: 'errors',
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
onSuccess: () =>
|
||||
user.reset(
|
||||
'password',
|
||||
'password_confirmation',
|
||||
),
|
||||
onSuccess: clearUser,
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -1017,7 +973,7 @@ export default function Parameters({
|
||||
: undefined
|
||||
}
|
||||
className={controlClass}
|
||||
value={user.data[key]}
|
||||
value={user.data[key] ?? ''}
|
||||
onChange={(e) =>
|
||||
user.setData(
|
||||
key,
|
||||
@@ -1073,6 +1029,10 @@ export default function Parameters({
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<p className="text-sm text-muted-foreground sm:col-span-2">
|
||||
As palavras-passe não são conservadas ao
|
||||
sair deste ecrã.
|
||||
</p>
|
||||
<Button disabled={user.processing}>
|
||||
Criar utilizador
|
||||
</Button>
|
||||
@@ -1082,12 +1042,19 @@ export default function Parameters({
|
||||
<Panel title="Organização e centros de custo">
|
||||
<div className="grid gap-5 sm:grid-cols-2">
|
||||
<form
|
||||
ref={departmentRef}
|
||||
data-preparation-dirty={
|
||||
departmentDirty ? 'true' : 'false'
|
||||
}
|
||||
className="space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
department.post(
|
||||
'/empresa/departamentos',
|
||||
{ preserveScroll: true },
|
||||
{
|
||||
preserveScroll: true,
|
||||
onSuccess: clearDepartment,
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
@@ -1116,12 +1083,19 @@ export default function Parameters({
|
||||
</p>
|
||||
</form>
|
||||
<form
|
||||
ref={centerRef}
|
||||
data-preparation-dirty={
|
||||
centerDirty ? 'true' : 'false'
|
||||
}
|
||||
className="space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
center.post(
|
||||
'/empresa/centros-de-custo',
|
||||
{ preserveScroll: true },
|
||||
{
|
||||
preserveScroll: true,
|
||||
onSuccess: clearCenter,
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
@@ -1204,3 +1178,181 @@ export default function Parameters({
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ProfileEditor({
|
||||
identity,
|
||||
source,
|
||||
version,
|
||||
permissions,
|
||||
workflowTasks = {},
|
||||
workContextConfiguration,
|
||||
onNew,
|
||||
}: {
|
||||
identity: string;
|
||||
source?: Profile;
|
||||
version: number;
|
||||
permissions: { [key: string]: string };
|
||||
workflowTasks?: Record<string, { key: string; label: string }[]>;
|
||||
workContextConfiguration?: WorkContextState;
|
||||
onNew: () => void;
|
||||
}) {
|
||||
const initialProfile = {
|
||||
version,
|
||||
id: source ? String(source.id) : '',
|
||||
name: source?.name ?? '',
|
||||
permissions: [...(source?.permissions ?? [])],
|
||||
work_contexts: [...(source?.work_contexts ?? [])],
|
||||
};
|
||||
const profile = useForm(identity, initialProfile);
|
||||
const profileDirty = hasPreparationChanges(initialProfile, profile.data);
|
||||
const profileRef = usePreparationDirty(profileDirty);
|
||||
const clearProfile = () => {
|
||||
profile.setData(initialProfile);
|
||||
profile.clearErrors();
|
||||
router.remember(initialProfile, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
onNew();
|
||||
};
|
||||
return (
|
||||
<form
|
||||
ref={profileRef}
|
||||
data-preparation-dirty={profileDirty ? 'true' : 'false'}
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
profile.transform((values) => ({
|
||||
...values,
|
||||
id: values.id || null,
|
||||
}));
|
||||
profile.post(base + '/profile', {
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
onSuccess: clearProfile,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={profile.errors} />
|
||||
<label className="block space-y-1">
|
||||
Nome do perfil
|
||||
<input
|
||||
required
|
||||
maxLength={120}
|
||||
className={controlClass}
|
||||
value={profile.data.name}
|
||||
onChange={(e) => profile.setData('name', e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{workContextConfiguration && (
|
||||
<fieldset className="space-y-2">
|
||||
<legend className="font-medium">
|
||||
Contextos autorizados deste perfil
|
||||
</legend>
|
||||
<p className="text-sm">
|
||||
A associação não acrescenta permissões funcionais nem
|
||||
opções contratadas.
|
||||
</p>
|
||||
{Object.entries(workContextConfiguration.options).map(
|
||||
([key, option]) => (
|
||||
<label
|
||||
className="flex items-center gap-2"
|
||||
key={key}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={profile.data.work_contexts.includes(
|
||||
key,
|
||||
)}
|
||||
onChange={(e) =>
|
||||
profile.setData(
|
||||
'work_contexts',
|
||||
e.target.checked
|
||||
? [
|
||||
...profile.data
|
||||
.work_contexts,
|
||||
key,
|
||||
]
|
||||
: profile.data.work_contexts.filter(
|
||||
(value) => value !== key,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
{option.areaLabel} · {option.label}
|
||||
</label>
|
||||
),
|
||||
)}
|
||||
</fieldset>
|
||||
)}
|
||||
<fieldset className="grid gap-3 sm:grid-cols-2">
|
||||
<legend className="mb-2 font-medium">
|
||||
Tarefas e permissões do perfil
|
||||
</legend>
|
||||
{Object.entries(permissions).map(([key, label]) => (
|
||||
<label
|
||||
key={key}
|
||||
className="flex items-center gap-2 text-sm"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={profile.data.permissions.includes(key)}
|
||||
onChange={(e) =>
|
||||
profile.setData(
|
||||
'permissions',
|
||||
e.target.checked
|
||||
? [...profile.data.permissions, key]
|
||||
: profile.data.permissions.filter(
|
||||
(p) => p !== key,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<span>
|
||||
{label}
|
||||
<span className="mt-1 block text-xs text-muted-foreground">
|
||||
{(workflowTasks[key] ?? []).map((task) => (
|
||||
<span className="block" key={task.key}>
|
||||
{task.label}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
<div className="rounded-md border p-4 text-sm">
|
||||
<p className="font-medium">
|
||||
Tarefas associadas a este perfil no workflow
|
||||
</p>
|
||||
<p className="mt-2 text-muted-foreground">
|
||||
Seleccione as tarefas nas permissões acima e atribua o
|
||||
perfil às pessoas. O contexto, departamento, equipa do
|
||||
processo, validade do acesso e independência continuam a
|
||||
limitar cada intervenção. Administração, por si só, não
|
||||
autoriza decisões de compras. Estas associações não alteram
|
||||
o percurso aprovado.
|
||||
</p>
|
||||
{profile.data.permissions.length === 0 ? (
|
||||
<p className="mt-3">Sem tarefas seleccionadas.</p>
|
||||
) : (
|
||||
<ul className="mt-3 list-disc space-y-1 pl-5">
|
||||
{profile.data.permissions
|
||||
.flatMap(
|
||||
(permission) => workflowTasks[permission] ?? [],
|
||||
)
|
||||
.map((task) => (
|
||||
<li key={task.key}>{task.label}</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
<ActionBar>
|
||||
<Button disabled={profile.processing}>
|
||||
{profile.data.id ? 'Actualizar perfil' : 'Criar perfil'}
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={() => onNew()}>
|
||||
Novo perfil
|
||||
</Button>
|
||||
</ActionBar>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
import { Head, useForm } from '@inertiajs/react';
|
||||
import { useProcurementPreparationIdentity } from '@/hooks/use-procurement-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { Head, router, useForm } from '@inertiajs/react';
|
||||
import { FormErrors, PageTitle, Panel } from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
|
||||
export default function Setup() {
|
||||
const form = useForm({
|
||||
const identity = useProcurementPreparationIdentity('company-setup');
|
||||
return <SetupFields key={identity} identity={identity} />;
|
||||
}
|
||||
function SetupFields({ identity }: { identity: string }) {
|
||||
const initial = {
|
||||
name: '',
|
||||
department: '',
|
||||
second_name: '',
|
||||
@@ -15,7 +22,13 @@ export default function Setup() {
|
||||
first_limit: '',
|
||||
second_limit: '',
|
||||
includes_tax: true,
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial).dontRemember(
|
||||
'second_password',
|
||||
'second_password_confirmation',
|
||||
);
|
||||
const dirty = hasPreparationChanges(initial, { ...initial, ...form.data });
|
||||
const ref = usePreparationDirty(dirty);
|
||||
return (
|
||||
<>
|
||||
<Head title="Configurar empresa" />
|
||||
@@ -27,9 +40,27 @@ export default function Setup() {
|
||||
/>
|
||||
<Panel title="Dados da organização">
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post('/empresa/iniciar');
|
||||
form.post('/empresa/iniciar', {
|
||||
onSuccess: () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
const {
|
||||
second_password: _password,
|
||||
second_password_confirmation:
|
||||
_confirmation,
|
||||
...remembered
|
||||
} = initial;
|
||||
router.remember(
|
||||
remembered,
|
||||
`${identity}:data`,
|
||||
);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
className="space-y-5"
|
||||
>
|
||||
@@ -101,7 +132,7 @@ export default function Setup() {
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
minLength={12}
|
||||
value={form.data.second_password}
|
||||
value={form.data.second_password ?? ''}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
'second_password',
|
||||
@@ -117,7 +148,8 @@ export default function Setup() {
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
value={
|
||||
form.data.second_password_confirmation
|
||||
form.data
|
||||
.second_password_confirmation ?? ''
|
||||
}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
@@ -180,6 +212,10 @@ export default function Setup() {
|
||||
Aplicar os limites ao valor com imposto
|
||||
</label>
|
||||
</fieldset>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
As palavras-passe não são conservadas ao sair deste
|
||||
ecrã.
|
||||
</p>
|
||||
<Button disabled={form.processing}>
|
||||
Criar empresa
|
||||
</Button>
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { Head, Link, useForm, usePage } from '@inertiajs/react';
|
||||
import { Head, Link, router, useForm, usePage } from '@inertiajs/react';
|
||||
import { useConflictPreparationIdentity } from '@/hooks/use-conflict-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import {
|
||||
TableViewport,
|
||||
FormErrors,
|
||||
@@ -23,20 +26,28 @@ type Props = {
|
||||
requisitions: { id: number; number: string }[];
|
||||
};
|
||||
|
||||
export default function Conflicts({
|
||||
export default function Conflicts(props: Props) {
|
||||
const identity = `${useConflictPreparationIdentity()}:new`;
|
||||
return <DeclarationFields key={identity} {...props} identity={identity} />;
|
||||
}
|
||||
function DeclarationFields({
|
||||
declarations,
|
||||
suppliers,
|
||||
requisitions,
|
||||
}: Props) {
|
||||
identity,
|
||||
}: Props & { identity: string }) {
|
||||
const { auth } = usePage().props;
|
||||
const form = useForm({
|
||||
const initial = {
|
||||
scope: 'supplier',
|
||||
supplier_id: '',
|
||||
requisition_id: '',
|
||||
has_conflict: '1',
|
||||
known_since: '',
|
||||
reason: '',
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty);
|
||||
return (
|
||||
<>
|
||||
<Head title="Conflitos de interesses" />
|
||||
@@ -58,6 +69,8 @@ export default function Conflicts({
|
||||
description={`Autor: ${auth.user.name}. A data e a hora do registo são guardadas pelo servidor.`}
|
||||
>
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="space-y-5"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -75,7 +88,15 @@ export default function Conflicts({
|
||||
}));
|
||||
form.post('/conflitos', {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => form.reset(),
|
||||
onSuccess: () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
router.remember(
|
||||
initial,
|
||||
`${identity}:data`,
|
||||
);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import { Head, Link, router, useForm } from '@inertiajs/react';
|
||||
import { useConflictPreparationIdentity } from '@/hooks/use-conflict-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import {
|
||||
FormErrors,
|
||||
PageTitle,
|
||||
@@ -12,18 +15,31 @@ import { conflictScope } from '@/types/conflict';
|
||||
import type { ConflictDeclaration } from '@/types/conflict';
|
||||
import { date } from '@/types/procurement';
|
||||
|
||||
export default function DeclarationHistory({
|
||||
export default function DeclarationHistory(props: {
|
||||
history: ConflictDeclaration[];
|
||||
canCorrect: boolean;
|
||||
}) {
|
||||
const current = props.history[props.history.length - 1];
|
||||
const identity = `${useConflictPreparationIdentity()}:correction:${current.id}:${current.declared_at}:${props.canCorrect}`;
|
||||
return <HistoryFields key={identity} {...props} identity={identity} />;
|
||||
}
|
||||
function HistoryFields({
|
||||
history,
|
||||
canCorrect,
|
||||
identity,
|
||||
}: {
|
||||
identity: string;
|
||||
history: ConflictDeclaration[];
|
||||
canCorrect: boolean;
|
||||
}) {
|
||||
const current = history[history.length - 1];
|
||||
const form = useForm({
|
||||
const initial = {
|
||||
reason: current.reason,
|
||||
known_since: current.known_since.slice(0, 10),
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial);
|
||||
const dirty = canCorrect && hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty, canCorrect);
|
||||
return (
|
||||
<>
|
||||
<Head title="Histórico da declaração" />
|
||||
@@ -77,11 +93,25 @@ export default function DeclarationHistory({
|
||||
description="A correcção cria um novo registo e mantém os anteriores. O autor, âmbito e situação declarada permanecem iguais."
|
||||
>
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.put(`/conflitos/${current.id}`, {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
router.remember(
|
||||
initial,
|
||||
`${identity}:data`,
|
||||
);
|
||||
router.remember(
|
||||
{},
|
||||
`${identity}:errors`,
|
||||
);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { useInventoryPreparationIdentity } from '@/hooks/use-inventory-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { AdministrativeLocation } from '@/components/administrative-location';
|
||||
import type {
|
||||
GeographyDescription,
|
||||
GeographyReference,
|
||||
} from '@/components/administrative-location';
|
||||
import { TerritorialFilter } from '@/components/territorial-filter';
|
||||
import { Head, useForm, Link } from '@inertiajs/react';
|
||||
import { Head, useForm, Link, router, useRemember } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { InventoryNotice, InventoryPagination } from '@/components/inventory';
|
||||
import {
|
||||
@@ -98,7 +101,18 @@ const statuses: Record<string, string> = {
|
||||
stopped: 'Parado',
|
||||
retired: 'Retirado',
|
||||
};
|
||||
export default function EquipmentPage({
|
||||
export default function EquipmentPage(props: Props) {
|
||||
if (props.demo)
|
||||
return <EquipmentFields {...props} identity="equipment:demo" />;
|
||||
return <PrivateEquipment {...props} />;
|
||||
}
|
||||
function PrivateEquipment(props: Props) {
|
||||
const identity = useInventoryPreparationIdentity(
|
||||
`/equipamentos:${props.canManage}:${props.canConfigure}:${props.geographyEnabled ?? false}`,
|
||||
);
|
||||
return <EquipmentFields key={identity} {...props} identity={identity} />;
|
||||
}
|
||||
function EquipmentFields({
|
||||
equipment,
|
||||
parts,
|
||||
levels,
|
||||
@@ -113,35 +127,45 @@ export default function EquipmentPage({
|
||||
geographyEnabled = false,
|
||||
equipmentGeography = {},
|
||||
geographyFilter = null,
|
||||
}: Props) {
|
||||
identity,
|
||||
}: Props & { identity: string }) {
|
||||
const [message, setMessage] = useState('');
|
||||
const category = useForm({
|
||||
const initialCategory = {
|
||||
code: '',
|
||||
name: '',
|
||||
criteria: '',
|
||||
is_critical: '',
|
||||
});
|
||||
const asset = useForm({
|
||||
geography_reference: null as GeographyReference | null,
|
||||
id: '',
|
||||
version: '',
|
||||
code: '',
|
||||
description: '',
|
||||
area: '',
|
||||
serial_number: '',
|
||||
department_id: '',
|
||||
stock_item_id: '',
|
||||
criticality_level_id: '',
|
||||
status: 'active',
|
||||
});
|
||||
const part = useForm({
|
||||
id: '',
|
||||
version: '',
|
||||
stock_item_id: '',
|
||||
criticality_level_id: '',
|
||||
minimum_quantity: '',
|
||||
});
|
||||
const association = useForm({ equipment_id: '', spare_part_id: '' });
|
||||
};
|
||||
const category = useForm(`${identity}:category`, initialCategory);
|
||||
const categoryDirty = hasPreparationChanges(initialCategory, category.data);
|
||||
const categoryRef = usePreparationDirty(
|
||||
categoryDirty,
|
||||
!demo && canConfigure,
|
||||
);
|
||||
const [selectedAssetId, setSelectedAssetId] = useRemember(
|
||||
'',
|
||||
`${identity}:selected-asset`,
|
||||
);
|
||||
const [selectedPartId, setSelectedPartId] = useRemember(
|
||||
'',
|
||||
`${identity}:selected-part`,
|
||||
);
|
||||
const selectedAsset = equipment.find(
|
||||
(row) => String(row.id) === selectedAssetId,
|
||||
);
|
||||
const selectedPart = parts.find((row) => String(row.id) === selectedPartId);
|
||||
const assetIdentity = `${identity}:asset:${selectedAssetId || 'new'}:${selectedAsset?.version ?? 0}`;
|
||||
const partIdentity = `${identity}:part:${selectedPartId || 'new'}:${selectedPart?.version ?? 0}`;
|
||||
const initialAssociation = { equipment_id: '', spare_part_id: '' };
|
||||
const association = useForm(`${identity}:association`, initialAssociation);
|
||||
const associationDirty = hasPreparationChanges(
|
||||
initialAssociation,
|
||||
association.data,
|
||||
);
|
||||
const associationRef = usePreparationDirty(
|
||||
associationDirty,
|
||||
!demo && canManage,
|
||||
);
|
||||
const stock = (id: number) => items.find((i) => i.id === id);
|
||||
const criticality = (id: number) => levels.find((l) => l.id === id);
|
||||
function simulate() {
|
||||
@@ -262,28 +286,7 @@ export default function EquipmentPage({
|
||||
className="mt-3"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
asset.setData({
|
||||
geography_reference:
|
||||
e.geography_reference ??
|
||||
null,
|
||||
id: String(e.id),
|
||||
version: String(e.version),
|
||||
code: e.code,
|
||||
description: e.description,
|
||||
area: e.area,
|
||||
serial_number:
|
||||
e.serial_number ?? '',
|
||||
department_id: String(
|
||||
e.department_id,
|
||||
),
|
||||
stock_item_id: e.stock_item_id
|
||||
? String(e.stock_item_id)
|
||||
: '',
|
||||
criticality_level_id: String(
|
||||
e.criticality_level_id,
|
||||
),
|
||||
status: e.status,
|
||||
})
|
||||
setSelectedAssetId(String(e.id))
|
||||
}
|
||||
>
|
||||
Editar ficha
|
||||
@@ -336,19 +339,7 @@ export default function EquipmentPage({
|
||||
className="mt-3"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
part.setData({
|
||||
id: String(p.id),
|
||||
version: String(p.version),
|
||||
stock_item_id: String(
|
||||
p.stock_item_id,
|
||||
),
|
||||
criticality_level_id: String(
|
||||
p.criticality_level_id,
|
||||
),
|
||||
minimum_quantity: (
|
||||
p.minimum_milli / 1000
|
||||
).toFixed(3),
|
||||
})
|
||||
setSelectedPartId(String(p.id))
|
||||
}
|
||||
>
|
||||
Editar mínimo e criticidade
|
||||
@@ -365,288 +356,82 @@ export default function EquipmentPage({
|
||||
<div className="grid gap-6 lg:grid-cols-2">
|
||||
<Panel
|
||||
title={
|
||||
asset.data.id
|
||||
selectedAssetId
|
||||
? 'Editar equipamento'
|
||||
: 'Cadastrar equipamento'
|
||||
}
|
||||
>
|
||||
<form
|
||||
className="grid gap-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (demo) {
|
||||
simulate();
|
||||
return;
|
||||
}
|
||||
asset.transform((data) => {
|
||||
const { geography_reference, ...rest } =
|
||||
data;
|
||||
return geographyEnabled
|
||||
? { ...rest, geography_reference }
|
||||
: rest;
|
||||
});
|
||||
asset.post('/equipamentos/activos', {
|
||||
onSuccess: () => asset.reset(),
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={asset.errors} />
|
||||
{geographyEnabled && !demo && (
|
||||
<AdministrativeLocation
|
||||
key={asset.data.id || 'new'}
|
||||
value={asset.data.geography_reference}
|
||||
initial={
|
||||
equipmentGeography[
|
||||
Number(asset.data.id)
|
||||
] ?? null
|
||||
}
|
||||
onChange={(value) =>
|
||||
asset.setData(
|
||||
'geography_reference',
|
||||
value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{(
|
||||
[
|
||||
'code',
|
||||
'description',
|
||||
'area',
|
||||
'serial_number',
|
||||
] as const
|
||||
).map((k) => (
|
||||
<Field
|
||||
key={k}
|
||||
label={
|
||||
{
|
||||
code: 'Código',
|
||||
description: 'Descrição',
|
||||
area: 'Área / linha de produção',
|
||||
serial_number:
|
||||
'Número de série',
|
||||
}[k]
|
||||
}
|
||||
>
|
||||
<Input
|
||||
required={k !== 'serial_number'}
|
||||
value={asset.data[k]}
|
||||
onChange={(e) =>
|
||||
asset.setData(k, e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
))}
|
||||
<Field label="Departamento">
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={asset.data.department_id}
|
||||
onChange={(e) =>
|
||||
asset.setData(
|
||||
'department_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccionar</option>
|
||||
{departments.map((d) => (
|
||||
<option key={d.id} value={d.id}>
|
||||
{d.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Artigo de stock (opcional)">
|
||||
<select
|
||||
className={controlClass}
|
||||
value={asset.data.stock_item_id}
|
||||
onChange={(e) =>
|
||||
asset.setData(
|
||||
'stock_item_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Sem artigo associado
|
||||
</option>
|
||||
{items.map((i) => (
|
||||
<option key={i.id} value={i.id}>
|
||||
{i.code} · {i.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Criticidade definida pela empresa">
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={asset.data.criticality_level_id}
|
||||
onChange={(e) =>
|
||||
asset.setData(
|
||||
'criticality_level_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccionar</option>
|
||||
{levels.map((l) => (
|
||||
<option key={l.id} value={l.id}>
|
||||
{l.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Estado">
|
||||
<select
|
||||
className={controlClass}
|
||||
value={asset.data.status}
|
||||
onChange={(e) =>
|
||||
asset.setData(
|
||||
'status',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
{Object.entries(statuses).map(
|
||||
([k, v]) => (
|
||||
<option key={k} value={k}>
|
||||
{v}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</Field>
|
||||
<Button
|
||||
disabled={
|
||||
asset.processing || levels.length === 0
|
||||
}
|
||||
>
|
||||
Guardar equipamento
|
||||
</Button>
|
||||
{asset.data.id && (
|
||||
{selectedAssetId && !selectedAsset ? (
|
||||
<p>
|
||||
Ficha seleccionada indisponível no contexto
|
||||
actual.{' '}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => asset.reset()}
|
||||
onClick={() => setSelectedAssetId('')}
|
||||
>
|
||||
Novo cadastro
|
||||
</Button>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
O cadastro não cria entradas nem retira
|
||||
existências. Os movimentos usam o fluxo de
|
||||
stock.
|
||||
</p>
|
||||
</form>
|
||||
) : (
|
||||
<AssetEditor
|
||||
key={assetIdentity}
|
||||
identity={assetIdentity}
|
||||
source={selectedAsset}
|
||||
items={items}
|
||||
levels={levels}
|
||||
departments={departments}
|
||||
geographyEnabled={geographyEnabled}
|
||||
equipmentGeography={equipmentGeography}
|
||||
demo={demo}
|
||||
simulate={simulate}
|
||||
onNew={() => setSelectedAssetId('')}
|
||||
onSaved={() => setSelectedAssetId('')}
|
||||
/>
|
||||
)}
|
||||
</Panel>
|
||||
<div className="space-y-6">
|
||||
<Panel
|
||||
title={
|
||||
part.data.id
|
||||
selectedPartId
|
||||
? 'Editar peça'
|
||||
: 'Cadastrar peça sobre artigo existente'
|
||||
}
|
||||
>
|
||||
<form
|
||||
className="grid gap-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (demo) {
|
||||
simulate();
|
||||
return;
|
||||
}
|
||||
part.post('/equipamentos/pecas', {
|
||||
onSuccess: () => part.reset(),
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={part.errors} />
|
||||
<Field label="Artigo / referência">
|
||||
<select
|
||||
required
|
||||
disabled={!!part.data.id}
|
||||
className={controlClass}
|
||||
value={part.data.stock_item_id}
|
||||
onChange={(e) =>
|
||||
part.setData(
|
||||
'stock_item_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Seleccionar
|
||||
</option>
|
||||
{items.map((i) => (
|
||||
<option key={i.id} value={i.id}>
|
||||
{i.code} · {i.name} (
|
||||
{i.unit})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Criticidade">
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={
|
||||
part.data.criticality_level_id
|
||||
}
|
||||
onChange={(e) =>
|
||||
part.setData(
|
||||
'criticality_level_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Seleccionar
|
||||
</option>
|
||||
{levels.map((l) => (
|
||||
<option key={l.id} value={l.id}>
|
||||
{l.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Quantidade mínima explícita (pode ser zero)">
|
||||
<Input
|
||||
required
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.001"
|
||||
value={part.data.minimum_quantity}
|
||||
onChange={(e) =>
|
||||
part.setData(
|
||||
'minimum_quantity',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Button
|
||||
disabled={
|
||||
part.processing ||
|
||||
levels.length === 0
|
||||
}
|
||||
>
|
||||
Guardar peça
|
||||
</Button>
|
||||
{part.data.id && (
|
||||
{selectedPartId && !selectedPart ? (
|
||||
<p>
|
||||
Ficha seleccionada indisponível no
|
||||
contexto actual.{' '}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => part.reset()}
|
||||
onClick={() =>
|
||||
setSelectedPartId('')
|
||||
}
|
||||
>
|
||||
Nova peça
|
||||
Novo cadastro
|
||||
</Button>
|
||||
)}
|
||||
</form>
|
||||
</p>
|
||||
) : (
|
||||
<PartEditor
|
||||
key={partIdentity}
|
||||
identity={partIdentity}
|
||||
source={selectedPart}
|
||||
items={items}
|
||||
levels={levels}
|
||||
demo={demo}
|
||||
simulate={simulate}
|
||||
onNew={() => setSelectedPartId('')}
|
||||
onSaved={() => setSelectedPartId('')}
|
||||
/>
|
||||
)}
|
||||
</Panel>
|
||||
<Panel title="Associar peça a equipamento">
|
||||
<form
|
||||
ref={associationRef}
|
||||
data-preparation-dirty={
|
||||
associationDirty ? 'true' : 'false'
|
||||
}
|
||||
className="grid gap-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -657,8 +442,20 @@ export default function EquipmentPage({
|
||||
association.post(
|
||||
'/equipamentos/associacoes',
|
||||
{
|
||||
onSuccess: () =>
|
||||
association.reset(),
|
||||
onSuccess: () => {
|
||||
association.setData(
|
||||
initialAssociation,
|
||||
);
|
||||
association.clearErrors();
|
||||
router.remember(
|
||||
initialAssociation,
|
||||
`${identity}:association:data`,
|
||||
);
|
||||
router.remember(
|
||||
{},
|
||||
`${identity}:association:errors`,
|
||||
);
|
||||
},
|
||||
},
|
||||
);
|
||||
}}
|
||||
@@ -734,6 +531,10 @@ export default function EquipmentPage({
|
||||
description="Sem categorias automáticas. Registe a decisão da empresa; os critérios guardados não são reescritos. Para novos critérios, crie uma nova categoria."
|
||||
>
|
||||
<form
|
||||
ref={categoryRef}
|
||||
data-preparation-dirty={
|
||||
categoryDirty ? 'true' : 'false'
|
||||
}
|
||||
className="grid gap-4 sm:grid-cols-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -742,7 +543,18 @@ export default function EquipmentPage({
|
||||
return;
|
||||
}
|
||||
category.post('/equipamentos/categorias', {
|
||||
onSuccess: () => category.reset(),
|
||||
onSuccess: () => {
|
||||
category.setData(initialCategory);
|
||||
category.clearErrors();
|
||||
router.remember(
|
||||
initialCategory,
|
||||
`${identity}:category:data`,
|
||||
);
|
||||
router.remember(
|
||||
{},
|
||||
`${identity}:category:errors`,
|
||||
);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -951,3 +763,302 @@ export function EquipmentDemo() {
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AssetEditor({
|
||||
identity,
|
||||
source,
|
||||
items,
|
||||
levels,
|
||||
demo,
|
||||
simulate,
|
||||
onNew,
|
||||
onSaved,
|
||||
departments,
|
||||
geographyEnabled,
|
||||
equipmentGeography,
|
||||
}: Pick<
|
||||
Props,
|
||||
| 'items'
|
||||
| 'levels'
|
||||
| 'departments'
|
||||
| 'geographyEnabled'
|
||||
| 'equipmentGeography'
|
||||
> & {
|
||||
identity: string;
|
||||
source?: Asset;
|
||||
demo: boolean;
|
||||
simulate: () => void;
|
||||
onNew: () => void;
|
||||
onSaved: () => void;
|
||||
}) {
|
||||
const initial = {
|
||||
geography_reference:
|
||||
source?.geography_reference ?? (null as GeographyReference | null),
|
||||
id: source ? String(source.id) : '',
|
||||
version: source ? String(source.version) : '',
|
||||
code: source?.code ?? '',
|
||||
description: source?.description ?? '',
|
||||
area: source?.area ?? '',
|
||||
serial_number: source?.serial_number ?? '',
|
||||
department_id: source ? String(source.department_id) : '',
|
||||
stock_item_id: source?.stock_item_id
|
||||
? String(source.stock_item_id)
|
||||
: '',
|
||||
criticality_level_id: source ? String(source.criticality_level_id) : '',
|
||||
status: source?.status ?? 'active',
|
||||
};
|
||||
const asset = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(initial, asset.data);
|
||||
const ref = usePreparationDirty(dirty, !demo);
|
||||
return (
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="grid gap-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (demo) {
|
||||
simulate();
|
||||
return;
|
||||
}
|
||||
asset.transform((data) => {
|
||||
const { geography_reference, ...rest } = data;
|
||||
return geographyEnabled
|
||||
? { ...rest, geography_reference }
|
||||
: rest;
|
||||
});
|
||||
asset.post('/equipamentos/activos', {
|
||||
onSuccess: () => {
|
||||
asset.setData(initial);
|
||||
asset.clearErrors();
|
||||
router.remember(initial, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
onSaved();
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={asset.errors} />
|
||||
{geographyEnabled && !demo && (
|
||||
<AdministrativeLocation
|
||||
key={asset.data.id || 'new'}
|
||||
value={asset.data.geography_reference}
|
||||
initial={
|
||||
(equipmentGeography ?? {})[Number(asset.data.id)] ??
|
||||
null
|
||||
}
|
||||
onChange={(value) =>
|
||||
asset.setData('geography_reference', value)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{(['code', 'description', 'area', 'serial_number'] as const).map(
|
||||
(k) => (
|
||||
<Field
|
||||
key={k}
|
||||
label={
|
||||
{
|
||||
code: 'Código',
|
||||
description: 'Descrição',
|
||||
area: 'Área / linha de produção',
|
||||
serial_number: 'Número de série',
|
||||
}[k]
|
||||
}
|
||||
>
|
||||
<Input
|
||||
required={k !== 'serial_number'}
|
||||
value={asset.data[k]}
|
||||
onChange={(e) => asset.setData(k, e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
),
|
||||
)}
|
||||
<Field label="Departamento">
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={asset.data.department_id}
|
||||
onChange={(e) =>
|
||||
asset.setData('department_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccionar</option>
|
||||
{departments.map((d) => (
|
||||
<option key={d.id} value={d.id}>
|
||||
{d.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Artigo de stock (opcional)">
|
||||
<select
|
||||
className={controlClass}
|
||||
value={asset.data.stock_item_id}
|
||||
onChange={(e) =>
|
||||
asset.setData('stock_item_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Sem artigo associado</option>
|
||||
{items.map((i) => (
|
||||
<option key={i.id} value={i.id}>
|
||||
{i.code} · {i.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Criticidade definida pela empresa">
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={asset.data.criticality_level_id}
|
||||
onChange={(e) =>
|
||||
asset.setData('criticality_level_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccionar</option>
|
||||
{levels.map((l) => (
|
||||
<option key={l.id} value={l.id}>
|
||||
{l.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Estado">
|
||||
<select
|
||||
className={controlClass}
|
||||
value={asset.data.status}
|
||||
onChange={(e) => asset.setData('status', e.target.value)}
|
||||
>
|
||||
{Object.entries(statuses).map(([k, v]) => (
|
||||
<option key={k} value={k}>
|
||||
{v}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Button disabled={asset.processing || levels.length === 0}>
|
||||
Guardar equipamento
|
||||
</Button>
|
||||
{asset.data.id && (
|
||||
<Button type="button" variant="outline" onClick={onNew}>
|
||||
Novo cadastro
|
||||
</Button>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
O cadastro não cria entradas nem retira existências. Os
|
||||
movimentos usam o fluxo de stock.
|
||||
</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function PartEditor({
|
||||
identity,
|
||||
source,
|
||||
items,
|
||||
levels,
|
||||
demo,
|
||||
simulate,
|
||||
onNew,
|
||||
onSaved,
|
||||
}: Pick<Props, 'items' | 'levels'> & {
|
||||
identity: string;
|
||||
source?: Part;
|
||||
demo: boolean;
|
||||
simulate: () => void;
|
||||
onNew: () => void;
|
||||
onSaved: () => void;
|
||||
}) {
|
||||
const initial = {
|
||||
id: source ? String(source.id) : '',
|
||||
version: source ? String(source.version) : '',
|
||||
stock_item_id: source ? String(source.stock_item_id) : '',
|
||||
criticality_level_id: source ? String(source.criticality_level_id) : '',
|
||||
minimum_quantity: source
|
||||
? (source.minimum_milli / 1000).toFixed(3)
|
||||
: '',
|
||||
};
|
||||
const part = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(initial, part.data);
|
||||
const ref = usePreparationDirty(dirty, !demo);
|
||||
return (
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="grid gap-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (demo) {
|
||||
simulate();
|
||||
return;
|
||||
}
|
||||
part.post('/equipamentos/pecas', {
|
||||
onSuccess: () => {
|
||||
part.setData(initial);
|
||||
part.clearErrors();
|
||||
router.remember(initial, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
onSaved();
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={part.errors} />
|
||||
<Field label="Artigo / referência">
|
||||
<select
|
||||
required
|
||||
disabled={!!part.data.id}
|
||||
className={controlClass}
|
||||
value={part.data.stock_item_id}
|
||||
onChange={(e) =>
|
||||
part.setData('stock_item_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccionar</option>
|
||||
{items.map((i) => (
|
||||
<option key={i.id} value={i.id}>
|
||||
{i.code} · {i.name} ({i.unit})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Criticidade">
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={part.data.criticality_level_id}
|
||||
onChange={(e) =>
|
||||
part.setData('criticality_level_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccionar</option>
|
||||
{levels.map((l) => (
|
||||
<option key={l.id} value={l.id}>
|
||||
{l.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Quantidade mínima explícita (pode ser zero)">
|
||||
<Input
|
||||
required
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.001"
|
||||
value={part.data.minimum_quantity}
|
||||
onChange={(e) =>
|
||||
part.setData('minimum_quantity', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Button disabled={part.processing || levels.length === 0}>
|
||||
Guardar peça
|
||||
</Button>
|
||||
{part.data.id && (
|
||||
<Button type="button" variant="outline" onClick={onNew}>
|
||||
Nova peça
|
||||
</Button>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -60,7 +60,16 @@ export default function EquipmentShow({
|
||||
purchases,
|
||||
movements,
|
||||
warehouseRequests = null,
|
||||
capitalReference = null,
|
||||
}: {
|
||||
capitalReference?: {
|
||||
record_key: string;
|
||||
code: string;
|
||||
name: string;
|
||||
version: number;
|
||||
state: string;
|
||||
href: string;
|
||||
} | null;
|
||||
geography?: GeographyDescription;
|
||||
equipment: {
|
||||
id: number;
|
||||
@@ -114,6 +123,27 @@ export default function EquipmentShow({
|
||||
</p>
|
||||
</Panel>
|
||||
)}
|
||||
{capitalReference && (
|
||||
<Panel title="Imobilizado no cadastro de Compras">
|
||||
<p className="font-medium">
|
||||
{capitalReference.code} · {capitalReference.name}
|
||||
</p>
|
||||
<p className="mt-2 text-sm">
|
||||
Referência actual, versão {capitalReference.version}
|
||||
{capitalReference.state === 'archived'
|
||||
? ' · arquivada'
|
||||
: ''}
|
||||
. Os documentos de compra conservam a referência
|
||||
utilizada na emissão.
|
||||
</p>
|
||||
<Link
|
||||
className="mt-3 inline-block underline"
|
||||
href={capitalReference.href}
|
||||
>
|
||||
Consultar aquisição e recepções
|
||||
</Link>
|
||||
</Panel>
|
||||
)}
|
||||
<Panel
|
||||
title={`Requisições de compra associadas · ${purchases.total}`}
|
||||
>
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { Head, useForm, usePage } from '@inertiajs/react';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import type { WorkContextState } from '@/types/work-context';
|
||||
import { Head, router, useForm, usePage } from '@inertiajs/react';
|
||||
import {
|
||||
FormErrors,
|
||||
Panel,
|
||||
@@ -30,8 +33,31 @@ type Review = {
|
||||
decision: string;
|
||||
reason: string;
|
||||
};
|
||||
function useInvestmentIdentity() {
|
||||
const { auth, workContext, canManage, organizationAccess } =
|
||||
usePage().props;
|
||||
const context = workContext as WorkContextState | null | undefined;
|
||||
const access = organizationAccess as { permissions?: string[] } | null;
|
||||
return `investment:${auth.user?.tenant_id}:${auth.user?.id}:${context?.active ?? 'legacy'}:${canManage === true}:${[...(access?.permissions ?? [])].sort().join(',')}`;
|
||||
}
|
||||
function Proposal({ previousId }: { previousId: number }) {
|
||||
const form = useForm({
|
||||
const identity = `${useInvestmentIdentity()}:proposal:${previousId}`;
|
||||
return (
|
||||
<ProposalFields
|
||||
key={identity}
|
||||
previousId={previousId}
|
||||
identity={identity}
|
||||
/>
|
||||
);
|
||||
}
|
||||
function ProposalFields({
|
||||
previousId,
|
||||
identity,
|
||||
}: {
|
||||
previousId: number;
|
||||
identity: string;
|
||||
}) {
|
||||
const initial = {
|
||||
previous_id: previousId,
|
||||
mode: '',
|
||||
scope: '',
|
||||
@@ -41,13 +67,18 @@ function Proposal({ previousId }: { previousId: number }) {
|
||||
valid_from: '',
|
||||
valid_until: '',
|
||||
reason: '',
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty);
|
||||
return (
|
||||
<Panel
|
||||
title="Propor nova versão"
|
||||
description="São necessárias duas aprovações de administradores distintos do proponente. Valores e vigência são decisões da empresa."
|
||||
>
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="grid gap-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -55,7 +86,14 @@ function Proposal({ previousId }: { previousId: number }) {
|
||||
...d,
|
||||
includes_tax: d.includes_tax === '1',
|
||||
}));
|
||||
form.post('/regras-investimento');
|
||||
form.post('/regras-investimento', {
|
||||
onSuccess: () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
router.remember(initial, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
@@ -172,13 +210,29 @@ function Proposal({ previousId }: { previousId: number }) {
|
||||
);
|
||||
}
|
||||
function Decision({ id }: { id: number }) {
|
||||
const form = useForm({ decision: 'approved', reason: '' });
|
||||
const identity = `${useInvestmentIdentity()}:review:${id}`;
|
||||
return <DecisionFields key={identity} id={id} identity={identity} />;
|
||||
}
|
||||
function DecisionFields({ id, identity }: { id: number; identity: string }) {
|
||||
const initial = { decision: 'approved', reason: '' };
|
||||
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-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post(`/regras-investimento/${id}/decidir`);
|
||||
form.post(`/regras-investimento/${id}/decidir`, {
|
||||
onSuccess: () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
router.remember(initial, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
|
||||
@@ -298,6 +298,7 @@ export default function Invoices({
|
||||
>
|
||||
<form
|
||||
ref={formElement}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="grid gap-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -14,6 +14,9 @@ type Level = {
|
||||
reminder_minutes: number | null;
|
||||
escalation_minutes: number | null;
|
||||
profile_ids: number[];
|
||||
urgent_expire_minutes?: number | null;
|
||||
urgent_reminder_minutes?: number | null;
|
||||
urgent_escalation_minutes?: number | null;
|
||||
};
|
||||
type Policy = {
|
||||
id: number;
|
||||
@@ -40,6 +43,9 @@ type Draft = {
|
||||
reminder_minutes: string;
|
||||
escalation_minutes: string;
|
||||
profile_ids: number[];
|
||||
urgent_expire_minutes: string;
|
||||
urgent_reminder_minutes: string;
|
||||
urgent_escalation_minutes: string;
|
||||
};
|
||||
const draft = (level: Level): Draft => ({
|
||||
...level,
|
||||
@@ -51,6 +57,18 @@ const draft = (level: Level): Draft => ({
|
||||
? ''
|
||||
: String(level.escalation_minutes),
|
||||
profile_ids: [...level.profile_ids],
|
||||
urgent_expire_minutes:
|
||||
level.urgent_expire_minutes == null
|
||||
? ''
|
||||
: String(level.urgent_expire_minutes),
|
||||
urgent_reminder_minutes:
|
||||
level.urgent_reminder_minutes == null
|
||||
? ''
|
||||
: String(level.urgent_reminder_minutes),
|
||||
urgent_escalation_minutes:
|
||||
level.urgent_escalation_minutes == null
|
||||
? ''
|
||||
: String(level.urgent_escalation_minutes),
|
||||
});
|
||||
export default function ApprovalTimeouts(props: Props) {
|
||||
const url = '/administracao/prazos-aprovacao';
|
||||
@@ -92,17 +110,17 @@ export default function ApprovalTimeouts(props: Props) {
|
||||
const change = (index: number, patch: Partial<Draft>) =>
|
||||
form.setData((data) => ({
|
||||
...data,
|
||||
levels: data.levels.map((level, i) =>
|
||||
i === index
|
||||
? {
|
||||
...level,
|
||||
...patch,
|
||||
...(patch.escalation_minutes === ''
|
||||
? { profile_ids: [] }
|
||||
: {}),
|
||||
}
|
||||
: level,
|
||||
),
|
||||
levels: data.levels.map((level, i) => {
|
||||
if (i !== index) return level;
|
||||
const next = { ...level, ...patch };
|
||||
return {
|
||||
...next,
|
||||
...(!next.escalation_minutes &&
|
||||
!next.urgent_escalation_minutes
|
||||
? { profile_ids: [] }
|
||||
: {}),
|
||||
};
|
||||
}),
|
||||
operation_key: '',
|
||||
}));
|
||||
return (
|
||||
@@ -142,6 +160,12 @@ export default function ApprovalTimeouts(props: Props) {
|
||||
level.reminder_minutes || null,
|
||||
escalation_minutes:
|
||||
level.escalation_minutes || null,
|
||||
urgent_expire_minutes:
|
||||
level.urgent_expire_minutes || null,
|
||||
urgent_reminder_minutes:
|
||||
level.urgent_reminder_minutes || null,
|
||||
urgent_escalation_minutes:
|
||||
level.urgent_escalation_minutes || null,
|
||||
})),
|
||||
}));
|
||||
form.post(url, {
|
||||
@@ -230,7 +254,58 @@ export default function ApprovalTimeouts(props: Props) {
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{level.escalation_minutes !== '' && (
|
||||
<details
|
||||
className="rounded-lg border p-3"
|
||||
open={Boolean(level.urgent_expire_minutes)}
|
||||
>
|
||||
<summary className="cursor-pointer font-medium">
|
||||
Prazos reduzidos para urgências · opcionais
|
||||
</summary>
|
||||
<p className="my-3 text-sm">
|
||||
Configure valores inferiores aos prazos
|
||||
gerais desta etapa. Os alertas já
|
||||
configurados mantêm-se com prazos próprios;
|
||||
os destinatários são os mesmos perfis
|
||||
expressamente seleccionados abaixo.
|
||||
</p>
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
{(
|
||||
[
|
||||
'urgent_reminder_minutes',
|
||||
'urgent_escalation_minutes',
|
||||
'urgent_expire_minutes',
|
||||
] as const
|
||||
).map((field) => (
|
||||
<label
|
||||
key={field}
|
||||
className="grid gap-2"
|
||||
>
|
||||
{field === 'urgent_expire_minutes'
|
||||
? 'Urgência: expiração · minutos'
|
||||
: field ===
|
||||
'urgent_reminder_minutes'
|
||||
? 'Urgência: lembrete · minutos'
|
||||
: 'Urgência: escalamento · minutos'}
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
max={5256000}
|
||||
step={1}
|
||||
className={controlClass}
|
||||
value={level[field] ?? ''}
|
||||
onChange={(event) =>
|
||||
change(index, {
|
||||
[field]:
|
||||
event.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
{(Boolean(level.escalation_minutes) ||
|
||||
Boolean(level.urgent_escalation_minutes)) && (
|
||||
<fieldset className="space-y-2">
|
||||
<legend>
|
||||
Perfis destinatários do escalamento
|
||||
@@ -311,6 +386,9 @@ export default function ApprovalTimeouts(props: Props) {
|
||||
reminder_minutes: '',
|
||||
escalation_minutes: '',
|
||||
profile_ids: [],
|
||||
urgent_expire_minutes: '',
|
||||
urgent_reminder_minutes: '',
|
||||
urgent_escalation_minutes: '',
|
||||
},
|
||||
],
|
||||
operation_key: '',
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import {
|
||||
PageTitle,
|
||||
Panel,
|
||||
FormErrors,
|
||||
controlClass,
|
||||
} from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
type Policy = {
|
||||
id: number;
|
||||
version: number;
|
||||
state: string;
|
||||
reason: string;
|
||||
data: { profile_ids: number[] };
|
||||
};
|
||||
export default function UrgentReviewPolicy(props: {
|
||||
current: Policy | null;
|
||||
profiles: { id: number; name: string }[];
|
||||
actorId: number;
|
||||
tenantId: number;
|
||||
history: {
|
||||
data: Policy[];
|
||||
prev_page_url: string | null;
|
||||
next_page_url: string | null;
|
||||
};
|
||||
}) {
|
||||
const form = useForm(
|
||||
`urgent-review-policy:${props.tenantId}:${props.actorId}`,
|
||||
{
|
||||
operation_key: '',
|
||||
version: props.current?.version ?? 0,
|
||||
enabled: props.current?.state === 'active',
|
||||
profile_ids: props.current?.data.profile_ids ?? [],
|
||||
reason: '',
|
||||
},
|
||||
);
|
||||
const ref = useRef<HTMLFormElement>(null);
|
||||
useEffect(() => {
|
||||
const node = ref.current;
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('sgc:context-dirty', {
|
||||
detail: { form: node, dirty: form.isDirty },
|
||||
}),
|
||||
);
|
||||
return () => {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('sgc:context-dirty', {
|
||||
detail: { form: node, dirty: false },
|
||||
}),
|
||||
);
|
||||
};
|
||||
}, [form.isDirty]);
|
||||
const current = form.data.version === (props.current?.version ?? 0);
|
||||
return (
|
||||
<main className="mx-auto flex w-full max-w-6xl flex-col gap-6 p-5 lg:p-8">
|
||||
<Head title="Perfis de revisão das urgências" />
|
||||
<PageTitle
|
||||
eyebrow="Administração"
|
||||
title="Revisão posterior das urgências"
|
||||
description="Designe os perfis da direcção de Compras que devem efectuar a revisão. A designação utiliza funções existentes e não concede permissões."
|
||||
/>
|
||||
<Link className="underline" href="/requisicoes/urgencias/revisoes">
|
||||
Consultar as urgências
|
||||
</Link>
|
||||
<Panel
|
||||
title={`Designação actual · versão ${props.current?.version ?? 0}`}
|
||||
description="A revisão fica disponível após a decisão final da requisição, incluindo rejeição ou expiração, para cada ciclo concluído."
|
||||
>
|
||||
<form
|
||||
ref={ref}
|
||||
className="space-y-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
const data = {
|
||||
...form.data,
|
||||
operation_key:
|
||||
form.data.operation_key || crypto.randomUUID(),
|
||||
};
|
||||
form.setData(data);
|
||||
form.transform(() => data);
|
||||
form.post('/administracao/revisao-urgencias', {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
const next = {
|
||||
...data,
|
||||
operation_key: '',
|
||||
version: data.version + 1,
|
||||
reason: '',
|
||||
};
|
||||
form.setData(next);
|
||||
form.setDefaults(next);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
{!current && (
|
||||
<p role="alert">
|
||||
A designação mudou. Confira a versão actual.
|
||||
</p>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
if (
|
||||
form.isDirty &&
|
||||
!window.confirm(
|
||||
'Descartar esta preparação e usar a designação actual?',
|
||||
)
|
||||
)
|
||||
return;
|
||||
form.setData({
|
||||
operation_key: '',
|
||||
version: props.current?.version ?? 0,
|
||||
enabled: props.current?.state === 'active',
|
||||
profile_ids:
|
||||
props.current?.data.profile_ids ?? [],
|
||||
reason: '',
|
||||
});
|
||||
}}
|
||||
>
|
||||
Preparar designação actual
|
||||
</Button>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.enabled}
|
||||
onChange={(event) =>
|
||||
form.setData('enabled', event.target.checked)
|
||||
}
|
||||
/>
|
||||
Aplicar esta designação
|
||||
</label>
|
||||
<fieldset className="space-y-3">
|
||||
<legend className="mb-3 font-semibold">
|
||||
Perfis responsáveis
|
||||
</legend>
|
||||
{props.profiles.length === 0 && (
|
||||
<p>
|
||||
Configure os perfis da empresa antes de efectuar
|
||||
a designação.
|
||||
</p>
|
||||
)}
|
||||
{props.profiles.map((profile) => (
|
||||
<label key={profile.id} className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.profile_ids.includes(
|
||||
profile.id,
|
||||
)}
|
||||
onChange={(event) =>
|
||||
form.setData(
|
||||
'profile_ids',
|
||||
event.target.checked
|
||||
? [
|
||||
...form.data.profile_ids,
|
||||
profile.id,
|
||||
]
|
||||
: form.data.profile_ids.filter(
|
||||
(id) => id !== profile.id,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
{profile.name}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
<p className="text-sm">
|
||||
O interveniente precisa também da função de Compras, de
|
||||
atribuição válida e do acesso ao pedido. Sem esses
|
||||
requisitos, o perfil seleccionado não pode registar a
|
||||
revisão.
|
||||
</p>
|
||||
<label className="block">
|
||||
Motivo desta versão
|
||||
<textarea
|
||||
className={controlClass}
|
||||
required
|
||||
minLength={10}
|
||||
maxLength={4000}
|
||||
value={form.data.reason}
|
||||
onChange={(event) =>
|
||||
form.setData('reason', event.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<Button disabled={form.processing || !current}>
|
||||
Guardar designação
|
||||
</Button>
|
||||
</form>
|
||||
</Panel>
|
||||
<Panel title="Versões preservadas">
|
||||
<ul className="space-y-3">
|
||||
{props.history.data.map((row) => (
|
||||
<li key={row.id}>
|
||||
Versão {row.version} ·{' '}
|
||||
{row.state === 'active' ? 'Activa' : 'Inactiva'} ·{' '}
|
||||
{row.reason}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<nav className="mt-4 flex gap-4">
|
||||
{props.history.prev_page_url && (
|
||||
<Link
|
||||
preserveState
|
||||
preserveScroll
|
||||
className="underline"
|
||||
href={props.history.prev_page_url}
|
||||
>
|
||||
Anterior
|
||||
</Link>
|
||||
)}
|
||||
{props.history.next_page_url && (
|
||||
<Link
|
||||
preserveState
|
||||
preserveScroll
|
||||
className="underline"
|
||||
href={props.history.next_page_url}
|
||||
>
|
||||
Seguinte
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
</Panel>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,14 @@
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
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,
|
||||
@@ -44,18 +53,34 @@ type Payment = {
|
||||
evidence_reference: string | null;
|
||||
supplier_bank_detail_id: number;
|
||||
};
|
||||
function Review({ id }: { id: number }) {
|
||||
const form = useForm({
|
||||
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`);
|
||||
form.post(`/pagamentos/${id}/conferir`, {
|
||||
onSuccess: () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
router.remember(initial, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
@@ -95,14 +120,28 @@ function Review({ id }: { id: number }) {
|
||||
</form>
|
||||
);
|
||||
}
|
||||
export default function Payments({
|
||||
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;
|
||||
@@ -110,18 +149,12 @@ export default function Payments({
|
||||
focusPaymentId?: number | null;
|
||||
focusInvoiceId?: number | null;
|
||||
}) {
|
||||
const [invoiceId, setInvoiceId] = useState(
|
||||
const [invoiceId, setInvoiceId] = useRemember(
|
||||
focusInvoiceId === null ? '' : String(focusInvoiceId),
|
||||
`${identity}:invoice`,
|
||||
);
|
||||
const form = useForm({
|
||||
supplier_bank_detail_id:
|
||||
invoices.find((i) => i.id === focusInvoiceId)?.bank_id ?? 0,
|
||||
amount: '',
|
||||
paid_on: '',
|
||||
external_reference: '',
|
||||
evidence_reference: '',
|
||||
});
|
||||
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" />
|
||||
@@ -192,172 +225,46 @@ export default function Payments({
|
||||
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."
|
||||
>
|
||||
<form
|
||||
className="grid gap-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post(`/facturas/${invoiceId}/pagamentos`, {
|
||||
onSuccess: () => {
|
||||
form.reset();
|
||||
setInvoiceId('');
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
<label>
|
||||
Factura
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={invoiceId}
|
||||
onChange={(e) => {
|
||||
setInvoiceId(e.target.value);
|
||||
form.setData(
|
||||
'supplier_bank_detail_id',
|
||||
invoices.find(
|
||||
(i) =>
|
||||
String(i.id) ===
|
||||
e.target.value,
|
||||
)?.bank_id ?? 0,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<option value="">Seleccionar</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>
|
||||
{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.bank_state !== 'approved' ||
|
||||
form.processing
|
||||
}
|
||||
<label className="mb-4 grid gap-1">
|
||||
Factura
|
||||
<select
|
||||
form="external-payment-registration"
|
||||
required
|
||||
className={controlClass}
|
||||
value={invoiceId}
|
||||
onChange={(e) => {
|
||||
setInvoiceId(e.target.value);
|
||||
}}
|
||||
>
|
||||
Registar para conferência independente
|
||||
</Button>
|
||||
</form>
|
||||
<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) => (
|
||||
@@ -384,7 +291,7 @@ export default function Payments({
|
||||
Evidência: {p.evidence_reference}
|
||||
</p>
|
||||
)}
|
||||
{p.canReview && <Review id={p.id} />}
|
||||
{p.canReview && <Review payment={p} />}
|
||||
{expenseAllocationsReady &&
|
||||
p.status === 'confirmed' && (
|
||||
<Link
|
||||
@@ -402,3 +309,146 @@ export default function Payments({
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import { Head, Link, router, useForm, usePage } from '@inertiajs/react';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import type { WorkContextState } from '@/types/work-context';
|
||||
import { PageTitle, Panel } from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
@@ -42,19 +45,53 @@ const states: Record<string, string> = {
|
||||
cancelled: 'Cancelado',
|
||||
};
|
||||
|
||||
function ReasonForm({
|
||||
function useControlIdentity() {
|
||||
const page = usePage().props;
|
||||
const actor = page.auth?.user;
|
||||
const actorId = typeof page.actorId === 'number' ? page.actorId : actor?.id;
|
||||
const context = page.workContext as WorkContextState | null | undefined;
|
||||
const permissions = Array.isArray(page.permissions)
|
||||
? page.permissions
|
||||
.filter((p) => typeof p === 'string')
|
||||
.sort()
|
||||
.join(',')
|
||||
: '';
|
||||
return `purchase-controls:${actor?.tenant_id}:${actorId}:${context?.active ?? 'legacy'}:${permissions}`;
|
||||
}
|
||||
|
||||
function ReasonForm(input: { url: string; decisions?: boolean }) {
|
||||
const identity = `${useControlIdentity()}:reason:${input.url}:${input.decisions ?? false}`;
|
||||
return <ReasonFields key={identity} {...input} identity={identity} />;
|
||||
}
|
||||
|
||||
function ReasonFields({
|
||||
url,
|
||||
decisions = false,
|
||||
identity,
|
||||
}: {
|
||||
url: string;
|
||||
decisions?: boolean;
|
||||
identity: string;
|
||||
}) {
|
||||
const form = useForm({ reason: '', decision: 'approved' });
|
||||
const initial = { reason: '', decision: 'approved' };
|
||||
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'}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
form.post(url, { preserveScroll: true });
|
||||
form.post(url, {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
router.remember(initial, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
className="mt-3 space-y-3"
|
||||
>
|
||||
@@ -98,20 +135,48 @@ function ReasonForm({
|
||||
}
|
||||
|
||||
function PolicyForm({ previousId }: { previousId: number }) {
|
||||
const form = useForm({
|
||||
const identity = `${useControlIdentity()}:policy:${previousId}`;
|
||||
return (
|
||||
<PolicyFields
|
||||
key={identity}
|
||||
previousId={previousId}
|
||||
identity={identity}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function PolicyFields({
|
||||
previousId,
|
||||
identity,
|
||||
}: {
|
||||
previousId: number;
|
||||
identity: string;
|
||||
}) {
|
||||
const initial = {
|
||||
previous_id: previousId,
|
||||
mode: 'unissued_award',
|
||||
enabled: false,
|
||||
valid_from: '',
|
||||
valid_until: '',
|
||||
reason: '',
|
||||
});
|
||||
};
|
||||
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'}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
form.post('/revisao-compras/politicas', {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
router.remember(initial, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
className="grid gap-4 sm:grid-cols-2"
|
||||
@@ -170,12 +235,29 @@ function PolicyForm({ previousId }: { previousId: number }) {
|
||||
}
|
||||
|
||||
function RevisionForm({ id }: { id: number }) {
|
||||
const form = useForm({ needed_by: '', justification: '' });
|
||||
const identity = `${useControlIdentity()}:revision:${id}`;
|
||||
return <RevisionFields key={identity} id={id} identity={identity} />;
|
||||
}
|
||||
|
||||
function RevisionFields({ id, identity }: { id: number; identity: string }) {
|
||||
const initial = { needed_by: '', justification: '' };
|
||||
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'}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
form.post(`/cancelamentos/${id}/revisao`);
|
||||
form.post(`/cancelamentos/${id}/revisao`, {
|
||||
onSuccess: () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
router.remember(initial, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
className="mt-3 grid gap-3"
|
||||
>
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import { Head, Link, router, useForm, usePage } from '@inertiajs/react';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import type { WorkContextState } from '@/types/work-context';
|
||||
import {
|
||||
Panel,
|
||||
PageTitle,
|
||||
@@ -31,14 +34,38 @@ type Policy = {
|
||||
};
|
||||
|
||||
function Decision({ url }: { url: string }) {
|
||||
const form = useForm({ decision: 'rejected', reason: '' });
|
||||
const identity = `${useOrderControlIdentity()}:decision:${url}`;
|
||||
return <DecisionFields key={identity} url={url} identity={identity} />;
|
||||
}
|
||||
|
||||
function useOrderControlIdentity() {
|
||||
const page = usePage().props;
|
||||
const actor = page.auth?.user;
|
||||
const context = page.workContext as WorkContextState | null | undefined;
|
||||
return `order-cancellations:${actor?.tenant_id}:${actor?.id}:${context?.active ?? 'legacy'}:${page.canAdminister === true}`;
|
||||
}
|
||||
|
||||
function DecisionFields({ url, identity }: { url: string; identity: string }) {
|
||||
const initial = { decision: 'rejected', reason: '' };
|
||||
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-3 space-y-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (window.confirm('Confirmar esta decisão definitiva?'))
|
||||
form.post(url);
|
||||
form.post(url, {
|
||||
onSuccess: () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
router.remember(initial, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
@@ -74,13 +101,38 @@ function Decision({ url }: { url: string }) {
|
||||
}
|
||||
|
||||
function Revision({ record }: { record: Record }) {
|
||||
const form = useForm({ needed_by: '', reason: '' });
|
||||
const identity = `${useOrderControlIdentity()}:revision:${record.id}:${record.status}:${record.revised_requisition_id ?? 0}`;
|
||||
return (
|
||||
<RevisionFields key={identity} record={record} identity={identity} />
|
||||
);
|
||||
}
|
||||
|
||||
function RevisionFields({
|
||||
record,
|
||||
identity,
|
||||
}: {
|
||||
record: Record;
|
||||
identity: string;
|
||||
}) {
|
||||
const initial = { needed_by: '', reason: '' };
|
||||
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-3 space-y-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
form.post(`/ordens/cancelamentos/${record.id}/rever`);
|
||||
form.post(`/ordens/cancelamentos/${record.id}/rever`, {
|
||||
onSuccess: () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
router.remember(initial, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
@@ -118,11 +170,7 @@ function Revision({ record }: { record: Record }) {
|
||||
);
|
||||
}
|
||||
|
||||
export default function OrderCancellations({
|
||||
records,
|
||||
policies,
|
||||
canAdminister,
|
||||
}: {
|
||||
type Props = {
|
||||
records: {
|
||||
data: Record[];
|
||||
prev_page_url: string | null;
|
||||
@@ -130,15 +178,37 @@ export default function OrderCancellations({
|
||||
};
|
||||
policies: Policy[];
|
||||
canAdminister: boolean;
|
||||
}) {
|
||||
const policy = useForm({
|
||||
};
|
||||
|
||||
export default function OrderCancellationsPage(props: Props) {
|
||||
const identity = useOrderControlIdentity();
|
||||
return (
|
||||
<OrderCancellations
|
||||
key={`${identity}:policy:${props.policies[0]?.id ?? 0}`}
|
||||
{...props}
|
||||
identity={identity}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function OrderCancellations({
|
||||
records,
|
||||
policies,
|
||||
canAdminister,
|
||||
identity,
|
||||
}: Props & { identity: string }) {
|
||||
const policyKey = `${identity}:policy:${policies[0]?.id ?? 0}`;
|
||||
const initial = {
|
||||
previous_id: policies[0]?.id ?? 0,
|
||||
mode: 'issued_order',
|
||||
enabled: false,
|
||||
valid_from: '',
|
||||
valid_until: '',
|
||||
reason: '',
|
||||
});
|
||||
};
|
||||
const policy = useForm(policyKey, initial);
|
||||
const dirty = hasPreparationChanges(initial, policy.data);
|
||||
const ref = usePreparationDirty(dirty, canAdminister);
|
||||
const labels: { [key: string]: string } = {
|
||||
pending: 'Pendente',
|
||||
approved: 'Aprovado',
|
||||
@@ -242,6 +312,10 @@ export default function OrderCancellations({
|
||||
<details className="mt-4">
|
||||
<summary>Propor nova versão</summary>
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={
|
||||
dirty ? 'true' : 'false'
|
||||
}
|
||||
className="mt-3 space-y-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
@@ -251,6 +325,20 @@ export default function OrderCancellations({
|
||||
}));
|
||||
policy.post(
|
||||
'/ordens/cancelamentos/politicas',
|
||||
{
|
||||
onSuccess: () => {
|
||||
policy.setData(initial);
|
||||
policy.clearErrors();
|
||||
router.remember(
|
||||
initial,
|
||||
`${policyKey}:data`,
|
||||
);
|
||||
router.remember(
|
||||
{},
|
||||
`${policyKey}:errors`,
|
||||
);
|
||||
},
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
@@ -325,7 +413,7 @@ export default function OrderCancellations({
|
||||
</>
|
||||
);
|
||||
}
|
||||
OrderCancellations.layout = {
|
||||
OrderCancellationsPage.layout = {
|
||||
breadcrumbs: [
|
||||
{ title: 'Ordens', href: '/ordens' },
|
||||
{ title: 'Cancelamentos', href: '/ordens/cancelamentos' },
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Head, Link, useForm, usePage } from '@inertiajs/react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import BudgetDistributionFields, {
|
||||
type BudgetDistributionOption,
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { money } from '@/types/procurement';
|
||||
|
||||
export default function Amendment({
|
||||
function AmendmentContent({
|
||||
order,
|
||||
options,
|
||||
planHash,
|
||||
@@ -58,15 +58,8 @@ export default function Amendment({
|
||||
`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]);
|
||||
const formElement = usePreparationDirty(dirty);
|
||||
return (
|
||||
<>
|
||||
<Head title={`Reafectação · ${order.number}`} />
|
||||
@@ -85,6 +78,7 @@ export default function Amendment({
|
||||
<FormErrors errors={form.errors} />
|
||||
<form
|
||||
ref={formElement}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="space-y-5"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
@@ -142,3 +136,15 @@ export default function Amendment({
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Amendment(
|
||||
props: Parameters<typeof AmendmentContent>[0],
|
||||
) {
|
||||
const actor = usePage().props.auth?.user;
|
||||
return (
|
||||
<AmendmentContent
|
||||
key={`distribution-amendment:${actor?.tenant_id}:${actor?.id}:${props.order.id}:${props.planHash}`}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Head, Link, useForm, usePage } from '@inertiajs/react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { FormErrors, PageTitle, Panel } from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
@@ -18,7 +19,7 @@ type Source = {
|
||||
}[];
|
||||
};
|
||||
|
||||
export default function Amendment({
|
||||
function AmendmentContent({
|
||||
order,
|
||||
sources,
|
||||
history,
|
||||
@@ -41,41 +42,28 @@ export default function Amendment({
|
||||
}[];
|
||||
}) {
|
||||
const actor = usePage().props.auth?.user;
|
||||
const initial = {
|
||||
operation_key: crypto.randomUUID(),
|
||||
reason: '',
|
||||
sources: sources.map((source) => ({
|
||||
origin: source.origin,
|
||||
version: source.version,
|
||||
plan_hash: source.plan_hash,
|
||||
allocations: source.allocations.map(
|
||||
({ allocation_key, subtotal, total }) => ({
|
||||
allocation_key,
|
||||
subtotal,
|
||||
total,
|
||||
}),
|
||||
),
|
||||
})),
|
||||
};
|
||||
const form = useForm(
|
||||
`order-parts-amendment:${actor?.tenant_id}:${actor?.id}:${order.id}:${sources.map((s) => `${s.origin}:${s.version}:${s.plan_hash}`).join(',')}`,
|
||||
{
|
||||
operation_key: crypto.randomUUID(),
|
||||
reason: '',
|
||||
sources: sources.map((source) => ({
|
||||
origin: source.origin,
|
||||
version: source.version,
|
||||
plan_hash: source.plan_hash,
|
||||
allocations: source.allocations.map(
|
||||
({ allocation_key, subtotal, total }) => ({
|
||||
allocation_key,
|
||||
subtotal,
|
||||
total,
|
||||
}),
|
||||
),
|
||||
})),
|
||||
},
|
||||
initial,
|
||||
);
|
||||
const ref = useRef<HTMLFormElement>(null);
|
||||
useEffect(() => {
|
||||
const current = ref.current;
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('sgc:context-dirty', {
|
||||
detail: { form: current, dirty: form.isDirty },
|
||||
}),
|
||||
);
|
||||
return () => {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('sgc:context-dirty', {
|
||||
detail: { form: current, dirty: false },
|
||||
}),
|
||||
);
|
||||
};
|
||||
}, [form.isDirty]);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty);
|
||||
const update = (
|
||||
origin: number,
|
||||
allocation: number,
|
||||
@@ -115,6 +103,7 @@ export default function Amendment({
|
||||
</p>
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="grid gap-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
@@ -261,3 +250,11 @@ export default function Amendment({
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Amendment(
|
||||
props: Parameters<typeof AmendmentContent>[0],
|
||||
) {
|
||||
const actor = usePage().props.auth?.user;
|
||||
const identity = `order-parts-amendment:${actor?.tenant_id}:${actor?.id}:${props.order.id}:${props.sources.map((source) => `${source.origin}:${source.version}:${source.plan_hash}`).join(',')}`;
|
||||
return <AmendmentContent key={identity} {...props} />;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Head, Link, useForm, usePage } from '@inertiajs/react';
|
||||
import { useEffect, useRef, type RefObject } from 'react';
|
||||
import { useEffect } from 'react';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { FormErrors, PageTitle, Panel } from '@/components/procurement';
|
||||
@@ -79,22 +80,6 @@ type Props = {
|
||||
preview: Preview | null;
|
||||
};
|
||||
|
||||
function useGuard(ref: RefObject<HTMLFormElement | null>, 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({
|
||||
source,
|
||||
currency,
|
||||
@@ -226,7 +211,6 @@ function Prepared({
|
||||
})),
|
||||
};
|
||||
const form = useForm(historyKey, initial);
|
||||
const ref = useRef<HTMLFormElement>(null);
|
||||
const changed = form.data.budget_sources.some((source, i) =>
|
||||
source.allocations.some(
|
||||
(row, j) =>
|
||||
@@ -235,7 +219,7 @@ function Prepared({
|
||||
row.total !== initial.budget_sources[i]?.allocations[j]?.total,
|
||||
),
|
||||
);
|
||||
useGuard(ref, changed);
|
||||
const ref = usePreparationDirty(changed);
|
||||
return (
|
||||
<div id="order-parts-review" tabIndex={-1} className="scroll-mt-24">
|
||||
<Panel title="Conferir e emitir a ordem">
|
||||
@@ -247,6 +231,7 @@ function Prepared({
|
||||
</p>
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={changed ? 'true' : 'false'}
|
||||
className="grid min-w-0 gap-5"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
@@ -489,14 +474,14 @@ function Prepared({
|
||||
);
|
||||
}
|
||||
|
||||
export default function Parts({ candidates, preview }: Props) {
|
||||
function PartsContent({ 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<HTMLFormElement>(null);
|
||||
useGuard(ref, form.data.sources.length > 0);
|
||||
const dirty = form.data.sources.length > 0;
|
||||
const ref = usePreparationDirty(dirty);
|
||||
useEffect(() => {
|
||||
if (preview) {
|
||||
const review = document.getElementById('order-parts-review');
|
||||
@@ -520,6 +505,7 @@ export default function Parts({ candidates, preview }: Props) {
|
||||
<Panel title="Escolher origens e quantidades">
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="grid min-w-0 gap-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
@@ -739,3 +725,13 @@ export default function Parts({ candidates, preview }: Props) {
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Parts(props: Props) {
|
||||
const actor = usePage().props.auth?.user;
|
||||
return (
|
||||
<PartsContent
|
||||
key={`order-parts:${actor?.tenant_id}:${actor?.id}`}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import { ExchangeSummary } from '@/components/quotation-exchange-panel';
|
||||
import type { PurchaseOrder } from '@/types/purchase';
|
||||
import ImportTariffSummary from '@/components/import-tariff-summary';
|
||||
import CapitalAssignmentSummary from '@/components/capital-assignment-summary';
|
||||
import RequisitionAccountSummary from '@/components/requisition-account-summary';
|
||||
import OrderCancellationRequest, {
|
||||
type OrderCancellationState,
|
||||
} from '@/components/order-cancellation-request';
|
||||
@@ -175,6 +176,9 @@ export default function OrderShow({
|
||||
<CapitalAssignmentSummary
|
||||
records={snapshot.capital_assignments}
|
||||
/>
|
||||
<RequisitionAccountSummary
|
||||
records={snapshot.account_assignments}
|
||||
/>
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
{snapshot.investment_rules && (
|
||||
<Panel title="Regra de investimento congelada">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Head, Link, useForm, usePage, useRemember } from '@inertiajs/react';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { ComparisonPolicySummary } from '@/components/comparison-policy-summary';
|
||||
import type { ComparisonPolicy } from '@/components/comparison-policy-summary';
|
||||
import { QuotationCommercialTerms } from '@/components/quotation-commercial-terms';
|
||||
@@ -19,6 +19,8 @@ import {
|
||||
QuotationExchangePanel,
|
||||
} from '@/components/quotation-exchange-panel';
|
||||
import type { ExchangeBasis } from '@/components/quotation-exchange-panel';
|
||||
import { QuotationEvaluationForm } from '@/components/quotation-evaluation-form';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
|
||||
type Item = {
|
||||
id: number;
|
||||
@@ -64,7 +66,7 @@ type Quote = {
|
||||
ineligibility_reasons: string[];
|
||||
commercial_terms: CommercialTerms | null;
|
||||
};
|
||||
export default function Comparison({
|
||||
function ComparisonContent({
|
||||
requisition,
|
||||
quotations,
|
||||
suppliers,
|
||||
@@ -82,6 +84,7 @@ export default function Comparison({
|
||||
id: number;
|
||||
number: string;
|
||||
justification: string;
|
||||
process_version?: number;
|
||||
items: Item[];
|
||||
};
|
||||
quotations: Quote[];
|
||||
@@ -97,9 +100,17 @@ export default function Comparison({
|
||||
exchangeAvailable?: boolean;
|
||||
canRecordExchange?: boolean;
|
||||
}) {
|
||||
const [adding, setAdding] = useState(prepare && canCreate);
|
||||
const [selected, setSelected] = useState<number | null>(focusQuotationId);
|
||||
const form = useForm({
|
||||
const actor = usePage().props.auth?.user;
|
||||
const historyKey = `quotation-preparation:${actor?.tenant_id}:${actor?.id}:${requisition.id}:${requisition.process_version ?? 0}`;
|
||||
const [adding, setAdding] = useRemember(
|
||||
prepare && canCreate,
|
||||
`${historyKey}:adding`,
|
||||
);
|
||||
const [selected, setSelected] = useRemember<number | null>(
|
||||
focusQuotationId,
|
||||
`${historyKey}:selected`,
|
||||
);
|
||||
const form = useForm(historyKey, {
|
||||
currency: 'MZN',
|
||||
supplier_id: '',
|
||||
reference: '',
|
||||
@@ -114,13 +125,10 @@ export default function Comparison({
|
||||
discount_value: '0',
|
||||
})),
|
||||
});
|
||||
const evaluation = useForm({
|
||||
quality: '5',
|
||||
history: '5',
|
||||
payment: '5',
|
||||
comment: '',
|
||||
no_conflict: false,
|
||||
});
|
||||
const preparationRef = usePreparationDirty(
|
||||
form.isDirty,
|
||||
adding && canCreate,
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<Head title={`Cotações · ${requisition.number}`} />
|
||||
@@ -217,6 +225,7 @@ export default function Comparison({
|
||||
description="Valores na moeda seleccionada, com duas casas decimais. Quantidades e IVA herdados da requisição. Desconto por unidade antes do IVA; preço líquido arredondado ao centavo antes de multiplicar pela quantidade. Preencha todas as linhas."
|
||||
>
|
||||
<form
|
||||
ref={preparationRef}
|
||||
className="space-y-5"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -247,6 +256,17 @@ export default function Comparison({
|
||||
}
|
||||
>
|
||||
<option value="MZN">MZN</option>
|
||||
{form.data.currency !== 'MZN' &&
|
||||
!exchangeRates.some(
|
||||
(rate) =>
|
||||
rate.currency ===
|
||||
form.data.currency,
|
||||
) && (
|
||||
<option value={form.data.currency}>
|
||||
{form.data.currency} · taxa
|
||||
indisponível nesta consulta
|
||||
</option>
|
||||
)}
|
||||
{exchangeRates.map((rate) => (
|
||||
<option
|
||||
key={rate.id}
|
||||
@@ -275,6 +295,22 @@ export default function Comparison({
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
{form.data.supplier_id !== '' &&
|
||||
!suppliers.some(
|
||||
(supplier) =>
|
||||
String(supplier.id) ===
|
||||
form.data.supplier_id,
|
||||
) && (
|
||||
<option
|
||||
value={
|
||||
form.data
|
||||
.supplier_id
|
||||
}
|
||||
>
|
||||
Fornecedor preservado ·
|
||||
confirme a elegibilidade
|
||||
</option>
|
||||
)}
|
||||
{suppliers.map((s) => (
|
||||
<option value={s.id} key={s.id}>
|
||||
{s.name}
|
||||
@@ -508,6 +544,7 @@ export default function Comparison({
|
||||
{exchangeAvailable && (
|
||||
<QuotationExchangePanel
|
||||
requisitionId={requisition.id}
|
||||
processVersion={requisition.process_version ?? 0}
|
||||
rates={exchangeRates}
|
||||
canRecord={canRecordExchange}
|
||||
/>
|
||||
@@ -602,8 +639,6 @@ export default function Comparison({
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setSelected(q.id);
|
||||
evaluation.reset();
|
||||
evaluation.clearErrors();
|
||||
}}
|
||||
>
|
||||
Detalhe
|
||||
@@ -685,106 +720,11 @@ export default function Comparison({
|
||||
</div>
|
||||
))}
|
||||
{q.canEvaluate && (
|
||||
<form
|
||||
className="mt-5 space-y-4 border-t pt-5"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
evaluation.post(
|
||||
`/cotacoes/${q.id}/avaliar`,
|
||||
{
|
||||
onSuccess: () =>
|
||||
evaluation.reset(),
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
<FormErrors
|
||||
errors={evaluation.errors}
|
||||
/>
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
{(
|
||||
[
|
||||
[
|
||||
'quality',
|
||||
'Qualidade técnica',
|
||||
],
|
||||
[
|
||||
'history',
|
||||
'Histórico (5 para novo)',
|
||||
],
|
||||
[
|
||||
'payment',
|
||||
'Condições de pagamento',
|
||||
],
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<div
|
||||
className="space-y-2"
|
||||
key={key}
|
||||
>
|
||||
<Label htmlFor={key}>
|
||||
{label} · 0 a 10
|
||||
</Label>
|
||||
<Input
|
||||
id={key}
|
||||
type="number"
|
||||
min="0"
|
||||
max="10"
|
||||
step="0.01"
|
||||
required
|
||||
value={
|
||||
evaluation.data[key]
|
||||
}
|
||||
onChange={(e) =>
|
||||
evaluation.setData(
|
||||
key,
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<Label htmlFor="comment">
|
||||
Fundamento da avaliação
|
||||
</Label>
|
||||
<textarea
|
||||
id="comment"
|
||||
className={controlClass}
|
||||
required
|
||||
minLength={10}
|
||||
value={evaluation.data.comment}
|
||||
onChange={(e) =>
|
||||
evaluation.setData(
|
||||
'comment',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
<label className="flex items-start gap-3 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
required
|
||||
checked={
|
||||
evaluation.data.no_conflict
|
||||
}
|
||||
onChange={(e) =>
|
||||
evaluation.setData(
|
||||
'no_conflict',
|
||||
e.target.checked,
|
||||
)
|
||||
}
|
||||
/>
|
||||
Declaro não ter conflito de
|
||||
interesses e confirmo a minha
|
||||
avaliação independente.
|
||||
</label>
|
||||
<Button
|
||||
disabled={evaluation.processing}
|
||||
>
|
||||
Registar avaliação
|
||||
</Button>
|
||||
</form>
|
||||
<QuotationEvaluationForm
|
||||
key={`${actor?.tenant_id}:${actor?.id}:${requisition.id}:${q.id}`}
|
||||
requisitionId={requisition.id}
|
||||
quotationId={q.id}
|
||||
/>
|
||||
)}
|
||||
</Panel>
|
||||
</div>
|
||||
@@ -793,6 +733,17 @@ export default function Comparison({
|
||||
</>
|
||||
);
|
||||
}
|
||||
export default function Comparison(
|
||||
props: ComponentProps<typeof ComparisonContent>,
|
||||
) {
|
||||
const actor = usePage().props.auth?.user;
|
||||
return (
|
||||
<ComparisonContent
|
||||
key={`${actor?.tenant_id}:${actor?.id}:${props.requisition.id}:${props.requisition.process_version ?? 0}`}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
Comparison.layout = {
|
||||
breadcrumbs: [
|
||||
{ title: 'Cotações', href: '/cotacoes' },
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import { Head, Link, useForm, usePage } from '@inertiajs/react';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import {
|
||||
receiptPreparationKey,
|
||||
receiptPreparationChanged,
|
||||
} from '@/lib/receipt-preparation';
|
||||
import { ReceiptConversionFields } from '@/components/receipt-conversion';
|
||||
import type { ReceiptConversion } from '@/components/receipt-conversion';
|
||||
import { InventoryNotice, ReceiptProgressTable } from '@/components/inventory';
|
||||
@@ -50,7 +55,7 @@ type Props = {
|
||||
quarantine_on_receipt: boolean;
|
||||
}[];
|
||||
};
|
||||
export default function ReceiveOrder({
|
||||
function ReceiveOrderContent({
|
||||
order,
|
||||
supplier_name,
|
||||
progress,
|
||||
@@ -61,7 +66,14 @@ export default function ReceiveOrder({
|
||||
conversionQaEnabled = false,
|
||||
lotScopes,
|
||||
}: Props) {
|
||||
const form = useForm({
|
||||
const actor = usePage().props.auth?.user;
|
||||
const historyKey = receiptPreparationKey(
|
||||
actor?.tenant_id,
|
||||
actor?.id,
|
||||
order.id,
|
||||
progress,
|
||||
);
|
||||
const initialData = {
|
||||
idempotency_key: crypto.randomUUID(),
|
||||
delivery_note: '',
|
||||
received_on: '',
|
||||
@@ -82,7 +94,12 @@ export default function ReceiveOrder({
|
||||
},
|
||||
lots: [] as Line['lots'],
|
||||
})),
|
||||
});
|
||||
};
|
||||
const form = useForm(historyKey, initialData);
|
||||
const preparationRef = usePreparationDirty(
|
||||
receiptPreparationChanged(initialData, form.data),
|
||||
canConfirm,
|
||||
);
|
||||
const change = (index: number, updates: Partial<Line>) =>
|
||||
form.setData(
|
||||
'items',
|
||||
@@ -117,6 +134,7 @@ export default function ReceiveOrder({
|
||||
description="A confirmação é definitiva e auditada. O emitente da ordem não pode confirmar a recepção."
|
||||
>
|
||||
<form
|
||||
ref={preparationRef}
|
||||
className="space-y-5"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -899,6 +917,20 @@ export default function ReceiveOrder({
|
||||
</>
|
||||
);
|
||||
}
|
||||
export default function ReceiveOrder(props: Props) {
|
||||
const actor = usePage().props.auth?.user;
|
||||
return (
|
||||
<ReceiveOrderContent
|
||||
key={receiptPreparationKey(
|
||||
actor?.tenant_id,
|
||||
actor?.id,
|
||||
props.order.id,
|
||||
props.progress,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
ReceiveOrder.layout = {
|
||||
breadcrumbs: [
|
||||
{ title: 'Recepção', href: '/recepcoes' },
|
||||
|
||||
@@ -0,0 +1,507 @@
|
||||
import { Head, Link, router, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import {
|
||||
FormErrors,
|
||||
PageTitle,
|
||||
Panel,
|
||||
controlClass,
|
||||
} from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { exactMinorAmount } from '@/components/procurement-payable-insights';
|
||||
|
||||
type Account = {
|
||||
id: number;
|
||||
code: string;
|
||||
label: string;
|
||||
currency: string;
|
||||
source_hash: string;
|
||||
};
|
||||
type Allocation = {
|
||||
account: Account;
|
||||
subtotal_minor: string;
|
||||
total_minor: string;
|
||||
};
|
||||
type Version = {
|
||||
id: number;
|
||||
version: number;
|
||||
reason: string;
|
||||
data: { requisition_item_id: number; allocations: Allocation[] };
|
||||
};
|
||||
type Page<T> = {
|
||||
data: T[];
|
||||
prev_page_url: string | null;
|
||||
next_page_url: string | null;
|
||||
};
|
||||
type Props = {
|
||||
requisition: { id: number; number: string; status: string };
|
||||
items: {
|
||||
id: number;
|
||||
description: string;
|
||||
subtotal_minor: string;
|
||||
total_minor: string;
|
||||
basis_hash: string;
|
||||
}[];
|
||||
current: Version[];
|
||||
history: Page<Version>;
|
||||
accounts: Page<Account> | null;
|
||||
canWrite: boolean;
|
||||
search: string;
|
||||
actorId: number;
|
||||
tenantId: number;
|
||||
};
|
||||
type InputAllocation = {
|
||||
account_id: number;
|
||||
source_hash: string;
|
||||
label: string;
|
||||
subtotal: string;
|
||||
total: string;
|
||||
};
|
||||
|
||||
export default function RequisitionAccounts(props: Props) {
|
||||
const url = `/requisicoes/${props.requisition.id}/contas`;
|
||||
const form = useForm(
|
||||
`req-accounts:${props.tenantId}:${props.actorId}:${props.requisition.id}`,
|
||||
{
|
||||
item_id: '',
|
||||
basis_hash: '',
|
||||
version: 0,
|
||||
reason: '',
|
||||
operation_key: '',
|
||||
allocations: [] as InputAllocation[],
|
||||
},
|
||||
);
|
||||
const ref = useRef<HTMLFormElement>(null);
|
||||
useEffect(() => {
|
||||
const node = ref.current;
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('sgc:context-dirty', {
|
||||
detail: { form: node, dirty: form.isDirty },
|
||||
}),
|
||||
);
|
||||
return () => {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('sgc:context-dirty', {
|
||||
detail: { form: node, dirty: false },
|
||||
}),
|
||||
);
|
||||
};
|
||||
}, [form.isDirty]);
|
||||
const selected = props.items.find(
|
||||
(line) => String(line.id) === form.data.item_id,
|
||||
);
|
||||
const current = props.current.find(
|
||||
(row) => String(row.data.requisition_item_id) === form.data.item_id,
|
||||
);
|
||||
const choose = (id: string) => {
|
||||
if (
|
||||
form.isDirty &&
|
||||
!window.confirm('Descartar a preparação desta linha e abrir outra?')
|
||||
)
|
||||
return;
|
||||
const line = props.items.find((row) => String(row.id) === id);
|
||||
const old = props.current.find(
|
||||
(row) => String(row.data.requisition_item_id) === id,
|
||||
);
|
||||
form.setData({
|
||||
item_id: id,
|
||||
basis_hash: line?.basis_hash ?? '',
|
||||
version: old?.version ?? 0,
|
||||
reason: '',
|
||||
operation_key: '',
|
||||
allocations: [],
|
||||
});
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<Head title="Contas da requisição" />
|
||||
<main className="mx-auto flex w-full max-w-6xl flex-col gap-6 p-5 lg:p-8">
|
||||
<PageTitle
|
||||
eyebrow="Requisição de compra"
|
||||
title="Contas contabilísticas por linha"
|
||||
description={props.requisition.number}
|
||||
/>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/requisicoes/${props.requisition.id}`}
|
||||
>
|
||||
Voltar à requisição
|
||||
</Link>
|
||||
<Panel
|
||||
title="Imputação da necessidade"
|
||||
description="Contas de movimento do núcleo comum na base própria de Compras. As parcelas são explícitas; o registo não cria lançamentos contabilísticos, pagamentos ou alterações da distribuição orçamental."
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
{props.canWrite ? (
|
||||
<form
|
||||
ref={ref}
|
||||
className="space-y-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
const data = {
|
||||
...form.data,
|
||||
operation_key:
|
||||
form.data.operation_key ||
|
||||
crypto.randomUUID(),
|
||||
};
|
||||
form.setData(data);
|
||||
form.transform(() => data);
|
||||
form.post(url, {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
const next = {
|
||||
...data,
|
||||
version: data.version + 1,
|
||||
operation_key: '',
|
||||
};
|
||||
form.setData(next);
|
||||
form.setDefaults(next);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<label className="block">
|
||||
Linha
|
||||
<select
|
||||
className={controlClass}
|
||||
value={form.data.item_id}
|
||||
onChange={(event) =>
|
||||
choose(event.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione a linha</option>
|
||||
{props.items.map((line) => (
|
||||
<option key={line.id} value={line.id}>
|
||||
{line.description}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{selected && (
|
||||
<p>
|
||||
Base sem IVA:{' '}
|
||||
{exactMinorAmount(
|
||||
selected.subtotal_minor,
|
||||
'MZN',
|
||||
)}{' '}
|
||||
· Total:{' '}
|
||||
{exactMinorAmount(
|
||||
selected.total_minor,
|
||||
'MZN',
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{current && (
|
||||
<div>
|
||||
<p>Versão actual: {current.version}</p>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
form.setData(
|
||||
'allocations',
|
||||
current.data.allocations.map(
|
||||
(row) => ({
|
||||
account_id:
|
||||
row.account.id,
|
||||
source_hash:
|
||||
row.account
|
||||
.source_hash,
|
||||
label: `${row.account.code} · ${row.account.label}`,
|
||||
subtotal:
|
||||
(
|
||||
BigInt(
|
||||
row.subtotal_minor,
|
||||
) / 100n
|
||||
).toString() +
|
||||
'.' +
|
||||
(
|
||||
BigInt(
|
||||
row.subtotal_minor,
|
||||
) % 100n
|
||||
)
|
||||
.toString()
|
||||
.padStart(
|
||||
2,
|
||||
'0',
|
||||
),
|
||||
total:
|
||||
(
|
||||
BigInt(
|
||||
row.total_minor,
|
||||
) / 100n
|
||||
).toString() +
|
||||
'.' +
|
||||
(
|
||||
BigInt(
|
||||
row.total_minor,
|
||||
) % 100n
|
||||
)
|
||||
.toString()
|
||||
.padStart(
|
||||
2,
|
||||
'0',
|
||||
),
|
||||
}),
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
Reutilizar parcelas actuais para revisão
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{form.data.allocations.map((row, index) => (
|
||||
<fieldset
|
||||
key={row.account_id}
|
||||
className="grid gap-3 rounded-xl border p-4 sm:grid-cols-2"
|
||||
>
|
||||
<legend className="px-2 break-words">
|
||||
{row.label}
|
||||
</legend>
|
||||
{(['subtotal', 'total'] as const).map(
|
||||
(field) => (
|
||||
<label key={field}>
|
||||
{field === 'subtotal'
|
||||
? 'Base sem IVA (MZN)'
|
||||
: 'Total com IVA (MZN)'}
|
||||
<input
|
||||
className={controlClass}
|
||||
inputMode="decimal"
|
||||
value={row[field]}
|
||||
onChange={(event) =>
|
||||
form.setData(
|
||||
'allocations',
|
||||
form.data.allocations.map(
|
||||
(value, at) =>
|
||||
at === index
|
||||
? {
|
||||
...value,
|
||||
[field]:
|
||||
event
|
||||
.target
|
||||
.value,
|
||||
}
|
||||
: value,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
),
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
if (
|
||||
window.confirm(
|
||||
'Remover esta parcela da preparação?',
|
||||
)
|
||||
)
|
||||
form.setData(
|
||||
'allocations',
|
||||
form.data.allocations.filter(
|
||||
(_, at) => at !== index,
|
||||
),
|
||||
);
|
||||
}}
|
||||
>
|
||||
Remover parcela
|
||||
</Button>
|
||||
</fieldset>
|
||||
))}
|
||||
<label className="block">
|
||||
Motivo da imputação ou correcção
|
||||
<textarea
|
||||
className={controlClass}
|
||||
required
|
||||
minLength={10}
|
||||
maxLength={4000}
|
||||
value={form.data.reason}
|
||||
onChange={(event) =>
|
||||
form.setData(
|
||||
'reason',
|
||||
event.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<Button
|
||||
disabled={
|
||||
form.processing ||
|
||||
!selected ||
|
||||
form.data.allocations.length === 0
|
||||
}
|
||||
>
|
||||
Guardar versão
|
||||
</Button>
|
||||
</form>
|
||||
) : (
|
||||
<p>
|
||||
Consulta das imputações preservadas; a edição
|
||||
pertence ao requisitante enquanto o pedido está em
|
||||
rascunho.
|
||||
</p>
|
||||
)}
|
||||
</Panel>
|
||||
{props.accounts && (
|
||||
<Panel title="Escolher contas do plano de Compras">
|
||||
<form
|
||||
method="get"
|
||||
action={url}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
const search = new FormData(
|
||||
event.currentTarget,
|
||||
).get('account_search');
|
||||
router.get(
|
||||
url,
|
||||
{
|
||||
account_search:
|
||||
typeof search === 'string'
|
||||
? search
|
||||
: '',
|
||||
},
|
||||
{
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
},
|
||||
);
|
||||
}}
|
||||
className="mb-4 flex flex-wrap gap-3"
|
||||
>
|
||||
<label>
|
||||
Código ou designação
|
||||
<input
|
||||
className={controlClass}
|
||||
name="account_search"
|
||||
defaultValue={props.search}
|
||||
maxLength={100}
|
||||
/>
|
||||
</label>
|
||||
<Button variant="outline">Pesquisar contas</Button>
|
||||
</form>
|
||||
<ul className="space-y-3">
|
||||
{props.accounts.data.map((account) => (
|
||||
<li
|
||||
key={account.id}
|
||||
className="flex flex-wrap items-center justify-between gap-3 border-b pb-3"
|
||||
>
|
||||
<span>
|
||||
{account.code} · {account.label} ·{' '}
|
||||
{account.currency}
|
||||
</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={
|
||||
!selected ||
|
||||
form.data.allocations.length >=
|
||||
20 ||
|
||||
form.data.allocations.some(
|
||||
(row) =>
|
||||
row.account_id ===
|
||||
account.id,
|
||||
)
|
||||
}
|
||||
onClick={() =>
|
||||
form.setData('allocations', [
|
||||
...form.data.allocations,
|
||||
{
|
||||
account_id: account.id,
|
||||
source_hash:
|
||||
account.source_hash,
|
||||
label: `${account.code} · ${account.label}`,
|
||||
subtotal: '',
|
||||
total: '',
|
||||
},
|
||||
])
|
||||
}
|
||||
>
|
||||
Adicionar conta à linha
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{props.accounts.data.length === 0 && (
|
||||
<p>Sem contas de movimento nesta pesquisa.</p>
|
||||
)}
|
||||
<nav className="mt-4 flex gap-4">
|
||||
{props.accounts.prev_page_url && (
|
||||
<Link
|
||||
preserveState
|
||||
preserveScroll
|
||||
className="underline"
|
||||
href={props.accounts.prev_page_url}
|
||||
>
|
||||
Anterior
|
||||
</Link>
|
||||
)}
|
||||
{props.accounts.next_page_url && (
|
||||
<Link
|
||||
preserveState
|
||||
preserveScroll
|
||||
className="underline"
|
||||
href={props.accounts.next_page_url}
|
||||
>
|
||||
Seguinte
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
</Panel>
|
||||
)}
|
||||
<Panel title="Versões preservadas">
|
||||
<ul className="space-y-4">
|
||||
{props.history.data.map((row) => (
|
||||
<li key={row.id}>
|
||||
<p>
|
||||
Linha #{row.data.requisition_item_id} ·
|
||||
Versão {row.version} · {row.reason}
|
||||
</p>
|
||||
<ul>
|
||||
{row.data.allocations.map((part) => (
|
||||
<li key={part.account.id}>
|
||||
{part.account.code} ·{' '}
|
||||
{part.account.label} · Base sem IVA:{' '}
|
||||
{exactMinorAmount(
|
||||
part.subtotal_minor,
|
||||
'MZN',
|
||||
)}{' '}
|
||||
· Total:{' '}
|
||||
{exactMinorAmount(
|
||||
part.total_minor,
|
||||
'MZN',
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<nav className="mt-4 flex gap-4">
|
||||
{props.history.prev_page_url && (
|
||||
<Link
|
||||
preserveState
|
||||
preserveScroll
|
||||
className="underline"
|
||||
href={props.history.prev_page_url}
|
||||
>
|
||||
Histórico anterior
|
||||
</Link>
|
||||
)}
|
||||
{props.history.next_page_url && (
|
||||
<Link
|
||||
preserveState
|
||||
preserveScroll
|
||||
className="underline"
|
||||
href={props.history.next_page_url}
|
||||
>
|
||||
Histórico seguinte
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
</Panel>
|
||||
</main>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,14 +1,16 @@
|
||||
import { Head, Link, router, useForm } from "@inertiajs/react";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { Head, Link, router, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import {
|
||||
FormErrors,
|
||||
PageTitle,
|
||||
Panel,
|
||||
controlClass,
|
||||
} from "@/components/procurement";
|
||||
import { Button } from "@/components/ui/button";
|
||||
} from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { date, money, priorityLabels, roleLabels } from '@/types/procurement';
|
||||
|
||||
type Deadline = {
|
||||
timing?: string;
|
||||
state: string;
|
||||
step_id: number | null;
|
||||
expires_at: string | null;
|
||||
@@ -36,12 +38,48 @@ type Props = {
|
||||
id: number;
|
||||
data: { cycle: number; next_cycle: number };
|
||||
reason: string;
|
||||
request: { number: string };
|
||||
created_at?: string | null;
|
||||
approval_amount_minor?: number | null;
|
||||
approval_uses_separate_basis?: boolean;
|
||||
request: {
|
||||
number: string;
|
||||
priority?: string;
|
||||
justification?: string;
|
||||
needed_by?: string | null;
|
||||
submitted_at?: string | null;
|
||||
subtotal_minor?: number | null;
|
||||
tax_minor?: number | null;
|
||||
total_minor?: number | null;
|
||||
};
|
||||
rules?: {
|
||||
first_limit_minor?: number | null;
|
||||
second_limit_minor?: number | null;
|
||||
approval_includes_tax?: boolean;
|
||||
rules_provisional?: boolean;
|
||||
routing_plan_revision?: number;
|
||||
};
|
||||
items?:
|
||||
| {
|
||||
id: number;
|
||||
description: string;
|
||||
quantity: string;
|
||||
unit: string;
|
||||
unit_price_minor?: number | null;
|
||||
tax_rate?: string | null;
|
||||
subtotal_minor?: number | null;
|
||||
tax_minor?: number | null;
|
||||
total_minor?: number | null;
|
||||
}[]
|
||||
| null;
|
||||
steps: {
|
||||
id: number;
|
||||
position: number;
|
||||
role: string;
|
||||
decision: string;
|
||||
approver_id?: number | null;
|
||||
decided_at?: string | null;
|
||||
comment?: string | null;
|
||||
routing?: { name?: string } | null;
|
||||
}[];
|
||||
}[];
|
||||
prev_page_url: string | null;
|
||||
@@ -49,40 +87,50 @@ type Props = {
|
||||
};
|
||||
};
|
||||
const labels: Record<string, string> = {
|
||||
inactive: "Sem etapa pendente",
|
||||
unconfigured: "Sem prazo configurado",
|
||||
unverified: "Datas por conferir",
|
||||
running: "Em prazo",
|
||||
expired: "Prazo terminado",
|
||||
inactive: 'Sem etapa pendente',
|
||||
unconfigured: 'Sem prazo configurado',
|
||||
unverified: 'Datas por conferir',
|
||||
running: 'Em prazo',
|
||||
expired: 'Prazo terminado',
|
||||
};
|
||||
const time = (value?: string | null) =>
|
||||
value ? new Date(value).toLocaleString("pt-MZ") : "Por indicar";
|
||||
value ? new Date(value).toLocaleString('pt-MZ') : 'Por indicar';
|
||||
const pastTime = (value?: string | null) =>
|
||||
value ? time(value) : 'Não preservada';
|
||||
const historicalDecisions: Record<string, string> = {
|
||||
approved: 'Aprovação preservada',
|
||||
pending: 'Etapa pendente no momento da devolução',
|
||||
rejected: 'Rejeição preservada',
|
||||
expired: 'Etapa expirada',
|
||||
};
|
||||
const preservedMoney = (value?: number | null) =>
|
||||
value == null ? 'Não preservado' : money(value);
|
||||
export default function Expiry(props: Props) {
|
||||
const r = props.requisition;
|
||||
const check = useForm({
|
||||
operation_key: "",
|
||||
operation_key: '',
|
||||
process_version: r.process_version,
|
||||
});
|
||||
const form = useForm(`expiry:${props.tenantId}:${props.actorId}:${r.id}`, {
|
||||
operation_key: "",
|
||||
operation_key: '',
|
||||
process_version: r.process_version,
|
||||
basis_hash: props.deadline.basis_hash || "",
|
||||
comment: "",
|
||||
basis_hash: props.deadline.basis_hash || '',
|
||||
comment: '',
|
||||
});
|
||||
const current =
|
||||
form.data.process_version === r.process_version &&
|
||||
form.data.basis_hash === (props.deadline.basis_hash || "");
|
||||
form.data.basis_hash === (props.deadline.basis_hash || '');
|
||||
const ref = useRef<HTMLFormElement>(null);
|
||||
useEffect(() => {
|
||||
const node = ref.current;
|
||||
window.dispatchEvent(
|
||||
new CustomEvent("sgc:context-dirty", {
|
||||
new CustomEvent('sgc:context-dirty', {
|
||||
detail: { form: node, dirty: form.isDirty },
|
||||
}),
|
||||
);
|
||||
return () => {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent("sgc:context-dirty", {
|
||||
new CustomEvent('sgc:context-dirty', {
|
||||
detail: { form: node, dirty: false },
|
||||
}),
|
||||
);
|
||||
@@ -100,8 +148,15 @@ export default function Expiry(props: Props) {
|
||||
Voltar à requisição
|
||||
</Link>
|
||||
<Panel
|
||||
title={`${labels[props.deadline.state] || "Por conferir"} · ciclo ${r.approval_cycle}`}
|
||||
title={`${labels[props.deadline.state] || 'Por conferir'} · ciclo ${r.approval_cycle}`}
|
||||
>
|
||||
{props.deadline.timing && (
|
||||
<p className="mb-4 text-sm">
|
||||
{props.deadline.timing === 'urgent_override'
|
||||
? 'Prazos reduzidos para urgência, preservados na submissão.'
|
||||
: 'Prazos gerais da etapa, preservados na submissão.'}
|
||||
</p>
|
||||
)}
|
||||
<dl className="grid gap-3 text-sm">
|
||||
<div>
|
||||
<dt>Início da etapa</dt>
|
||||
@@ -143,7 +198,7 @@ export default function Expiry(props: Props) {
|
||||
event.preventDefault();
|
||||
const operation =
|
||||
check.data.operation_key || crypto.randomUUID();
|
||||
check.setData("operation_key", operation);
|
||||
check.setData('operation_key', operation);
|
||||
check.transform(() => ({
|
||||
operation_key: operation,
|
||||
process_version: r.process_version,
|
||||
@@ -180,7 +235,7 @@ export default function Expiry(props: Props) {
|
||||
event.preventDefault();
|
||||
const operation =
|
||||
form.data.operation_key || crypto.randomUUID();
|
||||
form.setData("operation_key", operation);
|
||||
form.setData('operation_key', operation);
|
||||
form.transform((data) => ({
|
||||
...data,
|
||||
operation_key: operation,
|
||||
@@ -209,8 +264,8 @@ export default function Expiry(props: Props) {
|
||||
...data,
|
||||
process_version: r.process_version,
|
||||
basis_hash:
|
||||
props.deadline.basis_hash || "",
|
||||
operation_key: "",
|
||||
props.deadline.basis_hash || '',
|
||||
operation_key: '',
|
||||
}))
|
||||
}
|
||||
>
|
||||
@@ -225,7 +280,7 @@ export default function Expiry(props: Props) {
|
||||
maxLength={2000}
|
||||
value={form.data.comment}
|
||||
onChange={(event) =>
|
||||
form.setData("comment", event.target.value)
|
||||
form.setData('comment', event.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
@@ -259,17 +314,171 @@ export default function Expiry(props: Props) {
|
||||
className="space-y-2 border-b py-4 break-words"
|
||||
>
|
||||
<h3 className="font-semibold">
|
||||
Ciclo {row.data.cycle} · devolvido para o ciclo{" "}
|
||||
Ciclo {row.data.cycle} · devolvido para o ciclo{' '}
|
||||
{row.data.next_cycle}
|
||||
</h3>
|
||||
<p>{row.reason}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Documento preservado na devolução. As decisões e os
|
||||
valores deste ciclo não são as aprovações da nova
|
||||
submissão.
|
||||
</p>
|
||||
<dl className="grid gap-2 text-sm sm:grid-cols-2">
|
||||
<div>
|
||||
<dt className="text-muted-foreground">
|
||||
Submissão original
|
||||
</dt>
|
||||
<dd>{pastTime(row.request.submitted_at)}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">
|
||||
Devolvido em
|
||||
</dt>
|
||||
<dd>{pastTime(row.created_at)}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">
|
||||
Prioridade original
|
||||
</dt>
|
||||
<dd>
|
||||
{row.request.priority
|
||||
? (priorityLabels[
|
||||
row.request.priority
|
||||
] ?? row.request.priority)
|
||||
: 'Não preservada'}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">
|
||||
Data de necessidade original
|
||||
</dt>
|
||||
<dd>
|
||||
{row.request.needed_by
|
||||
? date(row.request.needed_by)
|
||||
: 'Não preservada'}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">
|
||||
Sem IVA
|
||||
</dt>
|
||||
<dd>
|
||||
{preservedMoney(row.request.subtotal_minor)}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">IVA</dt>
|
||||
<dd>{preservedMoney(row.request.tax_minor)}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">
|
||||
Total original (MZN)
|
||||
</dt>
|
||||
<dd>
|
||||
{preservedMoney(row.request.total_minor)}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
{row.request.justification && (
|
||||
<p className="whitespace-pre-wrap">
|
||||
{row.request.justification}
|
||||
</p>
|
||||
)}
|
||||
<details className="rounded border p-3">
|
||||
<summary>Artigos e regras preservados</summary>
|
||||
<ul className="mt-3 space-y-3">
|
||||
{row.items?.map((item) => (
|
||||
<li key={item.id} className="break-words">
|
||||
<p>
|
||||
{item.description} · {item.quantity}{' '}
|
||||
{item.unit}
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Preço unitário:{' '}
|
||||
{preservedMoney(
|
||||
item.unit_price_minor,
|
||||
)}{' '}
|
||||
· Taxa de IVA declarada:{' '}
|
||||
{item.tax_rate == null
|
||||
? 'Não preservada'
|
||||
: `${item.tax_rate}%`}
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Sem IVA:{' '}
|
||||
{preservedMoney(
|
||||
item.subtotal_minor,
|
||||
)}{' '}
|
||||
· IVA:{' '}
|
||||
{preservedMoney(item.tax_minor)} ·
|
||||
Total:{' '}
|
||||
{preservedMoney(item.total_minor)}
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{!row.items?.length && (
|
||||
<p>Artigos não preservados neste registo.</p>
|
||||
)}
|
||||
<p className="mt-3 text-sm">
|
||||
Base de aprovação:{' '}
|
||||
{row.rules?.approval_includes_tax === true
|
||||
? 'com IVA'
|
||||
: row.rules?.approval_includes_tax === false
|
||||
? 'sem IVA'
|
||||
: 'Não preservada'}
|
||||
.
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Valor usado no encaminhamento:{' '}
|
||||
{preservedMoney(row.approval_amount_minor)}.
|
||||
</p>
|
||||
{row.approval_uses_separate_basis && (
|
||||
<p className="text-sm">
|
||||
Base adicional preservada na submissão
|
||||
original.
|
||||
</p>
|
||||
)}
|
||||
{row.rules?.routing_plan_revision != null && (
|
||||
<p className="text-sm">
|
||||
Plano de encaminhamento · versão{' '}
|
||||
{row.rules.routing_plan_revision}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm">
|
||||
Limites preservados:{' '}
|
||||
{preservedMoney(row.rules?.first_limit_minor)} /{' '}
|
||||
{preservedMoney(row.rules?.second_limit_minor)}.
|
||||
</p>
|
||||
{row.rules?.rules_provisional === true && (
|
||||
<p className="text-sm">
|
||||
Regras provisórias na submissão original.
|
||||
</p>
|
||||
)}
|
||||
</details>
|
||||
<ul>
|
||||
{row.steps.map((step) => (
|
||||
<li key={step.id}>
|
||||
Etapa {step.position}:{" "}
|
||||
{step.decision === "approved"
|
||||
? "Aprovação preservada"
|
||||
: "Etapa pendente no momento da devolução"}
|
||||
<li key={step.id} className="my-3">
|
||||
Etapa {step.position}:{' '}
|
||||
{step.routing?.name ??
|
||||
roleLabels[step.role] ??
|
||||
step.role}{' '}
|
||||
·{' '}
|
||||
{historicalDecisions[step.decision] ??
|
||||
'Estado não preservado'}
|
||||
{step.approver_id != null && (
|
||||
<span>
|
||||
{' '}
|
||||
· Utilizador #{step.approver_id}
|
||||
</span>
|
||||
)}
|
||||
{step.decided_at && (
|
||||
<span> · {time(step.decided_at)}</span>
|
||||
)}
|
||||
{step.comment && (
|
||||
<p className="mt-1 whitespace-pre-wrap">
|
||||
{step.comment}
|
||||
</p>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -12,7 +12,8 @@ import {
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { money } from '@/types/procurement';
|
||||
import { exactMinorAmount } from '@/components/procurement-payable-insights';
|
||||
import { requisitionEstimate } from '@/lib/requisition-estimate';
|
||||
import type { CostCenter, Requisition } from '@/types/procurement';
|
||||
import { CatalogueSearch } from '@/components/requisition-catalogue';
|
||||
import { RequisitionCategoryFields } from '@/components/requisition-category-fields';
|
||||
@@ -186,15 +187,49 @@ export default function RequisitionForm({
|
||||
i === index ? { ...item, [field]: value } : item,
|
||||
),
|
||||
);
|
||||
const estimate = form.data.items.reduce(
|
||||
(sum, i) =>
|
||||
sum +
|
||||
Math.round(
|
||||
Math.round(Number(i.quantity) * Number(i.unit_price) * 100) *
|
||||
(1 + Number(i.tax_rate) / 100),
|
||||
),
|
||||
0,
|
||||
);
|
||||
const estimate = requisitionEstimate(form.data.items);
|
||||
const validationErrors: Record<string, string> = form.errors;
|
||||
const errorAttributes = (field: string) => ({
|
||||
'aria-invalid': !!validationErrors[field],
|
||||
'aria-describedby': validationErrors[field]
|
||||
? `error-${field}`
|
||||
: undefined,
|
||||
});
|
||||
const fieldError = (field: string) =>
|
||||
validationErrors[field] ? (
|
||||
<p id={`error-${field}`} className="text-sm text-destructive">
|
||||
{validationErrors[field]}
|
||||
</p>
|
||||
) : null;
|
||||
const errorTargets: Record<string, string> = {
|
||||
cost_center_id: 'cost-center',
|
||||
priority: 'priority',
|
||||
needed_by: 'needed-by',
|
||||
justification: 'justification',
|
||||
items: 'requisition-items',
|
||||
};
|
||||
for (const error of Object.keys(form.errors)) {
|
||||
const match = /^items\.(\d+)(?:\.(.+))?$/.exec(error);
|
||||
if (!match) continue;
|
||||
const index = Number(match[1]);
|
||||
const line = form.data.items[index];
|
||||
if (!line) continue;
|
||||
const field = match[2];
|
||||
errorTargets[error] = lineFields.some(({ key }) => key === field)
|
||||
? `${field}-${line.key}`
|
||||
: field === 'purchase_type' && !line.catalogue_entry_id
|
||||
? `type-${line.key}`
|
||||
: `requisition-line-${line.key}`;
|
||||
if (Object.keys(requisitionCategories).length > 0) {
|
||||
if (field === 'procurement_category')
|
||||
errorTargets[error] = `rq-category-${index}`;
|
||||
if (
|
||||
field === 'category_reason' &&
|
||||
(line.procurement_category || line.category_reason)
|
||||
)
|
||||
errorTargets[error] = `rq-category-${index}-reason`;
|
||||
}
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<Head
|
||||
@@ -212,6 +247,7 @@ export default function RequisitionForm({
|
||||
/>
|
||||
<form
|
||||
ref={formElement}
|
||||
data-preparation-dirty={preparationDirty ? 'true' : 'false'}
|
||||
data-context-save
|
||||
noValidate={incompleteDraftsAvailable}
|
||||
className="space-y-6"
|
||||
@@ -233,7 +269,7 @@ export default function RequisitionForm({
|
||||
else form.post('/requisicoes', options);
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
<FormErrors errors={form.errors} targets={errorTargets} />
|
||||
{incompleteDraftsAvailable && (
|
||||
<p className="rounded-lg border p-4 text-sm">
|
||||
Pode guardar esta preparação mesmo com campos em
|
||||
@@ -266,6 +302,7 @@ export default function RequisitionForm({
|
||||
</Label>
|
||||
<select
|
||||
id="cost-center"
|
||||
{...errorAttributes('cost_center_id')}
|
||||
required
|
||||
className={controlClass}
|
||||
value={form.data.cost_center_id}
|
||||
@@ -283,11 +320,13 @@ export default function RequisitionForm({
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{fieldError('cost_center_id')}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="priority">Prioridade</Label>
|
||||
<select
|
||||
id="priority"
|
||||
{...errorAttributes('priority')}
|
||||
className={controlClass}
|
||||
value={form.data.priority}
|
||||
onChange={(e) =>
|
||||
@@ -298,6 +337,7 @@ export default function RequisitionForm({
|
||||
<option value="high">Alta</option>
|
||||
<option value="urgent">Urgente</option>
|
||||
</select>
|
||||
{fieldError('priority')}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="needed-by">
|
||||
@@ -305,6 +345,7 @@ export default function RequisitionForm({
|
||||
</Label>
|
||||
<Input
|
||||
id="needed-by"
|
||||
{...errorAttributes('needed_by')}
|
||||
type="date"
|
||||
required
|
||||
value={form.data.needed_by}
|
||||
@@ -315,6 +356,7 @@ export default function RequisitionForm({
|
||||
)
|
||||
}
|
||||
/>
|
||||
{fieldError('needed_by')}
|
||||
</div>
|
||||
<div className="space-y-2 sm:col-span-3">
|
||||
<Label htmlFor="justification">
|
||||
@@ -322,6 +364,7 @@ export default function RequisitionForm({
|
||||
</Label>
|
||||
<textarea
|
||||
id="justification"
|
||||
{...errorAttributes('justification')}
|
||||
required
|
||||
minLength={10}
|
||||
maxLength={5000}
|
||||
@@ -335,6 +378,7 @@ export default function RequisitionForm({
|
||||
)
|
||||
}
|
||||
/>
|
||||
{fieldError('justification')}
|
||||
</div>
|
||||
</div>
|
||||
</Panel>
|
||||
@@ -342,12 +386,18 @@ export default function RequisitionForm({
|
||||
title="Artigos e serviços"
|
||||
description="Preços em MZN. Confira a taxa de IVA aplicável a cada artigo antes de submeter."
|
||||
>
|
||||
<div className="space-y-5">
|
||||
<div
|
||||
className="space-y-5"
|
||||
id="requisition-items"
|
||||
tabIndex={-1}
|
||||
>
|
||||
{catalogue?.ready && (
|
||||
<CatalogueSearch data={catalogue} />
|
||||
)}
|
||||
{form.data.items.map((line, index) => (
|
||||
<fieldset
|
||||
id={`requisition-line-${line.key}`}
|
||||
tabIndex={-1}
|
||||
className="rounded-lg border bg-muted/20 p-4"
|
||||
key={line.key}
|
||||
>
|
||||
@@ -504,6 +554,9 @@ export default function RequisitionForm({
|
||||
</Label>
|
||||
<Input
|
||||
id={`${key}-${line.key}`}
|
||||
{...errorAttributes(
|
||||
`items.${index}.${key}`,
|
||||
)}
|
||||
{...attributes}
|
||||
readOnly={
|
||||
!!line.catalogue_entry_id &&
|
||||
@@ -523,6 +576,9 @@ export default function RequisitionForm({
|
||||
)
|
||||
}
|
||||
/>
|
||||
{fieldError(
|
||||
`items.${index}.${key}`,
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
@@ -719,6 +775,23 @@ export default function RequisitionForm({
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{Object.keys(validationErrors)
|
||||
.filter(
|
||||
(field) =>
|
||||
field.startsWith(
|
||||
`items.${index}.`,
|
||||
) &&
|
||||
!lineFields.some(
|
||||
({ key }) =>
|
||||
field ===
|
||||
`items.${index}.${key}`,
|
||||
),
|
||||
)
|
||||
.map((field) => (
|
||||
<div key={field} className="mt-2">
|
||||
{fieldError(field)}
|
||||
</div>
|
||||
))}
|
||||
<ActionBar align="end" className="mt-3">
|
||||
<Button
|
||||
type="button"
|
||||
@@ -761,18 +834,9 @@ export default function RequisitionForm({
|
||||
<p className="text-sm">
|
||||
Total estimado com IVA{' '}
|
||||
<strong className="ml-3 text-lg">
|
||||
{money(
|
||||
form.data.items.length > 0 &&
|
||||
form.data.items.every(
|
||||
(line) =>
|
||||
line.quantity !== '' &&
|
||||
line.unit_price !== '' &&
|
||||
line.tax_rate !== '',
|
||||
) &&
|
||||
Number.isFinite(estimate)
|
||||
? estimate
|
||||
: null,
|
||||
)}
|
||||
{estimate === null
|
||||
? 'Por completar'
|
||||
: exactMinorAmount(estimate, 'MZN')}
|
||||
</strong>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { Head, Link, useForm, usePage } from '@inertiajs/react';
|
||||
import { Check, Circle, Pencil, Send } from 'lucide-react';
|
||||
import { Check, Circle, Pencil } from 'lucide-react';
|
||||
import {
|
||||
RequisitionSubmissionAction,
|
||||
type SubmissionPreview,
|
||||
} from '@/components/requisition-submission-confirmation';
|
||||
import { ComparisonPolicySummary } from '@/components/comparison-policy-summary';
|
||||
import type { ComparisonPolicy } from '@/components/comparison-policy-summary';
|
||||
import {
|
||||
@@ -37,6 +41,7 @@ const actions: Record<string, string> = {
|
||||
'budget.distribution_cancel': 'Compromisso distribuído cancelado',
|
||||
'budget.distribution_amended': 'Compromisso reafectado por Finanças',
|
||||
'requisition.submitted': 'Pedido submetido',
|
||||
'requisition.accounts_assigned': 'Imputação contabilística preservada',
|
||||
'requisition.expired_returned': 'Pedido devolvido por expiração',
|
||||
'budget.cycle_opened': 'Novo ciclo orçamental preparado',
|
||||
'budget.cycle_closed':
|
||||
@@ -63,10 +68,21 @@ export default function Show({
|
||||
importEstimatesReady = false,
|
||||
capitalRegisterReady = false,
|
||||
expiryReady = false,
|
||||
accountsReady = false,
|
||||
duplicateHints = null,
|
||||
submissionPreview = null,
|
||||
canReadAuditMetadata = false,
|
||||
}: {
|
||||
canReadAuditMetadata?: boolean;
|
||||
submissionPreview?: SubmissionPreview | null;
|
||||
duplicateHints?: {
|
||||
matches: { id: number; number: string; status: string }[];
|
||||
complete: boolean;
|
||||
} | null;
|
||||
importEstimatesReady?: boolean;
|
||||
capitalRegisterReady?: boolean;
|
||||
expiryReady?: boolean;
|
||||
accountsReady?: boolean;
|
||||
importTariffsReady?: boolean;
|
||||
canPrepareDistributions?: boolean;
|
||||
requisition: Requisition;
|
||||
@@ -129,10 +145,6 @@ export default function Show({
|
||||
};
|
||||
}) {
|
||||
const ready = usePage().props.internalRequisitionReady === true;
|
||||
const submission = useForm({
|
||||
operation_key: ready ? crypto.randomUUID() : null,
|
||||
process_version: r.process_version ?? null,
|
||||
});
|
||||
const routing = useForm({
|
||||
operation_key: crypto.randomUUID(),
|
||||
process_version: r.process_version ?? 1,
|
||||
@@ -174,7 +186,6 @@ export default function Show({
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<FormErrors errors={submission.errors} />
|
||||
{capitalRegisterReady && (
|
||||
<Button asChild variant="outline">
|
||||
<Link
|
||||
@@ -184,6 +195,13 @@ export default function Show({
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
{accountsReady && (
|
||||
<Button asChild variant="outline">
|
||||
<Link href={`/requisicoes/${r.id}/contas`}>
|
||||
Atribuir contas contabilísticas
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
{expiryReady && (
|
||||
<Button asChild variant="outline">
|
||||
<Link href={`/requisicoes/${r.id}/prazos`}>
|
||||
@@ -216,6 +234,38 @@ export default function Show({
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
{duplicateHints &&
|
||||
(duplicateHints.matches.length > 0 ||
|
||||
!duplicateHints.complete) && (
|
||||
<Panel title="Conferir possíveis pedidos repetidos">
|
||||
<p>
|
||||
Pedidos seus com o mesmo centro de custo, data
|
||||
necessária e linhas iguais. Confira a
|
||||
necessidade antes de submeter; este aviso não
|
||||
bloqueia a submissão.
|
||||
</p>
|
||||
<ul className="mt-3 space-y-2">
|
||||
{duplicateHints.matches.map((match) => (
|
||||
<li key={match.id}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/requisicoes/${match.id}`}
|
||||
>
|
||||
{match.number}
|
||||
</Link>{' '}
|
||||
· <Status value={match.status} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{!duplicateHints.complete && (
|
||||
<p className="mt-3">
|
||||
Comparação limitada aos 100 candidatos mais
|
||||
recentes. Consulte também as suas
|
||||
requisições anteriores.
|
||||
</p>
|
||||
)}
|
||||
</Panel>
|
||||
)}
|
||||
{automaticSource && (
|
||||
<Panel title="Origem na reposição automática">
|
||||
<p>
|
||||
@@ -406,17 +456,14 @@ export default function Show({
|
||||
Editar
|
||||
</Link>
|
||||
</Button>
|
||||
<Button
|
||||
disabled={submission.processing}
|
||||
onClick={() =>
|
||||
submission.post(
|
||||
`/requisicoes/${r.id}/submeter`,
|
||||
)
|
||||
}
|
||||
>
|
||||
<Send className="size-4" />
|
||||
Submeter para aprovação
|
||||
</Button>
|
||||
<RequisitionSubmissionAction
|
||||
key={`${r.id}:${r.process_version ?? 0}`}
|
||||
id={r.id}
|
||||
number={r.number}
|
||||
version={r.process_version ?? null}
|
||||
ready={ready}
|
||||
preview={submissionPreview}
|
||||
/>
|
||||
</ActionBar>
|
||||
</div>
|
||||
))}
|
||||
@@ -828,6 +875,16 @@ export default function Show({
|
||||
</Panel>
|
||||
<Panel title="Histórico">
|
||||
<div id="requisition-history" />
|
||||
{canReadAuditMetadata && (
|
||||
<p className="mb-3 text-sm">
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/auditoria/eventos?request_reference=${encodeURIComponent(r.number)}`}
|
||||
>
|
||||
Consultar eventos deste pedido
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
<a
|
||||
className="mb-4 inline-block text-sm underline"
|
||||
href={`/requisicoes/${r.id}/historico.csv`}
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import {
|
||||
PageTitle,
|
||||
Panel,
|
||||
FormErrors,
|
||||
controlClass,
|
||||
} from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { exactMinorAmount } from '@/components/procurement-payable-insights';
|
||||
import { date, roleLabels } from '@/types/procurement';
|
||||
import { urgentOutcomes } from '@/pages/requisitions/urgent-reviews';
|
||||
|
||||
type Review = {
|
||||
id: number;
|
||||
version: number;
|
||||
data: { notes: string };
|
||||
snapshot: { fingerprint: string };
|
||||
};
|
||||
type Props = {
|
||||
source: {
|
||||
cycle: number;
|
||||
outcome: string;
|
||||
fingerprint: string;
|
||||
closed_at: string;
|
||||
request: {
|
||||
id: number;
|
||||
number: string;
|
||||
justification: string;
|
||||
total_minor: string | null;
|
||||
};
|
||||
items: {
|
||||
id: number;
|
||||
description: string;
|
||||
quantity: string;
|
||||
unit: string;
|
||||
total_minor: string | null;
|
||||
}[];
|
||||
steps: {
|
||||
id: number;
|
||||
role: string;
|
||||
decision: string;
|
||||
comment: string | null;
|
||||
routing?: { name: string } | null;
|
||||
}[];
|
||||
};
|
||||
current: Review | null;
|
||||
currentVerified: boolean;
|
||||
canReview: boolean;
|
||||
actorId: number;
|
||||
tenantId: number;
|
||||
history: {
|
||||
data: Review[];
|
||||
prev_page_url: string | null;
|
||||
next_page_url: string | null;
|
||||
};
|
||||
};
|
||||
export default function UrgentReview(props: Props) {
|
||||
const source = props.source;
|
||||
const url = `/requisicoes/${source.request.id}/ciclos/${source.cycle}/revisao-urgencia`;
|
||||
const form = useForm(
|
||||
`urgent-review:${props.tenantId}:${props.actorId}:${source.request.id}:${source.cycle}`,
|
||||
{
|
||||
operation_key: '',
|
||||
version: props.current?.version ?? 0,
|
||||
source_hash: source.fingerprint,
|
||||
notes: '',
|
||||
},
|
||||
);
|
||||
const ref = useRef<HTMLFormElement>(null);
|
||||
useEffect(() => {
|
||||
const node = ref.current;
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('sgc:context-dirty', {
|
||||
detail: { form: node, dirty: form.isDirty },
|
||||
}),
|
||||
);
|
||||
return () => {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('sgc:context-dirty', {
|
||||
detail: { form: node, dirty: false },
|
||||
}),
|
||||
);
|
||||
};
|
||||
}, [form.isDirty]);
|
||||
const fresh =
|
||||
form.data.version === (props.current?.version ?? 0) &&
|
||||
form.data.source_hash === source.fingerprint;
|
||||
return (
|
||||
<main className="mx-auto flex w-full max-w-6xl flex-col gap-6 p-5 lg:p-8">
|
||||
<Head title="Revisão posterior de urgência" />
|
||||
<PageTitle
|
||||
eyebrow={`${source.request.number} · Ciclo ${source.cycle}`}
|
||||
title="Revisão posterior de urgência"
|
||||
description="A revisão regista a conferência posterior da direcção de Compras. As aprovações, a decisão final e os movimentos conservam o seu percurso próprio."
|
||||
/>
|
||||
<nav className="flex flex-wrap gap-4">
|
||||
<Link
|
||||
className="underline"
|
||||
href="/requisicoes/urgencias/revisoes"
|
||||
>
|
||||
Voltar às urgências
|
||||
</Link>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/requisicoes/${source.request.id}`}
|
||||
>
|
||||
Consultar o pedido actual
|
||||
</Link>
|
||||
</nav>
|
||||
<Panel
|
||||
title={`Ciclo concluído · ${urgentOutcomes[source.outcome]}`}
|
||||
>
|
||||
<p className="whitespace-pre-wrap">
|
||||
{source.request.justification}
|
||||
</p>
|
||||
<p className="mt-3">
|
||||
Conclusão registada em: {date(source.closed_at)}
|
||||
</p>
|
||||
<p className="mt-3">
|
||||
Valor da necessidade original:{' '}
|
||||
{source.request.total_minor === null
|
||||
? 'Indeterminado'
|
||||
: exactMinorAmount(source.request.total_minor, 'MZN')}
|
||||
</p>
|
||||
{source.outcome === 'expired' && (
|
||||
<p className="mt-3">
|
||||
Estes dados pertencem ao ciclo expirado. O rascunho
|
||||
actual e uma nova submissão podem ter valores
|
||||
diferentes.
|
||||
</p>
|
||||
)}
|
||||
<ul className="mt-4 space-y-2">
|
||||
{source.items.map((line) => (
|
||||
<li key={line.id}>
|
||||
{line.description} · {line.quantity} {line.unit} ·{' '}
|
||||
{line.total_minor === null
|
||||
? 'Indeterminado'
|
||||
: exactMinorAmount(line.total_minor, 'MZN')}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<h3 className="mt-4 font-semibold">Decisões conservadas</h3>
|
||||
<ul className="mt-2 space-y-2">
|
||||
{source.steps.map((step) => (
|
||||
<li key={step.id}>
|
||||
{step.routing?.name ||
|
||||
roleLabels[step.role] ||
|
||||
'Etapa configurada'}{' '}
|
||||
·{' '}
|
||||
{step.decision === 'approved'
|
||||
? 'Aprovada'
|
||||
: step.decision === 'rejected'
|
||||
? 'Rejeitada'
|
||||
: 'Sem decisão antes da conclusão do ciclo'}
|
||||
{step.comment && (
|
||||
<p className="whitespace-pre-wrap">
|
||||
{step.comment}
|
||||
</p>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Panel>
|
||||
<Panel
|
||||
title={
|
||||
props.current
|
||||
? `Revisão actual · versão ${props.current.version}`
|
||||
: 'Registar a revisão posterior'
|
||||
}
|
||||
>
|
||||
{!props.currentVerified && (
|
||||
<p role="alert">
|
||||
A revisão anterior não confirma a origem actualmente
|
||||
apresentada. O ciclo não é apresentado como revisto.
|
||||
</p>
|
||||
)}
|
||||
{props.current && (
|
||||
<p className="mb-4 whitespace-pre-wrap">
|
||||
{props.current.data.notes}
|
||||
</p>
|
||||
)}
|
||||
{props.canReview ? (
|
||||
<form
|
||||
ref={ref}
|
||||
className="space-y-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
const data = {
|
||||
...form.data,
|
||||
operation_key:
|
||||
form.data.operation_key ||
|
||||
crypto.randomUUID(),
|
||||
};
|
||||
form.setData(data);
|
||||
form.transform(() => data);
|
||||
form.post(url, {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
const next = {
|
||||
...data,
|
||||
operation_key: '',
|
||||
version: data.version + 1,
|
||||
notes: '',
|
||||
};
|
||||
form.setData(next);
|
||||
form.setDefaults(next);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
{!fresh && (
|
||||
<p role="alert">
|
||||
A origem ou a revisão mudou. Confira os dados
|
||||
actuais antes de registar outra versão.
|
||||
</p>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
if (
|
||||
form.isDirty &&
|
||||
!window.confirm(
|
||||
'Descartar esta preparação e usar a origem actual?',
|
||||
)
|
||||
)
|
||||
return;
|
||||
form.setData({
|
||||
operation_key: '',
|
||||
version: props.current?.version ?? 0,
|
||||
source_hash: source.fingerprint,
|
||||
notes: '',
|
||||
});
|
||||
}}
|
||||
>
|
||||
Preparar versão actual
|
||||
</Button>
|
||||
<label className="block">
|
||||
Conclusões da revisão e observações
|
||||
<textarea
|
||||
className={controlClass}
|
||||
required
|
||||
minLength={10}
|
||||
maxLength={4000}
|
||||
value={form.data.notes}
|
||||
onChange={(event) =>
|
||||
form.setData('notes', event.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<Button disabled={form.processing || !fresh}>
|
||||
Registar revisão posterior
|
||||
</Button>
|
||||
</form>
|
||||
) : (
|
||||
<p>
|
||||
A consulta não confere competência para registar a
|
||||
revisão. São exigidos perfil designado, função e
|
||||
atribuição actualmente válidos.
|
||||
</p>
|
||||
)}
|
||||
</Panel>
|
||||
<Panel title="Histórico das revisões">
|
||||
<ul className="space-y-4">
|
||||
{props.history.data.map((row) => (
|
||||
<li key={row.id}>
|
||||
<h3 className="font-semibold">
|
||||
Versão {row.version}
|
||||
</h3>
|
||||
<p className="whitespace-pre-wrap">
|
||||
{row.data.notes}
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<nav className="mt-4 flex gap-4">
|
||||
{props.history.prev_page_url && (
|
||||
<Link
|
||||
preserveScroll
|
||||
preserveState
|
||||
className="underline"
|
||||
href={props.history.prev_page_url}
|
||||
>
|
||||
Anterior
|
||||
</Link>
|
||||
)}
|
||||
{props.history.next_page_url && (
|
||||
<Link
|
||||
preserveScroll
|
||||
preserveState
|
||||
className="underline"
|
||||
href={props.history.next_page_url}
|
||||
>
|
||||
Seguinte
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
</Panel>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { Head, Link } from '@inertiajs/react';
|
||||
import { PageTitle, Panel } from '@/components/procurement';
|
||||
import { date } from '@/types/procurement';
|
||||
|
||||
export const urgentOutcomes: Record<string, string> = {
|
||||
approved: 'Aprovada',
|
||||
rejected: 'Rejeitada',
|
||||
expired: 'Expirada e devolvida ao requisitante',
|
||||
};
|
||||
const states: Record<string, string> = {
|
||||
pending: 'Por rever',
|
||||
reviewed: 'Revisão registada',
|
||||
indeterminate: 'Origem por conferir',
|
||||
all: 'Todos os ciclos concluídos',
|
||||
};
|
||||
export default function UrgentReviews(props: {
|
||||
coverage: Record<string, number>;
|
||||
state: string;
|
||||
canReview: boolean;
|
||||
canConfigure: boolean;
|
||||
records: {
|
||||
data: {
|
||||
key: string;
|
||||
number: string;
|
||||
cycle: number;
|
||||
outcome: string;
|
||||
status: string;
|
||||
closed_at: string | null;
|
||||
href: string;
|
||||
}[];
|
||||
total: number;
|
||||
current_page: number;
|
||||
last_page: number;
|
||||
};
|
||||
}) {
|
||||
const url = '/requisicoes/urgencias/revisoes';
|
||||
return (
|
||||
<main className="mx-auto flex w-full max-w-6xl flex-col gap-6 p-5 lg:p-8">
|
||||
<Head title="Revisão posterior das urgências" />
|
||||
<PageTitle
|
||||
eyebrow="Compras"
|
||||
title="Revisão posterior das urgências"
|
||||
description="Ciclos com decisão final, incluindo rejeição e expiração. A revisão conserva o ciclo concluído e as suas decisões."
|
||||
/>
|
||||
<Link className="underline" href="/requisicoes/tarefas">
|
||||
Voltar às tarefas
|
||||
</Link>
|
||||
{props.canConfigure && (
|
||||
<Link
|
||||
className="underline"
|
||||
href="/administracao/revisao-urgencias"
|
||||
>
|
||||
Designar perfis da direcção de Compras
|
||||
</Link>
|
||||
)}
|
||||
<Panel title="Conferir ciclos concluídos">
|
||||
<dl className="grid gap-4 sm:grid-cols-3">
|
||||
{Object.entries(props.coverage).map(([key, count]) => (
|
||||
<div key={key}>
|
||||
<dt>{states[key]}</dt>
|
||||
<dd className="font-semibold">{count}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
<nav
|
||||
aria-label="Filtrar revisões de urgências"
|
||||
className="my-4 flex flex-wrap gap-4"
|
||||
>
|
||||
{Object.entries(states).map(([key, label]) => (
|
||||
<Link
|
||||
key={key}
|
||||
className="underline"
|
||||
href={`${url}?state=${key}`}
|
||||
>
|
||||
{label}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
{!props.canReview && (
|
||||
<p className="mb-4 text-sm">
|
||||
O registo da revisão exige um perfil expressamente
|
||||
designado e a função de Compras actualmente válida.
|
||||
</p>
|
||||
)}
|
||||
{props.records.data.length === 0 && (
|
||||
<p>Sem ciclos nesta selecção.</p>
|
||||
)}
|
||||
<ul className="space-y-4">
|
||||
{props.records.data.map((row) => (
|
||||
<li key={row.key} className="border-b pb-4">
|
||||
<Link
|
||||
className="font-semibold underline"
|
||||
href={row.href}
|
||||
>
|
||||
{row.number} · Ciclo {row.cycle}
|
||||
</Link>
|
||||
<p>
|
||||
{urgentOutcomes[row.outcome]} ·{' '}
|
||||
{states[row.status]} · Conclusão:{' '}
|
||||
{row.closed_at
|
||||
? date(row.closed_at)
|
||||
: 'Por conferir'}
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="mt-4">
|
||||
{props.records.total} ciclo(s) · Página{' '}
|
||||
{props.records.current_page} de {props.records.last_page}
|
||||
</p>
|
||||
<nav
|
||||
className="mt-3 flex gap-4"
|
||||
aria-label="Páginas de revisão de urgências"
|
||||
>
|
||||
{props.records.current_page > 1 && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={`${url}?state=${props.state}&page=${props.records.current_page - 1}`}
|
||||
>
|
||||
Anterior
|
||||
</Link>
|
||||
)}
|
||||
{props.records.current_page < props.records.last_page && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={`${url}?state=${props.state}&page=${props.records.current_page + 1}`}
|
||||
>
|
||||
Seguinte
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
</Panel>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -31,16 +31,27 @@ const statuses: Record<string, string> = {
|
||||
active: 'Activo',
|
||||
inactive: 'Inactivo',
|
||||
confirmed: 'Confirmada',
|
||||
returned: 'Devolvido',
|
||||
suspended: 'Suspenso',
|
||||
submitted: 'Submetida',
|
||||
authorized: 'Autorizada',
|
||||
partial: 'Entrega parcial',
|
||||
delivered: 'Entregue',
|
||||
closed: 'Encerrada',
|
||||
};
|
||||
export default function ProcurementSearch({
|
||||
term,
|
||||
groups,
|
||||
invoiceSearchAvailable = false,
|
||||
supplySearchAvailable = false,
|
||||
warehouseRequestSearchAvailable = false,
|
||||
savedSearches = null,
|
||||
}: {
|
||||
term: string;
|
||||
groups: Group[];
|
||||
invoiceSearchAvailable?: boolean;
|
||||
supplySearchAvailable?: boolean;
|
||||
warehouseRequestSearchAvailable?: boolean;
|
||||
savedSearches?: SavedSearches | null;
|
||||
}) {
|
||||
const form = useForm({ q: term });
|
||||
@@ -55,7 +66,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.${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.`}
|
||||
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.' : ''}${supplySearchAvailable ? ' Acordos e contratos disponíveis são pesquisados pela referência ou pelo nome do fornecedor preservado, na sua versão actual.' : ''}${warehouseRequestSearchAvailable ? ' Requisições internas de armazém podem ser encontradas pela referência RA, destino ou nome do requisitante preservado.' : ''} A pesquisa não inclui Pessoas, conteúdo de anexos ou arquivos externos.`}
|
||||
>
|
||||
<form
|
||||
className="flex flex-wrap items-end gap-3"
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { useInventoryPreparationIdentity } from '@/hooks/use-inventory-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { InventoryEventActions } from '@/components/inventory-event-actions';
|
||||
import { Head, Link, router, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
@@ -102,13 +105,39 @@ const states: Record<string, string> = {
|
||||
};
|
||||
|
||||
function Prepare({ props, old }: { props: Props; old?: RecordEntry }) {
|
||||
const capabilities = JSON.stringify(
|
||||
Object.entries(props.capabilities).sort(([a], [b]) =>
|
||||
a.localeCompare(b),
|
||||
),
|
||||
);
|
||||
const identity = useInventoryPreparationIdentity(
|
||||
`/stock/ocorrencias:prepare:${old?.record_key ?? 'new'}:${old?.version ?? 0}:${old?.state ?? 'new'}:${capabilities}`,
|
||||
);
|
||||
return (
|
||||
<PrepareFields
|
||||
key={identity}
|
||||
props={props}
|
||||
old={old}
|
||||
identity={identity}
|
||||
/>
|
||||
);
|
||||
}
|
||||
function PrepareFields({
|
||||
props,
|
||||
old,
|
||||
identity,
|
||||
}: {
|
||||
props: Props;
|
||||
old?: RecordEntry;
|
||||
identity: string;
|
||||
}) {
|
||||
const [receipts, setReceipts] = useState(props.receipts);
|
||||
const formKey = `disposition:${old?.id ?? 'new'}`;
|
||||
useEffect(() => {
|
||||
if (!props.sourceFormKey || props.sourceFormKey === formKey)
|
||||
setReceipts(props.receipts);
|
||||
}, [props.sourceFormKey, props.receipts, formKey]);
|
||||
const form = useForm({
|
||||
const initial = {
|
||||
operation_key: crypto.randomUUID(),
|
||||
record_key: old?.record_key,
|
||||
version: old?.version ?? 0,
|
||||
@@ -125,7 +154,10 @@ function Prepare({ props, old }: { props: Props; old?: RecordEntry }) {
|
||||
quantity: old ? String(old.data.quantity_milli / 1000) : '',
|
||||
reference: old?.data.reference ?? '',
|
||||
},
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty);
|
||||
const searchSources = (value: string) =>
|
||||
router.get(
|
||||
'/stock/ocorrencias',
|
||||
@@ -158,10 +190,23 @@ function Prepare({ props, old }: { props: Props; old?: RecordEntry }) {
|
||||
);
|
||||
return (
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="grid gap-4 md:grid-cols-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post('/stock/ocorrencias');
|
||||
form.post('/stock/ocorrencias', {
|
||||
onSuccess: () => {
|
||||
const next = {
|
||||
...initial,
|
||||
operation_key: crypto.randomUUID(),
|
||||
};
|
||||
form.setData(next);
|
||||
form.clearErrors();
|
||||
router.remember(next, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
@@ -223,6 +268,20 @@ function Prepare({ props, old }: { props: Props; old?: RecordEntry }) {
|
||||
)}
|
||||
</option>
|
||||
))}
|
||||
{form.data.data.receipt_item_id &&
|
||||
!receipts.some(
|
||||
(receipt) =>
|
||||
String(receipt.id) ===
|
||||
form.data.data.receipt_item_id,
|
||||
) && (
|
||||
<option
|
||||
value={form.data.data.receipt_item_id}
|
||||
disabled
|
||||
>
|
||||
Origem seleccionada — pesquisar para
|
||||
conferir disponibilidade
|
||||
</option>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { useInventoryPreparationIdentity } from '@/hooks/use-inventory-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { AdministrativeLocation } from '@/components/administrative-location';
|
||||
import type {
|
||||
GeographyDescription,
|
||||
GeographyReference,
|
||||
} from '@/components/administrative-location';
|
||||
import { TerritorialFilter } from '@/components/territorial-filter';
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import { Head, Link, router, useForm } from '@inertiajs/react';
|
||||
import { InventoryNotice, InventoryPagination } from '@/components/inventory';
|
||||
import {
|
||||
TableViewport,
|
||||
@@ -25,29 +28,57 @@ import type {
|
||||
Warehouse,
|
||||
} from '@/types/inventory';
|
||||
|
||||
function WarehouseLocation({
|
||||
warehouse,
|
||||
geography,
|
||||
}: {
|
||||
function WarehouseLocation(props: {
|
||||
warehouse: Warehouse;
|
||||
geography: GeographyDescription;
|
||||
}) {
|
||||
const form = useForm({
|
||||
const identity = useInventoryPreparationIdentity(
|
||||
`/stock/warehouse-location:${props.warehouse.id}:${JSON.stringify(props.geography?.reference ?? null)}`,
|
||||
);
|
||||
return (
|
||||
<WarehouseLocationFields
|
||||
key={identity}
|
||||
{...props}
|
||||
identity={identity}
|
||||
/>
|
||||
);
|
||||
}
|
||||
function WarehouseLocationFields({
|
||||
warehouse,
|
||||
geography,
|
||||
identity,
|
||||
}: {
|
||||
identity: string;
|
||||
warehouse: Warehouse;
|
||||
geography: GeographyDescription;
|
||||
}) {
|
||||
const initial = {
|
||||
geography_reference:
|
||||
geography?.reference ?? (null as GeographyReference | null),
|
||||
expected_reference: geography?.reference ?? null,
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty);
|
||||
return (
|
||||
<details className="mb-4 rounded-lg border p-3">
|
||||
<summary className="cursor-pointer text-sm font-medium">
|
||||
Localização de {warehouse.code} · {warehouse.name}
|
||||
</summary>
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="mt-4 space-y-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
form.post(`/stock/armazens/${warehouse.id}/localizacao`, {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
form.setData(initial);
|
||||
form.clearErrors();
|
||||
router.remember(initial, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -85,7 +116,13 @@ type Props = {
|
||||
filters: { search?: string; warehouse_id?: number; location?: string };
|
||||
canManage: boolean;
|
||||
};
|
||||
export default function Stock({
|
||||
export default function Stock(props: Props) {
|
||||
const identity = useInventoryPreparationIdentity(
|
||||
`/stock:catalogue:${props.canManage}:${props.geographyEnabled ?? false}`,
|
||||
);
|
||||
return <StockFields key={identity} {...props} identity={identity} />;
|
||||
}
|
||||
function StockFields({
|
||||
items,
|
||||
warehouses,
|
||||
balances,
|
||||
@@ -95,18 +132,28 @@ export default function Stock({
|
||||
geographyEnabled = false,
|
||||
warehouseGeography = {},
|
||||
geographyFilter = null,
|
||||
}: Props) {
|
||||
identity,
|
||||
}: Props & { identity: string }) {
|
||||
const search = useForm({
|
||||
location: filters.location ?? '',
|
||||
search: filters.search ?? '',
|
||||
warehouse_id: filters.warehouse_id ? String(filters.warehouse_id) : '',
|
||||
});
|
||||
const item = useForm({ code: '', name: '', unit: '' });
|
||||
const warehouse = useForm({
|
||||
const initialItem = { code: '', name: '', unit: '' };
|
||||
const item = useForm(`${identity}:item`, initialItem);
|
||||
const itemDirty = hasPreparationChanges(initialItem, item.data);
|
||||
const itemRef = usePreparationDirty(itemDirty);
|
||||
const initialWarehouse = {
|
||||
code: '',
|
||||
name: '',
|
||||
geography_reference: null as GeographyReference | null,
|
||||
});
|
||||
};
|
||||
const warehouse = useForm(`${identity}:warehouse`, initialWarehouse);
|
||||
const warehouseDirty = hasPreparationChanges(
|
||||
initialWarehouse,
|
||||
warehouse.data,
|
||||
);
|
||||
const warehouseRef = usePreparationDirty(warehouseDirty);
|
||||
return (
|
||||
<>
|
||||
<Head title="Stock e movimentos" />
|
||||
@@ -309,12 +356,27 @@ export default function Stock({
|
||||
</div>
|
||||
{canManage && (
|
||||
<form
|
||||
ref={itemRef}
|
||||
data-preparation-dirty={
|
||||
itemDirty ? 'true' : 'false'
|
||||
}
|
||||
className="space-y-4 border-t pt-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
item.post('/stock/artigos', {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => item.reset(),
|
||||
onSuccess: () => {
|
||||
item.setData(initialItem);
|
||||
item.clearErrors();
|
||||
router.remember(
|
||||
initialItem,
|
||||
`${identity}:item:data`,
|
||||
);
|
||||
router.remember(
|
||||
{},
|
||||
`${identity}:item:errors`,
|
||||
);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -378,6 +440,10 @@ export default function Stock({
|
||||
))}
|
||||
{canManage && (
|
||||
<form
|
||||
ref={warehouseRef}
|
||||
data-preparation-dirty={
|
||||
warehouseDirty ? 'true' : 'false'
|
||||
}
|
||||
className="space-y-4 border-t pt-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -390,7 +456,18 @@ export default function Stock({
|
||||
});
|
||||
warehouse.post('/stock/armazens', {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => warehouse.reset(),
|
||||
onSuccess: () => {
|
||||
warehouse.setData(initialWarehouse);
|
||||
warehouse.clearErrors();
|
||||
router.remember(
|
||||
initialWarehouse,
|
||||
`${identity}:warehouse:data`,
|
||||
);
|
||||
router.remember(
|
||||
{},
|
||||
`${identity}:warehouse:errors`,
|
||||
);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { useInventoryPreparationIdentity } from '@/hooks/use-inventory-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { InventoryEventActions } from '@/components/inventory-event-actions';
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import { Head, Link, router, useForm } from '@inertiajs/react';
|
||||
import {
|
||||
FormErrors,
|
||||
PageTitle,
|
||||
@@ -139,9 +142,35 @@ const states: Record<string, string> = {
|
||||
};
|
||||
|
||||
function Prepare({ props, old }: { props: Props; old?: RecordEntry }) {
|
||||
const capabilities = JSON.stringify(
|
||||
Object.entries(props.capabilities).sort(([a], [b]) =>
|
||||
a.localeCompare(b),
|
||||
),
|
||||
);
|
||||
const identity = useInventoryPreparationIdentity(
|
||||
`/stock/lotes:prepare:${old?.record_key ?? 'new'}:${old?.version ?? 0}:${old?.state ?? 'new'}:${capabilities}`,
|
||||
);
|
||||
return (
|
||||
<PrepareFields
|
||||
key={identity}
|
||||
props={props}
|
||||
old={old}
|
||||
identity={identity}
|
||||
/>
|
||||
);
|
||||
}
|
||||
function PrepareFields({
|
||||
props,
|
||||
old,
|
||||
identity,
|
||||
}: {
|
||||
props: Props;
|
||||
old?: RecordEntry;
|
||||
identity: string;
|
||||
}) {
|
||||
const revision =
|
||||
old?.state === 'active' || !!old?.snapshot.previous_setup_id;
|
||||
const form = useForm({
|
||||
const initial = {
|
||||
operation_key: crypto.randomUUID(),
|
||||
record_key: old?.record_key,
|
||||
version: old?.version ?? 0,
|
||||
@@ -164,13 +193,29 @@ function Prepare({ props, old }: { props: Props; old?: RecordEntry }) {
|
||||
quantity: String(l.quantity_milli / 1000),
|
||||
})) ?? []),
|
||||
},
|
||||
});
|
||||
};
|
||||
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="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post('/stock/lotes');
|
||||
form.post('/stock/lotes', {
|
||||
onSuccess: () => {
|
||||
const next = {
|
||||
...initial,
|
||||
operation_key: crypto.randomUUID(),
|
||||
};
|
||||
form.setData(next);
|
||||
form.clearErrors();
|
||||
router.remember(next, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
@@ -445,7 +490,13 @@ function Decision({
|
||||
);
|
||||
}
|
||||
function Identify({ lot }: { lot: Lot }) {
|
||||
const form = useForm({
|
||||
const identity = useInventoryPreparationIdentity(
|
||||
`/stock/lotes:identify:${lot.record_key}:${lot.version}`,
|
||||
);
|
||||
return <IdentifyFields key={identity} lot={lot} identity={identity} />;
|
||||
}
|
||||
function IdentifyFields({ lot, identity }: { lot: Lot; identity: string }) {
|
||||
const initial = {
|
||||
operation_key: crypto.randomUUID(),
|
||||
record_key: lot.record_key,
|
||||
version: lot.version,
|
||||
@@ -456,17 +507,33 @@ function Identify({ lot }: { lot: Lot }) {
|
||||
expires_on: lot.data.expires_on ?? '',
|
||||
no_expiry: lot.data.no_expiry,
|
||||
},
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty);
|
||||
return (
|
||||
<details className="mt-3">
|
||||
<summary className="cursor-pointer text-sm">
|
||||
Identificar ou corrigir dados do lote
|
||||
</summary>
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="mt-3 grid gap-3 md:grid-cols-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post('/stock/lotes');
|
||||
form.post('/stock/lotes', {
|
||||
onSuccess: () => {
|
||||
const next = {
|
||||
...initial,
|
||||
operation_key: crypto.randomUUID(),
|
||||
};
|
||||
form.setData(next);
|
||||
form.clearErrors();
|
||||
router.remember(next, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<p className="text-sm text-muted-foreground md:col-span-2">
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import { useInventoryPreparationIdentity } from '@/hooks/use-inventory-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { Head, Link, router, useForm, useRemember } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { InventoryNotice, InventoryPagination } from '@/components/inventory';
|
||||
import { LotCountFields, countTotal } from '@/components/inventory-lot-count';
|
||||
@@ -105,7 +108,20 @@ const kinds: Record<string, string> = {
|
||||
count: 'Contagem física',
|
||||
adjustment: 'Ajuste de inventário',
|
||||
};
|
||||
export default function Operations({
|
||||
export default function Operations(props: Props) {
|
||||
if (props.demo)
|
||||
return (
|
||||
<OperationFields {...props} identity="inventory-operations:demo" />
|
||||
);
|
||||
return <PrivateOperations {...props} />;
|
||||
}
|
||||
function PrivateOperations(props: Props) {
|
||||
const identity = useInventoryPreparationIdentity(
|
||||
`/stock/operacoes:${props.canOperate}:${props.canAdjust ?? false}`,
|
||||
);
|
||||
return <OperationFields key={identity} {...props} identity={identity} />;
|
||||
}
|
||||
function OperationFields({
|
||||
items,
|
||||
warehouses,
|
||||
users,
|
||||
@@ -119,9 +135,10 @@ export default function Operations({
|
||||
lotCounts = [],
|
||||
demo = false,
|
||||
equipment = [],
|
||||
}: Props) {
|
||||
identity,
|
||||
}: Props & { identity: string }) {
|
||||
const [message, setMessage] = useState('');
|
||||
const form = useForm({
|
||||
const initial = {
|
||||
kind: canOperate ? 'issue' : 'adjustment',
|
||||
reference: '',
|
||||
idempotency_key: crypto.randomUUID(),
|
||||
@@ -135,7 +152,8 @@ export default function Operations({
|
||||
count_id: '',
|
||||
ledger_version: 0,
|
||||
equipment_id: '',
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial);
|
||||
const balance = balances.find(
|
||||
(b) =>
|
||||
String(b.stock_item_id) === form.data.stock_item_id &&
|
||||
@@ -146,9 +164,9 @@ export default function Operations({
|
||||
String(s.stock_item_id) === form.data.stock_item_id &&
|
||||
String(s.warehouse_id) === form.data.warehouse_id,
|
||||
);
|
||||
const [countInputs, setCountInputs] = useState<
|
||||
const [countInputs, setCountInputs] = useRemember<
|
||||
Record<string, CountInput[]>
|
||||
>({});
|
||||
>({}, `${identity}:lot-count-inputs`);
|
||||
const countKey = countSource?.hash ?? '';
|
||||
const countRows =
|
||||
countInputs[countKey] ??
|
||||
@@ -163,6 +181,12 @@ export default function Operations({
|
||||
no_expiry: lot.no_expiry,
|
||||
})) ??
|
||||
[];
|
||||
const dirty =
|
||||
hasPreparationChanges(
|
||||
{ ...initial, idempotency_key: '' },
|
||||
{ ...form.data, idempotency_key: '' },
|
||||
) || Object.keys(countInputs).length > 0;
|
||||
const ref = usePreparationDirty(dirty, !demo && (canOperate || canAdjust));
|
||||
return (
|
||||
<>
|
||||
<Head title="Operações de stock" />
|
||||
@@ -173,7 +197,11 @@ export default function Operations({
|
||||
description="Movimentos com fundamento, contagens físicas e histórico preservado."
|
||||
/>
|
||||
<InventoryNotice />
|
||||
{canViewReturns && <Link href="/stock/devolucoes-internas">Conferir devoluções de excedentes</Link>}
|
||||
{canViewReturns && (
|
||||
<Link href="/stock/devolucoes-internas">
|
||||
Conferir devoluções de excedentes
|
||||
</Link>
|
||||
)}
|
||||
{canOperate && form.data.kind === 'issue' && (
|
||||
<label className="grid gap-2 text-sm">
|
||||
Equipamento de destino (obrigatório para peças
|
||||
@@ -206,6 +234,8 @@ export default function Operations({
|
||||
>
|
||||
{canOperate || canAdjust ? (
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="grid gap-4 sm:grid-cols-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -230,14 +260,31 @@ export default function Operations({
|
||||
}));
|
||||
form.post('/stock/operacoes', {
|
||||
onSuccess: () => {
|
||||
form.setData({
|
||||
const next = {
|
||||
...form.data,
|
||||
idempotency_key:
|
||||
crypto.randomUUID(),
|
||||
reference: '',
|
||||
quantity: '',
|
||||
reason: '',
|
||||
});
|
||||
};
|
||||
form.setData(next);
|
||||
form.clearErrors();
|
||||
router.remember(
|
||||
next,
|
||||
`${identity}:data`,
|
||||
);
|
||||
router.remember(
|
||||
{},
|
||||
`${identity}:errors`,
|
||||
);
|
||||
const remaining = { ...countInputs };
|
||||
delete remaining[countKey];
|
||||
setCountInputs(remaining);
|
||||
router.remember(
|
||||
remaining,
|
||||
`${identity}:lot-count-inputs`,
|
||||
);
|
||||
},
|
||||
});
|
||||
}}
|
||||
@@ -537,7 +584,8 @@ export default function Operations({
|
||||
'Devolução ao fornecedor',
|
||||
write_off: 'Abate físico',
|
||||
reversal: 'Estorno integral',
|
||||
workshop_return: 'Devolução de excedente',
|
||||
workshop_return:
|
||||
'Devolução de excedente',
|
||||
}[o.kind] ??
|
||||
o.kind}
|
||||
</strong>
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { useInventoryPreparationIdentity } from '@/hooks/use-inventory-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import { InventoryEventActions } from '@/components/inventory-event-actions';
|
||||
import { Head, Link, router, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
@@ -86,6 +89,32 @@ const states: Record<string, string> = {
|
||||
};
|
||||
|
||||
function Prepare({ props, old }: { props: Props; old?: Entry }) {
|
||||
const capabilities = JSON.stringify(
|
||||
Object.entries(props.capabilities).sort(([a], [b]) =>
|
||||
a.localeCompare(b),
|
||||
),
|
||||
);
|
||||
const identity = useInventoryPreparationIdentity(
|
||||
`/stock/estornos:prepare:${old?.record_key ?? 'new'}:${old?.version ?? 0}:${old?.state ?? 'new'}:${capabilities}`,
|
||||
);
|
||||
return (
|
||||
<PrepareFields
|
||||
key={identity}
|
||||
props={props}
|
||||
old={old}
|
||||
identity={identity}
|
||||
/>
|
||||
);
|
||||
}
|
||||
function PrepareFields({
|
||||
props,
|
||||
old,
|
||||
identity,
|
||||
}: {
|
||||
props: Props;
|
||||
old?: Entry;
|
||||
identity: string;
|
||||
}) {
|
||||
const [operations, setOperations] = useState(props.operations);
|
||||
const [receipts, setReceipts] = useState(props.receipts);
|
||||
const formKey = `reversal:${old?.id ?? 'new'}`;
|
||||
@@ -95,7 +124,7 @@ function Prepare({ props, old }: { props: Props; old?: Entry }) {
|
||||
setReceipts(props.receipts);
|
||||
}
|
||||
}, [props.sourceFormKey, props.operations, props.receipts, formKey]);
|
||||
const form = useForm({
|
||||
const initial = {
|
||||
operation_key: crypto.randomUUID(),
|
||||
record_key: old?.record_key,
|
||||
version: old?.version ?? 0,
|
||||
@@ -111,7 +140,10 @@ function Prepare({ props, old }: { props: Props; old?: Entry }) {
|
||||
? String(old.data.receipt_item_id)
|
||||
: '',
|
||||
},
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty);
|
||||
const searchSources = (value: string) =>
|
||||
router.get(
|
||||
'/stock/estornos',
|
||||
@@ -142,10 +174,23 @@ function Prepare({ props, old }: { props: Props; old?: Entry }) {
|
||||
);
|
||||
return (
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="grid gap-4 md:grid-cols-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post('/stock/estornos');
|
||||
form.post('/stock/estornos', {
|
||||
onSuccess: () => {
|
||||
const next = {
|
||||
...initial,
|
||||
operation_key: crypto.randomUUID(),
|
||||
};
|
||||
form.setData(next);
|
||||
form.clearErrors();
|
||||
router.remember(next, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
@@ -195,6 +240,20 @@ function Prepare({ props, old }: { props: Props; old?: Entry }) {
|
||||
{op.label}
|
||||
</option>
|
||||
))}
|
||||
{form.data.data.source_operation_id &&
|
||||
!operations.some(
|
||||
(op) =>
|
||||
String(op.id) ===
|
||||
form.data.data.source_operation_id,
|
||||
) && (
|
||||
<option
|
||||
value={form.data.data.source_operation_id}
|
||||
disabled
|
||||
>
|
||||
Origem seleccionada — pesquisar para
|
||||
conferir disponibilidade
|
||||
</option>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
) : (
|
||||
@@ -217,6 +276,20 @@ function Prepare({ props, old }: { props: Props; old?: Entry }) {
|
||||
{receipt.label}
|
||||
</option>
|
||||
))}
|
||||
{form.data.data.receipt_item_id &&
|
||||
!receipts.some(
|
||||
(receipt) =>
|
||||
String(receipt.id) ===
|
||||
form.data.data.receipt_item_id,
|
||||
) && (
|
||||
<option
|
||||
value={form.data.data.receipt_item_id}
|
||||
disabled
|
||||
>
|
||||
Origem seleccionada — pesquisar para
|
||||
conferir disponibilidade
|
||||
</option>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
Head,
|
||||
Link,
|
||||
router,
|
||||
useForm,
|
||||
usePage,
|
||||
useRemember,
|
||||
} from '@inertiajs/react';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import {
|
||||
FormErrors,
|
||||
Panel,
|
||||
@@ -51,9 +59,10 @@ type Props = {
|
||||
canReview: boolean;
|
||||
};
|
||||
export default function BankPage(props: Props) {
|
||||
const actor = usePage().props.auth?.user;
|
||||
return (
|
||||
<Bank
|
||||
key={`${props.supplier.id}:${props.accountKey ?? 'legacy'}:${props.actorId ?? 0}:${props.canPropose}:${props.canReview}`}
|
||||
key={`${actor?.tenant_id}:${props.supplier.id}:${props.accountKey ?? 'legacy'}:${props.actorId ?? actor?.id ?? 0}:${props.currentId}:${props.state}:${props.canPropose}:${props.canReview}`}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
@@ -71,9 +80,15 @@ function Bank({
|
||||
accountKey = null,
|
||||
accounts = [],
|
||||
multiAccountsAvailable = false,
|
||||
actorId,
|
||||
}: Props) {
|
||||
const [addingAccount, setAddingAccount] = useState(false);
|
||||
const form = useForm({
|
||||
const actor = usePage().props.auth?.user;
|
||||
const identity = `supplier-bank:${actor?.tenant_id}:${actorId ?? actor?.id ?? 0}:${supplier.id}:${accountKey ?? 'legacy'}:${currentId}:${canPropose}:${canReview}`;
|
||||
const [addingAccount, setAddingAccount] = useRemember(
|
||||
false,
|
||||
`${identity}:adding`,
|
||||
);
|
||||
const initial = {
|
||||
previous_id: currentId,
|
||||
account_key: accountKey,
|
||||
bank_name: '',
|
||||
@@ -83,12 +98,29 @@ function Bank({
|
||||
account_identifier: '',
|
||||
evidence_reference: '',
|
||||
reason: '',
|
||||
});
|
||||
const review = useForm({
|
||||
};
|
||||
const form = useForm(`${identity}:proposal`, initial);
|
||||
const initialReview = {
|
||||
decision: 'approved',
|
||||
reason: '',
|
||||
independently_verified: false,
|
||||
});
|
||||
};
|
||||
const review = useForm(`${identity}:review`, initialReview);
|
||||
const dirty = Object.values({
|
||||
bank_name: form.data.bank_name,
|
||||
country: form.data.country,
|
||||
currency: form.data.currency,
|
||||
beneficiary: form.data.beneficiary,
|
||||
account_identifier: form.data.account_identifier,
|
||||
evidence_reference: form.data.evidence_reference,
|
||||
reason: form.data.reason,
|
||||
}).some((value) => value !== '');
|
||||
const proposalRef = usePreparationDirty(dirty, canPropose);
|
||||
const reviewDirty = hasPreparationChanges(initialReview, review.data);
|
||||
const reviewRef = usePreparationDirty(
|
||||
reviewDirty,
|
||||
canReview && current !== null && state === 'pending',
|
||||
);
|
||||
const labels = {
|
||||
bank_name: 'Banco',
|
||||
country: 'Código do país (2 letras)',
|
||||
@@ -189,11 +221,25 @@ function Bank({
|
||||
{canReview && current && state === 'pending' && (
|
||||
<Panel title="Conferência independente">
|
||||
<form
|
||||
ref={reviewRef}
|
||||
data-preparation-dirty={
|
||||
reviewDirty ? 'true' : 'false'
|
||||
}
|
||||
className="grid gap-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
review.post(
|
||||
`/fornecedores/${supplier.id}/dados-bancarios/${current.id}/validar`,
|
||||
{
|
||||
onSuccess: () => {
|
||||
review.reset();
|
||||
review.clearErrors();
|
||||
router.remember(
|
||||
initialReview,
|
||||
`${identity}:review:data`,
|
||||
);
|
||||
},
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
@@ -256,18 +302,26 @@ function Bank({
|
||||
description="Preencha integralmente os dados confirmados. A nova versão exige duas validações novas; a versão anterior permanece no histórico."
|
||||
>
|
||||
<form
|
||||
ref={proposalRef}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="grid gap-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post(
|
||||
`/fornecedores/${supplier.id}/dados-bancarios`,
|
||||
{
|
||||
onSuccess: (page) => {
|
||||
onSuccess: () => {
|
||||
form.reset();
|
||||
form.setData(
|
||||
'previous_id',
|
||||
Number(page.props.currentId),
|
||||
form.clearErrors();
|
||||
router.remember(
|
||||
initial,
|
||||
`${identity}:proposal:data`,
|
||||
);
|
||||
router.remember(
|
||||
false,
|
||||
`${identity}:adding`,
|
||||
);
|
||||
setAddingAccount(false);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
@@ -3,7 +3,9 @@ import type {
|
||||
GeographyDescription,
|
||||
GeographyReference,
|
||||
} from '@/components/administrative-location';
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import { Head, Link, useForm, usePage } from '@inertiajs/react';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import {
|
||||
ActionBar,
|
||||
FormErrors,
|
||||
@@ -17,7 +19,7 @@ import { Label } from '@/components/ui/label';
|
||||
import { supplierFields } from '@/types/supplier';
|
||||
import type { Supplier } from '@/types/supplier';
|
||||
|
||||
export default function EditSupplier({
|
||||
function EditSupplierContent({
|
||||
supplier,
|
||||
geographyEnabled = false,
|
||||
geography = null,
|
||||
@@ -26,23 +28,29 @@ export default function EditSupplier({
|
||||
geographyEnabled?: boolean;
|
||||
geography?: GeographyDescription;
|
||||
}) {
|
||||
const form = useForm({
|
||||
geography_reference:
|
||||
supplier.geography_reference ?? (null as GeographyReference | null),
|
||||
name: supplier.name,
|
||||
nuit: supplier.nuit,
|
||||
contact: supplier.contact,
|
||||
email: supplier.email,
|
||||
phone: supplier.phone,
|
||||
address: supplier.address,
|
||||
category: supplier.category,
|
||||
beneficiaries: supplier.beneficiaries,
|
||||
document_references: supplier.document_references,
|
||||
diligence_notes: supplier.diligence_notes,
|
||||
next_review: supplier.next_review.slice(0, 10),
|
||||
blocked: supplier.blocked,
|
||||
version: supplier.version,
|
||||
});
|
||||
const actor = usePage().props.auth?.user;
|
||||
const form = useForm(
|
||||
`supplier-preparation:${actor?.tenant_id}:${actor?.id}:${supplier.id}:${supplier.version}`,
|
||||
{
|
||||
geography_reference:
|
||||
supplier.geography_reference ??
|
||||
(null as GeographyReference | null),
|
||||
name: supplier.name,
|
||||
nuit: supplier.nuit,
|
||||
contact: supplier.contact,
|
||||
email: supplier.email,
|
||||
phone: supplier.phone,
|
||||
address: supplier.address,
|
||||
category: supplier.category,
|
||||
beneficiaries: supplier.beneficiaries,
|
||||
document_references: supplier.document_references,
|
||||
diligence_notes: supplier.diligence_notes,
|
||||
next_review: supplier.next_review.slice(0, 10),
|
||||
blocked: supplier.blocked,
|
||||
version: supplier.version,
|
||||
},
|
||||
);
|
||||
const preparationRef = usePreparationDirty(form.isDirty);
|
||||
return (
|
||||
<>
|
||||
<Head title={`Editar ${supplier.name}`} />
|
||||
@@ -59,6 +67,7 @@ export default function EditSupplier({
|
||||
elegível para novas cotações.
|
||||
</p>
|
||||
<form
|
||||
ref={preparationRef}
|
||||
className="space-y-5"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -162,6 +171,17 @@ export default function EditSupplier({
|
||||
</>
|
||||
);
|
||||
}
|
||||
export default function EditSupplier(
|
||||
props: ComponentProps<typeof EditSupplierContent>,
|
||||
) {
|
||||
const actor = usePage().props.auth?.user;
|
||||
return (
|
||||
<EditSupplierContent
|
||||
key={`${actor?.tenant_id}:${actor?.id}:${props.supplier.id}:${props.supplier.version}`}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
EditSupplier.layout = {
|
||||
breadcrumbs: [
|
||||
{ title: 'Fornecedores', href: '/fornecedores' },
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { useProcurementPreparationIdentity } from '@/hooks/use-procurement-preparation-identity';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import type { GeographyDescription } from '@/components/administrative-location';
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import { Head, Link, router, useForm } from '@inertiajs/react';
|
||||
import { Download, FileLock2, Pencil, Upload } from 'lucide-react';
|
||||
import { useRef } from 'react';
|
||||
import {
|
||||
@@ -48,7 +51,6 @@ export default function SupplierShow({
|
||||
file: null,
|
||||
document_type: 'license',
|
||||
});
|
||||
const review = useForm({ status: 'active', comment: '' });
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
return (
|
||||
<>
|
||||
@@ -268,65 +270,7 @@ export default function SupplierShow({
|
||||
title="Validação independente por Finanças"
|
||||
description="Confira os dados e os documentos actuais antes de decidir."
|
||||
>
|
||||
<form
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
review.transform((data) => ({
|
||||
...data,
|
||||
version: supplier.version,
|
||||
}));
|
||||
review.post(
|
||||
`/fornecedores/${supplier.id}/validar`,
|
||||
{
|
||||
preserveScroll: true,
|
||||
onSuccess: () => review.reset(),
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={review.errors} />
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="review-result">Resultado</Label>
|
||||
<select
|
||||
id="review-result"
|
||||
className={controlClass}
|
||||
value={review.data.status}
|
||||
onChange={(e) =>
|
||||
review.setData('status', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="active">
|
||||
Activar fornecedor
|
||||
</option>
|
||||
<option value="suspended">
|
||||
Suspender fornecedor
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="review-reason">
|
||||
Fundamento da decisão
|
||||
</Label>
|
||||
<textarea
|
||||
id="review-reason"
|
||||
className={`${controlClass} h-24 py-2`}
|
||||
required
|
||||
minLength={10}
|
||||
maxLength={2000}
|
||||
value={review.data.comment}
|
||||
onChange={(e) =>
|
||||
review.setData(
|
||||
'comment',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<Button disabled={review.processing}>
|
||||
Registar decisão
|
||||
</Button>
|
||||
</form>
|
||||
<SupplierReview supplier={supplier} />
|
||||
</Panel>
|
||||
)}
|
||||
</div>
|
||||
@@ -339,3 +283,74 @@ SupplierShow.layout = {
|
||||
{ title: 'Ficha e documentos', href: '#' },
|
||||
],
|
||||
};
|
||||
|
||||
function SupplierReview({ supplier }: { supplier: Supplier }) {
|
||||
const identity = useProcurementPreparationIdentity(
|
||||
`supplier-review:${supplier.id}:${supplier.version}`,
|
||||
);
|
||||
return (
|
||||
<ReviewFields key={identity} supplier={supplier} identity={identity} />
|
||||
);
|
||||
}
|
||||
function ReviewFields({
|
||||
supplier,
|
||||
identity,
|
||||
}: {
|
||||
supplier: Supplier;
|
||||
identity: string;
|
||||
}) {
|
||||
const initial = { status: 'active', comment: '' };
|
||||
const review = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(initial, review.data);
|
||||
const ref = usePreparationDirty(dirty);
|
||||
return (
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
review.transform((data) => ({
|
||||
...data,
|
||||
version: supplier.version,
|
||||
}));
|
||||
review.post(`/fornecedores/${supplier.id}/validar`, {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
review.setData(initial);
|
||||
review.clearErrors();
|
||||
router.remember(initial, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={review.errors} />
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="review-result">Resultado</Label>
|
||||
<select
|
||||
id="review-result"
|
||||
className={controlClass}
|
||||
value={review.data.status}
|
||||
onChange={(e) => review.setData('status', e.target.value)}
|
||||
>
|
||||
<option value="active">Activar fornecedor</option>
|
||||
<option value="suspended">Suspender fornecedor</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="review-reason">Fundamento da decisão</Label>
|
||||
<textarea
|
||||
id="review-reason"
|
||||
className={`${controlClass} h-24 py-2`}
|
||||
required
|
||||
minLength={10}
|
||||
maxLength={2000}
|
||||
value={review.data.comment}
|
||||
onChange={(e) => review.setData('comment', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<Button disabled={review.processing}>Registar decisão</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
import { Head, Link, router, useForm } from '@inertiajs/react';
|
||||
import {
|
||||
Head,
|
||||
Link,
|
||||
router,
|
||||
useForm,
|
||||
usePage,
|
||||
useRemember,
|
||||
} from '@inertiajs/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import type { WorkContextState } from '@/types/work-context';
|
||||
import {
|
||||
ReceiptConversionFields,
|
||||
type ReceiptConversion,
|
||||
@@ -120,13 +130,43 @@ const quantity = (milli: number) =>
|
||||
(milli / 1000).toLocaleString('pt-MZ', { maximumFractionDigits: 3 });
|
||||
|
||||
function Prepare({ props, old }: { props: Props; old?: RecordVersion }) {
|
||||
const [conversion, setConversion] = useState<ReceiptConversion>(
|
||||
old?.snapshot.quantity_conversion ?? {
|
||||
numerator: '',
|
||||
denominator: '',
|
||||
source: '',
|
||||
version: '',
|
||||
},
|
||||
const identity = `${useCoordinationIdentity(props, old)}:prepare`;
|
||||
return (
|
||||
<PrepareForm
|
||||
key={identity}
|
||||
props={props}
|
||||
old={old}
|
||||
identity={identity}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function useCoordinationIdentity(props: Props, record?: RecordVersion) {
|
||||
const page = usePage().props;
|
||||
const actor = page.auth?.user;
|
||||
const context = page.workContext as WorkContextState | null | undefined;
|
||||
return `supply-coordination:${actor?.tenant_id}:${actor?.id}:${props.kind}:${props.ready}:${props.canPrepare}:${props.canReview}:${props.conversionQaEnabled ?? false}:${record?.record_key ?? 'new'}:${record?.version ?? 0}:${record?.state ?? 'new'}:${record ? (props.pending[record.record_key] ?? '') : ''}${context?.active ? `:context:${context.active}` : ''}`;
|
||||
}
|
||||
|
||||
function PrepareForm({
|
||||
props,
|
||||
old,
|
||||
identity,
|
||||
}: {
|
||||
props: Props;
|
||||
old?: RecordVersion;
|
||||
identity: string;
|
||||
}) {
|
||||
const initialConversion: ReceiptConversion = old?.snapshot
|
||||
.quantity_conversion ?? {
|
||||
numerator: '',
|
||||
denominator: '',
|
||||
source: '',
|
||||
version: '',
|
||||
};
|
||||
const [conversion, setConversion] = useRemember<ReceiptConversion>(
|
||||
initialConversion,
|
||||
`${identity}:conversion`,
|
||||
);
|
||||
const [orderLines, setOrderLines] = useState(props.orderLines);
|
||||
const [requestLines, setRequestLines] = useState(props.requestLines);
|
||||
@@ -173,14 +213,20 @@ function Prepare({ props, old }: { props: Props; old?: RecordVersion }) {
|
||||
if (old.data.quantity_milli !== undefined)
|
||||
defaults.quantity = Number(old.data.quantity_milli) / 1000;
|
||||
}
|
||||
const form = useForm({
|
||||
const initial = {
|
||||
operation_key: crypto.randomUUID(),
|
||||
record_key: old?.record_key,
|
||||
version: old?.version ?? 0,
|
||||
action: 'save',
|
||||
reason: '',
|
||||
data: defaults,
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(
|
||||
{ ...initial, conversion: initialConversion },
|
||||
{ ...form.data, conversion },
|
||||
);
|
||||
const ref = usePreparationDirty(dirty);
|
||||
const documentUnit =
|
||||
orderLines.find(
|
||||
(line) => line.id === Number(form.data.data.purchase_order_item_id),
|
||||
@@ -270,6 +316,8 @@ function Prepare({ props, old }: { props: Props; old?: RecordVersion }) {
|
||||
);
|
||||
return (
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="mt-4 space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -291,8 +339,21 @@ function Prepare({ props, old }: { props: Props; old?: RecordVersion }) {
|
||||
});
|
||||
form.post(`/compras/fornecimento/${props.kind}`, {
|
||||
preserveScroll: true,
|
||||
onSuccess: () =>
|
||||
form.setData('operation_key', crypto.randomUUID()),
|
||||
onSuccess: () => {
|
||||
const clean = {
|
||||
...initial,
|
||||
operation_key: crypto.randomUUID(),
|
||||
};
|
||||
form.setData(clean);
|
||||
form.clearErrors();
|
||||
setConversion(initialConversion);
|
||||
router.remember(clean, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
router.remember(
|
||||
initialConversion,
|
||||
`${identity}:conversion`,
|
||||
);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -542,14 +603,33 @@ function Prepare({ props, old }: { props: Props; old?: RecordVersion }) {
|
||||
}
|
||||
|
||||
function Actions({ props, record }: { props: Props; record: RecordVersion }) {
|
||||
const [action, setAction] = useState('');
|
||||
const identity = `${useCoordinationIdentity(props, record)}:action:${record.canApprove}:${record.canReturn}:${record.canSuspend}:${record.canEdit}:${record.canFulfil}:${record.canCancel}`;
|
||||
return (
|
||||
<ActionsForm
|
||||
key={identity}
|
||||
props={props}
|
||||
record={record}
|
||||
identity={identity}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ActionsForm({
|
||||
props,
|
||||
record,
|
||||
identity,
|
||||
}: {
|
||||
props: Props;
|
||||
record: RecordVersion;
|
||||
identity: string;
|
||||
}) {
|
||||
const [issueSearch, setIssueSearch] = useState(props.issueSearch ?? '');
|
||||
const [operationOptions, setOperationOptions] = useState(props.operations);
|
||||
useEffect(() => {
|
||||
if (props.issueRecordId === record.id)
|
||||
setOperationOptions(props.operations);
|
||||
}, [props.issueRecordId, props.operations, record.id]);
|
||||
const form = useForm({
|
||||
const initial = {
|
||||
operation_key: crypto.randomUUID(),
|
||||
record_key: record.record_key,
|
||||
version: record.version,
|
||||
@@ -557,7 +637,11 @@ function Actions({ props, record }: { props: Props; record: RecordVersion }) {
|
||||
reason: '',
|
||||
data: { stock_operation_id: '', quantity_milli: 0 },
|
||||
quantity: '',
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial);
|
||||
const action = form.data.action;
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty, Boolean(action));
|
||||
const choices =
|
||||
props.kind === 'alternative'
|
||||
? [
|
||||
@@ -620,7 +704,6 @@ function Actions({ props, record }: { props: Props; record: RecordVersion }) {
|
||||
className={controlClass}
|
||||
value={action}
|
||||
onChange={(e) => {
|
||||
setAction(e.target.value);
|
||||
form.setData('action', e.target.value);
|
||||
}}
|
||||
>
|
||||
@@ -635,6 +718,8 @@ function Actions({ props, record }: { props: Props; record: RecordVersion }) {
|
||||
)}
|
||||
{action && (
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -649,6 +734,16 @@ function Actions({ props, record }: { props: Props; record: RecordVersion }) {
|
||||
}));
|
||||
form.post(`/compras/fornecimento/${props.kind}`, {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
const clean = {
|
||||
...initial,
|
||||
operation_key: crypto.randomUUID(),
|
||||
};
|
||||
form.setData(clean);
|
||||
form.clearErrors();
|
||||
router.remember(clean, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import { Head, Link, router, useForm, usePage } 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,
|
||||
PageTitle,
|
||||
@@ -107,7 +110,34 @@ const qty = (milli: number | string, mean = false) =>
|
||||
});
|
||||
|
||||
function Prepare({ props, old }: { props: Props; old?: HistoryRecord }) {
|
||||
const form = useForm({
|
||||
const identity = `${useHistoryIdentity(props, old)}:prepare`;
|
||||
return (
|
||||
<PrepareForm
|
||||
key={identity}
|
||||
props={props}
|
||||
old={old}
|
||||
identity={identity}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function useHistoryIdentity(props: Props, record?: HistoryRecord) {
|
||||
const page = usePage().props;
|
||||
const actor = page.auth?.user;
|
||||
const context = page.workContext as WorkContextState | null | undefined;
|
||||
return `supply-history:${actor?.tenant_id}:${props.actorId ?? actor?.id}:${props.ready}:${props.canPrepare}:${props.canReview}:${record?.record_key ?? 'new'}:${record?.version ?? 0}:${record?.state ?? 'new'}${context?.active ? `:context:${context.active}` : ''}`;
|
||||
}
|
||||
|
||||
function PrepareForm({
|
||||
props,
|
||||
old,
|
||||
identity,
|
||||
}: {
|
||||
props: Props;
|
||||
old?: HistoryRecord;
|
||||
identity: string;
|
||||
}) {
|
||||
const initial = {
|
||||
operation_key: crypto.randomUUID(),
|
||||
record_key: old?.record_key,
|
||||
version: old?.version ?? 0,
|
||||
@@ -122,7 +152,10 @@ function Prepare({ props, old }: { props: Props; old?: HistoryRecord }) {
|
||||
quality: old?.data.quality ?? 'unknown',
|
||||
pattern: old?.data.pattern ?? 'unknown',
|
||||
},
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty);
|
||||
const select = (
|
||||
key: keyof typeof form.data.data,
|
||||
label: string,
|
||||
@@ -153,11 +186,23 @@ function Prepare({ props, old }: { props: Props; old?: HistoryRecord }) {
|
||||
);
|
||||
return (
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="mt-4 space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post('/compras/fornecimento/history', {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
const clean = {
|
||||
...initial,
|
||||
operation_key: crypto.randomUUID(),
|
||||
};
|
||||
form.setData(clean);
|
||||
form.clearErrors();
|
||||
router.remember(clean, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -393,21 +438,32 @@ function Facts({
|
||||
);
|
||||
}
|
||||
|
||||
function Decision({
|
||||
function Decision(input: { props: Props; record: HistoryRecord }) {
|
||||
const r = input.record;
|
||||
const identity = `${useHistoryIdentity(input.props, r)}:decision:${r.canApprove}:${r.canReturn}:${r.canSuspend}`;
|
||||
return <DecisionForm key={identity} {...input} identity={identity} />;
|
||||
}
|
||||
|
||||
function DecisionForm({
|
||||
props,
|
||||
record: r,
|
||||
identity,
|
||||
}: {
|
||||
props: Props;
|
||||
record: HistoryRecord;
|
||||
identity: string;
|
||||
}) {
|
||||
const form = useForm({
|
||||
const initial = {
|
||||
operation_key: crypto.randomUUID(),
|
||||
record_key: r.record_key,
|
||||
version: r.version,
|
||||
action: '',
|
||||
reason: '',
|
||||
data: { confirm_scope: false },
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty, Boolean(form.data.action));
|
||||
return (
|
||||
<div className="mt-4 space-y-4">
|
||||
{props.canPrepare && ['draft', 'returned'].includes(r.state) && (
|
||||
@@ -449,11 +505,29 @@ function Decision({
|
||||
</label>
|
||||
{form.data.action && (
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post('/compras/fornecimento/history', {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
const clean = {
|
||||
...initial,
|
||||
operation_key: crypto.randomUUID(),
|
||||
};
|
||||
form.setData(clean);
|
||||
form.clearErrors();
|
||||
router.remember(
|
||||
clean,
|
||||
`${identity}:data`,
|
||||
);
|
||||
router.remember(
|
||||
{},
|
||||
`${identity}:errors`,
|
||||
);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { Head, Link, router, useForm } from '@inertiajs/react';
|
||||
import { Head, Link, router, useForm, usePage } from '@inertiajs/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import type { WorkContextState } from '@/types/work-context';
|
||||
import {
|
||||
FormErrors,
|
||||
PageTitle,
|
||||
@@ -244,14 +247,34 @@ function PreservedData({ record }: { record: SupplyRecord }) {
|
||||
);
|
||||
}
|
||||
|
||||
function Preparation({
|
||||
function useSupplyIdentity(props: Props, record?: SupplyRecord) {
|
||||
const page = usePage().props;
|
||||
const actor = page.auth?.user;
|
||||
const context = page.workContext as WorkContextState | null | undefined;
|
||||
return `supply:${actor?.tenant_id}:${actor?.id}:${props.kind}:${props.view}:${props.linkedContractKey ?? ''}:${props.linkedAgreementKey ?? ''}:${props.ready}:${props.canPrepare}:${props.canReview}:${props.canCustoms}:${props.orderLimitsReady ?? false}:${record?.record_key ?? 'new'}:${record?.version ?? 0}:${record?.state ?? 'new'}${context?.active ? `:context:${context.active}` : ''}`;
|
||||
}
|
||||
|
||||
function Preparation(input: {
|
||||
props: Props;
|
||||
record?: SupplyRecord;
|
||||
copy?: boolean;
|
||||
}) {
|
||||
const historyKey = `${useSupplyIdentity(input.props, input.record)}:${input.copy ? 'copy' : 'prepare'}`;
|
||||
return (
|
||||
<PreparationForm key={historyKey} {...input} historyKey={historyKey} />
|
||||
);
|
||||
}
|
||||
|
||||
function PreparationForm({
|
||||
props,
|
||||
record,
|
||||
copy = false,
|
||||
historyKey,
|
||||
}: {
|
||||
props: Props;
|
||||
record?: SupplyRecord;
|
||||
copy?: boolean;
|
||||
historyKey: string;
|
||||
}) {
|
||||
const defaults: Data =
|
||||
props.kind === 'policy'
|
||||
@@ -350,14 +373,17 @@ function Preparation({
|
||||
}
|
||||
}
|
||||
}
|
||||
const form = useForm({
|
||||
const initial = {
|
||||
operation_key: crypto.randomUUID(),
|
||||
record_key: copy ? undefined : record?.record_key,
|
||||
version: copy ? 0 : (record?.version ?? 0),
|
||||
action: 'save',
|
||||
reason: '',
|
||||
data: defaults,
|
||||
});
|
||||
};
|
||||
const form = useForm(historyKey, initial);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty);
|
||||
const [orderSearch, setOrderSearch] = useState(props.orderSearch ?? '');
|
||||
const [historyOptions, setHistoryOptions] = useState(props.histories);
|
||||
const [periodFrom, setPeriodFrom] = useState('');
|
||||
@@ -517,6 +543,8 @@ function Preparation({
|
||||
);
|
||||
return (
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -557,8 +585,16 @@ function Preparation({
|
||||
});
|
||||
form.post(`/compras/fornecimento/${props.kind}`, {
|
||||
preserveScroll: true,
|
||||
onSuccess: () =>
|
||||
form.setData('operation_key', crypto.randomUUID()),
|
||||
onSuccess: () => {
|
||||
const clean = {
|
||||
...initial,
|
||||
operation_key: crypto.randomUUID(),
|
||||
};
|
||||
form.setData(clean);
|
||||
form.clearErrors();
|
||||
router.remember(clean, `${historyKey}:data`);
|
||||
router.remember({}, `${historyKey}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -1119,22 +1155,38 @@ function Preparation({
|
||||
);
|
||||
}
|
||||
|
||||
function RecordActions({
|
||||
function RecordActions(input: { record: SupplyRecord; props: Props }) {
|
||||
const historyKey = `${useSupplyIdentity(input.props, input.record)}:action:${input.record.canApprove}:${input.record.canReturn}:${input.record.canSuspend}`;
|
||||
return (
|
||||
<RecordActionsForm
|
||||
key={historyKey}
|
||||
{...input}
|
||||
historyKey={historyKey}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function RecordActionsForm({
|
||||
record,
|
||||
props,
|
||||
historyKey,
|
||||
}: {
|
||||
record: SupplyRecord;
|
||||
props: Props;
|
||||
historyKey: string;
|
||||
}) {
|
||||
const [action, setAction] = useState('');
|
||||
const form = useForm({
|
||||
const initial = {
|
||||
operation_key: crypto.randomUUID(),
|
||||
record_key: record.record_key,
|
||||
version: record.version,
|
||||
action: '',
|
||||
reason: '',
|
||||
data: { evidence: '', event_date: '' },
|
||||
});
|
||||
};
|
||||
const form = useForm(historyKey, initial);
|
||||
const action = form.data.action;
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty, Boolean(action));
|
||||
const imports = props.kind === 'import';
|
||||
const choices: [string, string][] = imports
|
||||
? [
|
||||
@@ -1198,7 +1250,6 @@ function RecordActions({
|
||||
className={controlClass}
|
||||
value={action}
|
||||
onChange={(e) => {
|
||||
setAction(e.target.value);
|
||||
form.setData('action', e.target.value);
|
||||
}}
|
||||
>
|
||||
@@ -1214,11 +1265,23 @@ function RecordActions({
|
||||
)}
|
||||
{action && (
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post(`/compras/fornecimento/${props.kind}`, {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
const clean = {
|
||||
...initial,
|
||||
operation_key: crypto.randomUUID(),
|
||||
};
|
||||
form.setData(clean);
|
||||
form.clearErrors();
|
||||
router.remember(clean, `${historyKey}:data`);
|
||||
router.remember({}, `${historyKey}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { Head, Link, router, useForm } from '@inertiajs/react';
|
||||
import { Head, Link, router, useForm, usePage } from '@inertiajs/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
import type { WorkContextState } from '@/types/work-context';
|
||||
import {
|
||||
FormErrors,
|
||||
PageTitle,
|
||||
@@ -110,7 +113,33 @@ const quantity = (value: number) =>
|
||||
(value / 1000).toLocaleString('pt-MZ', { maximumFractionDigits: 3 });
|
||||
|
||||
function Prepare({ props, old }: { props: Props; old?: Suggestion }) {
|
||||
const [selected, setSelected] = useState(old?.data.policy_key ?? '');
|
||||
const identity = `${useSuggestionIdentity(props, old)}:prepare`;
|
||||
return (
|
||||
<PrepareForm
|
||||
key={identity}
|
||||
props={props}
|
||||
old={old}
|
||||
identity={identity}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function useSuggestionIdentity(props: Props, record?: Suggestion) {
|
||||
const page = usePage().props;
|
||||
const actor = page.auth?.user;
|
||||
const context = page.workContext as WorkContextState | null | undefined;
|
||||
return `supply-suggestion:${actor?.tenant_id}:${props.actorId ?? actor?.id}:${props.ready}:${props.canPrepare}:${props.canReview}:${props.canConvert}:${record?.record_key ?? 'new'}:${record?.version ?? 0}:${record?.state ?? 'new'}${context?.active ? `:context:${context.active}` : ''}`;
|
||||
}
|
||||
|
||||
function PrepareForm({
|
||||
props,
|
||||
old,
|
||||
identity,
|
||||
}: {
|
||||
props: Props;
|
||||
old?: Suggestion;
|
||||
identity: string;
|
||||
}) {
|
||||
const [policies, setPolicies] = useState(props.policies);
|
||||
const [policySearch, setPolicySearch] = useState(props.policySearch ?? '');
|
||||
const formKey = `suggestion:${old?.id ?? 'new'}`;
|
||||
@@ -118,8 +147,8 @@ function Prepare({ props, old }: { props: Props; old?: Suggestion }) {
|
||||
if (!props.policyFormKey || props.policyFormKey === formKey)
|
||||
setPolicies(props.policies);
|
||||
}, [props.policyFormKey, props.policies, formKey]);
|
||||
const option = policies.find((p) => p.key === selected);
|
||||
const form = useForm({
|
||||
const originalOption = policies.find((p) => p.key === old?.data.policy_key);
|
||||
const initial = {
|
||||
operation_key: crypto.randomUUID(),
|
||||
record_key: old?.record_key,
|
||||
version: old?.version ?? 0,
|
||||
@@ -127,14 +156,20 @@ function Prepare({ props, old }: { props: Props; old?: Suggestion }) {
|
||||
reason: '',
|
||||
data: {
|
||||
policy_key: old?.data.policy_key ?? '',
|
||||
unit_price: option?.unit_price ?? old?.data.unit_price ?? '',
|
||||
tax_rate: option?.tax_rate ?? old?.data.tax_rate ?? '',
|
||||
unit_price:
|
||||
originalOption?.unit_price ?? old?.data.unit_price ?? '',
|
||||
tax_rate: originalOption?.tax_rate ?? old?.data.tax_rate ?? '',
|
||||
quantity: old?.data.manual_plan
|
||||
? String(old.data.quantity_milli / 1000)
|
||||
: '',
|
||||
delivery_on: old?.data.manual_plan ? old.data.delivery_on : '',
|
||||
},
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial);
|
||||
const selected = form.data.data.policy_key;
|
||||
const option = policies.find((p) => p.key === selected);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty);
|
||||
const searchPolicies = () =>
|
||||
router.get(
|
||||
'/compras/fornecimento',
|
||||
@@ -156,6 +191,8 @@ function Prepare({ props, old }: { props: Props; old?: Suggestion }) {
|
||||
);
|
||||
return (
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="mt-4 space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -176,6 +213,16 @@ function Prepare({ props, old }: { props: Props; old?: Suggestion }) {
|
||||
}));
|
||||
form.post('/compras/fornecimento/suggestion', {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
const clean = {
|
||||
...initial,
|
||||
operation_key: crypto.randomUUID(),
|
||||
};
|
||||
form.setData(clean);
|
||||
form.clearErrors();
|
||||
router.remember(clean, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -227,7 +274,6 @@ function Prepare({ props, old }: { props: Props; old?: Suggestion }) {
|
||||
const p = policies.find(
|
||||
(o) => o.key === e.target.value,
|
||||
);
|
||||
setSelected(e.target.value);
|
||||
form.setData('data', {
|
||||
policy_key: e.target.value,
|
||||
unit_price: p?.unit_price ?? '',
|
||||
@@ -249,6 +295,11 @@ function Prepare({ props, old }: { props: Props; old?: Suggestion }) {
|
||||
indisponível
|
||||
</option>
|
||||
)}
|
||||
{!old && selected && !option && (
|
||||
<option value={selected}>
|
||||
Política seleccionada — procurar para conferir
|
||||
</option>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
{option?.issue && (
|
||||
@@ -522,14 +573,37 @@ function Facts({
|
||||
}
|
||||
|
||||
function Decisions({ props, record: r }: { props: Props; record: Suggestion }) {
|
||||
const form = useForm({
|
||||
const identity = `${useSuggestionIdentity(props, r)}:decision:${r.canApprove}:${r.canReturn}:${r.canConvert}:${r.canCancel}:${r.canClose}:${props.excess[r.record_key] ?? false}`;
|
||||
return (
|
||||
<DecisionsForm
|
||||
key={identity}
|
||||
props={props}
|
||||
record={r}
|
||||
identity={identity}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DecisionsForm({
|
||||
props,
|
||||
record: r,
|
||||
identity,
|
||||
}: {
|
||||
props: Props;
|
||||
record: Suggestion;
|
||||
identity: string;
|
||||
}) {
|
||||
const initial = {
|
||||
operation_key: crypto.randomUUID(),
|
||||
record_key: r.record_key,
|
||||
version: r.version,
|
||||
action: '',
|
||||
reason: '',
|
||||
data: { cost_center_id: '', confirm_exception: false },
|
||||
});
|
||||
};
|
||||
const form = useForm(identity, initial);
|
||||
const dirty = hasPreparationChanges(initial, form.data);
|
||||
const ref = usePreparationDirty(dirty, Boolean(form.data.action));
|
||||
const choices: [string, string][] = [];
|
||||
if (r.canApprove && !props.excess[r.record_key])
|
||||
choices.push(['approve', 'Aprovar para requisitar']);
|
||||
@@ -574,11 +648,23 @@ function Decisions({ props, record: r }: { props: Props; record: Suggestion }) {
|
||||
)}
|
||||
{form.data.action && (
|
||||
<form
|
||||
ref={ref}
|
||||
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||
className="space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post('/compras/fornecimento/suggestion', {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
const clean = {
|
||||
...initial,
|
||||
operation_key: crypto.randomUUID(),
|
||||
};
|
||||
form.setData(clean);
|
||||
form.clearErrors();
|
||||
router.remember(clean, `${identity}:data`);
|
||||
router.remember({}, `${identity}:errors`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { PageTitle, Panel, controlClass } from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
type Props = {
|
||||
urgentReviewsReady?: boolean;
|
||||
area: 'procurement' | 'people';
|
||||
modules: Record<string, string>;
|
||||
counts: Record<string, number>;
|
||||
@@ -30,6 +31,7 @@ type Props = {
|
||||
};
|
||||
|
||||
export default function Tasks({
|
||||
urgentReviewsReady = false,
|
||||
area,
|
||||
modules,
|
||||
counts,
|
||||
@@ -54,6 +56,14 @@ export default function Tasks({
|
||||
<>
|
||||
<Head title="As minhas tarefas" />
|
||||
<div className="space-y-6 p-6">
|
||||
{urgentReviewsReady && (
|
||||
<Link
|
||||
className="underline"
|
||||
href="/requisicoes/urgencias/revisoes"
|
||||
>
|
||||
Revisão posterior das urgências
|
||||
</Link>
|
||||
)}
|
||||
<PageTitle
|
||||
eyebrow={
|
||||
area === 'people'
|
||||
|
||||
@@ -101,6 +101,10 @@ export type PurchaseOrder = {
|
||||
items: OrderItem[];
|
||||
snapshot: {
|
||||
capital_assignments?: Record<number, FrozenCapitalAssignment>;
|
||||
account_assignments?: Record<
|
||||
string,
|
||||
import('@/components/requisition-account-summary').FrozenAccountAssignment
|
||||
>;
|
||||
import_tariffs?: Record<number, FrozenImportTariff>;
|
||||
budget_checked?: boolean;
|
||||
agreement_bindings?: Record<string, FrozenOrderAgreement>;
|
||||
|
||||
Reference in New Issue
Block a user