203 lines
6.4 KiB
TypeScript
203 lines
6.4 KiB
TypeScript
/** Presentation routing for existing diagnostics only; never validates or edits values. */
|
|
export const normaliseFieldLabel = (value: string) =>
|
|
value
|
|
.normalize('NFD')
|
|
.replace(/[\u0300-\u036f]/g, '')
|
|
.toLowerCase()
|
|
.replace(/[^a-z0-9]+/g, ' ')
|
|
.trim();
|
|
const routes: [RegExp, string[]][] = [
|
|
[
|
|
/unidades.*produto|quantidade.*produto/,
|
|
['Unidades por mes', 'Unidades mensais base'],
|
|
],
|
|
[/preco.*produto|preco por unidade/, ['Preço por unidade']],
|
|
[/custo variavel.*produto/, ['Custo variável por unidade']],
|
|
[/prazo.*dias/, ['Prazo (dias)', 'Prazo contratual (dias)']],
|
|
[
|
|
/preencha.*montantes.*relatorio/,
|
|
[
|
|
'Activos fixos anteriores (valor líquido)',
|
|
'Outros activos anteriores',
|
|
'Capital e resultados anteriores',
|
|
],
|
|
],
|
|
[
|
|
/capital discriminado|capital proprio.*coincide|capital do proprietario/,
|
|
[
|
|
'Capital próprio',
|
|
'Capital do proprietário',
|
|
'Capital do investidor',
|
|
'Capital adicional angariado',
|
|
],
|
|
],
|
|
[
|
|
/saldos de abertura|capital e resultados anteriores/,
|
|
[
|
|
'Capital e resultados anteriores',
|
|
'Saldo de caixa inicial',
|
|
'Activos fixos anteriores (valor líquido)',
|
|
'Outros activos anteriores',
|
|
'Existências iniciais',
|
|
'Valores a receber',
|
|
'Valores a pagar',
|
|
],
|
|
],
|
|
[
|
|
/depreciacao.*excede|base depreciavel/,
|
|
[
|
|
'Base depreciável contabilística',
|
|
'Vida útil (meses)',
|
|
'Aquisição de activos',
|
|
'Activos fixos anteriores (valor líquido)',
|
|
],
|
|
],
|
|
[
|
|
/reembolso.*excede|divida declarada/,
|
|
['Reembolso de capital', 'Empréstimo recebido', 'Suprimentos'],
|
|
],
|
|
[
|
|
/existencias iniciais.*produto/,
|
|
['Existências iniciais', 'Existências iniciais do produto'],
|
|
],
|
|
[
|
|
/stock insuficiente|existencias insuficientes/,
|
|
[
|
|
'Existências iniciais',
|
|
'Encomenda',
|
|
'Prazo de recepcao',
|
|
'Unidades por mes',
|
|
],
|
|
],
|
|
[
|
|
/aquisicoes.*necessidades|arranque.*aquisicao/,
|
|
[
|
|
'Aquisição de activos',
|
|
'Caixa requerida',
|
|
'Outros activos correntes requeridos',
|
|
'Activos de longo prazo requeridos',
|
|
],
|
|
],
|
|
[/ano inicial/, ['Ano inicial']],
|
|
[/fonte.*pressuposto fiscal/, ['Fonte ou pressuposto fiscal']],
|
|
[
|
|
/imposto estimado.*pagamento fiscal/,
|
|
['Imposto estimado', 'Pagamento fiscal'],
|
|
],
|
|
[
|
|
/recebimentos manuais|natureza.*cobrancas/,
|
|
['Natureza dos recebimentos manuais', 'Recebimentos mensais'],
|
|
],
|
|
[
|
|
/mapa de pessoal|folha salarial/,
|
|
[
|
|
'Quantidade',
|
|
'Remuneração mensal',
|
|
'Meses activos',
|
|
'Custo mensal de pessoal',
|
|
'Moeda do custo',
|
|
],
|
|
],
|
|
[
|
|
/percentagem.*recebiveis|cobrancas.*recebiveis/,
|
|
[
|
|
'Percentagem do saldo inicial',
|
|
'Percentagem de cobrança dos valores a receber de abertura',
|
|
],
|
|
],
|
|
[/recuperacao.*mes|mes unico/, ['Mês']],
|
|
[/moeda.*pessoal|moeda da folha/, ['Moeda do custo', 'Moeda do plano']],
|
|
[
|
|
/ficheiro|snapshot|importa/,
|
|
['Importar plano financeiro InvestMoz (.json, até 60 KB)'],
|
|
],
|
|
];
|
|
export function correctionFieldHints(
|
|
message: string,
|
|
availableLabels?: string[],
|
|
): string[] {
|
|
const normal = normaliseFieldLabel(message);
|
|
const quoted = [...message.matchAll(/«([^»]+)»/g)].map((m) => m[1]);
|
|
const exact = quoted.filter((h) =>
|
|
availableLabels?.some(
|
|
(label) => normaliseFieldLabel(label) === normaliseFieldLabel(h),
|
|
),
|
|
);
|
|
if (exact.length) return exact;
|
|
const mapped = routes
|
|
.filter(([pattern]) => pattern.test(normal))
|
|
.flatMap(([, labels]) => labels);
|
|
const prefix = message.split(':')[0].split('/').at(-1)?.trim() ?? '';
|
|
return [
|
|
...new Set([
|
|
...quoted,
|
|
...mapped,
|
|
...(prefix.length >= 4 ? [prefix] : []),
|
|
]),
|
|
];
|
|
}
|
|
export function fieldLabelMatches(
|
|
label: string,
|
|
hint: string,
|
|
availableLabels?: string[] | Set<string>,
|
|
): boolean {
|
|
const a = normaliseFieldLabel(label),
|
|
b = normaliseFieldLabel(hint);
|
|
if (
|
|
availableLabels instanceof Set
|
|
? availableLabels.has(b)
|
|
: availableLabels?.some((value) => normaliseFieldLabel(value) === b)
|
|
)
|
|
return a === b;
|
|
return (
|
|
!!a &&
|
|
!!b &&
|
|
(a === b ||
|
|
(b.length >= 7 && (a.startsWith(b + ' ') || b.startsWith(a + ' '))))
|
|
);
|
|
}
|
|
/** Match repeated groups by kind as well as index; personnel uses Necessidade in the editor. */
|
|
export function correctionGroupMatches(
|
|
message: string,
|
|
groupName: string,
|
|
): boolean {
|
|
const match =
|
|
/\b(produto|parcela|marco|funcao|necessidade|segmento)\s+(\d+)\b/.exec(
|
|
normaliseFieldLabel(message),
|
|
);
|
|
if (!match) return true;
|
|
const kind =
|
|
match[1] === 'funcao' || match[1] === 'necessidade'
|
|
? '(?:funcao|necessidade)'
|
|
: match[1];
|
|
return new RegExp(`\\b${kind}\\s+${match[2]}\\b`).test(
|
|
normaliseFieldLabel(groupName),
|
|
);
|
|
}
|
|
export function revealCorrectionTarget(target: HTMLElement): void {
|
|
const control = target.matches(
|
|
'input,select,textarea,button,[contenteditable="true"]',
|
|
)
|
|
? target
|
|
: (target.querySelector<HTMLElement>(
|
|
'input:not([type="hidden"]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),[contenteditable="true"]',
|
|
) ?? target);
|
|
for (
|
|
let node: HTMLElement | null = control.parentElement;
|
|
node;
|
|
node = node.parentElement
|
|
)
|
|
if (node instanceof HTMLDetailsElement) node.open = true;
|
|
control.scrollIntoView({ block: 'center', behavior: 'auto' });
|
|
control.focus({ preventScroll: true });
|
|
}
|
|
export function focusCorrectionId(id: string): void {
|
|
let attempts = 0;
|
|
const locate = () => {
|
|
const target = document.getElementById(id);
|
|
if (target) revealCorrectionTarget(target);
|
|
else if (++attempts < 10) requestAnimationFrame(locate);
|
|
};
|
|
requestAnimationFrame(locate);
|
|
}
|