@ossy/consultancy 3.21.0 → 3.23.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 (43) hide show
  1. package/package.json +4 -2
  2. package/src/AssignmentMarginCalculator.jsx +7 -32
  3. package/src/ConsultancyNav.jsx +17 -9
  4. package/src/Forecast.jsx +33 -384
  5. package/src/MonthDayGrid.jsx +68 -0
  6. package/src/Overview.jsx +10 -31
  7. package/src/RequestStatsPanel.jsx +66 -0
  8. package/src/consultancy.page.jsx +3 -40
  9. package/src/current-month.component.jsx +47 -25
  10. package/src/en.translations.json +52 -2
  11. package/src/extract-request.action.js +5 -0
  12. package/src/extract-request.task.js +117 -0
  13. package/src/extract-request.task.spec.js +131 -0
  14. package/src/forecast-panels.jsx +125 -0
  15. package/src/forecast-widget-menu.jsx +89 -0
  16. package/src/get-request-stats.action.js +6 -0
  17. package/src/get-request-stats.task.js +26 -0
  18. package/src/index.js +1 -0
  19. package/src/intake-categories.js +39 -0
  20. package/src/kpi-trend.component.jsx +17 -0
  21. package/src/margin-panels.jsx +7 -32
  22. package/src/org.page.jsx +1 -2
  23. package/src/reports.page.jsx +103 -0
  24. package/src/request-buckets.js +76 -0
  25. package/src/request-buckets.spec.js +33 -0
  26. package/src/request-stats.aggregate.js +52 -0
  27. package/src/request-stats.aggregate.spec.js +34 -0
  28. package/src/request-stats.component.jsx +16 -0
  29. package/src/request.schema.js +29 -0
  30. package/src/requests.page.jsx +26 -0
  31. package/src/resume-inbound-screening.task.js +77 -0
  32. package/src/resume-inbound-screening.task.spec.js +68 -0
  33. package/src/schema-ids.js +1 -0
  34. package/src/screen-inbound.task.js +133 -0
  35. package/src/screen-inbound.task.spec.js +154 -0
  36. package/src/sv.translations.json +52 -2
  37. package/src/use-chart-months.js +27 -0
  38. package/src/utilization-hours.js +21 -3
  39. package/src/utilization-hours.spec.js +23 -0
  40. package/src/utilization.component.jsx +17 -0
  41. package/src/year-totals.component.jsx +17 -0
  42. package/src/forecast-kpi-chart.js +0 -184
  43. package/src/forecast-kpi-chart.spec.js +0 -159
