@ossy/consultancy 3.20.1 → 3.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,11 @@
2
2
  "consultancy/home.documentTitle": "Overview",
3
3
  "consultancy/org.documentTitle": "Org Details",
4
4
  "consultancy/margins.documentTitle": "Margins",
5
+ "consultancy/employees.documentTitle": "Employees",
6
+ "consultancy/vacations.documentTitle": "Vacations",
7
+ "consultancy/contracts.documentTitle": "Contracts",
8
+ "consultancy/opportunities.documentTitle": "Opportunities",
9
+ "consultancy/proposals.documentTitle": "Proposals",
5
10
  "consultancy.home.title": "Overview",
6
11
  "consultancy.home.description": "Fiscal-year KPIs, year totals, and monthly capacity from contracts, employees, and vacations",
7
12
  "consultancy.org.title": "Org Details",
@@ -9,13 +14,27 @@
9
14
  "consultancy.nav.title": "Consultancy",
10
15
  "consultancy.nav.overview": "Overview",
11
16
  "consultancy.nav.forecasts": "Forecasts",
17
+ "consultancy.nav.employees": "Employees",
18
+ "consultancy.nav.vacations": "Vacations",
19
+ "consultancy.nav.contracts": "Contracts",
20
+ "consultancy.nav.opportunities": "Opportunities",
21
+ "consultancy.nav.proposals": "Proposals",
12
22
  "consultancy.nav.margins": "Margins",
13
23
  "consultancy.forecasts.title": "Overview",
14
24
  "consultancy.forecasts.description": "Fiscal-year KPIs, year totals, and monthly capacity from contracts, employees, and vacations",
15
25
  "consultancy.forecasts.income": "Income",
26
+ "consultancy.forecasts.forecastIncome": "Forecast income",
27
+ "consultancy.forecasts.actualIncome": "Actual income",
28
+ "consultancy.forecasts.forecastRevenue": "Forecast result",
29
+ "consultancy.forecasts.actualRevenue": "Actual result",
16
30
  "consultancy.forecasts.salaryCost": "Salary cost",
17
31
  "consultancy.forecasts.revenue": "Revenue",
18
32
  "consultancy.forecasts.hoursWorked": "Hours worked",
33
+ "consultancy.forecasts.utilization": "Utilization",
34
+ "consultancy.forecasts.forecastHours": "Forecast hours",
35
+ "consultancy.forecasts.actualHours": "Actual hours",
36
+ "consultancy.forecasts.unitMoney": "SEK",
37
+ "consultancy.forecasts.unitHours": "h",
19
38
  "consultancy.margins.title": "Margins",
20
39
  "consultancy.margins.description": "See assignment margin and admin leakage before you invoice",
21
40
  "consultancy.margins.notes.purpose": "Built for Nordic IT consultancies that outgrew timers + spreadsheets but do not need an enterprise PSA.",
@@ -40,6 +59,28 @@
40
59
  "consultancy.overview.fiscalYears": "Fiscal years",
41
60
  "consultancy.overview.company": "Company",
42
61
  "consultancy.overview.noFiscalYears": "No fiscal years yet.",
62
+ "consultancy.employees.title": "Employees",
63
+ "consultancy.employees.description": "People on the consultancy",
64
+ "consultancy.employees.empty": "No employees yet.",
65
+ "consultancy.vacations.title": "Vacations",
66
+ "consultancy.vacations.description": "Time off that is not billed",
67
+ "consultancy.vacations.empty": "No vacations yet.",
68
+ "consultancy.contracts.title": "Contracts",
69
+ "consultancy.contracts.description": "Client assignments and rates",
70
+ "consultancy.contracts.empty": "No contracts yet.",
71
+ "consultancy.opportunities.title": "Opportunities",
72
+ "consultancy.opportunities.description": "Pipeline of possible assignments",
73
+ "consultancy.opportunities.empty": "No opportunities yet.",
74
+ "consultancy.proposals.title": "Proposals",
75
+ "consultancy.proposals.description": "Offers sent for opportunities",
76
+ "consultancy.proposals.empty": "No proposals yet.",
77
+ "consultancy.records.loading": "Loading…",
78
+ "consultancy.add.company": "Company",
79
+ "consultancy.add.employee": "Employee",
80
+ "consultancy.add.contract": "Contract",
81
+ "consultancy.add.opportunity": "Opportunity",
82
+ "consultancy.add.proposal": "Proposal",
83
+ "consultancy.add.vacation": "Vacation",
43
84
  "consultancy.empty.title": "Looks empty",
