@@ -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 ) * 100 n + 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 ) * 10000 n + BigInt ( fraction . padEnd ( 4 , '0' ) ) ) *
( s . growthPercent . startsWith ( '-' ) ? - 1n : 1n ) ;
for ( let y = 1 ; y < years ; y ++ ) {
const next =
( BigInt ( clients ) * ( 1000000 n + growthUnits ) + 500000 n ) /
1000000 n ;
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 ) ! / s e r i e s [ 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 = 0 n ,
actual = 0 n ,
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 ( 0 n ) 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 ) : 0 n ,
) ;
values . forEach ( ( v , j ) = > ( totals [ j ] += v ) ) ;
const annual = years . map ( ( _ , y ) = >
values . slice ( y * 12 , y * 12 + 12 ) . reduce ( ( a , b ) = > a + b , 0 n ) ,
) ;
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 , 0 n ) ,
) ;
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 , 0 n ) ,
) ,
) ,
] ) ;
if ( differences . some ( ( v ) = > v !== 0 n ) )
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 ] ;
}