@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.
Files changed (38) hide show
  1. package/package.json +3 -2
  2. package/src/AssignmentMarginCalculator.jsx +7 -32
  3. package/src/ConsultancyNav.jsx +17 -9
  4. package/src/Forecast.jsx +42 -343
  5. package/src/Overview.jsx +10 -31
  6. package/src/RequestStatsPanel.jsx +66 -0
  7. package/src/consultancy.page.jsx +3 -40
  8. package/src/current-month.component.jsx +43 -25
  9. package/src/en.translations.json +26 -2
  10. package/src/extract-request.action.js +5 -0
  11. package/src/extract-request.task.js +100 -0
  12. package/src/extract-request.task.spec.js +89 -0
  13. package/src/forecast-panels.jsx +125 -0
  14. package/src/forecast-widget-menu.jsx +89 -0
  15. package/src/get-request-stats.action.js +6 -0
  16. package/src/get-request-stats.task.js +26 -0
  17. package/src/index.js +1 -0
  18. package/src/intake-categories.js +39 -0
  19. package/src/kpi-trend.component.jsx +17 -0
  20. package/src/margin-panels.jsx +7 -32
  21. package/src/org.page.jsx +1 -2
  22. package/src/reports.page.jsx +103 -0
  23. package/src/request-buckets.js +76 -0
  24. package/src/request-buckets.spec.js +33 -0
  25. package/src/request-stats.aggregate.js +52 -0
  26. package/src/request-stats.aggregate.spec.js +34 -0
  27. package/src/request-stats.component.jsx +16 -0
  28. package/src/request.schema.js +29 -0
  29. package/src/requests.page.jsx +26 -0
  30. package/src/schema-ids.js +1 -0
  31. package/src/screen-inbound.task.js +84 -0
  32. package/src/screen-inbound.task.spec.js +97 -0
  33. package/src/sv.translations.json +26 -2
  34. package/src/use-chart-months.js +27 -0
  35. package/src/utilization.component.jsx +17 -0
  36. package/src/year-totals.component.jsx +17 -0
  37. package/src/forecast-kpi-chart.js +0 -184
  38. package/src/forecast-kpi-chart.spec.js +0 -159
@@ -0,0 +1,66 @@
1
+ import React, { useEffect, useState } from 'react'
2
+ import { LineChart, Panel } from '@ossy/design-system'
3
+ import { useSdk } from '@ossy/sdk-react'
4
+ import { ForecastWidgetMenu } from './forecast-widget-menu.jsx'
5
+
6
+ export const REQUEST_STATS_WIDGET_ID = '@ossy/consultancy/view/request-stats'
7
+ const GetRequestStats = { id: '@ossy/consultancy/actions/get-request-stats' }
8
+
9
+ const SERIES = [
10
+ {
11
+ key: 'count',
12
+ label: 'consultancy.requests.statsSeries',
13
+ color: 'var(--color-info, hsl(199, 89%, 43%))',
14
+ },
15
+ ]
16
+
17
+ /**
18
+ * Monthly incoming requests, dated by the email Date header.
19
+ */
20
+ export function RequestStatsChart () {
21
+ const sdk = useSdk()
22
+ const [months, setMonths] = useState([])
23
+
24
+ useEffect(() => {
25
+ let cancelled = false
26
+ sdk.invoke(GetRequestStats, {})
27
+ .then((json) => {
28
+ if (cancelled) return
29
+ setMonths(Array.isArray(json?.months) ? json.months : [])
30
+ })
31
+ .catch(() => {
32
+ if (!cancelled) setMonths([])
33
+ })
34
+ return () => {
35
+ cancelled = true
36
+ }
37
+ }, [sdk])
38
+
39
+ return (
40
+ <LineChart
41
+ months={months}
42
+ series={SERIES}
43
+ unit="consultancy.requests.statsUnit"
44
+ empty="consultancy.requests.statsEmpty"
45
+ />
46
+ )
47
+ }
48
+
49
+ export function RequestStatsPanel ({ dashboardId, pinnedWidgetId }) {
50
+ return (
51
+ <Panel
52
+ title="consultancy.requests.statsTitle"
53
+ style={{ height: 'auto', flex: '0 0 auto' }}
54
+ data-request-stats
55
+ actions={(
56
+ <ForecastWidgetMenu
57
+ componentId={REQUEST_STATS_WIDGET_ID}
58
+ dashboardId={dashboardId}
59
+ pinnedWidgetId={pinnedWidgetId}
60
+ />
61
+ )}
62
+ >
63
+ <RequestStatsChart />
64
+ </Panel>
65
+ )
66
+ }
@@ -1,7 +1,5 @@
1
- import React, { useState } from 'react'
2
- import { Button, Text, View, Page, Tags } from '@ossy/design-system'
3
- import { useSdk } from '@ossy/sdk-react'
4
- import { PinWidget } from '@ossy/dashboard'
1
+ import React from 'react'
2
+ import { View, Page, Tags } from '@ossy/design-system'
5
3
  import { Forecast } from './Forecast.jsx'
