@@ -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`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
|
||||
Reference in New Issue
Block a user