import { forecastBusinessPlan, businessPlanNumberError, 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(raw: string, keys: string[], optional: string[]) { const rows = readRows(raw, keys).filter((r) => optional.every( (k) => !(k in (r as object)) || typeof (r as Record)[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 { if (!value || typeof value !== 'object' || Array.isArray(value)) return false; const m = value as Record; 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, 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( `Pessoal / Moeda das remunerações (${declaredCurrency}) difere de Plano financeiro / Moeda (${plan?.currency}). Confira a moeda e os montantes de origem e corrija apenas os campos incorrectos. Enquanto forem moedas diferentes, 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( 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) ) milestones.issues.push( `Marco ${i + 1}: complete título, responsável, departamento e datas de início/término válidas.`, ); if ( date(r.start_date ?? '') && date(r.due_date) && r.start_date! > r.due_date ) milestones.issues.push( `Marcos / Marco ${i + 1} / «Prazo previsto»: A data de término não pode ser anterior à data de início.`, ); 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( 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 quantityError = businessPlanNumberError(r.quantity ?? '', { integer: true, }); if (quantityError) throw Error( `«Quantidade de pessoas (inteiro)»: ${quantityError}`, ); 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]; }