@@ -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
+ }
@@ -0,0 +1,89 @@
1
+ import React, { useEffect, useState } from 'react'
2
+ import { Button, ContextMenu, Dropdown, useLocale } from '@ossy/design-system'
3
+ import { useSdk } from '@ossy/sdk-react'
4
+ import { ListDashboards, PinWidget, UpdateDashboard } from '@ossy/dashboard'
5
+
6
+ function findPlacement (boards, componentId) {
7
+ for (const board of boards) {
8
+ const match = (board.widgets ?? []).find((widget) => widget.componentId === componentId)
9
+ if (match) return { dashboardId: board.id, widgetId: match.id }
10
+ }
11
+ return null
12
+ }
13
+
14
+ /**
15
+ * More menu on a forecast panel. Pins the widget onto the default dashboard,
16
+ * or unpins the instance already on a dashboard.
17
+ *
18
+ * When the panel is rendered inside a dashboard, pass that board and widget id
19
+ * so unpin targets the instance on screen.
20
+ */
21
+ export function ForecastWidgetMenu ({ componentId, dashboardId, pinnedWidgetId }) {
22
+ const sdk = useSdk()
23
+ const { t } = useLocale()
24
+ const [boards, setBoards] = useState(null)
25
+ const [busy, setBusy] = useState(false)
26
+
27
+ useEffect(() => {
28
+ let cancelled = false
29
+ sdk.invoke(ListDashboards, { ensureDefault: false })
30
+ .then((data) => {
31
+ if (!cancelled) setBoards(Array.isArray(data?.items) ? data.items : [])
32
+ })
33
+ .catch(() => {
34
+ if (!cancelled) setBoards([])
35
+ })
36
+ return () => { cancelled = true }
37
+ }, [sdk])
38
+
39
+ const placement = (dashboardId && pinnedWidgetId)
40
+ ? { dashboardId, widgetId: pinnedWidgetId }
41
+ : findPlacement(boards ?? [], componentId)
42
+ const pinned = Boolean(placement)
43
+
44
+ const toggle = async () => {
45
+ if (busy || boards == null) return
46
+ const board = (boards ?? []).find((item) => item.id === placement?.dashboardId)
47
+ if (pinned && !board) return
48
+ setBusy(true)
49
+ try {
50
+ if (pinned) {
51
+ const widgets = (board.widgets ?? []).filter((widget) => widget.id !== placement.widgetId)
52
+ await sdk.invoke(UpdateDashboard, { dashboardId: placement.dashboardId, widgets })
53
+ } else {
54
+ await sdk.invoke(PinWidget, { componentId })
55
+ }
56
+ const data = await sdk.invoke(ListDashboards, { ensureDefault: false })
57
+ setBoards(Array.isArray(data?.items) ? data.items : [])
58
+ } catch {
59
+ // Leave the menu on the previous pin state so the user can retry.
60
+ } finally {
61
+ setBusy(false)
62
+ }
63
+ }
64
+
65
+ return (
66
+ <Dropdown
67
+ trigger={(
68
+ <Button
69
+ variant="command"
70
+ prefix="more-vertical-alt"
71
+ aria-label={t('consultancy.widgets.menu')}
72
+ title={t('consultancy.widgets.menu')}
73
+ data-forecast-widget-menu={componentId}
74
+ />
75
+ )}
76
+ >
77
+ <ContextMenu>
78
+ <ContextMenu.Item
79
+ prefix={pinned ? 'close' : 'pin'}
80
+ disabled={busy || boards == null || (pinned && !(boards ?? []).some((item) => item.id === placement.dashboardId))}
81
+ onClick={toggle}
82
+ data-forecast-widget-pin={pinned ? 'unpin' : 'pin'}
83
+ >
84
+ {pinned ? t('dashboard.unpin') : t('dashboard.actions.pinWidget')}
85
+ </ContextMenu.Item>
86
+ </ContextMenu>
87
+ </Dropdown>
88
+ )
89
+ }
@@ -0,0 +1,6 @@
1
+ export const metadata = {
2
+ id: '@ossy/consultancy/actions/get-request-stats',
3
+ access: 'workspace',
4
+ audit: false,
5
+ label: 'consultancy.requests.statsTitle',
6
+ }
@@ -0,0 +1,26 @@
1
+ import { getProjection } from '@ossy/event-store'
2
+ import { monthPoints } from './request-buckets.js'
3
+ import { RequestStatsProjection } from './request-stats.aggregate.js'
4
+
5
+ export const metadata = {
6
+ id: '@ossy/consultancy/tasks/get-request-stats',
7
+ audit: false,
8
+ }
9
+
10
+ export async function run ({ payload, req }) {
11
+ const workspaceId = payload?.workspaceId ?? req?.workspaceId
12
+ if (!workspaceId) {
13
+ throw Object.assign(new Error('workspaceId required'), { status: 400 })
14
+ }
15
+
16
+ const state = await getProjection(workspaceId, RequestStatsProjection.ProjectionId)
17
+ const byMonth = state?.byMonth ?? {}
18
+ const byWeek = state?.byWeek ?? {}
19
+
20
+ return {
21
+ workspaceId,
22
+ byMonth,
23
+ byWeek,
24
+ months: monthPoints(byMonth),
25
+ }
26
+ }
package/src/index.js CHANGED
@@ -5,6 +5,7 @@ export { default as contractSchema } from './contract.schema.js'
5
5
  export { default as companyBasicInfoSchema } from './company-basic-info.schema.js'
