Files
Investidor-V2/resources/js/components/simulation-service-normal.tsx
T

319 lines
14 KiB
TypeScript

import { inputText } from '../lib/input-text.ts';
import { useState } from 'react';
import {
newServiceNormal,
switchServiceTreatment,
serviceNormalBook,
serviceNormalConditions,
ownServiceConditions,
serviceNormalCurrent,
serviceNormalReportRows,
serviceNormalSource,
serviceNormalTreatments,
recordServiceNormals,
saveServiceNormalBook,
type ServiceNormalBook,
type ServiceNormalRow,
} from '@/lib/iva-service-normal';
export function SimulationServiceNormal({
draft,
onChange,
}: {
draft: Record<string, unknown>;
onChange: (field: string, value: string) => void;
}) {
const [error, setError] = useState('');
let book: ServiceNormalBook;
try {
book = serviceNormalBook(draft);
} catch (cause) {
return <p role="alert">{String(cause)}</p>;
}
const save = (next: ServiceNormalBook) => {
try {
onChange('modelo_a_snapshot', saveServiceNormalBook(draft, next));
setError('');
} catch (cause) {
setError(String(cause));
}
};
const change = (id: string, patch: Partial<ServiceNormalRow>) =>
save({
...book,
rows: book.rows.map((row) =>
row.id === id ? { ...row, ...patch } : row,
),
});
return (
<details className="space-y-3 rounded border p-3">
<summary>
Base tributável — serviços gratuitos e utilização de bens da
empresa
</summary>
<p>
Oportunidade:{' '}
{inputText(draft.context_opportunity || 'entrada geral')}.
Identifique o serviço e a finalidade abrangida pelo artigo4(2).
A base é o valor normal do serviço,com fundamento e âmbito
identificados;nenhum custo ou preço de aquisição dos bens é
usado como substituto automático.
</p>
<p>
O serviço gratuito da alínea a)não exige a dedução anterior
prevista na alínea b). A utilização de bens exige identificar os
bens/elementos e a dedução total/parcial anterior,sem a calcular
ou conceder aqui. Utilização não é transmissão permanente de
bens. Base e IVA são resultados distintos.
</p>
<p>{serviceNormalSource}</p>
{error && <p role="alert">{error}</p>}
<button
type="button"
className="underline"
onClick={() =>
save({
...book,
rows: [
...book.rows,
newServiceNormal(
crypto.randomUUID(),
inputText(draft.currency ?? ''),
),
],
})
}
>
Acrescentar serviço ou utilização
</button>
{book.rows.map((row) => (
<details key={row.id} className="rounded border p-3">
<summary>
{row.description || 'Operação por identificar'} —{' '}
{row.period || 'mês por indicar'}
</summary>
<div className="grid gap-3 md:grid-cols-2">
<label>
Tratamento do serviço ou utilização
<select
className="block rounded border p-2"
value={row.treatment}
onChange={(e) =>
change(
row.id,
switchServiceTreatment(
row,
e.target.value,
),
)
}
>
<option value="">Por indicar</option>
{serviceNormalTreatments.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 ServiceNormalRow['origin'],
})
}
>
<option value="projected">
Projectados / pressupostos
</option>
<option value="effective">
Efectivos declarados
</option>
</select>
</label>
{(
[
[
'description',
'Serviço e operação identificados',
],
[
'operationRef',
'Referência da operação / pressuposto',
],
[
'purposeRef',
'Finalidade e destinatário / sector isento',
],
[
'documentRef',
'Documento da operação / referência da previsão',
],
[
'documentDate',
'Data do documento / prevista',
],
['period', 'Mês da operação'],
['currency', 'Moeda de origem'],
[
'normalValue',
'Valor normal do serviço sem IVA (moeda indicada)',
],
[
'valuationRef',
'Fundamento do valor normal / pressuposto',
],
[
'valuationScope',
'Âmbito do valor normal: serviço, estádio, tempo, lugar e condições',
],
[
'compositionRef',
'Referência da composição sem próprio IVA',
],
[
'evidence',
'Fundamento factual / pressupostos',
],
] as const
).map(([field, label]) => (
<label key={field}>
{label}
<input
className="block rounded border p-2"
type={
field === 'documentDate'
? 'date'
: field === 'period'
? 'month'
: 'text'
}
value={row[field]}
onChange={(e) =>
change(row.id, {
[field]: e.target.value,
})
}
/>
</label>
))}
{row.treatment &&
row.treatment !== 'free_company_service' && (
<>
<label>
Bens da empresa / elementos
constitutivos identificados
<input
className="block rounded border p-2"
value={row.assetRef}
onChange={(e) =>
change(row.id, {
assetRef: e.target.value,
})
}
/>
</label>
<label>
Referência da dedução anterior total ou
parcial / pressuposto
<input
className="block rounded border p-2"
value={row.deductionRef}
onChange={(e) =>
change(row.id, {
deductionRef:
e.target.value,
})
}
/>
</label>
</>
)}
</div>
<p>
Mudar o tratamento conserva os valores e documentos,mas
exige rever as condições próprias. Os campos sem
aplicação ficam ocultos e conservados.
</p>
<fieldset>
<legend>Condições próprias deste percurso</legend>
{[
...serviceNormalConditions,
...ownServiceConditions(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(recordServiceNormals(draft, book));
} catch (cause) {
setError(String(cause));
}
}}
>
Determinar valores normais e guardar versão
</button>
)}
{book.result && (
<>
<p role="status">
{serviceNormalCurrent(draft, book)
? 'Valores normais correspondentes às entradas guardadas.'
: 'Entradas alteradas;valores normais históricos conservados. Reveja e determine novamente.'}{' '}
{book.history?.length ?? 0} versões anteriores. IVA e
campo11 não são preenchidos por estas bases.
</p>
<dl>
{serviceNormalReportRows(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>
);
}