@ossy/consultancy 3.24.1 → 3.26.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 (54) hide show
  1. package/README.md +7 -7
  2. package/package.json +7 -5
  3. package/src/ConsultancyNav.jsx +6 -6
  4. package/src/CreateConsultancyButton.jsx +21 -7
  5. package/src/Forecast.jsx +38 -37
  6. package/src/MonthDayGrid.jsx +18 -50
  7. package/src/RequestMatches.jsx +29 -19
  8. package/src/RequestStatsPanel.jsx +1 -1
  9. package/src/ResumeMatches.jsx +51 -0
  10. package/src/calendar-quarter-months.js +36 -0
  11. package/src/calendar-quarter-months.spec.js +22 -0
  12. package/src/create-company.flow.js +9 -9
  13. package/src/current-month.component.jsx +14 -25
  14. package/src/delete-company.flow.js +5 -5
  15. package/src/en.translations.json +17 -32
  16. package/src/extract-request.task.js +20 -13
  17. package/src/extract-request.task.spec.js +7 -3
  18. package/src/file-inbound-request.task.js +93 -0
  19. package/src/file-inbound-request.task.spec.js +118 -0
  20. package/src/forecast-figures.jsx +42 -0
  21. package/src/forecast-panels.jsx +29 -42
  22. package/src/index.js +0 -1
  23. package/src/intake-categories.js +6 -22
  24. package/src/kpi-trend.component.jsx +1 -1
  25. package/src/match-reasons.js +85 -0
  26. package/src/match-reasons.spec.js +73 -0
  27. package/src/match-resumes.js +12 -7
  28. package/src/match-resumes.spec.js +13 -8
  29. package/src/match-resumes.task.js +1 -22
  30. package/src/match-resumes.task.spec.js +19 -14
  31. package/src/{consultancy.page.jsx → overview.page.jsx} +7 -7
  32. package/src/refresh-matches.js +38 -0
  33. package/src/refresh-matches.spec.js +31 -1
  34. package/src/refresh-matches.task.js +322 -72
  35. package/src/refresh-matches.task.spec.js +229 -27
  36. package/src/request.schema.js +0 -1
  37. package/src/{resume-inbound-screening.task.js → resume-inbound-requests.task.js} +12 -14
  38. package/src/{resume-inbound-screening.task.spec.js → resume-inbound-requests.task.spec.js} +32 -18
  39. package/src/resumes.page.jsx +43 -12
  40. package/src/schema-ids.js +0 -1
  41. package/src/spend-for-month.js +67 -0
  42. package/src/spend-for-month.spec.js +41 -0
  43. package/src/spend-year.jsx +91 -0
  44. package/src/{org.page.jsx → spend.page.jsx} +14 -13
  45. package/src/sv.translations.json +17 -32
  46. package/src/use-chart-months.js +5 -2
  47. package/src/use-spend-by-month.js +52 -0
  48. package/src/utilization.component.jsx +1 -1
  49. package/src/view-forecasts.flow.js +3 -3
  50. package/src/year-totals.component.jsx +1 -1
  51. package/src/Overview.jsx +0 -91
  52. package/src/company-basic-info.schema.js +0 -25
  53. package/src/screen-inbound.task.js +0 -133
  54. package/src/screen-inbound.task.spec.js +0 -154
@@ -1,36 +1,23 @@
1
1
  import React from 'react'
2
2
  import { Panel, Text, View, useLocale } from '@ossy/design-system'
3
3
  import { DataLoader, useForecast } from '@ossy/calendar'
4
+ import { ForecastFigures } from './forecast-figures.jsx'
4
5
  import { ForecastWidgetMenu } from './forecast-widget-menu.jsx'
5
6
  import { MonthDayGrid } from './MonthDayGrid.jsx'
7
+ import { spendForMonth } from './spend-for-month.js'
8
+ import { useSpendByMonth } from './use-spend-by-month.js'
6
9
 
7
10
  export const CURRENT_MONTH_WIDGET_ID = '@ossy/consultancy/view/current-month'
8
11
 
9
12
  const panelStyle = { height: '100%', flex: '1 1 auto', minWidth: 0 }