44
85
  "consultancy.empty.text": "Add company info, employees, contracts, and vacations to get started.",
45
86
  "@ossy/consultancy/form/calculator.label": "Assignment margin calculator",
@@ -1,6 +1,7 @@
1
1
  /**
2
- * Pure layout helpers for the consultancy fiscal-year KPI line chart.
3
- * Money series share one Y-scale; hours use a secondary scale so shapes stay distinct.
2
+ * Pure layout helpers for consultancy line charts.
3
+ * Money series share one Y-scale. Series with `scale: 'hours'` (or the legacy
4
+ * `hoursWorked` key) share a second scale so hour shapes stay distinct from money.
4
5
  */
5
6
 
6
7
  export const MONEY_KEYS = ['projectedIncome', 'monthlyCostOfEmployees', 'revenue']
@@ -76,10 +77,11 @@ export function valueToY (value, extent, padY, innerH) {
76
77
  * @param {string} [options.language='en']
77
78
  * @param {number} [options.viewWidth=560]
78
79
  * @param {number} [options.plotHeight=140]
79
- * @param {number} [options.padX=16]
80
+ * @param {number} [options.padX=16] Right inset.
81
+ * @param {number} [options.padLeft=12] Left inset. Tick labels sit outside the plot.
80
82
  * @param {number} [options.padTop=12]
81
83
  * @param {number} [options.padBottom=28]
82
- * @returns {{ viewWidth: number, viewHeight: number, seriesPaths: Array<object>, monthLabels: Array<object> } | null}
84
+ * @returns {{ viewWidth: number, viewHeight: number, seriesPaths: Array<object>, monthLabels: Array<object>, yTicks: Array<object> } | null}
83
85
  */
84
86
  export function buildKpiChartLayout ({
85
87
  months,
@@ -88,26 +90,37 @@ export function buildKpiChartLayout ({
88
90
  viewWidth = 560,
89
91
  plotHeight = 140,
90
92
  padX = 16,
93
+ padLeft = 12,
91
94
  padTop = 12,
92
95
  padBottom = 28,
93
96
  }) {
94
97
  if (!months?.length || !series?.length) return null
95
98
 
96
99
  const viewHeight = padTop + plotHeight + padBottom
97
- const innerW = viewWidth - padX * 2
100
+ const innerW = Math.max(0, viewWidth - padLeft - padX)
98
101
  const innerH = plotHeight
99
102
  const step = months.length === 1 ? 0 : innerW / (months.length - 1)
100
103
 
101
- const moneyExtent = extentForKeys(months, MONEY_KEYS)
102
- const hoursExtent = extentForKeys(months, [HOURS_KEY])
104
+ const hoursKeys = [...new Set(
105
+ series
106
+ .filter((entry) => entry.scale === 'hours' || entry.key === HOURS_KEY)
107
+ .map((entry) => entry.key),
108
+ )]
109
+ const moneyKeys = [...new Set(
110
+ series
111
+ .filter((entry) => entry.scale !== 'hours' && entry.key !== HOURS_KEY)
112
+ .map((entry) => entry.key),
113
+ )]
114
+ const moneyExtent = moneyKeys.length ? extentForKeys(months, moneyKeys) : null
115
+ const hoursExtent = hoursKeys.length ? extentForKeys(months, hoursKeys) : null
103
116
 
104
117
  const seriesPaths = series.map((entry) => {
105
- const extent = entry.key === HOURS_KEY ? hoursExtent : moneyExtent
118
+ const extent = (entry.scale === 'hours' || entry.key === HOURS_KEY) ? hoursExtent : moneyExtent
106
119
  if (!extent) return { ...entry, path: null }
107
120
 
108
121
  const points = months.map((month, index) => {
109
122
  const value = Number(month[entry.key]) || 0
110
- const x = padX + index * step
123
+ const x = padLeft + index * step
111
124
  const y = valueToY(value, extent, padTop, innerH)
112
125
  return `${x},${y}`
113
126
  })
@@ -117,17 +130,31 @@ export function buildKpiChartLayout ({
117
130
  const monthLabels = months.map((month, index) => ({
118
131
  index,
119
132
  label: shortMonthLabel(month, language),
120
- x: padX + index * step,
133
+ x: padLeft + index * step,
121
134
  y: viewHeight - 6,
122
135
  }))
123
136
 
137
+ const tickScale = hoursExtent && !moneyExtent ? 'hours' : (moneyExtent ? 'money' : null)
138
+ const tickExtent = tickScale === 'hours' ? hoursExtent : moneyExtent
139
+ const yTicks = tickExtent
140
+ ? [tickExtent.max, tickExtent.min + (tickExtent.max - tickExtent.min) / 2, tickExtent.min].map((value) => ({
141
+ value,
142
+ label: formatChartTick(value, tickScale, language),
143
+ y: valueToY(value, tickExtent, padTop, innerH),
144
+ x1: padLeft,
145
+ x2: viewWidth - padX,
146
+ }))
147
+ : []
148
+
124
149
  return {
125
150
  viewWidth,
126
151
  viewHeight,
127
152
  seriesPaths,
128
153
  monthLabels,
154
+ yTicks,
129
155
  step,
130
156
  padX,
157
+ padLeft,
131
158
  padTop,
132
159
  padBottom,
133
160
  plotHeight,
@@ -135,3 +162,23 @@ export function buildKpiChartLayout ({
135
162
  innerH,
136
163
  }
137
164
  }
165
+
166
+ /**
167
+ * Compact axis number. The chart legend already states the unit.
168
+ *
169
+ * @param {number} value
170
+ * @param {'money'|'hours'} scale
171
+ * @param {string} [language='en']
172
+ * @returns {string}
173
+ */
174
+ export function formatChartTick (value, scale, language = 'en') {
175
+ const locale = language === 'sv' ? 'sv-SE' : 'en'
176
+ if (scale === 'hours') {
177
+ return new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(value)
178
+ }
179
+ const abs = Math.abs(value)
180
+ return new Intl.NumberFormat(locale, {
181
+ notation: abs >= 1000 ? 'compact' : 'standard',
182
+ maximumFractionDigits: abs >= 1000 ? 1 : 0,
183
+ }).format(value)
184
+ }
@@ -58,7 +58,7 @@ describe('buildKpiChartLayout', () => {
58
58
  it('spans the full viewBox width for N months', () => {
59
59
  const layout = buildKpiChartLayout({ months: sampleMonths, series, viewWidth: 100 })
60
60
  expect(layout).not.toBeNull()
61
- expect(layout.padX + (sampleMonths.length - 1) * layout.step).toBeCloseTo(100 - layout.padX)
61
+ expect(layout.padLeft + (sampleMonths.length - 1) * layout.step).toBeCloseTo(100 - layout.padX)
62
62
  expect(layout.viewWidth).toBe(100)
63
63
  })
64
64
 
@@ -106,8 +106,8 @@ describe('buildKpiChartLayout', () => {
106
106
  'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
107
107
  'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
108
108
  ])
109
- expect(layout.monthLabels[0].x).toBe(layout.padX)
110
- expect(layout.monthLabels[11].x).toBeCloseTo(layout.padX + 11 * layout.step)
109
+ expect(layout.monthLabels[0].x).toBe(layout.padLeft)
110
+ expect(layout.monthLabels[11].x).toBeCloseTo(layout.padLeft + 11 * layout.step)
111
111
  })
112
112
 
113
113
  it('defaults to a wide viewBox so meet-scaling keeps labels readable', () => {
@@ -119,4 +119,41 @@ describe('buildKpiChartLayout', () => {
119
119
  it('returns null for empty months', () => {
120
120
  expect(buildKpiChartLayout({ months: [], series })).toBeNull()
121
121
  })
122
+
123
+ it('plots hour series on one scale independent of money', () => {
124
+ const hourSeries = [
125
+ { key: 'forecastHours', label: 'forecast', color: 'blue', scale: 'hours' },
126
+ { key: 'actualHours', label: 'actual', color: 'green', scale: 'hours' },
127
+ ]
128
+ const months = [
129
+ { forecastHours: 0, actualHours: 40, projectedIncome: 100000 },
130
+ { forecastHours: 80, actualHours: 40, projectedIncome: 100000 },
131
+ ]
132
+ const layout = buildKpiChartLayout({ months, series: hourSeries })
133
+ const forecast = layout.seriesPaths.find((entry) => entry.key === 'forecastHours')
134
+ const actual = layout.seriesPaths.find((entry) => entry.key === 'actualHours')
135
+ const forecastStartY = Number(forecast.path.split(' ')[1].split(',')[1])
136
+ const actualStartY = Number(actual.path.split(' ')[1].split(',')[1])
137
+
138
+ expect(forecast.path).not.toBe(actual.path)
139
+ expect(forecastStartY).toBeGreaterThan(actualStartY)
140
+ expect(layout.yTicks.map((tick) => tick.label)).toEqual(['80', '40', '0'])
141
+ expect(layout.yTicks[0].y).toBeLessThan(layout.yTicks[2].y)
142
+ })
143
+
144
+ it('labels the money scale with compact values', () => {
145
+ const months = sampleMonths.map((month) => ({
146
+ ...month,
147
+ projectedIncome: month.projectedIncome * 10000,
148
+ monthlyCostOfEmployees: month.monthlyCostOfEmployees * 10000,
149
+ revenue: month.revenue * 10000,
150
+ }))
151
+ const layout = buildKpiChartLayout({
152
+ months,
153
+ series: series.filter((entry) => entry.key !== 'hoursWorked'),
154
+ language: 'en',
155
+ })
156
+ expect(layout.yTicks.map((tick) => tick.label)).toEqual(['2M', '1.3M', '500K'])
157
+ expect(layout.yTicks[0].y).toBeLessThan(layout.yTicks[2].y)
158
+ })
122
159
  })
@@ -0,0 +1,26 @@
1
+ import React from 'react'
2
+ import { ConsultancyRecordPage } from './ConsultancyRecordList.jsx'
3
+ import { ConsultancySchema } from './schema-ids.js'
4
+ import opportunitySchema from './opportunity.schema.js'
5
+
6
+ export const metadata = {
7
+ id: 'consultancy/opportunities',
8
+ path: {
9
+ sv: '/konsultverksamhet/mojligheter',
10
+ en: '/consultancy/opportunities',
11
+ },
12
+ }
13
+
14
+ export const OpportunitiesPage = () => (
15
+ <ConsultancyRecordPage
16
+ active="consultancy/opportunities"
17
+ title="consultancy.opportunities.title"
18
+ description="consultancy.opportunities.description"
19
+ schemaId={ConsultancySchema.opportunity}
20
+ icon={opportunitySchema.icon}
21
+ listHeader="consultancy.nav.opportunities"
22
+ emptyText="consultancy.opportunities.empty"
23
+ />
24
+ )
25
+
26
+ export default OpportunitiesPage
@@ -4,7 +4,7 @@ export default {
4
4
  name: 'Opportunity',
5
5
  id: ConsultancySchema.opportunity,
6
6
  categoryName: 'Consultancy',
7
- icon: 'target',
7
+ icon: 'briefcase',
8
8
  fields: [
9
9
  { name: 'title', type: 'text' },
10
10
  { name: 'source', type: 'text' },
@@ -0,0 +1,26 @@
1
+ import React from 'react'
2
+ import { ConsultancyRecordPage } from './ConsultancyRecordList.jsx'
3
+ import { ConsultancySchema } from './schema-ids.js'
4
+ import proposalSchema from './proposal.schema.js'
5
+
6
+ export const metadata = {
7
+ id: 'consultancy/proposals',
8
+ path: {
9
+ sv: '/konsultverksamhet/offerter',
10
+ en: '/consultancy/proposals',
11
+ },
12
+ }
13
+
14
+ export const ProposalsPage = () => (
15
+ <ConsultancyRecordPage
16
+ active="consultancy/proposals"
17
+ title="consultancy.proposals.title"
18
+ description="consultancy.proposals.description"
19
+ schemaId={ConsultancySchema.proposal}
20
+ icon={proposalSchema.icon}
21
+ listHeader="consultancy.nav.proposals"
22
+ emptyText="consultancy.proposals.empty"
23
+ />
24
+ )
25
+
26
+ export default ProposalsPage
@@ -2,6 +2,11 @@
2
2
  "consultancy/home.documentTitle": "Översikt",
3
3
  "consultancy/org.documentTitle": "Orgdetaljer",
4
4
  "consultancy/margins.documentTitle": "Marginaler",
5
+ "consultancy/employees.documentTitle": "Anställda",
6
+ "consultancy/vacations.documentTitle": "Semester",
7
+ "consultancy/contracts.documentTitle": "Avtal",
8
+ "consultancy/opportunities.documentTitle": "Möjligheter",
9
+ "consultancy/proposals.documentTitle": "Offerter",
5
10
  "consultancy.home.title": "Översikt",
6
11
  "consultancy.home.description": "KPIer för räkenskapsåret, års totalsummor och månadskapacitet från avtal, anställda och semester",
7
12
  "consultancy.org.title": "Orgdetaljer",
@@ -9,13 +14,27 @@
9
14
  "consultancy.nav.title": "Konsultverksamhet",
10
15
  "consultancy.nav.overview": "Översikt",
11
16
  "consultancy.nav.forecasts": "Prognoser",
17
+ "consultancy.nav.employees": "Anställda",
18
+ "consultancy.nav.vacations": "Semester",
19
+ "consultancy.nav.contracts": "Avtal",
20
+ "consultancy.nav.opportunities": "Möjligheter",
21
+ "consultancy.nav.proposals": "Offerter",
12
22
  "consultancy.nav.margins": "Marginaler",
13
23
  "consultancy.forecasts.title": "Översikt",
14
24
  "consultancy.forecasts.description": "KPIer för räkenskapsåret, års totalsummor och månadskapacitet från avtal, anställda och semester",
15
25
  "consultancy.forecasts.income": "Intäkt",
26
+ "consultancy.forecasts.forecastIncome": "Prognostiserad intäkt",
27
+ "consultancy.forecasts.actualIncome": "Faktisk intäkt",
28
+ "consultancy.forecasts.forecastRevenue": "Prognostiserat resultat",
29
+ "consultancy.forecasts.actualRevenue": "Faktiskt resultat",
16
30
  "consultancy.forecasts.salaryCost": "Lönekostnad",
17
31
  "consultancy.forecasts.revenue": "Resultat",
18
32
  "consultancy.forecasts.hoursWorked": "Arbetade timmar",
33
+ "consultancy.forecasts.utilization": "Beläggning",
34
+ "consultancy.forecasts.forecastHours": "Prognostiserade timmar",
35
+ "consultancy.forecasts.actualHours": "Faktiska timmar",
36
+ "consultancy.forecasts.unitMoney": "kr",
37
+ "consultancy.forecasts.unitHours": "tim",
19
38
  "consultancy.margins.title": "Marginaler",
20
39
  "consultancy.margins.description": "Se uppdragets marginal och adminläckage innan du fakturerar",
21
40
  "consultancy.margins.notes.purpose": "Byggt för nordiska IT-konsultbolag som vuxit ur timer + kalkylark men inte behöver ett tungt PSA.",
@@ -40,6 +59,28 @@
40
59
  "consultancy.overview.fiscalYears": "Räkenskapsår",
41
60
  "consultancy.overview.company": "Företag",
42
61
  "consultancy.overview.noFiscalYears": "Inga räkenskapsår ännu.",
62
+ "consultancy.employees.title": "Anställda",
63
+ "consultancy.employees.description": "Personer i konsultverksamheten",
64
+ "consultancy.employees.empty": "Inga anställda ännu.",
65
+ "consultancy.vacations.title": "Semester",
66
+ "consultancy.vacations.description": "Ledighet som inte faktureras",
67
+ "consultancy.vacations.empty": "Ingen semester ännu.",
68
+ "consultancy.contracts.title": "Avtal",
69
+ "consultancy.contracts.description": "Kunduppdrag och timpriser",
70
+ "consultancy.contracts.empty": "Inga avtal ännu.",
71
+ "consultancy.opportunities.title": "Möjligheter",
72
+ "consultancy.opportunities.description": "Pipeline med möjliga uppdrag",
73
+ "consultancy.opportunities.empty": "Inga möjligheter ännu.",
74
+ "consultancy.proposals.title": "Offerter",
75
+ "consultancy.proposals.description": "Offerter skickade för möjligheter",
76
+ "consultancy.proposals.empty": "Inga offerter ännu.",
77
+ "consultancy.records.loading": "Laddar…",
78
+ "consultancy.add.company": "Företag",
79
+ "consultancy.add.employee": "Anställd",
80
+ "consultancy.add.contract": "Avtal",
81
+ "consultancy.add.opportunity": "Möjlighet",
82
+ "consultancy.add.proposal": "Offert",
83
+ "consultancy.add.vacation": "Semester",
43
84
  "consultancy.empty.title": "Här är tomt",
44
85
  "consultancy.empty.text": "Lägg till företagsinfo, anställda, avtal och semester för att komma igång.",
45
86
  "@ossy/consultancy/form/calculator.label": "Uppdragsmarginalkalkylator",
@@ -0,0 +1,196 @@
1
+ import { isDayInInclusiveRange, localDayKey, resourceIdOf, utcDayKey } from '@ossy/calendar/holiday-locale'
2
+
3
+ /** Timesheet documents used for beläggning actuals. */
4
+ export const TIMESHEET_LOCATION = '/@ossy/timesheets/sheets/'
5
+ export const TIMESHEET_TYPE = '@ossy/timesheets/schema/timesheet'
6
+
7
+ function contentOf (resource) {
8
+ if (resource?.content && typeof resource.content === 'object') {
9
+ return { ...resource.content, id: resource.id ?? resource.content.id }
10
+ }
11
+ return resource ?? {}
12
+ }
13
+
14
+ function padMonth (monthNumber) {
15
+ return String(monthNumber).padStart(2, '0')
16
+ }
17
+
18
+ /**
19
+ * Local calendar month of a timesheet line date.
20
+ * Timesheet rows are stored as local-midnight timestamps.
21
+ *
22
+ * @param {unknown} value
23
+ * @returns {{ year: string, monthNumber: string } | null}
24
+ */
25
+ export function localMonthOf (value) {
26
+ if (value == null || value === '') return null
27
+ const date = value instanceof Date ? value : new Date(value)
28
+ if (Number.isNaN(date.getTime())) return null
29
+ return {
30
+ year: String(date.getFullYear()),
31
+ monthNumber: padMonth(date.getMonth() + 1),
32
+ }
33
+ }
34
+
35
+ function dayKeysForLine (employeeId, lineDate) {
36
+ if (!employeeId) return []
37
+ const keys = []
38
+ const utc = utcDayKey(lineDate)
39
+ if (utc) keys.push(`${employeeId}:${utc}`)
40
+ const date = lineDate instanceof Date ? lineDate : new Date(lineDate)
41
+ if (!Number.isNaN(date.getTime())) keys.push(`${employeeId}:${localDayKey(date)}`)
42
+ return keys
43
+ }
44
+
45
+ function contractRecord (contract) {
46
+ if (contract?.content && typeof contract.content === 'object') {
47
+ return { ...contract.content, id: contract.id ?? contract.content.id }
48
+ }
49
+ return contract ?? {}
50
+ }
51
+
52
+ /**
53
+ * Hourly rate for a timesheet. Prefer its contract, then the employee's contract.
54
+ *
55
+ * @param {object} content
56
+ * @param {Array<object>} contracts
57
+ * @returns {number}
58
+ */
59
+ function hourlyRateForSheet (content, contracts) {
60
+ const list = Array.isArray(contracts) ? contracts.map(contractRecord) : []
61
+ const contractId = resourceIdOf(content.contractId)
62
+ const employeeId = resourceIdOf(content.employeeId)
63
+ const contract = (contractId && list.find((entry) => entry.id === contractId))
64
+ || (employeeId && list.find((entry) => resourceIdOf(entry.employeeId) === employeeId))
65
+ || null
66
+ const rate = Number(contract?.hourlyCompensation)
67
+ return Number.isFinite(rate) ? rate : 0
68
+ }
69
+
70
+ function lineInMonth (lineDate, month) {
71
+ const local = localMonthOf(lineDate)
72
+ if (!local) return false
73
+ return local.year === String(month.year) && local.monthNumber === padMonth(month.monthNumber)
74
+ }
75
+
76
+ /**
77
+ * Actual hours for one fiscal month.
78
+ *
79
+ * Timesheet line hours in the month are the reported actuals. Vacation is
80
+ * included by adding the employee's work hours for each vacation workday that
81
+ * has no timesheet line yet, so an unlogged vacation still counts.
82
+ *
83
+ * @param {object} options
84
+ * @param {{ year?: number|string, monthNumber?: number|string, days?: Array<{ date: string, isWorkday?: boolean }> }} options.month
85
+ * @param {Array<object>} [options.timesheets]
86
+ * @param {Array<object>} [options.vacations]
87
+ * @param {Array<object>} [options.employees]
88
+ * @returns {number}
89
+ */
90
+ export function actualHoursForMonth ({
91
+ month,
92
+ timesheets = [],
93
+ vacations = [],
94
+ employees = [],
95
+ }) {
96
+ if (!month) return 0
97
+
98
+ let hours = 0
99
+ /** @type {Set<string>} */
100
+ const covered = new Set()
101
+
102
+ for (const sheet of timesheets) {
103
+ const content = contentOf(sheet)
104
+ const employeeId = resourceIdOf(content.employeeId) || ''
105
+ for (const line of content.lines || []) {
106
+ if (!lineInMonth(line?.date, month)) continue
107
+ hours += Number(line.hours) || 0
108
+ for (const key of dayKeysForLine(employeeId, line?.date)) covered.add(key)
109
+ }
110
+ }
111
+
112
+ const employeesById = new Map(employees.map((employee) => {
113
+ const content = contentOf(employee)
114
+ return [content.id, content]
115
+ }))
116
+
117
+ for (const vacation of vacations) {
118
+ const content = contentOf(vacation)
119
+ const employeeId = resourceIdOf(content.employeeId)
120
+ const perDay = Number(employeesById.get(employeeId)?.workHoursPerDay) || 0
121
+ if (!employeeId || !perDay) continue
122
+
123
+ for (const day of month.days || []) {
124
+ if (!day?.isWorkday || !day.date) continue
125
+ if (!isDayInInclusiveRange(day.date, content.start, content.end)) continue
126
+ const key = `${employeeId}:${day.date}`
127
+ if (covered.has(key)) continue
128
+ hours += perDay
129
+ covered.add(key)
130
+ }
131
+ }
132
+
133
+ return hours
134
+ }
135
+
136
+ /**
137
+ * Billable income from timesheet lines in the month, at each sheet's contract rate.
138
+ * Vacation days are not billed unless they are logged on a timesheet.
139
+ *
140
+ * @param {object} options
141
+ * @param {object} options.month
142
+ * @param {Array<object>} [options.timesheets]
143
+ * @param {Array<object>} [options.contracts]
144
+ * @returns {number}
145
+ */
146
+ export function actualIncomeForMonth ({
147
+ month,
148
+ timesheets = [],
149
+ contracts = [],
150
+ }) {
151
+ if (!month) return 0
152
+
153
+ let income = 0
154
+ for (const sheet of timesheets) {
155
+ const content = contentOf(sheet)
156
+ const rate = hourlyRateForSheet(content, contracts)
157
+ if (!rate) continue
158
+ for (const line of content.lines || []) {
159
+ if (!lineInMonth(line?.date, month)) continue
160
+ income += (Number(line.hours) || 0) * rate
161
+ }
162
+ }
163
+ return income
164
+ }
165
+
166
+ /**
167
+ * Attach forecast and actual hour series to fiscal-year months.
168
+ * Forecast hours are the contract projection (`hoursWorked`), which already
169
+ * drops vacation days, weekends, and days outside the contract.
170
+ *
171
+ * @param {object} options
172
+ * @param {Array<object>} options.months
173
+ * @param {Array<object>} [options.timesheets]
174
+ * @param {Array<object>} [options.vacations]
175
+ * @param {Array<object>} [options.employees]
176
+ * @param {Array<object>} [options.contracts]
177
+ */
178
+ export function withUtilizationHours ({
179
+ months = [],
180
+ timesheets = [],
181
+ vacations = [],
182
+ employees = [],
183
+ contracts = [],
184
+ } = {}) {
185
+ return months.map((month) => {
186
+ const actualIncome = actualIncomeForMonth({ month, timesheets, contracts })
187
+ const salary = Number(month.monthlyCostOfEmployees) || 0
188
+ return {
189
+ ...month,
190
+ forecastHours: Number(month.hoursWorked) || 0,
191
+ actualHours: actualHoursForMonth({ month, timesheets, vacations, employees }),
192
+ actualIncome,
193
+ actualRevenue: actualIncome - salary,
194
+ }
195
+ })
196
+ }