From 2cecb28c36a26d80198ef87b57a34117c5e8dc65 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 23:37:00 +0200 Subject: [PATCH] Plano de pessoal: a folha salarial do mapa de pessoal passa a ser a fonte do custo de pessoal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit O mapa de pessoal (passo Equipa) e o «Custo mensal de pessoal» do plano financeiro eram duas fontes independentes; o portal só avisava que divergiam. O mapa passa a calcular a folha salarial mês a mês e, enquanto o plano tiver outro valor, oferece duas acções expressas: usar como custo mensal de pessoal, ou como custo e pagamento no próprio mês. Depois da escolha a diferença desaparece e o passo confirma que coincidem. Um mapa incompleto ou noutra moeda nunca é adoptado; os pagamentos só mudam quando o investidor o pede. Os campos numéricos do mapa de pessoal, da análise de mercado, dos investimentos por período e das importações em regime de remissão passam a usar o mesmo campo decimal do simulador. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jM --- .../js/components/market-analysis-plan.tsx | 22 +- .../js/components/period-investments.tsx | 21 +- resources/js/components/project-planning.tsx | 87 ++++++-- resources/js/components/simulation-form.tsx | 10 + .../simulation-remission-imports.tsx | 24 +- resources/js/lib/complementary-report.ts | 71 ++++++ tests/frontend/team-payroll-source.test.mjs | 210 ++++++++++++++++++ 7 files changed, 409 insertions(+), 36 deletions(-) create mode 100644 tests/frontend/team-payroll-source.test.mjs diff --git a/resources/js/components/market-analysis-plan.tsx b/resources/js/components/market-analysis-plan.tsx index fc288fb4..ab4d3ef5 100644 --- a/resources/js/components/market-analysis-plan.tsx +++ b/resources/js/components/market-analysis-plan.tsx @@ -1,3 +1,4 @@ +import { DecimalInput } from '@/components/decimal-input'; import type { BusinessFinancialPlanInput } from '@/lib/business-financial-plan'; import { buildComplementaryTables, @@ -34,13 +35,20 @@ export function MarketAnalysisPlan({ ) => ( ); return ( diff --git a/resources/js/components/period-investments.tsx b/resources/js/components/period-investments.tsx index 187f6072..1bda877d 100644 --- a/resources/js/components/period-investments.tsx +++ b/resources/js/components/period-investments.tsx @@ -1,3 +1,4 @@ +import { DecimalInput } from '@/components/decimal-input'; import { forecastBusinessPlan, type BusinessFinancialPlanInput, @@ -42,12 +43,20 @@ export function PeriodInvestmentsEditor({ ) => ( ); let ledger: ReturnType< diff --git a/resources/js/components/project-planning.tsx b/resources/js/components/project-planning.tsx index 4ebf9cd1..3987f8bb 100644 --- a/resources/js/components/project-planning.tsx +++ b/resources/js/components/project-planning.tsx @@ -5,7 +5,10 @@ import { type TeamNeed, } from '@/lib/project-dossier'; import { restoreBusinessPlanSnapshot } from '@/lib/business-financial-plan'; -import { buildComplementaryTables } from '@/lib/complementary-report'; +import { + buildComplementaryTables, + teamPayrollSchedule, +} from '@/lib/complementary-report'; import { InvestmentReportTables } from './investment-report-tables'; const teamKeys = [ @@ -64,20 +67,20 @@ function SupplementaryFields({ {fields.map(([key, label, type]) => ( ))} @@ -89,13 +92,34 @@ export function ProjectTeamPlanner({ onChange, financialPlanSnapshot = '', projectCurrency = '', + onAdoptPayroll, }: { value: string; onChange: (value: string) => void; financialPlanSnapshot?: string; projectCurrency?: string; + /** Writes the map's monthly payroll into the financial plan, on the investor's request. */ + onAdoptPayroll?: (schedule: string[], payments: boolean) => void; }) { const rows = readRows(value, teamKeys); + const plan = restoreBusinessPlanSnapshot(financialPlanSnapshot); + const sameCurrency = + !projectCurrency || + !plan?.currency || + plan.currency === projectCurrency; + const payroll = + plan && sameCurrency + ? teamPayrollSchedule(value, plan.periods ?? 12) + : null; + const adopted = + payroll !== null && + payroll.every((amount, month) => { + const current = + plan?.monthlyPayrollExpenseByPeriod?.[month] ?? + plan?.monthlyPayrollExpense ?? + ''; + return Number(current || 0) === Number(amount); + }); const persist = (next: TeamNeed[]) => onChange(JSON.stringify(next)); if ( unreadable(value, rows, [ @@ -303,10 +327,41 @@ export function ProjectTeamPlanner({ project_team_snapshot: value, currency: projectCurrency, }, - restoreBusinessPlanSnapshot(financialPlanSnapshot), + plan, )[2], ]} /> + {onAdoptPayroll && payroll && !adopted && ( +
+

+ O mapa de pessoal é a fonte da folha salarial. Para que + o plano financeiro use os mesmos valores, escolha uma + das opções. Só muda o que escolher. +

+
+ + +
+
+ )} + {onAdoptPayroll && payroll && adopted && ( +

+ O custo de pessoal do plano financeiro coincide com este + mapa de pessoal. +

+ )} ); } diff --git a/resources/js/components/simulation-form.tsx b/resources/js/components/simulation-form.tsx index 59c2bb67..a7833de8 100644 --- a/resources/js/components/simulation-form.tsx +++ b/resources/js/components/simulation-form.tsx @@ -1,5 +1,6 @@ import { DecimalInput } from '@/components/decimal-input'; import { focusCorrectionId } from '@/lib/field-corrections'; +import { adoptTeamPayroll } from '@/lib/complementary-report'; import FiscalOperationPicker from './fiscal-operation-picker'; import { SimulationIrpcAnnual } from '@/components/simulation-irpc-annual'; import DemographicContext from '@/components/demographic-context'; @@ -3523,6 +3524,15 @@ export function SimulationForm() { onChange={(value) => change('project_team_snapshot', value) } + onAdoptPayroll={(schedule, payments) => { + const next = adoptTeamPayroll( + String(draft.business_plan_snapshot ?? ''), + schedule, + payments, + ); + if (next) + change('business_plan_snapshot', next); + }} /> {draft.skills_needed && (
diff --git a/resources/js/components/simulation-remission-imports.tsx b/resources/js/components/simulation-remission-imports.tsx index c7f8a3cb..129dcdc8 100644 --- a/resources/js/components/simulation-remission-imports.tsx +++ b/resources/js/components/simulation-remission-imports.tsx @@ -1,3 +1,4 @@ +import { DecimalInput } from '@/components/decimal-input'; import { inputText } from '../lib/input-text.ts'; import { useState } from 'react'; import EvidenceDetails from '@/components/evidence-details'; @@ -86,13 +87,22 @@ export function SimulationRemissionImports({ ) => ( ); const select = ( diff --git a/resources/js/lib/complementary-report.ts b/resources/js/lib/complementary-report.ts index d3ed79d5..a963a610 100644 --- a/resources/js/lib/complementary-report.ts +++ b/resources/js/lib/complementary-report.ts @@ -1,6 +1,8 @@ import { forecastBusinessPlan, businessPlanNumberError, + restoreBusinessPlanSnapshot, + serializeBusinessPlanSnapshot, type BusinessFinancialPlanInput, } from './business-financial-plan.ts'; import { @@ -102,6 +104,75 @@ const table = ( ], }); +/** + * Monthly payroll of the personnel map, in the plan's decimal format: the one + * source the investor can adopt for «Custo mensal de pessoal». Null while any + * function is incomplete, so a partial map never becomes the plan's payroll. + */ +export function teamPayrollSchedule( + teamSnapshot: string, + periods: number, +): string[] | null { + const data = structuredRows( + teamSnapshot, + ['competency', 'state', 'action', 'estimated_cost', 'due_date'], + [ + 'department', + 'quantity', + 'monthly_salary', + 'start_month', + 'end_month', + ], + ); + if (!data.valid || !data.rows.length) return null; + const totals = Array(periods).fill(0n) as bigint[]; + try { + for (const r of data.rows) { + requireField(r.competency, 'Competência ou função'); + requireField(r.department, 'Departamento (mapa de pessoal)'); + const count = integer(r.quantity, 0, 1000000); + const salary = amount(r.monthly_salary); + const start = integer(r.start_month, 1, periods); + const end = integer(r.end_month, 1, periods); + if (start > end) return null; + for (let month = start; month <= end; month++) + totals[month - 1] += salary * BigInt(count); + } + } catch { + return null; + } + return totals.map( + (v) => `${v / 100n}.${String(v % 100n).padStart(2, '0')}`, + ); +} + +/** + * The financial plan with the personnel map's payroll as its personnel cost + * (and, when asked, as its payment in the same month). Every other value of + * the plan is kept. Null when the saved plan cannot be read. + */ +export function adoptTeamPayroll( + planSnapshot: string, + schedule: string[], + payments: boolean, +): string | null { + const plan = restoreBusinessPlanSnapshot(planSnapshot); + if (!plan) return null; + const constant = schedule.every((amount) => amount === schedule[0]); + const byPeriod = constant ? undefined : [...schedule]; + return serializeBusinessPlanSnapshot({ + ...plan, + monthlyPayrollExpense: schedule[0] ?? '', + monthlyPayrollExpenseByPeriod: byPeriod, + ...(payments + ? { + monthlyPayrollPayments: schedule[0] ?? '', + monthlyPayrollPaymentsByPeriod: byPeriod, + } + : {}), + }); +} + export function isMarketAnalysis( value: unknown, ): value is NonNullable { diff --git a/tests/frontend/team-payroll-source.test.mjs b/tests/frontend/team-payroll-source.test.mjs new file mode 100644 index 00000000..8a3c39e7 --- /dev/null +++ b/tests/frontend/team-payroll-source.test.mjs @@ -0,0 +1,210 @@ +import test from 'node:test'; +import fs from 'node:fs'; +import { createRequire } from 'node:module'; +import { compileFunction } from 'node:vm'; +import React from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; +import ts from 'typescript'; +import * as dossier from '../../resources/js/lib/project-dossier.ts'; +import * as complementary from '../../resources/js/lib/complementary-report.ts'; +import { decimalInputModule } from './helpers/decimal-input.mjs'; +import assert from 'node:assert/strict'; +import { complementaryFixture } from './fixtures/complementary-plan.mjs'; +import * as business from '../../resources/js/lib/business-financial-plan.ts'; +import { + adoptTeamPayroll, + buildComplementaryTables, + teamPayrollSchedule, +} from '../../resources/js/lib/complementary-report.ts'; + +const staffTable = (draft) => + buildComplementaryTables( + draft, + business.restoreBusinessPlanSnapshot(draft.business_plan_snapshot), + )[2]; + +test('the personnel map is the payroll source: the investor adopts it and the plan then agrees (tarefa 21)', () => { + const { draft } = complementaryFixture(); + const team = [ + { + competency: 'Recepção', + department: 'Alojamento', + quantity: '2', + monthly_salary: '15000.00', + start_month: '1', + end_month: '13', + state: 'gap', + action: '', + estimated_cost: '', + due_date: '', + }, + { + competency: 'Cozinha', + department: 'Restauração', + quantity: '1', + monthly_salary: '20000.00', + start_month: '4', + end_month: '13', + state: 'gap', + action: '', + estimated_cost: '', + due_date: '', + }, + ]; + draft.project_team_snapshot = JSON.stringify(team); + const schedule = teamPayrollSchedule(draft.project_team_snapshot, 13); + assert.deepEqual(schedule.slice(0, 4), [ + '30000.00', + '30000.00', + '30000.00', + '50000.00', + ]); + assert.ok( + staffTable(draft).issues.some((issue) => + /diverge da despesa de pessoal/.test(issue), + ), + 'before adoption the two sources disagree', + ); + + const paymentsBefore = business.restoreBusinessPlanSnapshot( + draft.business_plan_snapshot, + ).monthlyPayrollPayments; + const adopted = { + ...draft, + business_plan_snapshot: adoptTeamPayroll( + draft.business_plan_snapshot, + schedule, + false, + ), + }; + const plan = business.restoreBusinessPlanSnapshot( + adopted.business_plan_snapshot, + ); + assert.deepEqual(plan.monthlyPayrollExpenseByPeriod, schedule); + assert.equal( + plan.monthlyPayrollPayments, + paymentsBefore, + 'payments only change when asked', + ); + assert.ok( + !staffTable(adopted).issues.some((issue) => + /diverge da despesa de pessoal/.test(issue), + ), + 'after adoption the plan agrees with the map', + ); + const forecast = business.forecastBusinessPlan(plan); + assert.equal(forecast.rows[3].payrollExpense, '50000.00'); + + const withPayments = business.restoreBusinessPlanSnapshot( + adoptTeamPayroll(draft.business_plan_snapshot, schedule, true), + ); + assert.deepEqual(withPayments.monthlyPayrollPaymentsByPeriod, schedule); +}); + +test('an incomplete personnel map is never adopted as the plan payroll', () => { + const row = { + competency: 'Recepção', + department: 'Alojamento', + quantity: '2', + monthly_salary: '', + start_month: '1', + end_month: '12', + state: 'gap', + action: '', + estimated_cost: '', + due_date: '', + }; + assert.equal(teamPayrollSchedule(JSON.stringify([row]), 12), null); + assert.equal( + teamPayrollSchedule( + JSON.stringify([ + { + ...row, + monthly_salary: '100', + start_month: '5', + end_month: '2', + }, + ]), + 12, + ), + null, + ); + assert.equal(teamPayrollSchedule('[]', 12), null); + const constant = teamPayrollSchedule( + JSON.stringify([{ ...row, monthly_salary: '100' }]), + 12, + ); + assert.equal(constant.length, 12); + const { plan } = complementaryFixture(); + const restored = business.restoreBusinessPlanSnapshot( + adoptTeamPayroll( + business.serializeBusinessPlanSnapshot({ ...plan, periods: 12 }), + constant, + false, + ), + ); + assert.equal(restored.monthlyPayrollExpense, '200.00'); + assert.equal(restored.monthlyPayrollExpenseByPeriod, undefined); +}); + +test('the team step offers the adoption only while the plan differs, and says so once it agrees', () => { + const require = createRequire(import.meta.url); + const module = { exports: {} }; + const mocks = { + '@/lib/project-dossier': dossier, + '@/lib/business-financial-plan': business, + '@/lib/complementary-report': complementary, + '@/components/decimal-input': decimalInputModule, + './investment-report-tables': { InvestmentReportTables: () => null }, + }; + compileFunction( + ts.transpileModule( + fs.readFileSync( + 'resources/js/components/project-planning.tsx', + 'utf8', + ), + { + compilerOptions: { + module: ts.ModuleKind.CommonJS, + jsx: ts.JsxEmit.ReactJSX, + }, + }, + ).outputText, + ['require', 'module', 'exports'], + )((key) => mocks[key] ?? require(key), module, module.exports); + const { draft, team } = complementaryFixture(); + // The fixture plan matches the map; a raise makes the two sources differ. + draft.project_team_snapshot = JSON.stringify([ + { ...team[0], monthly_salary: '150.00' }, + ]); + const props = { + value: draft.project_team_snapshot, + onChange() {}, + financialPlanSnapshot: draft.business_plan_snapshot, + projectCurrency: 'MZN', + onAdoptPayroll() {}, + }; + const render = (extra) => + renderToStaticMarkup( + React.createElement(module.exports.ProjectTeamPlanner, { + ...props, + ...extra, + }), + ); + assert.match(render(), /Usar como custo mensal de pessoal/); + const schedule = teamPayrollSchedule(draft.project_team_snapshot, 13); + const agreed = render({ + financialPlanSnapshot: adoptTeamPayroll( + draft.business_plan_snapshot, + schedule, + false, + ), + }); + assert.doesNotMatch(agreed, /Usar como custo mensal de pessoal/); + assert.match(agreed, /coincide com este\s+mapa de pessoal/); + assert.doesNotMatch( + render({ projectCurrency: 'USD' }), + /Usar como custo mensal de pessoal/, + 'no adoption across currencies', + ); +});