Files
Investidor-V2/resources/js/components/simulation-own-name.tsx
T

321 lines
14 KiB
TypeScript

import { inputText } from '../lib/input-text.ts';
import { useState } from 'react';
import {
newOwnName,
switchOwnNameTreatment,
ownNameBook,
ownNameConditions,
ownNameSpecificConditions,
ownNameCurrent,
ownNameReportRows,
ownNameSource,
ownNameTreatments,
recordOwnNames,
saveOwnNameBook,
type OwnNameBook,
type OwnNameRow,
} from '@/lib/iva-own-name';
export function SimulationOwnName({
draft,
onChange,
}: {
draft: Record<string, unknown>;
onChange: (field: string, value: string) => void;
}) {
const [error, setError] = useState('');
let book: OwnNameBook;
try {
book = ownNameBook(draft);
} catch (cause) {
return <p role="alert">{String(cause)}</p>;
}
const save = (next: OwnNameBook) => {
try {
onChange('modelo_a_snapshot', saveOwnNameBook(draft, next));
setError('');
} catch (cause) {
setError(String(cause));
}
};
const change = (id: string, patch: Partial<OwnNameRow>) =>
save({
...book,
rows: book.rows.map((row) =>
row.id === id ? { ...row, ...patch } : row,
),
});
return (
<details className="space-y-3 rounded border p-3">
<summary>Comissão e mandato — circuitos emnome próprio</summary>
<p>
Oportunidade:{' '}
{inputText(draft.context_opportunity || 'entrada geral')}.
Venda/prestação:mandante ou comitente → agente → terceiro.
Aquisição:terceiro → agente → mandante ou comitente. Nos
serviços,o mandatário emnome próprio é adquirente eprestador
sucessivamente;nos bens,os papéis dependem da comissão de compra
ou venda.
</p>
<p>
Conserve as contraprestações originais das duas relações
separadas. Este percurso não as soma,não calcula imposto nem
dedução e não cria uma comissão autónoma. A base de comissões de
bensP091já entregue mantém o seu cálculo e histórico próprios.
</p>
<p>{ownNameSource}</p>
{error && <p role="alert">{error}</p>}
<button
type="button"
className="underline"
onClick={() =>
save({
...book,
rows: [
...book.rows,
newOwnName(
crypto.randomUUID(),
inputText(draft.currency ?? ''),
),
],
})
}
>
Acrescentar circuito emnome próprio
</button>
{book.rows.map((row) => (
<details key={row.id} className="rounded border p-3">
<summary>
{row.description || 'Circuito por identificar'} —{' '}
{row.period || 'mês por indicar'}
</summary>
<div className="grid gap-3 md:grid-cols-2">
<label>
Natureza e sentido do circuito
<select
className="block rounded border p-2"
value={row.treatment}
onChange={(e) =>
change(
row.id,
switchOwnNameTreatment(
row,
e.target.value,
),
)
}
>
<option value="">Por indicar</option>
{ownNameTreatments.map((t) => (
<option key={t.id} value={t.id}>
{t.label}
</option>
))}
</select>
</label>
<label>
Natureza dos dados
<select
className="block rounded border p-2"
value={row.origin}
onChange={(e) =>
change(row.id, {
origin: e.target
.value as OwnNameRow['origin'],
})
}
>
<option value="projected">
Projectados / pressupostos
</option>
<option value="effective">
Efectivos declarados
</option>
</select>
</label>
{(
[
['description', 'Circuito identificado'],
[
'operationRef',
'Referência da operação / pressuposto',
],
[
'operationDate',
'Data da operação / prevista',
],
['period', 'Mês da operação'],
[
'documentRef',
'Documento / referência da previsão',
],
[
'documentDate',
'Data do documento / prevista',
],
[
'principalRef',
'Mandante ou comitente e referência',
],
[
'agentRef',
'Comissário ou mandatário e referência',
],
['thirdPartyRef', 'Terceiro e referência'],
[
'contractRef',
'Contrato de comissão ou mandato',
],
[
'subjectRef',
'Bens ou serviço e âmbito do objecto',
],
[
'currency',
'Moeda original das contraprestações',
],
[
'firstAmount',
'Contraprestação original da relação1',
],
['firstLegRef', 'Referência da relação1'],
[
'secondAmount',
'Contraprestação original da relação2',
],
['secondLegRef', 'Referência da relação2'],
[
'scope',
'Âmbito:partes,objecto,operação eperíodo',
],
[
'evidence',
'Fundamento factual / pressupostos',
],
] as const
).map(([field, label]) => (
<label key={field}>
{label}
<input
className="block rounded border p-2"
type={
[
'operationDate',
'documentDate',
].includes(field)
? 'date'
: field === 'period'
? 'month'
: 'text'
}
value={row[field]}
onChange={(e) =>
change(row.id, {
[field]: e.target.value,
})
}
/>
</label>
))}
{ownNameTreatments.find((t) => t.id === row.treatment)
?.kind === 'goods' && (
<label>
Referência de baseP091já existente,se aplicável
<input
className="block rounded border p-2"
value={row.existingBaseRef}
onChange={(e) =>
change(row.id, {
existingBaseRef: e.target.value,
})
}
/>
</label>
)}
</div>
<p>
As relações seguem a ordem indicada no sentido
escolhido;contraprestação desconhecida não é zero. A
referênciaP091é reutilizável e não constitui nova
exigência para identificar o circuito. Mudar
sentido/natureza conserva partes,contrato,valores e
referências,mas exige rever os factos próprios.
</p>
<fieldset>
<legend>Factos próprios do circuito</legend>
{[
...ownNameConditions,
...ownNameSpecificConditions(row.treatment),
].map(([key, label]) => (
<label className="block" key={key}>
{label}
<select
className="block rounded border p-2"
value={row.conditions[key] ?? ''}
onChange={(e) =>
change(row.id, {
conditions: {
...row.conditions,
[key]: e.target.value as
| ''
| 'yes'
| 'no',
},
})
}
>
<option value="">Por indicar</option>
<option value="yes">Sim</option>
<option value="no">Não</option>
</select>
</label>
))}
</fieldset>
</details>
))}
{!!book.rows.length && (
<button
type="button"
className="rounded bg-emerald-800 p-2 text-white"
onClick={() => {
try {
save(recordOwnNames(draft, book));
} catch (cause) {
setError(String(cause));
}
}}
>
Identificar circuitos e guardar versão
</button>
)}
{book.result && (
<>
<p role="status">
{ownNameCurrent(draft, book)
? 'Circuitos correspondentes às entradas guardadas.'
: 'Entradas alteradas;circuitos históricos conservados. Reveja e identifique novamente.'}{' '}
{book.history?.length ?? 0} versões anteriores. Duas
relações separadas,sem soma de bases,IVA ou
dedução/campo11.
</p>
<dl>
{ownNameReportRows(draft).map(
([, label, value, origin], index) => (
<div key={index}>
<dt className="font-semibold">{label}</dt>
<dd>
{value}
<small className="block">
{origin}
</small>
</dd>
</div>
),
)}
</dl>
</>
)}
</details>
);
}