@ossy/consultancy 3.21.0 → 3.22.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.
- package/package.json +3 -2
- package/src/AssignmentMarginCalculator.jsx +7 -32
- package/src/ConsultancyNav.jsx +17 -9
- package/src/Forecast.jsx +42 -343
- package/src/Overview.jsx +10 -31
- package/src/RequestStatsPanel.jsx +66 -0
- package/src/consultancy.page.jsx +3 -40
- package/src/current-month.component.jsx +43 -25
- package/src/en.translations.json +26 -2
- package/src/extract-request.action.js +5 -0
- package/src/extract-request.task.js +100 -0
- package/src/extract-request.task.spec.js +89 -0
- package/src/forecast-panels.jsx +125 -0
- package/src/forecast-widget-menu.jsx +89 -0
- package/src/get-request-stats.action.js +6 -0
- package/src/get-request-stats.task.js +26 -0
- package/src/index.js +1 -0
- package/src/intake-categories.js +39 -0
- package/src/kpi-trend.component.jsx +17 -0
- package/src/margin-panels.jsx +7 -32
- package/src/org.page.jsx +1 -2
- package/src/reports.page.jsx +103 -0
- package/src/request-buckets.js +76 -0
- package/src/request-buckets.spec.js +33 -0
- package/src/request-stats.aggregate.js +52 -0
- package/src/request-stats.aggregate.spec.js +34 -0
- package/src/request-stats.component.jsx +16 -0
- package/src/request.schema.js +29 -0
- package/src/requests.page.jsx +26 -0
- package/src/schema-ids.js +1 -0
- package/src/screen-inbound.task.js +84 -0
- package/src/screen-inbound.task.spec.js +97 -0
- package/src/sv.translations.json +26 -2
- package/src/use-chart-months.js +27 -0
- package/src/utilization.component.jsx +17 -0
- package/src/year-totals.component.jsx +17 -0
- package/src/forecast-kpi-chart.js +0 -184
- package/src/forecast-kpi-chart.spec.js +0 -159
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { location } from './locations.js'
|
|
2
|
+
import { ConsultancySchema } from './schema-ids.js'
|
|
3
|
+
import { requestSourceText } from './extract-request.task.js'
|
|
4
|
+
import {
|
|
5
|
+
INTAKE_CATEGORIES,
|
|
6
|
+
acceptsRequestCategory,
|
|
7
|
+
} from './intake-categories.js'
|
|
8
|
+
|
|
9
|
+
const GetResource = { id: '@ossy/resources/actions/get' }
|
|
10
|
+
const Categorize = { id: '@ossy/media-tasks/actions/categorize' }
|
|
11
|
+
const ExtractRequest = { id: '@ossy/consultancy/actions/extract-request' }
|
|
12
|
+
const INBOUND_MESSAGE = '@ossy/email/schema/inbound-message'
|
|
13
|
+
|
|
14
|
+
export const metadata = {
|
|
15
|
+
id: '@ossy/consultancy/tasks/screen-inbound',
|
|
16
|
+
triggers: [
|
|
17
|
+
{
|
|
18
|
+
type: INBOUND_MESSAGE,
|
|
19
|
+
event: 'Created',
|
|
20
|
+
},
|
|
21
|
+
],
|
|
22
|
+
outputs: [
|
|
23
|
+
{
|
|
24
|
+
name: 'request',
|
|
25
|
+
kind: 'location',
|
|
26
|
+
schemaId: ConsultancySchema.request,
|
|
27
|
+
prefix: location,
|
|
28
|
+
},
|
|
29
|
+
],
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function fail (message, status) {
|
|
33
|
+
throw Object.assign(new Error(message), { status })
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function workspaceIdFrom ({ event, payload, req }) {
|
|
37
|
+
return event?.payload?.belongsTo
|
|
38
|
+
?? event?.belongsTo
|
|
39
|
+
?? payload?.workspaceId
|
|
40
|
+
?? req?.workspaceId
|
|
41
|
+
?? null
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* New inbound mail is categorized first. A consultancy request is extracted.
|
|
46
|
+
* Anything else stays in the inbox.
|
|
47
|
+
*/
|
|
48
|
+
export async function run ({ event, payload, req, sdk }) {
|
|
49
|
+
if (!sdk?.invoke) fail('sdk is required', 500)
|
|
50
|
+
|
|
51
|
+
const resourceId = event?.resourceId || payload?.resourceId
|
|
52
|
+
if (!resourceId) fail('resourceId is required', 400)
|
|
53
|
+
|
|
54
|
+
const workspaceId = workspaceIdFrom({ event, payload, req })
|
|
55
|
+
if (!workspaceId) fail('workspaceId is required', 400)
|
|
56
|
+
|
|
57
|
+
const resource = await sdk.invoke(GetResource, { resourceId })
|
|
58
|
+
if (resource?.type !== INBOUND_MESSAGE) fail('inbound message is required', 400)
|
|
59
|
+
|
|
60
|
+
const text = requestSourceText(resource)
|
|
61
|
+
if (!text) {
|
|
62
|
+
return { skipped: true, reason: 'empty', category: null, confidence: null }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const categorized = await sdk.invoke(Categorize, {
|
|
66
|
+
workspaceId,
|
|
67
|
+
text,
|
|
68
|
+
categories: INTAKE_CATEGORIES,
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
const category = typeof categorized?.category === 'string' ? categorized.category : null
|
|
72
|
+
const confidence = typeof categorized?.confidence === 'number' ? categorized.confidence : null
|
|
73
|
+
if (!acceptsRequestCategory({ category, confidence })) {
|
|
74
|
+
return { skipped: true, reason: 'category', category, confidence }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const request = await sdk.invoke(ExtractRequest, { resourceId, workspaceId })
|
|
78
|
+
return {
|
|
79
|
+
skipped: false,
|
|
80
|
+
category,
|
|
81
|
+
confidence,
|
|
82
|
+
requestId: request?.id ?? null,
|
|
83
|
+
}
|
|
84
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { metadata, run } from './screen-inbound.task.js'
|
|
2
|
+
import { INTAKE_CATEGORIES, REQUEST_CATEGORY } from './intake-categories.js'
|
|
3
|
+
import { requestSourceText } from './extract-request.task.js'
|
|
4
|
+
|
|
5
|
+
const GetResource = { id: '@ossy/resources/actions/get' }
|
|
6
|
+
const Categorize = { id: '@ossy/media-tasks/actions/categorize' }
|
|
7
|
+
const ExtractRequest = { id: '@ossy/consultancy/actions/extract-request' }
|
|
8
|
+
|
|
9
|
+
const inbound = {
|
|
10
|
+
id: 'msg-1',
|
|
11
|
+
type: '@ossy/email/schema/inbound-message',
|
|
12
|
+
content: {
|
|
13
|
+
from: 'Anna Berg <anna@client.se>',
|
|
14
|
+
subject: 'Senior React, 6 manader',
|
|
15
|
+
text: 'Vi soker en senior React-utvecklare i Stockholm.',
|
|
16
|
+
messageId: 'assignment-1@client.se',
|
|
17
|
+
},
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function sdkFor (categorized) {
|
|
21
|
+
const calls = []
|
|
22
|
+
const sdk = {
|
|
23
|
+
async invoke (action, payload) {
|
|
24
|
+
calls.push({ id: action.id, payload })
|
|
25
|
+
if (action.id === GetResource.id) return inbound
|
|
26
|
+
if (action.id === Categorize.id) return categorized
|
|
27
|
+
if (action.id === ExtractRequest.id) return { id: 'request-1' }
|
|
28
|
+
throw new Error(`unexpected ${action.id}`)
|
|
29
|
+
},
|
|
30
|
+
}
|
|
31
|
+
return { calls, sdk }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
describe('screen-inbound task', () => {
|
|
35
|
+
it('listens for a new inbound message', () => {
|
|
36
|
+
expect(metadata.triggers).toEqual([
|
|
37
|
+
{ type: '@ossy/email/schema/inbound-message', event: 'Created' },
|
|
38
|
+
])
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
it('extracts a request when the category is a confident consultancy request', async () => {
|
|
42
|
+
const { calls, sdk } = sdkFor({ category: REQUEST_CATEGORY, confidence: 1 })
|
|
43
|
+
const result = await run({
|
|
44
|
+
event: { resourceId: inbound.id, payload: { belongsTo: 'ws-1' } },
|
|
45
|
+
sdk,
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
const categorize = calls.find((call) => call.id === Categorize.id)
|
|
49
|
+
expect(categorize.payload).toMatchObject({
|
|
50
|
+
workspaceId: 'ws-1',
|
|
51
|
+
text: requestSourceText(inbound),
|
|
52
|
+
categories: INTAKE_CATEGORIES,
|
|
53
|
+
})
|
|
54
|
+
expect(calls.map((call) => call.id)).toEqual([
|
|
55
|
+
GetResource.id,
|
|
56
|
+
Categorize.id,
|
|
57
|
+
ExtractRequest.id,
|
|
58
|
+
])
|
|
59
|
+
expect(calls.find((call) => call.id === ExtractRequest.id).payload).toEqual({
|
|
60
|
+
resourceId: inbound.id,
|
|
61
|
+
workspaceId: 'ws-1',
|
|
62
|
+
})
|
|
63
|
+
expect(result).toEqual({
|
|
64
|
+
skipped: false,
|
|
65
|
+
category: REQUEST_CATEGORY,
|
|
66
|
+
confidence: 1,
|
|
67
|
+
requestId: 'request-1',
|
|
68
|
+
})
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
it('leaves a contact message in the inbox', async () => {
|
|
72
|
+
const { calls, sdk } = sdkFor({ category: 'contact', confidence: 0.99 })
|
|
73
|
+
const result = await run({
|
|
74
|
+
event: { resourceId: inbound.id, payload: { belongsTo: 'ws-1' } },
|
|
75
|
+
sdk,
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
expect(calls.map((call) => call.id)).not.toContain(ExtractRequest.id)
|
|
79
|
+
expect(result).toEqual({
|
|
80
|
+
skipped: true,
|
|
81
|
+
reason: 'category',
|
|
82
|
+
category: 'contact',
|
|
83
|
+
confidence: 0.99,
|
|
84
|
+
})
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
it('leaves a low-confidence consultancy request in the inbox', async () => {
|
|
88
|
+
const { calls, sdk } = sdkFor({ category: REQUEST_CATEGORY, confidence: 0.4 })
|
|
89
|
+
const result = await run({
|
|
90
|
+
event: { resourceId: inbound.id, payload: { belongsTo: 'ws-1' } },
|
|
91
|
+
sdk,
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
expect(calls.map((call) => call.id)).not.toContain(ExtractRequest.id)
|
|
95
|
+
expect(result).toMatchObject({ skipped: true, reason: 'category', confidence: 0.4 })
|
|
96
|
+
})
|
|
97
|
+
})
|
package/src/sv.translations.json
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
"consultancy/vacations.documentTitle": "Semester",
|
|
7
7
|
"consultancy/contracts.documentTitle": "Avtal",
|
|
8
8
|
"consultancy/opportunities.documentTitle": "Möjligheter",
|
|
9
|
+
"consultancy/requests.documentTitle": "Förfrågningar",
|
|
10
|
+
"consultancy/reports.documentTitle": "Rapporter",
|
|
9
11
|
"consultancy/proposals.documentTitle": "Offerter",
|
|
10
12
|
"consultancy.home.title": "Översikt",
|
|
11
13
|
"consultancy.home.description": "KPIer för räkenskapsåret, års totalsummor och månadskapacitet från avtal, anställda och semester",
|
|
@@ -17,8 +19,10 @@
|
|
|
17
19
|
"consultancy.nav.employees": "Anställda",
|
|
18
20
|
"consultancy.nav.vacations": "Semester",
|
|
19
21
|
"consultancy.nav.contracts": "Avtal",
|
|
22
|
+
"consultancy.nav.requests": "Förfrågningar",
|
|
20
23
|
"consultancy.nav.opportunities": "Möjligheter",
|
|
21
24
|
"consultancy.nav.proposals": "Offerter",
|
|
25
|
+
"consultancy.nav.reports": "Rapporter",
|
|
22
26
|
"consultancy.nav.margins": "Marginaler",
|
|
23
27
|
"consultancy.forecasts.title": "Översikt",
|
|
24
28
|
"consultancy.forecasts.description": "KPIer för räkenskapsåret, års totalsummor och månadskapacitet från avtal, anställda och semester",
|
|
@@ -68,6 +72,16 @@
|
|
|
68
72
|
"consultancy.contracts.title": "Avtal",
|
|
69
73
|
"consultancy.contracts.description": "Kunduppdrag och timpriser",
|
|
70
74
|
"consultancy.contracts.empty": "Inga avtal ännu.",
|
|
75
|
+
"consultancy.requests.title": "Förfrågningar",
|
|
76
|
+
"consultancy.requests.description": "Uppdrag tolkade från inkommande e-post",
|
|
77
|
+
"consultancy.requests.empty": "Inga förfrågningar ännu.",
|
|
78
|
+
"consultancy.requests.statsTitle": "Inkommande förfrågningar",
|
|
79
|
+
"consultancy.requests.statsSeries": "Förfrågningar",
|
|
80
|
+
"consultancy.requests.statsUnit": "förfrågningar",
|
|
81
|
+
"consultancy.requests.statsEmpty": "Inga daterade förfrågningar ännu.",
|
|
82
|
+
"consultancy.reports.title": "Rapporter",
|
|
83
|
+
"consultancy.reports.description": "Diagram över inkommande arbete",
|
|
84
|
+
"consultancy.reports.empty": "Inga rapporter ännu.",
|
|
71
85
|
"consultancy.opportunities.title": "Möjligheter",
|
|
72
86
|
"consultancy.opportunities.description": "Pipeline med möjliga uppdrag",
|
|
73
87
|
"consultancy.opportunities.empty": "Inga möjligheter ännu.",
|
|
@@ -187,7 +201,8 @@
|
|
|
187
201
|
"@ossy/consultancy/schema/proposal.body.description": "Hela anbudstexten.",
|
|
188
202
|
"consultancy.nav.orgDetails": "Orgdetaljer",
|
|
189
203
|
"consultancy.forecasts.yearChart": "KPI-trend",
|
|
190
|
-
"consultancy.forecasts.
|
|
204
|
+
"consultancy.forecasts.monthForecast": "{month} prognos",
|
|
205
|
+
"consultancy.forecasts.yearSummary": "Räkenskapsåret prognos",
|
|
191
206
|
"consultancy.forecasts.yearChartEmpty": "Inga prognosmånader att visa ännu.",
|
|
192
207
|
"consultancy.margins.pin.done": "Nålad på instrumentpanel",
|
|
193
208
|
"consultancy.margins.pin.error": "Nålning misslyckades — försök igen",
|
|
@@ -202,5 +217,14 @@
|
|
|
202
217
|
"consultancy.widgets.adminLeakage.title": "Adminläckage",
|
|
203
218
|
"consultancy.widgets.adminLeakage.description": "Årliga timmar och intäkter som går förlorade på återkommande admin.",
|
|
204
219
|
"consultancy.widgets.forecastCurrentMonth.title": "Prognos denna månad",
|
|
205
|
-
"consultancy.widgets.forecastCurrentMonth.description": "Prognostiserad intäkt, lönekostnad, omsättning och timmar för innevarande månad."
|
|
220
|
+
"consultancy.widgets.forecastCurrentMonth.description": "Prognostiserad intäkt, lönekostnad, omsättning och timmar för innevarande månad.",
|
|
221
|
+
"consultancy.widgets.kpiTrend.title": "KPI-trend",
|
|
222
|
+
"consultancy.widgets.kpiTrend.description": "Prognos och utfall för intäkt, lönekostnad och omsättning under räkenskapsåret.",
|
|
223
|
+
"consultancy.widgets.yearTotals.title": "Räkenskapsåret prognos",
|
|
224
|
+
"consultancy.widgets.yearTotals.description": "Intäkt, lönekostnad, omsättning och timmar för räkenskapsåret.",
|
|
225
|
+
"consultancy.widgets.utilization.title": "Beläggning",
|
|
226
|
+
"consultancy.widgets.utilization.description": "Prognostiserade och faktiska timmar under räkenskapsåret.",
|
|
227
|
+
"consultancy.widgets.requestStats.title": "Inkommande förfrågningar",
|
|
228
|
+
"consultancy.widgets.requestStats.description": "Förfrågningar per månad, daterade efter e-postens egen ankomsttid.",
|
|
229
|
+
"consultancy.widgets.menu": "Mer"
|
|
206
230
|
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { useMemo } from 'react'
|
|
2
|
+
import { useContracts, useEmployees, useForecast, useVacations } from '@ossy/calendar'
|
|
3
|
+
import { ListResources } from '@ossy/resources'
|
|
4
|
+
import { useSdk } from '@ossy/sdk-react'
|
|
5
|
+
import { TIMESHEET_LOCATION, TIMESHEET_TYPE, withUtilizationHours } from './utilization-hours.js'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Fiscal-year months with timesheet actuals merged in.
|
|
9
|
+
* Shared by the overview and the pinnable forecast widgets.
|
|
10
|
+
*/
|
|
11
|
+
export function useChartMonths () {
|
|
12
|
+
const months = useForecast()
|
|
13
|
+
const contracts = useContracts()
|
|
14
|
+
const employees = useEmployees()
|
|
15
|
+
const vacations = useVacations()
|
|
16
|
+
const sdk = useSdk()
|
|
17
|
+
const { data: timesheetResources = [] } = sdk.read(ListResources, { location: TIMESHEET_LOCATION })
|
|
18
|
+
|
|
19
|
+
return useMemo(() => withUtilizationHours({
|
|
20
|
+
months,
|
|
21
|
+
timesheets: (Array.isArray(timesheetResources) ? timesheetResources : [])
|
|
22
|
+
.filter((resource) => resource.type === TIMESHEET_TYPE),
|
|
23
|
+
vacations,
|
|
24
|
+
employees,
|
|
25
|
+
contracts,
|
|
26
|
+
}), [months, timesheetResources, vacations, employees, contracts])
|
|
27
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import React from 'react'
|
|
2
|
+
import { DataLoader } from '@ossy/calendar'
|
|
3
|
+
import { UtilizationPanel } from './forecast-panels.jsx'
|
|
4
|
+
|
|
5
|
+
export const metadata = {
|
|
6
|
+
id: '@ossy/consultancy/view/utilization',
|
|
7
|
+
widget: {
|
|
8
|
+
title: 'consultancy.widgets.utilization.title',
|
|
9
|
+
description: 'consultancy.widgets.utilization.description',
|
|
10
|
+
ownsHeader: true,
|
|
11
|
+
},
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Slot widget — fiscal-year utilization for dashboards. */
|
|
15
|
+
export default function UtilizationWidget (props) {
|
|
16
|
+
return <DataLoader content={<UtilizationPanel {...props} />} />
|
|
17
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import React from 'react'
|
|
2
|
+
import { DataLoader } from '@ossy/calendar'
|
|
3
|
+
import { YearTotalsPanel } from './forecast-panels.jsx'
|
|
4
|
+
|
|
5
|
+
export const metadata = {
|
|
6
|
+
id: '@ossy/consultancy/view/year-totals',
|
|
7
|
+
widget: {
|
|
8
|
+
title: 'consultancy.widgets.yearTotals.title',
|
|
9
|
+
description: 'consultancy.widgets.yearTotals.description',
|
|
10
|
+
ownsHeader: true,
|
|
11
|
+
},
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Slot widget — fiscal-year totals for dashboards. */
|
|
15
|
+
export default function YearTotalsWidget (props) {
|
|
16
|
+
return <DataLoader content={<YearTotalsPanel {...props} />} />
|
|
17
|
+
}
|
|
@@ -1,184 +0,0 @@
|
|
|
1
|
-
/**
|
|
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.
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
export const MONEY_KEYS = ['projectedIncome', 'monthlyCostOfEmployees', 'revenue']
|
|
8
|
-
export const HOURS_KEY = 'hoursWorked'
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* 3-letter month label for chart axis (locale-aware short month, truncated).
|
|
12
|
-
*
|
|
13
|
-
* @param {{ year?: number|string, monthNumber?: number|string, month?: string }} month
|
|
14
|
-
* @param {string} [language='en']
|
|
15
|
-
* @returns {string}
|
|
16
|
-
*/
|
|
17
|
-
export function shortMonthLabel (month, language = 'en') {
|
|
18
|
-
const year = Number(month?.year)
|
|
19
|
-
const monthNumber = Number(month?.monthNumber)
|
|
20
|
-
if (Number.isFinite(year) && Number.isFinite(monthNumber) && monthNumber >= 1 && monthNumber <= 12) {
|
|
21
|
-
const locale = language === 'sv' ? 'sv-SE' : 'en'
|
|
22
|
-
const date = new Date(Date.UTC(year, monthNumber - 1, 1))
|
|
23
|
-
const short = new Intl.DateTimeFormat(locale, { month: 'short' }).format(date)
|
|
24
|
-
const letters = short.replace(/\./g, '').trim()
|
|
25
|
-
if (letters.length >= 3) {
|
|
26
|
-
return letters.slice(0, 3).replace(/^./, (c) => c.toUpperCase())
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
const fallback = String(month?.month || '').replace(/\./g, '').trim()
|
|
30
|
-
return fallback.slice(0, 3).replace(/^./, (c) => c.toUpperCase())
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* @param {Array<Record<string, unknown>>} months
|
|
35
|
-
* @param {string[]} keys
|
|
36
|
-
* @returns {{ min: number, max: number } | null}
|
|
37
|
-
*/
|
|
38
|
-
export function extentForKeys (months, keys) {
|
|
39
|
-
if (!months?.length || !keys?.length) return null
|
|
40
|
-
let min = Infinity
|
|
41
|
-
let max = -Infinity
|
|
42
|
-
for (const month of months) {
|
|
43
|
-
for (const key of keys) {
|
|
44
|
-
const value = Number(month[key]) || 0
|
|
45
|
-
if (value < min) min = value
|
|
46
|
-
if (value > max) max = value
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
if (!Number.isFinite(min) || !Number.isFinite(max)) return null
|
|
50
|
-
if (min === max) {
|
|
51
|
-
min -= 1
|
|
52
|
-
max += 1
|
|
53
|
-
}
|
|
54
|
-
return { min, max }
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/**
|
|
58
|
-
* @param {number} value
|
|
59
|
-
* @param {{ min: number, max: number }} extent
|
|
60
|
-
* @param {number} padY
|
|
61
|
-
* @param {number} innerH
|
|
62
|
-
*/
|
|
63
|
-
export function valueToY (value, extent, padY, innerH) {
|
|
64
|
-
const span = extent.max - extent.min
|
|
65
|
-
return padY + innerH - ((value - extent.min) / span) * innerH
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* Build SVG path strings for KPI series plus all-month X labels.
|
|
70
|
-
*
|
|
71
|
-
* ViewBox defaults use a wide aspect ratio (~3.5:1) so `preserveAspectRatio="meet"`
|
|
72
|
-
* can scale uniformly without squishing axis labels (see #1001).
|
|
73
|
-
*
|
|
74
|
-
* @param {object} options
|
|
75
|
-
* @param {Array<Record<string, unknown>>} options.months
|
|
76
|
-
* @param {Array<{ key: string, label: string, color: string, dashed?: boolean }>} options.series
|
|
77
|
-
* @param {string} [options.language='en']
|
|
78
|
-
* @param {number} [options.viewWidth=560]
|
|
79
|
-
* @param {number} [options.plotHeight=140]
|
|
80
|
-
* @param {number} [options.padX=16] Right inset.
|
|
81
|
-
* @param {number} [options.padLeft=12] Left inset. Tick labels sit outside the plot.
|
|
82
|
-
* @param {number} [options.padTop=12]
|
|
83
|
-
* @param {number} [options.padBottom=28]
|
|
84
|
-
* @returns {{ viewWidth: number, viewHeight: number, seriesPaths: Array<object>, monthLabels: Array<object>, yTicks: Array<object> } | null}
|
|
85
|
-
*/
|
|
86
|
-
export function buildKpiChartLayout ({
|
|
87
|
-
months,
|
|
88
|
-
series,
|
|
89
|
-
language = 'en',
|
|
90
|
-
viewWidth = 560,
|
|
91
|
-
plotHeight = 140,
|
|
92
|
-
padX = 16,
|
|
93
|
-
padLeft = 12,
|
|
94
|
-
padTop = 12,
|
|
95
|
-
padBottom = 28,
|
|
96
|
-
}) {
|
|
97
|
-
if (!months?.length || !series?.length) return null
|
|
98
|
-
|
|
99
|
-
const viewHeight = padTop + plotHeight + padBottom
|
|
100
|
-
const innerW = Math.max(0, viewWidth - padLeft - padX)
|
|
101
|
-
const innerH = plotHeight
|
|
102
|
-
const step = months.length === 1 ? 0 : innerW / (months.length - 1)
|
|
103
|
-
|
|
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
|
|
116
|
-
|
|
117
|
-
const seriesPaths = series.map((entry) => {
|
|
118
|
-
const extent = (entry.scale === 'hours' || entry.key === HOURS_KEY) ? hoursExtent : moneyExtent
|
|
119
|
-
if (!extent) return { ...entry, path: null }
|
|
120
|
-
|
|
121
|
-
const points = months.map((month, index) => {
|
|
122
|
-
const value = Number(month[entry.key]) || 0
|
|
123
|
-
const x = padLeft + index * step
|
|
124
|
-
const y = valueToY(value, extent, padTop, innerH)
|
|
125
|
-
return `${x},${y}`
|
|
126
|
-
})
|
|
127
|
-
return { ...entry, path: `M ${points.join(' L ')}` }
|
|
128
|
-
})
|
|
129
|
-
|
|
130
|
-
const monthLabels = months.map((month, index) => ({
|
|
131
|
-
index,
|
|
132
|
-
label: shortMonthLabel(month, language),
|
|
133
|
-
x: padLeft + index * step,
|
|
134
|
-
y: viewHeight - 6,
|
|
135
|
-
}))
|
|
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
|
-
|
|
149
|
-
return {
|
|
150
|
-
viewWidth,
|
|
151
|
-
viewHeight,
|
|
152
|
-
seriesPaths,
|
|
153
|
-
monthLabels,
|
|
154
|
-
yTicks,
|
|
155
|
-
step,
|
|
156
|
-
padX,
|
|
157
|
-
padLeft,
|
|
158
|
-
padTop,
|
|
159
|
-
padBottom,
|
|
160
|
-
plotHeight,
|
|
161
|
-
innerW,
|
|
162
|
-
innerH,
|
|
163
|
-
}
|
|
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
|
-
}
|
|
@@ -1,159 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
MONEY_KEYS,
|
|
3
|
-
HOURS_KEY,
|
|
4
|
-
extentForKeys,
|
|
5
|
-
valueToY,
|
|
6
|
-
buildKpiChartLayout,
|
|
7
|
-
shortMonthLabel,
|
|
8
|
-
} from './forecast-kpi-chart.js'
|
|
9
|
-
|
|
10
|
-
const sampleMonths = [
|
|
11
|
-
{ year: 2026, monthNumber: '01', month: 'January', projectedIncome: 100, monthlyCostOfEmployees: 50, revenue: 50, hoursWorked: 10 },
|
|
12
|
-
{ year: 2026, monthNumber: '02', month: 'February', projectedIncome: 200, monthlyCostOfEmployees: 50, revenue: 150, hoursWorked: 20 },
|
|
13
|
-
{ year: 2026, monthNumber: '03', month: 'March', projectedIncome: 150, monthlyCostOfEmployees: 50, revenue: 100, hoursWorked: 15 },
|
|
14
|
-
]
|
|
15
|
-
|
|
16
|
-
const series = [
|
|
17
|
-
{ key: 'projectedIncome', label: 'income', color: 'blue' },
|
|
18
|
-
{ key: 'monthlyCostOfEmployees', label: 'salary', color: 'orange' },
|
|
19
|
-
{ key: 'revenue', label: 'revenue', color: 'green' },
|
|
20
|
-
{ key: 'hoursWorked', label: 'hours', color: 'gray', dashed: true },
|
|
21
|
-
]
|
|
22
|
-
|
|
23
|
-
describe('shortMonthLabel', () => {
|
|
24
|
-
it('formats English months as three letters', () => {
|
|
25
|
-
expect(shortMonthLabel({ year: 2026, monthNumber: '01' }, 'en')).toBe('Jan')
|
|
26
|
-
expect(shortMonthLabel({ year: 2026, monthNumber: '09' }, 'en')).toBe('Sep')
|
|
27
|
-
expect(shortMonthLabel({ year: 2026, monthNumber: 12 }, 'en')).toBe('Dec')
|
|
28
|
-
})
|
|
29
|
-
|
|
30
|
-
it('formats Swedish months as three letters without trailing punctuation', () => {
|
|
31
|
-
expect(shortMonthLabel({ year: 2026, monthNumber: '01' }, 'sv')).toBe('Jan')
|
|
32
|
-
expect(shortMonthLabel({ year: 2026, monthNumber: '02' }, 'sv')).toBe('Feb')
|
|
33
|
-
})
|
|
34
|
-
|
|
35
|
-
it('falls back to the long month name when numbers are missing', () => {
|
|
36
|
-
expect(shortMonthLabel({ month: 'January' }, 'en')).toBe('Jan')
|
|
37
|
-
})
|
|
38
|
-
})
|
|
39
|
-
|
|
40
|
-
describe('extentForKeys', () => {
|
|
41
|
-
it('returns shared min/max across money keys', () => {
|
|
42
|
-
const extent = extentForKeys(sampleMonths, MONEY_KEYS)
|
|
43
|
-
expect(extent).toEqual({ min: 50, max: 200 })
|
|
44
|
-
})
|
|
45
|
-
|
|
46
|
-
it('expands a constant series so a flat line stays mid-range', () => {
|
|
47
|
-
const flat = [
|
|
48
|
-
{ monthlyCostOfEmployees: 50 },
|
|
49
|
-
{ monthlyCostOfEmployees: 50 },
|
|
50
|
-
]
|
|
51
|
-
const extent = extentForKeys(flat, ['monthlyCostOfEmployees'])
|
|
52
|
-
expect(extent.min).toBe(49)
|
|
53
|
-
expect(extent.max).toBe(51)
|
|
54
|
-
})
|
|
55
|
-
})
|
|
56
|
-
|
|
57
|
-
describe('buildKpiChartLayout', () => {
|
|
58
|
-
it('spans the full viewBox width for N months', () => {
|
|
59
|
-
const layout = buildKpiChartLayout({ months: sampleMonths, series, viewWidth: 100 })
|
|
60
|
-
expect(layout).not.toBeNull()
|
|
61
|
-
expect(layout.padLeft + (sampleMonths.length - 1) * layout.step).toBeCloseTo(100 - layout.padX)
|
|
62
|
-
expect(layout.viewWidth).toBe(100)
|
|
63
|
-
})
|
|
64
|
-
|
|
65
|
-
it('keeps salary flat and distinct from income under a shared money scale', () => {
|
|
66
|
-
const layout = buildKpiChartLayout({ months: sampleMonths, series })
|
|
67
|
-
const income = layout.seriesPaths.find((s) => s.key === 'projectedIncome')
|
|
68
|
-
const salary = layout.seriesPaths.find((s) => s.key === 'monthlyCostOfEmployees')
|
|
69
|
-
const revenue = layout.seriesPaths.find((s) => s.key === 'revenue')
|
|
70
|
-
const hours = layout.seriesPaths.find((s) => s.key === HOURS_KEY)
|
|
71
|
-
|
|
72
|
-
expect(income.path).not.toBe(salary.path)
|
|
73
|
-
expect(income.path).not.toBe(revenue.path)
|
|
74
|
-
expect(salary.path).not.toBe(revenue.path)
|
|
75
|
-
|
|
76
|
-
// Constant salary → identical Y across months
|
|
77
|
-
const salaryYs = salary.path.match(/[\d.]+,([\d.]+)/g).map((p) => p.split(',')[1])
|
|
78
|
-
expect(new Set(salaryYs).size).toBe(1)
|
|
79
|
-
|
|
80
|
-
// Hours secondary scale is not forced onto the money path
|
|
81
|
-
expect(hours.path).not.toBe(income.path)
|
|
82
|
-
expect(hours.dashed).toBe(true)
|
|
83
|
-
})
|
|
84
|
-
|
|
85
|
-
it('maps shared money extent extremes to plot top/bottom', () => {
|
|
86
|
-
const extent = extentForKeys(sampleMonths, MONEY_KEYS)
|
|
87
|
-
const padTop = 10
|
|
88
|
-
const plotHeight = 100
|
|
89
|
-
expect(valueToY(extent.max, extent, padTop, plotHeight)).toBeCloseTo(padTop)
|
|
90
|
-
expect(valueToY(extent.min, extent, padTop, plotHeight)).toBeCloseTo(padTop + plotHeight)
|
|
91
|
-
})
|
|
92
|
-
|
|
93
|
-
it('labels every month with a 3-letter abbreviation', () => {
|
|
94
|
-
const fiscalYear = Array.from({ length: 12 }, (_, i) => ({
|
|
95
|
-
year: 2026,
|
|
96
|
-
monthNumber: String(i + 1).padStart(2, '0'),
|
|
97
|
-
month: 'placeholder',
|
|
98
|
-
projectedIncome: 100 + i,
|
|
99
|
-
monthlyCostOfEmployees: 50,
|
|
100
|
-
revenue: 50 + i,
|
|
101
|
-
hoursWorked: 10,
|
|
102
|
-
}))
|
|
103
|
-
const layout = buildKpiChartLayout({ months: fiscalYear, series, language: 'en' })
|
|
104
|
-
expect(layout.monthLabels).toHaveLength(12)
|
|
105
|
-
expect(layout.monthLabels.map((entry) => entry.label)).toEqual([
|
|
106
|
-
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
|
|
107
|
-
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
|
|
108
|
-
])
|
|
109
|
-
expect(layout.monthLabels[0].x).toBe(layout.padLeft)
|
|
110
|
-
expect(layout.monthLabels[11].x).toBeCloseTo(layout.padLeft + 11 * layout.step)
|
|
111
|
-
})
|
|
112
|
-
|
|
113
|
-
it('defaults to a wide viewBox so meet-scaling keeps labels readable', () => {
|
|
114
|
-
const layout = buildKpiChartLayout({ months: sampleMonths, series })
|
|
115
|
-
expect(layout.viewWidth).toBe(560)
|
|
116
|
-
expect(layout.viewHeight / layout.viewWidth).toBeLessThan(0.5)
|
|
117
|
-
})
|
|
118
|
-
|
|
119
|
-
it('returns null for empty months', () => {
|
|
120
|
-
expect(buildKpiChartLayout({ months: [], series })).toBeNull()
|
|
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
|
-
})
|
|
159
|
-
})
|