6
6
  export { default as vacationSchema } from './vacation.schema.js'
7
7
  export { default as opportunitySchema } from './opportunity.schema.js'
8
+ export { default as requestSchema } from './request.schema.js'
8
9
  export { default as proposalSchema } from './proposal.schema.js'
9
10
  export { Definition } from './Definition.js'
10
11
  export { CreateConsultancyButton } from './CreateConsultancyButton.jsx'
@@ -0,0 +1,39 @@
1
+ /** Category the intake pipeline files as a consultancy request. */
2
+ export const REQUEST_CATEGORY = 'consultancy-request'
3
+
4
+ /**
5
+ * Below this, a consultancy-request label stays in the inbox.
6
+ * Jev's confidence is how concentrated the choice is.
7
+ */
8
+ export const MIN_REQUEST_CONFIDENCE = 0.8
9
+
10
+ /**
11
+ * Contrasting options so a contact, invoice, or receipt is not forced
12
+ * into a consultancy request. The chosen category is the only route.
13
+ */
14
+ export const INTAKE_CATEGORIES = Object.freeze([
15
+ {
16
+ name: REQUEST_CATEGORY,
17
+ description: 'Someone is offering or asking for a consulting assignment, role, or engagement.',
18
+ },
19
+ {
20
+ name: 'invoice',
21
+ description: 'A bill asking to be paid, with an amount due.',
22
+ },
23
+ {
24
+ name: 'receipt',
25
+ description: 'Proof that a payment was already made.',
26
+ },
27
+ {
28
+ name: 'contact',
29
+ description: 'A general message, question, or introduction that is none of the above.',
30
+ },
31
+ ])
32
+
33
+ /**
34
+ * @param {{ category?: string | null, confidence?: number | null } | null | undefined} result
35
+ */
36
+ export function acceptsRequestCategory (result) {
37
+ if (result?.category !== REQUEST_CATEGORY) return false
38
+ return typeof result.confidence === 'number' && result.confidence >= MIN_REQUEST_CONFIDENCE
39
+ }
@@ -0,0 +1,17 @@
1
+ import React from 'react'
2
+ import { DataLoader } from '@ossy/calendar'
3
+ import { KpiTrendPanel } from './forecast-panels.jsx'
4
+
5
+ export const metadata = {
6
+ id: '@ossy/consultancy/view/kpi-trend',
7
+ widget: {
8
+ title: 'consultancy.widgets.kpiTrend.title',
9
+ description: 'consultancy.widgets.kpiTrend.description',
10
+ ownsHeader: true,
11
+ },
12
+ }
13
+
14
+ /** Slot widget — fiscal-year KPI trend for dashboards. */
15
+ export default function KpiTrendWidget (props) {
16
+ return <DataLoader content={<KpiTrendPanel {...props} />} />
17
+ }
@@ -1,5 +1,6 @@
1
1
  import React, { useMemo, useState } from 'react'
