Merge branch 'main' of https://git.tempo.co.mz/nala/Investidor-V2 into front
This commit is contained in:
@@ -236,6 +236,7 @@
|
||||
}
|
||||
@media (min-width: 1280px) {
|
||||
.tempo-header-inner {
|
||||
grid-template-rows: minmax(71px, auto);
|
||||
grid-template-columns: auto minmax(0, 1fr) auto auto auto;
|
||||
column-gap: 0.25rem;
|
||||
padding-inline: 1.25rem;
|
||||
@@ -256,6 +257,7 @@
|
||||
}
|
||||
.tempo-primary-navigation > ul {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import { profileLinks } from '@/components/profile-navigation';
|
||||
import {PortalSidebarNavigation} from '@/components/portal-sidebar-navigation';
|
||||
import type { ProfileAccess } from '@/types/profile-access';
|
||||
import { Link, usePage } from '@inertiajs/react';
|
||||
import { LayoutGrid } from 'lucide-react';
|
||||
import { portalNavigation } from '@/lib/portal-navigation';
|
||||
import { portalNavigation,canShowLegacyManagement } from '@/lib/portal-navigation';
|
||||
import AppLogo from '@/components/app-logo';
|
||||
import { NavMain } from '@/components/nav-main';
|
||||
import { NavUser } from '@/components/nav-user';
|
||||
import {
|
||||
Sidebar,
|
||||
@@ -20,6 +18,7 @@ import type { Auth } from '@/types';
|
||||
import type { OpportunityManagementAccess } from '@/types/opportunity-management';
|
||||
|
||||
export function AppSidebar() {
|
||||
const currentPage=usePage();
|
||||
const {
|
||||
auth,
|
||||
existingBusinessEnabled,
|
||||
@@ -27,7 +26,9 @@ export function AppSidebar() {
|
||||
aiEnabled,
|
||||
opportunityManagement,
|
||||
contentManagementHref,
|
||||
contentManagementAccess,
|
||||
profileAccess,
|
||||
scopedAdministration,
|
||||
} = usePage<{
|
||||
auth: Auth;
|
||||
existingBusinessEnabled?: boolean;
|
||||
@@ -36,45 +37,26 @@ export function AppSidebar() {
|
||||
profileAccess?: ProfileAccess | null;
|
||||
opportunityManagement?: OpportunityManagementAccess | null;
|
||||
contentManagementHref?: string | null;
|
||||
scopedAdministration?: {label:string;href:string}[];
|
||||
contentManagementAccess?: {opportunities?:{index:string;create?:string|null}};
|
||||
}>().props;
|
||||
const groups = portalNavigation({
|
||||
authenticated: !!auth.user,
|
||||
manager: auth.canManagePortal,
|
||||
manager: canShowLegacyManagement(auth),
|
||||
businesses: existingBusinessEnabled,
|
||||
education: educationEnabled,
|
||||
ai: aiEnabled,
|
||||
opportunityManagement,
|
||||
profileAccess,
|
||||
contentManagementHref,
|
||||
contentManagementAccess,
|
||||
scopedAdministration,
|
||||
legacyContent: currentPage.props.legacyContentEnabled as boolean|undefined,
|
||||
procurement: currentPage.props.procurementEnabled as boolean|undefined,
|
||||
businessReviewUrl: currentPage.props.businessReviewUrl as string|null|undefined,
|
||||
});
|
||||
const items = groups.map((group) => ({
|
||||
title: group.label,
|
||||
href: group.children?.find((item) => item.href)?.href ?? '/',
|
||||
icon: LayoutGrid,
|
||||
}));
|
||||
if (contentManagementHref) {
|
||||
items.unshift({ title: 'Gestão de conteúdos e oportunidades', href: contentManagementHref, icon: LayoutGrid });
|
||||
}
|
||||
if (auth.canManagePortal && opportunityManagement) {
|
||||
items.push({
|
||||
title: opportunityManagement.manage.label,
|
||||
href: opportunityManagement.manage.href,
|
||||
icon: LayoutGrid,
|
||||
});
|
||||
if (opportunityManagement.installed) {
|
||||
items.push({
|
||||
title: opportunityManagement.create.label,
|
||||
href: opportunityManagement.create.href,
|
||||
icon: LayoutGrid,
|
||||
});
|
||||
}
|
||||
}
|
||||
items.push(
|
||||
...profileLinks(profileAccess).map((link) => ({
|
||||
...link,
|
||||
icon: LayoutGrid,
|
||||
})),
|
||||
);
|
||||
return (
|
||||
<Sidebar collapsible="icon" variant="inset">
|
||||
<Sidebar collapsible="offcanvas" variant="inset">
|
||||
<SidebarHeader>
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
@@ -88,7 +70,7 @@ export function AppSidebar() {
|
||||
</SidebarHeader>
|
||||
|
||||
<SidebarContent>
|
||||
<NavMain items={items} />
|
||||
<PortalSidebarNavigation groups={groups} url={currentPage.url}/>
|
||||
</SidebarContent>
|
||||
|
||||
<SidebarFooter>
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import type { EducationalArticle } from './educational-article-card';
|
||||
|
||||
/** Guides remain available on request; they are not matching investment results. */
|
||||
export default function CatalogueGuideLinks({ articles }: { articles: EducationalArticle[] }) {
|
||||
if (!articles.length) return null;
|
||||
return <details className="rounded border p-3">
|
||||
<summary className="cursor-pointer font-medium">Guias do sector — apoio opcional</summary>
|
||||
<ul className="mt-3 space-y-2">
|
||||
{articles.map((article) => <li key={article.href}>
|
||||
<Link className="underline" href={article.href}>Ler guia: {article.title}</Link>
|
||||
</li>)}
|
||||
</ul>
|
||||
</details>;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { forceLabels, forces } from '@/lib/cluster-competitiveness';
|
||||
import type { CompetitivenessDraft } from '@/lib/cluster-competitiveness';
|
||||
|
||||
export type ApprovedCompetitiveness = {
|
||||
draft: CompetitivenessDraft;
|
||||
version: number;
|
||||
at: string;
|
||||
};
|
||||
const pressures = {
|
||||
low: 'Baixa',
|
||||
medium: 'Média',
|
||||
high: 'Alta',
|
||||
'': 'Indeterminada',
|
||||
};
|
||||
|
||||
export default function ClusterCompetitivenessPublic({
|
||||
analysis,
|
||||
}: {
|
||||
analysis: ApprovedCompetitiveness;
|
||||
}) {
|
||||
return (
|
||||
<section
|
||||
className="space-y-3 rounded border p-4"
|
||||
aria-label="Competitividade aprovada"
|
||||
>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Competitividade — cinco forças de Porter
|
||||
</h2>
|
||||
<p>
|
||||
{analysis.draft.sector} · {analysis.draft.region} · Versão
|
||||
aprovada {analysis.version} · {analysis.at}
|
||||
</p>
|
||||
<p>
|
||||
Apreciação qualitativa fundamentada nas fontes e períodos
|
||||
indicados. Não representa garantia de procura ou viabilidade.
|
||||
</p>
|
||||
{forces.map((force) => {
|
||||
const row = analysis.draft.forces[force];
|
||||
return (
|
||||
<details key={force} className="rounded border p-3">
|
||||
<summary>
|
||||
{forceLabels[force]} · Pressão{' '}
|
||||
{pressures[row.pressure]}
|
||||
</summary>
|
||||
<dl className="space-y-2">
|
||||
{(
|
||||
[
|
||||
['evidence', 'Evidências'],
|
||||
['source', 'Fonte e referência'],
|
||||
['period', 'Período'],
|
||||
['rationale', 'Justificação'],
|
||||
['limitations', 'Limitações'],
|
||||
[
|
||||
'opportunity',
|
||||
'Oportunidade e fundamento',
|
||||
],
|
||||
] as const
|
||||
).map(([field, label]) => (
|
||||
<div key={field}>
|
||||
<dt className="font-semibold">{label}</dt>
|
||||
<dd className="whitespace-pre-wrap">
|
||||
{row[field]}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</details>
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -2,5 +2,5 @@ import { Link, usePage } from '@inertiajs/react';
|
||||
|
||||
export default function ContentManagementEntry() {
|
||||
const { contentManagementHref } = usePage<{ contentManagementHref?: string | null }>().props;
|
||||
return contentManagementHref ? <Link className="inline-block rounded-lg border px-4 py-3 font-semibold underline" href={contentManagementHref}>Gestão de conteúdos e oportunidades</Link> : null;
|
||||
return contentManagementHref ? <Link className="inline-block rounded-lg border px-4 py-3 font-semibold underline" href={contentManagementHref}>Área de trabalho</Link> : null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import type {FiscalProofParcel} from '@/lib/fiscal-proof-parcel';
|
||||
|
||||
export function FiscalProofParcelFields({value, change, label}: {value: FiscalProofParcel; change: (value: FiscalProofParcel) => void; label: string}) {
|
||||
return <details className="rounded border p-2" open={!!value.parcel || !!value.parcelReference}>
|
||||
<summary>Identificar parcela quando o documento suporta várias parcelas — {label}</summary>
|
||||
<p>Sem identificação específica, o comprovativo existente abrange o documento inteiro. Para distinguir impostos ou parcelas, indique a linha/identificador exacto e o suporte dessa separação. Os montantes comprovado e seleccionado devem corresponder à parcela identificada. A mudança do identificador não comprova uma parcela diferente.</p>
|
||||
<label className="block">Identificador da parcela<input aria-label={label + ' — Parcela documental'} value={value.parcel ?? ''} onChange={e => change({parcel: e.target.value})}/></label>
|
||||
<label className="block">Suporte da separação das parcelas<input aria-label={label + ' — Suporte da parcela'} value={value.parcelReference ?? ''} onChange={e => change({parcelReference: e.target.value})}/></label>
|
||||
</details>;
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { useEffect, useId, useState } from 'react';
|
||||
import { api } from '@/pages/investment/shared';
|
||||
import { replaceTerritoryPath } from '@/lib/territory-path.js';
|
||||
import TerritoryGeometryPreview from './territory-geometry-preview';
|
||||
import TerritorySearchSelect from './territory-search-select';
|
||||
|
||||
export type TerritoryOption = {
|
||||
id: string;
|
||||
@@ -135,37 +136,11 @@ export function ProvinceSelect({
|
||||
total={options.length}
|
||||
retry={() => setRetry((value) => value + 1)}
|
||||
/>
|
||||
<input
|
||||
className={className}
|
||||
aria-label={`Pesquisar ${label}`}
|
||||
maxLength={100}
|
||||
placeholder="Pesquisar nome ou código"
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
/>
|
||||
<select
|
||||
id={id}
|
||||
aria-label={label}
|
||||
className={className}
|
||||
required={required}
|
||||
value={value}
|
||||
disabled={loading || Boolean(error)}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
>
|
||||
<option value="">
|
||||
{loading ? 'A carregar províncias…' : placeholder}
|
||||
</option>
|
||||
{value && !options.some((option) => option.name === value) && (
|
||||
<option value={value}>
|
||||
{value} (seleção guardada; conferir cadastro)
|
||||
</option>
|
||||
)}
|
||||
{options.map((option) => (
|
||||
<option key={option.id} value={option.name}>
|
||||
{option.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<TerritorySearchSelect id={id} label={label} className={className} required={required}
|
||||
placeholder={placeholder === 'Seleccione uma província' ? 'Pesquisar província' : placeholder}
|
||||
search={search} onSearch={setSearch} options={options} loading={loading} error={error}
|
||||
selected={value ? options.find((option) => option.name === value) ?? { id: value, name: value } : undefined}
|
||||
onChange={(option) => onChange(option?.name ?? '')} />
|
||||
{geometryFeedback && <p role="status">{geometryFeedback}</p>}
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={
|
||||
@@ -334,65 +309,15 @@ export function TerritoryLevel({
|
||||
<label htmlFor={id} className="font-medium">
|
||||
{labels[index]}
|
||||
</label>
|
||||
<input
|
||||
className={control}
|
||||
aria-label={`Pesquisar ${labels[index]}`}
|
||||
disabled={!enabled}
|
||||
maxLength={100}
|
||||
value={search}
|
||||
onChange={(event) => {
|
||||
setSearch(event.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder={`Pesquisar ${labels[index].toLowerCase()}`}
|
||||
/>
|
||||
<select
|
||||
id={id}
|
||||
aria-invalid={Boolean(fieldError)}
|
||||
aria-describedby={fieldError ? `${id}-error` : undefined}
|
||||
className={control}
|
||||
disabled={!enabled || loading || !!error}
|
||||
value={selected?.id ?? ''}
|
||||
onChange={(e) =>
|
||||
onChange(options.find((o) => o.id === e.target.value))
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
{enabled ? 'Seleccione' : 'Seleccione o nível anterior'}
|
||||
</option>
|
||||
{selected && !options.some((o) => o.id === selected.id) && (
|
||||
<option value={selected.id}>
|
||||
{selected.name}
|
||||
{selected.deleted_at
|
||||
? ' (arquivada)'
|
||||
: ' (selecção actual)'}
|
||||
</option>
|
||||
)}
|
||||
{options.map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.name}
|
||||
{o.source_code ? ` (${o.source_code})` : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<TerritorySearchSelect id={id} label={labels[index]} className={control}
|
||||
disabled={!enabled} search={search} onSearch={(query) => { setSearch(query); setPage(1); }}
|
||||
options={options} selected={selected} onChange={onChange} loading={loading} error={fieldError || error}>
|
||||
<div className="flex gap-3 p-2 text-sm">
|
||||
{page > 1 && <button type="button" onClick={() => setPage(page - 1)}>Anterior</button>}
|
||||
{more && <button type="button" onClick={() => setPage(page + 1)}>Mais opções</button>}
|
||||
</div>
|
||||
</TerritorySearchSelect>
|
||||
{loading && <p role="status">A carregar…</p>}
|
||||
{fieldError && (
|
||||
<p id={`${id}-error`} role="alert">
|
||||
{fieldError}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex gap-3 text-sm">
|
||||
{page > 1 && (
|
||||
<button type="button" onClick={() => setPage(page - 1)}>
|
||||
Anterior
|
||||
</button>
|
||||
)}
|
||||
{more && (
|
||||
<button type="button" onClick={() => setPage(page + 1)}>
|
||||
Mais opções
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { Link, usePage } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { fiscalPreparationGuide } from '@/lib/fiscal-preparation-guide';
|
||||
|
||||
@@ -8,6 +8,8 @@ export function JourneyDocumentResources({
|
||||
stages?: string[];
|
||||
}) {
|
||||
const [stage, setStage] = useState('');
|
||||
const context=new URL(usePage().url,'https://portal.invalid').searchParams.get('context');
|
||||
const preparationHref=context&&/^[a-f0-9-]{36}$/i.test(context)?`/investimentos/${context}/contexto/editar#preparation-questions`:'/investimentos';
|
||||
function destination(path: string, type?: string) {
|
||||
const query = new URLSearchParams();
|
||||
if (stage) query.set('stage[0]', stage);
|
||||
@@ -20,8 +22,24 @@ export function JourneyDocumentResources({
|
||||
className="space-y-3 rounded-xl border border-emerald-200 bg-emerald-50 p-4"
|
||||
>
|
||||
<h2 className="font-semibold text-emerald-950">
|
||||
Fontes e guias para a jornada
|
||||
Preencher formulários e preparar documentos
|
||||
</h2>
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
<div className="rounded border bg-white p-3"><h3 className="font-semibold">Pedido de investimento</h3>
|
||||
<p>Preencha a preparação digital no dossier existente, reutilizando os dados já guardados.</p>
|
||||
<Link className="underline" href={preparationHref}>Abrir o formulário no meu dossier</Link>
|
||||
</div>
|
||||
<div className="rounded border bg-white p-3"><h3 className="font-semibold">Terra e DUAT</h3>
|
||||
<p>Prepare os dados do pedido com os campos do formulário existente.</p>
|
||||
<Link className="underline" href="/terra-duat">Preencher ou continuar pedido de terra</Link>
|
||||
</div>
|
||||
<div className="rounded border bg-white p-3"><h3 className="font-semibold">Pedido de apoio do investidor</h3>
|
||||
<p>Identifique-se e preencha o pedido de apoio. Este formulário não é um pedido de autorização de investimento.</p>
|
||||
<Link className="underline" href="/formularios/investidor">Preencher pedido de apoio</Link>
|
||||
</div>
|
||||
</div>
|
||||
<p>Preparação digital e exemplar oficial são apresentados separadamente. Um guia ou diploma não é um formulário preenchível.</p>
|
||||
<details><summary className="cursor-pointer font-medium">Consultar exemplares, fontes e guias</summary>
|
||||
<p>
|
||||
Prepare as etapas em paralelo. A disponibilidade para consulta,
|
||||
a situação jurídica e a utilização numa regra ou cálculo são
|
||||
@@ -143,6 +161,7 @@ export function JourneyDocumentResources({
|
||||
<Link className="underline" href="/documentos">
|
||||
Explorar todo o acervo autorizado
|
||||
</Link>
|
||||
</details>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,9 @@ import { valueText } from '@/lib/value-text';
|
||||
import OpportunityParcelGeometry from './opportunity-parcel-geometry';
|
||||
import TerritoryGeometryPreview from './territory-geometry-preview';
|
||||
import { control } from '@/pages/management/shared';
|
||||
import OpportunityFillFlow from './opportunity-fill-flow';
|
||||
import { opportunityFillGroups } from '@/lib/opportunity-fill-flow';
|
||||
import { modalityLabels } from './opportunity-search-filters';
|
||||
|
||||
type Data = Record<string, unknown>;
|
||||
type Schema = {
|
||||
@@ -241,6 +244,11 @@ const labels: Record<string, string> = {
|
||||
assessment_status: 'Estado da avaliação',
|
||||
environmental_category: 'Categoria ambiental',
|
||||
direct_jobs: 'Empregos diretos',
|
||||
indirect_jobs: 'Empregos indirectos',
|
||||
female_percentage: 'Participação de mulheres (%)',
|
||||
youth_percentage: 'Participação de jovens (%)',
|
||||
social_risks: 'Riscos sociais',
|
||||
mitigation_plan: 'Plano de mitigação',
|
||||
employment_type: 'Tipo de emprego',
|
||||
geometry: 'Geometria da parcela',
|
||||
start_date: 'Data de início',
|
||||
@@ -621,6 +629,8 @@ export default function OpportunityCanonicalFields({
|
||||
sectors,
|
||||
disabled = false,
|
||||
errors = {},
|
||||
onOpenResources,
|
||||
missingPaths,
|
||||
}: {
|
||||
value: Data;
|
||||
onChange: (v: Data) => void;
|
||||
@@ -631,6 +641,8 @@ export default function OpportunityCanonicalFields({
|
||||
sectors: { id: number; name: string }[];
|
||||
disabled?: boolean;
|
||||
errors?: Record<string, string>;
|
||||
onOpenResources?: (group: string) => void;
|
||||
missingPaths?: string[];
|
||||
}) {
|
||||
const initiative = (value.initiative ?? {}) as Data;
|
||||
const isInitiative = category === 'investment_project' && ['program', 'portfolio'].includes(valueText(initiative.kind ?? ''));
|
||||
@@ -815,7 +827,7 @@ export default function OpportunityCanonicalFields({
|
||||
: ['classified_other'];
|
||||
return (
|
||||
<fieldset disabled={disabled} className="space-y-4 rounded border p-4">
|
||||
<legend>Contrato da oportunidade — {category}</legend>
|
||||
<legend>Preparar oportunidade — {modalityLabels[category] ?? 'Modalidade por escolher'}</legend>
|
||||
<p>
|
||||
O rascunho pode ficar incompleto. A submissão verifica os campos
|
||||
aplicáveis e os recursos guardados. Validação interna não
|
||||
@@ -870,7 +882,7 @@ export default function OpportunityCanonicalFields({
|
||||
</>}
|
||||
</section>
|
||||
)}
|
||||
{[...new Set([...common, ...specialized])].map((key) => {
|
||||
<OpportunityFillFlow groups={opportunityFillGroups([...new Set([...common, ...specialized])].filter((key) => !ignoredFields.includes(key)))} errors={errors} missingPaths={missingPaths} onOpenResources={onOpenResources} renderField={(key) => {
|
||||
if (ignoredFields.includes(key)) return null;
|
||||
|
||||
if (key === 'relations' && options.classification) {
|
||||
@@ -1167,7 +1179,7 @@ export default function OpportunityCanonicalFields({
|
||||
onChange={(v) => set(key, v)}
|
||||
/>
|
||||
) : null;
|
||||
})}
|
||||
}} />
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Link } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { button, card, input } from '@/pages/investment/shared';
|
||||
|
||||
type Item = {id:number;title:string;slug:string;summary:string|null;province:string|null;district:string|null;chains:string[];stages:string[];maturity_label:string|null};
|
||||
type Item = {id:number;title:string;slug:string;summary:string|null;province:string|null;district:string|null;provinces?:string[];territorial_summary?:string;chains:string[];stages:string[];maturity_label:string|null};
|
||||
export type CorridorGroup = {id:string;name:string;count:number;locations:string[];opportunities:Item[]};
|
||||
type Props = {groups:CorridorGroup[];selected:number[];onSelect:(id:number,checked:boolean)=>void;onCompare:(ids:number[])=>void;onClear:()=>void};
|
||||
|
||||
@@ -10,10 +10,11 @@ function Group({group,selected,onSelect}: {group:CorridorGroup} & Pick<Props,'se
|
||||
const [province,setProvince]=useState('');
|
||||
const [district,setDistrict]=useState('');
|
||||
const [chain,setChain]=useState('');
|
||||
const provinces=[...new Set(group.opportunities.map(r=>r.province).filter((s):s is string=>!!s))].sort();
|
||||
const districts=[...new Set(group.opportunities.filter(r=>!province||r.province===province).map(r=>r.district).filter((s):s is string=>!!s))].sort();
|
||||
const provinceNames=(r:Item)=>r.provinces??(r.province?[r.province]:[]);
|
||||
const provinces=[...new Set(group.opportunities.flatMap(provinceNames))].sort();
|
||||
const districts=[...new Set(group.opportunities.filter(r=>!province||provinceNames(r).includes(province)).map(r=>r.district).filter((s):s is string=>!!s))].sort();
|
||||
const chains=[...new Set(group.opportunities.flatMap(r=>r.chains))].sort();
|
||||
const rows=group.opportunities.filter(r=>(!province||r.province===province)&&(!district||r.district===district)&&(!chain||r.chains.includes(chain)));
|
||||
const rows=group.opportunities.filter(r=>(!province||provinceNames(r).includes(province))&&(!district||r.district===district)&&(!chain||r.chains.includes(chain)));
|
||||
return <section className={card+' space-y-4'} aria-label={group.name}>
|
||||
<header><h2 className="text-2xl font-bold">{group.name}</h2><p>{group.count} oportunidades publicadas</p>
|
||||
<p>{group.locations.length ? 'Localizações identificadas: '+group.locations.join(' · ') : 'Abrangência territorial por indicar.'}</p></header>
|
||||
@@ -25,7 +26,7 @@ function Group({group,selected,onSelect}: {group:CorridorGroup} & Pick<Props,'se
|
||||
<p role="status">{rows.length} oportunidades com estes filtros</p>
|
||||
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">{rows.map(r=><article key={r.id} className="space-y-3 rounded-lg border p-4">
|
||||
<h3 className="text-lg font-semibold"><Link href={'/oportunidades/'+r.slug}>{r.title}</Link></h3>
|
||||
<p>{[r.province,r.district].filter(Boolean).join(' / ')||'Localização por escolher'}</p>
|
||||
<p>{r.territorial_summary||[r.province,r.district].filter(Boolean).join(' / ')||'Localização por escolher'}</p>
|
||||
<p>Cadeia de valor: {r.chains.join(' · ')||'Por indicar'}</p>
|
||||
{r.summary && !r.stages.includes(r.summary) && <p>{r.summary}</p>}
|
||||
<p>Etapas e actividades: {r.stages.join(' · ')||'Por indicar'}</p><p>{r.maturity_label}</p>
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { opportunityErrorGroup, opportunityMissingGroups, type FillGroup } from '@/lib/opportunity-fill-flow';
|
||||
|
||||
export default function OpportunityFillFlow({groups,errors,renderField,onOpenResources,missingPaths=[]}:{
|
||||
groups:FillGroup[];errors:Record<string,string>;renderField:(field:string)=>ReactNode;onOpenResources?:(group:string)=>void;
|
||||
missingPaths?:string[];
|
||||
}) {
|
||||
const [active,setActive]=useState(groups[0]?.id??'');
|
||||
const groupIds=groups.map(group=>group.id).join(',');
|
||||
useEffect(()=>{
|
||||
const saved=window.location.hash.replace('#fill-','');
|
||||
if(groupIds.split(',').includes(saved))setActive(saved);
|
||||
},[groupIds]);
|
||||
const heading=useRef<HTMLHeadingElement|null>(null);
|
||||
const errorGroup=opportunityErrorGroup(groups,errors);
|
||||
const missing=opportunityMissingGroups(groups,missingPaths);
|
||||
const errorKey=JSON.stringify(errors);
|
||||
useEffect(()=>{if(errorGroup)setActive(errorGroup);},[errorGroup,errorKey]);
|
||||
const index=Math.max(0,groups.findIndex(group=>group.id===active));
|
||||
const current=groups[index];
|
||||
if(!current)return null;
|
||||
const go=(id:string)=>{
|
||||
setActive(id);
|
||||
window.history.replaceState(window.history.state,'',`#fill-${id}`);
|
||||
requestAnimationFrame(()=>heading.current?.focus());
|
||||
};
|
||||
return <div className="space-y-4">
|
||||
<p>Pode escolher qualquer grupo, guardar incompleto e retomar. As informações já preenchidas mantêm-se ao avançar e regressar.</p>
|
||||
<nav aria-label="Preencher a oportunidade" className="flex flex-wrap gap-2">
|
||||
{groups.map(group=><a key={group.id} href={`#fill-${group.id}`} aria-current={current.id===group.id?'step':undefined}
|
||||
className={`rounded border px-3 py-2 text-left ${current.id===group.id?'bg-primary text-primary-foreground':'bg-background'}`}
|
||||
onClick={event=>{event.preventDefault();go(group.id);}}>{group.title}{opportunityErrorGroup([group],errors)?' — verificar':missing.some(item=>item.id===group.id)?' — dados em falta':''}</a>)}
|
||||
</nav>
|
||||
{missing.length>0&&<p>Pendências da última gravação: {missing.map(group=>group.title).join(' · ')}. Guarde para actualizar esta indicação.</p>}
|
||||
<h2 ref={heading} tabIndex={-1} className="text-xl font-semibold">{current.title}</h2>
|
||||
<p>{current.hint}</p>
|
||||
{groups.map(group=><section key={group.id} id={`fill-${group.id}`} hidden={current.id!==group.id}
|
||||
aria-label={group.title} className="space-y-4">
|
||||
{group.fields.map(field=><div key={field}>{renderField(field)}</div>)}
|
||||
{onOpenResources&&group.fields.some(field=>['locations','documents','images'].includes(field))&&
|
||||
<button type="button" className="rounded border px-4 py-2 font-medium" onClick={()=>onOpenResources(group.id)}>Guardar e abrir documentos, imagens e localizações</button>}
|
||||
</section>)}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 border-t pt-3">
|
||||
<span className="text-sm">Grupo {index+1} de {groups.length} · navegação livre</span>
|
||||
<div className="flex gap-3">
|
||||
{index>0&&<a href={`#fill-${groups[index-1].id}`} className="rounded border px-4 py-2" onClick={event=>{event.preventDefault();go(groups[index-1].id);}}>Anterior</a>}
|
||||
{index<groups.length-1&&<a href={`#fill-${groups[index+1].id}`} className="rounded border px-4 py-2" onClick={event=>{event.preventDefault();go(groups[index+1].id);}}>Continuar: {groups[index+1].title}</a>}
|
||||
</div>
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
@@ -283,6 +283,11 @@ export default function OpportunitySearchFilters({
|
||||
escolher todos os níveis. O contexto provincial de um
|
||||
corredor é identificado nos resultados; não confirma uma
|
||||
implantação distrital.
|
||||
{path.length > 1 && (
|
||||
<button type="button" className="ml-2 underline" onClick={() => territory(path.slice(0, 1))}>
|
||||
Ver toda a província de {path[0].name}
|
||||
</button>
|
||||
)}
|
||||
</p>
|
||||
<fieldset className="grid gap-3 sm:grid-cols-2 lg:grid-cols-1">
|
||||
<legend className="sr-only">Localização</legend>
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
portalNavigation,
|
||||
canShowLegacyManagement,
|
||||
currentNavigationGroup,
|
||||
currentNavigationItem,
|
||||
} from '@/lib/portal-navigation';
|
||||
@@ -44,6 +45,7 @@ export function PortalGroupedMenu() {
|
||||
auth: {
|
||||
user: { name?: string; email?: string } | null;
|
||||
canManagePortal: boolean;
|
||||
legacyManagementAccess?:boolean;
|
||||
};
|
||||
existingBusinessEnabled?: boolean;
|
||||
businessReviewUrl?: string | null;
|
||||
@@ -54,6 +56,8 @@ export function PortalGroupedMenu() {
|
||||
profileAccess?: ProfileAccess | null;
|
||||
opportunityManagement?: OpportunityManagementAccess | null;
|
||||
scopedAdministration?: { label: string; href: string }[];
|
||||
contentManagementHref?: string | null;
|
||||
contentManagementAccess?: {opportunities?:{index:string;create?:string|null}};
|
||||
}>();
|
||||
const { t, language, requestCount } = useTempoUi();
|
||||
const mobile = useIsMobile();
|
||||
@@ -63,7 +67,7 @@ export function PortalGroupedMenu() {
|
||||
? { id: navigation.active, ...navigation.view.tools }
|
||||
: undefined,
|
||||
authenticated: !!props.auth?.user,
|
||||
manager: !!props.auth?.canManagePortal,
|
||||
manager: canShowLegacyManagement(props.auth),
|
||||
businesses: props.existingBusinessEnabled,
|
||||
businessReviewUrl: props.businessReviewUrl,
|
||||
education: props.educationEnabled,
|
||||
@@ -72,17 +76,10 @@ export function PortalGroupedMenu() {
|
||||
legacyContent: props.legacyContentEnabled,
|
||||
opportunityManagement: props.opportunityManagement,
|
||||
profileAccess: props.profileAccess,
|
||||
contentManagementHref: props.contentManagementHref,
|
||||
contentManagementAccess: props.contentManagementAccess,
|
||||
scopedAdministration: props.scopedAdministration,
|
||||
});
|
||||
if (props.scopedAdministration?.length)
|
||||
groups.push({
|
||||
id: 'scoped-administration',
|
||||
label: 'Administração',
|
||||
children: props.scopedAdministration.map((item, index) => ({
|
||||
id: `scoped-${index}`,
|
||||
label: item.label,
|
||||
href: item.href,
|
||||
})),
|
||||
});
|
||||
const current = currentNavigationGroup(groups, url);
|
||||
const currentItem = currentNavigationItem(groups, url);
|
||||
const [loggingOut, setLoggingOut] = useState(false);
|
||||
@@ -134,7 +131,7 @@ export function PortalGroupedMenu() {
|
||||
);
|
||||
const accountGroups = groups.filter(
|
||||
(group) =>
|
||||
!['home', 'discovery', 'realization', 'support'].includes(group.id),
|
||||
!['home', 'discovery', 'realization', 'support','work'].includes(group.id),
|
||||
);
|
||||
const panelLabel = `${t('O meu painel')} — ${requestCount} ${t(requestCount === 1 ? 'pedido recebido' : 'pedidos recebidos')}`;
|
||||
const institutionalCurrent = url.split('?')[0] === '/contacto';
|
||||
@@ -200,6 +197,7 @@ export function PortalGroupedMenu() {
|
||||
'discovery',
|
||||
'realization',
|
||||
'support',
|
||||
'work',
|
||||
].includes(group.id),
|
||||
)
|
||||
.map((group) => (
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import {Link} from '@inertiajs/react';
|
||||
import {LayoutGrid} from 'lucide-react';
|
||||
import type {ReactNode} from 'react';
|
||||
import type {PortalNavItem} from '@/lib/portal-navigation';
|
||||
import {currentNavigationItem} from '@/lib/portal-navigation';
|
||||
import {searchTerritoryHref} from '@/lib/search-territory';
|
||||
import {SidebarGroup,SidebarGroupLabel,SidebarMenu,SidebarMenuButton,SidebarMenuItem} from '@/components/ui/sidebar';
|
||||
|
||||
/** Render every authorised destination; a group is never reduced to its first link. */
|
||||
export function PortalSidebarNavigation({groups,url}:{groups:PortalNavItem[];url:string}){
|
||||
const active=currentNavigationItem(groups,url);
|
||||
const ordered=[...groups.filter(group=>group.id==='work'),...groups.filter(group=>group.id!=='work')];
|
||||
const links=(items:PortalNavItem[],depth=0):ReactNode=>items.map(item=>item.children?
|
||||
<li key={item.id} className="list-none"><p className="px-2 pt-3 pb-1 text-xs font-medium text-muted-foreground">{item.label}</p><ul className="ml-2 border-l pl-2">{links(item.children,depth+1)}</ul></li>:
|
||||
item.href?<SidebarMenuItem key={item.id}><SidebarMenuButton asChild isActive={item.id===active} className="h-auto min-h-8 whitespace-normal py-2"><Link href={searchTerritoryHref(item.href,url)} aria-current={item.id===active?'page':undefined}>{depth===0&&<LayoutGrid aria-hidden="true"/>}<span className="min-w-0 flex-1" style={{whiteSpace:'normal',overflow:'visible',textOverflow:'clip',overflowWrap:'anywhere'}}>{item.label}</span></Link></SidebarMenuButton></SidebarMenuItem>:null);
|
||||
return <nav aria-label="Navegação completa do portal">{ordered.map(group=><SidebarGroup key={group.id}><SidebarGroupLabel>{group.label}</SidebarGroupLabel><SidebarMenu>{links(group.children??[])}</SidebarMenu></SidebarGroup>)}</nav>;
|
||||
}
|
||||
@@ -73,6 +73,8 @@ export function PreparationSummary({
|
||||
<h2 className="text-xl font-bold">
|
||||
Preparar o pedido de investimento privado
|
||||
</h2>
|
||||
{caseId&&<p><Link className="inline-block rounded border px-4 py-2 font-semibold" href={`/investimentos/${caseId}/contexto/editar#preparation-questions`}>Preencher ou continuar o formulário</Link></p>}
|
||||
<details><summary className="cursor-pointer font-medium">Consultar situação, documentos e fundamentos</summary>
|
||||
{!data.enabled ? (
|
||||
<p>
|
||||
Use os dados deste dossier para identificar o pedido e os
|
||||
@@ -219,10 +221,11 @@ export function PreparationSummary({
|
||||
className="underline"
|
||||
href={`/investimentos/${caseId}/contexto/editar#preparation-questions`}
|
||||
>
|
||||
Completar apenas os dados em falta ou editar declarações
|
||||
Editar os dados do formulário
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
</details>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,30 +1,34 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { Field, control, button } from '@/pages/management/shared';
|
||||
import {ProactiveSupplyBrowser} from './proactive-supply';
|
||||
|
||||
export type ProactiveEvidence = {id:string;category:string;purpose:'local'|'methodology';statement:string;interpretation:string;source:string;locator:string;period:string;scope:string;coverage:string;verified_on:string;access:'internal'|'public';document_id:string};
|
||||
export type ProactiveEvidence = {id:string;observation_id?:string;category:string;purpose:'local'|'methodology';statement:string;interpretation:string;source:string;locator:string;period:string;scope:string;coverage:string;verified_on:string;access:'internal'|'public';document_id:string};
|
||||
export type ProactiveAnalysis = {
|
||||
version:1;kind:'exists'|'needs'|'ideas';evidence:ProactiveEvidence[];
|
||||
need:{state:'hypothesis'|'confirmed';problem:string;observed_supply:string;observed_demand:string;type:string;clients:string;evidence_ids:string[];limitations:string;missing:string;confirmation:string};
|
||||
idea:{solution:string;activity:string;chain_id:string;stage:string;coverage:string;mode:string;resources:string;assumptions:string;conditions:string;pending:string;next_action:string};
|
||||
relations:{id:string;kind:string;target_id:string;relation:string;reference:string;evidence_ids:string[]}[];
|
||||
supply_comparisons?:{observation_id:string;relationship:'competition'|'complementarity'|'partner'|'uncertain';rationale:string;limitations:string}[];
|
||||
};
|
||||
export type ProactiveOptions = {documents?:{id:string;title:string}[];groups:Record<string,string>;references:Record<string,{id:string;name:string}[]>};
|
||||
export type ProactivePublic = {version?:number;group:string;state:string;need:string;proposal:string;basis:string;limitations:string;next_action:string;evidence_ids:string[];chain_id?:string|null;stage?:string|null;notice?:string;resources?:string;assumptions?:string;conditions?:string;relation_ids?:string[];relations?:{kind:string;target_id:string;label:string;relationship:string;basis:string}[];evidence?:Partial<ProactiveEvidence>[]};
|
||||
export type ProactivePublic = {version?:number;group:string;state:string;need:string;proposal:string;basis:string;limitations:string;next_action:string;evidence_ids:string[];chain_id?:string|null;stage?:string|null;notice?:string;resources?:string;assumptions?:string;conditions?:string;relation_ids?:string[];relations?:{kind:string;target_id:string;label:string;relationship:string;basis:string}[];evidence?:Partial<ProactiveEvidence>[];internal_comparisons?:{relationship:string;rationale:string;limitations:string;statement?:string;source?:string;locator?:string;period?:string}[]};
|
||||
export const proactiveNotice = 'Ausência de registo não comprova ausência de oferta. Proximidade não comprova contrato, participação, energia acessível, terra disponível ou benefício fiscal. Necessidade confirmada não comprova viabilidade comercial; hipótese de fornecimento não é encomenda.';
|
||||
export const newProactive = ():ProactiveAnalysis => ({version:1,kind:'ideas',evidence:[],need:{state:'hypothesis',problem:'',observed_supply:'',observed_demand:'',type:'',clients:'',evidence_ids:[],limitations:'',missing:'',confirmation:''},idea:{solution:'',activity:'',chain_id:'',stage:'',coverage:'',mode:'',resources:'',assumptions:'',conditions:'',pending:'',next_action:''},relations:[]});
|
||||
export const newPublicProactive = ():ProactivePublic => ({group:'ideas',state:'hypothesis',need:'',proposal:'',basis:'',limitations:'',next_action:'',evidence_ids:[],chain_id:'',stage:'',resources:'',assumptions:'',conditions:'',relation_ids:[]});
|
||||
|
||||
export function ProactiveInvestmentEditor({value,onChange,options,history=[]}:{value?:ProactiveAnalysis;onChange:(value:ProactiveAnalysis)=>void;options?:ProactiveOptions;history?:{version:number;at:string;state:string;problem:string;confirmation:string}[]}){
|
||||
export function ProactiveInvestmentEditor({value,onChange,options,history=[],territoryId,recordId}:{value?:ProactiveAnalysis;onChange:(value:ProactiveAnalysis)=>void;options?:ProactiveOptions;history?:{version:number;at:string;state:string;problem:string;confirmation:string}[];territoryId?:string;recordId?:number}){
|
||||
if(!value)return <section className="rounded border p-4"><h2 className="font-semibold">Análise territorial e preparação de ideias</h2><p>Comece pelo território e sector existentes, mesmo sem oportunidade publicada, promotor, montante ou coordenadas. O rascunho e a publicação são independentes.</p><button type="button" className={button} onClick={()=>onChange(newProactive())}>Preparar análise e ideia</button></section>;
|
||||
const patch=(p:Partial<ProactiveAnalysis>)=>onChange({...value,...p});
|
||||
const removeEvidence=(id:string)=>{const proof=value.evidence.find(e=>e.id===id);patch({evidence:value.evidence.filter(e=>e.id!==id),need:{...value.need,evidence_ids:value.need.evidence_ids.filter(x=>x!==id)},relations:value.relations.map(r=>({...r,evidence_ids:r.evidence_ids.filter(x=>x!==id)})),...(proof?.observation_id?{supply_comparisons:(value.supply_comparisons??[]).filter(c=>c.observation_id!==proof.observation_id)}:{})});};
|
||||
const text=(label:string,v:string,change:(v:string)=>void)=><Field label={label}><textarea className={control} aria-label={label} value={v??''} onChange={e=>change(e.target.value)}/></Field>;
|
||||
const select=(label:string,v:string,choices:Record<string,string>,change:(v:string)=>void)=><Field label={label}><select className={control} aria-label={label} value={v??''} onChange={e=>change(e.target.value)}><option value="">Por determinar</option>{Object.entries(choices).map(([key,label])=><option key={key} value={key}>{label}</option>)}</select></Field>;
|
||||
const evidenceChoice=(selected:string[],change:(v:string[])=>void)=><fieldset><legend>Evidências que fundamentam esta entrada</legend>{value.evidence.map((e,i)=><label key={e.id} className="block"><input type="checkbox" checked={selected.includes(e.id)} onChange={event=>change(event.target.checked?[...selected,e.id]:selected.filter(id=>id!==e.id))}/> Evidência {i+1}: {e.statement||'Por descrever'} ({e.access==='public'?'Pública autorizada':'Interna'})</label>)}</fieldset>;
|
||||
return <section className="space-y-4 rounded border p-4" aria-label="Análise territorial e ideia">
|
||||
<h2 className="text-xl font-semibold">Território e sector → evidências → necessidade → ideia</h2><details><summary>Como fundamentar esta análise</summary><p>Inventarie actividades, recursos, infra-estruturas e serviços de apoio. Confronte oferta observada com procura documentada e identifique os clientes ou beneficiários. Registe o período, cobertura e limitações de cada observação. Use referências internacionais para orientar as perguntas; a confirmação do caso depende de evidência local.</p></details><p>Reutiliza o sector e a localização principal escolhidos nesta ficha. Guarde pelo botão de rascunho existente. Nenhum montante, promotor ou ponto exacto é exigido.</p><p>{proactiveNotice}</p>
|
||||
{select('Tipo de conteúdo em preparação',value.kind,{exists:'O que existe',needs:'Necessidade identificada',ideas:'Ideia de investimento'},v=>patch({kind:v as ProactiveAnalysis['kind']}))}
|
||||
<ProactiveSupplyBrowser value={value} onChange={onChange} territoryId={territoryId} recordId={recordId}/>
|
||||
<fieldset className="space-y-3 rounded border p-3"><legend>Evidências e proveniência</legend><p>Registe factos e interpretações em campos separados. Listas de empresas, hotéis, restaurantes, contactos e documentos internos permanecem internos; não são copiados para a divulgação.</p>
|
||||
{value.evidence.map((e,i)=>{const change=(p:Partial<ProactiveEvidence>)=>patch({evidence:value.evidence.map(x=>x.id===e.id?{...x,...p}:x)});return <fieldset key={e.id} className="space-y-2 rounded border p-3"><legend>Evidência {i+1}</legend>
|
||||
{value.evidence.map((e,i)=>{const change=(p:Partial<ProactiveEvidence>)=>patch({evidence:value.evidence.map(x=>x.id===e.id?{...x,...p}:x)});if(e.observation_id)return <fieldset key={e.id} className="space-y-2 rounded border p-3"><legend>Evidência interna da oferta {i+1}</legend><p>{e.statement}</p><p>Fonte: {e.source} · {e.locator}</p><p>Período: {e.period} · Abrangência: {e.scope}</p><p>{e.coverage}</p><p>A proveniência é recuperada do original. A data indica consulta documental, sem confirmação de actividade actual.</p>{text(`Interpretação ou hipótese ${i+1}`,e.interpretation,v=>change({interpretation:v}))}<button type="button" onClick={()=>removeEvidence(e.id)}>Retirar evidência {i+1} e a sua comparação deste rascunho</button></fieldset>;return <fieldset key={e.id} className="space-y-2 rounded border p-3"><legend>Evidência {i+1}</legend>
|
||||
{select(`Finalidade da evidência ${i+1}`,e.purpose??'',{local:'Evidência local do caso',methodology:'Referência metodológica — não prova procura local'},v=>change({purpose:v as 'local'|'methodology'}))}
|
||||
{select(`Categoria da evidência ${i+1}`,e.category,{activity:'Actividade',resource:'Recurso',infrastructure:'Infra-estrutura',supply:'Oferta',demand:'Procura'},v=>change({category:v}))}
|
||||
{([['statement','Facto documentado'],['interpretation','Interpretação ou hipótese'],['source','Fonte e exemplar'],['locator','Localizador ou trecho'],['period','Período da evidência'],['scope','Abrangência'],['coverage','Cobertura e limitações']]as const).map(([key,label])=><div key={key}>{text(`${label} ${i+1}`,e[key],v=>change({[key]:v}))}</div>)}
|
||||
@@ -64,7 +68,7 @@ export function ProactiveInvestmentEditor({value,onChange,options,history=[]}:{v
|
||||
|
||||
export function ProactiveSummary({value}:{value?:ProactivePublic|null}){
|
||||
if(!value)return null;
|
||||
return <section className="space-y-2 rounded border p-4" aria-label="Origem proactiva do investimento"><h2 className="text-xl font-semibold">{value.group==='ideas'?'Ideia em preparação':value.group==='needs'?'Necessidade identificada':'O que existe'}</h2><p>{value.group==='exists'?'Registo documental; consultar abrangência, cobertura e limitações das fontes.':value.state==='confirmed'?'Necessidade confirmada no âmbito documentado':'Hipótese analítica; conclusão económica por confirmar'}</p>{([['need','Necessidade'],['proposal','Proposta'],['basis','Fundamento'],['limitations','Limitações'],['next_action','Próximo passo'],['stage','Etapa da cadeia'],['resources','Recursos'],['assumptions','Pressupostos'],['conditions','Condições']]as const).map(([key,label])=>value[key]?<p key={key}><strong>{label}:</strong> {value[key]}</p>:null)}{value.relations?.map(r=><p key={r.kind+r.target_id}>Relação seleccionada: {r.label} · {r.relationship==='documented'?'Documentada':r.relationship==='proximity'?'Proximidade, sem pertença':'Hipótese de relação'}. Fundamento: {r.basis}. Não confirma contrato, acesso ou participação.</p>)}{value.evidence?.map((e,i)=><p key={e.id??i}>Evidência pública: {e.statement}; fonte: {e.source}; localizador: {e.locator}; período: {e.period}; abrangência: {e.scope}; cobertura: {e.coverage}; verificação: {e.verified_on}.</p>)}<p>{value.notice??proactiveNotice}</p><p>Sem disponibilidade de participação, viabilidade comercial ou benefício fiscal presumidos.</p></section>;
|
||||
return <section className="space-y-2 rounded border p-4" aria-label="Origem proactiva do investimento"><h2 className="text-xl font-semibold">{value.group==='ideas'?'Ideia em preparação':value.group==='needs'?'Necessidade identificada':'O que existe'}</h2><p>{value.group==='exists'?'Registo documental; consultar abrangência, cobertura e limitações das fontes.':value.state==='confirmed'?'Necessidade confirmada no âmbito documentado':'Hipótese analítica; conclusão económica por confirmar'}</p>{([['need','Necessidade'],['proposal','Proposta'],['basis','Fundamento'],['limitations','Limitações'],['next_action','Próximo passo'],['stage','Etapa da cadeia'],['resources','Recursos'],['assumptions','Pressupostos'],['conditions','Condições']]as const).map(([key,label])=>value[key]?<p key={key}><strong>{label}:</strong> {value[key]}</p>:null)}{value.internal_comparisons?.map((c,i)=><div key={i} className="rounded border p-3"><strong>Comparação interna da oferta {i+1} · {({competition:'Possível concorrência',complementarity:'Possível complementaridade',partner:'Possível parceiro, sem compromisso',uncertain:'Relação por determinar'} as Record<string,string>)[c.relationship]}</strong><p>{c.statement}</p><p>Fonte: {c.source} · {c.locator} · {c.period}</p><p>{c.rationale}</p><p>Incertezas: {c.limitations}</p></div>)}{value.relations?.map(r=><p key={r.kind+r.target_id}>Relação seleccionada: {r.label} · {r.relationship==='documented'?'Documentada':r.relationship==='proximity'?'Proximidade, sem pertença':'Hipótese de relação'}. Fundamento: {r.basis}. Não confirma contrato, acesso ou participação.</p>)}{value.evidence?.map((e,i)=><p key={e.id??i}>Evidência pública: {e.statement}; fonte: {e.source}; localizador: {e.locator}; período: {e.period}; abrangência: {e.scope}; cobertura: {e.coverage}; verificação: {e.verified_on}.</p>)}<p>{value.notice??proactiveNotice}</p><p>Sem disponibilidade de participação, viabilidade comercial ou benefício fiscal presumidos.</p></section>;
|
||||
}
|
||||
|
||||
export function ProactivePublicationFields({value,onChange,evidence,relations=[],options,reviewed,onReview}:{value:ProactivePublic;onChange:(v:ProactivePublic)=>void;evidence:ProactiveEvidence[];relations?:{id:string;label:string;relationship:string}[];options?:ProactiveOptions;reviewed:boolean;onReview:(v:boolean)=>void}){
|
||||
@@ -86,5 +90,5 @@ export function proactiveView(raw:unknown):ProactivePublic|null{
|
||||
if(typeof p.group==='string'&&typeof p.need==='string')return p as ProactivePublic;
|
||||
const a=raw as ProactiveAnalysis;
|
||||
if(!a.need||typeof a.need.problem!=='string'||!a.idea)return null;
|
||||
return {version:1,group:a.kind,state:a.need.state,need:a.kind==='exists'?'':a.need.problem,proposal:a.kind==='ideas'?a.idea.solution:'',basis:a.need.confirmation||'Fundamento por completar',limitations:[a.need.limitations,a.need.missing,a.idea.assumptions,a.idea.conditions,a.idea.pending].filter(Boolean).join('; '),next_action:a.idea.next_action,evidence_ids:a.need.evidence_ids,chain_id:a.idea.chain_id,stage:a.kind==='ideas'?a.idea.stage:'',notice:'Origem privada autorizada deste dossier. '+proactiveNotice};
|
||||
return {version:1,group:a.kind,state:a.need.state,need:a.kind==='exists'?'':a.need.problem,proposal:a.kind==='ideas'?a.idea.solution:'',basis:a.need.confirmation||'Fundamento por completar',limitations:[a.need.limitations,a.need.missing,a.idea.assumptions,a.idea.conditions,a.idea.pending].filter(Boolean).join('; '),next_action:a.idea.next_action,evidence_ids:a.need.evidence_ids,chain_id:a.idea.chain_id,stage:a.kind==='ideas'?a.idea.stage:'',notice:'Origem privada autorizada deste dossier. '+proactiveNotice,internal_comparisons:(a.supply_comparisons??[]).map(c=>{const e=a.evidence.find(e=>e.observation_id===c.observation_id);return {...c,statement:e?.statement,source:e?.source,locator:e?.locator,period:e?.period};})};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import {button,control,Field} from '@/pages/management/shared';
|
||||
import {createOperationKey} from '@/lib/operation-key';
|
||||
import type {ProactiveAnalysis} from './proactive-investment';
|
||||
|
||||
type Observation={id:string;name:string;province:string;district:string;territory_id:string;cae:string;activity:string;sector:string;source_date:string;sheet:string;row_number:number;source_hash:string;source_name:string;source_period:string;identity_conflict:boolean};
|
||||
type Result={installed:boolean;rows:Observation[];total:number|null;duplicate_sightings?:number;page?:number;per_page?:number;sectors?:string[];territory_coverage?:{unmapped:number;province_only:number};limitations:string;status:string};
|
||||
export function ProactiveSupplyBrowser({value,onChange,territoryId,recordId}:{value:ProactiveAnalysis;onChange:(v:ProactiveAnalysis)=>void;territoryId?:string;recordId?:number}){
|
||||
const [activity,setActivity]=useState('');const [sector,setSector]=useState('');
|
||||
const [result,setResult]=useState<Result|null>(null);const [busy,setBusy]=useState(false);const [error,setError]=useState('');
|
||||
const [query,setQuery]=useState<{territory:string;activity:string;sector:string;page:number}|null>(null);
|
||||
useEffect(()=>{setResult(null);setQuery(null);setSector('');setError('');setBusy(false);},[territoryId]);
|
||||
useEffect(()=>{
|
||||
if(!query)return;const controller=new AbortController();setBusy(true);setError('');
|
||||
const p=new URLSearchParams({territory_id:query.territory,activity:query.activity,sector:query.sector,page:String(query.page)});if(recordId)p.set('record_id',String(recordId));
|
||||
fetch('/minhas-oportunidades/oferta-interna?'+p,{headers:{Accept:'application/json'},credentials:'same-origin',signal:controller.signal})
|
||||
.then(async r=>{if(!r.ok)throw new Error(r.status===403?'Consulta interna fora do âmbito de acesso desta sessão.':'Não foi possível consultar a base interna. A oferta permanece por determinar.');return r.json() as Promise<Result>;})
|
||||
.then(setResult).catch(e=>{if(e.name!=='AbortError'){setResult(null);setError(e.message);}}).finally(()=>{if(!controller.signal.aborted)setBusy(false);});
|
||||
return ()=>controller.abort();
|
||||
},[query,recordId]);
|
||||
const selected=value.supply_comparisons??[];
|
||||
const compare=(row:Observation)=>{
|
||||
if(selected.some(c=>c.observation_id===row.id))return;
|
||||
const proof=value.evidence.find(e=>e.observation_id===row.id);
|
||||
onChange({...value,supply_comparisons:[...selected,{observation_id:row.id,relationship:'uncertain',rationale:'',limitations:'Actividade actual, capacidade, procura e disponibilidade para parceria por confirmar.'}],evidence:proof?value.evidence:[...value.evidence,{
|
||||
id:createOperationKey(),observation_id:row.id,category:'supply',purpose:'local',access:'internal',document_id:'',
|
||||
statement:`Registo administrativo: ${row.name}; CAE ${row.cae}; ${row.activity||'actividade por classificar'}; ${row.district}, ${row.province}. Não confirma actividade actual.`,
|
||||
interpretation:'',source:`${row.source_name}; SHA256 ${row.source_hash}`,locator:`${row.sheet}!linha ${row.row_number}`,
|
||||
period:`${row.source_date}; ${row.source_period}`,scope:`${row.district}, ${row.province}`,
|
||||
coverage:result?.limitations??'Cobertura incompleta; situação actual por confirmar.',verified_on:new Date().toISOString().slice(0,10),
|
||||
}]});
|
||||
};
|
||||
return <fieldset className="space-y-3 rounded border p-3"><legend>Consultar oferta existente — base interna</legend>
|
||||
<p>Consulta a localização escolhida nesta ficha e os seus territórios subordinados. Os filtros por sector e actividade CAE não limitam a análise ao sector da ideia: podem existir concorrentes, complementos e parceiros noutros sectores. Nenhuma empresa é publicada.</p>
|
||||
<Field label="Sector da oferta (classificação CAE)"><select className={control} aria-label="Sector da oferta (classificação CAE)" value={sector} onChange={e=>setSector(e.target.value)}><option value="">Todos os sectores registados</option>{result?.sectors?.map(s=><option key={s}>{s}</option>)}</select></Field>
|
||||
<Field label="Actividade ou código CAE da oferta"><input className={control} aria-label="Actividade ou código CAE da oferta" value={activity} onChange={e=>setActivity(e.target.value)}/></Field>
|
||||
<button type="button" className={button} disabled={!territoryId||busy} onClick={()=>setQuery({territory:territoryId!,activity,sector,page:1})}>{busy?'A consultar…':'Consultar oferta da localização'}</button>
|
||||
{!territoryId&&<p>Escolha a localização para consultar. Sem localização, a oferta permanece por determinar.</p>}
|
||||
{error&&<p role="alert">{error}</p>}
|
||||
{result&&<><p role="status">{result.status}</p><p>{result.limitations}</p>{result.territory_coverage&&<p>Cobertura territorial da base nacional: {result.territory_coverage.unmapped} observações sem correspondência territorial única; {result.territory_coverage.province_only} apenas com província. Estas últimas não comprovam oferta num distrito específico.</p>}{result.total!==null&&<p>{result.total} observações distintas; {result.duplicate_sightings??0} repetições dos mesmos campos administrativos conservadas na origem. Não é uma contagem de empresas únicas.</p>}
|
||||
{result.rows.map(row=><article key={row.id} className="rounded border p-3"><h3 className="font-semibold">{row.name}</h3><p>{row.district}, {row.province} · {row.sector||'Sector por classificar'} · CAE {row.cae||'não indicado'} · {row.activity||'Actividade por classificar'}</p><p>Fonte: {row.source_name} · {row.sheet}, linha {row.row_number} · {row.source_date} · {row.source_period}</p><details><summary>Rastreabilidade do exemplar</summary><p>SHA256: {row.source_hash}</p><p>Observação: {row.id}</p></details>{row.identity_conflict&&<p>Identificador partilhado por denominações divergentes; identidade por conferir. Os registos não foram fundidos.</p>}<button type="button" className={button} disabled={busy||selected.some(c=>c.observation_id===row.id)||selected.length>=40||value.evidence.length>=60} onClick={()=>compare(row)}>Comparar com a ideia</button></article>)}
|
||||
{query&&<div className="flex gap-3"><button type="button" disabled={busy||query.page<=1} onClick={()=>setQuery({...query,page:query.page-1})}>Página anterior</button><span>Página {result.page??1}</span><button type="button" disabled={busy||query.page*25>=(result.total??0)} onClick={()=>setQuery({...query,page:query.page+1})}>Página seguinte</button></div>}
|
||||
</>}
|
||||
{selected.map((c,i)=>{const proof=value.evidence.find(e=>e.observation_id===c.observation_id);const patch=(p:Partial<typeof c>)=>onChange({...value,supply_comparisons:selected.map(x=>x.observation_id===c.observation_id?{...x,...p}:x)});return <fieldset className="space-y-2 rounded border p-3" key={c.observation_id}><legend>Comparação {i+1}</legend><p>{proof?.statement??'Evidência retirada: volte a associar a observação antes de guardar.'}</p><p>{proof?.source} · {proof?.locator}</p><p>Ideia em preparação: {value.idea.solution||'Descreva a ideia no campo existente abaixo.'}</p><Field label={`Relação com a ideia ${i+1}`}><select className={control} value={c.relationship} onChange={e=>patch({relationship:e.target.value as typeof c.relationship})}><option value="uncertain">Relação por determinar</option><option value="competition">Possível concorrência</option><option value="complementarity">Possível complementaridade</option><option value="partner">Possível parceiro — sem compromisso</option></select></Field><Field label={`Fundamento da comparação ${i+1}`}><textarea className={control} value={c.rationale} onChange={e=>patch({rationale:e.target.value})}/></Field><Field label={`Incertezas da comparação ${i+1}`}><textarea className={control} value={c.limitations} onChange={e=>patch({limitations:e.target.value})}/></Field><button type="button" onClick={()=>onChange({...value,supply_comparisons:selected.filter(x=>x.observation_id!==c.observation_id)})}>Retirar comparação {i+1}</button></fieldset>;})}
|
||||
{!!selected.length&&<p>Use estas comparações para fundamentar a necessidade abaixo e seleccione as evidências correspondentes. A fonte administrativa não confirma procura nem insuficiência de oferta. Guarde no rascunho existente; a continuidade para o dossier conserva o percurso já entregue.</p>}
|
||||
</fieldset>;
|
||||
}
|
||||
@@ -28,7 +28,7 @@ export function profileLinks(access: ProfileAccess | null | undefined) {
|
||||
...(access.administration
|
||||
? [
|
||||
{
|
||||
title: 'Instalação dos perfis 040000',
|
||||
title: 'Configuração dos perfis',
|
||||
href: '/management/profile-install',
|
||||
},
|
||||
]
|
||||
@@ -41,16 +41,26 @@ export default function ProfileNavigation() {
|
||||
profileAccess?: ProfileAccess | null;
|
||||
}>().props;
|
||||
if (!profileAccess) return null;
|
||||
const links = profileLinks(profileAccess);
|
||||
const workHrefs = [profileAccess.mine, profileAccess.create, profileAccess.review].filter(Boolean);
|
||||
const work = links.filter((link) => workHrefs.includes(link.href));
|
||||
const access = links.filter((link) => !workHrefs.includes(link.href));
|
||||
return (
|
||||
<nav
|
||||
aria-label="Perfil e oportunidades"
|
||||
className="flex flex-wrap gap-4 rounded border p-4"
|
||||
>
|
||||
{profileLinks(profileAccess).map((link) => (
|
||||
{work.map((link) => (
|
||||
<Link key={link.href} href={link.href} className="underline">
|
||||
{link.title}
|
||||
</Link>
|
||||
))}
|
||||
{access.length > 0 && <details className="basis-full">
|
||||
<summary className="cursor-pointer font-medium">O meu acesso e administração</summary>
|
||||
<div className="mt-3 flex flex-wrap gap-4">{access.map((link) =>
|
||||
<Link key={link.href} href={link.href} className="underline">{link.title}</Link>
|
||||
)}</div>
|
||||
</details>}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
export default function ProfileProofPicker({documents,value,onChange,disabled=false}:{
|
||||
documents:{id:string;file_name:string}[];value:string[];onChange:(ids:string[])=>void;disabled?:boolean;
|
||||
}) {
|
||||
const [query,setQuery]=useState('');
|
||||
const [showAll,setShowAll]=useState(false);
|
||||
const [limit,setLimit]=useState(10);
|
||||
const normalize=(text:string)=>text.normalize('NFD').replace(/\p{Diacritic}/gu,'').toLocaleLowerCase();
|
||||
const matches=documents.filter(document=>normalize(document.file_name).includes(normalize(query)));
|
||||
const toggle=(id:string)=>onChange(value.includes(id)?value.filter(item=>item!==id):[...value,id]);
|
||||
return <fieldset disabled={disabled} className="space-y-3 rounded border p-4">
|
||||
<legend>Escolher comprovativos</legend>
|
||||
<p className="text-sm">Escolha os seus documentos que sustentam este pedido. A lista contém ficheiros próprios com análise antimalware concluída; não confirma a sua adequação como comprovativo.</p>
|
||||
<p role="status">{value.length} comprovativos escolhidos</p>
|
||||
{value.map(id=><div key={id} className="flex items-start justify-between gap-3 rounded border p-2">
|
||||
<span className="min-w-0 break-words">{documents.find(document=>document.id===id)?.file_name??'Ficheiro seleccionado indisponível nesta consulta'}</span>
|
||||
<button type="button" className="underline" onClick={()=>toggle(id)}>Retirar</button>
|
||||
</div>)}
|
||||
<label className="block">Pesquisar nos meus ficheiros
|
||||
<input type="search" className="mt-1 w-full rounded border p-2" value={query} onChange={event=>{setQuery(event.target.value);setLimit(10);}} />
|
||||
</label>
|
||||
<button type="button" className="underline" onClick={()=>setShowAll(!showAll)}>{showAll?'Fechar lista':'Ver ficheiros disponíveis'}</button>
|
||||
{(query||showAll)&&<div className="space-y-2">
|
||||
<p role="status">{matches.length} ficheiros encontrados · a mostrar até {Math.min(limit,matches.length)}</p>
|
||||
{matches.slice(0,limit).map(document=><label key={document.id} className="flex gap-2 rounded border p-2">
|
||||
<input type="checkbox" checked={value.includes(document.id)} onChange={()=>toggle(document.id)} />
|
||||
<span className="min-w-0 break-words">{document.file_name}</span>
|
||||
</label>)}
|
||||
{matches.length>limit&&<button type="button" className="underline" onClick={()=>setLimit(limit+10)}>Mostrar mais ficheiros</button>}
|
||||
</div>}
|
||||
</fieldset>;
|
||||
}
|
||||
@@ -50,7 +50,7 @@ function count(props: Record<string, unknown>): number | null {
|
||||
}
|
||||
export default function SearchFeedback() {
|
||||
const page = usePage();
|
||||
const handledLocally = page.component === 'investment/catalogue';
|
||||
const handledLocally = ['investment/catalogue', 'investment/zones'].includes(page.component);
|
||||
const [state, setState] = useState<'idle' | 'loading' | 'error'>('idle');
|
||||
const latest = useRef<{
|
||||
url: string;
|
||||
|
||||
@@ -19,6 +19,7 @@ export type SectorEntryData = {
|
||||
}[];
|
||||
start_href: string | null;
|
||||
register_href: string | null;
|
||||
register_label?: string;
|
||||
start_notice: string | null;
|
||||
register_notice: string | null;
|
||||
specialization_href: string | null;
|
||||
@@ -58,7 +59,7 @@ export default function SectorEntry({
|
||||
className="rounded border px-4 py-3"
|
||||
href={data.register_href}
|
||||
>
|
||||
Cadastrar oportunidade — escolher modalidade
|
||||
{data.register_label ?? 'Cadastrar oportunidade — escolher modalidade'}
|
||||
</Link>
|
||||
) : (
|
||||
<p role="status">{data.register_notice}</p>
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import {SimulationIrpcEconomic} from './simulation-irpc-economic';
|
||||
import {FiscalProofParcelFields} from './fiscal-proof-parcel';
|
||||
import {SimulationIrpcCarry} from './simulation-irpc-carry';
|
||||
import {SimulationIrpcInternational} from './simulation-irpc-international';
|
||||
import {SimulationIrpcPec} from './simulation-irpc-pec';
|
||||
import {useState} from 'react';
|
||||
@@ -17,10 +20,10 @@ export function SimulationIrpcAnnual({draft,onChange}:Props){
|
||||
<p>Colecta disponível:{a.colecta?a.colecta.numerator+'/'+a.colecta.denominator+' MZN':'Indeterminada'};origem:{a.kind==='special'?'L7 qualificado':'L6 normal'};NUIT:{a.subjectNuit||'Por identificar'};exercício:{a.year||'Por identificar'}.</p><button type="button" onClick={()=>{try{save(reuseAnnualAssessment(draft,b));}catch(e){setError(String(e));}}}>Reutilizar colecta corrente L6/L7</button>{field('assessmentReference','Suporte da colecta reutilizada L8')}
|
||||
<fieldset className="space-y-2 rounded border p-3"><legend>Retenções efectivamente sofridas por conta</legend>{group('withholdings','Retenções sofridas')}
|
||||
{options.length===0?<p>Não há afectações de comprovativosL5 neste contexto. Reutilize e reconcilie a retenção recebida emL5 ou declare ausência com suporte.</p>:options.map(o=><div key={o.rowId+'|'+o.paymentId} className="rounded border p-2"><p>{o.document||'Prova por identificar'};emitente:{o.issuer};data:{o.date};parcelaL5:{o.amount}MZN;{o.reason||'Retenção recebida/efectiva por conta reconciliada emL5.'}</p><button type="button" disabled={!o.ready||b.withholdings.rows.some(r=>r.rowId===o.rowId&&r.paymentId===o.paymentId)} onClick={()=>{try{save(reuseAnnualWithholding(draft,b,o.rowId,o.paymentId,crypto.randomUUID()));}catch(e){setError(String(e));}}}>Seleccionar prova L5 {o.document||o.paymentId}</button></div>)}
|
||||
{b.withholdings.rows.map((r,index)=>{const change=(p:Partial<typeof r>)=>patch({withholdings:{...b.withholdings,rows:b.withholdings.rows.map(x=>x.id===r.id?{...x,...p}:x)}});return<fieldset key={r.id} className="rounded border p-2"><legend>Retenção seleccionada {index+1}</legend><p>Rendimento:{r.rowId};prova:{r.paymentId};NUIT:{r.subjectNuit};exercício:{r.year}. Fonte conservada. Se mudou, retire esta selecção e seleccione a prova actual. O histórico mantém-se.</p><label className="block">Parcela a abater<input aria-label={'Parcela da retenção L8 '+(index+1)} value={r.amount} onChange={e=>change({amount:e.target.value})}/></label><label className="block">O próprio sujeito é beneficiário e o rendimento está incluído na base deste exercício<select aria-label={'Rendimento incluído L8 '+(index+1)} value={r.incomeIncluded} onChange={e=>change({incomeIncluded:e.target.value as ''|'yes'|'no'})}><option value="">Informação em falta</option><option value="yes">Sim — documentado</option><option value="no">Não — crédito não aplicável neste fecho</option></select></label><label className="block">Suporte da titularidade e inclusão<input aria-label={'Suporte da retenção L8 '+(index+1)} value={r.reference} onChange={e=>change({reference:e.target.value})}/></label><button type="button" onClick={()=>patch({withholdings:{...b.withholdings,rows:b.withholdings.rows.filter(x=>x.id!==r.id)}})}>Retirar selecção L8 da retenção {index+1}</button></fieldset>;})}</fieldset>
|
||||
{b.withholdings.rows.map((r,index)=>{const change=(p:Partial<typeof r>)=>patch({withholdings:{...b.withholdings,rows:b.withholdings.rows.map(x=>x.id===r.id?{...x,...p}:x)}});return<fieldset key={r.id} className="rounded border p-2"><legend>Retenção seleccionada {index+1}</legend><p>Rendimento:{r.rowId};prova:{r.paymentId};NUIT:{r.subjectNuit};exercício:{r.year}. Fonte conservada. Se mudou, retire esta selecção e seleccione a prova actual. O histórico mantém-se.</p><label className="block">Parcela a abater<input aria-label={'Parcela da retenção L8 '+(index+1)} value={r.amount} onChange={e=>change({amount:e.target.value})}/></label><label className="block">O próprio sujeito é beneficiário e o rendimento está incluído na base deste exercício<select aria-label={'Rendimento incluído L8 '+(index+1)} value={r.incomeIncluded} onChange={e=>change({incomeIncluded:e.target.value as ''|'yes'|'no'})}><option value="">Informação em falta</option><option value="yes">Sim — documentado</option><option value="no">Não — crédito não aplicável neste fecho</option></select></label><label className="block">Suporte da titularidade e inclusão<input aria-label={'Suporte da retenção L8 '+(index+1)} value={r.reference} onChange={e=>change({reference:e.target.value})}/></label><FiscalProofParcelFields value={r} change={change} label={"Retenção L8 "+(index+1)}/><button type="button" onClick={()=>patch({withholdings:{...b.withholdings,rows:b.withholdings.rows.filter(x=>x.id!==r.id)}})}>Retirar selecção L8 da retenção {index+1}</button></fieldset>;})}</fieldset>
|
||||
<fieldset className="space-y-2 rounded border p-3"><legend>PPC efectivamente pagos</legend>{group('ppc','PPC efectuados')}<p>Regista comprovativos de pagamentos por conta; não calcula automaticamente a obrigação PPC nem usa pagamentos previstos no plano.</p><button type="button" onClick={()=>patch({ppc:{...b.ppc,rows:[...b.ppc.rows,{...newAnnualPpc(crypto.randomUUID()),subjectNuit:b.subjectNuit,year:b.year}]}})}>Registar comprovativo PPC</button>
|
||||
{b.ppc.rows.map((r,index)=>{const change=(p:Partial<AnnualPpc>)=>patch({ppc:{...b.ppc,rows:b.ppc.rows.map(x=>x.id===r.id?{...x,...p}:x)}});return<fieldset key={r.id} className="rounded border p-2"><legend>PPC {index+1}</legend>{([['document','Comprovativo'],['issuer','Emitente'],['date','Data (AAAA-MM-DD)'],['subjectNuit','NUIT beneficiário'],['year','Exercício do comprovativo'],['currency','Moeda do comprovativo'],['proofAmount','Montante comprovado'],['amount','Parcela a abater'],['reference','Suporte do pagamento e afectação']]as const).map(([key,label])=><label key={key} className="block">{label}<input aria-label={'PPC L8 '+(index+1)+' — '+label} value={r[key]} onChange={e=>change({[key]:e.target.value})}/></label>)}<label className="block">Pagamento efectivamente comprovado<select aria-label={'PPC L8 '+(index+1)+' — Efectivo'} value={r.effective} onChange={e=>change({effective:e.target.value as ''|'yes'|'no'})}><option value="">Informação em falta</option><option value="yes">Sim — comprovativo reconciliado</option><option value="no">Não — apenas previsão/outro estado</option></select></label><button type="button" onClick={()=>patch({ppc:{...b.ppc,rows:b.ppc.rows.filter(x=>x.id!==r.id)}})}>Retirar PPC {index+1}</button></fieldset>;})}</fieldset>
|
||||
<SimulationIrpcInternational book={b} save={save}/><SimulationIrpcPec book={b} save={save}/>{([...(b.pecPayments?[]:[['pec','PEC']as const]),...(b.internationalCredits?[]:[['credits','Créditos com regras próprias']as const])]).map(([key,label])=><fieldset key={key} className="rounded border p-3"><legend>{label} — tratamento separado</legend><label className="block">Estado — {label}<select aria-label={'Estado L8 — '+label} value={b[key].state} onChange={e=>patch({[key]:{...b[key],state:e.target.value as ''|'known'|'absent'}})}><option value="">Informação em falta</option><option value="absent">Ausência declarada com suporte</option><option value="known">Valor conhecido — positivo exige regra própria</option></select></label>{(b[key].state==='known'||b[key].amount)&&<label className="block">Montante declarado<input aria-label={'Montante L8 — '+label} value={b[key].amount} onChange={e=>patch({[key]:{...b[key],amount:e.target.value}})}/></label>}<label className="block">Suporte<input aria-label={'Suporte L8 — '+label} value={b[key].reference} onChange={e=>patch({[key]:{...b[key],reference:e.target.value}})}/></label></fieldset>)}
|
||||
{b.ppc.rows.map((r,index)=>{const change=(p:Partial<AnnualPpc>)=>patch({ppc:{...b.ppc,rows:b.ppc.rows.map(x=>x.id===r.id?{...x,...p}:x)}});return<fieldset key={r.id} className="rounded border p-2"><legend>PPC {index+1}</legend>{([['document','Comprovativo'],['issuer','Emitente'],['date','Data (AAAA-MM-DD)'],['subjectNuit','NUIT beneficiário'],['year','Exercício do comprovativo'],['currency','Moeda do comprovativo'],['proofAmount','Montante comprovado'],['amount','Parcela a abater'],['reference','Suporte do pagamento e afectação']]as const).map(([key,label])=><label key={key} className="block">{label}<input aria-label={'PPC L8 '+(index+1)+' — '+label} value={r[key]} onChange={e=>change({[key]:e.target.value})}/></label>)}<label className="block">Pagamento efectivamente comprovado<select aria-label={'PPC L8 '+(index+1)+' — Efectivo'} value={r.effective} onChange={e=>change({effective:e.target.value as ''|'yes'|'no'})}><option value="">Informação em falta</option><option value="yes">Sim — comprovativo reconciliado</option><option value="no">Não — apenas previsão/outro estado</option></select></label><FiscalProofParcelFields value={r} change={change} label={"PPC L8 "+(index+1)}/><button type="button" onClick={()=>patch({ppc:{...b.ppc,rows:b.ppc.rows.filter(x=>x.id!==r.id)}})}>Retirar PPC {index+1}</button></fieldset>;})}</fieldset>
|
||||
<SimulationIrpcEconomic book={b} save={save} residentConfirmed={a.current&&a.book.scope==='resident_general'&&b.subjectNuit===a.subjectNuit&&b.year===a.year&&b.assessmentKey===a.key}/><SimulationIrpcInternational book={b} save={save}/><SimulationIrpcPec book={b} save={save}/><SimulationIrpcCarry book={b} save={save}/>{([...(b.pecPayments?[]:[['pec','PEC']as const]),...(b.internationalCredits?[]:[['credits','Créditos com regras próprias']as const])]).map(([key,label])=><fieldset key={key} className="rounded border p-3"><legend>{label} — tratamento separado</legend><label className="block">Estado — {label}<select aria-label={'Estado L8 — '+label} value={b[key].state} onChange={e=>patch({[key]:{...b[key],state:e.target.value as ''|'known'|'absent'}})}><option value="">Informação em falta</option><option value="absent">Ausência declarada com suporte</option><option value="known">Valor conhecido — positivo exige regra própria</option></select></label>{(b[key].state==='known'||b[key].amount)&&<label className="block">Montante declarado<input aria-label={'Montante L8 — '+label} value={b[key].amount} onChange={e=>patch({[key]:{...b[key],amount:e.target.value}})}/></label>}<label className="block">Suporte<input aria-label={'Suporte L8 — '+label} value={b[key].reference} onChange={e=>patch({[key]:{...b[key],reference:e.target.value}})}/></label></fieldset>)}
|
||||
<button type="button" onClick={()=>{try{save(recordAnnual(draft,b));}catch(e){setError(String(e));}}}>Calcular e guardar saldo anual L8</button><button type="button" onClick={()=>{try{const html=annualHtml(draft),url=URL.createObjectURL(new Blob([html],{type:'text/html;charset=utf-8'})),link=document.createElement('a');link.href=url;link.download='IRPC-L8-saldo-simulado.html';link.click();URL.revokeObjectURL(url);setError('');}catch(e){setError(String(e));}}}>Exportar saldo anual L8</button>
|
||||
{annualReportRows(draft).map((r,n)=><p key={n}>{r[1]} — {r[2]} — {r[3]}</p>)}</section>;
|
||||
}catch(e){return<p role="alert">PreparaçãoL8 não recuperável:{String(e)}. Originais e históricos conservados.</p>;}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import {prepareCreditCarry, type AnnualBook} from '@/lib/irpc-annual-settlement';
|
||||
import {carrySource, newCarryLot, newCarryUse, type CarryLot, type CreditCarry} from '@/lib/irpc-credit-carry';
|
||||
import CountrySelect, {type Country} from '@/components/country-select';
|
||||
import {countryIsoCodes} from '@/lib/country-iso-codes';
|
||||
|
||||
const pt = new Intl.DisplayNames(['pt'], {type: 'region'});
|
||||
const en = new Intl.DisplayNames(['en'], {type: 'region'});
|
||||
const countries: Country[] = countryIsoCodes.filter(code => code !== 'MZ').map(code => ({code, name: pt.of(code) ?? code, name_en: en.of(code) ?? code})).sort((a, b) => a.name.localeCompare(b.name, 'pt'));
|
||||
|
||||
export function SimulationIrpcCarry({book, save}: {book: AnnualBook; save: (book: AnnualBook) => void}) {
|
||||
const c = book.creditCarry;
|
||||
if (!c) return <fieldset className="rounded border p-3"><legend>Saldos de exercícios anteriores</legend><p>Se dispõe de remanescentes documentados de crédito internacional ou PEC, prepare a origem e as utilizações efectivas. Os resultados anteriores ficam conservados.</p><button type="button" onClick={() => save(prepareCreditCarry(book))}>Preparar saldos anteriores</button></fieldset>;
|
||||
const update = (value: CreditCarry) => save({...book, creditCarry: value});
|
||||
const lotChange = (r: CarryLot) => update({...c, lots: c.lots.map(x => x.id === r.id ? r : x)});
|
||||
return <fieldset className="space-y-3 rounded border p-3"><legend>Crédito internacional e PEC — exercícios anteriores</legend>
|
||||
<p>{carrySource}</p>
|
||||
<label className="block">Inventário de saldos anteriores<select aria-label="Estado dos saldos anteriores L8" value={c.state} onChange={e => update({...c, state: e.target.value as CreditCarry['state']})}><option value="">Informação em falta</option><option value="known">Saldos conhecidos</option><option value="absent">Ausência documentada</option></select></label>
|
||||
<label className="block">Suporte do inventário<input aria-label="Suporte dos saldos anteriores L8" value={c.reference} onChange={e => update({...c, reference: e.target.value})}/></label>
|
||||
{(c.state === 'known' || c.lots.length > 0) && <>
|
||||
<p>Consolide uma origem por natureza, país e exercício. Transcreva o montante elegível apurado e o deduzido na origem, com o suporte da regra desse exercício. Imposto estrangeiro acima dos limites de elegibilidade não é remanescente por insuficiência de colecta. Só se aplica aqui o prazo ordinário a exercícios anuais; situações transitórias ou especiais exigem correspondência própria.</p>
|
||||
<button type="button" onClick={() => update({...c, lots: [...c.lots, {...newCarryLot(crypto.randomUUID()), subjectNuit: book.subjectNuit}]})}>Registar origem de saldo anterior</button>
|
||||
</>}
|
||||
{c.lots.map((r, i) => {
|
||||
const patch = (v: Partial<CarryLot>) => lotChange({...r, ...v});
|
||||
const prefix = 'Saldo anterior ' + (i + 1) + ' — ';
|
||||
return <fieldset key={r.id} className="space-y-2 rounded border p-3"><legend>Origem {i + 1}</legend>
|
||||
<label className="block">Natureza<select aria-label={prefix + 'Natureza'} value={r.kind} onChange={e => patch({kind: e.target.value as CarryLot['kind']})}><option value="">Por identificar</option><option value="international">Crédito por dupla tributação internacional</option><option value="pec">PEC efectivamente pago</option></select></label>
|
||||
{(r.kind === 'international' || r.country) && <CountrySelect countries={countries} label={prefix + 'País estrangeiro'} value={r.country} onChange={country => patch({country})} allowLegacyValue/>}
|
||||
{r.kind === 'pec' && <p>O PEC não tem país estrangeiro. A escolha da natureza conserva os valores introduzidos; reconcilie qualquer país anterior.</p>}
|
||||
{([['subjectNuit', 'NUIT titular'], ['year', 'Exercício de origem'], ['currency', 'Moeda comprovada'], ['originDocument', 'Declaração/apuramento de origem'], ['originReference', 'Suporte da origem e insuficiência de colecta'], ['ruleReference', 'Regra e período aplicáveis na origem'], ['eligible', 'Montante elegível na origem — MZN'], ['originDeducted', 'Deduzido na origem — MZN'], ['selected', 'Parcela escolhida para este fecho — MZN']] as const).map(([key, label]) => <label key={key} className="block">{label}<input aria-label={prefix + label} value={r[key]} onChange={e => patch({[key]: e.target.value})}/></label>)}
|
||||
<label className="block">Exercício de origem anual ordinário<select aria-label={prefix + 'Período ordinário'} value={r.ordinary} onChange={e => patch({ordinary: e.target.value as CarryLot['ordinary']})}><option value="">Informação em falta</option><option value="yes">Sim — documentado</option><option value="no">Não — regra específica por corresponder</option></select></label>
|
||||
<label className="block">Remanescente por insuficiência de colecta<select aria-label={prefix + 'Insuficiência de colecta'} value={r.insufficient} onChange={e => patch({insufficient: e.target.value as CarryLot['insufficient']})}><option value="">Informação em falta</option><option value="yes">Sim — documentado</option><option value="no">Não — não é saldo elegível neste percurso</option></select></label>
|
||||
<label className="block">Utilizações efectivas posteriores à origem<select aria-label={prefix + 'Estado dos usos'} value={r.usesState} onChange={e => patch({usesState: e.target.value as CarryLot['usesState']})}><option value="">Informação em falta</option><option value="known">Utilizações conhecidas</option><option value="absent">Ausência documentada</option></select></label>
|
||||
<label className="block">Suporte do inventário de utilizações<input aria-label={prefix + 'Suporte dos usos'} value={r.usesReference} onChange={e => patch({usesReference: e.target.value})}/></label>
|
||||
<p>Inclua utilizações efectivas já ocorridas neste exercício antes desta parcela. Não registe simulações históricas como utilizações fiscais. Crédito internacional admite fracção exacta n/d; não é aplicado arredondamento fiscal.</p>
|
||||
{r.usesState === 'known' && <button type="button" onClick={() => patch({uses: [...r.uses, newCarryUse(crypto.randomUUID())]})}>Registar utilização efectiva da origem {i + 1}</button>}
|
||||
{r.uses.map((u, j) => <fieldset key={u.id} className="rounded border p-2"><legend>Utilização {i + 1}.{j + 1}</legend>
|
||||
{([['year', 'Exercício'], ['amount', 'Montante MZN'], ['document', 'Documento de utilização'], ['reference', 'Suporte']] as const).map(([key, label]) => <label key={key} className="block">{label}<input aria-label={prefix + 'Uso ' + (j + 1) + ' — ' + label} value={u[key]} onChange={e => patch({uses: r.uses.map(x => x.id === u.id ? {...x, [key]: e.target.value} : x)})}/></label>)}
|
||||
<button type="button" onClick={() => patch({uses: r.uses.filter(x => x.id !== u.id)})}>Retirar utilização {i + 1}.{j + 1}</button>
|
||||
</fieldset>)}
|
||||
<button type="button" onClick={() => update({...c, lots: c.lots.filter(x => x.id !== r.id)})}>Retirar origem {i + 1}</button>
|
||||
</fieldset>;
|
||||
})}
|
||||
{(c.state === 'known' || c.currentInternational || c.currentPec || c.allocationReference) && <fieldset className="space-y-2 rounded border p-3"><legend>Escolha das parcelas entre exercícios</legend>
|
||||
<p>Escolha quanto deduzir dos créditos correntes e de cada origem anterior. Os créditos internacionais precedem o PEC; a soma fica limitada à colecta. Não se presume prioridade entre exercícios e nenhuma parcela é reduzida automaticamente. Valores não escolhidos ficam identificados, sem criação de transporte oficial.</p>
|
||||
<label className="block">Crédito internacional corrente a deduzir — MZN<input aria-label="Parcela corrente internacional L8" value={c.currentInternational} onChange={e => update({...c, currentInternational: e.target.value})}/></label>
|
||||
<label className="block">PEC corrente a deduzir — MZN<input aria-label="Parcela corrente PEC L8" value={c.currentPec} onChange={e => update({...c, currentPec: e.target.value})}/></label>
|
||||
<label className="block">Suporte da escolha e seus impactos<input aria-label="Suporte da afectação entre exercícios L8" value={c.allocationReference} onChange={e => update({...c, allocationReference: e.target.value})}/></label>
|
||||
<button type="button" onClick={() => update({...c, assessmentKey: book.assessmentKey})}>Confirmar afectação à colecta seleccionada</button>
|
||||
<p>{c.assessmentKey && c.assessmentKey === book.assessmentKey ? 'Escolha vinculada à colecta seleccionada; o cálculo verifica disponibilidade e limites.' : 'Falta confirmar a escolha na colecta seleccionada. Valores conservados.'}</p>
|
||||
</fieldset>}
|
||||
</fieldset>;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import {prepareEconomicBook, type AnnualBook} from '@/lib/irpc-annual-settlement';
|
||||
import {economicSource, newEconomicPosition, type EconomicPosition} from '@/lib/irpc-economic-credit';
|
||||
|
||||
export function SimulationIrpcEconomic({book, save, residentConfirmed}: {book: AnnualBook; save: (book: AnnualBook) => void; residentConfirmed: boolean}) {
|
||||
const c = book.economicCredits;
|
||||
if (!c) return <fieldset className="rounded border p-3"><legend>Crédito por dupla tributação económica</legend><p>Para lucros distribuídos por entidade moçambicana sujeita e não isenta de IRPC, distinga o imposto correspondente aos lucros da retenção sofrida e do imposto estrangeiro. Reutiliza a colecta e conserva o resumo de créditos anterior.</p><button type="button" onClick={() => save(prepareEconomicBook(book))}>Preparar crédito económico</button></fieldset>;
|
||||
const update = (next: typeof c) => save({...book, economicCredits: next});
|
||||
const rowChange = (r: EconomicPosition) => update({...c, rows: c.rows.map(x => x.id === r.id ? r : x)});
|
||||
return <fieldset className="space-y-3 rounded border p-3"><legend>Crédito económico — lucros distribuídos</legend>
|
||||
<p>{economicSource}</p>
|
||||
<p>O detalhe substitui nesta execução o resumo económico anterior, que permanece conservado: {book.internationalCredits?.economic.state || 'informação em falta'}; montante {book.internationalCredits?.economic.amount || 'não preenchido'}. Os benefícios e o crédito internacional mantêm os seus estados próprios.</p>
|
||||
<label className="block">Estado do crédito económico<select aria-label="Estado do crédito económico L8" value={c.state} onChange={e => update({...c, state: e.target.value as typeof c.state})}><option value="">Informação em falta</option><option value="known">Lucros e IRPC conhecidos</option><option value="absent">Ausência documentada</option></select></label>
|
||||
<label className="block">Suporte do inventário económico<input aria-label="Suporte económico L8" value={c.reference} onChange={e => update({...c, reference: e.target.value})}/></label>
|
||||
{(c.state === 'known' || c.rows.length > 0) && <button type="button" onClick={() => update({...c, state: 'known', rows: [...c.rows, {...newEconomicPosition(crypto.randomUUID()), subjectNuit: book.subjectNuit, year: book.year, recipientResident: residentConfirmed ? 'yes' : ''}]})}>Registar lucros distribuídos</button>}
|
||||
{c.rows.map((r, i) => {
|
||||
const patch = (v: Partial<EconomicPosition>) => rowChange({...r, ...v});
|
||||
const prefix = 'Crédito económico ' + (i + 1) + ' — ';
|
||||
const field = (key: Exclude<keyof EconomicPosition, 'previousUse'>, label: string) => <label key={key} className="block">{label}<input aria-label={prefix + label} value={r[key]} onChange={e => patch({[key]: e.target.value})}/></label>;
|
||||
const choice = (key: 'recipientResident' | 'payerResident' | 'payerIrpc' | 'payerExempt' | 'article40' | 'incomeIncluded', label: string) => <label key={key} className="block">{label}<select aria-label={prefix + label} value={r[key]} onChange={e => patch({[key]: e.target.value})}><option value="">Informação em falta</option><option value="yes">Sim — documentado</option><option value="no">Não — documentado</option></select></label>;
|
||||
const outside = !!r.kind && r.kind !== 'ordinary_profit' || r.article40 === 'yes';
|
||||
const detail = <>
|
||||
{([['distributionDocument', 'Documento da distribuição'], ['distributionParcel', 'Parcela dos lucros no documento'], ['distributionDate', 'Data da distribuição (AAAA-MM-DD)'], ['income', 'Lucros incluídos antes do crédito — MZN, ilíquidos de retenção'], ['incomeReference', 'Suporte da inclusão e do valor ilíquido na base corrente'], ['taxIssuer', 'Emitente do comprovativo de IRPC correspondente'], ['taxDocument', 'Documento do IRPC correspondente aos lucros'], ['taxParcel', 'Parcela desse IRPC no documento'], ['parcelReference', 'Suporte da identificação da parcela de imposto'], ['currency', 'Moeda comprovada'], ['proofAmount', 'IRPC comprovado nesta parcela — MZN'], ['taxAmount', 'IRPC correspondente aos lucros seleccionados — MZN'], ['attributionReference', 'Suporte da correspondência entre imposto e lucros'], ['previouslyAttributed', 'IRPC desta parcela já atribuído a outros lucros — MZN'], ['priorAttributionReference', 'Suporte das atribuições anteriores, incluindo zero conhecido'], ['grossUpIncluded', 'Crédito nominal já acrescido à base (art.53) — MZN'], ['grossUpReference', 'Suporte do acréscimo art.53 já incluído em L6'], ['nationalLimit', 'Quota proporcional da colecta após acréscimo — MZN'], ['nationalLimitReference', 'Suporte da quota proporcional da colecta']] as const).map(([key, label]) => field(key, label))}
|
||||
{choice('incomeIncluded', 'Lucros ilíquidos e acréscimo incluídos na base corrente')}
|
||||
<p>O cálculo confere 60% do IRPC correspondente com o acréscimo já incluído em L6 e a quota proporcional documentada. Se a base estiver incompleta, reconcilie-a no percurso existente. Esta acção conserva os valores e não altera a colecta automaticamente.</p>
|
||||
<button type="button" onClick={() => patch({assessmentKey: book.assessmentKey})}>Confirmar inclusão e quota na colecta seleccionada</button>
|
||||
<label className="block">Utilização anterior efectiva do crédito<select aria-label={prefix + 'Estado do uso anterior'} value={r.previousUse.state} onChange={e => patch({previousUse: {...r.previousUse, state: e.target.value as EconomicPosition['previousUse']['state']}})}><option value="">Informação em falta</option><option value="known">Montante conhecido</option><option value="absent">Ausência documentada</option></select></label>
|
||||
{(r.previousUse.state === 'known' || r.previousUse.amount) && <label className="block">Crédito já utilizado — MZN<input aria-label={prefix + 'Uso anterior MZN'} value={r.previousUse.amount} onChange={e => patch({previousUse: {...r.previousUse, amount: e.target.value}})}/></label>}
|
||||
<label className="block">Suporte do uso anterior ou da sua ausência<input aria-label={prefix + 'Suporte do uso anterior'} value={r.previousUse.reference} onChange={e => patch({previousUse: {...r.previousUse, reference: e.target.value}})}/></label>
|
||||
</>;
|
||||
return <fieldset key={r.id} className="space-y-2 rounded border p-3"><legend>Lucros {i + 1}</legend>
|
||||
{field('subjectNuit', 'NUIT beneficiário')}{field('payerNuit', 'NUIT distribuidor')}{field('year', 'Exercício')}
|
||||
<label className="block">Natureza<select aria-label={prefix + 'Natureza'} value={r.kind} onChange={e => patch({kind: e.target.value as EconomicPosition['kind']})}><option value="">Por identificar</option><option value="ordinary_profit">Lucros ordinários — art.64(1–2)</option><option value="liquidation">Partilha em liquidação — art.64(3)</option><option value="association">Associação — art.64(4)</option></select></label>
|
||||
{residentConfirmed && r.recipientResident === 'yes' ? <p>Residência do beneficiário reutilizada da colecta corrente no regime geral. NUIT e exercício conservados.</p> : choice('recipientResident', 'Beneficiário com sede/direcção efectiva em Moçambique')}{choice('payerResident', 'Distribuidor com sede/direcção efectiva em Moçambique')}{choice('payerIrpc', 'Distribuidor sujeito a IRPC')}{choice('payerExempt', 'Distribuidor isento de IRPC')}{field('qualificationReference', 'Suporte da qualificação das entidades e dos lucros')}
|
||||
{choice('article40', 'Esta parcela está abrangida pela exclusão do art.40(1)')}{field('article40Reference', 'Suporte da correspondência do art.40(1) e seu período')}
|
||||
<p>O art.40(1), na redacção de 2009, contempla as entidades e condições próprias, incluindo participação directa de pelo menos20% e prazo de dois anos, nos termos da fonte. Uma parcela excluída da base não recebe também o crédito64. A simples percentagem de participação não decide todas as condições.</p>
|
||||
{outside ? <><p>Esta parcela exige o tratamento específico identificado. O crédito ordinário não é aplicado; os valores introduzidos ficam conservados.</p><details><summary>Consultar ou reconciliar dados conservados</summary>{detail}</details></> : detail}
|
||||
<button type="button" onClick={() => update({...c, rows: c.rows.filter(x => x.id !== r.id)})}>Retirar lucros {i + 1}</button>
|
||||
</fieldset>;
|
||||
})}
|
||||
</fieldset>;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import {FiscalProofParcelFields} from './fiscal-proof-parcel';
|
||||
import CountrySelect, {type Country} from '@/components/country-select';
|
||||
import {countryIsoCodes} from '@/lib/country-iso-codes';
|
||||
import {newInternationalProof, prepareInternationalBook, type AnnualBook} from '@/lib/irpc-annual-settlement';
|
||||
@@ -22,9 +23,9 @@ export function SimulationIrpcInternational({book, save}: {book: AnnualBook; sav
|
||||
<p>Reúna os comprovativos de cada país numa posição por exercício. Indique a fracção nacional e a convenção conforme o suporte do caso. Limites admitem decimal ou fracção exacta n/d; a apresentação não constitui arredondamento fiscal. Valores MZN exigem correspondência documental; uma previsão de câmbio ou de pagamento não comprova o crédito.</p>
|
||||
<label className="block">Estado internacional<select aria-label="Estado do crédito internacional L8" value={c.state} onChange={e => update({...c, state: e.target.value as InternationalCredits['state']})}><option value="">Informação em falta</option><option value="known">Posições conhecidas</option><option value="absent">Ausência declarada</option></select></label>
|
||||
<label className="block">Suporte do inventário<input aria-label="Suporte do crédito internacional L8" value={c.reference} onChange={e => update({...c, reference: e.target.value})}/></label>
|
||||
<Evidence label="Crédito económico — regra própria" value={c.economic} change={economic => update({...c, economic})}/>
|
||||
{book.economicCredits ? <p>Resumo económico anterior conservado: {c.economic.state || "Informação em falta"}; {c.economic.amount || "Montante não preenchido"}. Nesta execução é usado o detalhe económico acima.</p> : <Evidence label="Crédito económico — regra própria" value={c.economic} change={economic => update({...c, economic})}/>}
|
||||
<Evidence label="Benefícios/créditos próprios — regra própria" value={c.benefits} change={benefits => update({...c, benefits})}/>
|
||||
<p>Créditos económicos e benefícios positivos exigem regras próprias; informação em falta mantém o saldo dependente indeterminado.</p>
|
||||
<p>{book.economicCredits ? "Benefícios positivos exigem regras próprias; o crédito económico tem o seu detalhe separado. Informação em falta mantém o saldo dependente indeterminado." : "Créditos económicos e benefícios positivos exigem regras próprias; informação em falta mantém o saldo dependente indeterminado."}</p>
|
||||
<button type="button" onClick={() => update({...c, state: 'known', positions: [...c.positions, {...newInternationalPosition(crypto.randomUUID()), subjectNuit: book.subjectNuit, year: book.year, assessmentKey: book.assessmentKey}]})}>Registar posição internacional</button>
|
||||
{c.positions.map((p, index) => {
|
||||
const patch = (v: Partial<InternationalPosition>) => positionChange({...p, ...v});
|
||||
@@ -47,7 +48,7 @@ export function SimulationIrpcInternational({book, save}: {book: AnnualBook; sav
|
||||
{(r.exerciseReference || r.date && !r.date.startsWith(p.year + '-')) && <label className="block">Suporte da correspondência da data ao exercício<input aria-label={'Imposto estrangeiro ' + (index + 1) + '.' + (ri + 1) + ' — Correspondência temporal'} value={r.exerciseReference} onChange={e => change({exerciseReference: e.target.value})}/></label>}
|
||||
<label className="block">Pagamento efectivo<select aria-label={'Imposto estrangeiro ' + (index + 1) + '.' + (ri + 1) + ' — Efectivo'} value={r.effective} onChange={e => change({effective: e.target.value as InternationalTaxProof['effective']})}><option value="">Informação em falta</option><option value="yes">Sim — comprovado</option><option value="no">Não — previsão/outra situação</option></select></label>
|
||||
<label className="block">Imposto sobre o rendimento elegível<select aria-label={'Imposto estrangeiro ' + (index + 1) + '.' + (ri + 1) + ' — Natureza'} value={r.incomeTax} onChange={e => change({incomeTax: e.target.value as InternationalTaxProof['incomeTax']})}><option value="">Informação em falta</option><option value="yes">Sim — natureza documentada</option><option value="no">Não — outra natureza, sem crédito presumido</option></select></label>
|
||||
<button type="button" onClick={() => patch({payments: p.payments.filter(x => x.id !== r.id)})}>Retirar imposto estrangeiro {index + 1}.{ri + 1}</button>
|
||||
<FiscalProofParcelFields value={r} change={change} label={"Imposto estrangeiro " + (index + 1) + "." + (ri + 1)}/><button type="button" onClick={() => patch({payments: p.payments.filter(x => x.id !== r.id)})}>Retirar imposto estrangeiro {index + 1}.{ri + 1}</button>
|
||||
</fieldset>;
|
||||
})}
|
||||
<button type="button" onClick={() => update({...c, positions: c.positions.filter(x => x.id !== p.id)})}>Retirar posição internacional {index + 1}</button>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import {FiscalProofParcelFields} from './fiscal-proof-parcel';
|
||||
import {newPecPayment, pecSource, type PecPayment} from '@/lib/irpc-pec';
|
||||
import type {AnnualBook} from '@/lib/irpc-annual-settlement';
|
||||
|
||||
@@ -15,7 +16,7 @@ export function SimulationIrpcPec({book, save}: {book: AnnualBook; save: (book:
|
||||
return <fieldset key={r.id} className="rounded border p-2"><legend>PEC {index + 1}</legend>
|
||||
{([['document', 'Comprovativo PEC'], ['issuer', 'Emitente'], ['date', 'Data (AAAA-MM-DD)'], ['subjectNuit', 'NUIT beneficiário'], ['year', 'Exercício de origem'], ['currency', 'Moeda'], ['proofAmount', 'Montante comprovado'], ['previouslyUsed', 'Já utilizado fora destas parcelas'], ['priorUseReference', 'Suporte das utilizações anteriores ou do zero conhecido'], ['amount', 'Parcela disponível seleccionada'], ['reference', 'Suporte do pagamento PEC e afectação']] as const).map(([key, label]) => <label key={key} className="block">{label}<input aria-label={'PEC L8 ' + (index + 1) + ' — ' + label} value={r[key]} onChange={e => change({[key]: e.target.value})}/></label>)}
|
||||
<label className="block">Pagamento PEC efectivamente comprovado<select aria-label={'PEC L8 ' + (index + 1) + ' — Efectivo'} value={r.effective} onChange={e => change({effective: e.target.value as PecPayment['effective']})}><option value="">Informação em falta</option><option value="yes">Sim — natureza PEC e pagamento reconciliados</option><option value="no">Não — previsão ou outra natureza</option></select></label>
|
||||
<button type="button" onClick={() => update({...detail, rows: detail.rows.filter(x => x.id !== r.id)})}>Retirar selecção PEC {index + 1}</button>
|
||||
<FiscalProofParcelFields value={r} change={change} label={"PEC L8 " + (index + 1)}/><button type="button" onClick={() => update({...detail, rows: detail.rows.filter(x => x.id !== r.id)})}>Retirar selecção PEC {index + 1}</button>
|
||||
</fieldset>;
|
||||
})}
|
||||
<p>O detalhe substitui o resumo PEC apenas nesta execução. Os comprovativos e resultados de execuções anteriores permanecem no histórico; não há consumo automático de saldos oficiais.</p>
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
|
||||
type Choice = { id: string; name: string; source_code?: string | null };
|
||||
|
||||
/** One search field owns the list and commits only an explicitly chosen option. */
|
||||
export default function TerritorySearchSelect<T extends Choice>({
|
||||
id, label, search, onSearch, options, selected, onChange, disabled = false,
|
||||
loading = false, error, required = false, className, placeholder, children,
|
||||
}: {
|
||||
id: string; label: string; search: string; onSearch: (query: string) => void;
|
||||
options: T[]; selected?: T; onChange: (option?: T) => void;
|
||||
disabled?: boolean; loading?: boolean; error?: string; required?: boolean;
|
||||
className?: string; placeholder?: string; children?: ReactNode;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [active, setActive] = useState(-1);
|
||||
const activeRef = useRef<HTMLButtonElement | null>(null);
|
||||
const expanded = open && !disabled;
|
||||
const listId = `${id}-options`;
|
||||
useEffect(() => { if (expanded) activeRef.current?.scrollIntoView({ block: 'nearest' }); }, [active, expanded]);
|
||||
const close = () => { setOpen(false); setActive(-1); onSearch(''); };
|
||||
const choose = (option?: T) => { onChange(option); close(); };
|
||||
return <div className="relative" onBlur={(event) => {
|
||||
if (!event.currentTarget.contains(event.relatedTarget as Node | null)) close();
|
||||
}}>
|
||||
<input id={id} className={className} role="combobox" aria-label={`Pesquisar ${label}`}
|
||||
aria-autocomplete="list" aria-expanded={expanded} aria-controls={expanded ? listId : undefined}
|
||||
aria-activedescendant={expanded && !loading && options[active] ? `${listId}-${active}` : undefined}
|
||||
aria-invalid={Boolean(error)} aria-describedby={error ? `${id}-error` : undefined}
|
||||
aria-required={required || undefined} required={required} autoComplete="off" maxLength={100}
|
||||
disabled={disabled} value={expanded ? search : selected?.name ?? ''}
|
||||
placeholder={disabled ? 'Seleccione o nível anterior' : placeholder ?? `Pesquisar ${label.toLowerCase()}`}
|
||||
onFocus={() => { setOpen(true); setActive(-1); onSearch(''); }}
|
||||
onClick={() => setOpen(true)}
|
||||
onChange={(event) => { setOpen(true); setActive(-1); onSearch(event.target.value); }}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Escape') { event.preventDefault(); close(); }
|
||||
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
|
||||
event.preventDefault(); setOpen(true);
|
||||
setActive((current) => !options.length ? -1 : event.key === 'ArrowDown'
|
||||
? Math.min(current + 1, options.length - 1) : current < 0 ? options.length - 1 : Math.max(0, current - 1));
|
||||
}
|
||||
if (event.key === 'Enter' && expanded) {
|
||||
event.preventDefault();
|
||||
if (!loading && options[active < 0 ? 0 : active]) choose(options[active < 0 ? 0 : active]);
|
||||
}
|
||||
}} />
|
||||
{selected && !disabled && <button type="button" className="mt-1 text-sm underline"
|
||||
aria-label={`Limpar ${label}`} onClick={() => choose()}>Limpar</button>}
|
||||
{error && <p id={`${id}-error`} role="alert">{error}</p>}
|
||||
{expanded && <div className="absolute z-50 mt-1 max-h-72 w-full overflow-y-auto rounded border bg-background p-1 text-foreground shadow-lg">
|
||||
<div id={listId} role="listbox" aria-label={label} aria-busy={loading}>
|
||||
{loading && <p role="status" className="p-2">A carregar…</p>}
|
||||
{!loading && options.length === 0 && <p className="p-2">{error ? 'Não foi possível carregar as opções.' : 'Sem resultados para esta pesquisa.'}</p>}
|
||||
{options.map((option, index) => <button key={option.id} id={`${listId}-${index}`} type="button"
|
||||
ref={index === active ? activeRef : undefined} role="option" tabIndex={-1}
|
||||
aria-selected={option.id === selected?.id} disabled={loading}
|
||||
className={`block w-full rounded p-2 text-left hover:bg-accent ${index === active ? 'bg-accent' : ''}`}
|
||||
onMouseDown={(event) => event.preventDefault()} onClick={() => choose(option)}>
|
||||
{option.name}{option.source_code ? ` (${option.source_code})` : ''}
|
||||
</button>)}
|
||||
</div>
|
||||
{children}
|
||||
</div>}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
export const forceLabels = {
|
||||
rivalry: 'Rivalidade entre concorrentes',
|
||||
entrants: 'Ameaça de novos entrantes',
|
||||
substitutes: 'Ameaça de produtos ou serviços substitutos',
|
||||
suppliers: 'Poder negocial dos fornecedores',
|
||||
buyers: 'Poder negocial dos clientes',
|
||||
} as const;
|
||||
|
||||
export type Force = keyof typeof forceLabels;
|
||||
export type Assessment = {
|
||||
pressure: '' | 'low' | 'medium' | 'high';
|
||||
evidence: string;
|
||||
source: string;
|
||||
period: string;
|
||||
rationale: string;
|
||||
limitations: string;
|
||||
opportunity: string;
|
||||
};
|
||||
export type CompetitivenessDraft = {
|
||||
version: 1;
|
||||
clusterId: string;
|
||||
sector: string;
|
||||
region: string;
|
||||
forces: Record<Force, Assessment>;
|
||||
};
|
||||
|
||||
export const forces = Object.keys(forceLabels) as Force[];
|
||||
const fields = [
|
||||
'evidence',
|
||||
'source',
|
||||
'period',
|
||||
'rationale',
|
||||
'limitations',
|
||||
'opportunity',
|
||||
] as const;
|
||||
|
||||
export function newCompetitivenessDraft(
|
||||
clusterId: string,
|
||||
sector: string,
|
||||
): CompetitivenessDraft {
|
||||
return {
|
||||
version: 1,
|
||||
clusterId,
|
||||
sector,
|
||||
region: '',
|
||||
forces: Object.fromEntries(
|
||||
forces.map((force) => [
|
||||
force,
|
||||
{
|
||||
pressure: '',
|
||||
evidence: '',
|
||||
source: '',
|
||||
period: '',
|
||||
rationale: '',
|
||||
limitations: '',
|
||||
opportunity: '',
|
||||
},
|
||||
]),
|
||||
) as Record<Force, Assessment>,
|
||||
};
|
||||
}
|
||||
|
||||
// A pressure is an author's qualitative assessment, never inferred from missing data.
|
||||
export function assessmentReady(row: Assessment): boolean {
|
||||
return (
|
||||
['low', 'medium', 'high'].includes(row.pressure) &&
|
||||
fields.every((field) => row[field].trim().length > 0)
|
||||
);
|
||||
}
|
||||
|
||||
export function diagnosticReady(draft: CompetitivenessDraft): boolean {
|
||||
return (
|
||||
Boolean(draft.sector.trim() && draft.region.trim()) &&
|
||||
forces.every((force) => assessmentReady(draft.forces[force]))
|
||||
);
|
||||
}
|
||||
|
||||
export function readCompetitivenessDraft(
|
||||
raw: string,
|
||||
clusterId: string,
|
||||
): CompetitivenessDraft {
|
||||
if (raw.length > 250_000)
|
||||
throw Error('O ficheiro excede o limite de 250 KB.');
|
||||
const input = JSON.parse(raw);
|
||||
if (!input || input.version !== 1 || input.clusterId !== clusterId) {
|
||||
throw Error(
|
||||
'O ficheiro não corresponde a este cluster ou tem uma versão incompatível.',
|
||||
);
|
||||
}
|
||||
const text = (value: unknown, max: number): string => {
|
||||
if (typeof value !== 'string' || value.length > max)
|
||||
throw Error('O ficheiro contém campos inválidos.');
|
||||
return value;
|
||||
};
|
||||
const draft = newCompetitivenessDraft(clusterId, text(input.sector, 200));
|
||||
draft.region = text(input.region, 1000);
|
||||
for (const force of forces) {
|
||||
const row = input.forces?.[force];
|
||||
if (!row || !['', 'low', 'medium', 'high'].includes(row.pressure)) {
|
||||
throw Error('O ficheiro não contém as cinco forças válidas.');
|
||||
}
|
||||
draft.forces[force].pressure = row.pressure;
|
||||
for (const field of fields)
|
||||
draft.forces[force][field] = text(row[field], 5000);
|
||||
}
|
||||
return draft;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/** Presentation only. Original taxonomy identifiers remain the form/query values. */
|
||||
const names:Record<string,string>={
|
||||
agronegocio:'Agronegócio','bens-de-consumo-e-franquias':'Bens de consumo e franquias',energia:'Energia e mineração (catálogo histórico)',
|
||||
'energia-especifica':'Energia',fintech:'Fintech',fiscalidade:'Fiscalidade',imobiliario:'Imobiliário',infraestruturas:'Infraestruturas',
|
||||
iva:'IVA',mineracao:'Mineração','território':'Território',territorio:'Território',turismo:'Turismo','mercado-financeiro':'Mercado financeiro',
|
||||
education:'Formação e competências',media:'Imagens e conteúdos de apoio',pt:'Português',en:'Inglês',
|
||||
};
|
||||
export function documentFacetLabel(value:string):string{return names[value]??value;}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { modeloAFields, modeloAReference } from './iva-modelo-a.ts';
|
||||
|
||||
export type FiscalFormKind = 'iva' | 'irpc';
|
||||
export const fiscalFormVersion = 'investmoz-fiscal-preparation/1';
|
||||
export const fiscalForms = {
|
||||
iva: { title: 'IVA — Modelo A', source: modeloAReference.file, hash: modeloAReference.sha256, coverage: 'Campos 01–27 do exemplar, para preenchimento manual. A edição e as divergências já documentadas continuam identificadas.' },
|
||||
irpc: { title: 'IRPC — Modelo 22', source: 'IRPC M-22- DECLARACAO DE RENDIMENTOS.pdf', hash: '4b61bd83d1fbcfd3b7b5c5523cea5923f7d0f65dc4c004eff58e5db38f763c88', coverage: 'Preparação parcial: resultado, lucro, matéria colectável e liquidação nos campos abaixo. Os restantes ajustamentos e anexos do exemplar não são preenchidos aqui. L8 permanece parcial.' },
|
||||
} as const;
|
||||
const irpcFields = [
|
||||
['200', 'Resultado do exercício'], ['259', 'Prejuízo fiscal'], ['260', 'Lucro tributável'],
|
||||
['269', 'Prejuízo fiscal — regime geral'], ['270', 'Lucro tributável — regime geral'],
|
||||
['276', 'Prejuízos fiscais deduzidos'], ['277', 'Benefícios fiscais a deduzir'], ['278', 'Matéria colectável — regime geral'],
|
||||
['300', 'Imposto à taxa normal'], ['301', 'Imposto à taxa reduzida'], ['302', 'Colecta total'],
|
||||
['303', 'Dupla tributação económica'], ['304', 'Dupla tributação internacional'], ['305', 'Benefícios fiscais'],
|
||||
['306', 'Pagamento especial por conta'], ['308', 'Total das deduções'], ['309', 'IRPC liquidado'],
|
||||
['310', 'Retenções na fonte'], ['311', 'Pagamentos por conta'], ['312', 'IRPC a pagar antes de juros'],
|
||||
['313', 'IRPC a recuperar antes de juros'], ['314', 'Juros compensatórios'], ['315', 'IRPC a pagar'], ['316', 'IRPC a recuperar'],
|
||||
] as const;
|
||||
export function fiscalFormFields(kind: FiscalFormKind) {
|
||||
return kind === 'iva'
|
||||
? modeloAFields.map(f => ({ code: f.field, label: f.purpose, guidance: f.basis }))
|
||||
: irpcFields.map(([code, label]) => ({ code, label, guidance: Number(code) < 269 ? 'Quadro 10 do exemplar.' : Number(code) < 300 ? 'Quadro 11, regime geral. Outros regimes não incluídos nesta preparação.' : 'Quadro 12 do exemplar. Preenchimento manual, sem cálculo ou validação automática da liquidação.' }));
|
||||
}
|
||||
export type FiscalPreparation = {
|
||||
version: typeof fiscalFormVersion;
|
||||
kind: FiscalFormKind;
|
||||
sourceHash: string;
|
||||
name: string;
|
||||
nuit: string;
|
||||
period: string;
|
||||
notes: string;
|
||||
values: Record<string, string>;
|
||||
};
|
||||
export function newFiscalPreparation(kind: FiscalFormKind): FiscalPreparation {
|
||||
return { version: fiscalFormVersion, kind, sourceHash: fiscalForms[kind].hash, name: '', nuit: '', period: '', notes: '', values: {} };
|
||||
}
|
||||
export function readFiscalPreparation(raw: string): FiscalPreparation {
|
||||
if (raw.length > 100_000) throw new Error('O ficheiro excede o tamanho de uma preparação.');
|
||||
let p: unknown;
|
||||
try { p = JSON.parse(raw); } catch { throw new Error('Não foi possível ler este ficheiro de preparação. Os campos actuais foram preservados.'); }
|
||||
if (!p || typeof p !== 'object' || Array.isArray(p)) throw new Error('Ficheiro de preparação inválido.');
|
||||
const v = p as Record<string, unknown>;
|
||||
if (v.version !== fiscalFormVersion || (v.kind !== 'iva' && v.kind !== 'irpc') || v.sourceHash !== fiscalForms[v.kind].hash) throw new Error('Versão ou exemplar diferente. A preparação actual foi preservada.');
|
||||
for (const key of ['name', 'nuit', 'period', 'notes']) {
|
||||
if (typeof v[key] !== 'string' || v[key].length > 5000) throw new Error('Identificação ou notas inválidas.');
|
||||
}
|
||||
if (!v.values || typeof v.values !== 'object' || Array.isArray(v.values)) throw new Error('Campos inválidos.');
|
||||
const allowed = new Set(fiscalFormFields(v.kind).map(f => f.code));
|
||||
const values: Record<string, string> = {};
|
||||
for (const [code, value] of Object.entries(v.values)) {
|
||||
if (!allowed.has(code) || typeof value !== 'string' || value.length > 100) throw new Error('Campo não reconhecido. A preparação actual foi preservada.');
|
||||
values[code] = value;
|
||||
}
|
||||
return { ...newFiscalPreparation(v.kind), name: v.name as string, nuit: v.nuit as string, period: v.period as string, notes: v.notes as string, values };
|
||||
}
|
||||
export function fiscalPreparationIssues(p: FiscalPreparation): string[] {
|
||||
const issues: string[] = [];
|
||||
if (!p.name.trim()) issues.push('Indique o nome ou designação social.');
|
||||
if (!/^\d{9}$/.test(p.nuit)) issues.push('Indique o NUIT com 9 algarismos.');
|
||||
if (!(p.kind === 'iva' ? /^\d{4}-(0[1-9]|1[0-2])$/ : /^\d{4}$/).test(p.period)) issues.push(p.kind === 'iva' ? 'Indique ano e mês do período.' : 'Indique o ano do exercício.');
|
||||
for (const f of fiscalFormFields(p.kind)) {
|
||||
const value = p.values[f.code] ?? '';
|
||||
if (value !== '' && !/^-?\d{1,24}(?:[.,]\d{1,2})?$/.test(value)) issues.push(`Campo ${f.code}: use um montante sem separador de milhares, com até duas casas decimais.`);
|
||||
}
|
||||
return issues;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
export type FiscalProofParcel = {parcel?: string; parcelReference?: string};
|
||||
export const canonicalParcel = (s: string) => s.normalize('NFKC').trim().toLocaleLowerCase('pt').replace(/\s+/g, ' ');
|
||||
export function validateProofParcel(r: FiscalProofParcel) {
|
||||
if (r.parcel !== undefined && typeof r.parcel !== 'string' || r.parcelReference !== undefined && typeof r.parcelReference !== 'string') throw Error('Identificação da parcela documental não recuperável; original conservado.');
|
||||
}
|
||||
export function requireProofParcel(r: FiscalProofParcel) {
|
||||
validateProofParcel(r);
|
||||
if (!!r.parcel?.trim() !== !!r.parcelReference?.trim()) throw Error('Parcela documental e suporte devem corresponder; não se presume que linhas distintas representam impostos diferentes.');
|
||||
}
|
||||
export const parcelProjection = (r: FiscalProofParcel): FiscalProofParcel => ({...(r.parcel === undefined ? {} : {parcel: r.parcel}), ...(r.parcelReference === undefined ? {} : {parcelReference: r.parcelReference})});
|
||||
// Old proofs without a parcel cover the physical document. They overlap any newly identified parcel until reconciled.
|
||||
export const overlappingProofParcels = (a: FiscalProofParcel & {identity: string}, b: FiscalProofParcel & {identity: string}) => a.identity === b.identity && (!a.parcel?.trim() || !b.parcel?.trim() || canonicalParcel(a.parcel) === canonicalParcel(b.parcel));
|
||||
@@ -1,3 +1,6 @@
|
||||
import {carryPlan,carryIdentity,carrySource,newCreditCarry,validateCreditCarry,type CreditCarry} from './irpc-credit-carry.ts';
|
||||
import {economicTaxProof,economicGroupPending,economicDistributionIdentity,economicPosition,economicDeduction,economicSource,newEconomicCredits,validateEconomic,type EconomicCredits} from './irpc-economic-credit.ts';
|
||||
import {validateProofParcel,requireProofParcel,parcelProjection,overlappingProofParcels,type FiscalProofParcel} from './fiscal-proof-parcel.ts';
|
||||
import {validateInternational,internationalProofValue,internationalGroupPending,internationalPosition,internationalDeduction,internationalCreditSource,newInternationalCredits,type InternationalCredits,type InternationalTaxProof} from './irpc-international-credit.ts';
|
||||
import {validatePec,pecPaymentValue,pecDeduction,pecSource,type PecPayments} from './irpc-pec.ts';
|
||||
import {normalBook,normalCurrent} from './irpc-normal.ts';
|
||||
@@ -11,14 +14,21 @@ export const annualSettlementSource='CIRPC, arts. 63 e 67 (Lei 34/2007 e naturez
|
||||
type State=''|'known'|'absent';
|
||||
type Evidence={state:State;amount:string;reference:string};
|
||||
type Group={state:State;reference:string};
|
||||
export type AnnualWithholding={id:string;rowId:string;paymentId:string;sourceKey:string;subjectNuit:string;year:string;amount:string;incomeIncluded:''|'yes'|'no';reference:string};
|
||||
export type AnnualPpc={id:string;document:string;issuer:string;date:string;subjectNuit:string;year:string;currency:string;proofAmount:string;amount:string;effective:''|'yes'|'no';reference:string};
|
||||
export type AnnualWithholding=FiscalProofParcel&{id:string;rowId:string;paymentId:string;sourceKey:string;subjectNuit:string;year:string;amount:string;incomeIncluded:''|'yes'|'no';reference:string};
|
||||
export type AnnualPpc=FiscalProofParcel&{id:string;document:string;issuer:string;date:string;subjectNuit:string;year:string;currency:string;proofAmount:string;amount:string;effective:''|'yes'|'no';reference:string};
|
||||
type AnnualRecord={version:typeof annualSettlementVersion;key:string;createdAt:string;model:AnnualModel};
|
||||
export type AnnualBook={version:1;subjectNuit:string;year:string;reference:string;assessment:''|'normal'|'special';assessmentKey:string;assessmentReference:string;withholdings:Group&{rows:AnnualWithholding[]};ppc:Group&{rows:AnnualPpc[]};pec:Evidence;pecPayments?:PecPayments;credits:Evidence;internationalCredits?:InternationalCredits;result?:AnnualRecord;history:AnnualRecord[]};
|
||||
export type AnnualBook={version:1;subjectNuit:string;year:string;reference:string;assessment:''|'normal'|'special';assessmentKey:string;assessmentReference:string;withholdings:Group&{rows:AnnualWithholding[]};ppc:Group&{rows:AnnualPpc[]};pec:Evidence;pecPayments?:PecPayments;credits:Evidence;internationalCredits?:InternationalCredits;creditCarry?:CreditCarry;economicCredits?:EconomicCredits;result?:AnnualRecord;history:AnnualRecord[]};
|
||||
export const annualSource=(b:AnnualBook)=>{
|
||||
const excluded=b.internationalCredits?(b.pecPayments?'Créditos económicos/benefícios positivos':'PEC/créditos económicos/benefícios positivos'):(b.pecPayments?'Créditos próprios positivos':'PEC/créditos positivos');
|
||||
return annualSettlementSource.replace('PEC/créditos positivos',excluded)+(b.pecPayments?' '+pecSource:'')+(b.internationalCredits?' '+internationalCreditSource:'');
|
||||
return annualSettlementSource.replace('PEC/créditos positivos',b.economicCredits?(b.pecPayments?'Benefícios positivos':'PEC/benefícios positivos'):excluded)+(b.pecPayments?' '+pecSource:'')+(b.internationalCredits?' '+internationalCreditSource:'')+(b.creditCarry?' '+carrySource:'')+(b.economicCredits?' '+economicSource:'');
|
||||
};
|
||||
export function prepareEconomicBook(b:AnnualBook):AnnualBook{
|
||||
if(b.economicCredits)return b;
|
||||
const next=prepareInternationalBook(b),e=newEconomicCredits(),old=next.internationalCredits!.economic;
|
||||
if(old.state==='absent'){e.state='absent';e.reference=old.reference;}
|
||||
return{...next,economicCredits:e};
|
||||
}
|
||||
export function prepareCreditCarry(b:AnnualBook):AnnualBook{return b.creditCarry?b:{...b,creditCarry:newCreditCarry()};}
|
||||
export function prepareInternationalBook(b:AnnualBook):AnnualBook{
|
||||
if(b.internationalCredits)return b;
|
||||
const c=newInternationalCredits(),old=b.credits;
|
||||
@@ -41,6 +51,8 @@ const proofIdentity=(issuer:string,document:string,_date:string)=>JSON.stringify
|
||||
function store(d:Record<string,unknown>){const s=JSON.parse(String(d.modelo_a_snapshot||'{"version":1,"books":{}}'));if(s.version!==1||!s.books||typeof s.books!=='object'||Array.isArray(s.books))throw Error('Livros fiscais não recuperáveis;originais conservados.');return s;}
|
||||
function books(d:Record<string,unknown>):Record<string,AnnualBook>{const m=store(d).irpcAnnual;if(m===undefined)return{};if(!m||typeof m!=='object'||Array.isArray(m))throw Error('MapaL8 não recuperável;originais conservados.');return m;}
|
||||
export function validateAnnual(b:AnnualBook){
|
||||
if(b?.economicCredits!==undefined)validateEconomic(b.economicCredits);
|
||||
if(b?.creditCarry!==undefined)validateCreditCarry(b.creditCarry);
|
||||
if(b?.pecPayments!==undefined)validatePec(b.pecPayments);
|
||||
if(b?.internationalCredits!==undefined)validateInternational(b.internationalCredits);
|
||||
if(!b||b.version!==1||['subjectNuit','year','reference','assessmentKey','assessmentReference'].some(k=>typeof b[k as 'year']!=='string')||!['','normal','special'].includes(b.assessment)||!Array.isArray(b.history))throw Error('PreparaçãoL8 não recuperável.');
|
||||
@@ -48,6 +60,7 @@ export function validateAnnual(b:AnnualBook){
|
||||
for(const g of[b.pec,b.credits])if(typeof g.amount!=='string')throw Error('CréditoL8 não recuperável.');
|
||||
const w=['id','rowId','paymentId','sourceKey','subjectNuit','year','amount','incomeIncluded','reference'],p=Object.keys(newAnnualPpc(''));
|
||||
for(const[rows,keys]of[[b.withholdings.rows,w],[b.ppc.rows,p]]as const)if(!Array.isArray(rows)||new Set(rows.map(r=>r?.id)).size!==rows.length||rows.some(r=>!r||keys.some(k=>typeof(r as unknown as Record<string,unknown>)[k]!=='string')))throw Error('ComprovativosL8 não recuperáveis ou identificador repetido.');
|
||||
for(const r of[...b.withholdings.rows,...b.ppc.rows])validateProofParcel(r);
|
||||
if(b.withholdings.rows.some(r=>!['','yes','no'].includes(r.incomeIncluded))||b.ppc.rows.some(r=>!['','yes','no'].includes(r.effective)))throw Error('QualificaçãoL8 não recuperável.');
|
||||
for(const r of[b.result,...b.history])if(r&&(r.version!==annualSettlementVersion||typeof r.key!=='string'||typeof r.createdAt!=='string'||!r.model||!Array.isArray(r.model.pending)))throw Error('HistóricoL8 não recuperável.');
|
||||
}
|
||||
@@ -72,7 +85,7 @@ export function reuseAnnualWithholding(d:Record<string,unknown>,b:AnnualBook,row
|
||||
if(b.withholdings.rows.some(r=>r.rowId===rowId&&r.paymentId===paymentId))throw Error('Retenção/prova já seleccionada;altere a parcela existente sem duplicar.');
|
||||
return{...b,withholdings:{...b.withholdings,rows:[...b.withholdings.rows,{id,rowId,paymentId,sourceKey:o.key,subjectNuit:b.subjectNuit,year:o.year,amount:o.amount,incomeIncluded:'',reference:''}]}};
|
||||
}
|
||||
function dependencies(d:Record<string,unknown>){let normal:unknown,L5:unknown;try{const a=annualAssessment(d);normal=[a.record,a.current];}catch(e){normal=String(e);}try{const b=irpcBook(d);L5=[b.rows,b.payments,b.result,irpcCurrent(d,b)];}catch(e){L5=String(e);}return[normal,L5,Object.entries(books(d)).filter(([k])=>k!==acquisitionScope(d)).map(([k,b])=>[k,b.subjectNuit,b.year,b.withholdings,b.ppc,...(b.pecPayments?[b.pecPayments]:[]),...(b.internationalCredits?[b.internationalCredits]:[])])];}
|
||||
function dependencies(d:Record<string,unknown>){let normal:unknown,L5:unknown;try{const a=annualAssessment(d);normal=[a.record,a.current];}catch(e){normal=String(e);}try{const b=irpcBook(d);L5=[b.rows,b.payments,b.result,irpcCurrent(d,b)];}catch(e){L5=String(e);}return[normal,L5,Object.entries(books(d)).filter(([k])=>k!==acquisitionScope(d)).map(([k,b])=>[k,b.subjectNuit,b.year,b.withholdings,b.ppc,...(b.pecPayments?[b.pecPayments]:[]),...(b.internationalCredits?[b.internationalCredits]:[]),...(b.creditCarry?[b.creditCarry]:[]),...(b.economicCredits?[b.economicCredits]:[])])];}
|
||||
function key(d:Record<string,unknown>,b:AnnualBook){const{result:_,history:__,...input}=b;return closureFingerprint([annualSettlementVersion,acquisitionScope(d),input,dependencies(d)]);}
|
||||
export function annualCurrent(d:Record<string,unknown>,b:AnnualBook){return !!b.result&&b.result.key===key(d,b);}
|
||||
export function calculateAnnual(d:Record<string,unknown>,b:AnnualBook){
|
||||
@@ -89,43 +102,74 @@ export function calculateAnnual(d:Record<string,unknown>,b:AnnualBook){
|
||||
group(b.withholdings,b.withholdings.rows,'Retenções sofridas por conta');group(b.ppc,b.ppc.rows,'PPC efectuados');
|
||||
try{if(b.withholdings.state==='absent'&&options.some(o=>o.ready&&o.year===b.year&&cmp(moneyInput(o.amount),zero())>0n))pending.push('Ausência de retenções sofridas contradiz provaL5 efectiva por conta no exercício;reconcilie sem a ignorar.');}catch(e){pending.push('Reconciliação da ausência de retenções: '+String(e));}
|
||||
for(const[label,e]of[...(b.pecPayments?[]:[['PEC',b.pec]as const]),...(b.internationalCredits?[]:[['Créditos com regras próprias',b.credits]as const])]){try{if(!e.state||!e.reference.trim())throw Error('presença/ausência e suporte em falta');if(e.state==='absent'){if(e.amount.trim())throw Error('ausência contradiz montante preenchido');}else if(cmp(moneyInput(e.amount),zero())!==0n)throw Error('montante positivo fora deste recorte:corresponder ordem,limite e transporte próprios;sem abatimento ou reembolso automático');}catch(err){pending.push(label+': '+String(err));}}
|
||||
const claims:Array<{id:string;kind:'withholding'|'ppc'|'pec'|'foreign_credit';country?:string;positionId?:string;previouslyUsed?:FiscalFraction;identity:string;proofAmount:FiscalFraction|null;value:FiscalFraction|null;sourceKey:string;allocationAmount:FiscalFraction|null;document:string;issuer:string;date:string;subjectNuit:string;year:string;reason:string}>=[];
|
||||
const claims:Array<FiscalProofParcel&{id:string;kind:'withholding'|'ppc'|'pec'|'foreign_credit'|'economic_credit';country?:string;positionId?:string;previouslyUsed?:FiscalFraction;identity:string;proofAmount:FiscalFraction|null;value:FiscalFraction|null;sourceKey:string;allocationAmount:FiscalFraction|null;document:string;issuer:string;date:string;subjectNuit:string;year:string;reason:string}>=[];
|
||||
for(const r of b.withholdings.rows){const o=options.find(o=>o.rowId===r.rowId&&o.paymentId===r.paymentId),issues:string[]=[];let value:FiscalFraction|null=null,proofAmount:FiscalFraction|null=null;
|
||||
try{if(!o||!o.ready||r.sourceKey!==o.key)throw Error(o?.reason||'provaL5 ausente ou alterada;reutilize sem duplicar');if(r.subjectNuit!==b.subjectNuit||r.year!==b.year||o.year!==b.year||!o.date.startsWith(b.year+'-'))throw Error('entidade/exercício da retenção não correspondem ao fecho');if(r.incomeIncluded!=='yes'||!r.reference.trim())throw Error('confirme o próprio beneficiário/NUIT e inclusão do rendimento na base do exercício com suporte');value=moneyInput(r.amount);proofAmount=moneyInput(o.proofAmount);if(cmp(value,moneyInput(o.amount))>0n)throw Error('parcela ultrapassa a retenção efectivamente comprovada e afectada emL5');if(b.withholdings.rows.filter(x=>x.rowId===r.rowId&&x.paymentId===r.paymentId).length!==1)throw Error('retenção/prova repetida;uma afectação por linhaL5');if(assessment?.record?.model.special?.cooperative.status==='calculated'&&cmp(value,zero())>0n)throw Error('cooperativa integralmente elegível declara ausência de rendimentos retidos;segregue o casoL7 antes do crédito anual');}catch(e){issues.push(String(e));value=null;}
|
||||
claims.push({id:r.id,kind:'withholding',identity:o?.identity??'',proofAmount,value,sourceKey:r.sourceKey,allocationAmount:o&&value?moneyInput(o.amount):null,document:o?.document??r.paymentId,issuer:o?.issuer??'',date:o?.date??'',subjectNuit:r.subjectNuit,year:r.year,reason:issues.join(' ')});
|
||||
try{requireProofParcel(r);if(!o||!o.ready||r.sourceKey!==o.key)throw Error(o?.reason||'provaL5 ausente ou alterada;reutilize sem duplicar');if(r.subjectNuit!==b.subjectNuit||r.year!==b.year||o.year!==b.year||!o.date.startsWith(b.year+'-'))throw Error('entidade/exercício da retenção não correspondem ao fecho');if(r.incomeIncluded!=='yes'||!r.reference.trim())throw Error('confirme o próprio beneficiário/NUIT e inclusão do rendimento na base do exercício com suporte');value=moneyInput(r.amount);proofAmount=moneyInput(o.proofAmount);if(cmp(value,moneyInput(o.amount))>0n)throw Error('parcela ultrapassa a retenção efectivamente comprovada e afectada emL5');if(b.withholdings.rows.filter(x=>x.rowId===r.rowId&&x.paymentId===r.paymentId).length!==1)throw Error('retenção/prova repetida;uma afectação por linhaL5');if(assessment?.record?.model.special?.cooperative.status==='calculated'&&cmp(value,zero())>0n)throw Error('cooperativa integralmente elegível declara ausência de rendimentos retidos;segregue o casoL7 antes do crédito anual');}catch(e){issues.push(String(e));value=null;}
|
||||
claims.push({...parcelProjection(r),id:r.id,kind:'withholding',identity:o?.identity??'',proofAmount,value,sourceKey:r.sourceKey,allocationAmount:o&&value?moneyInput(o.amount):null,document:o?.document??r.paymentId,issuer:o?.issuer??'',date:o?.date??'',subjectNuit:r.subjectNuit,year:r.year,reason:issues.join(' ')});
|
||||
}
|
||||
for(const r of b.ppc.rows){const issues:string[]=[];let value:FiscalFraction|null=null,proofAmount:FiscalFraction|null=null;
|
||||
try{if(!r.document.trim()||!r.issuer.trim()||!r.reference.trim()||r.effective!=='yes'||r.currency!=='MZN'||!iso(r.date)||!r.date.startsWith(b.year+'-')||r.subjectNuit!==b.subjectNuit||r.year!==b.year)throw Error('PPC exige comprovativo efectivo,MZN,data,entidade e exercício correspondentes;projecção/tesouraria não é pagamento');value=moneyInput(r.amount);proofAmount=moneyInput(r.proofAmount);if(cmp(value,proofAmount)>0n)throw Error('parcelaPPC ultrapassa o montante comprovado');}catch(e){issues.push(String(e));value=null;}
|
||||
claims.push({id:r.id,kind:'ppc',identity:proofIdentity(r.issuer,r.document,r.date),proofAmount,value,sourceKey:'',allocationAmount:null,document:r.document,issuer:r.issuer,date:r.date,subjectNuit:r.subjectNuit,year:r.year,reason:issues.join(' ')});
|
||||
try{requireProofParcel(r);if(!r.document.trim()||!r.issuer.trim()||!r.reference.trim()||r.effective!=='yes'||r.currency!=='MZN'||!iso(r.date)||!r.date.startsWith(b.year+'-')||r.subjectNuit!==b.subjectNuit||r.year!==b.year)throw Error('PPC exige comprovativo efectivo,MZN,data,entidade e exercício correspondentes;projecção/tesouraria não é pagamento');value=moneyInput(r.amount);proofAmount=moneyInput(r.proofAmount);if(cmp(value,proofAmount)>0n)throw Error('parcelaPPC ultrapassa o montante comprovado');}catch(e){issues.push(String(e));value=null;}
|
||||
claims.push({...parcelProjection(r),id:r.id,kind:'ppc',identity:proofIdentity(r.issuer,r.document,r.date),proofAmount,value,sourceKey:'',allocationAmount:null,document:r.document,issuer:r.issuer,date:r.date,subjectNuit:r.subjectNuit,year:r.year,reason:issues.join(' ')});
|
||||
}
|
||||
if(b.pecPayments){group(b.pecPayments,b.pecPayments.rows,'PEC pagos no próprio exercício');for(const r of b.pecPayments.rows){let value:FiscalFraction|null=null,proofAmount:FiscalFraction|null=null,previouslyUsed:FiscalFraction|undefined;let reason='';try{({value,proofAmount,previouslyUsed}=pecPaymentValue(r,b.subjectNuit,b.year));}catch(e){reason=String(e);}claims.push({id:r.id,kind:'pec',identity:proofIdentity(r.issuer,r.document,r.date),value,proofAmount,previouslyUsed,sourceKey:'',allocationAmount:null,document:r.document,issuer:r.issuer,date:r.date,subjectNuit:r.subjectNuit,year:r.year,reason});}}
|
||||
if(b.pecPayments){group(b.pecPayments,b.pecPayments.rows,'PEC pagos no próprio exercício');for(const r of b.pecPayments.rows){let value:FiscalFraction|null=null,proofAmount:FiscalFraction|null=null,previouslyUsed:FiscalFraction|undefined;let reason='';try{({value,proofAmount,previouslyUsed}=pecPaymentValue(r,b.subjectNuit,b.year));}catch(e){reason=String(e);}claims.push({...parcelProjection(r),id:r.id,kind:'pec',identity:proofIdentity(r.issuer,r.document,r.date),value,proofAmount,previouslyUsed,sourceKey:'',allocationAmount:null,document:r.document,issuer:r.issuer,date:r.date,subjectNuit:r.subjectNuit,year:r.year,reason});}}
|
||||
if(b.internationalCredits){
|
||||
pending.push(...internationalGroupPending(b.internationalCredits));
|
||||
pending.push(...internationalGroupPending(b.internationalCredits,!!b.economicCredits));
|
||||
const countries=b.internationalCredits.positions.map(p=>p.country);
|
||||
if(new Set(countries).size!==countries.length)pending.push('Um país/exercício tem várias posições;consolide rendimentos e comprovativos sob uma única fracção nacional,sem repetir o limite.');
|
||||
for(const p of b.internationalCredits.positions)for(const r of p.payments){let value:FiscalFraction|null=null,proofAmount:FiscalFraction|null=null,reason='';try{({value,proofAmount}=internationalProofValue(r,b.subjectNuit,b.year));}catch(e){reason=String(e);}claims.push({id:r.id,kind:'foreign_credit',country:p.country,positionId:p.id,identity:proofIdentity(r.issuer,r.document,r.date),proofAmount,value,sourceKey:'',allocationAmount:null,document:r.document,issuer:r.issuer,date:r.date,subjectNuit:r.subjectNuit,year:r.year,reason});}
|
||||
for(const p of b.internationalCredits.positions)for(const r of p.payments){let value:FiscalFraction|null=null,proofAmount:FiscalFraction|null=null,reason='';try{({value,proofAmount}=internationalProofValue(r,b.subjectNuit,b.year));}catch(e){reason=String(e);}claims.push({...parcelProjection(r),id:r.id,kind:'foreign_credit',country:p.country,positionId:p.id,identity:proofIdentity(r.issuer,r.document,r.date),proofAmount,value,sourceKey:'',allocationAmount:null,document:r.document,issuer:r.issuer,date:r.date,subjectNuit:r.subjectNuit,year:r.year,reason});}
|
||||
}
|
||||
const elsewhere:Array<{identity:string;subjectNuit:string;year:string;value:FiscalFraction;proofAmount:FiscalFraction;sourceKey:string;kind:'ppc'|'pec'|'withholding'|'foreign_credit';country?:string;previouslyUsed?:FiscalFraction}>=[];
|
||||
for(const[scope,other]of Object.entries(books(d))){if(scope===acquisitionScope(d))continue;try{validateAnnual(other);for(const p of other.internationalCredits?.positions??[]){if(other.subjectNuit===b.subjectNuit&&other.year===b.year&&b.internationalCredits?.positions.some(x=>x.country===p.country))pending.push('País '+p.country+' já preparado noutro mapa da entidade/exercício;consolide a fracção nacional e usos sem duplicar quotas.');for(const r of p.payments){const v=internationalProofValue(r,other.subjectNuit,other.year);elsewhere.push({identity:proofIdentity(r.issuer,r.document,r.date),subjectNuit:r.subjectNuit,year:r.year,...v,sourceKey:'',kind:'foreign_credit',country:p.country});}}for(const r of other.pecPayments?.rows??[]){const p=pecPaymentValue(r,other.subjectNuit,other.year);elsewhere.push({identity:proofIdentity(r.issuer,r.document,r.date),subjectNuit:r.subjectNuit,year:r.year,...p,sourceKey:'',kind:'pec'});}for(const r of other.ppc.rows)elsewhere.push({identity:proofIdentity(r.issuer,r.document,r.date),subjectNuit:r.subjectNuit,year:r.year,value:moneyInput(r.amount),proofAmount:moneyInput(r.proofAmount),sourceKey:'',kind:'ppc'});for(const r of other.withholdings.rows){const source=(store(d).irpcWithholdings??{})[scope];const row=source?.rows?.find((x:{id:string})=>x.id===r.rowId),p=source?.payments?.find((x:{id:string})=>x.id===r.paymentId);if(row&&p)elsewhere.push({identity:proofIdentity(row.counterparty,p.reference,p.date),subjectNuit:r.subjectNuit,year:r.year,value:moneyInput(r.amount),proofAmount:moneyInput(p.amount),sourceKey:r.sourceKey,kind:'withholding'});}}catch(e){if(other?.subjectNuit===b.subjectNuit)pending.push('Outro mapa da mesma entidade não recuperável para conferir duplicações: '+scope+';'+String(e));}}
|
||||
for(const c of claims){if(!c.value||!c.proofAmount)continue;const same=claims.filter(x=>x.identity===c.identity&&x.value),other=elsewhere.filter(x=>x.identity===c.identity);let issue='';
|
||||
if(same.filter(x=>x.kind!=='withholding').length>1||new Set(same.map(x=>x.kind)).size>1)issue='Mesmo comprovativo repetido ou usado com naturezas diferentes (retenção/PPC/PEC/crédito internacional);reconcilie sem dedução dupla.';
|
||||
if(b.economicCredits){
|
||||
pending.push(...economicGroupPending(b.economicCredits));
|
||||
if(!b.internationalCredits)pending.push('Distinguir o detalhe económico do inventário internacional e dos benefícios; use a preparação existente sem apagar o resumo anterior.');
|
||||
for(const r of b.economicCredits.rows){let value:FiscalFraction|null=null,proofAmount:FiscalFraction|null=null,previouslyUsed:FiscalFraction|undefined,reason='';try{({value,proofAmount,previouslyUsed}=economicTaxProof(r));}catch(e){reason=String(e);}claims.push({id:r.id,kind:'economic_credit',positionId:r.id,identity:proofIdentity(r.taxIssuer,r.taxDocument,r.distributionDate),parcel:r.taxParcel,parcelReference:r.parcelReference,proofAmount,value,previouslyUsed,sourceKey:'',allocationAmount:null,document:r.taxDocument,issuer:r.taxIssuer,date:r.distributionDate,subjectNuit:r.subjectNuit,year:r.year,reason});}
|
||||
}
|
||||
const elsewhere:Array<FiscalProofParcel&{identity:string;subjectNuit:string;year:string;value:FiscalFraction;proofAmount:FiscalFraction;sourceKey:string;kind:'ppc'|'pec'|'withholding'|'foreign_credit'|'economic_credit';country?:string;previouslyUsed?:FiscalFraction}>=[];
|
||||
for(const[scope,other]of Object.entries(books(d))){if(scope===acquisitionScope(d))continue;try{validateAnnual(other);for(const r of other.economicCredits?.rows??[]){
|
||||
if(b.economicCredits?.rows.some(x=>economicDistributionIdentity(x)===economicDistributionIdentity(r)))pending.push('Parcela de lucros económicos já preparada noutro mapa;consolide sem duplicar o crédito, mesmo com documentos de imposto diferentes.');
|
||||
const v=economicTaxProof(r);elsewhere.push({identity:proofIdentity(r.taxIssuer,r.taxDocument,r.distributionDate),parcel:r.taxParcel,parcelReference:r.parcelReference,subjectNuit:r.subjectNuit,year:r.year,...v,sourceKey:'',kind:'economic_credit'});
|
||||
}for(const p of other.internationalCredits?.positions??[]){if(other.subjectNuit===b.subjectNuit&&other.year===b.year&&b.internationalCredits?.positions.some(x=>x.country===p.country))pending.push('País '+p.country+' já preparado noutro mapa da entidade/exercício;consolide a fracção nacional e usos sem duplicar quotas.');for(const r of p.payments){const v=internationalProofValue(r,other.subjectNuit,other.year);elsewhere.push({...parcelProjection(r),identity:proofIdentity(r.issuer,r.document,r.date),subjectNuit:r.subjectNuit,year:r.year,...v,sourceKey:'',kind:'foreign_credit',country:p.country});}}for(const r of other.pecPayments?.rows??[]){const p=pecPaymentValue(r,other.subjectNuit,other.year);elsewhere.push({...parcelProjection(r),identity:proofIdentity(r.issuer,r.document,r.date),subjectNuit:r.subjectNuit,year:r.year,...p,sourceKey:'',kind:'pec'});}for(const r of other.ppc.rows)elsewhere.push({...parcelProjection(r),identity:proofIdentity(r.issuer,r.document,r.date),subjectNuit:r.subjectNuit,year:r.year,value:moneyInput(r.amount),proofAmount:moneyInput(r.proofAmount),sourceKey:'',kind:'ppc'});for(const r of other.withholdings.rows){const source=(store(d).irpcWithholdings??{})[scope];const row=source?.rows?.find((x:{id:string})=>x.id===r.rowId),p=source?.payments?.find((x:{id:string})=>x.id===r.paymentId);if(row&&p)elsewhere.push({...parcelProjection(r),identity:proofIdentity(row.counterparty,p.reference,p.date),subjectNuit:r.subjectNuit,year:r.year,value:moneyInput(r.amount),proofAmount:moneyInput(p.amount),sourceKey:r.sourceKey,kind:'withholding'});}}catch(e){if(other?.subjectNuit===b.subjectNuit)pending.push('Outro mapa da mesma entidade não recuperável para conferir duplicações: '+scope+';'+String(e));}}
|
||||
for(const c of claims){if(!c.value||!c.proofAmount)continue;const same=claims.filter(x=>overlappingProofParcels(x,c)&&x.value),other=elsewhere.filter(x=>overlappingProofParcels(x,c));let issue='';
|
||||
if(same.filter(x=>x.kind!=='withholding').length>1&&!same.every(x=>x.kind==='economic_credit')||new Set(same.map(x=>x.kind)).size>1)issue='Mesmo comprovativo repetido ou usado com naturezas diferentes (retenção/PPC/PEC/crédito internacional);reconcilie sem dedução dupla.';
|
||||
if(other.some(x=>x.subjectNuit!==b.subjectNuit||x.year!==b.year))issue='Mesmo comprovativo já associado a outra entidade/exercício;reconcilie a titularidade e a afectação.';
|
||||
if([...same,...other].some(x=>x.proofAmount&&cmp(x.proofAmount,c.proofAmount!)!==0n)||cmp(addFractions([...same.flatMap(x=>x.value?[x.value]:[]),...other.map(x=>x.value)]),c.proofAmount)>0n)issue='Comprovativo utilizado além do montante disponível ou com montantes divergentes neste/outro mapa.';
|
||||
if(c.kind==='pec'&&c.previouslyUsed){if(other.some(x=>x.kind!=='pec')||other.some(x=>!x.previouslyUsed||cmp(x.previouslyUsed,c.previouslyUsed!)!==0n)||cmp(addFractions([c.previouslyUsed,...same.flatMap(x=>x.value?[x.value]:[]),...other.map(x=>x.value)]),c.proofAmount)>0n)issue='PEC com utilização anterior divergente, natureza incompatível ou parcelas acima do saldo disponível.';}
|
||||
if((c.kind==='pec'||c.kind==='economic_credit')&&c.previouslyUsed){if(other.some(x=>x.kind!==c.kind)||[...same,...other].some(x=>!x.previouslyUsed||cmp(x.previouslyUsed,c.previouslyUsed!)!==0n)||cmp(addFractions([c.previouslyUsed,...same.flatMap(x=>x.value?[x.value]:[]),...other.map(x=>x.value)]),c.proofAmount)>0n)issue='PEC/IRPC económico com utilização/atribuição anterior divergente, natureza incompatível ou parcelas acima do saldo disponível.';}
|
||||
if(other.some(x=>x.kind!==c.kind))issue='Comprovativo já afectado a outra natureza (retenção/PPC/PEC/crédito internacional);sem dupla dedução.';
|
||||
if(c.kind==='foreign_credit'&&other.some(x=>x.country!==c.country))issue='Comprovativo estrangeiro associado a outro país/natureza;reconcilie sem duplicação.';
|
||||
if(c.kind==='withholding'&&c.sourceKey&&c.allocationAmount&&cmp(addFractions([...same.filter(x=>x.sourceKey===c.sourceKey).flatMap(x=>x.value?[x.value]:[]),...other.filter(x=>x.sourceKey===c.sourceKey).map(x=>x.value)]),c.allocationAmount)>0n)issue='Mesma afectação L5 reutilizada além da parcela disponível, ainda que o comprovativo global seja maior.';
|
||||
if(c.kind==='withholding'&&c.sourceKey&&c.allocationAmount&&cmp(addFractions([...claims.filter(x=>x.kind==='withholding'&&x.sourceKey===c.sourceKey).flatMap(x=>x.value?[x.value]:[]),...elsewhere.filter(x=>x.kind==='withholding'&&x.sourceKey===c.sourceKey).map(x=>x.value)]),c.allocationAmount)>0n)issue='Mesma afectação L5 reutilizada além da parcela disponível, ainda que o comprovativo global seja maior.';
|
||||
if(issue)c.reason=[c.reason,issue].filter(Boolean).join(' ');
|
||||
}
|
||||
for(const c of claims)if(c.reason)pending.push((c.document||c.id)+': '+c.reason);
|
||||
const knownWithholdings=addFractions(claims.filter(c=>c.kind==='withholding'&&!c.reason&&c.value).map(c=>c.value!)),knownPpc=addFractions(claims.filter(c=>c.kind==='ppc'&&!c.reason&&c.value).map(c=>c.value!));
|
||||
const positions=b.internationalCredits?.positions.map(p=>{const own=claims.filter(c=>c.kind==='foreign_credit'&&c.positionId===p.id);const m=internationalPosition(p,addFractions(own.filter(c=>!c.reason&&c.value).map(c=>c.value!)),own.filter(c=>c.reason).map(c=>c.reason),b.subjectNuit,b.year,b.assessmentKey);pending.push(...m.pending.map(e=>'País '+p.country+': '+e));return m;})??[];
|
||||
const ready=pending.length===0&&colecta!==null,international=b.internationalCredits?internationalDeduction(positions,colecta,ready):null,creditCollecta=international?.afterCredit??colecta;
|
||||
const pec=b.pecPayments?pecDeduction(addFractions(claims.filter(c=>c.kind==='pec'&&!c.reason&&c.value).map(c=>c.value!)),creditCollecta,ready):null,arithmeticBalance=ready?subtractFractions(subtractFractions(pec?.afterPec??creditCollecta!,knownWithholdings),knownPpc):null;
|
||||
const economicRows=b.economicCredits?.rows.map(r=>{
|
||||
const issues=claims.filter(c=>c.kind==='economic_credit'&&c.positionId===r.id&&c.reason).map(c=>c.reason);
|
||||
const m=economicPosition(r,b.subjectNuit,b.year,b.assessmentKey,colecta,issues);
|
||||
pending.push(...m.pending.map(e=>'Lucros '+r.distributionDocument+': '+e));return m;
|
||||
})??[];
|
||||
if(b.economicCredits){
|
||||
if(b.economicCredits.rows.length&&assessment?.kind!=='normal')pending.push('Crédito económico delimitado à colecta normal corrente;efeitos L7 exigem correspondência própria.');
|
||||
}
|
||||
const economicPreview=b.economicCredits?economicDeduction(economicRows,colecta,true):null;
|
||||
const remainingForCarry=economicPreview?.afterCredit??colecta;
|
||||
const pecAvailable=addFractions(claims.filter(c=>c.kind==='pec'&&!c.reason&&c.value).map(c=>c.value!));
|
||||
const carryDuplicates:string[]=[];
|
||||
if(b.creditCarry)for(const[scope,other]of Object.entries(books(d))){
|
||||
if(scope===acquisitionScope(d)||other.subjectNuit!==b.subjectNuit)continue;
|
||||
try{validateAnnual(other);if(other.creditCarry?.lots.some(r=>b.creditCarry!.lots.some(x=>carryIdentity(x)===carryIdentity(r))))carryDuplicates.push('Saldo anterior já preparado noutro mapa da entidade;consolide a origem e usos sem duplicar: '+scope);}
|
||||
catch(e){carryDuplicates.push('Outro mapa da entidade não recuperável para conferir saldos anteriores: '+scope+';'+String(e));}
|
||||
}
|
||||
const carry=b.creditCarry?carryPlan(b.creditCarry,b.subjectNuit,b.year,b.assessmentKey,addFractions(positions.flatMap(p=>p.available&&!p.pending.length?[p.available]:[])),pecAvailable,remainingForCarry,carryDuplicates):null;
|
||||
if(carry)pending.push(...carry.pending);
|
||||
const ready=pending.length===0&&colecta!==null,economic=b.economicCredits?economicDeduction(economicRows,colecta,ready):null,afterEconomic=economic?.afterCredit??colecta;
|
||||
const international=b.internationalCredits?internationalDeduction(positions,afterEconomic,ready,carry?.international??undefined):null;
|
||||
const creditCollecta=ready&&carry?subtractFractions(international?.afterCredit??afterEconomic!,carry.priorInternational):international?.afterCredit??afterEconomic;
|
||||
const pec=b.pecPayments?pecDeduction(pecAvailable,creditCollecta,ready,carry?.pec??undefined):null;
|
||||
const afterPec=ready&&carry?subtractFractions(pec?.afterPec??creditCollecta!,carry.priorPec):pec?.afterPec??creditCollecta;
|
||||
const arithmeticBalance=ready?subtractFractions(subtractFractions(afterPec!,knownWithholdings),knownPpc):null;
|
||||
if(international&&international.insufficientCollecta&&cmp(international.insufficientCollecta,zero())>0n)warn.push('Crédito elegível sem colecta suficiente:sem reembolso,transporte ou escolha automática da afectação por país.');
|
||||
let payable:FiscalFraction|null=null,recoverable:FiscalFraction|null=null,belowMinimum:FiscalFraction|null=null;let status:'payable'|'recoverable'|'balanced'|'below_minimum'|'indeterminate'='indeterminate';
|
||||
if(arithmeticBalance){const n=BigInt(arithmeticBalance.numerator),abs=fraction(n<0n?-n:n,BigInt(arithmeticBalance.denominator));payable=zero();recoverable=zero();belowMinimum=zero();if(!n)status='balanced';else if(cmp(abs,fraction(100n))<0n){status='below_minimum';belowMinimum=abs;warn.push('Art27(6):saldo inferior a100MZN,sem cobrança/reembolso neste recorte;aritmética conservada,não é transporte de crédito.');}else if(n>0n){status='payable';payable=abs;}else{status='recoverable';recoverable=abs;}}
|
||||
return{version:annualSettlementVersion,input:structuredClone(input),subjectNuit:b.subjectNuit,year:b.year,assessment:assessment?.record?{key:b.assessmentKey,kind:b.assessment,version:assessment.record.model.version,createdAt:assessment.record.createdAt,colecta,period:assessment.period,origin:assessment.record.model.origin}:null,claims,internationalCredit:international,pecDeduction:pec,knownWithholdings,knownPpc,arithmeticBalance,payable,recoverable,belowMinimum,status,pending:[...new Set(pending)],warnings:warn,source:annualSource(b),officialBalancesConsumed:false,submitted:false,refundReceived:false,limitations:[...(b.internationalCredits?['Crédito internacional do próprio exercício:fracção nacional,convenção e montantes MZN são documentados;sem cálculo presumido,transporte ou consumo oficial. Créditos económicos/benefícios positivos ficam separados.']:[]),b.internationalCredits?'L8 parcial:créditos económicos/benefícios positivos,transporte/caducidade,obrigações,tributação autónoma,períodos especiais e outras moedas separados. PEC sem reembolso ou transporte automático.':(b.pecPayments?'L8 parcial:transporte/caducidade de PEC, cálculo da obrigação, créditos próprios positivos, tributação autónoma, períodos especiais e outras moedas separados. Excedente PEC não é reembolso nem saldo transportado oficialmente.':'L8 parcial:PEC e créditos positivos,tributação autónoma,períodos especiais e pagamentos noutra moeda exigem regras próprias.'),'PPC aqui é pagamento comprovado;não cálculo automático da obrigação ou calendário.','Retenção sofrida não é retenção entregue pela empresa por conta de terceiros.','Valores racionais exactos;camposM20/M22 e representação não presumidos.','Saldo simulado por colecta projectada;sem pagamento,submissão ou reembolso automático.']};
|
||||
return{version:annualSettlementVersion,input:structuredClone(input),subjectNuit:b.subjectNuit,year:b.year,assessment:assessment?.record?{key:b.assessmentKey,kind:b.assessment,version:assessment.record.model.version,createdAt:assessment.record.createdAt,colecta,period:assessment.period,origin:assessment.record.model.origin}:null,claims,...(economic?{economicCredit:economic}:{}),internationalCredit:international,pecDeduction:pec,...(carry?{creditCarry:{...carry,afterInternational:ready?creditCollecta:null,afterPec:ready?afterPec:null}}:{}),knownWithholdings,knownPpc,arithmeticBalance,payable,recoverable,belowMinimum,status,pending:[...new Set(pending)],warnings:warn,source:annualSource(b),officialBalancesConsumed:false,submitted:false,refundReceived:false,limitations:[...(b.economicCredits?['Crédito económico ordinário:IRPC correspondente aos lucros,acréscimo53 já incluído e quota proporcional documentados. Sem cálculo automático da inclusão ou da exclusão40;liquidação64(3),associações64(4),benefícios e regras especiais separados. Sem reembolso ou transporte económico presumidos.']:[]),...(b.creditCarry?['Saldos anteriores documentados: escolha explícita das parcelas correntes e anteriores, sem prioridade presumida entre exercícios, reembolso ou criação/consumo de saldos oficiais.']:[]),...(b.internationalCredits?['Crédito internacional do próprio exercício:fracção nacional,convenção e montantes MZN são documentados;sem cálculo presumido,transporte ou consumo oficial. '+(b.economicCredits?'Benefícios positivos ficam separados;crédito económico no detalhe próprio.':'Créditos económicos/benefícios positivos ficam separados.')]:[]),b.economicCredits?'L8 parcial:benefícios próprios,derivação automática de quotas,inclusão/correcção económica na base,liquidação/associações,obrigações,autónomos,períodos especiais,moedas eM20/M22 separados. Saldos anteriores só quando detalhados e documentados.':b.creditCarry?'L8 parcial:créditos económicos/benefícios,obrigações,tributação autónoma,períodos especiais,outras moedas e correspondência M20/M22 separados. Prazos dos saldos anteriores demonstrados apenas para origens anuais ordinárias documentadas;sem criação automática de transporte.':b.internationalCredits?'L8 parcial:créditos económicos/benefícios positivos,transporte/caducidade,obrigações,tributação autónoma,períodos especiais e outras moedas separados. PEC sem reembolso ou transporte automático.':(b.pecPayments?'L8 parcial:transporte/caducidade de PEC, cálculo da obrigação, créditos próprios positivos, tributação autónoma, períodos especiais e outras moedas separados. Excedente PEC não é reembolso nem saldo transportado oficialmente.':'L8 parcial:PEC e créditos positivos,tributação autónoma,períodos especiais e pagamentos noutra moeda exigem regras próprias.'),'PPC aqui é pagamento comprovado;não cálculo automático da obrigação ou calendário.','Retenção sofrida não é retenção entregue pela empresa por conta de terceiros.','Valores racionais exactos;camposM20/M22 e representação não presumidos.','Saldo simulado por colecta projectada;sem pagamento,submissão ou reembolso automático.']};
|
||||
}
|
||||
export type AnnualModel=ReturnType<typeof calculateAnnual>;
|
||||
export function recordAnnual(d:Record<string,unknown>,b:AnnualBook,now=new Date().toISOString()):AnnualBook{return{...b,history:b.result?[...b.history,structuredClone(b.result)]:b.history,result:{version:annualSettlementVersion,key:key(d,b),createdAt:now,model:calculateAnnual(d,b)}};}
|
||||
@@ -140,13 +184,27 @@ export function annualReportRows(d:Record<string,unknown>):Array<[string,string,
|
||||
'NUIT: '+m.subjectNuit+'; exercício: '+m.year+'; colecta: '+show(m.assessment?.colecta??null)+'; origem: '+(m.assessment?.kind==='special'?'L7 qualificado':'L6 normal')+'. '+(annualCurrent(d,b)?'Entradas correspondentes.':'Histórico; origem/entradas alteradas: recalcule o saldo corrente.')+' Saldo simulado, não liquidação submetida.',
|
||||
m.input.reference+'; '+m.input.assessmentReference+'; '+m.source],
|
||||
...m.claims.map(c=>[
|
||||
'IRPC — L8',(c.kind==='withholding'?'Retenção sofrida':c.kind==='pec'?'PEC':c.kind==='foreign_credit'?'Imposto estrangeiro':'PPC')+' — '+(c.document||c.id),
|
||||
'Entidade: '+c.subjectNuit+'; exercício: '+c.year+'; emitente: '+c.issuer+'; data: '+c.date+'; comprovado: '+show(c.proofAmount)+'; parcela: '+(c.reason?'Indeterminado':show(c.value))+'. '+(c.reason||'Reconciliada sem utilização duplicada.'),
|
||||
c.kind==='withholding'?m.input.withholdings.reference+'; '+(m.input.withholdings.rows.find(r=>r.id===c.id)?.reference??''):c.kind==='foreign_credit'?(m.input.internationalCredits?.reference??'')+'; '+(m.input.internationalCredits?.positions.flatMap(p=>p.payments).find(r=>r.id===c.id)?.reference??'')+'; '+(m.input.internationalCredits?.positions.flatMap(p=>p.payments).find(r=>r.id===c.id)?.exerciseReference??''):c.kind==='pec'?(m.input.pecPayments?.reference??'')+'; '+(m.input.pecPayments?.rows.find(r=>r.id===c.id)?.reference??'')+'; utilizações anteriores: '+(m.input.pecPayments?.rows.find(r=>r.id===c.id)?.previouslyUsed??'')+' MZN; '+(m.input.pecPayments?.rows.find(r=>r.id===c.id)?.priorUseReference??''):m.input.ppc.reference+'; '+(m.input.ppc.rows.find(r=>r.id===c.id)?.reference??'')
|
||||
'IRPC — L8',(c.kind==='withholding'?'Retenção sofrida':c.kind==='pec'?'PEC':c.kind==='economic_credit'?'IRPC correspondente aos lucros':c.kind==='foreign_credit'?'Imposto estrangeiro':'PPC')+' — '+(c.document||c.id),
|
||||
'Entidade: '+c.subjectNuit+'; exercício: '+c.year+'; emitente: '+c.issuer+'; data: '+c.date+'; comprovado: '+show(c.proofAmount)+'; parcela: '+(c.reason?'Indeterminado':show(c.value))+(c.parcel?'; parcela documental: '+c.parcel+'; '+(c.parcelReference??''):'')+'. '+(c.reason||'Reconciliada sem utilização duplicada.'),
|
||||
c.kind==='economic_credit'?(m.input.economicCredits?.reference??'')+'; '+(m.input.economicCredits?.rows.find(r=>r.id===c.id)?.attributionReference??''):c.kind==='withholding'?m.input.withholdings.reference+'; '+(m.input.withholdings.rows.find(r=>r.id===c.id)?.reference??''):c.kind==='foreign_credit'?(m.input.internationalCredits?.reference??'')+'; '+(m.input.internationalCredits?.positions.flatMap(p=>p.payments).find(r=>r.id===c.id)?.reference??'')+'; '+(m.input.internationalCredits?.positions.flatMap(p=>p.payments).find(r=>r.id===c.id)?.exerciseReference??''):c.kind==='pec'?(m.input.pecPayments?.reference??'')+'; '+(m.input.pecPayments?.rows.find(r=>r.id===c.id)?.reference??'')+'; utilizações anteriores: '+(m.input.pecPayments?.rows.find(r=>r.id===c.id)?.previouslyUsed??'')+' MZN; '+(m.input.pecPayments?.rows.find(r=>r.id===c.id)?.priorUseReference??''):m.input.ppc.reference+'; '+(m.input.ppc.rows.find(r=>r.id===c.id)?.reference??'')
|
||||
]as[string,string,string,string]),
|
||||
...(m.economicCredit?[
|
||||
...m.economicCredit.rows.map(r=>['IRPC — L8','Crédito económico — '+r.input.distributionDocument,
|
||||
'Lucros incluídos: '+r.input.income+' MZN;IRPC correspondente: '+r.input.taxAmount+' MZN;crédito nominal60%: '+show(r.nominal)+';acréscimo53 incluído: '+r.input.grossUpIncluded+' MZN;quota proporcional: '+show(r.nationalLimit)+';elegível: '+show(r.eligible)+';uso efectivo anterior: '+show(r.previousUse)+';disponível: '+show(r.available)+';estado: '+r.status+'. '+r.pending.join(' | '),
|
||||
r.input.qualificationReference+';40(1): '+r.input.article40Reference+';inclusão: '+r.input.incomeReference+';53: '+r.input.grossUpReference+';quota: '+r.input.nationalLimitReference+';uso: '+r.input.previousUse.reference]as[string,string,string,string]),
|
||||
['IRPC — L8','Crédito económico — antes do internacional','Disponível: '+show(m.economicCredit.available)+';dedução: '+show(m.economicCredit.deducted)+';colecta após crédito económico: '+show(m.economicCredit.afterCredit)+'. Sem reembolso ou criação/consumo de saldo oficial.',m.economicCredit.source+'; '+(m.input.economicCredits?.reference??'')]as[string,string,string,string]
|
||||
]:[]),
|
||||
...(m.internationalCredit?[
|
||||
...m.internationalCredit.positions.map(p=>['IRPC — L8','Crédito internacional — '+p.country,'Imposto pago seleccionado: '+show(p.paid)+'; fracção nacional: '+show(p.nationalLimit)+'; limite CDT: '+(p.input.treaty==='no'?'Não aplicável documentado':show(p.treatyLimit))+'; elegível: '+show(p.eligible)+'; utilização anterior: '+show(p.previousUse)+'; disponível: '+show(p.available)+'; imposto acima dos limites: '+show(p.aboveLimit)+'. '+p.pending.join(' | '),p.input.incomeReference+'; '+p.input.nationalLimitReference+'; '+p.input.treatyReference+'; '+p.input.previousUse.reference]as[string,string,string,string]),
|
||||
['IRPC — L8','Crédito internacional — antes do PEC','Disponível conhecido: '+show(m.internationalCredit.available)+'; dedução: '+show(m.internationalCredit.deducted)+'; colecta após crédito: '+show(m.internationalCredit.afterCredit)+'; elegível não deduzido por insuficiência de colecta: '+show(m.internationalCredit.insufficientCollecta)+'. Sem reembolso,transporte ou afectação oficial por país. Estado: '+stateLabel(m.input.internationalCredits?.state??'')+'. Créditos económicos/benefícios: '+stateLabel(m.input.internationalCredits?.economic.state??'')+' / '+stateLabel(m.input.internationalCredits?.benefits.state??'')+'.',m.internationalCredit.source+'; '+(m.input.internationalCredits?.reference??'')+'; '+(m.input.internationalCredits?.economic.reference??'')+'; '+(m.input.internationalCredits?.benefits.reference??'')]as[string,string,string,string]
|
||||
['IRPC — L8','Crédito internacional — antes do PEC','Disponível conhecido: '+show(m.internationalCredit.available)+'; dedução: '+show(m.internationalCredit.deducted)+'; colecta após crédito: '+show(m.internationalCredit.afterCredit)+'; elegível não deduzido por insuficiência de colecta: '+show(m.internationalCredit.insufficientCollecta)+(m.creditCarry?'; crédito corrente não escolhido: '+show(m.internationalCredit.notSelected??null):'')+'. Sem reembolso,transporte ou afectação oficial por país. Estado: '+stateLabel(m.input.internationalCredits?.state??'')+'. Créditos económicos/benefícios: '+stateLabel(m.input.internationalCredits?.economic.state??'')+' / '+stateLabel(m.input.internationalCredits?.benefits.state??'')+'.',m.internationalCredit.source+'; '+(m.input.internationalCredits?.reference??'')+'; '+(m.input.internationalCredits?.economic.reference??'')+'; '+(m.input.internationalCredits?.benefits.reference??'')]as[string,string,string,string]
|
||||
]:[]),
|
||||
...(m.creditCarry?[
|
||||
...m.creditCarry.lots.map(l=>['IRPC — L8','Saldo anterior — '+(l.kind==='pec'?'PEC':'Crédito internacional '+l.country)+' — '+l.year,
|
||||
'Remanescente da origem: '+show(l.opening)+'; usos efectivos: '+show(l.used)+'; disponível: '+show(l.available)+'; parcela escolhida: '+show(l.selected)+'; saldo aritmético posterior: '+show(l.remaining)+'; último exercício ordinário: '+(l.lastYear??'Indeterminado')+'; prazo terminado: '+(l.expired?'Sim':'Não')+'. '+l.pending.join(' | '),
|
||||
l.input.originDocument+'; '+l.input.originReference+'; '+l.input.ruleReference+'; '+l.input.usesReference+'; '+l.input.uses.map(u=>u.year+': '+u.amount+' MZN; '+u.document+'; '+u.reference).join(' | ')]as[string,string,string,string]),
|
||||
['IRPC — L8','Afectação escolhida entre exercícios',
|
||||
'Corrente internacional: '+show(m.creditCarry.international)+'; anterior internacional: '+show(m.creditCarry.priorInternational)+'; PEC corrente: '+show(m.creditCarry.pec)+'; PEC anterior: '+show(m.creditCarry.priorPec)+'; colecta após créditos internacionais: '+show(m.creditCarry.afterInternational)+'; colecta após todos os PEC: '+show(m.creditCarry.afterPec)+'. Parcelas só deduzidas se o saldo estiver determinado. Sem criação ou consumo de saldo oficial. '+m.creditCarry.pending.join(' | '),
|
||||
(m.input.creditCarry?.reference??'')+'; '+(m.input.creditCarry?.allocationReference??'')+'; '+m.creditCarry.source]as[string,string,string,string]
|
||||
]:[]),
|
||||
...(m.pecDeduction?[[
|
||||
'IRPC — L8','PEC — dedução limitada à colecta',
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import {countryIsoCodes} from './country-iso-codes.ts';
|
||||
import {creditCompare, creditMoney, creditLimit} from './irpc-international-credit.ts';
|
||||
import {addFractions, fraction, subtractFractions, type FiscalFraction} from './fiscal-rational.ts';
|
||||
|
||||
export const carryVersion = 'IRPC-credit-carry/1';
|
||||
export const carrySource = 'CIRPC, Lei 34/2007, art.65(3): crédito internacional elegível não deduzido por insuficiência de colecta, até ao fim dos cinco exercícios seguintes; art.66(1–2): PEC até três exercícios seguintes, depois dos créditos precedentes, sem reembolso. Exemplar BR52, PDF18/p.768-(72). Recorte: fecho2026, mesmo sujeito, exercícios anuais ordinários, montantes comprovados em MZN. A origem e os usos efectivos são documentados; simulações não criam nem consomem saldos oficiais.';
|
||||
type State = '' | 'known' | 'absent';
|
||||
export type CarryUse = {id: string; year: string; amount: string; document: string; reference: string};
|
||||
export type CarryLot = {
|
||||
id: string; kind: '' | 'international' | 'pec'; country: string; subjectNuit: string; year: string;
|
||||
currency: string; ordinary: '' | 'yes' | 'no'; originDocument: string; originReference: string;
|
||||
ruleReference: string; eligible: string; originDeducted: string; insufficient: '' | 'yes' | 'no';
|
||||
usesState: State; usesReference: string; uses: CarryUse[]; selected: string;
|
||||
};
|
||||
export type CreditCarry = {
|
||||
version: 1; state: State; reference: string; lots: CarryLot[];
|
||||
currentInternational: string; currentPec: string; allocationReference: string; assessmentKey: string;
|
||||
};
|
||||
export const newCreditCarry = (): CreditCarry => ({version: 1, state: '', reference: '', lots: [], currentInternational: '', currentPec: '', allocationReference: '', assessmentKey: ''});
|
||||
export const newCarryLot = (id: string): CarryLot => ({id, kind: '', country: '', subjectNuit: '', year: '', currency: 'MZN', ordinary: '', originDocument: '', originReference: '', ruleReference: '', eligible: '', originDeducted: '', insufficient: '', usesState: '', usesReference: '', uses: [], selected: ''});
|
||||
export const newCarryUse = (id: string): CarryUse => ({id, year: '', amount: '', document: '', reference: ''});
|
||||
const states = ['', 'known', 'absent'];
|
||||
const zero = () => fraction(0n);
|
||||
const canonical = (s: string) => s.normalize('NFKC').trim().toLocaleLowerCase('pt').replace(/\s+/g, ' ');
|
||||
// One consolidated balance per nature/country/origin exercise; changing the document does not create a second quota.
|
||||
export const carryIdentity = (r: CarryLot) => JSON.stringify([r.subjectNuit, r.kind, r.country, r.year]);
|
||||
export function validateCreditCarry(c: CreditCarry) {
|
||||
if (!c || c.version !== 1 || !states.includes(c.state) || ['reference', 'currentInternational', 'currentPec', 'allocationReference', 'assessmentKey'].some(k => typeof (c as unknown as Record<string, unknown>)[k] !== 'string') || !Array.isArray(c.lots)) throw Error('Saldos anteriores não recuperáveis; originais conservados.');
|
||||
const keys = Object.keys(newCarryLot('')).filter(k => k !== 'uses');
|
||||
const ids: string[] = [];
|
||||
for (const r of c.lots) {
|
||||
if (!r || keys.some(k => typeof (r as unknown as Record<string, unknown>)[k] !== 'string') || !['', 'international', 'pec'].includes(r.kind) || !['', 'yes', 'no'].includes(r.ordinary) || !['', 'yes', 'no'].includes(r.insufficient) || !states.includes(r.usesState) || !Array.isArray(r.uses)) throw Error('Origem do saldo anterior não recuperável.');
|
||||
ids.push(r.id);
|
||||
for (const u of r.uses) {
|
||||
if (!u || Object.keys(newCarryUse('')).some(k => typeof (u as unknown as Record<string, unknown>)[k] !== 'string')) throw Error('Utilização anterior não recuperável.');
|
||||
ids.push(u.id);
|
||||
}
|
||||
}
|
||||
if (new Set(ids).size !== ids.length || ids.some(id => !id.trim())) throw Error('Identificador de saldo/utilização ausente ou repetido.');
|
||||
}
|
||||
export function calculateCarryLot(r: CarryLot, subjectNuit: string, year: string) {
|
||||
let opening: FiscalFraction | null = null, used: FiscalFraction | null = null, available: FiscalFraction | null = null, selected: FiscalFraction | null = null, remaining: FiscalFraction | null = null;
|
||||
let lastYear: number | null = null, expired = false;
|
||||
const pending: string[] = [];
|
||||
try {
|
||||
if (!r.kind || r.subjectNuit !== subjectNuit || !/^\d{9}$/.test(r.subjectNuit) || year !== '2026' || !/^20\d{2}$/.test(r.year) || Number(r.year) >= Number(year) || r.ordinary !== 'yes' || r.currency !== 'MZN') throw Error('Origem exige mesmo titular, exercício anterior anual ordinário e montante documentado em MZN.');
|
||||
if (r.kind === 'international' ? !countryIsoCodes.includes(r.country) || r.country === 'MZ' : r.country !== '') throw Error('País estrangeiro obrigatório para crédito internacional; PEC não tem país estrangeiro.');
|
||||
if (!r.originDocument.trim() || !r.originReference.trim() || !r.ruleReference.trim()) throw Error('Faltam apuramento original e regra aplicável ao exercício de origem, com suporte.');
|
||||
if (r.insufficient !== 'yes') throw Error('Falta comprovar que o remanescente resulta de insuficiência de colecta na origem; imposto acima do limite não é saldo transportável.');
|
||||
lastYear = Number(r.year) + (r.kind === 'international' ? 5 : 3);
|
||||
expired = Number(year) > lastYear;
|
||||
const amount = r.kind === 'international' ? creditLimit : creditMoney;
|
||||
const eligible = amount(r.eligible), originDeducted = amount(r.originDeducted);
|
||||
if (creditCompare(originDeducted, eligible) > 0n) throw Error('Dedução na origem ultrapassa o montante elegível comprovado.');
|
||||
opening = subtractFractions(eligible, originDeducted);
|
||||
if (!r.usesState || !r.usesReference.trim() || r.usesState === 'absent' && r.uses.length || r.usesState === 'known' && !r.uses.length) throw Error('Utilizações efectivas posteriores à origem exigem inventário conhecido ou ausência expressa com suporte.');
|
||||
const documents = new Set<string>();
|
||||
const values = r.uses.map(u => {
|
||||
if (!/^20\d{2}$/.test(u.year) || Number(u.year) <= Number(r.year) || Number(u.year) > Number(year) || Number(u.year) > lastYear! || !u.document.trim() || !u.reference.trim()) throw Error('Uso exige exercício elegível, posterior à origem, documento e suporte; pode incluir uso efectivo já ocorrido no exercício corrente.');
|
||||
const identity = canonical(u.document);
|
||||
if (documents.has(identity)) throw Error('Documento de utilização repetido; consolide a dedução efectiva.');
|
||||
documents.add(identity);
|
||||
return amount(u.amount);
|
||||
});
|
||||
used = addFractions(values);
|
||||
if (creditCompare(used, opening) > 0n) throw Error('Utilizações efectivas ultrapassam o remanescente da origem.');
|
||||
const balance = subtractFractions(opening, used);
|
||||
selected = amount(r.selected);
|
||||
available = expired ? zero() : balance;
|
||||
if (creditCompare(selected, available) > 0n) throw Error(expired ? 'Prazo ordinário terminado; saldo conservado no histórico, sem dedução neste exercício.' : 'Parcela seleccionada ultrapassa o saldo documentado disponível.');
|
||||
remaining = subtractFractions(balance, selected);
|
||||
} catch (e) { pending.push(String(e)); selected = null; }
|
||||
return {id: r.id, kind: r.kind, country: r.country, year: r.year, opening, used, available, selected, remaining, lastYear, expired, pending, input: structuredClone(r)};
|
||||
}
|
||||
export function carryPlan(c: CreditCarry, subjectNuit: string, year: string, assessmentKey: string, currentInternational: FiscalFraction, currentPec: FiscalFraction, colecta: FiscalFraction | null, duplicates: string[] = []) {
|
||||
validateCreditCarry(c);
|
||||
const pending = [...duplicates];
|
||||
if (!c.state || !c.reference.trim() || c.state === 'absent' && c.lots.length || c.state === 'known' && !c.lots.length) pending.push('Inventário de saldos anteriores em falta ou contraditório; desconhecido não significa ausente.');
|
||||
const ids = c.lots.map(carryIdentity);
|
||||
if (new Set(ids).size !== ids.length) pending.push('Saldo de mesma natureza/país/exercício repetido; consolide a origem e os usos.');
|
||||
const lots = c.lots.map(r => calculateCarryLot(r, subjectNuit, year));
|
||||
pending.push(...lots.flatMap(r => r.pending.map(p => r.year + '/' + r.kind + ': ' + p)));
|
||||
let international: FiscalFraction | null = null, pec: FiscalFraction | null = null;
|
||||
try {
|
||||
if (c.state !== 'known') return {version: carryVersion, lots, international, pec, priorInternational: zero(), priorPec: zero(), pending, source: carrySource, officialBalancesConsumed: false, carryCreated: false};
|
||||
if (!c.allocationReference.trim() || !c.assessmentKey || c.assessmentKey !== assessmentKey) throw Error('Confirme a escolha das parcelas correntes e anteriores com suporte na colecta seleccionada; não se presume prioridade entre exercícios.');
|
||||
international = creditLimit(c.currentInternational); pec = creditMoney(c.currentPec);
|
||||
if (creditCompare(international, currentInternational) > 0n || creditCompare(pec, currentPec) > 0n) throw Error('Parcela corrente escolhida ultrapassa o respectivo crédito/PEC comprovado disponível.');
|
||||
} catch (e) {pending.push(String(e));}
|
||||
const priorInternational = addFractions(lots.filter(r => r.kind === 'international' && !r.pending.length && r.selected).map(r => r.selected!));
|
||||
const priorPec = addFractions(lots.filter(r => r.kind === 'pec' && !r.pending.length && r.selected).map(r => r.selected!));
|
||||
if (international && pec && colecta && creditCompare(addFractions([international, pec, priorInternational, priorPec]), colecta) > 0n) pending.push('As parcelas escolhidas ultrapassam a colecta; ajuste a afectação entre exercícios antes de confirmar, sem reduzir valores automaticamente.');
|
||||
return {version: carryVersion, lots, international, pec, priorInternational, priorPec, pending, source: carrySource, officialBalancesConsumed: false, carryCreated: false};
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import {addFractions, fraction, subtractFractions, type FiscalFraction} from './fiscal-rational.ts';
|
||||
import {creditCompare, creditMoney, creditLimit, type CreditEvidence, type CreditState} from './irpc-international-credit.ts';
|
||||
import {canonicalParcel} from './fiscal-proof-parcel.ts';
|
||||
|
||||
export const economicVersion = 'IRPC-economic-credit/1';
|
||||
export const economicSource = 'CIRPC64(1–2), Lei34/2007, BR52, PDF18/p768-(72):60% do IRPC correspondente aos lucros distribuídos incluídos na base, limitado à colecta proporcional após acréscimo53(1)a (PDF15/p768-(69)). Distinto de65 e da exclusão40(1), na redacçãoLei20/2009,PDF4/p272-(16). RIRPC21(2/5),PDF6/p121:económico antes do internacional/benefícios/PEC,até à colecta,sem reembolso. Recorte2026,residente geral,ano civil,MZN,lucros ordinários,qualificação e quota proporcional documentadas na colecta corrente. Sem alterar a base por presunção, transporte ou consumo de saldos oficiais.';
|
||||
type Choice = '' | 'yes' | 'no';
|
||||
export type EconomicPosition = {
|
||||
id: string; subjectNuit: string; year: string; assessmentKey: string;
|
||||
kind: '' | 'ordinary_profit' | 'liquidation' | 'association'; payerNuit: string;
|
||||
recipientResident: Choice; payerResident: Choice; payerIrpc: Choice; payerExempt: Choice;
|
||||
article40: Choice; qualificationReference: string; article40Reference: string;
|
||||
distributionDocument: string; distributionParcel: string; distributionDate: string;
|
||||
income: string; incomeIncluded: Choice; incomeReference: string;
|
||||
taxIssuer: string; taxDocument: string; taxParcel: string; parcelReference: string;
|
||||
currency: string; proofAmount: string; taxAmount: string; attributionReference: string;
|
||||
previouslyAttributed: string; priorAttributionReference: string;
|
||||
grossUpIncluded: string; grossUpReference: string; nationalLimit: string; nationalLimitReference: string;
|
||||
previousUse: CreditEvidence;
|
||||
};
|
||||
export type EconomicCredits = {version: 1; state: CreditState; reference: string; rows: EconomicPosition[]};
|
||||
export const newEconomicCredits = (): EconomicCredits => ({version: 1, state: '', reference: '', rows: []});
|
||||
export const newEconomicPosition = (id: string): EconomicPosition => ({id, subjectNuit: '', year: '', assessmentKey: '', kind: '', payerNuit: '', recipientResident: '', payerResident: '', payerIrpc: '', payerExempt: '', article40: '', qualificationReference: '', article40Reference: '', distributionDocument: '', distributionParcel: '', distributionDate: '', income: '', incomeIncluded: '', incomeReference: '', taxIssuer: '', taxDocument: '', taxParcel: '', parcelReference: '', currency: 'MZN', proofAmount: '', taxAmount: '', attributionReference: '', previouslyAttributed: '', priorAttributionReference: '', grossUpIncluded: '', grossUpReference: '', nationalLimit: '', nationalLimitReference: '', previousUse: {state: '', amount: '', reference: ''}});
|
||||
export function validateEconomic(c: EconomicCredits) {
|
||||
if (!c || c.version !== 1 || !['', 'known', 'absent'].includes(c.state) || typeof c.reference !== 'string' || !Array.isArray(c.rows) || new Set(c.rows.map(r => r?.id)).size !== c.rows.length) throw Error('Crédito económico não recuperável; originais conservados.');
|
||||
const keys = Object.keys(newEconomicPosition('')).filter(k => k !== 'previousUse');
|
||||
for (const r of c.rows) if (!r || keys.some(k => typeof (r as unknown as Record<string, unknown>)[k] !== 'string') || !['', 'ordinary_profit', 'liquidation', 'association'].includes(r.kind) || ['recipientResident', 'payerResident', 'payerIrpc', 'payerExempt', 'article40', 'incomeIncluded'].some(k => !['', 'yes', 'no'].includes(r[k as 'payerIrpc'])) || !r.previousUse || !['', 'known', 'absent'].includes(r.previousUse.state) || typeof r.previousUse.amount !== 'string' || typeof r.previousUse.reference !== 'string') throw Error('Posição económica não recuperável; originais conservados.');
|
||||
}
|
||||
const zero = () => fraction(0n);
|
||||
const minimum = (...v: FiscalFraction[]) => v.reduce((a, b) => creditCompare(a, b) < 0n ? a : b);
|
||||
const validDate = (s: string) => /^20\d{2}-\d{2}-\d{2}$/.test(s) && Number.isFinite(Date.parse(s)) && new Date(s).toISOString().slice(0, 10) === s;
|
||||
export const economicDistributionIdentity = (r: EconomicPosition) => JSON.stringify([r.payerNuit, canonicalParcel(r.distributionDocument), canonicalParcel(r.distributionParcel)]);
|
||||
export function economicTaxProof(r: EconomicPosition) {
|
||||
if (!r.taxIssuer.trim() || !r.taxDocument.trim() || !r.taxParcel.trim() || !r.parcelReference.trim() || !r.attributionReference.trim() || !r.priorAttributionReference.trim() || r.currency !== 'MZN') throw Error('IRPC correspondente exige documento, emitente/parcela, suporte da atribuição aos lucros e montante MZN; não é retenção do beneficiário nem imposto estrangeiro.');
|
||||
const proofAmount = creditMoney(r.proofAmount), value = creditMoney(r.taxAmount), previouslyUsed = creditMoney(r.previouslyAttributed);
|
||||
if (creditCompare(addFractions([value, previouslyUsed]), proofAmount) > 0n) throw Error('IRPC atribuído aos lucros mais parcelas já atribuídas ultrapassam o comprovado disponível.');
|
||||
return {proofAmount, value, previouslyUsed};
|
||||
}
|
||||
export function economicGroupPending(c: EconomicCredits) {
|
||||
const pending: string[] = [];
|
||||
if (!c.state || !c.reference.trim()) pending.push('Crédito económico: inventário conhecido/ausente e suporte em falta.');
|
||||
if (c.state === 'absent' && c.rows.length) pending.push('Ausência de crédito económico contradiz lucros registados; conserve e reconcilie.');
|
||||
if (c.state === 'known' && !c.rows.length) pending.push('Crédito económico conhecido sem lucros/IRPC discriminados; zero não é ausência presumida.');
|
||||
if (new Set(c.rows.map(economicDistributionIdentity)).size !== c.rows.length) pending.push('Mesma parcela de lucros distribuídos repetida; consolide a origem, mesmo que o documento de imposto ou a data tenham sido alterados.');
|
||||
return pending;
|
||||
}
|
||||
export function economicPosition(r: EconomicPosition, subjectNuit: string, year: string, assessmentKey: string, colecta: FiscalFraction | null, proofIssues: string[]) {
|
||||
const pending = [...proofIssues];
|
||||
let nominal: FiscalFraction | null = null, nationalLimit: FiscalFraction | null = null, eligible: FiscalFraction | null = null, previousUse: FiscalFraction | null = null, available: FiscalFraction | null = null, included: FiscalFraction | null = null;
|
||||
let status: 'qualified' | 'outside_scope' | 'indeterminate' = 'indeterminate';
|
||||
try {
|
||||
if (!r.id.trim() || !/^\d{9}$/.test(r.payerNuit) || r.subjectNuit !== subjectNuit || year !== '2026' || r.year !== year || r.currency !== 'MZN') throw Error('Titular, entidade distribuidora, exercício2026 e MZN por corresponder.');
|
||||
if (r.kind !== 'ordinary_profit') {status = r.kind ? 'outside_scope' : 'indeterminate'; throw Error('Lucros ordinários64(1–2) por identificar; liquidação64(3) e associações64(4) exigem correspondência específica, sem converter a parcela em crédito internacional.');}
|
||||
if (r.recipientResident !== 'yes' || r.payerResident !== 'yes' || r.payerIrpc !== 'yes' || r.payerExempt !== 'no' || !r.qualificationReference.trim()) throw Error('Exige sede/direcção efectiva em Moçambique de beneficiário e distribuidor, distribuidor sujeito a IRPC e não isento, com suporte.');
|
||||
if (r.article40 !== 'no' || !r.article40Reference.trim()) {status = r.article40 === 'yes' ? 'outside_scope' : 'indeterminate'; throw Error(r.article40 === 'yes' ? 'Exclusão40(1) identificada: tratar na base; não somar crédito64 à mesma parcela excluída.' : 'Falta corresponder a não aplicação de40(1), incluindo a redacção20/2009; desconhecido não significa não aplicável.');}
|
||||
if (!validDate(r.distributionDate) || !r.distributionDate.startsWith(year + '-') || !r.distributionDocument.trim() || !r.distributionParcel.trim()) throw Error('Documento/parcela e data da distribuição do exercício por identificar.');
|
||||
if (!r.assessmentKey || r.assessmentKey !== assessmentKey || r.incomeIncluded !== 'yes' || !r.incomeReference.trim()) throw Error('Confirme a inclusão dos lucros ilíquidos de retenção e a correspondência com a colecta corrente; a origem pode ter mudado.');
|
||||
const tax = economicTaxProof(r), income = creditMoney(r.income);
|
||||
nominal = fraction(BigInt(tax.value.numerator) * 3n, BigInt(tax.value.denominator) * 5n);
|
||||
if (creditCompare(income, zero()) === 0n && creditCompare(nominal, zero()) > 0n) throw Error('Lucros incluídos zero contradizem IRPC correspondente positivo.');
|
||||
if (!r.grossUpReference.trim() || creditCompare(creditLimit(r.grossUpIncluded), nominal) !== 0n) throw Error('Acréscimo53(1)a incluído na base deve corresponder ao crédito nominal60%; reconcilie L6 sem alterar a colecta ou o histórico automaticamente.');
|
||||
included = addFractions([income, nominal]);
|
||||
nationalLimit = creditLimit(r.nationalLimit);
|
||||
if (!r.nationalLimitReference.trim() || !colecta || creditCompare(nationalLimit, colecta) > 0n || creditCompare(included, zero()) === 0n && creditCompare(nationalLimit, zero()) > 0n) throw Error('Quota proporcional da colecta após acréscimo53 exige suporte e correspondência; não pode exceder a colecta nem ser positiva para rendimento zero.');
|
||||
if (!r.previousUse.state || !r.previousUse.reference.trim()) throw Error('Utilização anterior efectiva do crédito em falta; simulação não é utilização fiscal.');
|
||||
if (r.previousUse.state === 'absent') {if (r.previousUse.amount.trim()) throw Error('Ausência de uso anterior contradiz montante'); previousUse = zero();}
|
||||
else previousUse = creditLimit(r.previousUse.amount);
|
||||
eligible = minimum(nominal, nationalLimit);
|
||||
if (creditCompare(previousUse, eligible) > 0n) throw Error('Uso anterior excede o crédito económico elegível.');
|
||||
if (!pending.length) {available = subtractFractions(eligible, previousUse); status = 'qualified';}
|
||||
} catch (e) {pending.push(String(e));}
|
||||
return {id: r.id, nominal, nationalLimit, eligible, previousUse, available, included, status, pending, input: structuredClone(r)};
|
||||
}
|
||||
export function economicDeduction(rows: ReturnType<typeof economicPosition>[], colecta: FiscalFraction | null, ready: boolean) {
|
||||
const available = addFractions(rows.flatMap(r => r.available && !r.pending.length ? [r.available] : []));
|
||||
const deducted = ready && colecta ? minimum(available, colecta) : null;
|
||||
return {version: economicVersion, rows, available, deducted, afterCredit: deducted && colecta ? subtractFractions(colecta, deducted) : null, source: economicSource, officialBalancesConsumed: false, carryCreated: false};
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import type {AnnualPpc} from './irpc-annual-settlement.ts';
|
||||
import {validateProofParcel, requireProofParcel} from './fiscal-proof-parcel.ts';
|
||||
import {countryIsoCodes} from './country-iso-codes.ts';
|
||||
import {addFractions, subtractFractions, decimalFraction, fraction, type FiscalFraction} from './fiscal-rational.ts';
|
||||
|
||||
@@ -32,6 +33,7 @@ export function validateInternational(c: InternationalCredits) {
|
||||
for (const p of c.positions) {
|
||||
if (!p || positionKeys.some(k => typeof (p as unknown as Record<string, unknown>)[k] !== 'string') || !yesNo.includes(p.incomeIncluded) || !yesNo.includes(p.treaty) || !evidenceValid(p.previousUse) || !Array.isArray(p.payments)) throw Error('Posição internacional não recuperável; originais conservados.');
|
||||
for (const r of p.payments) {
|
||||
validateProofParcel(r);
|
||||
if (!r || proofKeys.some(k => typeof (r as unknown as Record<string, unknown>)[k] !== 'string') || !yesNo.includes(r.effective) || !yesNo.includes(r.incomeTax)) throw Error('Comprovativo internacional não recuperável.');
|
||||
proofIds.push(r.id);
|
||||
}
|
||||
@@ -43,7 +45,7 @@ export const creditMoney = (raw: string) => {
|
||||
return decimalFraction(raw);
|
||||
};
|
||||
export const creditCompare = (a: FiscalFraction, b: FiscalFraction) => BigInt(a.numerator) * BigInt(b.denominator) - BigInt(b.numerator) * BigInt(a.denominator);
|
||||
const creditLimit = (raw: string) => {
|
||||
export const creditLimit = (raw: string) => {
|
||||
const rational = /^(\d{1,18})\/(\d{1,18})$/.exec(raw);
|
||||
if (rational) return fraction(BigInt(rational[1]), BigInt(rational[2]));
|
||||
if (!/^\d{1,18}(\.\d{1,6})?$/.test(raw)) throw Error('Limite documentado em falta/inválido; use decimal ou fracção exacta n/d, sem arredondamento presumido.');
|
||||
@@ -53,18 +55,19 @@ const zero = () => fraction(0n);
|
||||
const minimum = (...values: FiscalFraction[]) => values.reduce((a, b) => creditCompare(a, b) < 0n ? a : b);
|
||||
const isDate = (s: string) => /^20\d{2}-\d{2}-\d{2}$/.test(s) && Number.isFinite(Date.parse(s)) && new Date(s).toISOString().slice(0, 10) === s;
|
||||
export function internationalProofValue(r: InternationalTaxProof, subjectNuit: string, year: string) {
|
||||
requireProofParcel(r);
|
||||
if (!r.id.trim() || !r.document.trim() || !r.issuer.trim() || !r.reference.trim() || !r.taxReference.trim() || r.incomeTax !== 'yes' || r.effective !== 'yes' || r.currency !== 'MZN' || !isDate(r.date) || r.subjectNuit !== subjectNuit || r.year !== year || year !== '2026') throw Error('Crédito internacional: exige imposto sobre o rendimento efectivamente pago, prova/titular/exercício 2026 e MZN; previsões, outras naturezas e conversões não correspondidas ficam separados.');
|
||||
if (!r.date.startsWith(year + '-') && !r.exerciseReference.trim()) throw Error('Data de pagamento fora do exercício: falta correspondência documental com o rendimento e imposto deste exercício; não é transporte presumido.');
|
||||
const value = creditMoney(r.amount), proofAmount = creditMoney(r.proofAmount);
|
||||
if (creditCompare(value, proofAmount) > 0n) throw Error('Parcela estrangeira ultrapassa o montante comprovado.');
|
||||
return {value, proofAmount};
|
||||
}
|
||||
export function internationalGroupPending(c: InternationalCredits) {
|
||||
export function internationalGroupPending(c: InternationalCredits, economicDetailed = false) {
|
||||
const pending: string[] = [];
|
||||
if (!c.state || !c.reference.trim()) pending.push('Crédito internacional: declare pagamentos conhecidos, ausência ou informação em falta, com suporte.');
|
||||
if (c.state === 'absent' && c.positions.length) pending.push('Ausência de crédito internacional contradiz posições presentes; conserve e reconcilie.');
|
||||
if (c.state === 'known' && !c.positions.length) pending.push('Crédito internacional conhecido sem posição/comprovativo; zero não é ausência presumida.');
|
||||
for (const [label, e] of [['Dupla tributação económica', c.economic], ['Benefícios/créditos próprios', c.benefits]] as const) {
|
||||
for (const [label, e] of [...(economicDetailed ? [] : [['Dupla tributação económica', c.economic] as const]), ['Benefícios/créditos próprios', c.benefits] as const]) {
|
||||
try {
|
||||
if (!e.state || !e.reference.trim()) throw Error('estado e suporte em falta');
|
||||
if (e.state === 'absent') {if (e.amount.trim()) throw Error('ausência contradiz montante');}
|
||||
@@ -101,8 +104,8 @@ export function internationalPosition(p: InternationalPosition, paid: FiscalFrac
|
||||
} catch (e) {pending.push(String(e));available = null;}
|
||||
return {id: p.id, country: p.country, paid, nationalLimit, treatyLimit, previousUse, eligible, available, aboveLimit, pending, input: structuredClone(p)};
|
||||
}
|
||||
export function internationalDeduction(positions: ReturnType<typeof internationalPosition>[], colecta: FiscalFraction | null, ready: boolean) {
|
||||
export function internationalDeduction(positions: ReturnType<typeof internationalPosition>[], colecta: FiscalFraction | null, ready: boolean, selected?: FiscalFraction | null) {
|
||||
const available = addFractions(positions.flatMap(p => p.available && !p.pending.length ? [p.available] : []));
|
||||
const deducted = ready && colecta ? minimum(available, colecta) : null;
|
||||
return {version: internationalCreditVersion, positions, available, deducted, afterCredit: deducted && colecta ? subtractFractions(colecta, deducted) : null, insufficientCollecta: deducted ? subtractFractions(available, deducted) : null, source: internationalCreditSource, countryAllocationCreated: false, carryCreated: false, officialBalancesConsumed: false};
|
||||
const deducted = ready && colecta ? selected ?? minimum(available, colecta) : null;
|
||||
return {version: internationalCreditVersion, positions, available, deducted, afterCredit: deducted && colecta ? subtractFractions(colecta, deducted) : null, insufficientCollecta: selected === undefined && deducted ? subtractFractions(available, deducted) : null, ...(selected !== undefined ? {notSelected: deducted ? subtractFractions(available, deducted) : null} : {}), source: internationalCreditSource, countryAllocationCreated: false, carryCreated: false, officialBalancesConsumed: false};
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import {subtractFractions, decimalFraction, type FiscalFraction} from './fiscal-rational.ts';
|
||||
import {validateProofParcel, requireProofParcel, type FiscalProofParcel} from './fiscal-proof-parcel.ts';
|
||||
|
||||
export const pecVersion = 'IRPC-PEC/1';
|
||||
export const pecSource = 'CIRPC, art. 66(1–2), Lei 34/2007, exemplar BR52, p. 768-(72): dedução após créditos anteriores, até à colecta, sem reembolso do PEC. Recorte demonstrado: pagamento efectivo do próprio exercício 2026, residente geral, ano civil, MZN. Não calcula a obrigação PEC, transporte, caducidade ou consumo de saldos oficiais.';
|
||||
export type PecPayment = {
|
||||
export type PecPayment = FiscalProofParcel & {
|
||||
id: string; document: string; issuer: string; date: string; subjectNuit: string;
|
||||
year: string; currency: string; proofAmount: string; amount: string;
|
||||
effective: '' | 'yes' | 'no'; reference: string;
|
||||
@@ -15,6 +16,7 @@ export function validatePec(p: PecPayments) {
|
||||
if (!p || p.version !== 1 || !['', 'known', 'absent'].includes(p.state) || typeof p.reference !== 'string' || !Array.isArray(p.rows) || new Set(p.rows.map(r => r?.id)).size !== p.rows.length || p.rows.some(r => !r || keys.some(k => typeof (r as unknown as Record<string, unknown>)[k] !== 'string') || !['', 'yes', 'no'].includes(r.effective))) {
|
||||
throw Error('Comprovativos PEC não recuperáveis; originais conservados.');
|
||||
}
|
||||
for (const r of p.rows) validateProofParcel(r);
|
||||
}
|
||||
export const pecCompare = (a: FiscalFraction, b: FiscalFraction) => BigInt(a.numerator) * BigInt(b.denominator) - BigInt(b.numerator) * BigInt(a.denominator);
|
||||
const money = (s: string) => {
|
||||
@@ -22,6 +24,7 @@ const money = (s: string) => {
|
||||
return decimalFraction(s);
|
||||
};
|
||||
export function pecPaymentValue(r: PecPayment, subjectNuit: string, year: string) {
|
||||
requireProofParcel(r);
|
||||
if (!r.id.trim() || !r.document.trim() || !r.issuer.trim() || !r.reference.trim() || !r.priorUseReference.trim() || r.effective !== 'yes' || r.currency !== 'MZN' || !/^20\d{2}-\d{2}-\d{2}$/.test(r.date) || !Number.isFinite(Date.parse(r.date)) || new Date(r.date).toISOString().slice(0, 10) !== r.date || !r.date.startsWith(year + '-') || r.subjectNuit !== subjectNuit || r.year !== year || year !== '2026') {
|
||||
throw Error('PEC: exige prova efectiva, natureza PEC, titular, exercício 2026, data válida e MZN; saldos anteriores e previsões ficam separados.');
|
||||
}
|
||||
@@ -29,7 +32,7 @@ export function pecPaymentValue(r: PecPayment, subjectNuit: string, year: string
|
||||
if (pecCompare(previouslyUsed, proofAmount) > 0n || pecCompare(value, subtractFractions(proofAmount, previouslyUsed)) > 0n) throw Error('PEC: parcela e utilizações anteriores excedem o comprovativo disponível.');
|
||||
return {proofAmount, value, previouslyUsed};
|
||||
}
|
||||
export function pecDeduction(available: FiscalFraction, colecta: FiscalFraction | null, ready: boolean) {
|
||||
const deducted = ready && colecta ? (pecCompare(available, colecta) > 0n ? colecta : available) : null;
|
||||
export function pecDeduction(available: FiscalFraction, colecta: FiscalFraction | null, ready: boolean, selected?: FiscalFraction | null) {
|
||||
const deducted = ready && colecta ? selected ?? (pecCompare(available, colecta) > 0n ? colecta : available) : null;
|
||||
return {version: pecVersion, available, deducted, remaining: deducted ? subtractFractions(available, deducted) : null, afterPec: deducted && colecta ? subtractFractions(colecta, deducted) : null, source: pecSource, officialBalancesConsumed: false, carryCreated: false};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
export type FillGroup = { id: string; title: string; hint: string; fields: string[] };
|
||||
const definitions: Omit<FillGroup, 'fields'>[] = [
|
||||
{id:'idea',title:'Ideia e actividade',hint:'Identifique o investimento e descreva a necessidade que pretende responder.'},
|
||||
{id:'people',title:'Promotor e contactos',hint:'Reutilize os contactos guardados e escolha o que pode ser divulgado.'},
|
||||
{id:'territory',title:'Localização e enquadramento',hint:'Indique o território conhecido e as associações documentadas que se aplicam.'},
|
||||
{id:'operation',title:'Actividade e impacto',hint:'Complete os produtos, recursos, mercados e impactos relevantes para esta oportunidade.'},
|
||||
{id:'finance',title:'Investimento e financiamento',hint:'Preencha os valores conhecidos. O rascunho pode continuar incompleto.'},
|
||||
{id:'evidence',title:'Documentos e imagens',hint:'Reutilize os recursos guardados na mesma oportunidade.'},
|
||||
{id:'specific',title:'Dados específicos',hint:'Preencha os detalhes aplicáveis à modalidade escolhida.'},
|
||||
{id:'review',title:'Revisão e divulgação',hint:'Reveja riscos, condições e visibilidade antes das acções autorizadas de submissão.'},
|
||||
];
|
||||
const fields: Record<string,string[]> = {
|
||||
idea:['official_title','sector_id','subsector_id','economic_activity_id','executive_summary','demand_statement','opportunity_type','maturity_stage','enterprise_size'],
|
||||
people:['promoter_type','internal_contact_id','publish_contact','public_contact_id'],
|
||||
territory:['location_mode','geographic_scope','multi_district_rationale','locations','relations'],
|
||||
operation:['investment_modalities','investor_profiles','products','assets','inputs','markets','competitive_advantage','employment','impact_indicators'],
|
||||
finance:['total_investment','currency','investment_breakdown','secured_financing','funding_sought','financial_indicators'],
|
||||
evidence:['documents','evidences','images'],
|
||||
review:['publication_languages','visibility','review_due_date','truth_declaration','milestones','licenses','environmental_social','risks'],
|
||||
};
|
||||
|
||||
/** Presentation groups only: retain every applicable field exactly once, including future schema keys. */
|
||||
export function opportunityFillGroups(available: string[]): FillGroup[] {
|
||||
const unique=[...new Set(available)];
|
||||
return definitions.map(group=>({...group,fields:unique.filter(field=>{
|
||||
const owner=Object.keys(fields).find(key=>fields[key].includes(field))??'specific';
|
||||
return owner===group.id;
|
||||
})})).filter(group=>group.fields.length>0);
|
||||
}
|
||||
|
||||
export function opportunityErrorGroup(groups: FillGroup[], errors: Record<string,string>): string | undefined {
|
||||
return groups.find(group=>group.fields.some(field=>Object.keys(errors).some(path=>path===`canonical.${field}`||path.startsWith(`canonical.${field}.`))))?.id;
|
||||
}
|
||||
|
||||
export function opportunityMissingGroups(groups:FillGroup[], paths:string[]):FillGroup[] {
|
||||
return groups.filter(group=>group.fields.some(field=>paths.some(path=>{
|
||||
const normalized=path.replace(/^canonical\./,'');
|
||||
return normalized===field||normalized.startsWith(`${field}.`);
|
||||
})));
|
||||
}
|
||||
@@ -8,6 +8,9 @@ export type PortalNavItem = {
|
||||
children?: PortalNavItem[];
|
||||
};
|
||||
export type PortalNavAccess = {
|
||||
contentManagementHref?: string | null;
|
||||
contentManagementAccess?: {opportunities?:{index:string;create?:string|null}};
|
||||
scopedAdministration?: { label: string; href: string }[];
|
||||
procurement?: boolean;
|
||||
authenticated: boolean;
|
||||
manager: boolean;
|
||||
@@ -31,6 +34,10 @@ const link = (id: string, label: string, href: string): PortalNavItem => ({
|
||||
label,
|
||||
href,
|
||||
});
|
||||
/** Display the existing server decision; a generic manager flag cannot override a scoped denial. */
|
||||
export function canShowLegacyManagement(auth?:{user?:unknown;canManagePortal?:boolean;legacyManagementAccess?:boolean}):boolean {
|
||||
return !!auth?.user && (auth.legacyManagementAccess??auth.canManagePortal??false);
|
||||
}
|
||||
|
||||
/** One route catalogue for the public shell and authenticated pages. */
|
||||
export function legacyPortalNavigation(
|
||||
@@ -371,6 +378,7 @@ export function legacyPortalNavigation(
|
||||
'Gestão de perfis',
|
||||
profile.administration,
|
||||
),
|
||||
link('profile-installation','Instalação dos perfis 040000','/management/profile-install'),
|
||||
]
|
||||
: []),
|
||||
],
|
||||
@@ -439,7 +447,10 @@ export function currentNavigationItem(
|
||||
|
||||
/** Investor organization; existing capability filters still determine private destinations. */
|
||||
export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
|
||||
const previous = legacyPortalNavigation(access);
|
||||
const previous = legacyPortalNavigation({...access,manager:access.authenticated&&access.manager,profileAccess:access.authenticated?access.profileAccess:null});
|
||||
const workHub=access.authenticated?access.contentManagementHref:null;
|
||||
const workOpportunities=access.authenticated?access.contentManagementAccess?.opportunities:undefined;
|
||||
const workCreate=access.authenticated?(access.profileAccess?.create||workOpportunities?.create||(access.manager&&access.opportunityManagement?.installed?access.opportunityManagement.create.href:null)):null;
|
||||
return uniqueNavigationDestinations([
|
||||
{
|
||||
id: 'discovery',
|
||||
@@ -544,11 +555,20 @@ export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
|
||||
),
|
||||
],
|
||||
},
|
||||
...previous.filter((group) =>
|
||||
['account', 'management', 'profile-opportunities'].includes(
|
||||
group.id,
|
||||
),
|
||||
),
|
||||
...[{
|
||||
id: 'work',
|
||||
label: 'Área de trabalho',
|
||||
children: [
|
||||
link('work-entry', workHub ? 'Gestão de conteúdos e oportunidades':'Acesso à gestão', workHub || '/acesso-gestao'),
|
||||
...(workCreate ? [
|
||||
link('prepare-analysis', 'Preparar análise e ideia', workCreate+'?analysis=proactive'),
|
||||
] : []),
|
||||
...(workOpportunities ? [link('work-opportunities','Oportunidades em preparação',workOpportunities.index)] : []),
|
||||
...previous.filter(group=>['management','profile-opportunities'].includes(group.id)).flatMap(group=>group.children??[]),
|
||||
...(access.authenticated&&access.scopedAdministration?.length ? [{id:'work-administration',label:'Administração',children:access.scopedAdministration.map((item,index)=>link('scoped-'+index,item.label,item.href))}] : []),
|
||||
],
|
||||
}],
|
||||
...previous.filter((group) => group.id === 'account'),
|
||||
...(access.authenticated &&
|
||||
access.businesses &&
|
||||
access.businessReviewUrl
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
const territoryKeys=['province_id','district_id','admin_post_id','locality_id'];
|
||||
/** No fallback scope: an explicit empty path means all; a selected path replaces its old descendants. */
|
||||
export function territorialSearchParams(entries: Iterable<[string,FormDataEntryValue]>, path?: {id:string;location_type:string}[]): URLSearchParams {
|
||||
const params=new URLSearchParams();
|
||||
for(const [key,value] of entries)if(typeof value==='string'&&value!==''&&key!=='page')params.set(key,value);
|
||||
if(path){
|
||||
territoryKeys.forEach(key=>params.delete(key));
|
||||
for(const node of path){const key=`${node.location_type}_id`;if(territoryKeys.includes(key))params.set(key,node.id);}
|
||||
}
|
||||
return params;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import EducationalGuides from '@/components/educational-guides';
|
||||
import CatalogueGuideLinks from '@/components/catalogue-guide-links';
|
||||
import OpportunityCorridorGroups, {
|
||||
type CorridorGroup,
|
||||
} from '@/components/opportunity-corridor-groups';
|
||||
@@ -444,7 +444,11 @@ export default function Catalogue({
|
||||
aria-busy={searchLoading}
|
||||
>
|
||||
<header className="catalogue-results-heading">
|
||||
<h2>Oportunidades publicadas</h2>
|
||||
<h2>
|
||||
Oportunidades publicadas
|
||||
{filters.sector && ` · ${references.sectors.find((sector) => sector.slug === filters.sector)?.name ?? filters.sector}`}
|
||||
{territorySelection.length > 0 && ` · ${territorySelection.map((territory) => territory.name).join(' / ')}`}
|
||||
</h2>
|
||||
<SearchState
|
||||
loading={searchLoading}
|
||||
error={searchError}
|
||||
@@ -516,7 +520,7 @@ export default function Catalogue({
|
||||
}));
|
||||
}}
|
||||
>
|
||||
Alargar pesquisa (remover localização)
|
||||
Pesquisar noutras províncias (remover localização)
|
||||
</button>
|
||||
)}
|
||||
<div
|
||||
@@ -771,7 +775,7 @@ export default function Catalogue({
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span>
|
||||
{r.province ||
|
||||
{r.territorial_summary || [r.province, r.district].filter(Boolean).join(' / ') ||
|
||||
'Localização não indicada'}
|
||||
</span>
|
||||
</p>
|
||||
@@ -891,12 +895,12 @@ export default function Catalogue({
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{!results.total && (
|
||||
{!searchLoading && !searchError && !results.total && (
|
||||
<p className={card}>
|
||||
Sem oportunidades com estes filtros. Explore as
|
||||
fichas territoriais ou{' '}
|
||||
Não há oportunidades publicadas com estes filtros no cadastro consultado.
|
||||
A informação disponível pode ser incompleta. Pode{' '}
|
||||
<Link href="/apoio" className="underline">
|
||||
peça apoio
|
||||
pedir apoio
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
@@ -1084,7 +1088,7 @@ export default function Catalogue({
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
<EducationalGuides articles={guides} />
|
||||
<CatalogueGuideLinks articles={guides} />
|
||||
</section>
|
||||
</div>
|
||||
</Frame>
|
||||
|
||||
@@ -53,6 +53,7 @@ export type Opportunity = {
|
||||
description: string | null;
|
||||
province: string | null;
|
||||
district: string | null;
|
||||
territorial_summary?: string;
|
||||
sector?: { name: string; slug: string };
|
||||
estimated_investment_amount: string | null;
|
||||
estimated_investment_currency: string;
|
||||
|
||||
@@ -3,7 +3,9 @@ import InvestmentZoneInstallation, {
|
||||
} from '@/components/investment-zone-installation';
|
||||
import { Link, router, usePage } from '@inertiajs/react';
|
||||
import { searchTerritoryHref } from '@/lib/search-territory';
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { territorialSearchParams } from '@/lib/territorial-search-params';
|
||||
import CatalogueFilterContext from '@/components/catalogue-filter-context';
|
||||
import { catalogueDetailHref } from '@/lib/catalogue-context';
|
||||
import {
|
||||
TerritoryFields,
|
||||
@@ -77,6 +79,10 @@ export default function Zones({
|
||||
total: number;
|
||||
next_page_url: string | null;
|
||||
prev_page_url: string | null;
|
||||
from?: number | null;
|
||||
to?: number | null;
|
||||
current_page?: number;
|
||||
last_page?: number;
|
||||
};
|
||||
filters: {
|
||||
q?: string;
|
||||
@@ -94,6 +100,30 @@ export default function Zones({
|
||||
const pageUrl = usePage().url;
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const searchForm=useRef<HTMLFormElement|null>(null);
|
||||
const searchTimer=useRef<ReturnType<typeof setTimeout>|undefined>(undefined);
|
||||
const cancelSearch=useRef<(()=>void)|undefined>(undefined);
|
||||
const searchSequence=useRef(0);
|
||||
const [searching,setSearching]=useState(false);
|
||||
const [searchError,setSearchError]=useState('');
|
||||
const appliedKey=JSON.stringify([filters,territorySelection]);
|
||||
useEffect(()=>{searchForm.current?.reset();},[appliedKey]);
|
||||
useEffect(()=>()=>{clearTimeout(searchTimer.current);cancelSearch.current?.();},[]);
|
||||
const runSearch=(path?:TerritoryOption[])=>{
|
||||
clearTimeout(searchTimer.current);cancelSearch.current?.();
|
||||
if(!searchForm.current)return;
|
||||
const sequence=++searchSequence.current;
|
||||
const params=territorialSearchParams(new FormData(searchForm.current),path);
|
||||
setSearching(true);setSearchError('');
|
||||
router.get(`${management?'/management/investment/zones':'/zonas'}?${params}`,{}, {
|
||||
preserveState:true,preserveScroll:true,replace:true,
|
||||
onCancelToken:token=>{cancelSearch.current=()=>token.cancel();},
|
||||
onError:()=>{if(sequence===searchSequence.current)setSearchError('A pesquisa não foi concluída. Confira os filtros e tente novamente.');},
|
||||
onNetworkError:()=>{if(sequence===searchSequence.current)setSearchError('Ligação indisponível. Os filtros escolhidos foram preservados.');return false;},
|
||||
onHttpException:()=>{if(sequence===searchSequence.current)setSearchError('Não foi possível consultar esta selecção.');return false;},
|
||||
onFinish:()=>{if(sequence===searchSequence.current)setSearching(false);},
|
||||
});
|
||||
};
|
||||
const exportParams = new URLSearchParams();
|
||||
['province_id', 'district_id', 'admin_post_id', 'locality_id'].forEach((field, index) => {
|
||||
if (territorySelection[index]) exportParams.set(field, territorySelection[index].id);
|
||||
@@ -160,22 +190,18 @@ export default function Zones({
|
||||
</Link>
|
||||
</nav>
|
||||
</details>
|
||||
<CatalogueFilterContext />
|
||||
<form
|
||||
ref={searchForm}
|
||||
method="get"
|
||||
onChange={(event)=>{
|
||||
if(!event.target.getAttribute('name'))return;
|
||||
clearTimeout(searchTimer.current);cancelSearch.current?.();searchSequence.current++;
|
||||
setSearching(true);setSearchError('');searchTimer.current=setTimeout(()=>runSearch(),350);
|
||||
}}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget;
|
||||
const url = new URL(form.action);
|
||||
const params = new URLSearchParams();
|
||||
for (const [name, value] of new FormData(form))
|
||||
if (typeof value === 'string')
|
||||
params.append(name, value);
|
||||
url.search = params.toString();
|
||||
router.get(
|
||||
url.toString(),
|
||||
{},
|
||||
{ preserveState: true, preserveScroll: true },
|
||||
);
|
||||
runSearch();
|
||||
}}
|
||||
className={card + ' grid gap-4 md:grid-cols-3'}
|
||||
>
|
||||
@@ -307,10 +333,14 @@ export default function Zones({
|
||||
)}
|
||||
</div>
|
||||
</details>
|
||||
<TerritoryFields initial={territorySelection} />
|
||||
<TerritoryFields initial={territorySelection} onChange={path=>runSearch(path)} />
|
||||
<button type="button" className="underline" onClick={()=>runSearch([])}>Todo o território (remover localização)</button>
|
||||
<button className={button}>Pesquisar</button>
|
||||
</form>
|
||||
{!management && (
|
||||
<h2 className="text-xl font-semibold">{searching?'A pesquisar a selecção…':searchError?'Pesquisa por concluir':`${records.total} registos disponíveis · ${territorySelection.length?territorySelection.map(node=>node.name).join(' / '):'Todo o território'}`}</h2>
|
||||
{!searching&&!searchError&&records.total>0&&<p>A mostrar {records.from??1} a {records.to??records.data.length} de {records.total}. Página {records.current_page??1} de {records.last_page??1}.</p>}
|
||||
{searchError&&<p role="alert">{searchError}</p>}
|
||||
{!management && !searching && !searchError && (
|
||||
<a
|
||||
className="underline"
|
||||
href={`/api/v2/investment/zones/export.csv?${exportParams.toString()}`}
|
||||
@@ -318,12 +348,12 @@ export default function Zones({
|
||||
Exportar resultados filtrados (CSV)
|
||||
</a>
|
||||
)}
|
||||
{!records.total && (
|
||||
{!searching && !searchError && !records.total && (
|
||||
<p className={card}>
|
||||
Não foram encontrados resultados para esta pesquisa.
|
||||
</p>
|
||||
)}
|
||||
{records.data.map((zone) => (
|
||||
{!searching && !searchError && records.data.map((zone) => (
|
||||
<article className={card} key={zone.id}>
|
||||
<h2 className="text-xl font-bold">
|
||||
<Link
|
||||
@@ -451,10 +481,10 @@ export default function Zones({
|
||||
</article>
|
||||
))}
|
||||
<nav aria-label="Paginação" className="flex gap-4 underline">
|
||||
{records.prev_page_url && (
|
||||
{!searching && !searchError && records.prev_page_url && (
|
||||
<Link href={records.prev_page_url}>Anterior</Link>
|
||||
)}
|
||||
{records.next_page_url && (
|
||||
{!searching && !searchError && records.next_page_url && (
|
||||
<Link href={records.next_page_url}>Seguinte</Link>
|
||||
)}
|
||||
</nav>
|
||||
|
||||
@@ -171,10 +171,8 @@ function Stage({ step, path }: { step: Step; path: Path }) {
|
||||
];
|
||||
const states = path.canWrite ? ownerStates : reviewStates;
|
||||
return (
|
||||
<article id={step.code} className="space-y-3 rounded-xl border p-4">
|
||||
<h3 className="font-semibold">
|
||||
{step.code} · {step.title}
|
||||
</h3>
|
||||
<details id={step.code} open={path.next?.code===step.code} className="space-y-3 rounded-xl border p-4">
|
||||
<summary className="cursor-pointer font-semibold">{step.title} · {pathStates[step.state]}</summary>
|
||||
<p>{pathStates[step.state]}</p>
|
||||
{step.context_review_required && (
|
||||
<label className="block rounded border border-amber-600 bg-amber-50 p-3">
|
||||
@@ -235,17 +233,18 @@ function Stage({ step, path }: { step: Step; path: Path }) {
|
||||
: action === 'operate'
|
||||
? 'Operação'
|
||||
: 'Execução'}{' '}
|
||||
aguarda {gaps.join(', ')}. Pode continuar a preparar.
|
||||
aguarda {gaps.map(code=>path.steps.find(item=>item.code===code)?.title??code).join(', ')}. Pode continuar a preparar.
|
||||
</p>
|
||||
))}
|
||||
<p className="text-xs">
|
||||
<details className="text-xs"><summary className="cursor-pointer underline">Fonte e referência desta etapa</summary><p>
|
||||
Referência interna {step.code}.{' '}
|
||||
Documento original, parágrafo {step.source_paragraph}.{' '}
|
||||
{step.detail.scope === 'internal_validation'
|
||||
? 'Conferência interna; não equivale a decisão externa.'
|
||||
: step.detail.scope === 'external_document_recorded'
|
||||
? 'Acto externo registado a partir de documento.'
|
||||
: 'Preparação declarada pelo promotor.'}
|
||||
</p>
|
||||
</p></details>
|
||||
{step.preparation_allowed && (path.canWrite || path.canReview) && (
|
||||
<details>
|
||||
<summary className="cursor-pointer underline">
|
||||
@@ -405,7 +404,7 @@ function Stage({ step, path }: { step: Step; path: Path }) {
|
||||
</form>
|
||||
</details>
|
||||
)}
|
||||
</article>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -718,10 +717,10 @@ export default function InvestmentPath(path: Path) {
|
||||
</section>
|
||||
)}
|
||||
{Object.entries(path.phases).filter(([number]) => path.steps.some((step) => step.phase === Number(number) && step.preparation_allowed)).map(([number, label]) => (
|
||||
<section className="space-y-3" key={number}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
<details open={path.steps.some(step=>step.phase===Number(number)&&step.code===path.next?.code)} className="space-y-3 rounded border p-4" key={number}>
|
||||
<summary className="cursor-pointer text-lg font-semibold">
|
||||
Fase {number} · {label}
|
||||
</h2>
|
||||
</summary>
|
||||
<div className="grid items-start gap-3 md:grid-cols-2">
|
||||
{path.steps
|
||||
.filter((step) => step.phase === Number(number) && step.preparation_allowed)
|
||||
@@ -733,7 +732,7 @@ export default function InvestmentPath(path: Path) {
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</details>
|
||||
))}
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-lg font-semibold">
|
||||
@@ -819,10 +818,10 @@ export default function InvestmentPath(path: Path) {
|
||||
Anexar ou conferir no Balcão
|
||||
</Link>
|
||||
</section>
|
||||
<section className="space-y-3 rounded-xl border p-4">
|
||||
<h2 className="text-lg font-semibold">
|
||||
<details className="space-y-3 rounded-xl border p-4">
|
||||
<summary className="cursor-pointer text-lg font-semibold">
|
||||
Acompanhamento interno
|
||||
</h2>
|
||||
</summary>
|
||||
{path.canWrite && (
|
||||
<form
|
||||
className="grid min-w-0 gap-3 [&_input]:max-w-full [&_input]:min-w-0 [&_label]:min-w-0 [&_select]:max-w-full [&_select]:min-w-0"
|
||||
@@ -983,7 +982,7 @@ export default function InvestmentPath(path: Path) {
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
</details>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {ProactiveInvestmentEditor,type ProactiveAnalysis,type ProactiveOptions} from '@/components/proactive-investment';
|
||||
import {ProactiveInvestmentEditor,newProactive,type ProactiveAnalysis,type ProactiveOptions} from '@/components/proactive-investment';
|
||||
import { ClassificationReview } from '@/components/opportunity-classification';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { valueText } from '@/lib/value-text';
|
||||
@@ -140,18 +140,21 @@ export default function OpportunityDraft({
|
||||
auth: { user: { id: number } };
|
||||
canEditDraft?: boolean;
|
||||
}>().props;
|
||||
const proactiveEntryUrl=usePage().url;
|
||||
const uniquePromoterContext=profileAccess?.contexts.length===1?profileAccess.contexts[0]:undefined;
|
||||
const [data, setData] = useState<Values>({
|
||||
...values,
|
||||
...(!record && !values.proactive && new URLSearchParams(proactiveEntryUrl.split('?')[1]??'').get('analysis')==='proactive' ? {proactive:newProactive()} : {}),
|
||||
...(profileMode
|
||||
? {
|
||||
organization_id: record
|
||||
? (profileOrganization ?? null)
|
||||
: profileAccess?.internalPromoter
|
||||
? null
|
||||
: (profileAccess?.contexts[0]?.organization_id ?? null),
|
||||
: (uniquePromoterContext?.organization_id ?? null),
|
||||
opportunity_category:
|
||||
values.opportunity_category ??
|
||||
profileAccess?.contexts[0]?.type ??
|
||||
uniquePromoterContext?.type ??
|
||||
'',
|
||||
}
|
||||
: {}),
|
||||
@@ -171,10 +174,11 @@ export default function OpportunityDraft({
|
||||
const unavailable = Boolean(
|
||||
record?.deleted_at || record?.status === 'archived',
|
||||
);
|
||||
const hasCanonicalPreparation = profileMode && canonicalOptions && Boolean(data.opportunity_category) && !data.proactive;
|
||||
const archiveAvailable = Boolean(usePage().props.opportunityManagement);
|
||||
const set = (key: string, value: string) =>
|
||||
setData((d) => ({ ...d, [key]: value }));
|
||||
async function send(action: 'save' | 'delete' | 'archive' | 'restore') {
|
||||
async function send(action: 'save' | 'delete' | 'archive' | 'restore', resourcesGroup?: string) {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setErrors({});
|
||||
@@ -222,8 +226,10 @@ export default function OpportunityDraft({
|
||||
}
|
||||
setMessage(result.message);
|
||||
if (result.etag) setToken(result.etag);
|
||||
if (!record) router.visit(`${basePath}/${result.id}/edit`);
|
||||
if (resourcesGroup) router.visit(`${basePath}/${record?.id ?? result.id}/resources?return_group=${encodeURIComponent(resourcesGroup)}`);
|
||||
else if (!record) router.visit(`${basePath}/${result.id}/edit${window.location.hash.startsWith('#fill-') ? window.location.hash : ''}`);
|
||||
else if (action !== 'save') router.reload();
|
||||
else if (profileMode) router.reload({only:['canonicalResponse','etag','history','workflowState','profileContext']});
|
||||
} catch {
|
||||
setMessage(
|
||||
'Resposta indisponível. Os dados foram preservados; confira o registo no servidor antes de repetir.',
|
||||
@@ -235,10 +241,8 @@ export default function OpportunityDraft({
|
||||
document.querySelector<HTMLSelectElement>(
|
||||
'[data-association-index][aria-invalid="true"]',
|
||||
);
|
||||
(
|
||||
invalidAssociation ??
|
||||
document.getElementById('opportunity-result')
|
||||
)?.focus();
|
||||
if (invalidAssociation) invalidAssociation.focus();
|
||||
else document.getElementById('opportunity-result')?.focus({preventScroll:true});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -250,9 +254,7 @@ export default function OpportunityDraft({
|
||||
: 'Nova oportunidade'
|
||||
}
|
||||
>
|
||||
<Link href={basePath}>
|
||||
{profileMode ? 'Minhas oportunidades' : 'Voltar à gestão'}
|
||||
</Link>
|
||||
{!profileMode && <Link href={basePath}>Voltar à gestão</Link>}
|
||||
{promotionHref && <Link className="ml-3 underline" href={promotionHref}>Divulgação promocional — Em preparação</Link>}
|
||||
{!!profileContext?.corridor_agribusiness && (
|
||||
<section className="my-4 space-y-2 rounded border p-4">
|
||||
@@ -271,11 +273,11 @@ export default function OpportunityDraft({
|
||||
</Link>
|
||||
)}
|
||||
{profileMode && (
|
||||
<section
|
||||
aria-label="Âmbito desta entrega"
|
||||
<details
|
||||
aria-label="Disponibilidade por modalidade"
|
||||
className="rounded border p-3"
|
||||
>
|
||||
<h2>Âmbito desta entrega</h2>
|
||||
<summary className="cursor-pointer font-medium">Modalidades disponíveis e condições de submissão</summary>
|
||||
<p>
|
||||
Seis categorias base: projeto de investimento,
|
||||
imobiliário, fundiário, venda de negócio, parceria e
|
||||
@@ -304,7 +306,7 @@ export default function OpportunityDraft({
|
||||
certifica a viabilidade, a titularidade ou a decisão
|
||||
externa de cada caso.
|
||||
</p>
|
||||
</section>
|
||||
</details>
|
||||
)}
|
||||
{profileMode && record && (
|
||||
<ClassificationReview id={record.id} refreshToken={token} />
|
||||
@@ -334,8 +336,8 @@ export default function OpportunityDraft({
|
||||
}));
|
||||
}}
|
||||
>
|
||||
{profileAccess?.internalPromoter && (
|
||||
<option value="">
|
||||
{(profileAccess?.internalPromoter || !uniquePromoterContext) && (
|
||||
<option value="|">
|
||||
Selecionar o promotor real da oportunidade
|
||||
</option>
|
||||
)}
|
||||
@@ -485,7 +487,7 @@ export default function OpportunityDraft({
|
||||
<p>Seleccione apenas o nível territorial conhecido; não exige coordenadas, montante ou promotor.</p>
|
||||
{(['province_id','district_id','admin_post_id','locality_id']as const).map((key,index)=><TerritoryLevel key={`proactive-${key}-${path[index-1]?.id??''}`} index={index} parent={path[index-1]?.id??''} selected={path[index]} endpoint="/minhas-oportunidades/territory-options" fieldError={errors[key]} onChange={value=>{const next=[...path.slice(0,index),...(value?[value]:[])];setPath(next);setData(d=>({...d,province_id:next[0]?.id??'',district_id:next[1]?.id??'',admin_post_id:next[2]?.id??'',locality_id:next[3]?.id??''}));}}/>)}
|
||||
</fieldset>}
|
||||
<fieldset disabled={busy || readOnly || unavailable}><ProactiveInvestmentEditor value={data.proactive as ProactiveAnalysis|undefined} onChange={v=>setData(d=>({...d,proactive:v}))} options={proactiveOptions} history={proactiveHistory}/></fieldset>
|
||||
<fieldset disabled={busy || readOnly || unavailable}><ProactiveInvestmentEditor value={data.proactive as ProactiveAnalysis|undefined} onChange={v=>setData(d=>({...d,proactive:v}))} options={proactiveOptions} history={proactiveHistory} territoryId={path.at(-1)?.id} recordId={record?.id}/></fieldset>
|
||||
{!profileMode && (
|
||||
<fieldset
|
||||
disabled={busy || readOnly || unavailable}
|
||||
@@ -821,7 +823,7 @@ export default function OpportunityDraft({
|
||||
)}
|
||||
{!readOnly && (
|
||||
<>
|
||||
<Field
|
||||
{!hasCanonicalPreparation && <Field
|
||||
label="Motivo da alteração"
|
||||
error={errors.reason}
|
||||
>
|
||||
@@ -832,8 +834,8 @@ export default function OpportunityDraft({
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
/>
|
||||
</Field>
|
||||
{!unavailable && (
|
||||
</Field>}
|
||||
{!unavailable && !hasCanonicalPreparation && (
|
||||
<button className={button} disabled={busy}>
|
||||
Guardar rascunho
|
||||
</button>
|
||||
@@ -891,7 +893,7 @@ export default function OpportunityDraft({
|
||||
</>
|
||||
)}
|
||||
</form>
|
||||
{record && (
|
||||
{record && (!profileMode || readOnly || unavailable || !canonicalOptions || !data.opportunity_category) && (
|
||||
<Link
|
||||
href={
|
||||
resourcesInstalled
|
||||
@@ -909,10 +911,10 @@ export default function OpportunityDraft({
|
||||
Associações territoriais e produtivas existentes
|
||||
</Link>
|
||||
)}
|
||||
{profileMode && canonicalOptions && (
|
||||
{profileMode && canonicalOptions && Boolean(data.opportunity_category) && (
|
||||
<section>
|
||||
{record && !readOnly && !unavailable && (
|
||||
<OpportunityContactForm
|
||||
<details><summary className="cursor-pointer font-medium">Acrescentar um contacto à oportunidade</summary><OpportunityContactForm
|
||||
id={record.id}
|
||||
etag={token ?? ''}
|
||||
organization={
|
||||
@@ -938,7 +940,7 @@ export default function OpportunityDraft({
|
||||
},
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
/></details>
|
||||
)}
|
||||
<OpportunityCanonicalFields
|
||||
value={
|
||||
@@ -960,6 +962,7 @@ export default function OpportunityDraft({
|
||||
],
|
||||
}}
|
||||
errors={errors}
|
||||
missingPaths={canonicalResponse?.completion.missing_paths}
|
||||
category={valueText(data.opportunity_category ?? '')}
|
||||
organization={
|
||||
(data.organization_id ?? null) as string | null
|
||||
@@ -967,16 +970,23 @@ export default function OpportunityDraft({
|
||||
actorId={auth.user.id}
|
||||
sectors={sectors}
|
||||
disabled={busy || readOnly || unavailable}
|
||||
onOpenResources={!readOnly && !unavailable && resourcesInstalled ? (group) => void send('save',group) : undefined}
|
||||
/>
|
||||
{!readOnly && !unavailable && (
|
||||
{!readOnly && !unavailable && hasCanonicalPreparation && (
|
||||
<div className="sticky bottom-0 space-y-3 rounded border bg-background p-4 shadow-sm">
|
||||
<Field label="O que alterou nesta preparação" error={errors.reason}>
|
||||
<textarea className={control} value={reason} onChange={(event) => setReason(event.target.value)} minLength={20} maxLength={1000} />
|
||||
</Field>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => void send('save')}
|
||||
>
|
||||
Guardar contrato no rascunho
|
||||
Guardar preparação
|
||||
</button>
|
||||
<p className="text-sm">Pode guardar incompleto e continuar mais tarde em Minhas oportunidades.</p>
|
||||
</div>
|
||||
)}
|
||||
{Object.entries(errors)
|
||||
.filter(([key]) => key.startsWith('canonical'))
|
||||
|
||||
@@ -179,6 +179,8 @@ export default function OpportunityResources({
|
||||
readOnly?: boolean;
|
||||
countries?: { code: string; name: string }[];
|
||||
}>().props;
|
||||
const returnGroup = new URLSearchParams(usePage().url.split('?')[1] ?? '').get('return_group');
|
||||
const returnHash = ['territory', 'evidence'].includes(returnGroup ?? '') ? `#fill-${returnGroup}` : '#fill-evidence';
|
||||
const [kind, setKind] = useState<Kind>('locations');
|
||||
const [editing, setEditing] = useState<Resource | null>(null);
|
||||
const [payload, setPayload] = useState<Payload>({ country_code: 'MZ' });
|
||||
@@ -307,7 +309,7 @@ export default function OpportunityResources({
|
||||
!!opportunity.deleted_at || opportunity.status === 'archived';
|
||||
return (
|
||||
<Management title="Imagens, documentos e localizações">
|
||||
<Link href={`${basePath}/${opportunity.id}/edit`}>
|
||||
<Link href={`${basePath}/${opportunity.id}/edit${returnHash}`}>
|
||||
Regressar ao rascunho #{opportunity.id}
|
||||
</Link>
|
||||
<p>
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { Head, Link, router } from '@inertiajs/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { PortalMenu } from '@/layouts/portal-navigation';
|
||||
import { fiscalForms, fiscalFormFields, fiscalPreparationIssues, newFiscalPreparation, readFiscalPreparation, type FiscalFormKind, type FiscalPreparation } from '@/lib/fiscal-form-preparation';
|
||||
|
||||
const input = 'mt-1 block w-full rounded border border-slate-400 bg-white p-3 text-slate-900';
|
||||
const button = 'rounded border border-emerald-800 px-4 py-3 font-semibold text-emerald-900 disabled:opacity-50';
|
||||
export default function FiscalForms({ initialTax = 'iva' }: { initialTax?: FiscalFormKind }) {
|
||||
const [kind, setKind] = useState<FiscalFormKind>(initialTax);
|
||||
const [drafts, setDrafts] = useState({ iva: newFiscalPreparation('iva'), irpc: newFiscalPreparation('irpc') });
|
||||
const [step, setStep] = useState(0);
|
||||
const [notice, setNotice] = useState('');
|
||||
const [pending, setPending] = useState<FiscalPreparation | null>(null);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const p = drafts[kind], source = fiscalForms[kind], fields = fiscalFormFields(kind);
|
||||
const issues = fiscalPreparationIssues(p);
|
||||
useEffect(() => {
|
||||
setKind(initialTax);
|
||||
}, [initialTax]);
|
||||
useEffect(() => {
|
||||
const warn = (e: BeforeUnloadEvent) => { if (dirty) { e.preventDefault(); e.returnValue = ''; } };
|
||||
window.addEventListener('beforeunload', warn);
|
||||
const unsubscribe = router.on('before', e => {
|
||||
if (dirty && !window.confirm('Os campos estão apenas nesta página. Guarde o ficheiro para continuar depois. Pretende sair?')) e.preventDefault();
|
||||
});
|
||||
return () => { window.removeEventListener('beforeunload', warn); unsubscribe(); };
|
||||
}, [dirty]);
|
||||
function patch(update: Partial<FiscalPreparation>) {
|
||||
setDrafts(d => ({ ...d, [kind]: { ...d[kind], ...update } }));
|
||||
setDirty(true); setNotice('');
|
||||
}
|
||||
function download() {
|
||||
const url = URL.createObjectURL(new Blob([JSON.stringify(p)], { type: 'application/json' }));
|
||||
const a = document.createElement('a'); a.href = url; a.download = `investmoz-preparacao-${kind}.json`; a.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
setNotice('Ficheiro de preparação gerado. Guarde-o para recuperar os campos. Não foi enviado ao portal nem à AT.');
|
||||
// Other tax preparation may still contain unsaved edits.
|
||||
}
|
||||
return <div className="min-h-screen bg-slate-50 text-slate-900">
|
||||
<Head title="Preencher formulário fiscal" />
|
||||
<div className="print:hidden"><PortalMenu /></div>
|
||||
<main className="mx-auto max-w-5xl space-y-6 px-5 py-8">
|
||||
<div className="print:hidden"><Link href="/documentos" className="underline">Documentos e Formulários</Link></div>
|
||||
<h1 className="text-3xl font-bold">Preencher formulário fiscal</h1>
|
||||
<p>Prepare os valores de IVA ou IRPC, confira e guarde um ficheiro para continuar depois. Os campos vazios significam informação em falta.</p>
|
||||
<p className="rounded border border-amber-600 bg-amber-50 p-3">Preparação para conferência, sem submissão à Autoridade Tributária. Os valores são introduzidos por si; não há apuramento automático nem confirmação de elegibilidade de deduções.</p>
|
||||
<label className="block max-w-lg print:hidden">Formulário
|
||||
<select className={input} value={kind} onChange={e => { setKind(e.target.value as FiscalFormKind); setStep(0); setNotice(''); setPending(null); }}>
|
||||
<option value="iva">IVA — Modelo A</option><option value="irpc">IRPC — Modelo 22</option>
|
||||
</select>
|
||||
</label>
|
||||
<h2 className="text-xl font-bold">{source.title}</h2>
|
||||
<p>{source.coverage}</p>
|
||||
<nav aria-label="Etapas de preenchimento" className="flex flex-wrap gap-2 print:hidden">
|
||||
{['Identificação e período', 'Preencher valores', 'Conferir e guardar'].map((label, n) => <button type="button" key={label} className={button} aria-current={step === n ? 'step' : undefined} onClick={() => setStep(n)}>{n + 1}. {label}</button>)}
|
||||
</nav>
|
||||
<form onSubmit={e => e.preventDefault()} className="space-y-5">
|
||||
<fieldset className={`${step !== 0 ? 'hidden print:block' : ''} space-y-4 rounded border bg-white p-5`}>
|
||||
<legend className="font-bold">Identificação e período</legend>
|
||||
<label className="block">Nome ou designação social<input className={input} autoComplete="organization" maxLength={5000} value={p.name} onChange={e => patch({ name: e.target.value })} /></label>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<label>NUIT<input className={input} inputMode="numeric" maxLength={9} value={p.nuit} onChange={e => patch({ nuit: e.target.value })} /></label>
|
||||
<label>{kind === 'iva' ? 'Período — ano e mês' : 'Exercício — ano'}<input className={input} type={kind === 'iva' ? 'month' : 'text'} inputMode={kind === 'irpc' ? 'numeric' : undefined} placeholder={kind === 'iva' ? 'AAAA-MM' : 'AAAA'} maxLength={7} value={p.period} onChange={e => patch({ period: e.target.value })} /></label>
|
||||
</div>
|
||||
<p className="text-sm">Dados mantidos apenas nesta página até descarregar o ficheiro. Não há gravação automática. Guarde antes de sair ou actualizar.</p>
|
||||
</fieldset>
|
||||
<fieldset className={`${step !== 1 ? 'hidden print:block' : ''} space-y-4 rounded border bg-white p-5`}>
|
||||
<legend className="font-bold">Valores em meticais (MZN)</legend>
|
||||
<p>Sem separador de milhares; vírgula ou ponto para os cêntimos. Não preencha zero quando desconhece o valor.</p>
|
||||
{kind === 'irpc' && <p>Crédito económico (303) e internacional (304) são distintos. Não utilize a mesma parcela nos dois campos. Esta preparação manual não verifica as parcelas; conserve o suporte para conferência.</p>}
|
||||
<div className="grid gap-5 sm:grid-cols-2">{fields.map(f => <div key={f.code} className="break-inside-avoid">
|
||||
<label className="block">{f.code} — {f.label}<input className={input} inputMode="decimal" maxLength={100} value={p.values[f.code] ?? ''} onChange={e => patch({ values: { ...p.values, [f.code]: e.target.value } })} /></label>
|
||||
<details className="mt-1 text-sm print:hidden"><summary className="cursor-pointer underline">Orientação do campo</summary><p>{f.guidance}</p></details>
|
||||
</div>)}</div>
|
||||
</fieldset>
|
||||
<section className={`${step !== 2 ? 'hidden print:block' : ''} space-y-4 rounded border bg-white p-5`} aria-label="Conferir e guardar">
|
||||
<h3 className="font-bold">Conferência da preparação</h3>
|
||||
<p>{fields.filter(f => (p.values[f.code] ?? '') !== '').length} de {fields.length} campos com valor. Campos vazios não foram convertidos em zero.</p>
|
||||
{issues.length > 0 ? <div><p>Por conferir — pode guardar a preparação incompleta:</p><ul className="list-disc pl-6">{issues.map(i => <li key={i}>{i}</li>)}</ul></div> : <p>Formato dos campos conferido. Os montantes e a aplicação fiscal ainda devem ser conferidos.</p>}
|
||||
<dl className="grid gap-3 sm:grid-cols-2 print:hidden">{fields.filter(f => (p.values[f.code] ?? '') !== '').map(f => <div key={f.code}><dt>{f.code} — {f.label}</dt><dd className="font-semibold">{p.values[f.code]} MZN</dd></div>)}</dl>
|
||||
<label className="block">Notas e referências dos valores<textarea className={input} rows={4} maxLength={5000} value={p.notes} onChange={e => patch({ notes: e.target.value })} /></label>
|
||||
<div className="flex flex-wrap gap-3 print:hidden"><button type="button" className={button} onClick={download}>Guardar ficheiro para continuar</button><button type="button" className={button} onClick={() => window.print()}>Imprimir preparação</button></div>
|
||||
<p className="text-sm">O ficheiro contém os dados introduzidos. Guarde-o num local privado. Não fica associado automaticamente ao dossier.</p>
|
||||
</section>
|
||||
<div className="flex justify-between gap-3 print:hidden"><button type="button" className={button} disabled={step === 0} onClick={() => setStep(step - 1)}>Anterior</button><button type="button" className={button} disabled={step === 2} onClick={() => setStep(step + 1)}>Continuar</button></div>
|
||||
</form>
|
||||
<section className="space-y-3 rounded border p-4 print:hidden" aria-label="Recuperar preparação">
|
||||
<label className="block">Recuperar ficheiro guardado<input className={input} type="file" accept=".json,application/json" onChange={async e => {
|
||||
const file = e.target.files?.[0]; e.target.value = ''; if (!file) return;
|
||||
try { if (file.size > 100_000) throw new Error('O ficheiro é demasiado grande.'); setPending(readFiscalPreparation(await file.text())); setNotice('Ficheiro lido. Confirme a recuperação abaixo.'); }
|
||||
catch (error) { setPending(null); setNotice(error instanceof Error ? error.message : 'Não foi possível ler o ficheiro. Os campos actuais foram preservados.'); }
|
||||
}} /></label>
|
||||
{pending && <div className="space-y-2"><p>Recuperar {fiscalForms[pending.kind].title}, período {pending.period || 'por indicar'}? Substitui apenas os campos desse formulário nesta página.</p><button type="button" className={button} onClick={() => { setDrafts(d => ({ ...d, [pending.kind]: pending })); setKind(pending.kind); setStep(2); setPending(null); setDirty(true); setNotice('Preparação recuperada.'); }}>Confirmar recuperação</button> <button type="button" className={button} onClick={() => setPending(null)}>Cancelar</button></div>}
|
||||
</section>
|
||||
{notice && <p role="status" className="rounded border p-3">{notice}</p>}
|
||||
<details className="rounded border p-4"><summary className="cursor-pointer font-semibold">Exemplar e cobertura</summary><p>{source.source}</p><p className="break-all text-sm">SHA256: {source.hash}</p><p>{source.coverage}</p><p>Os cálculos e correspondências já disponíveis no simulador permanecem separados desta introdução manual. Não se executam fórmulas nem se transportam valores entre edições automaticamente.</p></details>
|
||||
<div className="flex flex-wrap gap-4 print:hidden"><Link href="/simulador-fiscal" className="underline">Consultar cálculos e preparação M20/M22 no simulador</Link><Link href="/legislacao" className="underline">Consultar legislação</Link></div>
|
||||
</main>
|
||||
</div>;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { PublicSectorCards } from '@/components/public-sector-cards';
|
||||
import { documentFacetLabel } from '@/lib/document-facet-label';
|
||||
import { PORTAL_MORE_LINK } from '@/lib/portal-presentation';
|
||||
import {
|
||||
PublicDocumentContent,
|
||||
@@ -537,6 +538,15 @@ export default function Services(p: Props) {
|
||||
opportunities={p.opportunities}
|
||||
/>
|
||||
)}
|
||||
{p.section === 'documents' && <section aria-label="Preencher formulários fiscais" className="space-y-3 rounded-xl border bg-white p-5">
|
||||
<h2 className="text-xl font-bold">Que formulário pretende preencher?</h2>
|
||||
<p>Abra os campos do formulário fiscal. A legislação e os guias de consulta ficam abaixo.</p>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Link className={button} href="/formularios/fiscais?imposto=iva">Preencher IVA — Modelo A</Link>
|
||||
<Link className={button} href="/formularios/fiscais?imposto=irpc">Preparar IRPC — Modelo 22</Link>
|
||||
</div>
|
||||
<p className="text-sm">Preparação manual, com gravação em ficheiro. Cobertura parcial de IRPC; sem submissão à AT.</p>
|
||||
</section>}
|
||||
{['procedures', 'documents', 'legislation'].includes(
|
||||
p.section,
|
||||
) && <JourneyDocumentResources stages={p.stages} />}
|
||||
@@ -579,7 +589,7 @@ export default function Services(p: Props) {
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{p.topics?.map((topic) => (
|
||||
<option key={topic}>{topic}</option>
|
||||
<option key={topic} value={topic}>{documentFacetLabel(topic)}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
@@ -606,7 +616,7 @@ export default function Services(p: Props) {
|
||||
value={category}
|
||||
>
|
||||
{documentTypeLabels[category] ??
|
||||
category}
|
||||
documentFacetLabel(category)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -809,8 +819,8 @@ export default function Services(p: Props) {
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{p.languages?.map((language) => (
|
||||
<option key={language}>
|
||||
{language}
|
||||
<option key={language} value={language}>
|
||||
{documentFacetLabel(language)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -917,7 +927,7 @@ export default function Services(p: Props) {
|
||||
className="rounded-full border bg-white px-3 py-1 underline"
|
||||
href={`${p.section === 'documents' ? '/documentos' : '/legislacao'}?${new URLSearchParams({ topic }).toString()}`}
|
||||
>
|
||||
{topic}
|
||||
{documentFacetLabel(topic)}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
@@ -11,6 +11,7 @@ import { Management } from '../management/shared';
|
||||
import { Layout, Field, control, button, labels, kind } from './shared';
|
||||
import type { Dossier } from './shared';
|
||||
import InvestmentComplements, { type ComplementOption } from '@/components/investment-complements';
|
||||
import ClusterCompetitivenessPublic, { type ApprovedCompetitiveness } from '@/components/cluster-competitiveness-public';
|
||||
export default function Show(props: Props) {
|
||||
return (
|
||||
<Editor
|
||||
@@ -21,6 +22,7 @@ export default function Show(props: Props) {
|
||||
}
|
||||
|
||||
type Props = {
|
||||
competitiveness?: ApprovedCompetitiveness | null;
|
||||
complements?: ComplementOption[];
|
||||
geography: StructureGeography;
|
||||
existingSubmissions?: { id: string; version: number; updated_at: string }[];
|
||||
@@ -54,6 +56,7 @@ type Props = {
|
||||
};
|
||||
|
||||
function Editor({
|
||||
competitiveness,
|
||||
complements = [],
|
||||
record,
|
||||
related,
|
||||
@@ -94,6 +97,7 @@ function Editor({
|
||||
{kind(record)} · {record.content.code}
|
||||
</p>
|
||||
<p className="text-sm">Fonte: {record.source}</p>
|
||||
{competitiveness && <ClusterCompetitivenessPublic analysis={competitiveness} />}
|
||||
{!management && (
|
||||
<div className="space-y-2 rounded-xl border p-4">
|
||||
<Link className="underline" href={portfolioPreparationHref(record.id, pageUrl)}>
|
||||
|
||||
@@ -4,6 +4,11 @@ import { useState } from 'react';
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import { profileJson } from '@/lib/profile-json';
|
||||
import { button, control } from '@/pages/management/shared';
|
||||
import { modalityLabels } from '@/components/opportunity-search-filters';
|
||||
import ProfileProofPicker from '@/components/profile-proof-picker';
|
||||
|
||||
const representations: Record<string,string> = {individual:'Em nome próprio',company:'Empresa',public_entity:'Entidade pública',association:'Associação',partner:'Parceiro ou representante'};
|
||||
const requestStates: Record<string,string> = {pending:'Em análise',approved:'Aprovado',rejected:'Devolvido ou recusado',cancelled:'Cancelado'};
|
||||
|
||||
type RequestEntry = {
|
||||
id: string;
|
||||
@@ -67,9 +72,8 @@ export default function RequestProfile({
|
||||
Solicitar perfil de Promotor
|
||||
</h1>
|
||||
<p>
|
||||
A aprovação confirma identidade, representação e comprovativos.
|
||||
Só os tipos aprovados ficam disponíveis; o pedido não ativa o
|
||||
perfil.
|
||||
Indique em nome de quem vai actuar, as modalidades que pretende preparar e os comprovativos do pedido.
|
||||
Pode acompanhar a decisão nesta página. A submissão do pedido não activa o perfil.
|
||||
</p>
|
||||
<form
|
||||
className="max-w-2xl space-y-4"
|
||||
@@ -79,7 +83,7 @@ export default function RequestProfile({
|
||||
}}
|
||||
>
|
||||
<label className="block">
|
||||
Representação
|
||||
Em nome de quem vai actuar?
|
||||
<select
|
||||
className={control}
|
||||
value={representation}
|
||||
@@ -92,7 +96,7 @@ export default function RequestProfile({
|
||||
'association',
|
||||
'partner',
|
||||
].map((v) => (
|
||||
<option key={v}>{v}</option>
|
||||
<option key={v} value={v}>{representations[v]}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
@@ -115,9 +119,10 @@ export default function RequestProfile({
|
||||
</label>
|
||||
)}
|
||||
<fieldset>
|
||||
<legend>Tipos pretendidos</legend>
|
||||
<legend>Que oportunidades pretende preparar?</legend>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{types.map((type) => (
|
||||
<label key={type} className="block">
|
||||
<label key={type} className="flex gap-2 rounded border p-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selected.includes(type)}
|
||||
@@ -125,23 +130,12 @@ export default function RequestProfile({
|
||||
setSelected(toggle(selected, type))
|
||||
}
|
||||
/>{' '}
|
||||
{type}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>Comprovativos próprios analisados</legend>
|
||||
{documents.map((d) => (
|
||||
<label key={d.id} className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={proofs.includes(d.id)}
|
||||
onChange={() => setProofs(toggle(proofs, d.id))}
|
||||
/>{' '}
|
||||
{d.file_name}
|
||||
{modalityLabels[type] ?? 'Outra modalidade'}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
<ProfileProofPicker documents={documents} value={proofs} onChange={setProofs} disabled={busy} />
|
||||
{!documents.length && (
|
||||
<p>
|
||||
Sem comprovativos próprios disponíveis. Pode anexar ao
|
||||
@@ -156,7 +150,7 @@ export default function RequestProfile({
|
||||
</p>
|
||||
)}
|
||||
<label className="block">
|
||||
Fundamentação
|
||||
Explique o seu pedido
|
||||
<textarea
|
||||
required
|
||||
minLength={20}
|
||||
@@ -180,7 +174,7 @@ export default function RequestProfile({
|
||||
{requests.map((r) => (
|
||||
<article key={r.id} className="border-b py-3">
|
||||
<p>
|
||||
{r.id} — {r.status}
|
||||
Pedido de {new Date(r.created_at).toLocaleDateString('pt-MZ')} — {requestStates[r.status] ?? 'Estado por consultar'}
|
||||
</p>
|
||||
<p>
|
||||
{r.decision_reason ??
|
||||
|
||||
@@ -0,0 +1,501 @@
|
||||
import { useState } from 'react';
|
||||
import { portalRequest, PortalApiError } from '@/lib/portal-api';
|
||||
import {
|
||||
assessmentReady,
|
||||
diagnosticReady,
|
||||
forceLabels,
|
||||
forces,
|
||||
newCompetitivenessDraft,
|
||||
readCompetitivenessDraft,
|
||||
} from '@/lib/cluster-competitiveness';
|
||||
import type {
|
||||
Assessment,
|
||||
CompetitivenessDraft,
|
||||
Force,
|
||||
} from '@/lib/cluster-competitiveness';
|
||||
import { button, control } from '../management/shared';
|
||||
|
||||
const labels = {
|
||||
evidence: 'Observações e evidências locais',
|
||||
source: 'Fonte e referência recuperável (documento, página ou endereço)',
|
||||
period: 'Período dos dados e data da consulta',
|
||||
rationale: 'Justificação da pressão atribuída',
|
||||
limitations: 'Limitações, cobertura e pressupostos',
|
||||
opportunity: 'Oportunidade de investimento e fundamento',
|
||||
} as const;
|
||||
|
||||
export type CompetitivenessState = {
|
||||
version: number;
|
||||
draft: CompetitivenessDraft | null;
|
||||
approved: {
|
||||
draft: CompetitivenessDraft;
|
||||
version: number;
|
||||
at: string;
|
||||
} | null;
|
||||
history: { version: number; action: string; at: string; actor: number }[];
|
||||
};
|
||||
const actions: Record<string, string> = {
|
||||
saved: 'Gravação',
|
||||
approved: 'Aprovação pública',
|
||||
withdrawn: 'Retirada da aprovação',
|
||||
restored: 'Recuperação do histórico',
|
||||
};
|
||||
|
||||
export default function Competitiveness({
|
||||
clusterId,
|
||||
sector,
|
||||
initial,
|
||||
}: {
|
||||
clusterId: string;
|
||||
sector: string;
|
||||
initial?: CompetitivenessState | null;
|
||||
}) {
|
||||
const [draft, setDraft] = useState(
|
||||
() => initial?.draft ?? newCompetitivenessDraft(clusterId, sector),
|
||||
);
|
||||
const [server, setServer] = useState<CompetitivenessState>(
|
||||
initial ?? { version: 0, draft: null, approved: null, history: [] },
|
||||
);
|
||||
const [serverPending, setServerPending] =
|
||||
useState<CompetitivenessState | null>(null);
|
||||
const [restoreVersion, setRestoreVersion] = useState<number | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [reason, setReason] = useState('');
|
||||
const [pending, setPending] = useState<CompetitivenessDraft | null>(null);
|
||||
const [message, setMessage] = useState('');
|
||||
const dirty =
|
||||
JSON.stringify(draft) !==
|
||||
JSON.stringify(
|
||||
server.draft ?? newCompetitivenessDraft(clusterId, sector),
|
||||
);
|
||||
const endpoint = `/management/clusters/${clusterId}/competitiveness`;
|
||||
function errorMessage(error: unknown) {
|
||||
if (error instanceof PortalApiError) {
|
||||
if (error.status === 409)
|
||||
return 'Conflito de versão. Os campos actuais foram conservados. Transfira o rascunho e consulte a versão do servidor antes de reconciliar.';
|
||||
if ([401, 403, 419].includes(error.status))
|
||||
return 'Sessão ou permissão indisponível. Os campos foram conservados; transfira o rascunho antes de autenticar-se novamente.';
|
||||
if (error.status === 422)
|
||||
return (
|
||||
Object.values(error.errors).flat().join(' ') ||
|
||||
error.message
|
||||
);
|
||||
}
|
||||
return 'Não foi possível concluir a operação; os campos actuais foram conservados.';
|
||||
}
|
||||
function apply(state: CompetitivenessState) {
|
||||
setServer(state);
|
||||
setDraft(state.draft ?? newCompetitivenessDraft(clusterId, sector));
|
||||
setPending(null);
|
||||
setServerPending(null);
|
||||
setRestoreVersion(null);
|
||||
}
|
||||
async function command(
|
||||
action: string,
|
||||
extra: Record<string, unknown> = {},
|
||||
) {
|
||||
setBusy(true);
|
||||
try {
|
||||
const state = await portalRequest<CompetitivenessState>(
|
||||
`${endpoint}/${action}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
expected_version: server.version,
|
||||
...extra,
|
||||
}),
|
||||
},
|
||||
);
|
||||
apply(state);
|
||||
setMessage(
|
||||
`${actions[action]} concluída no servidor. Versão ${state.version}.`,
|
||||
);
|
||||
} catch (error) {
|
||||
setMessage(errorMessage(error));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
function change(force: Force, field: keyof Assessment, value: string) {
|
||||
setDraft((previous) => ({
|
||||
...previous,
|
||||
forces: {
|
||||
...previous.forces,
|
||||
[force]: { ...previous.forces[force], [field]: value },
|
||||
},
|
||||
}));
|
||||
}
|
||||
function download() {
|
||||
const url = URL.createObjectURL(
|
||||
new Blob([JSON.stringify(draft, null, 2)], {
|
||||
type: 'application/json',
|
||||
}),
|
||||
);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `competitividade-${clusterId}.json`;
|
||||
link.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
setMessage(
|
||||
'Ficheiro preparado para transferência. Conserve-o para recuperar a análise.',
|
||||
);
|
||||
}
|
||||
return (
|
||||
<section
|
||||
className="max-w-3xl space-y-4 rounded border p-4"
|
||||
aria-label="Diagnóstico de competitividade"
|
||||
>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Competitividade — cinco forças de Porter
|
||||
</h2>
|
||||
<p>
|
||||
Análise qualitativa por sector e região ligada a este cluster.
|
||||
Descreva as evidências e justifique cada pressão; não existe
|
||||
pontuação automática nem média entre forças.
|
||||
</p>
|
||||
<p>
|
||||
Guarde o rascunho para o recuperar no servidor. A publicação
|
||||
exige aprovação expressa; a classificação representa a
|
||||
apreciação do autor.
|
||||
</p>
|
||||
<p role="status">
|
||||
Versão no servidor: {server.version}.{' '}
|
||||
{dirty
|
||||
? 'Existem alterações por guardar.'
|
||||
: 'Campos correspondem à versão recuperada.'}{' '}
|
||||
{server.approved
|
||||
? `Consulta pública: versão aprovada ${server.approved.version}; novas edições conservam essa versão até outra aprovação.`
|
||||
: 'Sem análise aprovada para consulta pública.'}
|
||||
</p>
|
||||
<fieldset disabled={busy} className="space-y-4">
|
||||
<label className="block">
|
||||
Sector analisado
|
||||
<input
|
||||
className={control}
|
||||
maxLength={200}
|
||||
value={draft.sector}
|
||||
onChange={(e) =>
|
||||
setDraft({ ...draft, sector: e.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
{draft.sector !== sector && (
|
||||
<p>
|
||||
O sector da análise difere do sector actual do cluster (
|
||||
{sector}). Confira o âmbito antes de reutilizar
|
||||
conclusões.
|
||||
</p>
|
||||
)}
|
||||
<label className="block">
|
||||
Região / província / distrito e abrangência
|
||||
<input
|
||||
className={control}
|
||||
maxLength={1000}
|
||||
value={draft.region}
|
||||
onChange={(e) =>
|
||||
setDraft({ ...draft, region: e.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<p role="status">
|
||||
{diagnosticReady(draft)
|
||||
? 'Cinco forças preenchidas para revisão; fontes e conclusões requerem leitura do autor.'
|
||||
: 'Diagnóstico incompleto: indique o âmbito e complete as evidências das cinco forças.'}
|
||||
</p>
|
||||
{forces.map((force) => (
|
||||
<details key={force} className="rounded border p-3">
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
{forceLabels[force]} ·{' '}
|
||||
{assessmentReady(draft.forces[force])
|
||||
? 'Preenchida para revisão'
|
||||
: 'Indeterminada / incompleta'}
|
||||
</summary>
|
||||
<div className="space-y-3 pt-3">
|
||||
<label className="block">
|
||||
Pressão competitiva
|
||||
<select
|
||||
className={control}
|
||||
value={draft.forces[force].pressure}
|
||||
onChange={(e) =>
|
||||
change(
|
||||
force,
|
||||
'pressure',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Indeterminada</option>
|
||||
<option value="low">Baixa</option>
|
||||
<option value="medium">Média</option>
|
||||
<option value="high">Alta</option>
|
||||
</select>
|
||||
</label>
|
||||
{Object.entries(labels).map(([field, label]) => (
|
||||
<label key={field} className="block">
|
||||
{label}
|
||||
<textarea
|
||||
className={control}
|
||||
rows={3}
|
||||
maxLength={5000}
|
||||
value={
|
||||
draft.forces[force][
|
||||
field as keyof typeof labels
|
||||
]
|
||||
}
|
||||
onChange={(e) =>
|
||||
change(
|
||||
force,
|
||||
field as keyof typeof labels,
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
))}
|
||||
<button type="button" className={button} onClick={download}>
|
||||
Transferir análise / rascunho
|
||||
</button>
|
||||
<label className="block">
|
||||
Recuperar ficheiro deste cluster
|
||||
<input
|
||||
className={control}
|
||||
type="file"
|
||||
accept=".json,application/json"
|
||||
onChange={async (e) => {
|
||||
const file = e.target.files?.[0];
|
||||
e.target.value = '';
|
||||
if (!file) return;
|
||||
setPending(null);
|
||||
try {
|
||||
if (file.size > 250_000)
|
||||
throw Error(
|
||||
'O ficheiro excede o limite de 250 KB.',
|
||||
);
|
||||
setPending(
|
||||
readCompetitivenessDraft(
|
||||
await file.text(),
|
||||
clusterId,
|
||||
),
|
||||
);
|
||||
setMessage(
|
||||
'Ficheiro lido. Confira o âmbito e confirme a substituição dos campos actuais.',
|
||||
);
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Não foi possível ler o ficheiro.',
|
||||
);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
{pending && (
|
||||
<div className="space-y-2 rounded border p-3">
|
||||
<p>
|
||||
Recuperar análise de{' '}
|
||||
{pending.sector || 'sector não indicado'} em{' '}
|
||||
{pending.region || 'região não indicada'}? Os campos
|
||||
actuais serão substituídos. Transfira primeiro o
|
||||
rascunho actual se o quiser conservar.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => {
|
||||
setDraft(pending);
|
||||
setPending(null);
|
||||
setMessage('Análise recuperada para edição.');
|
||||
}}
|
||||
>
|
||||
Confirmar recuperação
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => {
|
||||
setPending(null);
|
||||
setMessage(
|
||||
'Recuperação cancelada; campos actuais preservados.',
|
||||
);
|
||||
}}
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{message && <p role="status">{message}</p>}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={!dirty}
|
||||
onClick={() => command('saved', { draft })}
|
||||
>
|
||||
Guardar rascunho no servidor
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
setServerPending(
|
||||
await portalRequest<CompetitivenessState>(
|
||||
endpoint,
|
||||
),
|
||||
);
|
||||
setMessage(
|
||||
'Versão do servidor lida. Confirme antes de substituir os campos.',
|
||||
);
|
||||
} catch (error) {
|
||||
setMessage(errorMessage(error));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Consultar versão actual do servidor
|
||||
</button>
|
||||
</div>
|
||||
{serverPending && (
|
||||
<div className="rounded border p-3">
|
||||
<p>
|
||||
Versão {serverPending.version}:{' '}
|
||||
{serverPending.draft?.sector ||
|
||||
'Sector não indicado'}{' '}
|
||||
/{' '}
|
||||
{serverPending.draft?.region ||
|
||||
'Região não indicada'}
|
||||
. Recuperar substitui os campos actuais. Transfira
|
||||
primeiro alterações que queira conservar.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => {
|
||||
apply(serverPending);
|
||||
setMessage(
|
||||
'Versão actual recuperada do servidor.',
|
||||
);
|
||||
}}
|
||||
>
|
||||
Confirmar recuperação do servidor
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => setServerPending(null)}
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<details className="rounded border p-3">
|
||||
<summary>
|
||||
Histórico no servidor (últimas 50 versões)
|
||||
</summary>
|
||||
{!server.history.length && (
|
||||
<p>Ainda não existem gravações.</p>
|
||||
)}
|
||||
{server.history.map((entry) => (
|
||||
<p key={entry.version}>
|
||||
Versão {entry.version} ·{' '}
|
||||
{actions[entry.action] ?? entry.action} · {entry.at}{' '}
|
||||
· Utilizador {entry.actor}{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() => setRestoreVersion(entry.version)}
|
||||
>
|
||||
Recuperar como rascunho
|
||||
</button>
|
||||
</p>
|
||||
))}
|
||||
{restoreVersion !== null && (
|
||||
<div>
|
||||
<p>
|
||||
Recuperar a versão {restoreVersion} cria uma
|
||||
nova versão no servidor e substitui os campos
|
||||
actuais. A versão pública aprovada mantém-se.
|
||||
Transfira primeiro alterações por guardar.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() =>
|
||||
command('restored', {
|
||||
revision: restoreVersion,
|
||||
})
|
||||
}
|
||||
>
|
||||
Confirmar recuperação do histórico
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => setRestoreVersion(null)}
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</details>
|
||||
<details className="rounded border p-3">
|
||||
<summary>Aprovação para consulta pública</summary>
|
||||
<p>
|
||||
Aprovar torna a versão guardada consultável na ficha
|
||||
pública deste cluster, quando essa ficha estiver
|
||||
publicada. Guardar um rascunho não o publica. A
|
||||
evidência de aprovação e as identidades do histórico
|
||||
ficam na gestão.
|
||||
</p>
|
||||
<label className="block">
|
||||
Evidência / motivo da aprovação ou retirada
|
||||
<textarea
|
||||
className={control}
|
||||
maxLength={3000}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={
|
||||
dirty ||
|
||||
!diagnosticReady(draft) ||
|
||||
server.version === 0 ||
|
||||
reason.trim().length < 10
|
||||
}
|
||||
onClick={() => command('approved', { reason })}
|
||||
>
|
||||
Aprovar versão guardada para consulta pública
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={
|
||||
dirty ||
|
||||
!server.approved ||
|
||||
reason.trim().length < 10
|
||||
}
|
||||
onClick={() => command('withdrawn', { reason })}
|
||||
>
|
||||
Retirar aprovação pública
|
||||
</button>
|
||||
{dirty && (
|
||||
<p>
|
||||
Guarde primeiro as alterações ou recupere a versão
|
||||
pretendida antes de decidir a aprovação.
|
||||
</p>
|
||||
)}
|
||||
</details>
|
||||
</fieldset>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import { Management, Field, button, control } from '../management/shared';
|
||||
import { titles, statuses, stages, roles } from './types';
|
||||
import type { Structure, StructureRecord, Chain } from './types';
|
||||
import ValueNetwork from './value-network';
|
||||
import Competitiveness from './competitiveness';
|
||||
import type { CompetitivenessState } from './competitiveness';
|
||||
import type { ChainLink, Gap } from './value-network';
|
||||
|
||||
function ChainForm({ clusterId, chain }: { clusterId: string; chain?: Chain }) {
|
||||
@@ -75,6 +77,7 @@ export default function Editor({
|
||||
memberships,
|
||||
chainLinks,
|
||||
gaps,
|
||||
competitiveness,
|
||||
}: {
|
||||
structure: Structure;
|
||||
record: StructureRecord | null;
|
||||
@@ -83,6 +86,7 @@ export default function Editor({
|
||||
chains: Chain[];
|
||||
chainLinks: ChainLink[];
|
||||
gaps: Gap[];
|
||||
competitiveness?: CompetitivenessState | null;
|
||||
memberships: {
|
||||
id: string;
|
||||
project_id: string;
|
||||
@@ -298,6 +302,12 @@ export default function Editor({
|
||||
</form>
|
||||
{isCluster && record && (
|
||||
<>
|
||||
<Competitiveness
|
||||
key={record.id}
|
||||
clusterId={record.id}
|
||||
sector={record.sector ?? ''}
|
||||
initial={competitiveness}
|
||||
/>
|
||||
<section className="max-w-3xl space-y-4">
|
||||
<h2 className="text-xl font-semibold">
|
||||
Projectos associados
|
||||
|
||||
Reference in New Issue
Block a user