@ossy/consultancy 3.20.1 → 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 (48) hide show
  1. package/package.json +4 -2
  2. package/src/AssignmentMarginCalculator.jsx +7 -32
  3. package/src/ConsultancyNav.jsx +30 -1
  4. package/src/ConsultancyRecordList.jsx +172 -0
  5. package/src/CreateConsultancyButton.jsx +61 -13
  6. package/src/Forecast.jsx +42 -220
  7. package/src/Overview.jsx +10 -31
  8. package/src/RequestStatsPanel.jsx +66 -0
  9. package/src/consultancy.page.jsx +3 -40
  10. package/src/contracts.page.jsx +26 -0
  11. package/src/current-month.component.jsx +43 -25
  12. package/src/employees.page.jsx +26 -0
  13. package/src/en.translations.json +67 -2
  14. package/src/extract-request.action.js +5 -0
  15. package/src/extract-request.task.js +100 -0
  16. package/src/extract-request.task.spec.js +89 -0
  17. package/src/forecast-panels.jsx +125 -0
  18. package/src/forecast-widget-menu.jsx +89 -0
  19. package/src/get-request-stats.action.js +6 -0
  20. package/src/get-request-stats.task.js +26 -0
  21. package/src/index.js +1 -0
  22. package/src/intake-categories.js +39 -0
  23. package/src/kpi-trend.component.jsx +17 -0
  24. package/src/margin-panels.jsx +7 -32
  25. package/src/opportunities.page.jsx +26 -0
  26. package/src/opportunity.schema.js +1 -1
  27. package/src/org.page.jsx +1 -2
  28. package/src/proposals.page.jsx +26 -0
  29. package/src/reports.page.jsx +103 -0
  30. package/src/request-buckets.js +76 -0
  31. package/src/request-buckets.spec.js +33 -0
  32. package/src/request-stats.aggregate.js +52 -0
  33. package/src/request-stats.aggregate.spec.js +34 -0
  34. package/src/request-stats.component.jsx +16 -0
  35. package/src/request.schema.js +29 -0
  36. package/src/requests.page.jsx +26 -0
  37. package/src/schema-ids.js +1 -0
  38. package/src/screen-inbound.task.js +84 -0
  39. package/src/screen-inbound.task.spec.js +97 -0
  40. package/src/sv.translations.json +67 -2
  41. package/src/use-chart-months.js +27 -0
  42. package/src/utilization-hours.js +196 -0
  43. package/src/utilization-hours.spec.js +134 -0
  44. package/src/utilization.component.jsx +17 -0
  45. package/src/vacations.page.jsx +26 -0
  46. package/src/year-totals.component.jsx +17 -0
  47. package/src/forecast-kpi-chart.js +0 -137
  48. package/src/forecast-kpi-chart.spec.js +0 -122
@@ -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
  }