2
2
  import {
3
+ Panel,
3
4
  View,
4
5
  Text,
5
6
  Separator,
@@ -33,32 +34,6 @@ function parseNumber (value, fallback = 0) {
33
34
  return Number.isFinite(parsed) ? parsed : fallback
34
35
  }
35
36
 
36
- function SectionPanel ({ title, children, ...props }) {
37
- return (
38
- <View surface="primary" roundness="xs" style={{ minWidth: 0, overflow: 'hidden' }} {...props}>
39
- <View stack bordered>
40
- <View.Item
41
- data-surface="primary"
42
- layout="row"
43
- style={{
44
- alignItems: 'center',
45
- justifyContent: 'space-between',
46
- padding: 'var(--space-s) var(--space-m)',
47
- gap: 'var(--space-m)',
48
- height: '48px',
49
- flexShrink: 0,
50
- }}
51
- >
52
- <Text variant="small" as="h2" style={{ fontWeight: 'bold' }} text={title} />
53
- </View.Item>
54
- <View.Item>
55
- {children}
56
- </View.Item>
57
- </View>
58
- </View>
59
- )
60
- }
61
-
62
37
  function MetricRow ({ label, value }) {
63
38
  return (
64
39
  <View layout="row" justifyContent="space-between" gap="s">
@@ -117,7 +92,7 @@ export function AssignmentMarginResultsPanel () {
117
92
 
118
93
  return (
119
94
  <View gap="m" data-margins-widget="results">
120
- <SectionPanel title="consultancy.margins.inputs.title">
95
+ <Panel title="consultancy.margins.inputs.title">
121
96
  <View inset="m" gap="m">
122
97
  <Field
123
98
  name="hourlyRate"
@@ -144,8 +119,8 @@ export function AssignmentMarginResultsPanel () {
144
119
  onChange={setField('availableHours')}
145
120
  />
146
121
  </View>
147
- </SectionPanel>
148
- <SectionPanel
122
+ </Panel>
123
+ <Panel
149
124
  title="consultancy.margins.results.title"
150
125
  data-margins-status={margin.isProfitable ? 'profitable' : 'unprofitable'}
151
126
  >
@@ -166,7 +141,7 @@ export function AssignmentMarginResultsPanel () {
166
141
  text={margin.coversEmployerCost ? 'consultancy.margins.results.coversCost' : 'consultancy.margins.results.missesCost'}
167
142
  />
168
143
  </View>
169
- </SectionPanel>
144
+ </Panel>
170
145
  </View>
171
146
  )
172
147
  }
@@ -187,7 +162,7 @@ export function AdminLeakagePanel () {
187
162
  })
188
163
 
189
164
  return (
190
- <SectionPanel title="consultancy.margins.leakage.title" data-margins-widget="leakage">
165
+ <Panel title="consultancy.margins.leakage.title" data-margins-widget="leakage">
191
166
  <View gap="m" inset="m">
192
167
  <Text variant="small" color="secondary" text="consultancy.margins.leakage.description" />
193
168
  <Field
@@ -211,6 +186,6 @@ export function AdminLeakagePanel () {
211
186
  <MetricRow label="consultancy.margins.leakage.hours" value={hoursFormat(leakage.leakedHours)} />
212
187
  <MetricRow label="consultancy.margins.leakage.revenue" value={money(leakage.leakedRevenue)} />
213
188
  </View>
214
- </SectionPanel>
189
+ </Panel>
215
190
  )
216
191
  }
package/src/org.page.jsx CHANGED
@@ -1,5 +1,5 @@
1
1
  import React from 'react'
2
- import { Text, View, Page, Tags } from '@ossy/design-system'
2
+ import { View, Page, Tags } from '@ossy/design-system'
3
3
  import { Overview } from './Overview.jsx'
4
4
  import { DataLoader } from '@ossy/calendar'
5
5
  import { Definition } from './Definition.js'
@@ -28,7 +28,6 @@ export const OrgPage = () => {
28
28
  >
29
29
  <View gap="m">
30
30
  <ConsultancyNav active="consultancy/org" />
31
- <Text variant="heading-secondary" as="h2" text="consultancy.nav.orgDetails" />
32
31
  <DataLoader content={<Overview />} />
33
32
  </View>
34
33
  </Page>
@@ -0,0 +1,103 @@
1
+ import React from 'react'
2
+ import { Button, Icon, List, Page, Panel, Tags, Text, View, useLocale } from '@ossy/design-system'
3
+ import {
4
+ ListPanelLayout,
5
+ listPanelPageProps,
6
+ useSelectedResourceId,
7
+ } from '@ossy/resources'
8
+ import { ConsultancyNav } from './ConsultancyNav.jsx'
9
+ import { CreateConsultancyButton } from './CreateConsultancyButton.jsx'
10
+ import { Definition } from './Definition.js'
11
+ import { ForecastWidgetMenu } from './forecast-widget-menu.jsx'
12
+ import { REQUEST_STATS_WIDGET_ID, RequestStatsChart } from './RequestStatsPanel.jsx'
13
+
14
+ export const metadata = {
15
+ id: 'consultancy/reports',
16
+ path: {
17
+ sv: '/konsultverksamhet/rapporter',
18
+ en: '/consultancy/reports',
19
+ },
20
+ }
21
+
22
+ const INCOMING_REQUESTS = 'incoming-requests'
23
+
24
+ const REPORTS = [
25
+ {
26
+ id: INCOMING_REQUESTS,
27
+ label: 'consultancy.requests.statsTitle',
28
+ description: 'consultancy.widgets.requestStats.description',
29
+ icon: 'chart',
30
+ },
31
+ ]
32
+
33
+ export const ReportsPage = () => {
34
+ const { t } = useLocale()
35
+ const { selectedResourceId, setSelectedResourceId, clearSelectedResourceId } = useSelectedResourceId()
36
+ const selected = REPORTS.find((report) => report.id === selectedResourceId) ?? null
37
+
38
+ const statusTags = (Definition.status ?? [])
39
+ .map((status) => ({ beta: 'Beta', 'coming-soon': 'Coming Soon' }[status]))
40
+ .filter(Boolean)
41
+
42
+ return (
43
+ <Page
44
+ {...listPanelPageProps}
45
+ title="consultancy.reports.title"
46
+ near={statusTags.length > 0 ? <Tags tags={statusTags} size="s" /> : undefined}
47
+ description="consultancy.reports.description"
48
+ far={<CreateConsultancyButton />}
49
+ >
50
+ <View gap="m" style={{ flex: '1 1 auto', height: '100%', minHeight: 0, display: 'flex', flexDirection: 'column' }}>
51
+ <ConsultancyNav active="consultancy/reports" />
52
+ <ListPanelLayout
53
+ data-consultancy-reports
54
+ listHeader="consultancy.nav.reports"
55
+ style={{ flex: '1 1 auto', minHeight: 0 }}
56
+ list={REPORTS.length === 0 ? (
57
+ <View inset="m">
58
+ <Text color="secondary" text="consultancy.reports.empty" />
59
+ </View>
60
+ ) : (
61
+ <List>
62
+ {REPORTS.map((report) => (
63
+ <List.Item
64
+ key={report.id}
65
+ selectable
66
+ selected={report.id === selectedResourceId}
67
+ onClick={() => setSelectedResourceId(report.id)}
68
+ data-report-id={report.id}
69
+ leading={(
70
+ <Icon size="s" name={report.icon} style={{ fill: 'hsl(0, 0%, 80%)' }} />
71
+ )}
72
+ meta={<Text variant="small" text={report.description} />}
73
+ >
74
+ {t(report.label)}
75
+ </List.Item>
76
+ ))}
77
+ </List>
78
+ )}
79
+ panel={selected ? (
80
+ <Panel
81
+ fill
82
+ title={selected.label}
83
+ data-request-stats
84
+ style={{ width: '100%', minWidth: 0, maxHeight: '100%', alignSelf: 'stretch' }}
85
+ actions={(
86
+ <View layout="row" alignItems="center" style={{ gap: '4px' }}>
87
+ {selected.id === INCOMING_REQUESTS ? (
88
+ <ForecastWidgetMenu componentId={REQUEST_STATS_WIDGET_ID} />
89
+ ) : null}
90
+ <Button prefix="close" variant="command" onClick={clearSelectedResourceId} />
91
+ </View>
92
+ )}
93
+ >
94
+ {selected.id === INCOMING_REQUESTS ? <RequestStatsChart /> : null}
95
+ </Panel>
96
+ ) : null}
97
+ />
98
+ </View>
99
+ </Page>
100
+ )
101
+ }
102
+
103
+ export default ReportsPage
@@ -0,0 +1,76 @@
1
+ const MONTH_KEY = /^(\d{4})-(\d{2})$/
2
+
3
+ /**
4
+ * Email Date header when it parses, otherwise the event's own write time.
5
+ *
6
+ * @param {unknown} receivedAt
7
+ * @param {unknown} created
8
+ * @returns {Date | null}
9
+ */
10
+ export function arrivalInstant (receivedAt, created) {
11
+ if (typeof receivedAt === 'string' && receivedAt.trim()) {
12
+ const fromHeader = Date.parse(receivedAt)
13
+ if (Number.isFinite(fromHeader)) return new Date(fromHeader)
14
+ }
15
+ const fromEvent = typeof created === 'number' ? created : Number(created)
16
+ if (Number.isFinite(fromEvent) && fromEvent > 0) return new Date(fromEvent)
17
+ return null
18
+ }
19
+
20
+ /**
21
+ * @param {Date | null | undefined} date
22
+ * @returns {string | null} `YYYY-MM` in UTC
23
+ */
24
+ export function utcMonthKey (date) {
25
+ if (!(date instanceof Date) || Number.isNaN(date.getTime())) return null
26
+ const month = String(date.getUTCMonth() + 1).padStart(2, '0')
27
+ return `${date.getUTCFullYear()}-${month}`
28
+ }
29
+
30
+ /**
31
+ * ISO week of the UTC date. The week-year can differ from the calendar year.
32
+ *
33
+ * @param {Date | null | undefined} date
34
+ * @returns {string | null} `YYYY-Www`
35
+ */
36
+ export function utcWeekKey (date) {
37
+ if (!(date instanceof Date) || Number.isNaN(date.getTime())) return null
38
+ const utc = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()))
39
+ const day = utc.getUTCDay() || 7
40
+ utc.setUTCDate(utc.getUTCDate() + 4 - day)
41
+ const yearStart = new Date(Date.UTC(utc.getUTCFullYear(), 0, 1))
42
+ const week = Math.ceil((((utc - yearStart) / 86400000) + 1) / 7)
43
+ return `${utc.getUTCFullYear()}-W${String(week).padStart(2, '0')}`
44
+ }
45
+
46
+ /**
47
+ * @param {Record<string, number> | null | undefined} byMonth
48
+ * @param {{ now?: Date }} [opts]
49
+ * @returns {Array<{ year: number, monthNumber: number, count: number }>}
50
+ */
51
+ export function monthPoints (byMonth, { now = new Date() } = {}) {
52
+ const keys = Object.keys(byMonth ?? {}).filter((key) => MONTH_KEY.test(key)).sort()
53
+ if (!keys.length) return []
54
+
55
+ const current = utcMonthKey(now)
56
+ const stop = current && current > keys[keys.length - 1] ? current : keys[keys.length - 1]
57
+ let [year, month] = keys[0].split('-').map(Number)
58
+ const [endYear, endMonth] = stop.split('-').map(Number)
59
+ const points = []
60
+
61
+ while (year < endYear || (year === endYear && month <= endMonth)) {
62
+ const key = `${year}-${String(month).padStart(2, '0')}`
63
+ points.push({
64
+ year,
65
+ monthNumber: month,
66
+ count: byMonth[key] ?? 0,
67
+ })
68
+ month += 1
69
+ if (month > 12) {
70
+ month = 1
71
+ year += 1
72
+ }
73
+ }
74
+
75
+ return points
76
+ }
@@ -0,0 +1,33 @@
1
+ import { arrivalInstant, monthPoints, utcMonthKey, utcWeekKey } from './request-buckets.js'
2
+
3
+ describe('request arrival buckets', () => {
4
+ it('uses the email date ahead of when the record was stored', () => {
5
+ const when = arrivalInstant('2023-04-15T10:00:00.000Z', Date.parse('2026-10-17T00:00:00.000Z'))
6
+ expect(utcMonthKey(when)).toBe('2023-04')
7
+ expect(utcWeekKey(when)).toBe('2023-W15')
8
+ })
9
+
10
+ it('falls back to the write time when the email has no date', () => {
11
+ const when = arrivalInstant('', Date.parse('2024-01-01T12:00:00.000Z'))
12
+ expect(utcMonthKey(when)).toBe('2024-01')
13
+ expect(utcWeekKey(when)).toBe('2024-W01')
14
+ })
15
+
16
+ it('keeps a New Year email in its ISO week-year', () => {
17
+ const when = arrivalInstant('2021-01-01T00:00:00.000Z')
18
+ expect(utcWeekKey(when)).toBe('2020-W53')
19
+ })
20
+
21
+ it('fills quiet months between the first email and now', () => {
22
+ const points = monthPoints(
23
+ { '2023-11': 2, '2024-01': 1 },
24
+ { now: new Date('2024-02-10T00:00:00.000Z') },
25
+ )
26
+ expect(points).toEqual([
27
+ { year: 2023, monthNumber: 11, count: 2 },
28
+ { year: 2023, monthNumber: 12, count: 0 },
29
+ { year: 2024, monthNumber: 1, count: 1 },
30
+ { year: 2024, monthNumber: 2, count: 0 },
31
+ ])
32
+ })
33
+ })
@@ -0,0 +1,52 @@
1
+ import { ConsultancySchema } from './schema-ids.js'
2
+ import { arrivalInstant, utcMonthKey, utcWeekKey } from './request-buckets.js'
3
+
4
+ /**
5
+ * Incoming consultancy requests, counted by the email's own date.
6
+ * One document per workspace. Weeks and months stay bounded by history,
7
+ * not by one row per message.
8
+ */
9
+ export class RequestStatsProjection {
10
+
11
+ static kind = 'projection'
12
+ static ProjectionId = '@ossy/consultancy/data/request-stats'
13
+
14
+ static sources = [
15
+ { type: ConsultancySchema.request, event: 'Created' },
16
+ ]
17
+
18
+ static scopeFromEvent (event) {
19
+ const workspaceId = event?.payload?.belongsTo ?? event?.belongsTo
20
+ return typeof workspaceId === 'string' && workspaceId ? workspaceId : null
21
+ }
22
+
23
+ static cacheKeys (scopeId) {
24
+ return [
25
+ `projection:${RequestStatsProjection.ProjectionId}:${scopeId}`,
26
+ 'action:@ossy/consultancy/actions/get-request-stats',
27
+ ]
28
+ }
29
+
30
+ static initialState (scopeId) {
31
+ return { workspaceId: scopeId, byMonth: {}, byWeek: {} }
32
+ }
33
+
34
+ /**
35
+ * @param {object} event
36
+ * @param {{ workspaceId?: string, byMonth?: Record<string, number>, byWeek?: Record<string, number> }} state
37
+ */
38
+ static Apply (event, state) {
39
+ const workspaceId = event?.payload?.belongsTo ?? state.workspaceId
40
+ const byMonth = { ...(state.byMonth ?? {}) }
41
+ const byWeek = { ...(state.byWeek ?? {}) }
42
+ const when = arrivalInstant(event?.payload?.content?.receivedAt, event?.created)
43
+ const month = utcMonthKey(when)
44
+ const week = utcWeekKey(when)
45
+ if (month) byMonth[month] = (byMonth[month] ?? 0) + 1
46
+ if (week) byWeek[week] = (byWeek[week] ?? 0) + 1
47
+ return { workspaceId, byMonth, byWeek }
48
+ }
49
+ }
50
+
51
+ export { RequestStatsProjection as Aggregate }
52
+ export const id = 'consultancy/data/request-stats'