@ossy/consultancy 3.22.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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ossy/consultancy",
3
3
  "description": "Consultancy feature package — schemas, forecasts UI, and assignment margins",
4
- "version": "3.22.0",
4
+ "version": "3.23.0",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
7
7
  "module": "./src/index.js",
@@ -25,6 +25,7 @@
25
25
  "README.md"
26
26
  ],
27
27
  "dependencies": {
28
+ "@ossy/email": "^3.23.0",
28
29
  "@ossy/event-store": "^3.20.1",
29
30
  "@ossy/schema": "^3.20.1"
30
31
  },
@@ -40,5 +41,5 @@
40
41
  "devDependencies": {
41
42
  "jest": "^30.2.0"
42
43
  },
43
- "gitHead": "29de300fd5e2c36f9d6d00f09eb9f1508997a904"
44
+ "gitHead": "fba601366c69184bbd82d990429d1a43152645c9"
44
45
  }
package/src/Forecast.jsx CHANGED
@@ -1,33 +1,9 @@
1
1
  import React from 'react'
2
2
  import { DashboardLayout, Panel, View, Text, useLocale } from '@ossy/design-system'
3
- import { CalendarDaySurfaceStyles, useForecast } from '@ossy/calendar'
3
+ import { useForecast } from '@ossy/calendar'
4
4
  import { CurrentMonthForecastPanel } from './current-month.component.jsx'
5
5
  import { KpiTrendPanel, UtilizationPanel, YearTotalsPanel } from './forecast-panels.jsx'
6
-
7
- const calendarGrid = {
8
- display: 'grid',
9
- width: '100%',
10
- minWidth: 0,
11
- gridTemplateColumns: 'repeat(7, minmax(0, 1fr))',
12
- gap: '4px',
13
- justifyItems: 'center',
14
- alignItems: 'center',
15
- }
16
-
17
- const calendarDayLayout = {
18
- boxSizing: 'border-box',
19
- display: 'flex',
20
- justifyContent: 'center',
21
- alignItems: 'center',
22
- width: '100%',
23
- maxWidth: 32,
24
- aspectRatio: '1',
25
- minWidth: 0,
26
- borderRadius: '50%',
27
- padding: 0,
28
- fontSize: '.6rem',
29
- margin: 0,
30
- }
6
+ import { MonthDayGrid } from './MonthDayGrid.jsx'
31
7
 