@@ -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' },
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,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
@@ -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'
@@ -0,0 +1,34 @@
1
+ import { RequestStatsProjection } from './request-stats.aggregate.js'
2
+ import { ConsultancySchema } from './schema-ids.js'
3
+
4
+ describe('RequestStatsProjection', () => {
5
+ it('counts a request in the email month and week, not the import week', () => {
6
+ const state = RequestStatsProjection.Apply({
7
+ type: ConsultancySchema.request,
8
+ event: 'Created',
9
+ created: Date.parse('2026-10-17T08:00:00.000Z'),
10
+ payload: {
11
+ belongsTo: 'ws-1',
12
+ content: { receivedAt: '2023-04-15T10:00:00.000Z' },
13
+ },
14
+ }, RequestStatsProjection.initialState('ws-1'))
15
+
16
+ expect(state.byMonth).toEqual({ '2023-04': 1 })
17
+ expect(state.byWeek).toEqual({ '2023-W15': 1 })
18
+ })
19
+
20
+ it('adds a second email in the same month', () => {
21
+ const first = RequestStatsProjection.Apply({
22
+ created: 1,
23
+ payload: { belongsTo: 'ws-1', content: { receivedAt: '2023-04-02T00:00:00.000Z' } },
24
+ }, RequestStatsProjection.initialState('ws-1'))
25
+ const second = RequestStatsProjection.Apply({
26
+ created: 2,
27
+ payload: { belongsTo: 'ws-1', content: { receivedAt: '2023-04-20T00:00:00.000Z' } },
28
+ }, first)
29
+
30
+ expect(second.byMonth['2023-04']).toBe(2)
31
+ expect(second.byWeek['2023-W13']).toBe(1)
32
+ expect(second.byWeek['2023-W16']).toBe(1)
33
+ })
34
+ })
@@ -0,0 +1,16 @@
1
+ import React from 'react'
2
+ import { RequestStatsPanel } from './RequestStatsPanel.jsx'
3
+
4
+ export const metadata = {
5
+ id: '@ossy/consultancy/view/request-stats',
6
+ widget: {
7
+ title: 'consultancy.widgets.requestStats.title',
8
+ description: 'consultancy.widgets.requestStats.description',
9
+ span: 8,
10
+ ownsHeader: true,
11
+ },
12
+ }
13
+
14
+ export default function RequestStatsWidget (props) {
15
+ return <RequestStatsPanel {...props} />
16
+ }
@@ -0,0 +1,29 @@
1
+ import { ConsultancySchema } from './schema-ids.js'
2
+
3
+ /**
4
+ * A consultancy request is the assignment described in an inbound email
5
+ * (role, duration, where, who wrote). It is not an Opportunity.
6
+ * Opportunity is the sales pipeline after someone qualifies the request
7
+ * (status, fit, next action, linked proposal).
8
+ */
9
+ export default {
10
+ name: 'Request',
11
+ id: ConsultancySchema.request,
12
+ categoryName: 'Consultancy',
13
+ icon: 'mail',
14
+ fields: [
15
+ { name: 'title', type: 'text', required: true, description: 'Assignment title' },
16
+ { name: 'summary', type: 'textarea', description: 'What the client is asking for' },
17
+ { name: 'role', type: 'text', description: 'Profile they are looking for' },
18
+ { name: 'skills', type: 'textarea', description: 'Skills or technologies named in the request' },
19
+ { name: 'location', type: 'text', description: 'Where the work happens' },
20
+ { name: 'duration', type: 'text', description: 'How long the assignment lasts, in the message\'s own words' },
21
+ { name: 'start', type: 'text', description: 'When the assignment starts, in the message\'s own words' },
22
+ { name: 'rate', type: 'number', description: 'Numeric amount only, without a currency symbol. Omit when the message states no rate.' },
23
+ { name: 'currency', type: 'select', options: ['SEK', 'EUR', 'USD', 'NOK', 'DKK'], description: 'Currency of the rate. Omit when the message states no rate.' },
24
+ { name: 'contactName', type: 'text', description: 'Person who sent the request' },
25
+ { name: 'contactEmail', type: 'email', description: 'Email address of that person. Omit when the message has none.' },
26
+ { name: 'messageId', type: 'text', description: 'Message-ID of the inbound email' },
27
+ { name: 'receivedAt', type: 'text', description: 'ISO-8601 arrival time from the email Date header. Omit; the pipeline copies it.' },
28
+ ],
29
+ }
@@ -0,0 +1,26 @@
1
+ import React from 'react'
2
+ import { ConsultancyRecordPage } from './ConsultancyRecordList.jsx'
3
+ import { ConsultancySchema } from './schema-ids.js'
4
+ import requestSchema from './request.schema.js'
5
+
6
+ export const metadata = {
7
+ id: 'consultancy/requests',
8
+ path: {
9
+ sv: '/konsultverksamhet/forfragningar',
10
+ en: '/consultancy/requests',
11
+ },
12
+ }
13
+
14
+ export const RequestsPage = () => (
15
+ <ConsultancyRecordPage
16
+ active="consultancy/requests"
17
+ title="consultancy.requests.title"
18
+ description="consultancy.requests.description"
19
+ schemaId={ConsultancySchema.request}
20
+ icon={requestSchema.icon}
21
+ listHeader="consultancy.nav.requests"
22
+ emptyText="consultancy.requests.empty"
23
+ />
24
+ )
25
+
26
+ export default RequestsPage
package/src/schema-ids.js CHANGED
@@ -5,5 +5,6 @@ export const ConsultancySchema = Object.freeze({
5
5
  employee: '@ossy/consultancy/schema/employee',
6
6
  vacation: '@ossy/consultancy/schema/vacation',
7
7
  opportunity: '@ossy/consultancy/schema/opportunity',
8
+ request: '@ossy/consultancy/schema/request',
8
9
  proposal: '@ossy/consultancy/schema/proposal',
9
10
  })
@@ -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
+ }