@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
package/src/Overview.jsx CHANGED
@@ -1,33 +1,7 @@
1
1
  import React from 'react'
2
- import { View, Text, useLocale } from '@ossy/design-system'
2
+ import { Panel, View, Text, useLocale } from '@ossy/design-system'
3
3
  import { useCompany } from '@ossy/calendar'
4
4
 
5
- function SectionPanel ({ title, children }) {
6
- return (
7
- <View surface="primary" roundness="xs" style={{ minWidth: 0, overflow: 'hidden', height: '100%' }}>
8
- <View stack bordered>
9
- <View.Item
10
- data-surface="primary"
11
- layout="row"
12
- style={{
13
- alignItems: 'center',
14
- justifyContent: 'space-between',
15
- padding: 'var(--space-s) var(--space-m)',
16
- gap: 'var(--space-m)',
17
- height: '48px',
18
- flexShrink: 0,
19
- }}
20
- >
21
- <Text variant="small" as="h2" style={{ fontWeight: 'bold' }}>{title}</Text>
22
- </View.Item>
23
- <View.Item>
24
- {children}
25
- </View.Item>
26
- </View>
27
- </View>
28
- )
29
- }
30
-
31
5
  function InfoRow ({ label, value }) {
32
6
  return (
33
7
  <View layout="row" justifyContent="space-between" gap="s">
@@ -63,7 +37,7 @@ export const Overview = () => {
63
37
  style={{ alignItems: 'stretch' }}
64
38
  >
65
39
  <View style={{ flex: '1 1 280px', minWidth: 0 }}>
66
- <SectionPanel title={t('consultancy.overview.fiscalYears')}>
40
+ <Panel title="consultancy.overview.fiscalYears" style={{ height: '100%' }}>
67
41
  <View gap="s" inset="m">
68
42
  {fiscalYears.length === 0 ? (
69
43
  <Text variant="small" text="consultancy.overview.noFiscalYears" />
@@ -74,11 +48,16 @@ export const Overview = () => {
74
48
  </View>
75
49
  ))}
76
50
  </View>
77
- </SectionPanel>
51
+ </Panel>
78
52
  </View>
79
53
 
80
54
  <View style={{ flex: '1 1 280px', minWidth: 0 }}>
81
- <SectionPanel title={company?.name || t('consultancy.overview.company')}>
55
+ <Panel
56
+ style={{ height: '100%' }}
57
+ title={company?.name
58
+ ? <Text variant="small" as="h2" style={{ fontWeight: 'bold' }}>{company.name}</Text>
59
+ : 'consultancy.overview.company'}
60
+ >
82
61
  <View gap="s" inset="m">
83
62
  <InfoRow
84
63
  label={t('@ossy/consultancy/schema/company-basic-info.registrationDate.label')}
@@ -105,7 +84,7 @@ export const Overview = () => {
105
84
  value={vatPeriodLabel}
106
85
  />
107
86
  </View>
108
- </SectionPanel>
87
+ </Panel>
109
88
  </View>
110
89
  </View>
111
90
  )
@@ -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,12 @@
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
+ import { MonthDayGrid } from './MonthDayGrid.jsx'
6
+
7
+ export const CURRENT_MONTH_WIDGET_ID = '@ossy/consultancy/view/current-month'
8
+
9
+ const panelStyle = { height: '100%', flex: '1 1 auto', minWidth: 0 }
4
10
 
5
11
  function MetricRow ({ label, value }) {
6
12
  return (
@@ -12,11 +18,11 @@ function MetricRow ({ label, value }) {
12
18
  }
13
19
 
14
20
  /**
15
- * Compact current-month forecast metrics (standalone dashboard panel).
21
+ * Compact current-month forecast metrics, using the shared Panel header.
16
22
  */
17
- export function CurrentMonthForecastPanel () {
23
+ export function CurrentMonthForecastPanel ({ dashboardId, pinnedWidgetId }) {
18
24
  const months = useForecast()
19
- const { language } = useLocale()
25
+ const { language, t } = useLocale()
20
26
  const money = (value) => new Intl.NumberFormat(language === 'sv' ? 'sv-SE' : 'en-SE', {
21
27
  style: 'currency',
22
28
  currency: 'SEK',
@@ -29,38 +35,54 @@ export function CurrentMonthForecastPanel () {
29
35
  const current = (Array.isArray(months) ? months : []).find((m) => m.isCurrentMonth)
30
36
  ?? (Array.isArray(months) ? months[0] : null)
31
37
 
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
- }
38
+ const actions = (
39
+ <ForecastWidgetMenu
40
+ componentId={CURRENT_MONTH_WIDGET_ID}
41
+ dashboardId={dashboardId}
42
+ pinnedWidgetId={pinnedWidgetId}
43
+ />
44
+ )
41
45
 
42
46
  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>
47
+ <Panel
48
+ title={current ? (
49
+ <Text variant="small" as="h2" style={{ fontWeight: 'bold' }}>
50
+ {t('consultancy.forecasts.monthForecast', { month: current.month })}
51
+ </Text>
52
+ ) : 'consultancy.widgets.forecastCurrentMonth.title'}
53
+ style={panelStyle}
54
+ actions={actions}
55
+ data-forecasts-widget="current-month"
56
+ >
57
+ {!current ? (
58
+ <View inset="m">
59
+ <Text color="secondary" text="consultancy.forecasts.widget.empty" />
60
+ </View>
61
+ ) : (
62
+ <>
63
+ <View gap="s" inset="m">
64
+ <MetricRow label="consultancy.forecasts.income" value={money(current.projectedIncome)} />
65
+ <MetricRow label="consultancy.forecasts.salaryCost" value={money(current.monthlyCostOfEmployees)} />
66
+ <MetricRow label="consultancy.forecasts.revenue" value={money(current.revenue)} />
67
+ <MetricRow label="consultancy.forecasts.hoursWorked" value={hours(current.hoursWorked)} />
68
+ </View>
69
+ <MonthDayGrid month={current} />
70
+ </>
71
+ )}
72
+ </Panel>
52
73
  )
53
74
  }
54
75
 
55
76
  export const metadata = {
56
- id: '@ossy/consultancy/view/current-month',
77
+ id: CURRENT_MONTH_WIDGET_ID,
57
78
  widget: {
58
79
  title: 'consultancy.widgets.forecastCurrentMonth.title',
59
80
  description: 'consultancy.widgets.forecastCurrentMonth.description',
81
+ ownsHeader: true,
60
82
  },
61
83
  }
62
84
 
63
85
  /** Slot widget — current-month forecast panel for dashboards. */
64
- export default function CurrentMonthForecastWidget () {
65
- return <DataLoader content={<CurrentMonthForecastPanel />} />
86
+ export default function CurrentMonthForecastWidget (props) {
87
+ return <DataLoader content={<CurrentMonthForecastPanel {...props} />} />
66
88
  }
@@ -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.",
@@ -151,6 +165,32 @@
151
165
  "@ossy/consultancy/schema/vacation.start.description": "First day of vacation (inclusive). These days are not billed.",
152
166
  "@ossy/consultancy/schema/vacation.end.label": "Last day off",
153
167
  "@ossy/consultancy/schema/vacation.end.description": "Last day of vacation (inclusive).",
168
+ "@ossy/consultancy/schema/request.title.label": "Title",
169
+ "@ossy/consultancy/schema/request.title.description": "Title of the assignment.",
170
+ "@ossy/consultancy/schema/request.summary.label": "Summary",
171
+ "@ossy/consultancy/schema/request.summary.description": "What the client is asking for.",
172
+ "@ossy/consultancy/schema/request.role.label": "Role",
173
+ "@ossy/consultancy/schema/request.role.description": "The profile they are looking for.",
174
+ "@ossy/consultancy/schema/request.skills.label": "Skills",
175
+ "@ossy/consultancy/schema/request.skills.description": "Skills or technologies named in the request.",
176
+ "@ossy/consultancy/schema/request.location.label": "Location",
177
+ "@ossy/consultancy/schema/request.location.description": "Where the work happens.",
178
+ "@ossy/consultancy/schema/request.duration.label": "Duration",
179
+ "@ossy/consultancy/schema/request.duration.description": "How long the assignment lasts.",
180
+ "@ossy/consultancy/schema/request.start.label": "Start",
181
+ "@ossy/consultancy/schema/request.start.description": "When the assignment starts.",
182
+ "@ossy/consultancy/schema/request.rate.label": "Rate",
183
+ "@ossy/consultancy/schema/request.rate.description": "Amount without a currency symbol.",
184
+ "@ossy/consultancy/schema/request.currency.label": "Currency",
185
+ "@ossy/consultancy/schema/request.currency.description": "Currency of the rate.",
186
+ "@ossy/consultancy/schema/request.contactName.label": "Contact",
187
+ "@ossy/consultancy/schema/request.contactName.description": "The person who sent the request.",
188
+ "@ossy/consultancy/schema/request.contactEmail.label": "Contact email",
189
+ "@ossy/consultancy/schema/request.contactEmail.description": "That person's email address.",
190
+ "@ossy/consultancy/schema/request.messageId.label": "Message id",
191
+ "@ossy/consultancy/schema/request.messageId.description": "Id of the inbound email.",
192
+ "@ossy/consultancy/schema/request.receivedAt.label": "Received",
193
+ "@ossy/consultancy/schema/request.receivedAt.description": "When the email was sent.",
154
194
  "@ossy/consultancy/schema/opportunity.title.label": "Title",
155
195
  "@ossy/consultancy/schema/opportunity.title.description": "Short name for this lead or opportunity.",
156
196
  "@ossy/consultancy/schema/opportunity.source.label": "Source",
@@ -187,7 +227,8 @@
187
227
  "@ossy/consultancy/schema/proposal.body.description": "Full proposal text.",
188
228
  "consultancy.nav.orgDetails": "Org Details",
189
229
  "consultancy.forecasts.yearChart": "KPI trend",
190
- "consultancy.forecasts.yearSummary": "Fiscal year totals",
230
+ "consultancy.forecasts.monthForecast": "{month} forecast",
231
+ "consultancy.forecasts.yearSummary": "Fiscal year forecast",
191
232
  "consultancy.forecasts.yearChartEmpty": "No forecast months to chart yet.",
192
233
  "consultancy.margins.pin.done": "Pinned to dashboard",
193
234
  "consultancy.margins.pin.error": "Pin failed — try again",
@@ -202,5 +243,14 @@
202
243
  "consultancy.widgets.adminLeakage.title": "Admin leakage",
203
244
  "consultancy.widgets.adminLeakage.description": "Annual hours and revenue lost to recurring admin work.",
204
245
  "consultancy.widgets.forecastCurrentMonth.title": "This month forecast",
205
- "consultancy.widgets.forecastCurrentMonth.description": "Projected income, salary cost, revenue, and hours for the current month."
246
+ "consultancy.widgets.forecastCurrentMonth.description": "Projected income, salary cost, revenue, and hours for the current month.",
247
+ "consultancy.widgets.kpiTrend.title": "KPI trend",
248
+ "consultancy.widgets.kpiTrend.description": "Forecast and actual income, salary cost, and revenue for the fiscal year.",
249
+ "consultancy.widgets.yearTotals.title": "Fiscal year forecast",
250
+ "consultancy.widgets.yearTotals.description": "Income, salary cost, revenue, and hours for the fiscal year.",
251
+ "consultancy.widgets.utilization.title": "Utilization",
252
+ "consultancy.widgets.utilization.description": "Forecast and actual hours across the fiscal year.",
253
+ "consultancy.widgets.requestStats.title": "Incoming requests",
254
+ "consultancy.widgets.requestStats.description": "Requests per month, dated by the email's own arrival time.",
255
+ "consultancy.widgets.menu": "More"
206
256
  }
@@ -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,117 @@
1
+ import { forwardedOriginal } from '@ossy/email/forwarded-original'
2
+ import { ConsultancySchema } from './schema-ids.js'
3
+ import { location } from './locations.js'
4
+
5
+ const GetResource = { id: '@ossy/resources/actions/get' }
6
+ const ListResources = { id: '@ossy/resources/actions/list' }
7
+ const CreateResource = { id: '@ossy/resources/actions/create' }
8
+ const ExtractStructuredData = { id: '@ossy/media-tasks/actions/extract-structured-data' }
9
+ const INBOUND_MESSAGE = '@ossy/email/schema/inbound-message'
10
+
11
+ export const metadata = {
12
+ id: '@ossy/consultancy/tasks/extract-request',
13
+ triggers: [
14
+ {
15
+ kind: 'on_action',
16
+ action: '@ossy/consultancy/actions/extract-request',
17
+ },
18
+ ],
19
+ outputs: [
20
+ {
21
+ name: 'request',
22
+ kind: 'location',
23
+ schemaId: ConsultancySchema.request,
24
+ prefix: location,
25
+ },
26
+ ],
27
+ }
28
+
29
+ function fail (message, status) {
30
+ throw Object.assign(new Error(message), { status })
31
+ }
32
+
33
+ function workspaceIdFrom ({ event, payload, req }) {
34
+ return event?.payload?.belongsTo
35
+ ?? event?.belongsTo
36
+ ?? payload?.workspaceId
37
+ ?? req?.workspaceId
38
+ ?? null
39
+ }
40
+
41
+ /**
42
+ * Text the extractor should read. The subject often is the assignment title.
43
+ *
44
+ * @param {object | null | undefined} resource
45
+ */
46
+ export function requestSourceText (resource) {
47
+ const content = resource?.content && typeof resource.content === 'object' ? resource.content : {}
48
+ const forward = forwardedOriginal(typeof content.text === 'string' ? content.text : '')
49
+ const subject = forward?.subject || content.subject
50
+ const from = forward?.from || content.from
51
+ const body = (forward?.body || (typeof content.text === 'string' ? content.text : '')).trim()
52
+ const lines = []
53
+ if (subject) lines.push(`Subject: ${subject}`)
54
+ if (from) lines.push(`From: ${from}`)
55
+ if (body) lines.push('', body)
56
+ return lines.join('\n').trim()
57
+ }
58
+
59
+ function asResourceList (result) {
60
+ if (Array.isArray(result)) return result
61
+ if (Array.isArray(result?.items)) return result.items
62
+ return []
63
+ }
64
+
65
+ /**
66
+ * Inbound assignment → extract-structured-data → a consultancy request resource.
67
+ * Screening decides whether this runs. It does not listen to every inbound message.
68
+ */
69
+ export async function run ({ event, payload, req, sdk }) {
70
+ if (!sdk?.invoke) fail('sdk is required', 500)
71
+
72
+ const resourceId = event?.resourceId || payload?.resourceId
73
+ if (!resourceId) fail('resourceId is required', 400)
74
+
75
+ const workspaceId = workspaceIdFrom({ event, payload, req })
76
+ if (!workspaceId) fail('workspaceId is required', 400)
77
+
78
+ const resource = await sdk.invoke(GetResource, { resourceId })
79
+ if (resource?.type !== INBOUND_MESSAGE) fail('inbound message is required', 400)
80
+
81
+ const text = requestSourceText(resource)
82
+ if (!text) fail('text is required', 400)
83
+
84
+ const messageId = typeof resource.content?.messageId === 'string' ? resource.content.messageId : ''
85
+ if (messageId) {
86
+ const listed = await sdk.invoke(ListResources, { location, workspaceId })
87
+ const existing = asResourceList(listed).find((item) => item?.content?.messageId === messageId)
88
+ if (existing?.id) return { id: existing.id, workspaceId, content: existing.content }
89
+ }
90
+
91
+ const extracted = await sdk.invoke(ExtractStructuredData, {
92
+ schemaId: ConsultancySchema.request,
93
+ text,
94
+ workspaceId,
95
+ })
96
+ const data = extracted?.data
97
+ if (!data || typeof data !== 'object') fail('extraction is required', 422)
98
+
99
+ const receivedAt = typeof resource.content?.receivedAt === 'string' ? resource.content.receivedAt.trim() : ''
100
+ const content = {
101
+ ...data,
102
+ ...(messageId ? { messageId } : {}),
103
+ ...(receivedAt ? { receivedAt } : {}),
104
+ }
105
+ const title = typeof content.title === 'string' ? content.title.trim() : ''
106
+ if (!title) fail('title is required', 422)
107
+
108
+ const created = await sdk.invoke(CreateResource, {
109
+ workspaceId,
110
+ type: ConsultancySchema.request,
111
+ location,
112
+ name: title,
113
+ content,
114
+ })
115
+
116
+ return { id: created?.id ?? null, workspaceId, content }
117
+ }
@@ -0,0 +1,131 @@
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 ListResources = { id: '@ossy/resources/actions/list' }
8
+ const CreateResource = { id: '@ossy/resources/actions/create' }
9
+ const ExtractStructuredData = { id: '@ossy/media-tasks/actions/extract-structured-data' }
10
+
11
+ const inbound = {
12
+ id: 'msg-1',
13
+ type: '@ossy/email/schema/inbound-message',
14
+ content: {
15
+ from: 'Anna Berg <anna@client.se>',
16
+ to: 'inbox+ws-1@inbound.ossy.se',
17
+ subject: 'Senior React, 6 manader',
18
+ text: 'Vi soker en senior React-utvecklare i Stockholm. Uppdraget ar 6 manader med start i januari. Anna Berg, anna@client.se.',
19
+ messageId: 'assignment-1@client.se',
20
+ receivedAt: '2023-04-15T10:00:00.000Z',
21
+ },
22
+ }
23
+
24
+ const extracted = {
25
+ title: 'Senior React, 6 manader',
26
+ summary: 'Senior React developer in Stockholm for 6 months, starting in January.',
27
+ role: 'Senior React developer',
28
+ skills: 'React',
29
+ location: 'Stockholm',
30
+ duration: '6 months',
31
+ start: 'January',
32
+ contactName: 'Anna Berg',
33
+ contactEmail: 'anna@client.se',
34
+ }
35
+
36
+ describe('extract-request task', () => {
37
+ it('runs only when the extract-request action is invoked', () => {
38
+ expect(metadata.triggers).toEqual([
39
+ {
40
+ kind: 'on_action',
41
+ action: '@ossy/consultancy/actions/extract-request',
42
+ },
43
+ ])
44
+ expect(metadata.outputs[0].schemaId).toBe(ConsultancySchema.request)
45
+ })
46
+
47
+ it('turns a forwarded assignment email into a request record', async () => {
48
+ const calls = []
49
+ const sdk = {
50
+ async invoke (action, payload) {
51
+ calls.push({ id: action.id, payload })
52
+ if (action.id === GetResource.id) return inbound
53
+ if (action.id === ListResources.id) return []
54
+ if (action.id === ExtractStructuredData.id) return { data: extracted }
55
+ if (action.id === CreateResource.id) return { id: 'request-1' }
56
+ throw new Error(`unexpected ${action.id}`)
57
+ },
58
+ }
59
+
60
+ const result = await run({
61
+ event: { resourceId: inbound.id, payload: { belongsTo: 'ws-1' } },
62
+ sdk,
63
+ })
64
+
65
+ const extractCall = calls.find((call) => call.id === ExtractStructuredData.id)
66
+ expect(extractCall.payload.schemaId).toBe(ConsultancySchema.request)
67
+ expect(extractCall.payload.text).toBe(requestSourceText(inbound))
68
+ expect(extractCall.payload.text).toContain('Senior React, 6 manader')
69
+ expect(extractCall.payload.text).toContain('Stockholm')
70
+
71
+ const created = calls.find((call) => call.id === CreateResource.id).payload
72
+ expect(created).toMatchObject({
73
+ workspaceId: 'ws-1',
74
+ type: ConsultancySchema.request,
75
+ name: 'Senior React, 6 manader',
76
+ })
77
+ expect(created.content).toMatchObject({
78
+ ...extracted,
79
+ messageId: 'assignment-1@client.se',
80
+ receivedAt: '2023-04-15T10:00:00.000Z',
81
+ })
82
+
83
+ const engine = Schema.of({ schemas: [requestSchema] })
84
+ expect(validateContent(engine, requestSchema, created.content).ok).toBe(true)
85
+ expect(result).toEqual({
86
+ id: 'request-1',
87
+ workspaceId: 'ws-1',
88
+ content: created.content,
89
+ })
90
+ })
91
+
92
+ it('reads the original sender from a forwarded body', () => {
93
+ const text = requestSourceText({
94
+ content: {
95
+ from: 'oskars.sylwan@ossy.se',
96
+ subject: 'Fwd: Teknisk specialist SDK, Stockholm',
97
+ text: [
98
+ '---------- Forwarded message ---------',
99
+ 'From: Client <client@studio.se>',
100
+ 'Subject: Teknisk specialist SDK, Stockholm',
101
+ '',
102
+ 'Vi behöver en specialist i Stockholm.',
103
+ ].join('\n'),
104
+ },
105
+ })
106
+ expect(text).toContain('From: client@studio.se')
107
+ expect(text).toContain('Subject: Teknisk specialist SDK, Stockholm')
108
+ expect(text).not.toContain('oskars.sylwan@ossy.se')
109
+ })
110
+
111
+ it('returns the request already filed for this message', async () => {
112
+ const calls = []
113
+ const sdk = {
114
+ async invoke (action) {
115
+ calls.push(action.id)
116
+ if (action.id === GetResource.id) return inbound
117
+ if (action.id === ListResources.id) return [{ id: 'request-existing', content: { messageId: inbound.content.messageId } }]
118
+ throw new Error(`unexpected ${action.id}`)
119
+ },
120
+ }
121
+
122
+ const result = await run({
123
+ payload: { resourceId: inbound.id, workspaceId: 'ws-1' },
124
+ sdk,
125
+ })
126
+
127
+ expect(result.id).toBe('request-existing')
128
+ expect(calls).not.toContain(ExtractStructuredData.id)
129
+ expect(calls).not.toContain(CreateResource.id)
130
+ })
131
+ })