10
13
 
11
- function MetricRow ({ label, value }) {
12
- return (
13
- <View layout="row" gap="s" style={{ justifyContent: 'space-between' }}>
14
- <Text variant="m" style={{ marginBottom: 0 }} text={label} />
15
- <Text variant="m" style={{ marginBottom: 0 }}>{value}</Text>
16
- </View>
17
- )
18
- }
19
-
20
14
  /**
21
15
  * Compact current-month forecast metrics, using the shared Panel header.
22
16
  */
23
17
  export function CurrentMonthForecastPanel ({ dashboardId, pinnedWidgetId }) {
24
18
  const months = useForecast()
25
- const { language, t } = useLocale()
26
- const money = (value) => new Intl.NumberFormat(language === 'sv' ? 'sv-SE' : 'en-SE', {
27
- style: 'currency',
28
- currency: 'SEK',
29
- }).format(value)
30
- const hours = (value) => new Intl.NumberFormat(language === 'sv' ? 'sv-SE' : 'en-GB', {
31
- style: 'unit',
32
- unit: 'hour',
33
- }).format(value)
19
+ const { totals: spendByMonth } = useSpendByMonth()
20
+ const { t } = useLocale()
34
21
 
35
22
  const current = (Array.isArray(months) ? months : []).find((m) => m.isCurrentMonth)
36
23
  ?? (Array.isArray(months) ? months[0] : null)
@@ -46,7 +33,7 @@ export function CurrentMonthForecastPanel ({ dashboardId, pinnedWidgetId }) {
46
33
  return (
47
34
  <Panel
48
35
  title={current ? (
49
- <Text variant="small" as="h2" style={{ fontWeight: 'bold' }}>
36
+ <Text variant="small" as="h2" weight="bold">
50
37
  {t('consultancy.forecasts.monthForecast', { month: current.month })}
51
38
  </Text>
52
39
  ) : 'consultancy.widgets.forecastCurrentMonth.title'}
@@ -60,11 +47,13 @@ export function CurrentMonthForecastPanel ({ dashboardId, pinnedWidgetId }) {
60
47
  </View>
61
48
  ) : (
62
49
  <>
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)} />
50
+ <View inset="m">
51
+ <ForecastFigures
52
+ income={current.projectedIncome}
53
+ salary={current.monthlyCostOfEmployees}
54
+ spend={spendForMonth(spendByMonth, current)}
55
+ hours={current.hoursWorked}
56
+ />
68
57
  </View>
69
58
  <MonthDayGrid month={current} />
70
59
  </>
@@ -84,5 +73,5 @@ export const metadata = {
84
73
 
85
74
  /** Slot widget — current-month forecast panel for dashboards. */
86
75
  export default function CurrentMonthForecastWidget (props) {
87
- return <DataLoader content={<CurrentMonthForecastPanel {...props} />} />
76
+ return <DataLoader emptyGuide={false} content={<CurrentMonthForecastPanel {...props} />} />
88
77
  }
@@ -1,5 +1,5 @@
1
1
  import createCompanyFlow from './create-company.flow.js'
2
- import { location } from '@ossy/consultancy'
2
+ import { location as organisationLocation } from '@ossy/organisation'
3
3
  import { DeleteResource } from '@ossy/resources'
4
4
 
5
5
  export const metadata = {
@@ -10,8 +10,8 @@ export const metadata = {
10
10
  }
11
11
 
12
12
  /**
13
- * After creating company-basic-info, open it in storage and delete it.
14
- * Consultancy home should return to the empty state.
13
+ * After creating organisation, open it in storage and delete it.
14
+ * Consultancy overview should return to the empty state.
15
15
  */
16
16
  export default {
17
17
  title: 'Delete company',
@@ -19,7 +19,7 @@ export default {
19
19
  'Signed-in user creates a company, deletes it from storage, and sees consultancy empty again',
20
20
  steps: [
21
21
  ...createCompanyFlow.steps,
22
- { page: '@storage/home', search: { location } },
22
+ { page: '@storage/home', search: { location: organisationLocation } },
23
23
  { result: { selector: '[data-resource-name="e2e-company"]', timeout: 20000 } },
24
24
  { click: { selector: '[data-resource-name="e2e-company"]' } },
25
25
  { result: { action: DeleteResource, timeout: 15000 } },
@@ -31,7 +31,7 @@ export default {
31
31
  timeout: 20000,
32
32
  },
33
33
  },
34
- { page: '@consultancy/home' },
34
+ { page: '@consultancy/overview' },
35
35
  { result: { selector: '[data-consultancy-status="empty"]', timeout: 15000 } },
36
36
  ],
37
37
  }
@@ -1,6 +1,5 @@
1
1
  {
2
- "consultancy/home.documentTitle": "Overview",
3
- "consultancy/org.documentTitle": "Org Details",
2
+ "consultancy/overview.documentTitle": "Overview",
4
3
  "consultancy/margins.documentTitle": "Margins",
5
4
  "consultancy/employees.documentTitle": "Employees",
6
5
  "consultancy/vacations.documentTitle": "Vacations",
@@ -10,12 +9,14 @@
10
9
  "consultancy/resumes.documentTitle": "Resumes",
11
10
  "consultancy/proposals.documentTitle": "Proposals",
12
11
  "consultancy/reports.documentTitle": "Reports",
13
- "consultancy.home.title": "Overview",
14
- "consultancy.home.description": "Fiscal-year KPIs, year totals, and monthly capacity from contracts, employees, and vacations",
15
- "consultancy.org.title": "Org Details",
16
- "consultancy.org.description": "Company and fiscal-year details",
12
+ "consultancy/spend.documentTitle": "Spend",
13
+ "consultancy.overview.title": "Overview",
14
+ "consultancy.overview.description": "Fiscal-year KPIs, year totals, and monthly capacity from contracts, employees, and vacations",
15
+ "consultancy.spend.title": "Spend",
16
+ "consultancy.spend.description": "Invoices and receipts for this fiscal year",
17
17
  "consultancy.nav.title": "Consultancy",
18
18
  "consultancy.nav.overview": "Overview",
19
+ "consultancy.nav.spend": "Spend",
19
20
  "consultancy.nav.forecasts": "Forecasts",
20
21
  "consultancy.nav.employees": "Employees",
21
22
  "consultancy.nav.vacations": "Vacations",
@@ -29,6 +30,8 @@
29
30
  "consultancy.forecasts.title": "Overview",
30
31
  "consultancy.forecasts.description": "Fiscal-year KPIs, year totals, and monthly capacity from contracts, employees, and vacations",
31
32
  "consultancy.forecasts.income": "Income",
33
+ "consultancy.forecasts.forecast": "Forecast",
34
+ "consultancy.forecasts.actual": "Actual",
32
35
  "consultancy.forecasts.forecastIncome": "Forecast income",
33
36
  "consultancy.forecasts.actualIncome": "Actual income",
34
37
  "consultancy.forecasts.forecastRevenue": "Forecast result",
@@ -36,7 +39,10 @@
36
39
  "consultancy.forecasts.salaryCost": "Salary cost",
37
40
  "consultancy.forecasts.revenue": "Revenue",
38
41
  "consultancy.forecasts.hoursWorked": "Hours worked",
42
+ "consultancy.forecasts.spend": "Spend",
43
+ "consultancy.forecasts.costs": "Costs",
39
44
  "consultancy.forecasts.utilization": "Utilization",
45
+ "consultancy.forecasts.hours": "Hours",
40
46
  "consultancy.forecasts.forecastHours": "Forecast hours",
41
47
  "consultancy.forecasts.actualHours": "Actual hours",
42
48
  "consultancy.forecasts.unitMoney": "SEK",
@@ -62,9 +68,6 @@
62
68
  "consultancy.margins.leakage.description": "Estimate annual revenue lost when the team spends recurring hours on non-billable admin.",
63
69
  "consultancy.margins.leakage.hours": "Leaked hours / year",
64
70
  "consultancy.margins.leakage.revenue": "Leaked revenue / year",
65
- "consultancy.overview.fiscalYears": "Fiscal years",
66
- "consultancy.overview.company": "Company",
67
- "consultancy.overview.noFiscalYears": "No fiscal years yet.",
68
71
  "consultancy.employees.title": "Employees",
69
72
  "consultancy.employees.description": "People on the consultancy",
70
73
  "consultancy.employees.empty": "No employees yet.",
@@ -79,10 +82,14 @@
79
82
  "consultancy.requests.empty": "No requests yet.",
80
83
  "consultancy.matches.title": "Matching resumes",
81
84
  "consultancy.matches.loading": "Matching resumes…",
82
- "consultancy.matches.empty": "No resumes to match.",
85
+ "consultancy.matches.empty": "No matching resumes yet.",
83
86
  "consultancy.matches.error": "Could not match resumes.",
84
87
  "consultancy.matches.embeddingsUnavailable": "Showing tag overlap. Similarity is unavailable.",
85
88
  "consultancy.matches.pending": "Matches are prepared when a request or resume changes.",
89
+ "consultancy.matches.requestsTitle": "Matching requests",
90
+ "consultancy.matches.requestsLoading": "Matching requests…",
91
+ "consultancy.matches.requestsEmpty": "No matching requests yet.",
92
+ "consultancy.resumes.openEditor": "Open resume editor",
86
93
  "@ossy/consultancy/actions/refresh-matches.label": "Refresh matches",
87
94
  "@ossy/consultancy/actions/refresh-matches.description": "Embed changed requests and resumes, then save their matches",
88
95
  "@ossy/consultancy/actions/match-resumes.label": "Match resumes",
@@ -119,27 +126,6 @@
119
126
  "@ossy/consultancy/schema/calculator.availableHours.label": "Available hours this month",
120
127
  "@ossy/consultancy/schema/calculator.teamSize.label": "Team size",
121
128
  "@ossy/consultancy/schema/calculator.adminHoursPerWeek.label": "Admin hours per person / week",
122
- "@ossy/consultancy/schema/company-basic-info.name.label": "Company name",
123
- "@ossy/consultancy/schema/company-basic-info.name.description": "The registered legal name of the company.",
124
- "@ossy/consultancy/schema/company-basic-info.registrationDate.label": "Registration date",
125
- "@ossy/consultancy/schema/company-basic-info.registrationDate.description": "Date the company was registered. Used to calculate fiscal years.",
126
- "@ossy/consultancy/schema/company-basic-info.vatNumber.label": "VAT number",
127
- "@ossy/consultancy/schema/company-basic-info.vatNumber.description": "VAT / Moms registration number, e.g. SE556123456701.",
128
- "@ossy/consultancy/schema/company-basic-info.vatRegistredFrom.label": "VAT registered from",
129
- "@ossy/consultancy/schema/company-basic-info.vatRegistredFrom.description": "Date VAT registration started.",
130
- "@ossy/consultancy/schema/company-basic-info.vatPaymentResponsibilityFrom.label": "VAT reporting from",
131
- "@ossy/consultancy/schema/company-basic-info.vatPaymentResponsibilityFrom.description": "Date the company became liable to file VAT returns.",
132
- "@ossy/consultancy/schema/company-basic-info.vatPaymentPeriod.label": "VAT reporting period",
133
- "@ossy/consultancy/schema/company-basic-info.vatPaymentPeriod.description": "How often VAT returns are filed.",
134
- "@ossy/consultancy/schema/company-basic-info.vatPaymentPeriod.option.month": "Monthly",
135
- "@ossy/consultancy/schema/company-basic-info.vatPaymentPeriod.option.quarter": "Quarterly",
136
- "@ossy/consultancy/schema/company-basic-info.vatPaymentPeriod.option.year": "Yearly",
137
- "@ossy/consultancy/schema/company-basic-info.financialYearStart.label": "Financial year start month",
138
- "@ossy/consultancy/schema/company-basic-info.financialYearStart.description": "Month the financial year starts.",
139
- "@ossy/consultancy/schema/company-basic-info.financialYearEnd.label": "Financial year end month",
140
- "@ossy/consultancy/schema/company-basic-info.financialYearEnd.description": "Month the financial year ends.",
141
- "@ossy/consultancy/schema/company-basic-info.holidayLocale.label": "Holiday calendar",
142
- "@ossy/consultancy/schema/company-basic-info.holidayLocale.description": "Country used for public holidays and red days in forecasts and timesheets.",
143
129
  "@ossy/consultancy/schema/employee.name.label": "Name",
144
130
  "@ossy/consultancy/schema/employee.name.description": "The employee’s full name.",
145
131
  "@ossy/consultancy/schema/employee.email.label": "Email",
@@ -240,7 +226,6 @@
240
226
  "@ossy/consultancy/schema/proposal.timeline.description": "When the work would start and finish.",
241
227
  "@ossy/consultancy/schema/proposal.body.label": "Body",
242
228
  "@ossy/consultancy/schema/proposal.body.description": "Full proposal text.",
243
- "consultancy.nav.orgDetails": "Org Details",
244
229
  "consultancy.forecasts.yearChart": "KPI trend",
245
230
  "consultancy.forecasts.monthForecast": "{month} forecast",
246
231
  "consultancy.forecasts.yearSummary": "Fiscal year forecast",
@@ -1,6 +1,7 @@
1
- import { forwardedOriginal } from '@ossy/email/forwarded-original'
1
+ import { inboundSourceText } from '@ossy/email/inbound-source-text'
2
2
  import { ConsultancySchema } from './schema-ids.js'
3
3
  import { location } from './locations.js'
4
+ import requestSchema from './request.schema.js'
4
5
 
5
6
  const GetResource = { id: '@ossy/resources/actions/get' }
6
7
  const ListResources = { id: '@ossy/resources/actions/list' }
@@ -8,6 +9,19 @@ const CreateResource = { id: '@ossy/resources/actions/create' }
8
9
  const ExtractStructuredData = { id: '@ossy/media-tasks/actions/extract-structured-data' }
9
10
  const INBOUND_MESSAGE = '@ossy/email/schema/inbound-message'
10
11
 
12
+ /** Prompt schema. The stored request schema has no tags field; tags are resource metadata. */
13
+ export const requestExtractionSchema = {
14
+ ...requestSchema,
15
+ fields: [
16
+ ...requestSchema.fields,
17
+ {
18
+ name: 'tags',
19
+ type: 'tags',
20
+ description: 'JSON array of skills or technologies named in the request. One string per item. Omit when the message names none.',
21
+ },
22
+ ],
23
+ }
24
+
11
25
  export const metadata = {
12
26
  id: '@ossy/consultancy/tasks/extract-request',
13
27
  triggers: [
@@ -44,16 +58,7 @@ function workspaceIdFrom ({ event, payload, req }) {
44
58
  * @param {object | null | undefined} resource
45
59
  */
46
60
  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()
61
+ return inboundSourceText(resource)
57
62
  }
58
63
 
59
64
  function asResourceList (result) {
@@ -89,16 +94,17 @@ export async function run ({ event, payload, req, sdk }) {
89
94
  }
90
95
 
91
96
  const extracted = await sdk.invoke(ExtractStructuredData, {
92
- schemaId: ConsultancySchema.request,
97
+ schema: requestExtractionSchema,
93
98
  text,
94
99
  workspaceId,
95
100
  })
96
101
  const data = extracted?.data
97
102
  if (!data || typeof data !== 'object') fail('extraction is required', 422)
98
103
 
104
+ const { tags, ...fields } = data
99
105
  const receivedAt = typeof resource.content?.receivedAt === 'string' ? resource.content.receivedAt.trim() : ''
100
106
  const content = {
101
- ...data,
107
+ ...fields,
102
108
  ...(messageId ? { messageId } : {}),
103
109
  ...(receivedAt ? { receivedAt } : {}),
104
110
  }
@@ -111,6 +117,7 @@ export async function run ({ event, payload, req, sdk }) {
111
117
  location,
112
118
  name: title,
113
119
  content,
120
+ ...(tags !== undefined ? { tags } : {}),
114
121
  })
115
122
 
116
123
  return { id: created?.id ?? null, workspaceId, content }
@@ -1,7 +1,7 @@
1
1
  import { Schema, validateContent } from '@ossy/schema'
2
2
  import { ConsultancySchema } from './schema-ids.js'
3
3
  import requestSchema from './request.schema.js'
4
- import { metadata, requestSourceText, run } from './extract-request.task.js'
4
+ import { metadata, requestExtractionSchema, requestSourceText, run } from './extract-request.task.js'
5
5
 
6
6
  const GetResource = { id: '@ossy/resources/actions/get' }
7
7
  const ListResources = { id: '@ossy/resources/actions/list' }
@@ -63,22 +63,26 @@ describe('extract-request task', () => {
63
63
  })
64
64
 
65
65
  const extractCall = calls.find((call) => call.id === ExtractStructuredData.id)
66
- expect(extractCall.payload.schemaId).toBe(ConsultancySchema.request)
66
+ expect(extractCall.payload.schema).toBe(requestExtractionSchema)
67
+ expect(extractCall.payload.schema.fields.some((field) => field.name === 'tags')).toBe(true)
67
68
  expect(extractCall.payload.text).toBe(requestSourceText(inbound))
68
69
  expect(extractCall.payload.text).toContain('Senior React, 6 manader')
69
70
  expect(extractCall.payload.text).toContain('Stockholm')
70
71
 
72
+ const { tags, ...fields } = extracted
71
73
  const created = calls.find((call) => call.id === CreateResource.id).payload
72
74
  expect(created).toMatchObject({
73
75
  workspaceId: 'ws-1',
74
76
  type: ConsultancySchema.request,
75
77
  name: 'Senior React, 6 manader',
78
+ tags,
76
79
  })
77
80
  expect(created.content).toMatchObject({
78
- ...extracted,
81
+ ...fields,
79
82
  messageId: 'assignment-1@client.se',
80
83
  receivedAt: '2023-04-15T10:00:00.000Z',
81
84
  })
85
+ expect(created.content.tags).toBeUndefined()
82
86
 
83
87
  const engine = Schema.of({ schemas: [requestSchema] })
84
88
  expect(validateContent(engine, requestSchema, created.content).ok).toBe(true)
@@ -0,0 +1,93 @@
1
+ import { location } from './locations.js'
2
+ import { ConsultancySchema } from './schema-ids.js'
3
+ import { acceptsRequestCategory, REQUEST_CATEGORY } from './intake-categories.js'
4
+
5
+ const GetResource = { id: '@ossy/resources/actions/get' }
6
+ const UpdateContent = { id: '@ossy/resources/actions/update-content' }
7
+ const ExtractRequest = { id: '@ossy/consultancy/actions/extract-request' }
8
+ const INBOUND_MESSAGE = '@ossy/email/schema/inbound-message'
9
+
10
+ export const metadata = {
11
+ id: '@ossy/consultancy/tasks/file-inbound-request',
12
+ triggers: [
13
+ {
14
+ type: INBOUND_MESSAGE,
15
+ event: 'Updated',
16
+ match: { 'content.intakeCategory': REQUEST_CATEGORY },
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, resource }) {
34
+ return resource?.belongsTo
35
+ ?? event?.payload?.belongsTo
36
+ ?? event?.belongsTo
37
+ ?? payload?.workspaceId
38
+ ?? req?.workspaceId
39
+ ?? null
40
+ }
41
+
42
+ /**
43
+ * When email labels an inbound message as a confident consultancy request,
44
+ * extract and link the request. Email owns categorization; this task only
45
+ * recognizes the request route.
46
+ */
47
+ export async function run ({ event, payload, req, sdk }) {
48
+ if (!sdk?.invoke) fail('sdk is required', 500)
49
+
50
+ const resourceId = event?.resourceId || payload?.resourceId
51
+ if (!resourceId) fail('resourceId is required', 400)
52
+
53
+ const resource = await sdk.invoke(GetResource, { resourceId })
54
+ if (resource?.type !== INBOUND_MESSAGE) fail('inbound message is required', 400)
55
+ if (resource.content?.requestId) {
56
+ return {
57
+ skipped: false,
58
+ requestId: resource.content.requestId,
59
+ category: resource.content.intakeCategory ?? null,
60
+ }
61
+ }
62
+
63
+ const category = typeof resource.content?.intakeCategory === 'string'
64
+ ? resource.content.intakeCategory
65
+ : null
66
+ const confidence = typeof resource.content?.intakeConfidence === 'number'
67
+ ? resource.content.intakeConfidence
68
+ : null
69
+
70
+ if (!acceptsRequestCategory({ category, confidence })) {
71
+ return { skipped: true, reason: 'category', category, confidence }
72
+ }
73
+
74
+ const workspaceId = workspaceIdFrom({ event, payload, req, resource })
75
+ if (!workspaceId) fail('workspaceId is required', 400)
76
+
77
+ const request = await sdk.invoke(ExtractRequest, { resourceId, workspaceId })
78
+ const requestId = request?.id ?? null
79
+ if (requestId) {
80
+ const content = { ...resource.content, requestId }
81
+ await sdk.invoke(UpdateContent, {
82
+ resourceId: resource.id,
83
+ workspaceId,
84
+ content,
85
+ })
86
+ }
87
+ return {
88
+ skipped: false,
89
+ category,
90
+ confidence,
91
+ requestId,
92
+ }
93
+ }
@@ -0,0 +1,118 @@
1
+ import { metadata, run } from './file-inbound-request.task.js'
2
+ import { REQUEST_CATEGORY } from './intake-categories.js'
3
+
4
+ const GetResource = { id: '@ossy/resources/actions/get' }
5
+ const UpdateContent = { id: '@ossy/resources/actions/update-content' }
6
+ const ExtractRequest = { id: '@ossy/consultancy/actions/extract-request' }
7
+
8
+ const inbound = {
9
+ id: 'msg-1',
10
+ type: '@ossy/email/schema/inbound-message',
11
+ belongsTo: 'ws-1',
12
+ content: {
13
+ from: 'Anna Berg <anna@client.se>',
14
+ subject: 'Senior React, 6 manader',
15
+ text: 'Vi soker en senior React-utvecklare i Stockholm.',
16
+ messageId: 'assignment-1@client.se',
17
+ intakeCategory: REQUEST_CATEGORY,
18
+ intakeConfidence: 1,
19
+ },
20
+ }
21
+
22
+ function sdkFor (source = inbound) {
23
+ let current = { ...source, content: { ...source.content } }
24
+ const calls = []
25
+ const sdk = {
26
+ async invoke (action, payload) {
27
+ calls.push({ id: action.id, payload })
28
+ if (action.id === GetResource.id) return current
29
+ if (action.id === UpdateContent.id) {
30
+ current = { ...current, content: payload.content }
31
+ return current
32
+ }
33
+ if (action.id === ExtractRequest.id) return { id: 'request-1' }
34
+ throw new Error(`unexpected ${action.id}`)
35
+ },
36
+ }
37
+ return { calls, sdk, getCurrent: () => current }
38
+ }
39
+
40
+ describe('file-inbound-request task', () => {
41
+ it('listens for consultancy-request labels on inbound updates', () => {
42
+ expect(metadata.id).toBe('@ossy/consultancy/tasks/file-inbound-request')
43
+ expect(metadata.triggers).toEqual([
44
+ {
45
+ type: '@ossy/email/schema/inbound-message',
46
+ event: 'Updated',
47
+ match: { 'content.intakeCategory': REQUEST_CATEGORY },
48
+ },
49
+ ])
50
+ })
51
+
52
+ it('extracts a request when the category is a confident consultancy request', async () => {
53
+ const { calls, sdk } = sdkFor()
54
+ const result = await run({
55
+ event: { resourceId: inbound.id },
56
+ sdk,
57
+ })
58
+
59
+ expect(calls.map((call) => call.id)).toEqual([
60
+ GetResource.id,
61
+ ExtractRequest.id,
62
+ UpdateContent.id,
63
+ ])
64
+ expect(calls.find((call) => call.id === ExtractRequest.id).payload).toEqual({
65
+ resourceId: inbound.id,
66
+ workspaceId: 'ws-1',
67
+ })
68
+ expect(calls.find((call) => call.id === UpdateContent.id).payload.content.requestId).toBe('request-1')
69
+ expect(result).toEqual({
70
+ skipped: false,
71
+ category: REQUEST_CATEGORY,
72
+ confidence: 1,
73
+ requestId: 'request-1',
74
+ })
75
+ })
76
+
77
+ it('leaves a low-confidence consultancy request in the inbox', async () => {
78
+ const { calls, sdk } = sdkFor({
79
+ ...inbound,
80
+ content: { ...inbound.content, intakeConfidence: 0.4 },
81
+ })
82
+ const result = await run({
83
+ event: { resourceId: inbound.id },
84
+ sdk,
85
+ })
86
+
87
+ expect(calls.map((call) => call.id)).not.toContain(ExtractRequest.id)
88
+ expect(result).toMatchObject({ skipped: true, reason: 'category', confidence: 0.4 })
89
+ })
90
+
91
+ it('skips when a request was already filed', async () => {
92
+ const { calls, sdk } = sdkFor({
93
+ ...inbound,
94
+ content: { ...inbound.content, requestId: 'request-1' },
95
+ })
96
+ const result = await run({
97
+ event: { resourceId: inbound.id },
98
+ sdk,
99
+ })
100
+
101
+ expect(calls.map((call) => call.id)).toEqual([GetResource.id])
102
+ expect(result).toEqual({
103
+ skipped: false,
104
+ requestId: 'request-1',
105
+ category: REQUEST_CATEGORY,
106
+ })
107
+ })
108
+
109
+ it('resolves workspace from the resource when the update event has no belongsTo', async () => {
110
+ const { calls, sdk } = sdkFor()
111
+ await run({
112
+ event: { resourceId: inbound.id, payload: { content: inbound.content } },
113
+ sdk,
114
+ })
115
+
116
+ expect(calls.find((call) => call.id === ExtractRequest.id).payload.workspaceId).toBe('ws-1')
117
+ })
118
+ })
@@ -0,0 +1,42 @@
1
+ import React from 'react'
2
+ import { Text, View, useLocale } from '@ossy/design-system'
3
+ import { monthResult } from './spend-for-month.js'
4
+
5
+ function MetricRow ({ label, value }) {
6
+ return (
7
+ <View layout="row" gap="s" style={{ justifyContent: 'space-between' }}>
8
+ <Text variant="m" style={{ marginBottom: 0 }} text={label} />
9
+ <Text variant="m" style={{ marginBottom: 0 }}>{value}</Text>
10
+ </View>
11
+ )
12
+ }
13
+
14
+ /**
15
+ * Overview rows: income, salary, spend, result, hours.
16
+ * Result is income minus salary minus spend. Suppliers stay on the spending page.
17
+ */
18
+ export function ForecastFigures ({ income = 0, salary = 0, spend = 0, hours = 0 }) {
19
+ const { language } = useLocale()
20
+ const money = (value) => {
21
+ const amount = Number(value)
22
+ return new Intl.NumberFormat(language === 'sv' ? 'sv-SE' : 'en-SE', {
23
+ style: 'currency',
24
+ currency: 'SEK',
25
+ }).format(Number.isFinite(amount) ? amount : 0)
26
+ }
27
+ const hoursLabel = (value) => new Intl.NumberFormat(language === 'sv' ? 'sv-SE' : 'en-GB', {
28
+ style: 'unit',
29
+ unit: 'hour',
30
+ }).format(value || 0)
31
+ const result = monthResult({ income, salary, spend })
32
+
33
+ return (
34
+ <View gap="s">
35
+ <MetricRow label="consultancy.forecasts.income" value={money(income)} />
36
+ <MetricRow label="consultancy.forecasts.salaryCost" value={money(salary)} />
37
+ <MetricRow label="consultancy.forecasts.spend" value={money(spend)} />
38
+ <MetricRow label="consultancy.forecasts.revenue" value={money(result)} />
39
+ <MetricRow label="consultancy.forecasts.hoursWorked" value={hoursLabel(hours)} />
40
+ </View>
41
+ )
42
+ }