feat(qa): complete market milestones and personnel report tables
This commit is contained in:
@@ -5,6 +5,7 @@ namespace App\Http\Requests;
|
|||||||
use App\Services\CountryCatalogue;
|
use App\Services\CountryCatalogue;
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
use Illuminate\Validation\Validator;
|
use Illuminate\Validation\Validator;
|
||||||
|
|
||||||
class StoreSimulationFormDraftRequest extends FormRequest
|
class StoreSimulationFormDraftRequest extends FormRequest
|
||||||
@@ -137,7 +138,7 @@ class StoreSimulationFormDraftRequest extends FormRequest
|
|||||||
'economic_snapshot.public_fields_confirmation' => ['nullable', 'in:yes,no'],
|
'economic_snapshot.public_fields_confirmation' => ['nullable', 'in:yes,no'],
|
||||||
'economic_snapshot.validation_acknowledged' => ['nullable', 'in:yes,no'],
|
'economic_snapshot.validation_acknowledged' => ['nullable', 'in:yes,no'],
|
||||||
'economic_snapshot.investment_budget_min' => ['nullable', 'numeric', 'min:0'],
|
'economic_snapshot.investment_budget_min' => ['nullable', 'numeric', 'min:0'],
|
||||||
'economic_snapshot.investment_budget_max' => ['nullable', 'numeric', 'min:0', \Illuminate\Validation\Rule::when($this->filled('economic_snapshot.investment_budget_min'), 'gte:economic_snapshot.investment_budget_min')],
|
'economic_snapshot.investment_budget_max' => ['nullable', 'numeric', 'min:0', Rule::when($this->filled('economic_snapshot.investment_budget_min'), 'gte:economic_snapshot.investment_budget_min')],
|
||||||
'economic_snapshot.currency' => ['nullable', 'string', 'regex:/^[A-Z]{3}$/'],
|
'economic_snapshot.currency' => ['nullable', 'string', 'regex:/^[A-Z]{3}$/'],
|
||||||
'economic_snapshot.opportunity_currency' => ['nullable', 'string', 'regex:/^[A-Z]{3}$/'],
|
'economic_snapshot.opportunity_currency' => ['nullable', 'string', 'regex:/^[A-Z]{3}$/'],
|
||||||
'economic_snapshot.rate' => ['nullable', 'numeric', 'between:0,100'],
|
'economic_snapshot.rate' => ['nullable', 'numeric', 'between:0,100'],
|
||||||
@@ -217,11 +218,13 @@ class StoreSimulationFormDraftRequest extends FormRequest
|
|||||||
foreach ([
|
foreach ([
|
||||||
'project_team_snapshot' => [
|
'project_team_snapshot' => [
|
||||||
'keys' => ['competency', 'state', 'action', 'estimated_cost', 'due_date'],
|
'keys' => ['competency', 'state', 'action', 'estimated_cost', 'due_date'],
|
||||||
|
'optional' => ['department', 'quantity', 'monthly_salary', 'start_month', 'end_month'],
|
||||||
'states' => ['available', 'gap', 'unknown'],
|
'states' => ['available', 'gap', 'unknown'],
|
||||||
'amounts' => ['estimated_cost'],
|
'amounts' => ['estimated_cost', 'monthly_salary'],
|
||||||
],
|
],
|
||||||
'project_execution_snapshot' => [
|
'project_execution_snapshot' => [
|
||||||
'keys' => ['title', 'due_date', 'status', 'planned_amount', 'actual_amount'],
|
'keys' => ['title', 'due_date', 'status', 'planned_amount', 'actual_amount'],
|
||||||
|
'optional' => ['start_date', 'responsible', 'department'],
|
||||||
'states' => ['planned', 'in_progress', 'completed'],
|
'states' => ['planned', 'in_progress', 'completed'],
|
||||||
'amounts' => ['planned_amount', 'actual_amount'],
|
'amounts' => ['planned_amount', 'actual_amount'],
|
||||||
],
|
],
|
||||||
@@ -232,7 +235,7 @@ class StoreSimulationFormDraftRequest extends FormRequest
|
|||||||
$rows = json_decode((string) $economic[$field], true);
|
$rows = json_decode((string) $economic[$field], true);
|
||||||
$valid = is_array($rows) && count($rows) <= 100;
|
$valid = is_array($rows) && count($rows) <= 100;
|
||||||
foreach (is_array($rows) ? $rows : [] as $row) {
|
foreach (is_array($rows) ? $rows : [] as $row) {
|
||||||
if (! is_array($row) || array_diff(array_keys($row), $schema['keys']) !== []
|
if (! is_array($row) || array_diff(array_keys($row), array_merge($schema['keys'], $schema['optional'])) !== []
|
||||||
|| array_diff($schema['keys'], array_keys($row)) !== []
|
|| array_diff($schema['keys'], array_keys($row)) !== []
|
||||||
|| array_filter($row, fn ($value) => ! is_string($value) || mb_strlen($value) > 500) !== []) {
|
|| array_filter($row, fn ($value) => ! is_string($value) || mb_strlen($value) > 500) !== []) {
|
||||||
$valid = false;
|
$valid = false;
|
||||||
@@ -244,12 +247,19 @@ class StoreSimulationFormDraftRequest extends FormRequest
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
foreach ($schema['amounts'] as $amountKey) {
|
foreach ($schema['amounts'] as $amountKey) {
|
||||||
if ($row[$amountKey] !== '' && (! is_numeric($row[$amountKey]) || (float) $row[$amountKey] < 0)) {
|
if (isset($row[$amountKey]) && $row[$amountKey] !== '' && ($amountKey === 'monthly_salary'
|
||||||
|
? ! preg_match('/^\d+(?:\.\d{1,2})?$/', $row[$amountKey])
|
||||||
|
: (! is_numeric($row[$amountKey]) || (float) $row[$amountKey] < 0))) {
|
||||||
$valid = false;
|
$valid = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
foreach (['due_date'] as $dateKey) {
|
foreach (['quantity', 'start_month', 'end_month'] as $integerKey) {
|
||||||
if ($row[$dateKey] !== '' && ! preg_match('/^\d{4}-\d{2}-\d{2}$/', $row[$dateKey])) {
|
if (isset($row[$integerKey]) && $row[$integerKey] !== '' && (! preg_match('/^\d+$/', $row[$integerKey]) || (float) $row[$integerKey] > ($integerKey === 'quantity' ? 1000000 : 60) || ($integerKey !== 'quantity' && (int) $row[$integerKey] < 1))) {
|
||||||
|
$valid = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach (['due_date', 'start_date'] as $dateKey) {
|
||||||
|
if (isset($row[$dateKey]) && $row[$dateKey] !== '' && ! preg_match('/^\d{4}-\d{2}-\d{2}$/', $row[$dateKey])) {
|
||||||
$valid = false;
|
$valid = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10425,3 +10425,9 @@ Referência722322f9: Word/PDF existentes conferidos por rasterização Poppler l
|
|||||||
### Encerramento formal do Pacote 1 — aceitação do proprietário
|
### Encerramento formal do Pacote 1 — aceitação do proprietário
|
||||||
|
|
||||||
Pacote 1 da Etapa 2 APROVADO EM QA E ENCERRADO, por decisão expressa do proprietário sobre a implementação `722322f9` e as evidências `20998b89`. Aceites as sete tabelas, Word/PDF de onze páginas, interface em computador e telemóvel emulado, persistência e isolamento; nenhuma regressão reportada. Aceitação baseada no relatório, sem inspecção directa dos ficheiros ou hashes pelo proprietário. Relatório integral NÃO APTO; Pacote 2 NÃO INICIADO; restantes pacotes pendentes; instalação e publicação NÃO AUTORIZADAS. Etapa 1 encerrada preservada e pendências de histórico QA/tradução independentes. Actualização apenas documental, sem código, testes ou início de outro pacote. Matriz e aditamento de aceitação existentes actualizados.
|
Pacote 1 da Etapa 2 APROVADO EM QA E ENCERRADO, por decisão expressa do proprietário sobre a implementação `722322f9` e as evidências `20998b89`. Aceites as sete tabelas, Word/PDF de onze páginas, interface em computador e telemóvel emulado, persistência e isolamento; nenhuma regressão reportada. Aceitação baseada no relatório, sem inspecção directa dos ficheiros ou hashes pelo proprietário. Relatório integral NÃO APTO; Pacote 2 NÃO INICIADO; restantes pacotes pendentes; instalação e publicação NÃO AUTORIZADAS. Etapa 1 encerrada preservada e pendências de histórico QA/tradução independentes. Actualização apenas documental, sem código, testes ou início de outro pacote. Matriz e aditamento de aceitação existentes actualizados.
|
||||||
|
|
||||||
|
### Pacote2 — implementação QA de Mercado, Marcos e Pessoal
|
||||||
|
|
||||||
|
Pedido posterior de avanço executado exclusivamente em QA, base `f3148d16`. Três tabelas integradas nos planeadores/dossier/Word/impressão, com campos obrigatórios/opcionais explícitos. Mercado persiste no snapshot financeiro existente; pessoal e marcos reutilizam os respectivos snapshots, com extensões opcionais compatíveis com dados antigos. Projecções de clientes não alteram receitas; orçamentos não se tornam pagamentos; diferenças salariais são avisos sem sobrescrita do plano ou conversão monetária. Registos malformados não produzem totais parciais enganosos.
|
||||||
|
|
||||||
|
Sete testes novos, integração HTTP201/200/422/404, tipos/lint/Pint e buildQA aprovados. UI em1440×1000 e390×844, edição/gravação/recuperação101clientes, Word4páginas e impressão4páginas conferidos. Provas, hashes e matriz individual no aditamento de `apresentacao-contexto-qa-20261115.md` e `outputs/controlled-5f7db7cd-20261120/package2/acceptance.json`. Resultado técnico APTO em QA, por aceitar pelo proprietário. Etapa1/Pacote1 preservados, sem repetição das suas baterias aprovadas. Relatório11tabelas NÃO APTO; Pacotes3–5 não iniciados nesta execução. Sem instalação/publicação/migrações.
|
||||||
|
|||||||
@@ -807,3 +807,40 @@ Pendências do Pacote1: nenhuma identificada nos critérios desta conferência;
|
|||||||
| Instalação e publicação | NÃO AUTORIZADAS |
|
| Instalação e publicação | NÃO AUTORIZADAS |
|
||||||
|
|
||||||
Este registo substitui a proposta de encerramento anterior pela aceitação expressa, preservando as provas e o histórico. Etapa 1 permanece APROVADA E ENCERRADA; histórico perdido do QA e tradução HTTP 503 permanecem independentes. Execução exclusivamente documental: sem alterações de código, repetição de testes ou início de outros pacotes. A recomendação do próximo passo não constitui autorização para o iniciar nesta execução.
|
Este registo substitui a proposta de encerramento anterior pela aceitação expressa, preservando as provas e o histórico. Etapa 1 permanece APROVADA E ENCERRADA; histórico perdido do QA e tradução HTTP 503 permanecem independentes. Execução exclusivamente documental: sem alterações de código, repetição de testes ou início de outros pacotes. A recomendação do próximo passo não constitui autorização para o iniciar nesta execução.
|
||||||
|
|
||||||
|
### Pacote 2 — Mercado, Marcos e Pessoal, implementação e verificação em QA
|
||||||
|
|
||||||
|
Base: encerramento `f3148d16`. Pedido posterior do proprietário para avançar apenas com o Pacote2 em QA. **Resultado técnico: APTO em QA, por aceitar pelo proprietário.** Não reabre a Etapa1 ou o Pacote1; não inicia Rácios, relatório consolidado final ou CAE. O relatório integral de11tabelas continua NÃO APTO.
|
||||||
|
|
||||||
|
| Tabela | Dados necessários para completar | Opcionais / limites | Cálculo e evidência |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| Análise de Mercado | Ano-base, horizonte2–10anos, segmento, clientes potenciais inteiros, crescimento e fonte ou hipótese identificada | Narrativa de mercado existente e fonte/data adicional continuam opcionais; segmentos não são automaticamente deduplicados nem convertidos em vendas | Projecção anual com arredondamento à pessoa em aritmética inteira; crescimento composto do primeiro ao último ano, denominador zero indeterminado. Fixture100→110→121;10,00%. Crescimento150% aceite com aviso não bloqueante |
|
||||||
|
| Marcos | Título, início/término válidos e ordenados, responsável funcional, departamento e orçamento | Realizado opcional; vazio permanece por determinar, nunca zero presumido | Soma exacta em centavos; fixture100,25 de orçamento. Não soma os marcos automaticamente ao investimento ou à caixa |
|
||||||
|
| Pessoal | Função, departamento, quantidade inteira, remuneração mensal por pessoa e meses inicial/final no horizonte | Competência, disponibilidade, resposta, custo de formação/contratação e prazo preservados; não são salários por inferência | Quantidade×remuneração por mês activo, somas anuais e ano parcial; fixture2×100,00 gera200,00/mês e2.400,00/200,00 por ano. Diferença face à despesa financeira0,00; editar para100,01 mostra divergência sem sobrescrever o plano. Moedas diferentes impedem comparação automática |
|
||||||
|
|
||||||
|
Persistência reutilizada: mercado em `business_plan_snapshot` existente (versão17, propriedade opcional); pessoal em `project_team_snapshot`; marcos em `project_execution_snapshot`. A validação admite somente os novos campos previstos, como extensões opcionais das linhas antigas; conserva limites existentes e rejeita quantidade fraccionária, remuneração inválida e campos não previstos. Sem novas tabelas, migrações, armazenamento paralelo, permissões ou dependências. Registos antigos mantêm os campos originais; complementos ausentes ficam visíveis. Estruturas não reconhecidas não são substituídas pelo editor e não geram totais parciais aparentemente completos.
|
||||||
|
|
||||||
|
Integração: reutilizados os planeadores `project-planning.tsx`, o plano financeiro e o componente partilhado de tabelas. Mercado disponível no plano detalhado; Pessoal e Marcos na etapa de equipa/execução. As três tabelas integram as secções correspondentes do dossier, pré-visualização, Word e impressão. Os campos narrativos existentes foram conservados. Em conjunto com o Pacote1, a prova de integração contém10tabelas; Rácios permanece fora deste pacote.
|
||||||
|
|
||||||
|
**Verificações executadas:** sete testes frontend novos aprovados (`complementary-report.test.mjs`): clientes/crescimento/limites, datas/centavos, folha mensal/anual e divergências, moedas diferentes, compatibilidade com linhas antigas, estruturas malformadas e roundtrip/exportações. Tipos TypeScript, lint/formatação dos ficheiros afectados, sintaxe PHP, Pint e buildQA aprovados. A primeira captura leu o estado antes de a recuperação terminar; a prova final aguarda o resultado derivado e a resposta de recuperação. Pedido PUT e leitura API contêm101clientes, e o campo recuperado mostra101. Não houve alteração funcional para esse atraso. O build termina com código0; avisos preexistentes de fonte opcional e chunks não foram convertidos em falha. Não repetidos92testes da Etapa1 nem o conjunto aprovado do Pacote1.
|
||||||
|
|
||||||
|
Prova HTTP (`package2/http.json`): criação201, recuperação200com os três snapshots exactos,422para quantidade fraccionária e chave inesperada,404noutra sessão. QA isolado `http://127.0.0.3:18720`, baseguardada pelo router existente. Só foram escritos rascunhos sintéticos desta verificação; não se substituiu histórico perdido.
|
||||||
|
|
||||||
|
| Conferência visual | Resultado | Prova em `outputs/controlled-5f7db7cd-20261120/package2/` |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Mercado, Marcos e Pessoal em1440×1000 | APROVADO, sem erro JavaScript ou transbordo da página | `1440-{market,milestones,staff}-{left,right}.png` e `visual.json` |
|
||||||
|
| Mercado, Marcos e Pessoal em390×844 | APROVADO, colunas anuais acessíveis por deslocamento interno | `390-{market,milestones,staff}-{left,right}.png` |
|
||||||
|
| Word: página1 | Mercado e projecções legíveis | `word-1.png` |
|
||||||
|
| Word: página2 | Pessoal Janeiro–Agosto, cabeçalhos e remunerações | `word-2.png` |
|
||||||
|
| Word: página3 | Pessoal Setembro–Janeiro/anos, contexto e início dos marcos | `word-3.png` |
|
||||||
|
| Word: página4 | Continuação dos marcos, orçamento100,25 e realizado indeterminado | `word-4.png` |
|
||||||
|
| Impressão: página1 | Mercado, séries e pressupostos | `print-1.png` |
|
||||||
|
| Impressão: página2 | Pessoal e primeira continuação | `print-2.png` |
|
||||||
|
| Impressão: página3 | Pessoal anual e título/contexto dos marcos | `print-3.png` |
|
||||||
|
| Impressão: página4 | Marcos e totais | `print-4.png` |
|
||||||
|
|
||||||
|
Word aberto na aplicação nativa e convertido localmente para PDF; impressão gerada pelo mecanismo HTML existente com Chromium já instalado. Ambos com4páginas, todas rasterizadas com Poppler e examinadas. Sem cortes de conteúdo ou sobreposições; continuações mantêm os cabeçalhos. Todas as células do DOCX estão presentes no PDF Word. [Recibo e hashes](../../../../outputs/controlled-5f7db7cd-20261120/package2/acceptance.json), [Word](../../../../outputs/controlled-5f7db7cd-20261120/package2/report.docx), [PDF Word](../../../../outputs/controlled-5f7db7cd-20261120/package2/report.pdf), [PDF de impressão](../../../../outputs/controlled-5f7db7cd-20261120/package2/report-print.pdf).
|
||||||
|
|
||||||
|
Ficheiros funcionais afectados: novos `complementary-report.ts` e `market-analysis-plan.tsx`; extensões localizadas de `project-planning.tsx`, `simulation-business-plan.tsx`, `simulation-form.tsx`, tipos em `business-financial-plan.ts`/`project-dossier.ts`, integração em `project-dossier-report.ts` e validação em `StoreSimulationFormDraftRequest.php`. Acrescentados teste e fixture sintética específicos; actualizadas apenas esta documentação, manual e matriz existentes.
|
||||||
|
|
||||||
|
Pendências concretas do Pacote2: nenhuma identificada nos critérios acima; aceitação formal cabe ao proprietário. Permanecem Pacotes3–5, relatório integral NÃO APTO, histórico QA perdido e tradução503 independentes. Nenhuma instalação, publicação, migração operacional ou alteração de fórmula financeira aprovada. Próxima tarefa recomendada: aceitar o Pacote2 e decidir sobre Rácios, sem os iniciar nesta execução.
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,153 @@
|
|||||||
|
import type { BusinessFinancialPlanInput } from '@/lib/business-financial-plan';
|
||||||
|
import {
|
||||||
|
buildComplementaryTables,
|
||||||
|
isMarketAnalysis,
|
||||||
|
} from '@/lib/complementary-report';
|
||||||
|
import { InvestmentReportTables } from './investment-report-tables';
|
||||||
|
|
||||||
|
export function MarketAnalysisPlan({
|
||||||
|
plan,
|
||||||
|
onChange,
|
||||||
|
}: {
|
||||||
|
plan: BusinessFinancialPlanInput;
|
||||||
|
onChange: (p: BusinessFinancialPlanInput) => void;
|
||||||
|
}) {
|
||||||
|
const a = plan.marketAnalysis ?? {
|
||||||
|
baseYear: plan.reportAssumptions?.startYear ?? '',
|
||||||
|
years: '3',
|
||||||
|
segments: [],
|
||||||
|
};
|
||||||
|
if (!isMarketAnalysis(a))
|
||||||
|
return (
|
||||||
|
<p role="alert">
|
||||||
|
A análise de mercado guardada tem uma estrutura desconhecida.
|
||||||
|
Foi preservada; reveja o ficheiro antes de editar.
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
const update = (patch: Partial<typeof a>) =>
|
||||||
|
onChange({ ...plan, marketAnalysis: { ...a, ...patch } });
|
||||||
|
const input = (
|
||||||
|
label: string,
|
||||||
|
value: string,
|
||||||
|
change: (v: string) => void,
|
||||||
|
type = 'text',
|
||||||
|
) => (
|
||||||
|
<label className="grid min-w-0 gap-1 text-sm">
|
||||||
|
{label}
|
||||||
|
<input
|
||||||
|
className="min-w-0 rounded border p-2"
|
||||||
|
type={type}
|
||||||
|
step={type === 'number' ? 'any' : undefined}
|
||||||
|
value={value}
|
||||||
|
onChange={(e) => change(e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<details className="my-4 rounded border p-3">
|
||||||
|
<summary>Análise de Mercado — segmentos e hipóteses</summary>
|
||||||
|
<p className="my-2 text-sm">
|
||||||
|
Obrigatório para completar esta tabela: ano-base, horizonte de 2
|
||||||
|
a 10 anos e, por segmento, nome, clientes potenciais inteiros,
|
||||||
|
crescimento anual e fonte ou hipótese identificada. Não são
|
||||||
|
vendas nem procura confirmada. O horizonte sugerido de três anos
|
||||||
|
é editável; não representa dados económicos.
|
||||||
|
</p>
|
||||||
|
<div className="grid gap-3 sm:grid-cols-2">
|
||||||
|
{input(
|
||||||
|
'Ano-base de mercado',
|
||||||
|
a.baseYear,
|
||||||
|
(v) => update({ baseYear: v }),
|
||||||
|
'number',
|
||||||
|
)}
|
||||||
|
{input(
|
||||||
|
'Horizonte de mercado (anos)',
|
||||||
|
a.years,
|
||||||
|
(v) => update({ years: v }),
|
||||||
|
'number',
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{a.segments.map((s, i) => (
|
||||||
|
<fieldset
|
||||||
|
key={i}
|
||||||
|
className="my-3 grid gap-3 rounded border p-3 sm:grid-cols-2"
|
||||||
|
>
|
||||||
|
<legend>Segmento {i + 1}</legend>
|
||||||
|
{(
|
||||||
|
[
|
||||||
|
['label', 'Nome do segmento', 'text'],
|
||||||
|
[
|
||||||
|
'customers',
|
||||||
|
'Clientes potenciais no ano-base',
|
||||||
|
'number',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'growthPercent',
|
||||||
|
'Crescimento anual do segmento (%)',
|
||||||
|
'number',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'basis',
|
||||||
|
'Fonte e data, ou hipótese ilustrativa',
|
||||||
|
'text',
|
||||||
|
],
|
||||||
|
] as const
|
||||||
|
).map(([key, label, type]) => (
|
||||||
|
<div className="min-w-0" key={key}>
|
||||||
|
{input(
|
||||||
|
label,
|
||||||
|
s[key],
|
||||||
|
(v) =>
|
||||||
|
update({
|
||||||
|
segments: a.segments.map((r, j) =>
|
||||||
|
j === i ? { ...r, [key]: v } : r,
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
type,
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="rounded border p-2"
|
||||||
|
onClick={() =>
|
||||||
|
update({
|
||||||
|
segments: a.segments.filter((_, j) => j !== i),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Remover segmento {i + 1}
|
||||||
|
</button>
|
||||||
|
</fieldset>
|
||||||
|
))}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="my-2 rounded border p-2"
|
||||||
|
disabled={a.segments.length >= 100}
|
||||||
|
onClick={() =>
|
||||||
|
update({
|
||||||
|
segments: [
|
||||||
|
...a.segments,
|
||||||
|
{
|
||||||
|
label: '',
|
||||||
|
customers: '',
|
||||||
|
growthPercent: '',
|
||||||
|
basis: '',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Adicionar segmento de mercado
|
||||||
|
</button>
|
||||||
|
<InvestmentReportTables
|
||||||
|
tables={[
|
||||||
|
buildComplementaryTables(
|
||||||
|
{},
|
||||||
|
{ ...plan, marketAnalysis: a },
|
||||||
|
)[0],
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</details>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,6 +3,9 @@ import {
|
|||||||
type ProjectMilestone,
|
type ProjectMilestone,
|
||||||
type TeamNeed,
|
type TeamNeed,
|
||||||
} from '@/lib/project-dossier';
|
} from '@/lib/project-dossier';
|
||||||
|
import { restoreBusinessPlanSnapshot } from '@/lib/business-financial-plan';
|
||||||
|
import { buildComplementaryTables } from '@/lib/complementary-report';
|
||||||
|
import { InvestmentReportTables } from './investment-report-tables';
|
||||||
|
|
||||||
const teamKeys = [
|
const teamKeys = [
|
||||||
'competency',
|
'competency',
|
||||||
@@ -28,15 +31,84 @@ function update<T extends Record<string, string>>(
|
|||||||
return rows.map((row, i) => (i === index ? { ...row, [key]: value } : row));
|
return rows.map((row, i) => (i === index ? { ...row, [key]: value } : row));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function unreadable(value: string, rows: unknown[], optional: string[]) {
|
||||||
|
try {
|
||||||
|
const parsed: unknown = JSON.parse(value || '[]');
|
||||||
|
return (
|
||||||
|
!Array.isArray(parsed) ||
|
||||||
|
parsed.length !== rows.length ||
|
||||||
|
parsed.length > 100 ||
|
||||||
|
parsed.some((row) =>
|
||||||
|
optional.some(
|
||||||
|
(key) => key in row && typeof row[key] !== 'string',
|
||||||
|
),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function SupplementaryFields({
|
||||||
|
row,
|
||||||
|
fields,
|
||||||
|
change,
|
||||||
|
}: {
|
||||||
|
row: Record<string, string | undefined>;
|
||||||
|
fields: readonly (readonly [string, string, string])[];
|
||||||
|
change: (key: string, value: string) => void;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{fields.map(([key, label, type]) => (
|
||||||
|
<label className="grid min-w-0 gap-1 text-sm" key={key}>
|
||||||
|
{label}
|
||||||
|
<input
|
||||||
|
className="min-w-0 rounded border p-2"
|
||||||
|
type={type}
|
||||||
|
min={type === 'number' ? 0 : undefined}
|
||||||
|
step={
|
||||||
|
type === 'number'
|
||||||
|
? key === 'monthly_salary'
|
||||||
|
? '0.01'
|
||||||
|
: '1'
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
value={row[key] ?? ''}
|
||||||
|
onChange={(e) => change(key, e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function ProjectTeamPlanner({
|
export function ProjectTeamPlanner({
|
||||||
value,
|
value,
|
||||||
onChange,
|
onChange,
|
||||||
|
financialPlanSnapshot = '',
|
||||||
}: {
|
}: {
|
||||||
value: string;
|
value: string;
|
||||||
onChange: (value: string) => void;
|
onChange: (value: string) => void;
|
||||||
|
financialPlanSnapshot?: string;
|
||||||
}) {
|
}) {
|
||||||
const rows = readRows<TeamNeed>(value, teamKeys);
|
const rows = readRows<TeamNeed>(value, teamKeys);
|
||||||
const persist = (next: TeamNeed[]) => onChange(JSON.stringify(next));
|
const persist = (next: TeamNeed[]) => onChange(JSON.stringify(next));
|
||||||
|
if (
|
||||||
|
unreadable(value, rows, [
|
||||||
|
'department',
|
||||||
|
'quantity',
|
||||||
|
'monthly_salary',
|
||||||
|
'start_month',
|
||||||
|
'end_month',
|
||||||
|
])
|
||||||
|
)
|
||||||
|
return (
|
||||||
|
<p role="alert">
|
||||||
|
O plano de equipa guardado contém linhas não reconhecidas. O
|
||||||
|
original foi preservado e não será substituído por este editor.
|
||||||
|
</p>
|
||||||
|
);
|
||||||
return (
|
return (
|
||||||
<section
|
<section
|
||||||
className="space-y-4"
|
className="space-y-4"
|
||||||
@@ -47,6 +119,12 @@ export function ProjectTeamPlanner({
|
|||||||
custo e prazo. Não é uma certificação nem uma correspondência
|
custo e prazo. Não é uma certificação nem uma correspondência
|
||||||
automática a prestadores.
|
automática a prestadores.
|
||||||
</p>
|
</p>
|
||||||
|
<p className="text-sm">
|
||||||
|
Para o mapa de pessoal: função, departamento, quantidade,
|
||||||
|
remuneração mensal e meses inicial/final são necessários. Os
|
||||||
|
restantes campos são opcionais; não confundir custo de formação
|
||||||
|
ou contratação com salário.
|
||||||
|
</p>
|
||||||
{rows.map((row, index) => (
|
{rows.map((row, index) => (
|
||||||
<fieldset
|
<fieldset
|
||||||
key={index}
|
key={index}
|
||||||
@@ -55,6 +133,42 @@ export function ProjectTeamPlanner({
|
|||||||
<legend className="font-medium">
|
<legend className="font-medium">
|
||||||
Necessidade {index + 1}
|
Necessidade {index + 1}
|
||||||
</legend>
|
</legend>
|
||||||
|
<SupplementaryFields
|
||||||
|
row={row}
|
||||||
|
fields={[
|
||||||
|
[
|
||||||
|
'department',
|
||||||
|
'Departamento (mapa de pessoal)',
|
||||||
|
'text',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'quantity',
|
||||||
|
'Quantidade de pessoas (inteiro)',
|
||||||
|
'number',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'monthly_salary',
|
||||||
|
'Remuneração mensal por pessoa (moeda do projecto)',
|
||||||
|
'number',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'start_month',
|
||||||
|
'Mês inicial no plano (1 = Janeiro do ano inicial)',
|
||||||
|
'number',
|
||||||
|
],
|
||||||
|
['end_month', 'Mês final no plano', 'number'],
|
||||||
|
]}
|
||||||
|
change={(key, value) =>
|
||||||
|
persist(
|
||||||
|
update(
|
||||||
|
rows,
|
||||||
|
index,
|
||||||
|
key as keyof TeamNeed,
|
||||||
|
value,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
<label className="text-sm">
|
<label className="text-sm">
|
||||||
Competência ou função
|
Competência ou função
|
||||||
<input
|
<input
|
||||||
@@ -180,6 +294,14 @@ export function ProjectTeamPlanner({
|
|||||||
>
|
>
|
||||||
Adicionar competência ou lacuna
|
Adicionar competência ou lacuna
|
||||||
</button>
|
</button>
|
||||||
|
<InvestmentReportTables
|
||||||
|
tables={[
|
||||||
|
buildComplementaryTables(
|
||||||
|
{ project_team_snapshot: value },
|
||||||
|
restoreBusinessPlanSnapshot(financialPlanSnapshot),
|
||||||
|
)[2],
|
||||||
|
]}
|
||||||
|
/>
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -194,6 +316,13 @@ export function ProjectMilestonePlanner({
|
|||||||
const rows = readRows<ProjectMilestone>(value, milestoneKeys);
|
const rows = readRows<ProjectMilestone>(value, milestoneKeys);
|
||||||
const persist = (next: ProjectMilestone[]) =>
|
const persist = (next: ProjectMilestone[]) =>
|
||||||
onChange(JSON.stringify(next));
|
onChange(JSON.stringify(next));
|
||||||
|
if (unreadable(value, rows, ['start_date', 'responsible', 'department']))
|
||||||
|
return (
|
||||||
|
<p role="alert">
|
||||||
|
O plano de marcos guardado contém linhas não reconhecidas. O
|
||||||
|
original foi preservado e não será substituído por este editor.
|
||||||
|
</p>
|
||||||
|
);
|
||||||
return (
|
return (
|
||||||
<section className="space-y-4" aria-label="Marcos de execução">
|
<section className="space-y-4" aria-label="Marcos de execução">
|
||||||
<p className="text-sm text-slate-700">
|
<p className="text-sm text-slate-700">
|
||||||
@@ -201,12 +330,35 @@ export function ProjectMilestonePlanner({
|
|||||||
valores são declarados; não alteram automaticamente o plano
|
valores são declarados; não alteram automaticamente o plano
|
||||||
financeiro.
|
financeiro.
|
||||||
</p>
|
</p>
|
||||||
|
<p className="text-sm">
|
||||||
|
Para completar o relatório, indique título, início, término,
|
||||||
|
responsável, departamento e orçamento. O montante realizado é
|
||||||
|
opcional.
|
||||||
|
</p>
|
||||||
{rows.map((row, index) => (
|
{rows.map((row, index) => (
|
||||||
<fieldset
|
<fieldset
|
||||||
key={index}
|
key={index}
|
||||||
className="grid gap-3 rounded border p-3 sm:grid-cols-2"
|
className="grid gap-3 rounded border p-3 sm:grid-cols-2"
|
||||||
>
|
>
|
||||||
<legend className="font-medium">Marco {index + 1}</legend>
|
<legend className="font-medium">Marco {index + 1}</legend>
|
||||||
|
<SupplementaryFields
|
||||||
|
row={row}
|
||||||
|
fields={[
|
||||||
|
['start_date', 'Data de início', 'date'],
|
||||||
|
['responsible', 'Responsável pelo marco', 'text'],
|
||||||
|
['department', 'Departamento do marco', 'text'],
|
||||||
|
]}
|
||||||
|
change={(key, value) =>
|
||||||
|
persist(
|
||||||
|
update(
|
||||||
|
rows,
|
||||||
|
index,
|
||||||
|
key as keyof ProjectMilestone,
|
||||||
|
value,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
<label className="text-sm">
|
<label className="text-sm">
|
||||||
Marco ou resultado
|
Marco ou resultado
|
||||||
<input
|
<input
|
||||||
@@ -334,6 +486,14 @@ export function ProjectMilestonePlanner({
|
|||||||
>
|
>
|
||||||
Adicionar marco
|
Adicionar marco
|
||||||
</button>
|
</button>
|
||||||
|
<InvestmentReportTables
|
||||||
|
tables={[
|
||||||
|
buildComplementaryTables(
|
||||||
|
{ project_execution_snapshot: value },
|
||||||
|
null,
|
||||||
|
)[1],
|
||||||
|
]}
|
||||||
|
/>
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import { buildFinancialFiscalBridge } from '@/lib/financial-fiscal-bridge';
|
|||||||
import { BusinessPlanWarnings } from '@/components/business-plan-warnings';
|
import { BusinessPlanWarnings } from '@/components/business-plan-warnings';
|
||||||
import { SimulationAnnualExample } from '@/components/simulation-annual-example';
|
import { SimulationAnnualExample } from '@/components/simulation-annual-example';
|
||||||
import { IntegralFinancialPlan } from '@/components/integral-financial-plan';
|
import { IntegralFinancialPlan } from '@/components/integral-financial-plan';
|
||||||
|
import { MarketAnalysisPlan } from '@/components/market-analysis-plan';
|
||||||
|
|
||||||
const emptyPlan: BusinessFinancialPlanInput = {
|
const emptyPlan: BusinessFinancialPlanInput = {
|
||||||
currency: '',
|
currency: '',
|
||||||
@@ -940,6 +941,7 @@ export function SimulationBusinessPlan({
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<IntegralFinancialPlan plan={plan} onChange={savePlan} />
|
<IntegralFinancialPlan plan={plan} onChange={savePlan} />
|
||||||
|
<MarketAnalysisPlan plan={plan} onChange={savePlan} />
|
||||||
<div className="my-3 flex flex-wrap items-end gap-3 rounded border p-3">
|
<div className="my-3 flex flex-wrap items-end gap-3 rounded border p-3">
|
||||||
<label className="grid gap-1 text-sm">
|
<label className="grid gap-1 text-sm">
|
||||||
Importar plano financeiro InvestMoz (.json, até 60 KB)
|
Importar plano financeiro InvestMoz (.json, até 60 KB)
|
||||||
|
|||||||
@@ -3473,6 +3473,9 @@ export function SimulationForm() {
|
|||||||
{current.id === 'team' && (
|
{current.id === 'team' && (
|
||||||
<>
|
<>
|
||||||
<ProjectTeamPlanner
|
<ProjectTeamPlanner
|
||||||
|
financialPlanSnapshot={String(
|
||||||
|
draft.business_plan_snapshot ?? '',
|
||||||
|
)}
|
||||||
value={String(draft.project_team_snapshot ?? '')}
|
value={String(draft.project_team_snapshot ?? '')}
|
||||||
onChange={(value) =>
|
onChange={(value) =>
|
||||||
change('project_team_snapshot', value)
|
change('project_team_snapshot', value)
|
||||||
|
|||||||
@@ -82,6 +82,16 @@ function validCurrency(value: string): boolean {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type BusinessFinancialPlanInput = {
|
export type BusinessFinancialPlanInput = {
|
||||||
|
marketAnalysis?: {
|
||||||
|
baseYear: string;
|
||||||
|
years: string;
|
||||||
|
segments: {
|
||||||
|
label: string;
|
||||||
|
customers: string;
|
||||||
|
growthPercent: string;
|
||||||
|
basis: string;
|
||||||
|
}[];
|
||||||
|
};
|
||||||
reportAssumptions?: {
|
reportAssumptions?: {
|
||||||
startYear: string;
|
startYear: string;
|
||||||
openingFixedAssets: string;
|
openingFixedAssets: string;
|
||||||
|
|||||||
@@ -0,0 +1,433 @@
|
|||||||
|
import {
|
||||||
|
forecastBusinessPlan,
|
||||||
|
type BusinessFinancialPlanInput,
|
||||||
|
} from './business-financial-plan.ts';
|
||||||
|
import {
|
||||||
|
reportMoney,
|
||||||
|
displayReportMoney,
|
||||||
|
type InvestmentReportTable,
|
||||||
|
} from './integral-financial-report.ts';
|
||||||
|
import {
|
||||||
|
readRows,
|
||||||
|
type ProjectMilestone,
|
||||||
|
type TeamNeed,
|
||||||
|
} from './project-dossier.ts';
|
||||||
|
|
||||||
|
const unknown = 'Por determinar';
|
||||||
|
function structuredRows<T>(raw: string, keys: string[], optional: string[]) {
|
||||||
|
const rows = readRows<T>(raw, keys).filter((r) =>
|
||||||
|
optional.every(
|
||||||
|
(k) =>
|
||||||
|
!(k in (r as object)) ||
|
||||||
|
typeof (r as Record<string, unknown>)[k] === 'string',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
const parsed: unknown = JSON.parse(raw || '[]');
|
||||||
|
return {
|
||||||
|
rows,
|
||||||
|
valid:
|
||||||
|
Array.isArray(parsed) &&
|
||||||
|
parsed.length === rows.length &&
|
||||||
|
rows.length <= 100,
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return { rows, valid: false };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const amount = (s: string | undefined) => {
|
||||||
|
if (!s || !/^\d+(?:\.\d{1,2})?$/.test(s))
|
||||||
|
throw Error(
|
||||||
|
'Indique montantes não negativos com até duas casas decimais.',
|
||||||
|
);
|
||||||
|
const [a, b = ''] = s.split('.');
|
||||||
|
return BigInt(a) * 100n + BigInt(b.padEnd(2, '0'));
|
||||||
|
};
|
||||||
|
const integer = (s: string | undefined, min: number, max: number) => {
|
||||||
|
if (
|
||||||
|
!s ||
|
||||||
|
!/^\d+$/.test(s) ||
|
||||||
|
!Number.isSafeInteger(Number(s)) ||
|
||||||
|
Number(s) < min ||
|
||||||
|
Number(s) > max
|
||||||
|
)
|
||||||
|
throw Error(`Indique um inteiro entre ${min} e ${max}.`);
|
||||||
|
return Number(s);
|
||||||
|
};
|
||||||
|
const date = (s: string) =>
|
||||||
|
/^\d{4}-\d{2}-\d{2}$/.test(s) &&
|
||||||
|
Number.isFinite(Date.parse(s)) &&
|
||||||
|
new Date(s).toISOString().slice(0, 10) === s;
|
||||||
|
const table = (
|
||||||
|
id: string,
|
||||||
|
title: string,
|
||||||
|
headers: string[],
|
||||||
|
): InvestmentReportTable => ({
|
||||||
|
id,
|
||||||
|
title,
|
||||||
|
headers,
|
||||||
|
rows: [],
|
||||||
|
issues: [],
|
||||||
|
notes: [
|
||||||
|
'Informação declarada ou hipótese identificada pelo investidor; não confirma procura, contratação ou execução.',
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
export function isMarketAnalysis(
|
||||||
|
value: unknown,
|
||||||
|
): value is NonNullable<BusinessFinancialPlanInput['marketAnalysis']> {
|
||||||
|
if (!value || typeof value !== 'object' || Array.isArray(value))
|
||||||
|
return false;
|
||||||
|
const m = value as Record<string, unknown>;
|
||||||
|
return (
|
||||||
|
typeof m.baseYear === 'string' &&
|
||||||
|
typeof m.years === 'string' &&
|
||||||
|
Array.isArray(m.segments) &&
|
||||||
|
m.segments.length <= 100 &&
|
||||||
|
m.segments.every(
|
||||||
|
(s) =>
|
||||||
|
s &&
|
||||||
|
typeof s === 'object' &&
|
||||||
|
['label', 'customers', 'growthPercent', 'basis'].every(
|
||||||
|
(k) => typeof s[k] === 'string' && s[k].length <= 2000,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildComplementaryTables(
|
||||||
|
draft: Record<string, string | string[]>,
|
||||||
|
plan: BusinessFinancialPlanInput | null,
|
||||||
|
) {
|
||||||
|
const market = table('market-analysis', 'Análise de Mercado', ['Segmento']);
|
||||||
|
const milestones = table('milestones', 'Marcos', [
|
||||||
|
'Marco',
|
||||||
|
'Início',
|
||||||
|
'Término',
|
||||||
|
'Responsável',
|
||||||
|
'Departamento',
|
||||||
|
'Orçamento',
|
||||||
|
'Realizado',
|
||||||
|
]);
|
||||||
|
const staff = table('personnel', 'Pessoal', ['Função / departamento']);
|
||||||
|
const m = plan?.marketAnalysis;
|
||||||
|
const declaredCurrency =
|
||||||
|
String(draft.currency ?? '') || plan?.currency || unknown;
|
||||||
|
const sameCurrency =
|
||||||
|
!draft.currency || !plan?.currency || draft.currency === plan.currency;
|
||||||
|
milestones.notes.push(`Moeda dos montantes: ${declaredCurrency}.`);
|
||||||
|
staff.notes.push(`Moeda das remunerações: ${declaredCurrency}.`);
|
||||||
|
if (!sameCurrency)
|
||||||
|
staff.issues.push(
|
||||||
|
'A moeda do projecto difere da moeda do plano financeiro. A reconciliação fica por determinar, sem conversão automática.',
|
||||||
|
);
|
||||||
|
market.notes.push(
|
||||||
|
'O total é a soma aritmética dos segmentos, sem deduplicação de clientes. Confirme eventuais sobreposições antes de o interpretar como dimensão única do mercado.',
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
if (!isMarketAnalysis(m) || !m.segments.length)
|
||||||
|
throw Error(
|
||||||
|
'Indique segmentos, clientes potenciais, crescimento e fonte ou hipótese para completar a análise; os dados guardados não serão substituídos automaticamente.',
|
||||||
|
);
|
||||||
|
const year = integer(m.baseYear, 1900, 9999),
|
||||||
|
years = integer(m.years, 2, 10);
|
||||||
|
if (year + years - 1 > 9999)
|
||||||
|
throw Error('O horizonte de mercado excede o ano 9999.');
|
||||||
|
market.headers.push(
|
||||||
|
...Array.from({ length: years }, (_, i) => String(year + i)),
|
||||||
|
'Crescimento anual composto',
|
||||||
|
);
|
||||||
|
const totals = Array(years).fill(0) as number[];
|
||||||
|
for (const [i, s] of m.segments.entries()) {
|
||||||
|
try {
|
||||||
|
if (!s.label?.trim() || !s.basis?.trim())
|
||||||
|
throw Error('Indique nome e fonte ou hipótese.');
|
||||||
|
let clients = integer(s.customers, 0, Number.MAX_SAFE_INTEGER);
|
||||||
|
if (
|
||||||
|
typeof s.growthPercent !== 'string' ||
|
||||||
|
!/^-?\d+(?:\.\d{1,4})?$/.test(s.growthPercent) ||
|
||||||
|
!Number.isFinite(Number(s.growthPercent)) ||
|
||||||
|
Number(s.growthPercent) < -100
|
||||||
|
)
|
||||||
|
throw Error(
|
||||||
|
'Indique crescimento igual ou superior a −100%.',
|
||||||
|
);
|
||||||
|
const growth = Number(s.growthPercent),
|
||||||
|
series = [clients];
|
||||||
|
const [whole, fraction = ''] = s.growthPercent
|
||||||
|
.replace('-', '')
|
||||||
|
.split('.');
|
||||||
|
const growthUnits =
|
||||||
|
(BigInt(whole) * 10000n + BigInt(fraction.padEnd(4, '0'))) *
|
||||||
|
(s.growthPercent.startsWith('-') ? -1n : 1n);
|
||||||
|
for (let y = 1; y < years; y++) {
|
||||||
|
const next =
|
||||||
|
(BigInt(clients) * (1000000n + growthUnits) + 500000n) /
|
||||||
|
1000000n;
|
||||||
|
clients = Number(next);
|
||||||
|
if (!Number.isSafeInteger(clients))
|
||||||
|
throw Error(
|
||||||
|
'A projecção excede a precisão de clientes inteiros.',
|
||||||
|
);
|
||||||
|
series.push(clients);
|
||||||
|
}
|
||||||
|
series.forEach((n, y) => (totals[y] += n));
|
||||||
|
if (totals.some((n) => !Number.isSafeInteger(n)))
|
||||||
|
throw Error(
|
||||||
|
'O total excede a precisão de clientes inteiros.',
|
||||||
|
);
|
||||||
|
const cagr =
|
||||||
|
series[0] === 0
|
||||||
|
? unknown
|
||||||
|
: (
|
||||||
|
((series.at(-1)! / series[0]) **
|
||||||
|
(1 / (years - 1)) -
|
||||||
|
1) *
|
||||||
|
100
|
||||||
|
)
|
||||||
|
.toFixed(2)
|
||||||
|
.replace('.', ',') + '%';
|
||||||
|
market.rows.push([s.label, ...series.map(String), cagr]);
|
||||||
|
market.notes.push(`${s.label}: ${s.basis}`);
|
||||||
|
if (growth > 100)
|
||||||
|
market.notes.push(
|
||||||
|
`${s.label}: crescimento superior a 100%; aviso não bloqueante.`,
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
market.issues.push(
|
||||||
|
`Segmento ${i + 1}: ${(e as Error).message}`,
|
||||||
|
);
|
||||||
|
market.rows.push([
|
||||||
|
s?.label || `Segmento ${i + 1}`,
|
||||||
|
...Array(years + 1).fill(unknown),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const complete = market.issues.length === 0;
|
||||||
|
const cagr =
|
||||||
|
complete && totals[0] > 0
|
||||||
|
? (
|
||||||
|
((totals.at(-1)! / totals[0]) ** (1 / (years - 1)) - 1) *
|
||||||
|
100
|
||||||
|
)
|
||||||
|
.toFixed(2)
|
||||||
|
.replace('.', ',') + '%'
|
||||||
|
: unknown;
|
||||||
|
market.rows.push([
|
||||||
|
'Total de clientes potenciais',
|
||||||
|
...totals.map((n) => (complete ? String(n) : unknown)),
|
||||||
|
cagr,
|
||||||
|
]);
|
||||||
|
market.notes.push(
|
||||||
|
'Clientes potenciais não são vendas. Projecção anual por segmento: ano anterior × (1 + crescimento/100), arredondada à pessoa; crescimento composto calculado entre primeiro e último ano. Nenhuma transferência automática para receitas.',
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
market.issues.push((e as Error).message);
|
||||||
|
}
|
||||||
|
|
||||||
|
const raw = String(draft.project_execution_snapshot ?? '');
|
||||||
|
const milestoneData = structuredRows<ProjectMilestone>(
|
||||||
|
raw,
|
||||||
|
['title', 'due_date', 'status', 'planned_amount', 'actual_amount'],
|
||||||
|
['start_date', 'responsible', 'department'],
|
||||||
|
);
|
||||||
|
const rows = milestoneData.rows;
|
||||||
|
let budget = 0n,
|
||||||
|
actual = 0n,
|
||||||
|
budgetComplete = rows.length > 0 && milestoneData.valid,
|
||||||
|
actualComplete = rows.length > 0 && milestoneData.valid;
|
||||||
|
if (!milestoneData.valid)
|
||||||
|
milestones.issues.push(
|
||||||
|
'Há linhas de marcos não reconhecidas; os totais permanecem por determinar. O original foi preservado.',
|
||||||
|
);
|
||||||
|
if (!rows.length)
|
||||||
|
milestones.issues.push(
|
||||||
|
raw && raw !== '[]'
|
||||||
|
? 'O plano de marcos não tem uma estrutura reconhecida; conserve e reveja o original.'
|
||||||
|
: 'Adicione os marcos aplicáveis para completar a tabela.',
|
||||||
|
);
|
||||||
|
for (const [i, r] of rows.entries()) {
|
||||||
|
let planned = unknown,
|
||||||
|
realised = unknown;
|
||||||
|
try {
|
||||||
|
budget += amount(r.planned_amount);
|
||||||
|
planned = reportMoney(amount(r.planned_amount));
|
||||||
|
} catch {
|
||||||
|
budgetComplete = false;
|
||||||
|
milestones.issues.push(
|
||||||
|
`Marco ${i + 1}: orçamento em falta ou inválido.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (r.actual_amount !== '') {
|
||||||
|
try {
|
||||||
|
actual += amount(r.actual_amount);
|
||||||
|
realised = reportMoney(amount(r.actual_amount));
|
||||||
|
} catch {
|
||||||
|
actualComplete = false;
|
||||||
|
milestones.issues.push(`Marco ${i + 1}: realizado inválido.`);
|
||||||
|
}
|
||||||
|
} else actualComplete = false;
|
||||||
|
if (
|
||||||
|
!r.title.trim() ||
|
||||||
|
!r.responsible?.trim() ||
|
||||||
|
!r.department?.trim() ||
|
||||||
|
!date(r.start_date ?? '') ||
|
||||||
|
!date(r.due_date) ||
|
||||||
|
r.start_date! > r.due_date
|
||||||
|
)
|
||||||
|
milestones.issues.push(
|
||||||
|
`Marco ${i + 1}: complete título, responsável, departamento e datas de início/término válidas e ordenadas.`,
|
||||||
|
);
|
||||||
|
milestones.rows.push([
|
||||||
|
r.title || unknown,
|
||||||
|
r.start_date || unknown,
|
||||||
|
r.due_date || unknown,
|
||||||
|
r.responsible || unknown,
|
||||||
|
r.department || unknown,
|
||||||
|
planned,
|
||||||
|
realised,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
milestones.rows.push([
|
||||||
|
'Total',
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
budgetComplete ? reportMoney(budget) : unknown,
|
||||||
|
actualComplete ? reportMoney(actual) : unknown,
|
||||||
|
]);
|
||||||
|
milestones.notes.push(
|
||||||
|
'Título, datas, responsável, departamento e orçamento são necessários para completar cada marco; realizado é opcional e vazio não significa zero. Orçamentos não são somados automaticamente ao investimento nem à tesouraria.',
|
||||||
|
);
|
||||||
|
|
||||||
|
const teamData = structuredRows<TeamNeed>(
|
||||||
|
String(draft.project_team_snapshot ?? ''),
|
||||||
|
['competency', 'state', 'action', 'estimated_cost', 'due_date'],
|
||||||
|
[
|
||||||
|
'department',
|
||||||
|
'quantity',
|
||||||
|
'monthly_salary',
|
||||||
|
'start_month',
|
||||||
|
'end_month',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
const team = teamData.rows;
|
||||||
|
const periods = plan?.periods ?? 12;
|
||||||
|
const year = Number(plan?.reportAssumptions?.startYear);
|
||||||
|
const calendar =
|
||||||
|
Number.isInteger(year) &&
|
||||||
|
year >= 1900 &&
|
||||||
|
year + Math.floor((periods - 1) / 12) <= 9999;
|
||||||
|
const labels = Array.from({ length: periods }, (_, i) =>
|
||||||
|
calendar
|
||||||
|
? `${year + Math.floor(i / 12)}-${String((i % 12) + 1).padStart(2, '0')}`
|
||||||
|
: `Mês ${i + 1}`,
|
||||||
|
);
|
||||||
|
const years = [
|
||||||
|
...new Set(
|
||||||
|
labels.map((l, i) =>
|
||||||
|
calendar ? l.slice(0, 4) : `Ano ${Math.floor(i / 12) + 1}`,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
staff.headers.push(
|
||||||
|
...labels,
|
||||||
|
...years.map((y, i) => (periods < (i + 1) * 12 ? `${y} (parcial)` : y)),
|
||||||
|
);
|
||||||
|
const totals = Array(periods).fill(0n) as bigint[];
|
||||||
|
let complete = team.length > 0 && teamData.valid,
|
||||||
|
headcount = 0;
|
||||||
|
if (!teamData.valid)
|
||||||
|
staff.issues.push(
|
||||||
|
'Há linhas de pessoal não reconhecidas; os totais permanecem por determinar. O original foi preservado.',
|
||||||
|
);
|
||||||
|
if (!plan)
|
||||||
|
staff.issues.push(
|
||||||
|
'O plano financeiro não está disponível para definir o horizonte e reconciliar a despesa de pessoal.',
|
||||||
|
);
|
||||||
|
if (!team.length)
|
||||||
|
staff.issues.push(
|
||||||
|
'Adicione funções e respectivas quantidades/remunerações para completar o mapa de pessoal.',
|
||||||
|
);
|
||||||
|
for (const [i, r] of team.entries()) {
|
||||||
|
try {
|
||||||
|
if (!r.competency.trim() || !r.department?.trim())
|
||||||
|
throw Error('Indique função e departamento.');
|
||||||
|
const count = integer(r.quantity, 0, 1000000),
|
||||||
|
salary = amount(r.monthly_salary),
|
||||||
|
start = integer(r.start_month, 1, periods),
|
||||||
|
end = integer(r.end_month, 1, periods);
|
||||||
|
if (start > end) throw Error('O mês final precede o mês inicial.');
|
||||||
|
headcount += count;
|
||||||
|
const values = totals.map((_, j) =>
|
||||||
|
j + 1 >= start && j + 1 <= end ? salary * BigInt(count) : 0n,
|
||||||
|
);
|
||||||
|
values.forEach((v, j) => (totals[j] += v));
|
||||||
|
const annual = years.map((_, y) =>
|
||||||
|
values.slice(y * 12, y * 12 + 12).reduce((a, b) => a + b, 0n),
|
||||||
|
);
|
||||||
|
staff.rows.push([
|
||||||
|
`${r.competency} / ${r.department} (${count} pessoas × ${displayReportMoney(reportMoney(salary))}/mês; meses ${start}–${end})`,
|
||||||
|
...values.map(reportMoney),
|
||||||
|
...annual.map(reportMoney),
|
||||||
|
]);
|
||||||
|
} catch (e) {
|
||||||
|
complete = false;
|
||||||
|
staff.issues.push(`Função ${i + 1}: ${(e as Error).message}`);
|
||||||
|
staff.rows.push([
|
||||||
|
r.competency || `Função ${i + 1}`,
|
||||||
|
...Array(periods + years.length).fill(unknown),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const annual = years.map((_, y) =>
|
||||||
|
totals.slice(y * 12, y * 12 + 12).reduce((a, b) => a + b, 0n),
|
||||||
|
);
|
||||||
|
staff.rows.push([
|
||||||
|
'Folha salarial prevista',
|
||||||
|
...[...totals, ...annual].map((v) =>
|
||||||
|
complete ? reportMoney(v) : unknown,
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
staff.notes.push(
|
||||||
|
`Postos declarados nas linhas: ${complete ? headcount : unknown}; não representa pessoas únicas nem postos simultâneos. Remuneração mensal por pessoa × quantidade × meses activos; sem encargos presumidos. Competências, resposta, custo de formação/contratação e prazo são opcionais para este mapa e não substituem salários.`,
|
||||||
|
);
|
||||||
|
staff.notes.push(
|
||||||
|
calendar
|
||||||
|
? 'Calendário: Janeiro do ano inicial do plano financeiro.'
|
||||||
|
: 'Ano inicial do plano em falta: meses relativos, sem datas presumidas.',
|
||||||
|
);
|
||||||
|
if (plan && complete && sameCurrency) {
|
||||||
|
try {
|
||||||
|
const f = forecastBusinessPlan(plan);
|
||||||
|
const expected = f.rows.map((month) =>
|
||||||
|
amount(month.payrollExpense),
|
||||||
|
);
|
||||||
|
const differences = totals.map((v, i) => v - expected[i]);
|
||||||
|
staff.rows.push([
|
||||||
|
'Diferença face à despesa de pessoal no plano',
|
||||||
|
...differences.map(reportMoney),
|
||||||
|
...years.map((_, y) =>
|
||||||
|
reportMoney(
|
||||||
|
differences
|
||||||
|
.slice(y * 12, y * 12 + 12)
|
||||||
|
.reduce((a, b) => a + b, 0n),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
if (differences.some((v) => v !== 0n))
|
||||||
|
staff.issues.push(
|
||||||
|
'O mapa de pessoal diverge da despesa de pessoal do plano. Reveja os pressupostos; nenhum valor financeiro foi sobrescrito.',
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
staff.issues.push(
|
||||||
|
'Não foi possível reconciliar com o plano financeiro; reveja os dados do plano.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else
|
||||||
|
staff.issues.push(
|
||||||
|
'Reconciliação com o plano financeiro por determinar.',
|
||||||
|
);
|
||||||
|
return [market, milestones, staff];
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { displayValue } from './display-value.ts';
|
import { displayValue } from './display-value.ts';
|
||||||
|
import { buildComplementaryTables } from './complementary-report.ts';
|
||||||
import {
|
import {
|
||||||
buildIntegralFinancialTables,
|
buildIntegralFinancialTables,
|
||||||
displayReportMoney,
|
displayReportMoney,
|
||||||
@@ -523,6 +524,11 @@ function makeSections(
|
|||||||
const financialPlan = restoreBusinessPlanSnapshot(
|
const financialPlan = restoreBusinessPlanSnapshot(
|
||||||
text(draft, 'business_plan_snapshot'),
|
text(draft, 'business_plan_snapshot'),
|
||||||
);
|
);
|
||||||
|
const complementaryTables = buildComplementaryTables(draft, financialPlan);
|
||||||
|
for (const [i, id] of ['market', 'execution', 'team'].entries()) {
|
||||||
|
const section = sections.get(id as DossierReportSectionId);
|
||||||
|
if (section) section.tables = [complementaryTables[i]];
|
||||||
|
}
|
||||||
if (finance && financialPlan?.reportAssumptions) {
|
if (finance && financialPlan?.reportAssumptions) {
|
||||||
finance.tables = buildIntegralFinancialTables(financialPlan);
|
finance.tables = buildIntegralFinancialTables(financialPlan);
|
||||||
const periods = financialPlan.periods ?? 12;
|
const periods = financialPlan.periods ?? 12;
|
||||||
|
|||||||
@@ -74,6 +74,11 @@ import {
|
|||||||
} from './project-readiness.ts';
|
} from './project-readiness.ts';
|
||||||
|
|
||||||
export type TeamNeed = {
|
export type TeamNeed = {
|
||||||
|
department?: string;
|
||||||
|
quantity?: string;
|
||||||
|
monthly_salary?: string;
|
||||||
|
start_month?: string;
|
||||||
|
end_month?: string;
|
||||||
competency: string;
|
competency: string;
|
||||||
state: 'available' | 'gap' | 'unknown';
|
state: 'available' | 'gap' | 'unknown';
|
||||||
action: string;
|
action: string;
|
||||||
@@ -82,6 +87,9 @@ export type TeamNeed = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export type ProjectMilestone = {
|
export type ProjectMilestone = {
|
||||||
|
start_date?: string;
|
||||||
|
responsible?: string;
|
||||||
|
department?: string;
|
||||||
title: string;
|
title: string;
|
||||||
due_date: string;
|
due_date: string;
|
||||||
status: 'planned' | 'in_progress' | 'completed';
|
status: 'planned' | 'in_progress' | 'completed';
|
||||||
|
|||||||
@@ -0,0 +1,197 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import JSZip from 'jszip';
|
||||||
|
import { complementaryFixture } from './fixtures/complementary-plan.mjs';
|
||||||
|
import { buildComplementaryTables } from '../../resources/js/lib/complementary-report.ts';
|
||||||
|
import { buildIntegralFinancialTables } from '../../resources/js/lib/integral-financial-report.ts';
|
||||||
|
import {
|
||||||
|
restoreBusinessPlanSnapshot,
|
||||||
|
serializeBusinessPlanSnapshot,
|
||||||
|
} from '../../resources/js/lib/business-financial-plan.ts';
|
||||||
|
import {
|
||||||
|
partitionSimulationDraft,
|
||||||
|
restoreSimulationDraft,
|
||||||
|
} from '../../resources/js/lib/simulation-form.ts';
|
||||||
|
import {
|
||||||
|
createProjectDossierReport,
|
||||||
|
createProjectDossierPrintHtml,
|
||||||
|
generateProjectDossierDocx,
|
||||||
|
} from '../../resources/js/lib/project-dossier-report.ts';
|
||||||
|
|
||||||
|
void test('personnel in a different currency remains unreconciled without automatic conversion', () => {
|
||||||
|
const { plan, draft } = complementaryFixture();
|
||||||
|
const staff = buildComplementaryTables(
|
||||||
|
{ ...draft, currency: 'USD' },
|
||||||
|
plan,
|
||||||
|
)[2];
|
||||||
|
assert.match(staff.issues.join(' '), /moeda/);
|
||||||
|
assert.ok(
|
||||||
|
!staff.rows.some(
|
||||||
|
(r) => r[0] === 'Diferença face à despesa de pessoal no plano',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('malformed rows never produce misleading partial totals or erase original data', () => {
|
||||||
|
const { plan, draft, team, milestones } = complementaryFixture();
|
||||||
|
const input = {
|
||||||
|
...draft,
|
||||||
|
project_team_snapshot: JSON.stringify([...team, { bad: 'row' }]),
|
||||||
|
project_execution_snapshot: JSON.stringify([
|
||||||
|
...milestones,
|
||||||
|
{ ...milestones[0], responsible: 42 },
|
||||||
|
]),
|
||||||
|
};
|
||||||
|
const before = JSON.stringify(input);
|
||||||
|
const t = buildComplementaryTables(input, plan);
|
||||||
|
assert.ok(t[1].issues.length);
|
||||||
|
assert.equal(t[1].rows.at(-1).at(-2), 'Por determinar');
|
||||||
|
assert.ok(t[2].issues.length);
|
||||||
|
assert.equal(t[2].rows.at(-1)[1], 'Por determinar');
|
||||||
|
assert.equal(JSON.stringify(input), before);
|
||||||
|
plan.marketAnalysis.segments = [null];
|
||||||
|
assert.ok(buildComplementaryTables(draft, plan)[0].issues.length);
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('market projects integer customers and CAGR, never replaces sales; high growth is a warning', () => {
|
||||||
|
const { plan, draft } = complementaryFixture();
|
||||||
|
const before = buildIntegralFinancialTables(plan);
|
||||||
|
let t = buildComplementaryTables(draft, plan)[0];
|
||||||
|
assert.deepEqual(t.rows[0], [
|
||||||
|
'Segmento ilustrativo',
|
||||||
|
'100',
|
||||||
|
'110',
|
||||||
|
'121',
|
||||||
|
'10,00%',
|
||||||
|
]);
|
||||||
|
assert.equal(t.issues.length, 0);
|
||||||
|
plan.marketAnalysis.segments[0].growthPercent = '150';
|
||||||
|
t = buildComplementaryTables(draft, plan)[0];
|
||||||
|
assert.deepEqual(t.rows[0].slice(1, 4), ['100', '250', '625']);
|
||||||
|
assert.equal(t.issues.length, 0);
|
||||||
|
assert.match(t.notes.join(' '), /não bloqueante/);
|
||||||
|
assert.deepEqual(buildIntegralFinancialTables(plan), before);
|
||||||
|
plan.marketAnalysis.segments[0].customers = '0';
|
||||||
|
assert.equal(
|
||||||
|
buildComplementaryTables(draft, plan)[0].rows[0].at(-1),
|
||||||
|
'Por determinar',
|
||||||
|
);
|
||||||
|
plan.marketAnalysis.segments[0].growthPercent = '-100';
|
||||||
|
assert.equal(buildComplementaryTables(draft, plan)[0].issues.length, 0);
|
||||||
|
plan.marketAnalysis.segments[0].customers = '1.5';
|
||||||
|
assert.ok(buildComplementaryTables(draft, plan)[0].issues.length);
|
||||||
|
plan.marketAnalysis.segments[0].customers = '100';
|
||||||
|
plan.marketAnalysis.segments[0].basis = '';
|
||||||
|
assert.ok(buildComplementaryTables(draft, plan)[0].issues.length);
|
||||||
|
});
|
||||||
|
void test('milestone totals distinguish optional unknown actuals, invalid dates and exact centavos', () => {
|
||||||
|
const { plan, draft, milestones } = complementaryFixture();
|
||||||
|
let t = buildComplementaryTables(draft, plan)[1];
|
||||||
|
assert.equal(t.issues.length, 0);
|
||||||
|
assert.deepEqual(t.rows.at(-1).slice(-2), ['100.25', 'Por determinar']);
|
||||||
|
milestones[0].actual_amount = '0';
|
||||||
|
milestones[0].start_date = '2027-02-30';
|
||||||
|
draft.project_execution_snapshot = JSON.stringify(milestones);
|
||||||
|
t = buildComplementaryTables(draft, plan)[1];
|
||||||
|
assert.ok(t.issues.length);
|
||||||
|
assert.equal(t.rows.at(-1).at(-1), '0.00');
|
||||||
|
milestones[0].start_date = '2027-03-01';
|
||||||
|
assert.match(
|
||||||
|
buildComplementaryTables(
|
||||||
|
{
|
||||||
|
...draft,
|
||||||
|
project_execution_snapshot: JSON.stringify(milestones),
|
||||||
|
},
|
||||||
|
plan,
|
||||||
|
)[1].issues.join(' '),
|
||||||
|
/ordenadas/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
void test('personnel reconciles 13 months and partial years, preserves financial figures on mismatch', () => {
|
||||||
|
const { plan, draft, team } = complementaryFixture();
|
||||||
|
const before = buildIntegralFinancialTables(plan);
|
||||||
|
let t = buildComplementaryTables(draft, plan)[2];
|
||||||
|
assert.equal(t.issues.length, 0);
|
||||||
|
assert.deepEqual(
|
||||||
|
t.rows.find((r) => r[0] === 'Folha salarial prevista').slice(-2),
|
||||||
|
['2400.00', '200.00'],
|
||||||
|
);
|
||||||
|
assert.ok(
|
||||||
|
t.rows
|
||||||
|
.at(-1)
|
||||||
|
.slice(1)
|
||||||
|
.every((x) => x === '0.00'),
|
||||||
|
);
|
||||||
|
team[0].monthly_salary = '100.01';
|
||||||
|
draft.project_team_snapshot = JSON.stringify(team);
|
||||||
|
t = buildComplementaryTables(draft, plan)[2];
|
||||||
|
assert.equal(t.rows.at(-1)[1], '0.02');
|
||||||
|
assert.match(t.issues.join(' '), /diverge/);
|
||||||
|
assert.deepEqual(buildIntegralFinancialTables(plan), before);
|
||||||
|
team[0].quantity = '1.5';
|
||||||
|
assert.ok(
|
||||||
|
buildComplementaryTables(
|
||||||
|
{ ...draft, project_team_snapshot: JSON.stringify(team) },
|
||||||
|
plan,
|
||||||
|
)[2].issues.length,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
void test('legacy rows remain preserved and missing supplements remain explicit, not zero', () => {
|
||||||
|
const { plan, draft, team, milestones } = complementaryFixture();
|
||||||
|
delete plan.marketAnalysis;
|
||||||
|
for (const k of [
|
||||||
|
'department',
|
||||||
|
'quantity',
|
||||||
|
'monthly_salary',
|
||||||
|
'start_month',
|
||||||
|
'end_month',
|
||||||
|
])
|
||||||
|
delete team[0][k];
|
||||||
|
for (const k of ['department', 'responsible', 'start_date'])
|
||||||
|
delete milestones[0][k];
|
||||||
|
const old = {
|
||||||
|
...draft,
|
||||||
|
project_team_snapshot: JSON.stringify(team),
|
||||||
|
project_execution_snapshot: JSON.stringify(milestones),
|
||||||
|
};
|
||||||
|
const t = buildComplementaryTables(old, plan);
|
||||||
|
assert.ok(t.every((x) => x.issues.length));
|
||||||
|
assert.equal(t[2].rows[0][1], 'Por determinar');
|
||||||
|
assert.equal(team[0].estimated_cost, '');
|
||||||
|
assert.equal(t[1].rows[0].at(-2), '100.25');
|
||||||
|
});
|
||||||
|
void test('economic draft roundtrip and existing Word/print exports include three complementary tables', async () => {
|
||||||
|
const { plan, draft } = complementaryFixture();
|
||||||
|
const parts = partitionSimulationDraft(draft);
|
||||||
|
const restored = restoreSimulationDraft(
|
||||||
|
parts.personal_snapshot,
|
||||||
|
parts.economic_snapshot,
|
||||||
|
);
|
||||||
|
assert.equal(restored.project_team_snapshot, draft.project_team_snapshot);
|
||||||
|
assert.equal(
|
||||||
|
restored.project_execution_snapshot,
|
||||||
|
draft.project_execution_snapshot,
|
||||||
|
);
|
||||||
|
const recovered = restoreBusinessPlanSnapshot(
|
||||||
|
serializeBusinessPlanSnapshot(plan),
|
||||||
|
);
|
||||||
|
assert.deepEqual(recovered.marketAnalysis, plan.marketAnalysis);
|
||||||
|
assert.deepEqual(
|
||||||
|
buildComplementaryTables(restored, recovered),
|
||||||
|
buildComplementaryTables(draft, plan),
|
||||||
|
);
|
||||||
|
const report = createProjectDossierReport(draft, {
|
||||||
|
selectedSections: new Set(['market', 'team', 'execution', 'finance']),
|
||||||
|
});
|
||||||
|
assert.equal(report.sections.flatMap((s) => s.tables ?? []).length, 10);
|
||||||
|
const html = await createProjectDossierPrintHtml(report, []);
|
||||||
|
for (const title of ['Análise de Mercado', 'Marcos', 'Pessoal'])
|
||||||
|
assert.ok(html.includes(title));
|
||||||
|
const doc = await generateProjectDossierDocx(report, []);
|
||||||
|
const zip = await JSZip.loadAsync(
|
||||||
|
doc instanceof Blob ? await doc.arrayBuffer() : doc,
|
||||||
|
);
|
||||||
|
const xml = await zip.file('word/document.xml').async('string');
|
||||||
|
for (const title of ['Análise de Mercado', 'Marcos', 'Pessoal'])
|
||||||
|
assert.ok(xml.includes(title));
|
||||||
|
});
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { financialReportFixture } from './integral-financial-plan.mjs';
|
||||||
|
import { serializeBusinessPlanSnapshot } from '../../../resources/js/lib/business-financial-plan.ts';
|
||||||
|
export function complementaryFixture() {
|
||||||
|
const plan=financialReportFixture(13);
|
||||||
|
plan.marketAnalysis={baseYear:'2027',years:'3',segments:[{label:'Segmento ilustrativo',customers:'100',growthPercent:'10',basis:'Hipótese sintética de QA; não é procura observada.'}]};
|
||||||
|
const team=[{competency:'Operação',department:'Operações',quantity:'2',monthly_salary:'100.00',start_month:'1',end_month:'13',state:'gap',action:'',estimated_cost:'',due_date:''}];
|
||||||
|
const milestones=[{title:'Preparação ilustrativa',start_date:'2027-01-01',due_date:'2027-02-01',responsible:'Responsável sintético',department:'Operações',status:'planned',planned_amount:'100.25',actual_amount:''}];
|
||||||
|
return {plan,team,milestones,draft:{currency:'MZN',project_title:'QA complementar sintético',business_plan_snapshot:serializeBusinessPlanSnapshot(plan),project_team_snapshot:JSON.stringify(team),project_execution_snapshot:JSON.stringify(milestones)}};
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user