32
8
  export const Forecast = () => {
33
9
  const months = useForecast()
@@ -37,7 +13,6 @@ export const Forecast = () => {
37
13
 
38
14
  return (
39
15
  <>
40
- <CalendarDaySurfaceStyles />
41
16
  <DashboardLayout gap="xs">
42
17
  <DashboardLayout.Widget span={4}>
43
18
  <CurrentMonthForecastPanel />
@@ -52,9 +27,6 @@ export const Forecast = () => {
52
27
  <KpiTrendPanel />
53
28
  </DashboardLayout.Widget>
54
29
  {months.map(month => {
55
- const startPad = month.days[0].isoWeekday - 1
56
- const totalCells = startPad + month.days.length
57
- const endPad = (7 - (totalCells % 7)) % 7
58
30
  const monthKey = `${month.year}-${month.month}`
59
31
 
60
32
  return (
@@ -100,29 +72,7 @@ export const Forecast = () => {
100
72
 
101
73
  </View>
102
74
 
103
- <div style={{ ...calendarGrid, padding: '0 var(--space-m) var(--space-m)' }}>
104
-
105
- {Array.from({ length: startPad }, (_, i) => (
106
- <div key={`${monthKey}-pad-s-${i}`} />
107
- ))}
108
-
109
- {month.days.map(day => (
110
- <Text
111
- key={`${monthKey}-${day.monthDay}`}
112
- variant="small"
113
- data-ossy-calendar-day
114
- data-day-off={!day.isWorkday}
115
- style={calendarDayLayout}
116
- >
117
- {day.monthDay}
118
- </Text>
119
- ))}
120
-
121
- {Array.from({ length: endPad }, (_, i) => (
122
- <div key={`${monthKey}-pad-e-${i}`} />
123
- ))}
124
-
125
- </div>
75
+ <MonthDayGrid month={month} />
126
76
  </Panel>
127
77
  </DashboardLayout.Widget>
128
78
  )
@@ -0,0 +1,68 @@
1
+ import React from 'react'
2
+ import { Text } from '@ossy/design-system'
3
+ import { CalendarDaySurfaceStyles } from '@ossy/calendar'
4
+
5
+ const calendarGrid = {
6
+ display: 'grid',
7
+ width: '100%',
8
+ minWidth: 0,
9
+ gridTemplateColumns: 'repeat(7, minmax(0, 1fr))',
10
+ gap: '4px',
11
+ justifyItems: 'center',
12
+ alignItems: 'center',
13
+ }
14
+
15
+ const calendarDayLayout = {
16
+ boxSizing: 'border-box',
17
+ display: 'flex',
18
+ justifyContent: 'center',
19
+ alignItems: 'center',
20
+ width: '100%',
21
+ maxWidth: 32,
22
+ aspectRatio: '1',
23
+ minWidth: 0,
24
+ borderRadius: '50%',
25
+ padding: 0,
26
+ fontSize: '.6rem',
27
+ margin: 0,
28
+ }
29
+
30
+ /**
31
+ * Day numbers for one forecast month, Monday first.
32
+ * Days off use the shared calendar day surface.
33
+ *
34
+ * @param {{ month?: { year?: number|string, month?: string, days?: Array<{ monthDay?: number|string, isoWeekday?: number, isWorkday?: boolean }> } }} props
35
+ */
36
+ export function MonthDayGrid ({ month }) {
37
+ const days = Array.isArray(month?.days) ? month.days : []
38
+ if (!days.length) return null
39
+
40
+ const startPad = Math.max(0, (Number(days[0].isoWeekday) || 1) - 1)
41
+ const endPad = (7 - ((startPad + days.length) % 7)) % 7
42
+ const monthKey = `${month.year}-${month.month}`
43
+
44
+ return (
45
+ <>
46
+ <CalendarDaySurfaceStyles />
47
+ <div style={{ ...calendarGrid, padding: '0 var(--space-m) var(--space-m)' }}>
48
+ {Array.from({ length: startPad }, (_, index) => (
49
+ <div key={`${monthKey}-pad-s-${index}`} />
50
+ ))}
51
+ {days.map((day) => (
52
+ <Text
53
+ key={`${monthKey}-${day.monthDay}`}
54
+ variant="small"
55
+ data-ossy-calendar-day
56
+ data-day-off={!day.isWorkday}
57
+ style={calendarDayLayout}
58
+ >
59
+ {day.monthDay}
60
+ </Text>
61
+ ))}
62
+ {Array.from({ length: endPad }, (_, index) => (
63
+ <div key={`${monthKey}-pad-e-${index}`} />
64
+ ))}
65
+ </div>
66
+ </>
67
+ )
68
+ }
@@ -2,6 +2,7 @@ import React from 'react'
2
2
  import { Panel, Text, View, useLocale } from '@ossy/design-system'
3
3
  import { DataLoader, useForecast } from '@ossy/calendar'
4
4
  import { ForecastWidgetMenu } from './forecast-widget-menu.jsx'
5
+ import { MonthDayGrid } from './MonthDayGrid.jsx'
5
6
 
6
7
  export const CURRENT_MONTH_WIDGET_ID = '@ossy/consultancy/view/current-month'
7
8
 
@@ -58,12 +59,15 @@ export function CurrentMonthForecastPanel ({ dashboardId, pinnedWidgetId }) {
58
59
  <Text color="secondary" text="consultancy.forecasts.widget.empty" />
59
60
  </View>
60
61
  ) : (
61
- <View gap="s" inset="m">
62
- <MetricRow label="consultancy.forecasts.income" value={money(current.projectedIncome)} />
63
- <MetricRow label="consultancy.forecasts.salaryCost" value={money(current.monthlyCostOfEmployees)} />
64
- <MetricRow label="consultancy.forecasts.revenue" value={money(current.revenue)} />
65
- <MetricRow label="consultancy.forecasts.hoursWorked" value={hours(current.hoursWorked)} />
66
- </View>
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
+ </>
67
71
  )}
68
72
  </Panel>
69
73
  )
@@ -165,6 +165,32 @@
165
165
  "@ossy/consultancy/schema/vacation.start.description": "First day of vacation (inclusive). These days are not billed.",
166
166
  "@ossy/consultancy/schema/vacation.end.label": "Last day off",
167
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.",
168
194
  "@ossy/consultancy/schema/opportunity.title.label": "Title",
169
195
  "@ossy/consultancy/schema/opportunity.title.description": "Short name for this lead or opportunity.",
170
196
  "@ossy/consultancy/schema/opportunity.source.label": "Source",
@@ -1,7 +1,9 @@
1
+ import { forwardedOriginal } from '@ossy/email/forwarded-original'
1
2
  import { ConsultancySchema } from './schema-ids.js'
2
3
  import { location } from './locations.js'
3
4
 
4
5
  const GetResource = { id: '@ossy/resources/actions/get' }
6
+ const ListResources = { id: '@ossy/resources/actions/list' }
5
7
  const CreateResource = { id: '@ossy/resources/actions/create' }
6
8
  const ExtractStructuredData = { id: '@ossy/media-tasks/actions/extract-structured-data' }
7
9
  const INBOUND_MESSAGE = '@ossy/email/schema/inbound-message'
@@ -43,14 +45,23 @@ function workspaceIdFrom ({ event, payload, req }) {
43
45
  */
44
46
  export function requestSourceText (resource) {
45
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()
46
52
  const lines = []
47
- if (content.subject) lines.push(`Subject: ${content.subject}`)
48
- if (content.from) lines.push(`From: ${content.from}`)
49
- const body = typeof content.text === 'string' ? content.text.trim() : ''
53
+ if (subject) lines.push(`Subject: ${subject}`)
54
+ if (from) lines.push(`From: ${from}`)
50
55
  if (body) lines.push('', body)
51
56
  return lines.join('\n').trim()
52
57
  }
53
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
+
54
65
  /**
55
66
  * Inbound assignment → extract-structured-data → a consultancy request resource.
56
67
  * Screening decides whether this runs. It does not listen to every inbound message.
@@ -70,6 +81,13 @@ export async function run ({ event, payload, req, sdk }) {
70
81
  const text = requestSourceText(resource)
71
82
  if (!text) fail('text is required', 400)
72
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
+
73
91
  const extracted = await sdk.invoke(ExtractStructuredData, {
74
92
  schemaId: ConsultancySchema.request,
75
93
  text,
@@ -78,7 +96,6 @@ export async function run ({ event, payload, req, sdk }) {
78
96
  const data = extracted?.data
79
97
  if (!data || typeof data !== 'object') fail('extraction is required', 422)
80
98
 
81
- const messageId = typeof resource.content?.messageId === 'string' ? resource.content.messageId : ''
82
99
  const receivedAt = typeof resource.content?.receivedAt === 'string' ? resource.content.receivedAt.trim() : ''
83
100
  const content = {
84
101
  ...data,
@@ -4,6 +4,7 @@ import requestSchema from './request.schema.js'
4
4
  import { metadata, requestSourceText, run } from './extract-request.task.js'
5
5
 
6
6
  const GetResource = { id: '@ossy/resources/actions/get' }
7
+ const ListResources = { id: '@ossy/resources/actions/list' }
7
8
  const CreateResource = { id: '@ossy/resources/actions/create' }
8
9
  const ExtractStructuredData = { id: '@ossy/media-tasks/actions/extract-structured-data' }
9
10
 
@@ -12,7 +13,7 @@ const inbound = {
12
13
  type: '@ossy/email/schema/inbound-message',
13
14
  content: {
14
15
  from: 'Anna Berg <anna@client.se>',
15
- to: 'requests+ws-1@inbound.ossy.se',
16
+ to: 'inbox+ws-1@inbound.ossy.se',
16
17
  subject: 'Senior React, 6 manader',
17
18
  text: 'Vi soker en senior React-utvecklare i Stockholm. Uppdraget ar 6 manader med start i januari. Anna Berg, anna@client.se.',
18
19
  messageId: 'assignment-1@client.se',
@@ -49,6 +50,7 @@ describe('extract-request task', () => {
49
50
  async invoke (action, payload) {
50
51
  calls.push({ id: action.id, payload })
51
52
  if (action.id === GetResource.id) return inbound
53
+ if (action.id === ListResources.id) return []
52
54
  if (action.id === ExtractStructuredData.id) return { data: extracted }
53
55
  if (action.id === CreateResource.id) return { id: 'request-1' }
54
56
  throw new Error(`unexpected ${action.id}`)
@@ -86,4 +88,44 @@ describe('extract-request task', () => {
86
88
  content: created.content,
87
89
  })
88
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
+ })
89
131
  })
@@ -0,0 +1,77 @@
1
+ import { run as screenInbound } from './screen-inbound.task.js'
2
+ import { acceptsRequestCategory } from './intake-categories.js'
3
+
4
+ const ListResources = { id: '@ossy/resources/actions/list' }
5
+ const INBOUND_MESSAGE = '@ossy/email/schema/inbound-message'
6
+ const INBOUND_LOCATION = '/@ossy/email/inbound/'
7
+ const MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000
8
+ const MAX_PER_PASS = 20
9
+
10
+ export const metadata = {
11
+ id: '@ossy/consultancy/tasks/resume-inbound-screening',
12
+ schedule: '*/5 * * * *',
13
+ }
14
+
15
+ function asResourceList (result) {
16
+ if (Array.isArray(result)) return result
17
+ if (Array.isArray(result?.items)) return result.items
18
+ return []
19
+ }
20
+
21
+ /**
22
+ * A message still needs screening when it has no request and no finished
23
+ * intake label. A confident request label with no request means extraction
24
+ * died and should be run again.
25
+ *
26
+ * @param {object | null | undefined} resource
27
+ * @param {number} [now]
28
+ */
29
+ export function needsInboundScreening (resource, now = Date.now()) {
30
+ if (resource?.type !== INBOUND_MESSAGE) return false
31
+ const content = resource.content && typeof resource.content === 'object' ? resource.content : {}
32
+ if (content.requestId) return false
33
+ const received = Date.parse(content.receivedAt || '')
34
+ if (!Number.isNaN(received) && now - received > MAX_AGE_MS) return false
35
+ if (!Object.hasOwn(content, 'intakeCategory')) return true
36
+ return acceptsRequestCategory({
37
+ category: content.intakeCategory,
38
+ confidence: content.intakeConfidence,
39
+ })
40
+ }
41
+
42
+ /**
43
+ * Finish inbound mail whose screening was interrupted. One pass per workspace.
44
+ */
45
+ export async function run ({ payload, req, sdk, log }) {
46
+ if (!sdk?.invoke) throw Object.assign(new Error('sdk is required'), { status: 500 })
47
+
48
+ const workspaceId = payload?.workspaceId || req?.workspaceId
49
+ if (!workspaceId) throw Object.assign(new Error('workspaceId is required'), { status: 400 })
50
+
51
+ const listed = await sdk.invoke(ListResources, {
52
+ location: INBOUND_LOCATION,
53
+ workspaceId,
54
+ })
55
+ const pending = asResourceList(listed)
56
+ .filter((resource) => needsInboundScreening(resource))
57
+ .slice(0, MAX_PER_PASS)
58
+
59
+ let screened = 0
60
+ let failed = 0
61
+ for (const message of pending) {
62
+ try {
63
+ await screenInbound({
64
+ event: { resourceId: message.id, payload: { belongsTo: workspaceId } },
65
+ payload: { resourceId: message.id, workspaceId },
66
+ req,
67
+ sdk,
68
+ })
69
+ screened += 1
70
+ } catch (error) {
71
+ failed += 1
72
+ log?.error('[consultancy/tasks/resume-inbound-screening] message failed', { resourceId: message.id }, error)
73
+ }
74
+ }
75
+
76
+ return { screened, failed }
77
+ }
@@ -0,0 +1,68 @@
1
+ import { metadata, needsInboundScreening, run } from './resume-inbound-screening.task.js'
2
+ import { REQUEST_CATEGORY } from './intake-categories.js'
3
+
4
+ const message = {
5
+ id: 'msg-1',
6
+ type: '@ossy/email/schema/inbound-message',
7
+ content: {
8
+ from: 'client@studio.se',
9
+ subject: 'SDK',
10
+ text: 'Vi behöver en specialist.',
11
+ receivedAt: '2026-10-17T17:56:46.000Z',
12
+ },
13
+ }
14
+
15
+ describe('resume-inbound-screening', () => {
16
+ it('runs every five minutes', () => {
17
+ expect(metadata.schedule).toBe('*/5 * * * *')
18
+ })
19
+
20
+ it('selects mail that never finished screening', () => {
21
+ const now = Date.parse('2026-10-17T19:00:00.000Z')
22
+ expect(needsInboundScreening(message, now)).toBe(true)
23
+ expect(needsInboundScreening({
24
+ ...message,
25
+ content: { ...message.content, intakeCategory: 'contact', intakeConfidence: 0.9 },
26
+ }, now)).toBe(false)
27
+ expect(needsInboundScreening({
28
+ ...message,
29
+ content: { ...message.content, intakeCategory: REQUEST_CATEGORY, intakeConfidence: 1 },
30
+ }, now)).toBe(true)
31
+ expect(needsInboundScreening({
32
+ ...message,
33
+ content: { ...message.content, requestId: 'request-1' },
34
+ }, now)).toBe(false)
35
+ expect(needsInboundScreening({
36
+ ...message,
37
+ content: { ...message.content, receivedAt: '2026-01-01T00:00:00.000Z' },
38
+ }, now)).toBe(false)
39
+ })
40
+
41
+ it('screens only the unfinished message', async () => {
42
+ const calls = []
43
+ const settled = {
44
+ ...message,
45
+ id: 'msg-settled',
46
+ content: { ...message.content, intakeCategory: 'contact', intakeConfidence: 1 },
47
+ }
48
+ const sdk = {
49
+ async invoke (action, payload) {
50
+ calls.push({ id: action.id, payload })
51
+ if (action.id === '@ossy/resources/actions/list') return [settled, message]
52
+ if (action.id === '@ossy/resources/actions/get') return message
53
+ if (action.id === '@ossy/media-tasks/actions/categorize') return { category: 'contact', confidence: 0.95 }
54
+ if (action.id === '@ossy/resources/actions/update-content') return { ...message, content: payload.content }
55
+ throw new Error(`unexpected ${action.id}`)
56
+ },
57
+ }
58
+
59
+ const result = await run({
60
+ payload: { workspaceId: 'ws-1' },
61
+ sdk,
62
+ })
63
+
64
+ expect(result).toEqual({ screened: 1, failed: 0 })
65
+ const gets = calls.filter((call) => call.id === '@ossy/resources/actions/get')
66
+ expect(gets.map((call) => call.payload.resourceId)).toEqual(['msg-1'])
67
+ })
68
+ })
@@ -1,3 +1,4 @@
1
+ import { forwardedOriginalFromMessage } from '@ossy/email/forwarded-original'
1
2
  import { location } from './locations.js'
2
3
  import { ConsultancySchema } from './schema-ids.js'
3
4
  import { requestSourceText } from './extract-request.task.js'
@@ -7,6 +8,7 @@ import {
7
8
  } from './intake-categories.js'
8
9
 
9
10
  const GetResource = { id: '@ossy/resources/actions/get' }
11
+ const UpdateContent = { id: '@ossy/resources/actions/update-content' }
10
12
  const Categorize = { id: '@ossy/media-tasks/actions/categorize' }
11
13
  const ExtractRequest = { id: '@ossy/consultancy/actions/extract-request' }
12
14
  const INBOUND_MESSAGE = '@ossy/email/schema/inbound-message'
@@ -41,9 +43,37 @@ function workspaceIdFrom ({ event, payload, req }) {
41
43
  ?? null
42
44
  }
43
45
 
46
+ async function saveContent (sdk, resource, workspaceId, patch) {
47
+ const content = { ...resource.content, ...patch }
48
+ const updated = await sdk.invoke(UpdateContent, {
49
+ resourceId: resource.id,
50
+ workspaceId,
51
+ content,
52
+ })
53
+ return updated?.content ? updated : { ...resource, content }
54
+ }
55
+
56
+ /**
57
+ * A forward stores the person who clicked forward as From. Replace that with
58
+ * the sender inside the forwarded block, and remember who forwarded it.
59
+ */
60
+ async function withOriginalSender (sdk, resource, workspaceId) {
61
+ const content = resource?.content && typeof resource.content === 'object' ? resource.content : {}
62
+ if (content.forwardedBy) return resource
63
+ const forward = forwardedOriginalFromMessage(content)
64
+ if (!forward?.from) return resource
65
+ return saveContent(sdk, resource, workspaceId, {
66
+ from: forward.from,
67
+ forwardedBy: content.from || '',
68
+ ...(forward.subject ? { subject: forward.subject } : {}),
69
+ ...(forward.receivedAt ? { receivedAt: forward.receivedAt } : {}),
70
+ })
71
+ }
72
+
44
73
  /**
45
74
  * New inbound mail is categorized first. A consultancy request is extracted.
46
- * Anything else stays in the inbox.
75
+ * The outcome is stored on the message so a later pass can finish a run that
76
+ * died before the request was saved. Anything else stays in the inbox.
47
77
  */
48
78
  export async function run ({ event, payload, req, sdk }) {
49
79
  if (!sdk?.invoke) fail('sdk is required', 500)
@@ -54,31 +84,50 @@ export async function run ({ event, payload, req, sdk }) {
54
84
  const workspaceId = workspaceIdFrom({ event, payload, req })
55
85
  if (!workspaceId) fail('workspaceId is required', 400)
56
86
 
57
- const resource = await sdk.invoke(GetResource, { resourceId })
87
+ let resource = await sdk.invoke(GetResource, { resourceId })
58
88
  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 }
89
+ if (resource.content?.requestId) {
90
+ return { skipped: false, requestId: resource.content.requestId, category: resource.content.intakeCategory ?? null }
63
91
  }
64
92
 
65
- const categorized = await sdk.invoke(Categorize, {
66
- workspaceId,
67
- text,
68
- categories: INTAKE_CATEGORIES,
69
- })
93
+ resource = await withOriginalSender(sdk, resource, workspaceId)
94
+
95
+ const alreadyScreened = Object.hasOwn(resource.content ?? {}, 'intakeCategory')
96
+ let category = typeof resource.content?.intakeCategory === 'string' ? resource.content.intakeCategory : null
97
+ let confidence = typeof resource.content?.intakeConfidence === 'number' ? resource.content.intakeConfidence : null
98
+
99
+ if (!alreadyScreened) {
100
+ const text = requestSourceText(resource)
101
+ if (!text) {
102
+ return { skipped: true, reason: 'empty', category: null, confidence: null }
103
+ }
104
+
105
+ const categorized = await sdk.invoke(Categorize, {
106
+ workspaceId,
107
+ text,
108
+ categories: INTAKE_CATEGORIES,
109
+ })
110
+ category = typeof categorized?.category === 'string' ? categorized.category : null
111
+ confidence = typeof categorized?.confidence === 'number' ? categorized.confidence : null
112
+ resource = await saveContent(sdk, resource, workspaceId, {
113
+ intakeCategory: category,
114
+ intakeConfidence: confidence,
115
+ })
116
+ }
70
117
 
71
- const category = typeof categorized?.category === 'string' ? categorized.category : null
72
- const confidence = typeof categorized?.confidence === 'number' ? categorized.confidence : null
73
118
  if (!acceptsRequestCategory({ category, confidence })) {
74
119
  return { skipped: true, reason: 'category', category, confidence }
75
120
  }
76
121
 
77
122
  const request = await sdk.invoke(ExtractRequest, { resourceId, workspaceId })
123
+ const requestId = request?.id ?? null
124
+ if (requestId) {
125
+ await saveContent(sdk, resource, workspaceId, { requestId })
126
+ }
78
127
  return {
79
128
  skipped: false,
80
129
  category,
81
130
  confidence,
82
- requestId: request?.id ?? null,
131
+ requestId,
83
132
  }
84
133
  }
@@ -3,6 +3,7 @@ import { INTAKE_CATEGORIES, REQUEST_CATEGORY } from './intake-categories.js'
3
3
  import { requestSourceText } from './extract-request.task.js'
4
4
 
5
5
  const GetResource = { id: '@ossy/resources/actions/get' }
6
+ const UpdateContent = { id: '@ossy/resources/actions/update-content' }
6
7
  const Categorize = { id: '@ossy/media-tasks/actions/categorize' }
7
8
  const ExtractRequest = { id: '@ossy/consultancy/actions/extract-request' }
8
9
 
@@ -17,12 +18,17 @@ const inbound = {
17
18
  },
18
19
  }
19
20
 
20
- function sdkFor (categorized) {
21
+ function sdkFor (categorized, source = inbound) {
22
+ let current = { ...source, content: { ...source.content } }
21
23
  const calls = []
22
24
  const sdk = {
23
25
  async invoke (action, payload) {
24
26
  calls.push({ id: action.id, payload })
25
- if (action.id === GetResource.id) return inbound
27
+ if (action.id === GetResource.id) return current
28
+ if (action.id === UpdateContent.id) {
29
+ current = { ...current, content: payload.content }
30
+ return current
31
+ }
26
32
  if (action.id === Categorize.id) return categorized
27
33
  if (action.id === ExtractRequest.id) return { id: 'request-1' }
28
34
  throw new Error(`unexpected ${action.id}`)
@@ -54,12 +60,15 @@ describe('screen-inbound task', () => {
54
60
  expect(calls.map((call) => call.id)).toEqual([
55
61
  GetResource.id,
56
62
  Categorize.id,
63
+ UpdateContent.id,
57
64
  ExtractRequest.id,
65
+ UpdateContent.id,
58
66
  ])
59
67
  expect(calls.find((call) => call.id === ExtractRequest.id).payload).toEqual({
60
68
  resourceId: inbound.id,
61
69
  workspaceId: 'ws-1',
62
70
  })
71
+ expect(calls.filter((call) => call.id === UpdateContent.id).at(-1).payload.content.requestId).toBe('request-1')
63
72
  expect(result).toEqual({
64
73
  skipped: false,
65
74
  category: REQUEST_CATEGORY,
@@ -76,6 +85,7 @@ describe('screen-inbound task', () => {
76
85
  })
77
86
 
78
87
  expect(calls.map((call) => call.id)).not.toContain(ExtractRequest.id)
88
+ expect(calls.find((call) => call.id === UpdateContent.id).payload.content.intakeCategory).toBe('contact')
79
89
  expect(result).toEqual({
80
90
  skipped: true,
81
91
  reason: 'category',
@@ -94,4 +104,51 @@ describe('screen-inbound task', () => {
94
104
  expect(calls.map((call) => call.id)).not.toContain(ExtractRequest.id)
95
105
  expect(result).toMatchObject({ skipped: true, reason: 'category', confidence: 0.4 })
96
106
  })
107
+
108
+ it('extracts again when a confident label was saved and the request was not', async () => {
109
+ const { calls, sdk } = sdkFor(null, {
110
+ ...inbound,
111
+ content: {
112
+ ...inbound.content,
113
+ intakeCategory: REQUEST_CATEGORY,
114
+ intakeConfidence: 1,
115
+ },
116
+ })
117
+ const result = await run({
118
+ event: { resourceId: inbound.id, payload: { belongsTo: 'ws-1' } },
119
+ sdk,
120
+ })
121
+
122
+ expect(calls.map((call) => call.id)).not.toContain(Categorize.id)
123
+ expect(calls.map((call) => call.id)).toContain(ExtractRequest.id)
124
+ expect(result.requestId).toBe('request-1')
125
+ })
126
+
127
+ it('stores the original sender before screening a forward', async () => {
128
+ const { calls, sdk } = sdkFor({ category: 'contact', confidence: 0.99 }, {
129
+ ...inbound,
130
+ content: {
131
+ ...inbound.content,
132
+ from: 'oskars.sylwan@ossy.se',
133
+ subject: 'Fwd: Senior React',
134
+ text: [
135
+ '---------- Forwarded message ---------',
136
+ 'From: Recruiter <recruiter@client.se>',
137
+ 'Subject: Senior React',
138
+ '',
139
+ 'Vi soker en senior React-utvecklare i Stockholm.',
140
+ ].join('\n'),
141
+ },
142
+ })
143
+
144
+ await run({
145
+ event: { resourceId: inbound.id, payload: { belongsTo: 'ws-1' } },
146
+ sdk,
147
+ })
148
+
149
+ const firstSave = calls.find((call) => call.id === UpdateContent.id)
150
+ expect(firstSave.payload.content.from).toBe('recruiter@client.se')
151
+ expect(firstSave.payload.content.forwardedBy).toBe('oskars.sylwan@ossy.se')
152
+ expect(firstSave.payload.content.subject).toBe('Senior React')
153
+ })
97
154
  })
@@ -165,6 +165,32 @@
165
165
  "@ossy/consultancy/schema/vacation.start.description": "Första semesterdagen (inklusive). De här dagarna faktureras inte.",
166
166
  "@ossy/consultancy/schema/vacation.end.label": "Sista lediga dagen",
167
167
  "@ossy/consultancy/schema/vacation.end.description": "Sista semesterdagen (inklusive).",
168
+ "@ossy/consultancy/schema/request.title.label": "Titel",
169
+ "@ossy/consultancy/schema/request.title.description": "Uppdragets titel.",
170
+ "@ossy/consultancy/schema/request.summary.label": "Sammanfattning",
171
+ "@ossy/consultancy/schema/request.summary.description": "Vad kunden frågar efter.",
172
+ "@ossy/consultancy/schema/request.role.label": "Roll",
173
+ "@ossy/consultancy/schema/request.role.description": "Profilen de söker.",
174
+ "@ossy/consultancy/schema/request.skills.label": "Kompetenser",
175
+ "@ossy/consultancy/schema/request.skills.description": "Kompetenser eller tekniker som nämns.",
176
+ "@ossy/consultancy/schema/request.location.label": "Plats",
177
+ "@ossy/consultancy/schema/request.location.description": "Var arbetet sker.",
178
+ "@ossy/consultancy/schema/request.duration.label": "Längd",
179
+ "@ossy/consultancy/schema/request.duration.description": "Hur länge uppdraget pågår.",
180
+ "@ossy/consultancy/schema/request.start.label": "Start",
181
+ "@ossy/consultancy/schema/request.start.description": "När uppdraget startar.",
182
+ "@ossy/consultancy/schema/request.rate.label": "Arvode",
183
+ "@ossy/consultancy/schema/request.rate.description": "Belopp utan valutasymbol.",
184
+ "@ossy/consultancy/schema/request.currency.label": "Valuta",
185
+ "@ossy/consultancy/schema/request.currency.description": "Valuta för arvodet.",
186
+ "@ossy/consultancy/schema/request.contactName.label": "Kontaktperson",
187
+ "@ossy/consultancy/schema/request.contactName.description": "Personen som skickade förfrågan.",
188
+ "@ossy/consultancy/schema/request.contactEmail.label": "Kontaktens e-post",
189
+ "@ossy/consultancy/schema/request.contactEmail.description": "Personens e-postadress.",
190
+ "@ossy/consultancy/schema/request.messageId.label": "Meddelande-id",
191
+ "@ossy/consultancy/schema/request.messageId.description": "Id på det inkommande mejlet.",
192
+ "@ossy/consultancy/schema/request.receivedAt.label": "Mottaget",
193
+ "@ossy/consultancy/schema/request.receivedAt.description": "När mejlet skickades.",
168
194
  "@ossy/consultancy/schema/opportunity.title.label": "Titel",
169
195
  "@ossy/consultancy/schema/opportunity.title.description": "Kort namn på leadet eller möjligheten.",
170
196
  "@ossy/consultancy/schema/opportunity.source.label": "Källa",
@@ -175,22 +175,40 @@ export function actualIncomeForMonth ({
175
175
  * @param {Array<object>} [options.employees]
176
176
  * @param {Array<object>} [options.contracts]
177
177
  */
178
+ /**
179
+ * Months after the calendar month of `now` have no timesheets yet.
180
+ * Actual series stay empty there so the chart does not fall to zero.
181
+ *
182
+ * @param {{ year?: number|string, monthNumber?: number|string }} month
183
+ * @param {Date} [now]
184
+ */
185
+ export function isAfterCurrentMonth (month, now = new Date()) {
186
+ const year = Number(month?.year)
187
+ const monthNumber = Number(month?.monthNumber)
188
+ if (!Number.isFinite(year) || !Number.isFinite(monthNumber)) return false
189
+ const currentYear = now.getFullYear()
190
+ const currentMonth = now.getMonth() + 1
191
+ return year > currentYear || (year === currentYear && monthNumber > currentMonth)
192
+ }
193
+
178
194
  export function withUtilizationHours ({
179
195
  months = [],
180
196
  timesheets = [],
181
197
  vacations = [],
182
198
  employees = [],
183
199
  contracts = [],
200
+ now = new Date(),
184
201
  } = {}) {
185
202
  return months.map((month) => {
186
- const actualIncome = actualIncomeForMonth({ month, timesheets, contracts })
187
203
  const salary = Number(month.monthlyCostOfEmployees) || 0
204
+ const future = isAfterCurrentMonth(month, now)
205
+ const actualIncome = future ? null : actualIncomeForMonth({ month, timesheets, contracts })
188
206
  return {
189
207
  ...month,
190
208
  forecastHours: Number(month.hoursWorked) || 0,
191
- actualHours: actualHoursForMonth({ month, timesheets, vacations, employees }),
209
+ actualHours: future ? null : actualHoursForMonth({ month, timesheets, vacations, employees }),
192
210
  actualIncome,
193
- actualRevenue: actualIncome - salary,
211
+ actualRevenue: future ? null : actualIncome - salary,
194
212
  }
195
213
  })
196
214
  }
@@ -131,4 +131,27 @@ describe('withUtilizationHours', () => {
131
131
  expect(month.actualIncome).toBe(6000)
132
132
  expect(month.actualRevenue).toBe(2000)
133
133
  })
134
+
135
+ it('leaves actuals empty after the current month', () => {
136
+ const [past, current, future] = withUtilizationHours({
137
+ now: new Date(2026, 0, 15),
138
+ months: [
139
+ { year: 2025, monthNumber: '12', hoursWorked: 10, monthlyCostOfEmployees: 1000, days: [] },
140
+ { ...january, monthlyCostOfEmployees: 1000 },
141
+ { year: 2026, monthNumber: '02', hoursWorked: 10, monthlyCostOfEmployees: 1000, days: [] },
142
+ ],
143
+ timesheets: [{
144
+ content: {
145
+ lines: [{ date: new Date(2026, 0, 5).getTime(), hours: 6 }],
146
+ },
147
+ }],
148
+ })
149
+
150
+ expect(past.actualHours).toBe(0)
151
+ expect(current.actualHours).toBe(6)
152
+ expect(future.actualHours).toBeNull()
153
+ expect(future.actualIncome).toBeNull()
154
+ expect(future.actualRevenue).toBeNull()
155
+ expect(future.forecastHours).toBe(10)
156
+ })
134
157
  })