Preserve dossier context and expose contextual applicability in QA
This commit is contained in:
@@ -1,10 +1,12 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { InvestmentContextAssessment } from './investment-context-assessment';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import {
|
||||
contextApi,
|
||||
contextFieldNames,
|
||||
type ContextView,
|
||||
} from '@/lib/investor-context';
|
||||
import { inheritCompatibleFields } from '@/lib/context-inheritance';
|
||||
type Props = {
|
||||
contextId?: string | null;
|
||||
consumer: 'simulator' | 'land' | 'desk' | 'submission';
|
||||
@@ -12,6 +14,7 @@ type Props = {
|
||||
enabled?: boolean;
|
||||
readOnly?: boolean;
|
||||
allowedFields?: string[];
|
||||
persistInheritance?: boolean;
|
||||
boundRevision?: number;
|
||||
onApply: (patch: Record<string, unknown>, replace: boolean) => void;
|
||||
onReview?: (revision: number, reviewed: boolean) => void;
|
||||
@@ -40,17 +43,16 @@ export function DossierPrefill(props: Props) {
|
||||
const [selected, setSelected] = useState<string[]>([]);
|
||||
const [reviewed, setReviewed] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const filled = useRef('');
|
||||
useEffect(() => {
|
||||
if (!contextId) return;
|
||||
let stopped = false;
|
||||
setView(null);
|
||||
setError('');
|
||||
void contextApi<ContextView>(`/investimentos/${contextId}/contexto`)
|
||||
.then((v) => {
|
||||
if (!stopped) {
|
||||
setView(v);
|
||||
setReviewed(false);
|
||||
latest.current.onReview?.(v.context.revision, false);
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
@@ -61,44 +63,20 @@ export function DossierPrefill(props: Props) {
|
||||
};
|
||||
}, [contextId, retry]);
|
||||
useEffect(() => {
|
||||
if (!view || !enabled || readOnly || !view.can_write) return;
|
||||
const generation = `${contextId}:${view.context.revision}:${consumer}`;
|
||||
if (filled.current === generation) return;
|
||||
if (!view || view.case.id !== contextId || !enabled || readOnly || !view.can_write) return;
|
||||
const source = view.prefill[consumer] ?? {};
|
||||
const now = latest.current;
|
||||
const patch: Record<string, unknown> = {};
|
||||
const conflict = geo.some(
|
||||
(k) =>
|
||||
!empty(now.values[k]) &&
|
||||
String(now.values[k]) !== text(source[k]),
|
||||
);
|
||||
for (const [k, v] of Object.entries(source)) {
|
||||
if (
|
||||
(now.allowedFields && !now.allowedFields.includes(k)) ||
|
||||
(geo.includes(k) && conflict)
|
||||
)
|
||||
continue;
|
||||
if (k === 'parcels') {
|
||||
const old = now.values.parcels as
|
||||
| Record<string, unknown>[]
|
||||
| undefined;
|
||||
if (
|
||||
(!old?.length || geo.every((g) => empty(old[0]?.[g]))) &&
|
||||
Array.isArray(v) &&
|
||||
v[0] &&
|
||||
Object.keys(v[0]).length
|
||||
)
|
||||
patch[k] = v;
|
||||
} else if (empty(now.values[k]) && !empty(v)) patch[k] = v;
|
||||
}
|
||||
filled.current = generation;
|
||||
if (Object.keys(patch).length) {
|
||||
now.onApply(patch, false);
|
||||
const inherited = inheritCompatibleFields(`dossier:${contextId}:${consumer}`, now.values, source, now.values.context_reuse, now.allowedFields);
|
||||
if (Object.keys(inherited.patch).length || (now.persistInheritance !== false && now.values.context_reuse !== inherited.metadata)) {
|
||||
// The shared reconciliation has already selected safe fields; metadata travels with the same saved form.
|
||||
now.onApply({...inherited.patch, ...(now.persistInheritance === false ? {} : {context_reuse:inherited.metadata})}, true);
|
||||
setMessage(
|
||||
'Campos vazios preenchidos a partir do dossier. Reveja-os; os campos já preenchidos foram preservados.',
|
||||
'Dados compatíveis reutilizados do mesmo dossier. Os valores herdados acompanham o contexto; as suas alterações locais foram preservadas.',
|
||||
);
|
||||
}
|
||||
}, [view, enabled, readOnly, contextId, consumer]);
|
||||
setReviewed(true);
|
||||
now.onReview?.(view.context.revision, true);
|
||||
}, [view, enabled, readOnly, contextId, consumer, props.values]);
|
||||
if (!contextId) return null;
|
||||
if (error)
|
||||
return (
|
||||
@@ -126,7 +104,7 @@ export function DossierPrefill(props: Props) {
|
||||
),
|
||||
);
|
||||
const differences = Object.keys(source).filter(
|
||||
(k) => text(props.values[k]) !== text(source[k]),
|
||||
(k) => k !== 'context_applicability_snapshot' && text(props.values[k]) !== text(source[k]),
|
||||
);
|
||||
const linkedRevision =
|
||||
consumer === 'simulator'
|
||||
@@ -152,6 +130,7 @@ export function DossierPrefill(props: Props) {
|
||||
. Mestres, declarações deste formulário e conteúdo já submetido
|
||||
mantêm-se separados.
|
||||
</p>
|
||||
<InvestmentContextAssessment contextId={contextId} raw={view.prefill.simulator?.context_applicability_snapshot} />
|
||||
{stale && (
|
||||
<p className="font-semibold" role="status">
|
||||
{linkedRevision > 0
|
||||
@@ -254,7 +233,17 @@ export function DossierPrefill(props: Props) {
|
||||
const patch: Record<string, unknown> = {};
|
||||
for (const k of selected)
|
||||
patch[k] = source[k] ?? '';
|
||||
props.onApply(patch, true);
|
||||
const scope = `dossier:${contextId}:${consumer}`;
|
||||
let raw = String(props.values.context_reuse ?? '');
|
||||
try {
|
||||
const metadata = JSON.parse(raw);
|
||||
if(metadata.scope === scope) {
|
||||
for(const key of selected) delete metadata.inherited?.[key];
|
||||
raw=JSON.stringify(metadata);
|
||||
}
|
||||
} catch { /* Legacy metadata does not grant ownership of other fields. */ }
|
||||
const adopted=inheritCompatibleFields(scope,{...props.values,...Object.fromEntries(selected.map(key=>[key,undefined]))},patch,raw,props.allowedFields);
|
||||
props.onApply({...patch,...(props.persistInheritance === false ? {} : {context_reuse:adopted.metadata})}, true);
|
||||
setSelected([]);
|
||||
setReviewed(false);
|
||||
props.onReview?.(view.context.revision, false);
|
||||
@@ -267,27 +256,7 @@ export function DossierPrefill(props: Props) {
|
||||
</button>
|
||||
</details>
|
||||
)}
|
||||
{!readOnly &&
|
||||
view.can_write &&
|
||||
props.onReview &&
|
||||
view.context.revision > 0 && (
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={reviewed}
|
||||
onChange={(e) => {
|
||||
setReviewed(e.target.checked);
|
||||
props.onReview?.(
|
||||
view.context.revision,
|
||||
e.target.checked,
|
||||
);
|
||||
}}
|
||||
/>{' '}
|
||||
Conferi os dados e pressupostos deste formulário para o
|
||||
contexto v{view.context.revision}; os valores diferentes
|
||||
que conservei são declarações deste processo.
|
||||
</label>
|
||||
)}
|
||||
{!readOnly && reviewed && <p>Contexto v{view.context.revision} recuperado neste formulário, sem nova confirmação dos dados compatíveis. As edições locais conservam-se; as declarações e submissões formais mantêm os seus controlos próprios.</p>}
|
||||
<p className="text-xs">
|
||||
Associar uma referência não confirma incentivos, licenças, terra
|
||||
disponível, reserva ou autorização.
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
|
||||
type Snapshot = {context_revision:number;path?:{definition_version:number;steps:Array<{code:string;title:string;applicability:string;reason:string;state:string;context_review_required?:boolean}>}; zone?:{title:string;href:string;version:number|string;fields?:Record<string,string>;analysis?:{conditions?:Array<{id:string;label:string;knowledge:string;source_reference?:string;valid_from?:string;valid_until?:string}>;source?:{title:string;url:string;diploma?:string;article?:string;valid_from?:string;valid_until?:string}|null}}|null;fields?:Record<string,string>};
|
||||
export function InvestmentContextAssessment({raw,contextId}:{raw:unknown;contextId?:string|null}) {
|
||||
let snapshot:Snapshot|null=null;
|
||||
try {const value=JSON.parse(String(raw ?? ''));if(value.version===1) snapshot=value;} catch { /* Missing context remains explicit. */ }
|
||||
if(!snapshot) return null;
|
||||
const fields=snapshot.fields ?? {};const zone=snapshot.zone;
|
||||
const regime=zone?.fields?.investment_regime ?? fields.investment_regime;
|
||||
const names:Record<string,string>={zee:'ZEE',zfi:'ZFI',industrial_park:'Parque industrial'};
|
||||
return <section className="space-y-2 rounded border border-amber-400 p-3" aria-label="Aplicabilidade ao investimento">
|
||||
<h3 className="font-semibold">Aplicabilidade ao investimento · contexto v{snapshot.context_revision}</h3>
|
||||
<p>Origem do investidor: {{national:'nacional',foreign:'estrangeiro',mixed:'misto'}[fields.investor_origin] ?? 'informação em falta'}. Residência fiscal declarada: {fields.tax_residency_country || 'informação em falta'}. Estas condições são distintas; uma não determina a outra.</p>
|
||||
{zone ? <><p><strong>Potencialmente aplicável — análise específica de {names[regime ?? ''] ?? 'zona seleccionada'}.</strong> <Link className="underline" href={zone.href}>{zone.title} · versão {zone.version} · consultar ficha e fundamentos</Link>.</p>
|
||||
<p>A selecção identifica a referência consultada; não confirma o reconhecimento da entidade, actividade autorizada, licença ou acesso a benefícios. Consulte as condições documentadas na ficha e reúna a autorização ou evidência correspondente no dossier.</p>
|
||||
{zone.analysis?.source && <p>Fundamento cadastrado: <a className="underline" href={zone.analysis.source.url}>{zone.analysis.source.diploma || zone.analysis.source.title} {zone.analysis.source.article}</a>. Período cadastrado: {zone.analysis.source.valid_from || 'início por indicar'} a {zone.analysis.source.valid_until || 'sem termo indicado'}. A cobertura do investimento exige correspondência com estas condições.</p>}
|
||||
{zone.analysis?.conditions?.length ? <ul className="list-disc pl-5">{zone.analysis.conditions.map(condition=><li key={condition.id}><strong>{condition.label}</strong>: {condition.knowledge==='documented'?'condição documentada; cumprimento pelo investimento por confirmar':condition.knowledge==='disputed'?'condição com informação divergente':'informação em falta'}. {condition.source_reference && <>Fundamento: {condition.source_reference}.</>} {condition.valid_from && <>Desde {condition.valid_from}.</>} {condition.valid_until && <>Até {condition.valid_until}.</>}</li>)}</ul> : <p>Condições específicas: informação estruturada em falta nesta referência. A ficha e os documentos continuam consultáveis; não se presume cumprimento.</p>}
|
||||
<p role="status">Benefício fiscal deste enquadramento: indeterminado. Não existe neste consumidor uma regra executável ligada ao reconhecimento e condições da zona. No simulador, o IVA disponível corresponde apenas ao cenário geral sem benefício, sobre vendas declaradas compatíveis; não simula o regime especial. O cenário com benefício e o apuramento final estão indisponíveis.</p></>
|
||||
: <p>Enquadramento geral de preparação: sem ZEE, ZFI ou parque seleccionado. Isso não confirma a elegibilidade para uma operação fiscal. O cálculo mantém o âmbito e as exclusões da versão publicada.</p>}
|
||||
<p>Confirmado neste quadro significa apenas dado recuperado do dossier; declarações e referências não são decisões jurídicas. Requisitos específicos não documentados permanecem indeterminados.</p>
|
||||
{snapshot.path && <details><summary>Passos adaptados pelo percurso existente · versão {snapshot.path.definition_version}</summary><ul className="list-disc pl-5">{snapshot.path.steps.map(step=><li key={step.code}>{step.code} — {step.title}: {step.context_review_required?'informação alterada; rever fundamento':step.applicability==='not_needed_for_preparation'?'não aplicável à preparação declarada':step.applicability==='undetermined'?'informação em falta':['completed','approved'].includes(step.state)?'preparação confirmada no percurso; não é decisão fiscal':'potencialmente aplicável'}. {step.reason}</li>)}</ul></details>}
|
||||
{contextId && <Link className="underline" href={`/investimentos/${contextId}/contexto/editar`}>Alterar contexto e comparar impacto antes de guardar</Link>}
|
||||
</section>;
|
||||
}
|
||||
@@ -95,7 +95,7 @@ function MoneyInput({
|
||||
}
|
||||
|
||||
export function SimulationBusinessPlan({
|
||||
currency,
|
||||
currency: projectCurrency,
|
||||
snapshot,
|
||||
onCurrencyChange,
|
||||
onSnapshotChange,
|
||||
@@ -253,8 +253,10 @@ export function SimulationBusinessPlan({
|
||||
const plan = workingPlan ??
|
||||
restoreBusinessPlanSnapshot(snapshot) ?? {
|
||||
...emptyPlan,
|
||||
currency,
|
||||
currency: projectCurrency,
|
||||
};
|
||||
// A project edit is not a conversion or permission to relabel stored sales.
|
||||
const currency = plan.currency || projectCurrency;
|
||||
const update = (
|
||||
key: keyof BusinessFinancialPlanInput,
|
||||
value:
|
||||
@@ -858,6 +860,7 @@ export function SimulationBusinessPlan({
|
||||
<summary className="cursor-pointer text-lg font-semibold">
|
||||
Plano financeiro empresarial (pressupostos editáveis)
|
||||
</summary>
|
||||
{plan.currency && projectCurrency && plan.currency !== projectCurrency && <p role="alert">A projecção guardada está em {plan.currency}; o projecto está em {projectCurrency}. Os valores e a moeda de origem foram preservados. Reveja o enquadramento monetário antes de os reutilizar; não foi feita conversão.</p>}
|
||||
{snapshotError && (
|
||||
<p
|
||||
role="alert"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { SimulationPublishedIva, type PublishedIvaInput } from './simulation-published-iva';
|
||||
import { SimulationMonthlyIva } from './simulation-monthly-iva';
|
||||
import { inheritSimulatorFields } from '@/lib/context-inheritance';
|
||||
import {
|
||||
PublicDocumentContent,
|
||||
type PublicDocument,
|
||||
@@ -778,7 +779,7 @@ function SearchChoice({
|
||||
|
||||
export function SimulationForm() {
|
||||
const { auth } = usePage<{
|
||||
auth: { user: { email_verified_at?: string | null } | null };
|
||||
auth: { user: { id: number; email_verified_at?: string | null } | null };
|
||||
}>().props;
|
||||
const pageUrl = usePage().url;
|
||||
const draftContext = useMemo(() => {
|
||||
@@ -790,11 +791,12 @@ export function SimulationForm() {
|
||||
};
|
||||
}, [pageUrl]);
|
||||
const contextId = draftContext.context;
|
||||
const storageScope = contextId
|
||||
const projectScope = contextId
|
||||
? `:case:${contextId}`
|
||||
: draftContext.requestedDraft
|
||||
? `:draft:${draftContext.requestedDraft}`
|
||||
: '';
|
||||
const storageScope = `${auth?.user ? `:account:${auth.user.id}` : ':anonymous'}${projectScope}`;
|
||||
const draftKey = legacyDraftKey + storageScope;
|
||||
const draftCreateKey = legacyDraftCreateKey + storageScope;
|
||||
const draftIdKey = legacyDraftIdKey + storageScope;
|
||||
@@ -806,6 +808,7 @@ export function SimulationForm() {
|
||||
const canAssociateDraft = Boolean(auth?.user?.email_verified_at);
|
||||
const [draft, setDraft] = useState<SimulationDraft>({});
|
||||
const [ready, setReady] = useState(false);
|
||||
useEffect(() => { if (ready) setDraft(current => inheritSimulatorFields(current)); }, [draft, ready]);
|
||||
const [contextReview, setContextReview] = useState({
|
||||
revision: 0,
|
||||
reviewed: false,
|
||||
@@ -3611,7 +3614,7 @@ export function SimulationForm() {
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{current.id === 'tax' && <SimulationPublishedIva busy={isCalculating} onCalculate={runSimulation} />}
|
||||
{current.id === 'tax' && <SimulationPublishedIva draft={draft} onChange={change} busy={isCalculating} onCalculate={runSimulation} />}
|
||||
{current.id === 'tax' && (
|
||||
<div
|
||||
id="draft-tool-fiscal"
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { InvestmentContextAssessment } from './investment-context-assessment';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { monthlyIvaInput, monthlyIvaKey, monthlySalesFromDraft, readMonthlyIvaRecord, readMonthlyIvaSettings, monthlyIvaCashTreatment, type MonthlyIvaInput, type MonthlyIvaSettings } from '@/lib/monthly-iva';
|
||||
import { fiscalQaRows } from '@/lib/fiscal-qa-preview';
|
||||
@@ -31,7 +32,7 @@ export function SimulationMonthlyIva({draft, busy, onCalculate, onChange}: {
|
||||
return () => { active = false; };
|
||||
}, [retry]);
|
||||
useEffect(() => {
|
||||
if (!settings.auto || !input || busy || !available || completed || attempt.current === key) return;
|
||||
if (!settings.auto || !input || input.currency !== 'MZN' || busy || !available || completed || attempt.current === key) return;
|
||||
const request = input;
|
||||
const pending = current && record && ['queued','running'].includes(record.execution.status) ? record.execution.id : null;
|
||||
const timer = window.setTimeout(() => {
|
||||
@@ -56,6 +57,7 @@ export function SimulationMonthlyIva({draft, busy, onCalculate, onChange}: {
|
||||
const snapshot = record?.execution.result_snapshot;
|
||||
const projection = snapshot?.monthly_projection as {rows?: Array<{date:string; sales_declared:string|null; net_sales:string|null; rate:string|null; vat:string|null; gross_sales:string|null; status:string}>} | undefined;
|
||||
return <section className="space-y-3 rounded border border-emerald-700 p-4" aria-label="IVA mensal das vendas projectadas">
|
||||
<InvestmentContextAssessment raw={draft.context_applicability_snapshot} />
|
||||
<h3 className="font-semibold">IVA mensal das vendas projectadas</h3>
|
||||
<p>{source}</p><p>Declare se os preços projectados são sem IVA ou com IVA incluído. Nenhuma taxa é fixada neste formulário; o servidor selecciona a versão publicada.</p>
|
||||
<label className="block">Primeiro mês da projecção<input type="month" value={settings.start} min="2026-01" max="2026-12" onChange={(event) => saveSettings({start:event.target.value})} className="block rounded border p-2" /></label>
|
||||
@@ -63,6 +65,7 @@ export function SimulationMonthlyIva({draft, busy, onCalculate, onChange}: {
|
||||
<label className="block"><input type="checkbox" checked={settings.declared} onChange={(event) => saveSettings({declared:event.target.checked})} /> Declaro que as vendas projectadas são tributáveis à taxa geral interna e não incluem as operações excluídas deste lote.</label>
|
||||
<p className="text-sm">Sem importações, taxas reduzidas, isenções, regimes especiais, deduções, reembolsos ou apuramento final. Valores com IVA incluído permanecem indeterminados neste lote; não se aplica a taxa ao preço bruto.</p>
|
||||
<p className="text-sm">{monthlyIvaCashTreatment}</p>
|
||||
{!!draft.currency && draft.currency !== "MZN" && <p role="alert">Moeda do projecto: {String(draft.currency)}. A regra disponível aceita apenas MZN. As vendas e a moeda são preservadas, sem conversão; o IVA mensal não pode ser determinado por esta versão.</p>}
|
||||
{inputError && <p role="alert">{inputError}</p>}
|
||||
{available === null && !error && <p role="status">A consultar a disponibilidade da versão publicada…</p>}
|
||||
{available === false && <p role="status">A versão publicada de IVA está indisponível neste ambiente para novas execuções. Os pressupostos e históricos mantêm-se.</p>}
|
||||
|
||||
@@ -10,16 +10,22 @@ export type PublishedIvaInput = MonthlyIvaInput | {
|
||||
scope_declared: boolean;
|
||||
};
|
||||
|
||||
export function SimulationPublishedIva({ busy, onCalculate }: {
|
||||
export function SimulationPublishedIva({ busy, onCalculate, draft, onChange }: {
|
||||
draft: Record<string, unknown>;
|
||||
onChange: (field: string, value: string) => void;
|
||||
busy: boolean;
|
||||
onCalculate: (input: PublishedIvaInput) => Promise<unknown>;
|
||||
}) {
|
||||
const [available, setAvailable] = useState(false);
|
||||
const [message, setMessage] = useState('A consultar disponibilidade do cálculo de IVA…');
|
||||
const [base, setBase] = useState('');
|
||||
const [date, setDate] = useState('');
|
||||
const [currency, setCurrency] = useState('');
|
||||
const [declared, setDeclared] = useState(false);
|
||||
const base = String(draft.published_iva_base ?? '');
|
||||
const date = String(draft.published_iva_date ?? '');
|
||||
const currency = String(draft.published_iva_currency ?? '');
|
||||
const declared = draft.published_iva_scope === 'yes';
|
||||
const setBase = (value: string) => onChange('published_iva_base', value);
|
||||
const setDate = (value: string) => onChange('published_iva_date', value);
|
||||
const setCurrency = (value: string) => onChange('published_iva_currency', value);
|
||||
const setDeclared = (value: boolean) => onChange('published_iva_scope', value ? 'yes' : 'no');
|
||||
const [error, setError] = useState('');
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
@@ -58,12 +64,13 @@ export function SimulationPublishedIva({ busy, onCalculate }: {
|
||||
<p className="text-sm">Cobertura: exigibilidade em 2026, operação interna à taxa geral. A base tributável é indicada por si; não é copiada do orçamento. Sem isenções, taxas reduzidas, bases especiais, importações, deduções, declaração ou pagamento. O cálculo não valida o enquadramento jurídico.</p>
|
||||
<fieldset disabled={busy} className="space-y-3">
|
||||
<label className="block">Base tributável líquida (decimal, com ponto)<input aria-label="Base tributável líquida" inputMode="decimal" value={base} onChange={(e) => setBase(e.target.value)} className="block rounded border p-2" /></label>
|
||||
<label className="block">Moeda da base<select aria-label="Moeda da base IVA" value={currency} onChange={(e) => setCurrency(e.target.value)} className="block rounded border p-2"><option value="">Seleccione</option><option value="MZN">MZN</option></select></label>
|
||||
<label className="block">Moeda da base<select aria-label="Moeda da base IVA" value={currency} onChange={(e) => setCurrency(e.target.value)} className="block rounded border p-2"><option value="">Seleccione</option><option value="MZN">MZN</option>{currency && currency !== "MZN" && <option value={currency}>{currency} — moeda declarada</option>}</select></label>
|
||||
<label className="block">Data de exigibilidade declarada<input aria-label="Data de exigibilidade IVA" type="date" min="2026-01-01" max="2026-12-31" value={date} onChange={(e) => setDate(e.target.value)} className="block rounded border p-2" /></label>
|
||||
<label className="block"><input type="checkbox" checked={declared} onChange={(e) => setDeclared(e.target.checked)} /> Declaro operação interna à taxa geral, base líquida já apurada e ausência das excepções acima.</label>
|
||||
<p className="text-sm">Sem esta declaração, o resultado fica indeterminado. O valor calculado conserva a precisão decimal; não é saldo a pagar.</p>
|
||||
<button type="button" disabled={!available || busy} onClick={() => void calculate()} className="rounded bg-emerald-800 px-4 py-2 text-white disabled:opacity-50">{busy ? 'A calcular…' : 'Calcular IVA e gravar'}</button>
|
||||
</fieldset>
|
||||
{currency && currency !== "MZN" && <p role="alert">Moeda: {currency}. A versão disponível aceita apenas MZN. O valor declarado foi preservado; não foi feita conversão. Este cálculo permanece indisponível para esta moeda.</p>}
|
||||
{error && <p role="alert">{error}</p>}
|
||||
</section>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { restoreBusinessPlanSnapshot } from './business-financial-plan.ts';
|
||||
const empty = (value: unknown) => value == null || value === '' || (Array.isArray(value) && value.length === 0);
|
||||
function canonical(value: unknown): unknown {
|
||||
if (Array.isArray(value)) return value.map(canonical);
|
||||
if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([key,item])=>[key,canonical(item)]));
|
||||
return value;
|
||||
}
|
||||
// Change tracking only, never an authorization, integrity or legal-acceptance token. No personal values in metadata.
|
||||
function signature(value: unknown): string {
|
||||
const text=JSON.stringify(canonical(value)) ?? 'undefined';let hash=14695981039346656037n;
|
||||
for(let index=0;index<text.length;index++) hash=BigInt.asUintN(64,(hash^BigInt(text.charCodeAt(index)))*1099511628211n);
|
||||
return `${text.length}:${hash.toString(16)}`;
|
||||
}
|
||||
export function inheritCompatibleFields(scope:string, values:Record<string,unknown>, source:Record<string,unknown>, raw:unknown, allowed?:string[]): {patch:Record<string,unknown>; metadata:string; inherited:string[]; conflicts:string[]} {
|
||||
let previous:Record<string,string>={};
|
||||
try { const saved=JSON.parse(String(raw ?? ''));if(saved.version===1 && saved.scope===scope && saved.inherited && typeof saved.inherited==='object') previous=saved.inherited; } catch { /* Legacy inputs are retained, not overwritten. */ }
|
||||
const next={...previous};const patch:Record<string,unknown>={};const inherited:string[]=[];const conflicts:string[]=[];
|
||||
const geo=['province_id','district_id','admin_post_id','locality_id'];
|
||||
const geoConflict=geo.some(key=>(!empty(values[key]) || key in previous) && signature(values[key])!==signature(source[key]) && previous[key]!==signature(values[key]));
|
||||
for(const [key,value] of Object.entries(source)) {
|
||||
if ((allowed && !allowed.includes(key)) || (empty(value) && !(key in previous))) continue;
|
||||
const current=values[key];
|
||||
const track = (item:unknown) => key==='parcels' ? Object.fromEntries(geo.map(field=>[field,(item as Array<Record<string,unknown>>)?.[0]?.[field] ?? ''])) : item;
|
||||
const owned=previous[key]===signature(track(current));
|
||||
const vacant=key==='parcels' ? geo.every(field=>empty((current as Array<Record<string,unknown>>)?.[0]?.[field])) : empty(current);
|
||||
if ((geo.includes(key) && geoConflict) || (!owned && (!vacant || key in previous))) {
|
||||
if(signature(current)!==signature(value)) conflicts.push(key);
|
||||
continue;
|
||||
}
|
||||
if(key==='parcels') {
|
||||
const parcels=current as Array<Record<string,unknown>>|undefined;
|
||||
if(!owned && parcels?.length && geo.some(field=>!empty(parcels[0]?.[field]))) {conflicts.push(key);continue;}
|
||||
}
|
||||
if(signature(track(current))!==signature(track(value))) {
|
||||
if(key==='parcels') {
|
||||
const parcels=(current as Array<Record<string,unknown>>) ?? [];
|
||||
patch[key]=[{...parcels[0],...Object.fromEntries(geo.map(field=>[field,(value as Array<Record<string,unknown>>)[0]?.[field] ?? '']))},...parcels.slice(1)];
|
||||
} else patch[key]=value;
|
||||
}
|
||||
next[key]=signature(track(value));inherited.push(key);
|
||||
}
|
||||
return {patch,metadata:JSON.stringify({version:1,scope,inherited:next}),inherited,conflicts};
|
||||
}
|
||||
|
||||
export function inheritSimulatorFields<T extends Record<string,unknown>>(draft:T): T {
|
||||
const source:Record<string,unknown>={};
|
||||
const plan=draft.business_plan_snapshot ? restoreBusinessPlanSnapshot(String(draft.business_plan_snapshot)) : null;
|
||||
if(plan?.currency) source.currency=plan.currency;
|
||||
const currency=draft.currency || source.currency;
|
||||
if(currency) {source.fiscal_currency=currency;source.opportunity_currency=currency;source.published_iva_currency=currency;}
|
||||
if(draft.tax_residency_country) source.fiscal_residency_country=draft.tax_residency_country;
|
||||
if(draft.fiscal_reference_date) source.published_iva_date=draft.fiscal_reference_date;
|
||||
let settings:Record<string,unknown>={start:'',basis:'unknown',declared:false,auto:false};
|
||||
let settingsValid=!draft.monthly_iva_settings;
|
||||
try {const saved=JSON.parse(String(draft.monthly_iva_settings ?? ''));if(saved && !Array.isArray(saved) && typeof saved.start==='string' && ['net','included','unknown'].includes(saved.basis) && typeof saved.declared==='boolean' && typeof saved.auto==='boolean') {settings=saved;settingsValid=true;}} catch { /* Invalid stored inputs remain intact. */ }
|
||||
const start=String(draft.expected_start_date ?? '');
|
||||
if(/^\d{4}-\d{2}-\d{2}$/.test(start)) source.monthly_iva_start=start.slice(0,7);
|
||||
else if(/^\d{4}$/.test(String(draft.fiscal_period)) && draft.fiscal_periodicity==='monthly' && /^(0?[1-9]|1[0-2])$/.test(String(draft.fiscal_month))) source.monthly_iva_start=`${draft.fiscal_period}-${String(draft.fiscal_month).padStart(2,'0')}`;
|
||||
if(!settingsValid) delete source.monthly_iva_start;
|
||||
const values={...draft,monthly_iva_start:settings.start ?? ''};
|
||||
const patch=inheritCompatibleFields('simulator-compatible-fields',values,source,draft.compatible_fields_snapshot);
|
||||
const next:Record<string,unknown>={...draft,...patch.patch,compatible_fields_snapshot:patch.metadata};
|
||||
if('monthly_iva_start' in patch.patch) next.monthly_iva_settings=JSON.stringify({...settings,start:patch.patch.monthly_iva_start});
|
||||
delete next.monthly_iva_start;
|
||||
return JSON.stringify(next)===JSON.stringify(draft) ? draft : next as T;
|
||||
}
|
||||
@@ -134,4 +134,19 @@ export const contextFieldNames: Record<string, string> = {
|
||||
province: 'Província',
|
||||
district: 'Distrito',
|
||||
location: 'Localização',
|
||||
currency: 'Moeda do projecto',
|
||||
person_type: 'Tipo de pessoa',
|
||||
fiscal_period: 'Ano fiscal',
|
||||
fiscal_periodicity: 'Periodicidade',
|
||||
fiscal_month: 'Mês fiscal',
|
||||
fiscal_residency_country: 'País de residência fiscal declarado',
|
||||
activity_id: 'Actividade',
|
||||
project_type: 'Modalidade do investimento',
|
||||
maturity_stage: 'Fase do investimento',
|
||||
expected_start_date: 'Início previsto',
|
||||
investor_origin: 'Origem do investidor',
|
||||
entity_stage: 'Situação da entidade',
|
||||
tax_residency_country: 'Residência fiscal declarada',
|
||||
investment_regime: 'Enquadramento territorial consultado',
|
||||
special_zone_id: 'ZEE, ZFI ou parque',
|
||||
};
|
||||
|
||||
@@ -21,6 +21,7 @@ export function monthlySalesFromDraft(draft: Record<string, unknown>): { amounts
|
||||
if (draft.business_plan_snapshot) {
|
||||
const plan = restoreBusinessPlanSnapshot(String(draft.business_plan_snapshot));
|
||||
if (!plan) throw new Error('Não foi possível recuperar a projecção de vendas. Os dados guardados não foram substituídos.');
|
||||
if (draft.currency && plan.currency && draft.currency !== plan.currency) throw new Error(`A projecção de vendas está em ${plan.currency}, mas o projecto está em ${String(draft.currency)}. Reveja a moeda da projecção; os valores não foram convertidos nem reclassificados.`);
|
||||
return {amounts: monthlyProjectedSales(plan), source: 'Vendas por produto e mês do plano empresarial; mesmos pressupostos e representação monetária da projecção de vendas.'};
|
||||
}
|
||||
if (draft.cashflow_snapshot) {
|
||||
|
||||
@@ -277,6 +277,19 @@ function makeSections(
|
||||
}
|
||||
}
|
||||
|
||||
if (draft.context_applicability_snapshot) {
|
||||
try {
|
||||
const context = JSON.parse(String(draft.context_applicability_snapshot));
|
||||
if (context.version === 1) {
|
||||
const section = sections.get('sources');
|
||||
const zone = context.zone;
|
||||
section?.rows.push({field:'Contexto do investimento',value:`Revisão ${context.context_revision}; ${zone ? `${zone.title}, versão ${zone.version}` : 'sem ZEE, ZFI ou parque seleccionado'}`,origin:'Referência do mesmo dossier no momento da gravação',classification:'Contexto versionado; não é reconhecimento jurídico'});
|
||||
section?.paragraphs.push(zone ? 'Benefício fiscal da zona indeterminado: falta regra executável ligada às condições e reconhecimento. O IVA apresentado é apenas cenário geral sem benefício; não representa o regime especial nem o apuramento final.' : 'Cenário geral de preparação; sem confirmação automática de elegibilidade fiscal.');
|
||||
if(zone?.href) section?.rows.push({field:'Ficha e fundamentos da zona',value:zone.href,origin:`Versão consultada ${zone.version}`,classification:'Referência consultável; condições por verificar'});
|
||||
}
|
||||
} catch { sections.get('sources')?.paragraphs.push('Não foi possível recuperar o contexto guardado; o enquadramento territorial permanece indeterminado.'); }
|
||||
}
|
||||
|
||||
for (const [sectionName, field, value, origin] of rows.slice(1)) {
|
||||
// Questionnaire schema identifiers remain stored; they do not help the
|
||||
// reader assess the project and are not a business report field.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { inheritSimulatorFields } from './context-inheritance.ts';
|
||||
import { csvCell } from './csv.js';
|
||||
import { fiscalQaRows } from './fiscal-qa-preview.ts';
|
||||
import { isApiSimulationResultSnapshotV1 } from './simulation-contract.ts';
|
||||
@@ -1530,7 +1531,7 @@ export function restoreSimulationDraft(
|
||||
}
|
||||
}
|
||||
}
|
||||
return draft as SimulationDraft;
|
||||
return inheritSimulatorFields(draft as SimulationDraft);
|
||||
}
|
||||
|
||||
export function simulationDraftFingerprint(draft: SimulationDraft): string {
|
||||
|
||||
@@ -135,6 +135,7 @@ export default function RequestPage({
|
||||
<DossierPrefill
|
||||
contextId={dossier.id}
|
||||
consumer="desk"
|
||||
persistInheritance={request.status !== 'returned'}
|
||||
values={form.data.payload}
|
||||
boundRevision={boundContextRevision}
|
||||
readOnly={!canEdit}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { InvestmentContextAssessment } from '@/components/investment-context-assessment';
|
||||
import ContextDocuments from '@/components/context-documents';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
@@ -131,6 +132,7 @@ export default function ContextEditor({
|
||||
}
|
||||
return (
|
||||
<Frame title="Contexto do investimento">
|
||||
<InvestmentContextAssessment contextId={view.case.id} raw={view.prefill.simulator?.context_applicability_snapshot} />
|
||||
<ContextDocuments source={view.context.selection.opportunity} />
|
||||
<div className="space-y-5 [overflow-wrap:anywhere]">
|
||||
<Link
|
||||
@@ -286,7 +288,7 @@ export default function ContextEditor({
|
||||
</select>
|
||||
</label>
|
||||
<label className="grid min-w-0 gap-1">
|
||||
Parque consultado
|
||||
ZEE, ZFI ou parque consultado
|
||||
<select
|
||||
className={input + ' max-w-full min-w-0'}
|
||||
disabled={busy}
|
||||
@@ -294,7 +296,7 @@ export default function ContextEditor({
|
||||
onChange={(e) => change('park', e.target.value)}
|
||||
>
|
||||
<option value="">
|
||||
Sem parque no contexto atual
|
||||
Sem ZEE, ZFI ou parque seleccionado
|
||||
</option>
|
||||
{options.parks.map((p) => (
|
||||
<option key={p.id} value={'park:' + p.id}>
|
||||
@@ -335,6 +337,17 @@ export default function ContextEditor({
|
||||
Estes campos pertencem ao processo. Alterá-los não muda
|
||||
o cadastro da oportunidade nem o perfil da organização.
|
||||
</p>
|
||||
<p>Origem do investidor, residência fiscal e constituição da entidade são declarações distintas. A localização não confirma benefícios. A prévia identifica o impacto antes de guardar.</p>
|
||||
{[
|
||||
['currency','Moeda do projecto',null],
|
||||
['expected_start_date','Data prevista de início',null],
|
||||
['investor_origin','Origem do investidor',[['national','Nacional'],['foreign','Estrangeiro'],['mixed','Misto']]],
|
||||
['person_type','Tipo de entidade',[['singular','Pessoa singular'],['collective','Pessoa colectiva'],['consortium','Consórcio']]],
|
||||
['entity_stage','Situação da entidade',[['existing','Existente'],['being_formed','Em constituição']]],
|
||||
['tax_residency_country','País de residência fiscal declarado (ISO de duas letras)',null],
|
||||
].map(([key,label,choices]) => <label className="grid gap-1" key={String(key)}>{String(label)}{Array.isArray(choices)
|
||||
? <select className={input} value={declarations[String(key)] ?? view.context.fields[String(key)] ?? ''} onChange={e=>{setDeclarations({...declarations,[String(key)]:e.target.value});setPlan(null);}}><option value="">Por indicar</option>{choices.map(([value,text])=><option key={value} value={value}>{text}</option>)}</select>
|
||||
: <input className={input} type={key==='expected_start_date'?'date':'text'} maxLength={key==='currency'?3:key==='tax_residency_country'?2:10} value={declarations[String(key)] ?? view.context.fields[String(key)] ?? ''} onChange={e=>{setDeclarations({...declarations,[String(key)]:e.target.value});setPlan(null);}} />}</label>)}
|
||||
{['project_title', 'project_summary'].map((k) => (
|
||||
<label className="grid gap-1" key={k}>
|
||||
{contextFieldNames[k]}
|
||||
@@ -366,7 +379,18 @@ export default function ContextEditor({
|
||||
declarações do utilizador. Autorize somente os
|
||||
campos que pretende substituir pelo cadastro.
|
||||
</p>
|
||||
{['project_title', 'project_summary'].map((k) => (
|
||||
<p>Origem do investidor, residência fiscal e constituição da entidade são declarações distintas. A localização não confirma benefícios. A prévia identifica o impacto antes de guardar.</p>
|
||||
{[
|
||||
['currency','Moeda do projecto',null],
|
||||
['expected_start_date','Data prevista de início',null],
|
||||
['investor_origin','Origem do investidor',[['national','Nacional'],['foreign','Estrangeiro'],['mixed','Misto']]],
|
||||
['person_type','Tipo de entidade',[['singular','Pessoa singular'],['collective','Pessoa colectiva'],['consortium','Consórcio']]],
|
||||
['entity_stage','Situação da entidade',[['existing','Existente'],['being_formed','Em constituição']]],
|
||||
['tax_residency_country','País de residência fiscal declarado (ISO de duas letras)',null],
|
||||
].map(([key,label,choices]) => <label className="grid gap-1" key={String(key)}>{String(label)}{Array.isArray(choices)
|
||||
? <select className={input} value={declarations[String(key)] ?? view.context.fields[String(key)] ?? ''} onChange={e=>{setDeclarations({...declarations,[String(key)]:e.target.value});setPlan(null);}}><option value="">Por indicar</option>{choices.map(([value,text])=><option key={value} value={value}>{text}</option>)}</select>
|
||||
: <input className={input} type={key==='expected_start_date'?'date':'text'} maxLength={key==='currency'?3:key==='tax_residency_country'?2:10} value={declarations[String(key)] ?? view.context.fields[String(key)] ?? ''} onChange={e=>{setDeclarations({...declarations,[String(key)]:e.target.value});setPlan(null);}} />}</label>)}
|
||||
{['project_title', 'project_summary'].map((k) => (
|
||||
<label className="block" key={k}>
|
||||
<input
|
||||
type="checkbox"
|
||||
|
||||
Reference in New Issue
Block a user