1547 lines
74 KiB
TypeScript
1547 lines
74 KiB
TypeScript
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, 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';
|
|
import type { IntelligencePolicy } from '@/components/intelligence-settings';
|
|
import { comparisonCriteria } from '@/components/comparison-policy-summary';
|
|
import type { ComparisonPolicy } from '@/components/comparison-policy-summary';
|
|
import {
|
|
ActionBar,
|
|
PageTitle,
|
|
Panel,
|
|
FormErrors,
|
|
controlClass,
|
|
} from '@/components/procurement';
|
|
import { Button } from '@/components/ui/button';
|
|
import { WorkContextSettings } from '@/components/work-context-settings';
|
|
import type { WorkContextState } from '@/types/work-context';
|
|
import { OrganizationActivationPreview } from '@/components/organization-activation-preview';
|
|
import type { ActivationPreview } from '@/components/organization-activation-preview';
|
|
|
|
type Profile = {
|
|
id: number;
|
|
name: string;
|
|
permissions: string[];
|
|
work_contexts: string[];
|
|
};
|
|
type Member = {
|
|
user_id: number;
|
|
profile_id: number;
|
|
maintenance: boolean;
|
|
expires_at: string | null;
|
|
reason: string | null;
|
|
};
|
|
type Person = {
|
|
id: number;
|
|
name: string;
|
|
email: string;
|
|
department_id: number;
|
|
};
|
|
const base = '/administracao/parametrizacao';
|
|
function Choices({
|
|
profiles,
|
|
selected,
|
|
change,
|
|
}: {
|
|
profiles: Profile[];
|
|
selected: number[];
|
|
change: (ids: number[]) => void;
|
|
}) {
|
|
return (
|
|
<div className="flex flex-wrap gap-4">
|
|
{profiles.map((p) => (
|
|
<label className="flex items-center gap-2 text-sm" key={p.id}>
|
|
<input
|
|
type="checkbox"
|
|
checked={selected.includes(p.id)}
|
|
onChange={(e) =>
|
|
change(
|
|
e.target.checked
|
|
? [...selected, p.id]
|
|
: selected.filter((id) => id !== p.id),
|
|
)
|
|
}
|
|
/>
|
|
{p.name}
|
|
</label>
|
|
))}
|
|
</div>
|
|
);
|
|
}
|
|
function Assignment({
|
|
person,
|
|
profiles,
|
|
members,
|
|
version,
|
|
}: {
|
|
person: Person;
|
|
profiles: Profile[];
|
|
members: Member[];
|
|
version: number;
|
|
}) {
|
|
const assigned = members.filter((m) => m.user_id === person.id);
|
|
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();
|
|
form.transform((values) => ({
|
|
...values,
|
|
expires_at: values.expires_at
|
|
? new Date(values.expires_at).toISOString()
|
|
: null,
|
|
}));
|
|
form.post(base + '/assign', {
|
|
preserveState: true,
|
|
preserveScroll: true,
|
|
onSuccess: () => {
|
|
form.setData(initial);
|
|
form.clearErrors();
|
|
router.remember(initial, `${identity}:data`);
|
|
router.remember({}, `${identity}:errors`);
|
|
},
|
|
});
|
|
}}
|
|
>
|
|
<FormErrors errors={form.errors} />
|
|
<Choices
|
|
profiles={profiles}
|
|
selected={form.data.profile_ids}
|
|
change={(ids) => form.setData('profile_ids', ids)}
|
|
/>
|
|
<label className="flex items-center gap-2">
|
|
<input
|
|
type="checkbox"
|
|
checked={form.data.maintenance}
|
|
onChange={(e) =>
|
|
form.setData('maintenance', e.target.checked)
|
|
}
|
|
/>
|
|
Manutenção TEMPO — diagnóstico e consulta temporários
|
|
</label>
|
|
<label className="block space-y-1">
|
|
Expiração (obrigatória para manutenção)
|
|
<input
|
|
className={controlClass}
|
|
type="datetime-local"
|
|
required={form.data.maintenance}
|
|
value={form.data.expires_at}
|
|
onChange={(e) =>
|
|
form.setData('expires_at', e.target.value)
|
|
}
|
|
/>
|
|
</label>
|
|
{assigned.some((m) => m.expires_at) && (
|
|
<p className="text-sm">
|
|
Expiração anterior:{' '}
|
|
{assigned.find((m) => m.expires_at)?.expires_at}.
|
|
Indique a expiração para manter um acesso temporário.
|
|
</p>
|
|
)}
|
|
<label className="block space-y-1">
|
|
Fundamento da atribuição ou revogação
|
|
<textarea
|
|
required
|
|
minLength={10}
|
|
maxLength={4000}
|
|
className={controlClass}
|
|
value={form.data.reason}
|
|
onChange={(e) => form.setData('reason', e.target.value)}
|
|
/>
|
|
</label>
|
|
<p className="text-sm text-muted-foreground">
|
|
Sem perfis seleccionados, o acesso funcional será revogado
|
|
quando a parametrização estiver activa. Os dois
|
|
administradores permanentes devem ser mantidos.
|
|
</p>
|
|
<Button disabled={form.processing}>Guardar atribuição</Button>
|
|
</form>
|
|
</details>
|
|
);
|
|
}
|
|
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,
|
|
urgentReviewsReady = false,
|
|
requisitionCategoryOptions = {},
|
|
companyDetails,
|
|
companyDetailsReady,
|
|
ready,
|
|
geographyEnabled = false,
|
|
geography = null,
|
|
active,
|
|
version,
|
|
permissions,
|
|
workflowTasks = {},
|
|
activationPreview,
|
|
profiles,
|
|
memberships,
|
|
users,
|
|
departments,
|
|
costCenters,
|
|
notice,
|
|
companyRules,
|
|
comparisonPolicy,
|
|
urgentQuotationReady = false,
|
|
intelligencePolicy,
|
|
intelligenceReady = false,
|
|
aiPlan,
|
|
aiDomains = {},
|
|
aiDataScopes = {},
|
|
workContextConfiguration,
|
|
enabledWorkContexts = [],
|
|
identity,
|
|
}: {
|
|
identity: string;
|
|
approvalLevels?: RequisitionApprovalPlan | null;
|
|
approvalLevelsReady?: boolean;
|
|
expiryReady?: boolean;
|
|
urgentReviewsReady?: boolean;
|
|
requisitionCategoryOptions?: Record<string, string>;
|
|
companyDetails: CompanyDetails | null;
|
|
companyDetailsReady: boolean;
|
|
ready: boolean;
|
|
geographyEnabled?: boolean;
|
|
geography?: GeographyDescription;
|
|
comparisonPolicy: ComparisonPolicy;
|
|
urgentQuotationReady?: boolean;
|
|
intelligencePolicy?: IntelligencePolicy;
|
|
intelligenceReady?: boolean;
|
|
aiPlan?: AiPlan;
|
|
aiDomains?: Record<string, string>;
|
|
aiDataScopes?: Record<string, string>;
|
|
workContextConfiguration?: WorkContextState;
|
|
enabledWorkContexts?: string[];
|
|
active: boolean;
|
|
version: number;
|
|
permissions: { [key: string]: string };
|
|
workflowTasks?: Record<string, { key: string; label: string }[]>;
|
|
activationPreview?: ActivationPreview;
|
|
profiles: Profile[];
|
|
memberships: Member[];
|
|
users: Person[];
|
|
departments: { id: number; name: string }[];
|
|
costCenters: { id: number; code: string; name: string }[];
|
|
notice?: string;
|
|
companyRules: {
|
|
first_limit: string;
|
|
second_limit: string;
|
|
includes_tax: boolean;
|
|
provisional: boolean;
|
|
default_tax_rate: string;
|
|
};
|
|
}) {
|
|
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: '',
|
|
password: '',
|
|
password_confirmation: '',
|
|
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 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 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 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,
|
|
urgent_minimum_proposals:
|
|
comparisonPolicy.urgent_minimum_proposals?.toString() ?? '',
|
|
weights: { ...comparisonPolicy.weights },
|
|
reason: '',
|
|
};
|
|
const comparison = useForm(`${identity}:comparison`, initialComparison);
|
|
const comparisonDirty = hasPreparationChanges(initialComparison, {
|
|
...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" />
|
|
<div className="mx-auto max-w-6xl space-y-6 px-5 py-8 lg:px-8">
|
|
<PageTitle
|
|
eyebrow="Administração"
|
|
title="Parametrização da aplicação"
|
|
description="Defina os perfis da empresa, atribua responsabilidades e mantenha dois administradores permanentes."
|
|
/>
|
|
<nav
|
|
aria-label="Áreas da parametrização"
|
|
className="rounded-xl border bg-card p-4"
|
|
>
|
|
<p className="mb-3 font-semibold">Ir para uma área</p>
|
|
<ul className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
|
{[
|
|
['company-details', 'Dados da empresa'],
|
|
['approval-levels', 'Níveis de aprovação'],
|
|
...(geographyEnabled
|
|
? [
|
|
[
|
|
'company-geography',
|
|
'Localização administrativa',
|
|
],
|
|
]
|
|
: []),
|
|
...(ready
|
|
? [
|
|
[
|
|
'company-activation',
|
|
'Activação da configuração',
|
|
],
|
|
[
|
|
'company-comparison',
|
|
'Comparação de propostas',
|
|
],
|
|
['company-tax', 'IVA de novas linhas'],
|
|
[
|
|
'company-approval-rules',
|
|
'Regras e limites de aprovação',
|
|
],
|
|
[
|
|
'company-profiles',
|
|
'Perfis e permissões',
|
|
],
|
|
[
|
|
'company-users',
|
|
'Utilizadores e atribuições',
|
|
],
|
|
[
|
|
'company-cost-centres',
|
|
'Organização e centros de custo',
|
|
],
|
|
...(intelligencePolicy
|
|
? [
|
|
[
|
|
'company-intelligence',
|
|
'Inteligência operacional',
|
|
],
|
|
]
|
|
: []),
|
|
...(aiPlan
|
|
? [
|
|
[
|
|
'company-ai-plan',
|
|
'Plano de inteligência artificial',
|
|
],
|
|
]
|
|
: []),
|
|
...(workContextConfiguration
|
|
? [
|
|
[
|
|
'company-work-contexts',
|
|
'Opções contratadas',
|
|
],
|
|
]
|
|
: []),
|
|
[
|
|
'company-maintenance',
|
|
'Manutenção TEMPO',
|
|
],
|
|
]
|
|
: []),
|
|
].map(([id, label]) => (
|
|
<li key={id}>
|
|
<a
|
|
className="font-medium underline underline-offset-4"
|
|
href={`#${id}`}
|
|
>
|
|
{label}
|
|
</a>
|
|
</li>
|
|
))}
|
|
<li>
|
|
<Link
|
|
className="font-medium underline underline-offset-4"
|
|
href="/administracao/candidaturas/formularios"
|
|
>
|
|
Formulários de inscrições e candidaturas
|
|
</Link>
|
|
</li>
|
|
{expiryReady && (
|
|
<li>
|
|
<Link
|
|
className="font-medium underline underline-offset-4"
|
|
href="/administracao/prazos-aprovacao"
|
|
>
|
|
Prazos, escalamento e expiração
|
|
</Link>
|
|
</li>
|
|
)}
|
|
{urgentReviewsReady && (
|
|
<li>
|
|
<Link
|
|
className="font-medium underline underline-offset-4"
|
|
href="/administracao/revisao-urgencias"
|
|
>
|
|
Perfis de revisão posterior das urgências
|
|
</Link>
|
|
</li>
|
|
)}
|
|
</ul>
|
|
</nav>
|
|
{geographyEnabled && (
|
|
<div
|
|
id="company-geography"
|
|
tabIndex={-1}
|
|
className="min-w-0 scroll-mt-24 lg:scroll-mt-72"
|
|
>
|
|
<CompanyAdministrativeLocation geography={geography} />
|
|
<Link
|
|
className="mt-4 inline-block font-semibold underline"
|
|
href="/administracao/divisao-administrativa"
|
|
>
|
|
Consultar inconsistências da divisão administrativa
|
|
</Link>
|
|
</div>
|
|
)}
|
|
{notice && (
|
|
<p
|
|
role="status"
|
|
className="rounded border border-teal-300 p-3"
|
|
>
|
|
{notice}
|
|
</p>
|
|
)}
|
|
{activationPreview && (
|
|
<OrganizationActivationPreview
|
|
preview={activationPreview}
|
|
permissions={permissions}
|
|
tasks={workflowTasks}
|
|
/>
|
|
)}
|
|
<div
|
|
id="approval-levels"
|
|
tabIndex={-1}
|
|
className="min-w-0 scroll-mt-24 lg:scroll-mt-72"
|
|
>
|
|
<RequisitionApprovalSettings
|
|
plan={approvalLevels}
|
|
ready={approvalLevelsReady}
|
|
categoryOptions={requisitionCategoryOptions}
|
|
profiles={profiles}
|
|
costCenters={costCenters}
|
|
version={version}
|
|
/>
|
|
</div>
|
|
<div
|
|
id="company-details"
|
|
tabIndex={-1}
|
|
className="min-w-0 scroll-mt-24 lg:scroll-mt-72"
|
|
>
|
|
<CompanyDetailsSettings
|
|
details={companyDetails}
|
|
ready={companyDetailsReady && ready}
|
|
version={version}
|
|
/>
|
|
</div>
|
|
{!ready ? (
|
|
<Panel title="Instalação pendente">
|
|
<p>
|
|
A parametrização ainda não foi instalada neste
|
|
ambiente.
|
|
</p>
|
|
</Panel>
|
|
) : (
|
|
<>
|
|
<Panel
|
|
id="company-activation"
|
|
title={
|
|
active
|
|
? 'Parametrização activa'
|
|
: 'Preparar a configuração da empresa'
|
|
}
|
|
>
|
|
<p className="text-sm">
|
|
{active
|
|
? 'Os acessos são determinados pelos perfis e atribuições abaixo.'
|
|
: 'Crie os perfis e associe os utilizadores antes de activar. A activação substitui os perfis anteriores; utilizadores sem atribuições válidas deixam de ter acesso funcional.'}{' '}
|
|
Versão {version}.
|
|
</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: true,
|
|
preserveScroll: true,
|
|
onSuccess: clearActivate,
|
|
});
|
|
}}
|
|
>
|
|
<FormErrors errors={activate.errors} />
|
|
<label className="block">
|
|
Motivo da activação
|
|
<textarea
|
|
required
|
|
minLength={10}
|
|
className={controlClass}
|
|
value={activate.data.reason}
|
|
onChange={(e) =>
|
|
activate.setData(
|
|
'reason',
|
|
e.target.value,
|
|
)
|
|
}
|
|
/>
|
|
</label>
|
|
<label className="flex items-center gap-2">
|
|
<input
|
|
required
|
|
type="checkbox"
|
|
checked={activate.data.confirm}
|
|
onChange={(e) =>
|
|
activate.setData(
|
|
'confirm',
|
|
e.target.checked,
|
|
)
|
|
}
|
|
/>
|
|
Conferi os dois administradores e o
|
|
efeito das atribuições sobre todos os
|
|
utilizadores.
|
|
</label>
|
|
<Button
|
|
disabled={
|
|
activate.processing ||
|
|
!activate.data.confirm
|
|
}
|
|
>
|
|
Activar configuração da empresa
|
|
</Button>
|
|
</form>
|
|
)}
|
|
</Panel>
|
|
{intelligencePolicy && (
|
|
<div
|
|
id="company-intelligence"
|
|
tabIndex={-1}
|
|
className="min-w-0 scroll-mt-24 lg:scroll-mt-72"
|
|
>
|
|
<IntelligenceSettings
|
|
key={`intelligence-${version}`}
|
|
policy={intelligencePolicy}
|
|
version={version}
|
|
ready={intelligenceReady}
|
|
/>
|
|
</div>
|
|
)}
|
|
{aiPlan && (
|
|
<div
|
|
id="company-ai-plan"
|
|
tabIndex={-1}
|
|
className="min-w-0 scroll-mt-24 lg:scroll-mt-72"
|
|
>
|
|
<AiPlanSettings
|
|
key={`ai-plan-${version}`}
|
|
plan={aiPlan}
|
|
domains={aiDomains}
|
|
scopes={aiDataScopes}
|
|
version={version}
|
|
ready={intelligenceReady}
|
|
/>
|
|
</div>
|
|
)}
|
|
{workContextConfiguration && (
|
|
<div
|
|
id="company-work-contexts"
|
|
tabIndex={-1}
|
|
className="min-w-0 scroll-mt-24 lg:scroll-mt-72"
|
|
>
|
|
<WorkContextSettings
|
|
context={workContextConfiguration}
|
|
enabled={enabledWorkContexts}
|
|
version={version}
|
|
/>
|
|
</div>
|
|
)}
|
|
<Panel
|
|
id="company-comparison"
|
|
title="Regras de comparação de propostas"
|
|
>
|
|
<p className="mb-4 text-sm">
|
|
{comparisonPolicy.configured
|
|
? `Revisão ${comparisonPolicy.revision} da empresa.`
|
|
: 'Valores iniciais de compatibilidade.'}{' '}
|
|
A alteração aplica-se apenas a requisições
|
|
criadas depois de guardar. Rascunhos e processos
|
|
existentes conservam a regra anterior. Os
|
|
avaliadores devem continuar independentes e sem
|
|
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: true,
|
|
preserveScroll: true,
|
|
onSuccess: clearComparison,
|
|
});
|
|
}}
|
|
>
|
|
<FormErrors errors={comparison.errors} />
|
|
{urgentQuotationReady && (
|
|
<label className="block space-y-1">
|
|
Mínimo de propostas numa urgência com
|
|
stock mínimo documentado (opcional)
|
|
<input
|
|
className={controlClass}
|
|
type="number"
|
|
min="1"
|
|
max="100"
|
|
step="1"
|
|
value={
|
|
comparison.data
|
|
.urgent_minimum_proposals ??
|
|
''
|
|
}
|
|
onChange={(event) =>
|
|
comparison.setData(
|
|
'urgent_minimum_proposals',
|
|
event.target.value,
|
|
)
|
|
}
|
|
/>
|
|
<span className="text-sm text-muted-foreground">
|
|
Vazio conserva o mínimo normal. Só
|
|
novas requisições recebem esta
|
|
configuração; orçamento e aprovações
|
|
não são dispensados.
|
|
</span>
|
|
</label>
|
|
)}
|
|
<div className="grid gap-4 md:grid-cols-2">
|
|
<label className="block space-y-1">
|
|
Mínimo de fornecedores com proposta
|
|
elegível
|
|
<input
|
|
className={controlClass}
|
|
type="number"
|
|
min="1"
|
|
max="100"
|
|
step="1"
|
|
required
|
|
value={
|
|
comparison.data
|
|
.minimum_proposals
|
|
}
|
|
onChange={(e) =>
|
|
comparison.setData(
|
|
'minimum_proposals',
|
|
Number(e.target.value),
|
|
)
|
|
}
|
|
/>
|
|
</label>
|
|
<label className="block space-y-1">
|
|
Mínimo de avaliadores independentes por
|
|
proposta
|
|
<input
|
|
className={controlClass}
|
|
type="number"
|
|
min="1"
|
|
max="100"
|
|
step="1"
|
|
required
|
|
value={
|
|
comparison.data
|
|
.minimum_evaluators
|
|
}
|
|
onChange={(e) =>
|
|
comparison.setData(
|
|
'minimum_evaluators',
|
|
Number(e.target.value),
|
|
)
|
|
}
|
|
/>
|
|
</label>
|
|
</div>
|
|
<fieldset className="grid gap-4 md:grid-cols-3">
|
|
<legend className="mb-3 font-medium">
|
|
Ponderações — soma obrigatória de 100%
|
|
</legend>
|
|
{Object.entries(comparisonCriteria).map(
|
|
([key, label]) => (
|
|
<label
|
|
key={key}
|
|
className="block space-y-1"
|
|
>
|
|
{label} (%)
|
|
<input
|
|
className={controlClass}
|
|
type="number"
|
|
min="0"
|
|
max="100"
|
|
step="1"
|
|
required
|
|
value={
|
|
comparison.data.weights[
|
|
key as keyof typeof comparisonCriteria
|
|
]
|
|
}
|
|
onChange={(e) =>
|
|
comparison.setData(
|
|
'weights',
|
|
{
|
|
...comparison
|
|
.data
|
|
.weights,
|
|
[key]: Number(
|
|
e.target
|
|
.value,
|
|
),
|
|
},
|
|
)
|
|
}
|
|
/>
|
|
</label>
|
|
),
|
|
)}
|
|
</fieldset>
|
|
<p className="text-sm">
|
|
Soma actual:{' '}
|
|
{Object.values(
|
|
comparison.data.weights,
|
|
).reduce((sum, weight) => sum + weight, 0)}
|
|
%.
|
|
</p>
|
|
<label className="block space-y-1">
|
|
Fundamento e âmbito da alteração
|
|
<textarea
|
|
className={controlClass}
|
|
required
|
|
minLength={10}
|
|
maxLength={4000}
|
|
value={comparison.data.reason}
|
|
onChange={(e) =>
|
|
comparison.setData(
|
|
'reason',
|
|
e.target.value,
|
|
)
|
|
}
|
|
/>
|
|
</label>
|
|
<Button disabled={comparison.processing}>
|
|
Guardar para novos processos
|
|
</Button>
|
|
</form>
|
|
</Panel>
|
|
<Panel id="company-tax" title="IVA para novas linhas">
|
|
<p className="mb-4 text-sm">
|
|
Taxa inicial para novas linhas de requisição.
|
|
Pode ser ajustada em cada artigo conforme o
|
|
enquadramento fiscal. As linhas e propostas
|
|
anteriores conservam a taxa registada. Os
|
|
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: true,
|
|
preserveScroll: true,
|
|
onSuccess: clearTax,
|
|
});
|
|
}}
|
|
>
|
|
<FormErrors errors={tax.errors} />
|
|
<label className="block space-y-1">
|
|
Taxa de IVA inicial (%)
|
|
<input
|
|
className={controlClass}
|
|
type="number"
|
|
min="0"
|
|
max="100"
|
|
step="0.01"
|
|
required
|
|
value={tax.data.default_tax_rate}
|
|
onChange={(e) =>
|
|
tax.setData(
|
|
'default_tax_rate',
|
|
e.target.value,
|
|
)
|
|
}
|
|
/>
|
|
</label>
|
|
<label className="block space-y-1">
|
|
Fundamento e âmbito fiscal
|
|
<textarea
|
|
className={controlClass}
|
|
required
|
|
minLength={10}
|
|
maxLength={4000}
|
|
value={tax.data.reason}
|
|
onChange={(e) =>
|
|
tax.setData(
|
|
'reason',
|
|
e.target.value,
|
|
)
|
|
}
|
|
/>
|
|
</label>
|
|
<Button disabled={tax.processing}>
|
|
Guardar taxa inicial
|
|
</Button>
|
|
</form>
|
|
</Panel>
|
|
<Panel
|
|
id="company-approval-rules"
|
|
title="Regras de aprovação da empresa"
|
|
>
|
|
<p className="mb-4 text-sm">
|
|
{companyRules.provisional
|
|
? 'Os valores actuais são provisórios; confirme e guarde as regras da empresa.'
|
|
: 'Regras definidas pela empresa.'}{' '}
|
|
Alterações aplicam-se a novas submissões. Os
|
|
processos já submetidos conservam as regras
|
|
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: true,
|
|
preserveScroll: true,
|
|
onSuccess: clearRules,
|
|
});
|
|
}}
|
|
>
|
|
<div className="sm:col-span-2">
|
|
<FormErrors errors={rules.errors} />
|
|
</div>
|
|
<label className="space-y-1">
|
|
Primeiro limite (MZN)
|
|
<input
|
|
required
|
|
inputMode="decimal"
|
|
pattern="[0-9]+(\.[0-9]{1,2})?"
|
|
className={controlClass}
|
|
value={rules.data.first_limit}
|
|
onChange={(e) =>
|
|
rules.setData(
|
|
'first_limit',
|
|
e.target.value,
|
|
)
|
|
}
|
|
/>
|
|
</label>
|
|
<label className="space-y-1">
|
|
Segundo limite (MZN)
|
|
<input
|
|
required
|
|
inputMode="decimal"
|
|
pattern="[0-9]+(\.[0-9]{1,2})?"
|
|
className={controlClass}
|
|
value={rules.data.second_limit}
|
|
onChange={(e) =>
|
|
rules.setData(
|
|
'second_limit',
|
|
e.target.value,
|
|
)
|
|
}
|
|
/>
|
|
</label>
|
|
<label className="flex items-center gap-2 sm:col-span-2">
|
|
<input
|
|
type="checkbox"
|
|
checked={rules.data.includes_tax}
|
|
onChange={(e) =>
|
|
rules.setData(
|
|
'includes_tax',
|
|
e.target.checked,
|
|
)
|
|
}
|
|
/>
|
|
Aplicar os limites ao valor com imposto
|
|
</label>
|
|
<p className="text-sm sm:col-span-2">
|
|
Supervisão do departamento na primeira
|
|
etapa; acima do primeiro limite
|
|
acrescenta-se Compras; acima do segundo
|
|
acrescenta-se Finanças. Equipamentos mantêm
|
|
a conferência financeira e técnica. Atribua
|
|
estas funções às pessoas através dos perfis.
|
|
</p>
|
|
<label className="space-y-1 sm:col-span-2">
|
|
Fundamentação
|
|
<textarea
|
|
required
|
|
minLength={10}
|
|
className={controlClass}
|
|
value={rules.data.reason}
|
|
onChange={(e) =>
|
|
rules.setData(
|
|
'reason',
|
|
e.target.value,
|
|
)
|
|
}
|
|
/>
|
|
</label>
|
|
<Button disabled={rules.processing}>
|
|
Guardar regras da empresa
|
|
</Button>
|
|
</form>
|
|
</Panel>
|
|
<Panel
|
|
id="company-profiles"
|
|
title="Perfis e permissões da empresa"
|
|
>
|
|
<div className="mb-4 flex flex-wrap gap-3">
|
|
{profiles.map((p) => (
|
|
<Button
|
|
key={p.id}
|
|
variant="outline"
|
|
onClick={() =>
|
|
setSelectedProfileId(String(p.id))
|
|
}
|
|
>
|
|
{p.name}
|
|
</Button>
|
|
))}
|
|
</div>
|
|
{selectedProfileId && !selectedProfile ? (
|
|
<p>
|
|
Perfil seleccionado indisponível.{' '}
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
onClick={() => setSelectedProfileId('')}
|
|
>
|
|
Novo perfil
|
|
</Button>
|
|
</p>
|
|
) : (
|
|
<ProfileEditor
|
|
key={profileIdentity}
|
|
identity={profileIdentity}
|
|
source={selectedProfile}
|
|
version={version}
|
|
permissions={permissions}
|
|
workflowTasks={workflowTasks}
|
|
workContextConfiguration={
|
|
workContextConfiguration
|
|
}
|
|
onNew={() => setSelectedProfileId('')}
|
|
/>
|
|
)}
|
|
</Panel>
|
|
<Panel
|
|
id="company-users"
|
|
title="Utilizadores e atribuições"
|
|
>
|
|
<div className="space-y-3">
|
|
{users.map((person) => (
|
|
<Assignment
|
|
key={`${person.id}-${version}`}
|
|
person={person}
|
|
profiles={profiles}
|
|
members={memberships}
|
|
version={version}
|
|
/>
|
|
))}
|
|
</div>
|
|
<details className="mt-5 rounded border p-4">
|
|
<summary className="cursor-pointer font-medium">
|
|
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: true,
|
|
preserveScroll: true,
|
|
onSuccess: clearUser,
|
|
});
|
|
}}
|
|
>
|
|
<div className="sm:col-span-2">
|
|
<FormErrors errors={user.errors} />
|
|
</div>
|
|
{(
|
|
[
|
|
'name',
|
|
'email',
|
|
'password',
|
|
'password_confirmation',
|
|
] as const
|
|
).map((key) => (
|
|
<label className="space-y-1" key={key}>
|
|
{
|
|
{
|
|
name: 'Nome',
|
|
email: 'Email',
|
|
password:
|
|
'Palavra-passe inicial',
|
|
password_confirmation:
|
|
'Confirmar palavra-passe',
|
|
}[key]
|
|
}
|
|
<input
|
|
required
|
|
type={
|
|
key.includes('password')
|
|
? 'password'
|
|
: key === 'email'
|
|
? 'email'
|
|
: 'text'
|
|
}
|
|
minLength={
|
|
key.includes('password')
|
|
? 12
|
|
: undefined
|
|
}
|
|
autoComplete={
|
|
key.includes('password')
|
|
? 'new-password'
|
|
: undefined
|
|
}
|
|
className={controlClass}
|
|
value={user.data[key] ?? ''}
|
|
onChange={(e) =>
|
|
user.setData(
|
|
key,
|
|
e.target.value,
|
|
)
|
|
}
|
|
/>
|
|
</label>
|
|
))}
|
|
<label className="space-y-1">
|
|
Departamento
|
|
<select
|
|
required
|
|
className={controlClass}
|
|
value={user.data.department_id}
|
|
onChange={(e) =>
|
|
user.setData(
|
|
'department_id',
|
|
e.target.value,
|
|
)
|
|
}
|
|
>
|
|
<option value="">Escolher</option>
|
|
{departments.map((d) => (
|
|
<option key={d.id} value={d.id}>
|
|
{d.name}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
<div className="space-y-2 sm:col-span-2">
|
|
<p>Perfis atribuídos</p>
|
|
<Choices
|
|
profiles={profiles}
|
|
selected={user.data.profile_ids}
|
|
change={(ids) =>
|
|
user.setData('profile_ids', ids)
|
|
}
|
|
/>
|
|
</div>
|
|
<label className="space-y-1 sm:col-span-2">
|
|
Fundamento
|
|
<textarea
|
|
required
|
|
minLength={10}
|
|
className={controlClass}
|
|
value={user.data.reason}
|
|
onChange={(e) =>
|
|
user.setData(
|
|
'reason',
|
|
e.target.value,
|
|
)
|
|
}
|
|
/>
|
|
</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>
|
|
</form>
|
|
</details>
|
|
</Panel>
|
|
<Panel
|
|
id="company-cost-centres"
|
|
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,
|
|
onSuccess: clearDepartment,
|
|
},
|
|
);
|
|
}}
|
|
>
|
|
<FormErrors errors={department.errors} />
|
|
<label className="block">
|
|
Novo departamento
|
|
<input
|
|
required
|
|
className={controlClass}
|
|
value={department.data.name}
|
|
onChange={(e) =>
|
|
department.setData(
|
|
'name',
|
|
e.target.value,
|
|
)
|
|
}
|
|
/>
|
|
</label>
|
|
<Button disabled={department.processing}>
|
|
Adicionar departamento
|
|
</Button>
|
|
<p className="text-sm">
|
|
{departments
|
|
.map((d) => d.name)
|
|
.join(' · ')}
|
|
</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,
|
|
onSuccess: clearCenter,
|
|
},
|
|
);
|
|
}}
|
|
>
|
|
<FormErrors errors={center.errors} />
|
|
<label className="block">
|
|
Departamento
|
|
<select
|
|
required
|
|
className={controlClass}
|
|
value={center.data.department_id}
|
|
onChange={(e) =>
|
|
center.setData(
|
|
'department_id',
|
|
e.target.value,
|
|
)
|
|
}
|
|
>
|
|
<option value="">Escolher</option>
|
|
{departments.map((d) => (
|
|
<option key={d.id} value={d.id}>
|
|
{d.name}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
<label className="block">
|
|
Código
|
|
<input
|
|
required
|
|
className={controlClass}
|
|
value={center.data.code}
|
|
onChange={(e) =>
|
|
center.setData(
|
|
'code',
|
|
e.target.value,
|
|
)
|
|
}
|
|
/>
|
|
</label>
|
|
<label className="block">
|
|
Centro de custo
|
|
<input
|
|
required
|
|
className={controlClass}
|
|
value={center.data.name}
|
|
onChange={(e) =>
|
|
center.setData(
|
|
'name',
|
|
e.target.value,
|
|
)
|
|
}
|
|
/>
|
|
</label>
|
|
<Button disabled={center.processing}>
|
|
Adicionar centro
|
|
</Button>
|
|
<p className="text-sm">
|
|
{costCenters
|
|
.map((c) => c.code + ' · ' + c.name)
|
|
.join(' / ')}
|
|
</p>
|
|
</form>
|
|
</div>
|
|
</Panel>
|
|
<Panel
|
|
id="company-maintenance"
|
|
title="Manutenção TEMPO"
|
|
>
|
|
<p className="text-sm">
|
|
Atribua a uma conta nominativa um perfil sem
|
|
administração, assinale manutenção e defina a
|
|
expiração. O acesso fica limitado a diagnóstico
|
|
e consulta, é revogado removendo as atribuições
|
|
e termina automaticamente na data indicada. As
|
|
atribuições, alterações e operações mantêm
|
|
autoria e auditoria; não existe palavra-passe
|
|
universal.
|
|
</p>
|
|
</Panel>
|
|
</>
|
|
)}
|
|
</div>
|
|
</>
|
|
);
|
|
}
|
|
|
|
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>
|
|
);
|
|
}
|