6
4
  import { DataLoader } from '@ossy/calendar'
7
5
  import { Definition } from './Definition.js'
@@ -16,56 +14,21 @@ export const metadata = {
16
14
  },
17
15
  }
18
16
 
19
- const FORECAST_WIDGET_ID = '@ossy/consultancy/view/current-month'
20
-
21
17
  export const ConsultancyPage = () => {
22
- const sdk = useSdk()
23
- const [pinState, setPinState] = useState('idle')
24
-
25
18
  const statusTags = (Definition.status ?? [])
26
19
  .map((s) => ({ beta: 'Beta', 'coming-soon': 'Coming Soon' }[s]))
27
20
  .filter(Boolean)
28
21
 
29
- const pinToDashboard = async () => {
30
- if (pinState === 'pending') return
31
- setPinState('pending')
32
- try {
33
- await sdk.invoke(PinWidget, { componentId: FORECAST_WIDGET_ID })
34
- setPinState('done')
35
- } catch {
36
- setPinState('error')
37
- }
38
- }
39
-
40
22
  return (
41
23
  <Page
42
24
  data-forecasts-status="on"
43
25
  title="consultancy.home.title"
44
26
  near={statusTags.length > 0 ? <Tags tags={statusTags} size="s" /> : undefined}
45
27
  description="consultancy.home.description"
46
- far={(
47
- <View layout="row" gap="s" style={{ flexWrap: 'wrap' }}>
48
- <Button
49
- {...PinWidget}
50
- variant="primary"
51
- disabled={pinState === 'pending' || pinState === 'done'}
52
- label={
53
- pinState === 'done'
54
- ? 'consultancy.forecasts.pin.done'
55
- : pinState === 'error'
56
- ? 'consultancy.forecasts.pin.error'
57
- : 'consultancy.forecasts.pin.forecast'
58
- }
59
- onClick={pinToDashboard}
60
- data-forecasts-pin
61
- />
62
- <CreateConsultancyButton />
63
- </View>
64
- )}
28
+ far={<CreateConsultancyButton />}
65
29
  >
66
30
  <View gap="m">
67
31
  <ConsultancyNav active="consultancy/home" />
68
- <Text variant="heading-secondary" as="h2" text="design-system.overview" />
69
32
  <DataLoader content={<Forecast />} />
70
33
  </View>
71
34
  </Page>
@@ -1,6 +1,11 @@
1
1
  import React from 'react'
2
- import { View, Text, useLocale } from '@ossy/design-system'
2
+ import { Panel, Text, View, useLocale } from '@ossy/design-system'
3
3
  import { DataLoader, useForecast } from '@ossy/calendar'
4
+ import { ForecastWidgetMenu } from './forecast-widget-menu.jsx'
5
+
6
+ export const CURRENT_MONTH_WIDGET_ID = '@ossy/consultancy/view/current-month'
7
+
8
+ const panelStyle = { height: '100%', flex: '1 1 auto', minWidth: 0 }
4
9
 
5
10
  function MetricRow ({ label, value }) {
6
11
  return (
@@ -12,11 +17,11 @@ function MetricRow ({ label, value }) {
12
17
  }
13
18
 
14
19
  /**
15
- * Compact current-month forecast metrics (standalone dashboard panel).
20
+ * Compact current-month forecast metrics, using the shared Panel header.
16
21
  */
17
- export function CurrentMonthForecastPanel () {
22
+ export function CurrentMonthForecastPanel ({ dashboardId, pinnedWidgetId }) {
18
23
  const months = useForecast()
19
- const { language } = useLocale()
24
+ const { language, t } = useLocale()
20
25
  const money = (value) => new Intl.NumberFormat(language === 'sv' ? 'sv-SE' : 'en-SE', {
21
26
  style: 'currency',
22
27
  currency: 'SEK',
@@ -29,38 +34,51 @@ export function CurrentMonthForecastPanel () {
29
34
  const current = (Array.isArray(months) ? months : []).find((m) => m.isCurrentMonth)
30
35
  ?? (Array.isArray(months) ? months[0] : null)
31
36
 
32
- if (!current) {
33
- return (
34
- <Text
35
- color="secondary"
36
- text="consultancy.forecasts.widget.empty"
37
- data-forecasts-widget="current-month"
38
- />
39
- )
40
- }
37
+ const actions = (
38
+ <ForecastWidgetMenu
39
+ componentId={CURRENT_MONTH_WIDGET_ID}
40
+ dashboardId={dashboardId}
41
+ pinnedWidgetId={pinnedWidgetId}
42
+ />
43
+ )
41
44
 
42
45
  return (
43
- <View gap="s" data-forecasts-widget="current-month">
44
- <Text variant="heading-tertiary" as="h3">
45
- {current.year} {current.month}
46
- </Text>
47
- <MetricRow label="consultancy.forecasts.income" value={money(current.projectedIncome)} />
48
- <MetricRow label="consultancy.forecasts.salaryCost" value={money(current.monthlyCostOfEmployees)} />
49
- <MetricRow label="consultancy.forecasts.revenue" value={money(current.revenue)} />
50
- <MetricRow label="consultancy.forecasts.hoursWorked" value={hours(current.hoursWorked)} />
51
- </View>
46
+ <Panel
47
+ title={current ? (
48
+ <Text variant="small" as="h2" style={{ fontWeight: 'bold' }}>
49
+ {t('consultancy.forecasts.monthForecast', { month: current.month })}
50
+ </Text>
51
+ ) : 'consultancy.widgets.forecastCurrentMonth.title'}
52
+ style={panelStyle}
53
+ actions={actions}
54
+ data-forecasts-widget="current-month"
55
+ >
56
+ {!current ? (
57
+ <View inset="m">
58
+ <Text color="secondary" text="consultancy.forecasts.widget.empty" />
59
+ </View>
60
+ ) : (
61
+ <View gap="s" inset="m">
62
+ <MetricRow label="consultancy.forecasts.income" value={money(current.projectedIncome)} />
63
+ <MetricRow label="consultancy.forecasts.salaryCost" value={money(current.monthlyCostOfEmployees)} />
64
+ <MetricRow label="consultancy.forecasts.revenue" value={money(current.revenue)} />
65
+ <MetricRow label="consultancy.forecasts.hoursWorked" value={hours(current.hoursWorked)} />
66
+ </View>
67
+ )}
68
+ </Panel>
52
69
  )
53
70
  }
54
71
 
55
72
  export const metadata = {
56
- id: '@ossy/consultancy/view/current-month',
73
+ id: CURRENT_MONTH_WIDGET_ID,
57
74
  widget: {
58
75
  title: 'consultancy.widgets.forecastCurrentMonth.title',
59
76
  description: 'consultancy.widgets.forecastCurrentMonth.description',
77
+ ownsHeader: true,
60
78
  },
61
79
  }
62
80
 
63
81
  /** Slot widget — current-month forecast panel for dashboards. */
64
- export default function CurrentMonthForecastWidget () {
65
- return <DataLoader content={<CurrentMonthForecastPanel />} />
82
+ export default function CurrentMonthForecastWidget (props) {
83
+ return <DataLoader content={<CurrentMonthForecastPanel {...props} />} />
66
84
  }
@@ -6,7 +6,9 @@
6
6
  "consultancy/vacations.documentTitle": "Vacations",
7
7
  "consultancy/contracts.documentTitle": "Contracts",
8
8
  "consultancy/opportunities.documentTitle": "Opportunities",
9
+ "consultancy/requests.documentTitle": "Requests",
9
10
  "consultancy/proposals.documentTitle": "Proposals",
11
+ "consultancy/reports.documentTitle": "Reports",
10
12
  "consultancy.home.title": "Overview",
11
13
  "consultancy.home.description": "Fiscal-year KPIs, year totals, and monthly capacity from contracts, employees, and vacations",
12
14
  "consultancy.org.title": "Org Details",
@@ -17,8 +19,10 @@
17
19
  "consultancy.nav.employees": "Employees",
18
20
  "consultancy.nav.vacations": "Vacations",
19
21
  "consultancy.nav.contracts": "Contracts",
22
+ "consultancy.nav.requests": "Requests",
20
23
  "consultancy.nav.opportunities": "Opportunities",
21
24
  "consultancy.nav.proposals": "Proposals",
25
+ "consultancy.nav.reports": "Reports",
22
26
  "consultancy.nav.margins": "Margins",
23
27
  "consultancy.forecasts.title": "Overview",
24
28
  "consultancy.forecasts.description": "Fiscal-year KPIs, year totals, and monthly capacity from contracts, employees, and vacations",
@@ -68,6 +72,16 @@
68
72
  "consultancy.contracts.title": "Contracts",
69
73
  "consultancy.contracts.description": "Client assignments and rates",
70
74
  "consultancy.contracts.empty": "No contracts yet.",
75
+ "consultancy.requests.title": "Requests",
76
+ "consultancy.requests.description": "Assignments parsed from inbound email",
77
+ "consultancy.requests.empty": "No requests yet.",
78
+ "consultancy.requests.statsTitle": "Incoming requests",
79
+ "consultancy.requests.statsSeries": "Requests",
80
+ "consultancy.requests.statsUnit": "requests",
81
+ "consultancy.requests.statsEmpty": "No requests dated yet.",
82
+ "consultancy.reports.title": "Reports",
83
+ "consultancy.reports.description": "Charts of incoming work",
84
+ "consultancy.reports.empty": "No reports yet.",
71
85
  "consultancy.opportunities.title": "Opportunities",
72
86
  "consultancy.opportunities.description": "Pipeline of possible assignments",
73
87
  "consultancy.opportunities.empty": "No opportunities yet.",
@@ -187,7 +201,8 @@
187
201
  "@ossy/consultancy/schema/proposal.body.description": "Full proposal text.",
188
202
  "consultancy.nav.orgDetails": "Org Details",
189
203
  "consultancy.forecasts.yearChart": "KPI trend",
190
- "consultancy.forecasts.yearSummary": "Fiscal year totals",
204
+ "consultancy.forecasts.monthForecast": "{month} forecast",
205
+ "consultancy.forecasts.yearSummary": "Fiscal year forecast",
191
206
  "consultancy.forecasts.yearChartEmpty": "No forecast months to chart yet.",
192
207
  "consultancy.margins.pin.done": "Pinned to dashboard",
193
208
  "consultancy.margins.pin.error": "Pin failed — try again",
@@ -202,5 +217,14 @@
202
217
  "consultancy.widgets.adminLeakage.title": "Admin leakage",
203
218
  "consultancy.widgets.adminLeakage.description": "Annual hours and revenue lost to recurring admin work.",
204
219
  "consultancy.widgets.forecastCurrentMonth.title": "This month forecast",
205
- "consultancy.widgets.forecastCurrentMonth.description": "Projected income, salary cost, revenue, and hours for the current month."
220
+ "consultancy.widgets.forecastCurrentMonth.description": "Projected income, salary cost, revenue, and hours for the current month.",
221
+ "consultancy.widgets.kpiTrend.title": "KPI trend",
222
+ "consultancy.widgets.kpiTrend.description": "Forecast and actual income, salary cost, and revenue for the fiscal year.",
223
+ "consultancy.widgets.yearTotals.title": "Fiscal year forecast",
224
+ "consultancy.widgets.yearTotals.description": "Income, salary cost, revenue, and hours for the fiscal year.",
225
+ "consultancy.widgets.utilization.title": "Utilization",
226
+ "consultancy.widgets.utilization.description": "Forecast and actual hours across the fiscal year.",
227
+ "consultancy.widgets.requestStats.title": "Incoming requests",
228
+ "consultancy.widgets.requestStats.description": "Requests per month, dated by the email's own arrival time.",
229
+ "consultancy.widgets.menu": "More"
206
230
  }
@@ -0,0 +1,5 @@
1
+ export const metadata = {
2
+ id: '@ossy/consultancy/actions/extract-request',
3
+ access: 'workspace',
4
+ label: 'automation.task.extract-request.title',
5
+ }
@@ -0,0 +1,100 @@
1
+ import { ConsultancySchema } from './schema-ids.js'
2
+ import { location } from './locations.js'
3
+
4
+ const GetResource = { id: '@ossy/resources/actions/get' }
5
+ const CreateResource = { id: '@ossy/resources/actions/create' }
6
+ const ExtractStructuredData = { id: '@ossy/media-tasks/actions/extract-structured-data' }
7
+ const INBOUND_MESSAGE = '@ossy/email/schema/inbound-message'
8
+
9
+ export const metadata = {
10
+ id: '@ossy/consultancy/tasks/extract-request',
11
+ triggers: [
12
+ {
13
+ kind: 'on_action',
14
+ action: '@ossy/consultancy/actions/extract-request',
15
+ },
16
+ ],
17
+ outputs: [
18
+ {
19
+ name: 'request',
20
+ kind: 'location',
21
+ schemaId: ConsultancySchema.request,
22
+ prefix: location,
23
+ },
24
+ ],
25
+ }
26
+
27
+ function fail (message, status) {
28
+ throw Object.assign(new Error(message), { status })
29
+ }
30
+
31
+ function workspaceIdFrom ({ event, payload, req }) {
32
+ return event?.payload?.belongsTo
33
+ ?? event?.belongsTo
34
+ ?? payload?.workspaceId
35
+ ?? req?.workspaceId
36
+ ?? null
37
+ }
38
+
39
+ /**
40
+ * Text the extractor should read. The subject often is the assignment title.
41
+ *
42
+ * @param {object | null | undefined} resource
43
+ */
44
+ export function requestSourceText (resource) {
45
+ const content = resource?.content && typeof resource.content === 'object' ? resource.content : {}
46
+ const lines = []
47
+ if (content.subject) lines.push(`Subject: ${content.subject}`)
48
+ if (content.from) lines.push(`From: ${content.from}`)
49
+ const body = typeof content.text === 'string' ? content.text.trim() : ''
50
+ if (body) lines.push('', body)
51
+ return lines.join('\n').trim()
52
+ }
53
+
54
+ /**
55
+ * Inbound assignment → extract-structured-data → a consultancy request resource.
56
+ * Screening decides whether this runs. It does not listen to every inbound message.
57
+ */
58
+ export async function run ({ event, payload, req, sdk }) {
59
+ if (!sdk?.invoke) fail('sdk is required', 500)
60
+
61
+ const resourceId = event?.resourceId || payload?.resourceId
62
+ if (!resourceId) fail('resourceId is required', 400)
63
+
64
+ const workspaceId = workspaceIdFrom({ event, payload, req })
65
+ if (!workspaceId) fail('workspaceId is required', 400)
66
+
67
+ const resource = await sdk.invoke(GetResource, { resourceId })
68
+ if (resource?.type !== INBOUND_MESSAGE) fail('inbound message is required', 400)
69
+
70
+ const text = requestSourceText(resource)
71
+ if (!text) fail('text is required', 400)
72
+
73
+ const extracted = await sdk.invoke(ExtractStructuredData, {
74
+ schemaId: ConsultancySchema.request,
75
+ text,
76
+ workspaceId,
77
+ })
78
+ const data = extracted?.data
79
+ if (!data || typeof data !== 'object') fail('extraction is required', 422)
80
+
81
+ const messageId = typeof resource.content?.messageId === 'string' ? resource.content.messageId : ''
82
+ const receivedAt = typeof resource.content?.receivedAt === 'string' ? resource.content.receivedAt.trim() : ''
83
+ const content = {
84
+ ...data,
85
+ ...(messageId ? { messageId } : {}),
86
+ ...(receivedAt ? { receivedAt } : {}),
87
+ }
88
+ const title = typeof content.title === 'string' ? content.title.trim() : ''
89
+ if (!title) fail('title is required', 422)
90
+
91
+ const created = await sdk.invoke(CreateResource, {
92
+ workspaceId,
93
+ type: ConsultancySchema.request,
94
+ location,
95
+ name: title,
96
+ content,
97
+ })
98
+
99
+ return { id: created?.id ?? null, workspaceId, content }
100
+ }
@@ -0,0 +1,89 @@
1
+ import { Schema, validateContent } from '@ossy/schema'
2
+ import { ConsultancySchema } from './schema-ids.js'
3
+ import requestSchema from './request.schema.js'
4
+ import { metadata, requestSourceText, run } from './extract-request.task.js'
5
+
6
+ const GetResource = { id: '@ossy/resources/actions/get' }
7
+ const CreateResource = { id: '@ossy/resources/actions/create' }
8
+ const ExtractStructuredData = { id: '@ossy/media-tasks/actions/extract-structured-data' }
9
+
10
+ const inbound = {
11
+ id: 'msg-1',
12
+ type: '@ossy/email/schema/inbound-message',
13
+ content: {
14
+ from: 'Anna Berg <anna@client.se>',
15
+ to: 'requests+ws-1@inbound.ossy.se',
16
+ subject: 'Senior React, 6 manader',
17
+ text: 'Vi soker en senior React-utvecklare i Stockholm. Uppdraget ar 6 manader med start i januari. Anna Berg, anna@client.se.',
18
+ messageId: 'assignment-1@client.se',
19
+ receivedAt: '2023-04-15T10:00:00.000Z',
20
+ },
21
+ }
22
+
23
+ const extracted = {
24
+ title: 'Senior React, 6 manader',
25
+ summary: 'Senior React developer in Stockholm for 6 months, starting in January.',
26
+ role: 'Senior React developer',
27
+ skills: 'React',
28
+ location: 'Stockholm',
29
+ duration: '6 months',
30
+ start: 'January',
31
+ contactName: 'Anna Berg',
32
+ contactEmail: 'anna@client.se',
33
+ }
34
+
35
+ describe('extract-request task', () => {
36
+ it('runs only when the extract-request action is invoked', () => {
37
+ expect(metadata.triggers).toEqual([
38
+ {
39
+ kind: 'on_action',
40
+ action: '@ossy/consultancy/actions/extract-request',
41
+ },
42
+ ])
43
+ expect(metadata.outputs[0].schemaId).toBe(ConsultancySchema.request)
44
+ })
45
+
46
+ it('turns a forwarded assignment email into a request record', async () => {
47
+ const calls = []
48
+ const sdk = {
49
+ async invoke (action, payload) {
50
+ calls.push({ id: action.id, payload })
51
+ if (action.id === GetResource.id) return inbound
52
+ if (action.id === ExtractStructuredData.id) return { data: extracted }
53
+ if (action.id === CreateResource.id) return { id: 'request-1' }
54
+ throw new Error(`unexpected ${action.id}`)
55
+ },
56
+ }
57
+
58
+ const result = await run({
59
+ event: { resourceId: inbound.id, payload: { belongsTo: 'ws-1' } },
60
+ sdk,
61
+ })
62
+
63
+ const extractCall = calls.find((call) => call.id === ExtractStructuredData.id)
64
+ expect(extractCall.payload.schemaId).toBe(ConsultancySchema.request)
65
+ expect(extractCall.payload.text).toBe(requestSourceText(inbound))
66
+ expect(extractCall.payload.text).toContain('Senior React, 6 manader')
67
+ expect(extractCall.payload.text).toContain('Stockholm')
68
+
69
+ const created = calls.find((call) => call.id === CreateResource.id).payload
70
+ expect(created).toMatchObject({
71
+ workspaceId: 'ws-1',
72
+ type: ConsultancySchema.request,
73
+ name: 'Senior React, 6 manader',
74
+ })
75
+ expect(created.content).toMatchObject({
76
+ ...extracted,
77
+ messageId: 'assignment-1@client.se',
78
+ receivedAt: '2023-04-15T10:00:00.000Z',
79
+ })
80
+
81
+ const engine = Schema.of({ schemas: [requestSchema] })
82
+ expect(validateContent(engine, requestSchema, created.content).ok).toBe(true)
83
+ expect(result).toEqual({
84
+ id: 'request-1',
85
+ workspaceId: 'ws-1',
86
+ content: created.content,
87
+ })
88
+ })
89
+ })
@@ -0,0 +1,125 @@
1
+ import React, { useMemo } from 'react'
2
+ import { LineChart, Panel, Text, View, useLocale } from '@ossy/design-system'
3
+ import { sumFiscalYearTotals } from '@ossy/calendar'
4
+ import { ForecastWidgetMenu } from './forecast-widget-menu.jsx'
5
+ import { useChartMonths } from './use-chart-months.js'
6
+
7
+ export const KPI_TREND_WIDGET_ID = '@ossy/consultancy/view/kpi-trend'
8
+ export const YEAR_TOTALS_WIDGET_ID = '@ossy/consultancy/view/year-totals'
9
+ export const UTILIZATION_WIDGET_ID = '@ossy/consultancy/view/utilization'
10
+
11
+ const KPI_SERIES = [
12
+ { key: 'projectedIncome', label: 'consultancy.forecasts.forecastIncome', color: 'var(--color-info, hsl(199, 89%, 43%))', dashed: true },
13
+ { key: 'actualIncome', label: 'consultancy.forecasts.actualIncome', color: 'var(--color-info, hsl(199, 89%, 43%))' },
14
+ { key: 'monthlyCostOfEmployees', label: 'consultancy.forecasts.salaryCost', color: 'var(--color-warning, hsl(38, 92%, 50%))', dashed: true },
15
+ { key: 'revenue', label: 'consultancy.forecasts.forecastRevenue', color: 'var(--color-accent, hsl(167, 89%, 43%))', dashed: true },
16
+ { key: 'actualRevenue', label: 'consultancy.forecasts.actualRevenue', color: 'var(--color-accent, hsl(167, 89%, 43%))' },
17
+ ]
18
+
19
+ const UTILIZATION_SERIES = [
20
+ { key: 'forecastHours', label: 'consultancy.forecasts.forecastHours', color: 'var(--color-info, hsl(199, 89%, 43%))', scale: 'hours', dashed: true },
21
+ { key: 'actualHours', label: 'consultancy.forecasts.actualHours', color: 'var(--color-accent, hsl(167, 89%, 43%))', scale: 'hours' },
22
+ ]
23
+
24
+ const panelStyle = { height: '100%', flex: '1 1 auto', minWidth: 0 }
25
+
26
+ function useMoneyAndHours () {
27
+ const { language } = useLocale()
28
+ const money = (value) => new Intl.NumberFormat(language === 'sv' ? 'sv-SE' : 'en-SE', {
29
+ style: 'currency',
30
+ currency: 'SEK',
31
+ }).format(value)
32
+ const hours = (value) => new Intl.NumberFormat(language === 'sv' ? 'sv-SE' : 'en-GB', {
33
+ style: 'unit',
34
+ unit: 'hour',
35
+ }).format(value)
36
+ return { money, hours }
37
+ }
38
+
39
+ export function KpiTrendPanel ({ dashboardId, pinnedWidgetId }) {
40
+ const months = useChartMonths()
41
+ return (
42
+ <Panel
43
+ title="consultancy.forecasts.yearChart"
44
+ style={panelStyle}
45
+ actions={(
46
+ <ForecastWidgetMenu
47
+ componentId={KPI_TREND_WIDGET_ID}
48
+ dashboardId={dashboardId}
49
+ pinnedWidgetId={pinnedWidgetId}
50
+ />
51
+ )}
52
+ >
53
+ <LineChart
54
+ months={months}
55
+ series={KPI_SERIES}
56
+ unit="consultancy.forecasts.unitMoney"
57
+ empty="consultancy.forecasts.yearChartEmpty"
58
+ />
59
+ </Panel>
60
+ )
61
+ }
62
+
63
+ export function YearTotalsPanel ({ dashboardId, pinnedWidgetId }) {
64
+ const months = useChartMonths()
65
+ const { money, hours } = useMoneyAndHours()
66
+ const totals = useMemo(() => sumFiscalYearTotals(months), [months])
67
+
68
+ return (
69
+ <Panel
70
+ title="consultancy.forecasts.yearSummary"
71
+ style={panelStyle}
72
+ data-consultancy-year-summary
73
+ actions={(
74
+ <ForecastWidgetMenu
75
+ componentId={YEAR_TOTALS_WIDGET_ID}
76
+ dashboardId={dashboardId}
77
+ pinnedWidgetId={pinnedWidgetId}
78
+ />
79
+ )}
80
+ >
81
+ <View gap="s" inset="m">
82
+ <View layout="row" gap="s" style={{ justifyContent: 'space-between' }}>
83
+ <Text variant="m" style={{ marginBottom: 0 }} text="consultancy.forecasts.income" />
84
+ <Text variant="m" style={{ marginBottom: 0 }}>{money(totals.projectedIncome)}</Text>
85
+ </View>
86
+ <View layout="row" gap="s" style={{ justifyContent: 'space-between' }}>
87
+ <Text variant="m" style={{ marginBottom: 0 }} text="consultancy.forecasts.salaryCost" />
88
+ <Text variant="m" style={{ marginBottom: 0 }}>{money(totals.monthlyCostOfEmployees)}</Text>
89
+ </View>
90
+ <View layout="row" gap="s" style={{ justifyContent: 'space-between' }}>
91
+ <Text variant="m" style={{ marginBottom: 0 }} text="consultancy.forecasts.revenue" />
92
+ <Text variant="m" style={{ marginBottom: 0 }}>{money(totals.revenue)}</Text>
93
+ </View>
94
+ <View layout="row" gap="s" style={{ justifyContent: 'space-between' }}>
95
+ <Text variant="m" style={{ marginBottom: 0 }} text="consultancy.forecasts.hoursWorked" />
96
+ <Text variant="m" style={{ marginBottom: 0 }}>{hours(totals.hoursWorked)}</Text>
97
+ </View>
98
+ </View>
99
+ </Panel>
100
+ )
101
+ }
102
+
103
+ export function UtilizationPanel ({ dashboardId, pinnedWidgetId }) {
104
+ const months = useChartMonths()
105
+ return (
106
+ <Panel
107
+ title="consultancy.forecasts.utilization"
108
+ style={panelStyle}
109
+ actions={(
110
+ <ForecastWidgetMenu
111
+ componentId={UTILIZATION_WIDGET_ID}
112
+ dashboardId={dashboardId}
113
+ pinnedWidgetId={pinnedWidgetId}
114
+ />
115
+ )}
116
+ >
117
+ <LineChart
118
+ months={months}
119
+ series={UTILIZATION_SERIES}
120
+ unit="consultancy.forecasts.unitHours"
121
+ empty="consultancy.forecasts.yearChartEmpty"
122
+ />
123
+ </Panel>
124
+ )
125
+ }