@ossy/booking 3.20.0 → 3.20.1

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/README.md CHANGED
@@ -50,7 +50,7 @@ Resource schemas live in `src/*.schema.js` and are auto-discovered by `@ossy/app
50
50
 
51
51
  Documents are stored under canonical locations. Import paths from `@ossy/booking` (`services`, `bookings`, `availability`).
52
52
 
53
- Tasks write resources via `ResourceStream.commit` / `ResourceStream.mutate`, using `schemaId` on resource events (ADR 0008).
53
+ Tasks write resources via `sdk.invoke` (`CreateResource` / `PatchResourceContent` / …), using `schemaId` on resource events (ADR 0008).
54
54
 
55
55
  ## Projections
56
56
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ossy/booking",
3
3
  "description": "Booking feature package — services, availability, and appointment management for Ossy providers",
4
- "version": "3.20.0",
4
+ "version": "3.20.1",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
7
7
  "module": "./src/index.js",
@@ -16,12 +16,12 @@
16
16
  "dependencies": {
17
17
  "@ossy/config": "^3.0.9",
18
18
  "@ossy/email": "^3.11.0",
19
- "@ossy/event-store": "^3.20.0",
19
+ "@ossy/event-store": "^3.20.1",
20
20
  "@ossy/observability": "^3.0.9",
21
- "@ossy/platform": "^3.20.0",
22
- "@ossy/resources": "^3.20.0",
23
- "@ossy/users": "^3.20.0",
24
- "@ossy/workspaces": "^3.20.0"
21
+ "@ossy/platform": "^3.20.1",
22
+ "@ossy/resources": "^3.20.1",
23
+ "@ossy/users": "^3.20.1",
24
+ "@ossy/workspaces": "^3.20.1"
25
25
  },
26
26
  "peerDependencies": {
27
27
  "@ossy/app": ">=1.0.0",
@@ -38,5 +38,5 @@
38
38
  "/src",
39
39
  "README.md"
40
40
  ],
41
- "gitHead": "edab6a966f41c07a68bdd86f3864cc2ad02e3406"
41
+ "gitHead": "3e8bb118b3ef163792a004663ccb803ab51a8601"
42
42
  }
@@ -25,5 +25,25 @@ export default {
25
25
  type: 'text',
26
26
  default: 'Europe/Stockholm',
27
27
  },
28
+ {
29
+ name: 'weeklyWindows',
30
+ type: 'json',
31
+ description: 'Weekly open windows [{ dayOfWeek, startTime, endTime }]',
32
+ },
33
+ {
34
+ name: 'sessionDurations',
35
+ type: 'json',
36
+ description: 'Allowed session lengths in minutes',
37
+ },
38
+ {
39
+ name: 'bufferMinutes',
40
+ type: 'number',
41
+ description: 'Gap between bookings in minutes',
42
+ },
43
+ {
44
+ name: 'blackoutDates',
45
+ type: 'json',
46
+ description: 'Dates when no bookings are accepted',
47
+ },
28
48
  ],
29
49
  }
@@ -1,10 +1,27 @@
1
- import { ResourcesQueries } from '@ossy/resources/server'
1
+ import { ListResources } from '@ossy/resources'
2
+
3
+ function requireSdk (sdk) {
4
+ if (!sdk?.invoke) {
5
+ throw Object.assign(new Error('sdk is required'), { status: 500 })
6
+ }
7
+ return sdk
8
+ }
9
+
10
+ function asResourceList (result) {
11
+ if (Array.isArray(result)) return result
12
+ if (Array.isArray(result?.items)) return result.items
13
+ return []
14
+ }
2
15
 
3
16
  /**
4
- * List booking resources by schema id (and optional workspace).
17
+ * List booking resources by schema id (and optional workspace) via sdk.invoke.
5
18
  */
6
- export function getBookingResources ({ schemaId, belongsTo, user }) {
19
+ export async function getBookingResources ({ schemaId, belongsTo, sdk } = {}) {
20
+ requireSdk(sdk)
7
21
  const query = { type: schemaId }
8
- if (belongsTo) query.belongsTo = belongsTo
9
- return ResourcesQueries.GetResources(query, user)
22
+ const resources = await sdk.invoke(ListResources, {
23
+ ...(belongsTo ? { workspaceId: belongsTo } : {}),
24
+ query,
25
+ })
26
+ return asResourceList(resources)
10
27
  }
@@ -51,5 +51,20 @@ export default {
51
51
  name: 'notes',
52
52
  type: 'textarea',
53
53
  },
54
+ {
55
+ name: 'clientMessage',
56
+ type: 'textarea',
57
+ description: 'Optional message from the client with the booking request',
58
+ },
59
+ {
60
+ name: 'attachments',
61
+ type: 'json',
62
+ description: 'Optional attachment descriptors sent with the booking request',
63
+ },
64
+ {
65
+ name: 'duration',
66
+ type: 'number',
67
+ description: 'Requested session length in minutes',
68
+ },
54
69
  ],
55
70
  }
@@ -50,7 +50,8 @@ export default {
50
50
  { action: OpenCreateService },
51
51
  { result: { selector: '[data-services-form="open"]', timeout: 10000 } },
52
52
  { result: { action: CreateService, timeout: 15000 } },
53
- { form: ServiceForm },
53
+ // Pin duration to a catalog select option ('30'|'60'|'90').
54
+ { form: ServiceForm, fields: { duration: '60' } },
54
55
  { action: CreateService },
55
56
  { result: { action: OpenDeleteService, timeout: 15000 } },
56
57
 
@@ -1,4 +1,5 @@
1
1
  import { ActionService } from '@ossy/platform'
2
+ import { createInProcessSdk } from '@ossy/platform/tasks'
2
3
  import { verifyBookingEmailToken } from './booking-email-token.js'
3
4
 
4
5
  export const metadata = {
@@ -22,6 +23,8 @@ export default async function handle (req, res) {
22
23
  await ActionService.invoke('@ossy/booking/actions/confirm', {
23
24
  payload: { bookingId, workspaceId },
24
25
  req: { ...req, workspaceId },
26
+ // Email-token confirm runs as a workspace-scoped bot, not the visitor.
27
+ sdk: createInProcessSdk().forWorkspace(workspaceId),
25
28
  })
26
29
  res.status(200).send(htmlPage('Bokning bekräftad', 'Bokningen är bekräftad. Klienten har fått ett bekräftelsemejl.'))
27
30
  } catch (err) {
@@ -1,6 +1,6 @@
1
- import { nanoid } from 'nanoid'
1
+ import { randomUUID } from 'node:crypto'
2
2
  import { ConfigService } from '@ossy/config'
3
- import { ResourceStream, ResourcesEvents } from '@ossy/resources/server'
3
+ import { CreateResource } from '@ossy/resources'
4
4
  import { BookingSchema } from './schema-ids.js'
5
5
  import { getAvailableSlots } from './availability-engine.js'
6
6
  import { toMs } from './time.js'
@@ -13,10 +13,11 @@ import {
13
13
  resolveProviderName,
14
14
  } from './provider-fields.js'
15
15
  import { resolveWorkspaceContact, resolveWorkspaceId } from './resolve-workspace-contact.js'
16
+ import { sdkForWorkspace } from './sdk-for-workspace.js'
16
17
 
17
18
  export const metadata = { id: '@ossy/booking/tasks/create' }
18
19
 
19
- export async function run({ payload, req, log, integrations }) {
20
+ export async function run({ payload, req, log, integrations, sdk }) {
20
21
  const {
21
22
  startAt,
22
23
  duration,
@@ -30,12 +31,16 @@ export async function run({ payload, req, log, integrations }) {
30
31
  declineUrl,
31
32
  } = payload ?? {}
32
33
 
34
+ if (!sdk?.invoke) throw Object.assign(new Error('sdk is required'), { status: 500 })
35
+
33
36
  const workspaceId = await resolveWorkspaceId(payload)
34
37
  let providerName = resolveProviderName(payload)
35
38
  let providerEmail = resolveProviderEmail(payload)
36
39
 
37
40
  if (!workspaceId) throw Object.assign(new Error('workspaceId or providerSlug is required'), { status: 400 })
38
41
 
42
+ const workspaceSdk = sdkForWorkspace(sdk, workspaceId)
43
+
39
44
  if (!providerEmail || !providerName) {
40
45
  const contact = await resolveWorkspaceContact(workspaceId)
41
46
  providerEmail = providerEmail ?? contact?.providerEmail
@@ -48,11 +53,10 @@ export async function run({ payload, req, log, integrations }) {
48
53
 
49
54
  log?.info(`[booking/tasks/create] Creating booking for ${clientEmail} with workspace ${workspaceId}`)
50
55
 
51
- // Re-validate slot availability
52
56
  const availabilityResources = await getBookingResources({
53
57
  schemaId: BookingSchema.availability,
54
58
  belongsTo: workspaceId,
55
- user: ResourceStream.system('booking-create'),
59
+ sdk: workspaceSdk,
56
60
  })
57
61
 
58
62
  // New format: single resource with weeklyWindows array in content
@@ -84,7 +88,7 @@ export async function run({ payload, req, log, integrations }) {
84
88
  const allBookingResources = await getBookingResources({
85
89
  schemaId: BookingSchema.booking,
86
90
  belongsTo: workspaceId,
87
- user: ResourceStream.system('booking-create'),
91
+ sdk: workspaceSdk,
88
92
  })
89
93
 
90
94
  const confirmedBookings = allBookingResources
@@ -116,32 +120,31 @@ export async function run({ payload, req, log, integrations }) {
116
120
  throw Object.assign(new Error('The requested slot is no longer available'), { status: 409 })
117
121
  }
118
122
 
119
- // Create the booking resource
120
- const bookingId = nanoid()
121
- const event = ResourcesEvents.Created({
122
- resourceId: bookingId,
123
- schemaId: BookingSchema.booking,
124
- createdBy: 'public',
125
- belongsTo: workspaceId,
123
+ const content = {
124
+ ...(serviceId ? { serviceId } : {}),
125
+ clientName,
126
+ clientEmail,
127
+ workspaceId,
128
+ providerId: workspaceId,
129
+ startsAt: startMs,
130
+ endsAt,
131
+ status: 'pending',
132
+ paymentStatus: 'unpaid',
133
+ clientMessage: clientMessage ?? '',
134
+ attachments: Array.isArray(attachments) ? attachments : [],
135
+ duration,
136
+ }
137
+
138
+ const bookingNameId = randomUUID()
139
+ const booking = await workspaceSdk.invoke(CreateResource, {
140
+ workspaceId,
141
+ type: BookingSchema.booking,
126
142
  location: bookings,
127
- name: `booking-${bookingId}.json`,
128
- content: {
129
- serviceId: serviceId ?? null,
130
- clientName,
131
- clientEmail,
132
- clientMessage: clientMessage ?? '',
133
- attachments: Array.isArray(attachments) ? attachments : [],
134
- workspaceId,
135
- providerId: workspaceId,
136
- startsAt: startMs,
137
- endsAt,
138
- duration,
139
- status: 'pending',
140
- paymentStatus: 'unpaid',
141
- },
143
+ name: `booking-${bookingNameId}.json`,
144
+ content,
142
145
  })
143
146
 
144
- const booking = await ResourceStream.commit(event, ResourceStream.system('booking-create'))
147
+ const bookingId = booking.id
145
148
 
146
149
  log?.info(`[booking/tasks/create] Booking ${bookingId} created`)
147
150
 
@@ -0,0 +1,108 @@
1
+ import { beforeEach, describe, expect, it, jest } from '@jest/globals'
2
+
3
+ const CreateResource = { id: '@ossy/resources/actions/create' }
4
+
5
+ await jest.unstable_mockModule('@ossy/resources', () => ({
6
+ CreateResource,
7
+ }))
8
+
9
+ await jest.unstable_mockModule('./availability-engine.js', () => ({
10
+ getAvailableSlots: () => [{ startAt: 1_700_000_000_000 }],
11
+ }))
12
+
13
+ await jest.unstable_mockModule('./booking-resources.js', () => ({
14
+ getBookingResources: jest.fn(async ({ schemaId }) => {
15
+ if (schemaId.includes('availability')) {
16
+ return [{
17
+ id: 'avail-1',
18
+ content: {
19
+ weeklyWindows: [{ dayOfWeek: 1, startTime: '09:00', endTime: '17:00' }],
20
+ bufferMinutes: 0,
21
+ timezone: 'Europe/Stockholm',
22
+ },
23
+ }]
24
+ }
25
+ return []
26
+ }),
27
+ }))
28
+
29
+ await jest.unstable_mockModule('./resolve-workspace-contact.js', () => ({
30
+ resolveWorkspaceId: async () => 'ws-1',
31
+ resolveWorkspaceContact: async () => ({
32
+ providerEmail: 'provider@example.com',
33
+ providerName: 'Provider',
34
+ }),
35
+ }))
36
+
37
+ await jest.unstable_mockModule('./provider-fields.js', () => ({
38
+ resolveProviderEmail: () => 'provider@example.com',
39
+ resolveProviderName: () => 'Provider',
40
+ }))
41
+
42
+ await jest.unstable_mockModule('./booking-email-token.js', () => ({
43
+ createBookingEmailToken: () => 'token',
44
+ }))
45
+
46
+ await jest.unstable_mockModule('./booking-request.email.jsx', () => ({
47
+ default: () => null,
48
+ id: '@ossy/booking/email/booking-request',
49
+ }))
50
+
51
+ const { run } = await import('./create-booking.task.js')
52
+ const { BookingSchema } = await import('./schema-ids.js')
53
+
54
+ describe('create-booking task', () => {
55
+ beforeEach(() => {
56
+ jest.clearAllMocks()
57
+ })
58
+
59
+ it('creates the booking with duration and message in one CreateResource', async () => {
60
+ const invoke = jest.fn(async (action, payload) => {
61
+ if (action === CreateResource) {
62
+ return { id: 'booking-1', content: payload.content }
63
+ }
64
+ throw new Error(`unexpected action ${action?.id ?? action}`)
65
+ })
66
+
67
+ const result = await run({
68
+ payload: {
69
+ startAt: 1_700_000_000_000,
70
+ duration: 60,
71
+ clientName: 'Ada',
72
+ clientEmail: 'ada@example.com',
73
+ clientMessage: 'Hello',
74
+ attachments: [{ name: 'brief.pdf' }],
75
+ serviceId: 'svc-1',
76
+ },
77
+ sdk: { invoke, forWorkspace: () => ({ invoke }) },
78
+ log: { info: () => {} },
79
+ })
80
+
81
+ expect(invoke).toHaveBeenCalledTimes(1)
82
+ expect(invoke.mock.calls[0][0]).toBe(CreateResource)
83
+ expect(invoke.mock.calls[0][1]).toMatchObject({
84
+ workspaceId: 'ws-1',
85
+ type: BookingSchema.booking,
86
+ content: {
87
+ serviceId: 'svc-1',
88
+ clientName: 'Ada',
89
+ clientEmail: 'ada@example.com',
90
+ clientMessage: 'Hello',
91
+ attachments: [{ name: 'brief.pdf' }],
92
+ duration: 60,
93
+ status: 'pending',
94
+ paymentStatus: 'unpaid',
95
+ startsAt: 1_700_000_000_000,
96
+ endsAt: 1_700_000_000_000 + 60 * 60 * 1000,
97
+ },
98
+ })
99
+ expect(invoke.mock.calls[0][1].name).toMatch(/^booking-.+\.json$/)
100
+ expect(result).toMatchObject({
101
+ id: 'booking-1',
102
+ content: {
103
+ duration: 60,
104
+ clientMessage: 'Hello',
105
+ },
106
+ })
107
+ })
108
+ })
@@ -1,16 +1,17 @@
1
- import { nanoid } from 'nanoid'
2
- import { ResourceStream, ResourcesEvents } from '@ossy/resources/server'
1
+ import { CreateResource } from '@ossy/resources'
3
2
  import { BookingSchema } from './schema-ids.js'
4
3
  import { services } from './locations.js'
4
+ import { serviceDurationMinutes } from './service-duration.js'
5
5
 
6
6
  export const metadata = { id: '@ossy/booking/tasks/create-service' }
7
7
 
8
- export async function run ({ payload, req, log }) {
8
+ export async function run ({ payload, req, log, sdk }) {
9
9
  const workspaceId = req?.workspaceId
10
10
 
11
11
  if (!workspaceId) {
12
12
  throw Object.assign(new Error('workspaceId is required'), { status: 400 })
13
13
  }
14
+ if (!sdk?.invoke) throw Object.assign(new Error('sdk is required'), { status: 500 })
14
15
 
15
16
  const { name, duration, price, currency, description, active } = payload ?? {}
16
17
 
@@ -18,29 +19,24 @@ export async function run ({ payload, req, log }) {
18
19
  throw Object.assign(new Error('name is required'), { status: 400 })
19
20
  }
20
21
 
21
- const resourceId = nanoid()
22
22
  const content = {
23
23
  name: name.trim(),
24
- duration: Number(duration) || 60,
24
+ duration: serviceDurationMinutes(duration),
25
25
  price: Number(price) || 0,
26
26
  currency: currency ?? 'SEK',
27
27
  description: description?.trim() ?? '',
28
28
  active: active !== false,
29
29
  }
30
30
 
31
- log?.info(`[booking/tasks/create-service] Creating service ${resourceId} for workspace ${workspaceId}`)
31
+ log?.info(`[booking/tasks/create-service] Creating service for workspace ${workspaceId}`)
32
32
 
33
- const event = ResourcesEvents.Created({
34
- resourceId,
35
- schemaId: BookingSchema.service,
36
- createdBy: req?.userId ?? 'system',
37
- belongsTo: workspaceId,
33
+ const service = await sdk.invoke(CreateResource, {
34
+ workspaceId,
35
+ type: BookingSchema.service,
38
36
  location: services,
39
37
  name: `${content.name.replace(/\s+/g, '-').toLowerCase()}.json`,
40
38
  content,
41
39
  })
42
40
 
43
- const service = await ResourceStream.commit(event, ResourceStream.actor({ req, payload }))
44
-
45
- return { id: resourceId, ...content, ...service }
41
+ return { id: service.id, ...content, ...service }
46
42
  }
@@ -1,4 +1,5 @@
1
1
  import { ActionService } from '@ossy/platform'
2
+ import { createInProcessSdk } from '@ossy/platform/tasks'
2
3
  import { verifyBookingEmailToken } from './booking-email-token.js'
3
4
 
4
5
  export const metadata = {
@@ -22,6 +23,8 @@ export default async function handle (req, res) {
22
23
  await ActionService.invoke('@ossy/booking/actions/decline', {
23
24
  payload: { bookingId, workspaceId },
24
25
  req: { ...req, workspaceId },
26
+ // Email-token decline runs as a workspace-scoped bot, not the visitor.
27
+ sdk: createInProcessSdk().forWorkspace(workspaceId),
25
28
  })
26
29
  res.status(200).send(htmlPage('Bokning avböjd', 'Bokningen har avböjts. Klienten har fått ett meddelande.'))
27
30
  } catch (err) {
@@ -1,10 +1,10 @@
1
- import { ResourceStream, ResourcesEvents } from '@ossy/resources/server'
1
+ import { DeleteResource } from '@ossy/resources'
2
2
  import { BookingSchema } from './schema-ids.js'
3
3
  import { getBookingResources } from './booking-resources.js'
4
4
 
5
5
  export const metadata = { id: '@ossy/booking/tasks/delete-service' }
6
6
 
7
- export async function run ({ payload, req, log }) {
7
+ export async function run ({ payload, req, log, sdk }) {
8
8
  const workspaceId = req?.workspaceId
9
9
  const { serviceId } = payload ?? {}
10
10
 
@@ -14,12 +14,12 @@ export async function run ({ payload, req, log }) {
14
14
  if (!serviceId) {
15
15
  throw Object.assign(new Error('serviceId is required'), { status: 400 })
16
16
  }
17
+ if (!sdk?.invoke) throw Object.assign(new Error('sdk is required'), { status: 500 })
17
18
 
18
- const actor = ResourceStream.actor({ req, payload })
19
19
  const existing = await getBookingResources({
20
20
  schemaId: BookingSchema.service,
21
21
  belongsTo: workspaceId,
22
- user: actor.kind === 'system' ? actor : actor.user,
22
+ sdk,
23
23
  })
24
24
 
25
25
  const resource = existing.find(r => r.id === serviceId)
@@ -29,13 +29,7 @@ export async function run ({ payload, req, log }) {
29
29
 
30
30
  log?.info(`[booking/tasks/delete-service] Deleting service ${serviceId}`)
31
31
 
32
- await ResourceStream.mutate(
33
- serviceId,
34
- ResourcesEvents.Deleted({
35
- createdBy: req?.userId ?? 'system',
36
- }),
37
- actor,
38
- )
32
+ await sdk.invoke(DeleteResource, { resourceId: serviceId })
39
33
 
40
34
  return { id: serviceId, deleted: true }
41
35
  }
@@ -1,10 +1,9 @@
1
- import { ResourceStream } from '@ossy/resources/server'
2
1
  import { getBookingResources } from './booking-resources.js'
3
2
  import { BookingSchema } from './schema-ids.js'
4
3
 
5
4
  export const metadata = { id: '@ossy/booking/tasks/get-availability' }
6
5
 
7
- export async function run({ payload, req, log }) {
6
+ export async function run({ payload, req, log, sdk }) {
8
7
  const workspaceId = req?.workspaceId
9
8
 
10
9
  if (!workspaceId) {
@@ -13,11 +12,10 @@ export async function run({ payload, req, log }) {
13
12
 
14
13
  log?.info(`[booking/tasks/get-availability] Loading availability for workspace ${workspaceId}`)
15
14
 
16
- const actor = ResourceStream.actor({ req, payload })
17
15
  const resources = await getBookingResources({
18
16
  schemaId: BookingSchema.availability,
19
17
  belongsTo: workspaceId,
20
- user: actor.kind === 'system' ? actor : actor.user,
18
+ sdk,
21
19
  })
22
20
 
23
21
  if (!resources.length) {
@@ -1,15 +1,15 @@
1
- import { ResourceStream } from '@ossy/resources/server'
2
1
  import { getAvailableSlots } from './availability-engine.js'
3
2
  import { getBookingResources } from './booking-resources.js'
4
3
  import { BookingSchema } from './schema-ids.js'
5
4
  import { resolveWorkspaceId } from './resolve-workspace-contact.js'
5
+ import { sdkForWorkspace } from './sdk-for-workspace.js'
6
6
 
7
7
  export const metadata = { id: '@ossy/booking/tasks/get-available-slots' }
8
8
 
9
9
  const DEFAULT_DURATION = 60 // minutes
10
10
  const DEFAULT_RANGE_DAYS = 30
11
11
 
12
- export async function run ({ payload, log }) {
12
+ export async function run ({ payload, log, sdk }) {
13
13
  const { duration, serviceId, from, to } = payload ?? {}
14
14
  const workspaceId = await resolveWorkspaceId(payload)
15
15
 
@@ -19,24 +19,26 @@ export async function run ({ payload, log }) {
19
19
 
20
20
  log?.info(`[booking/tasks/get-available-slots] Loading slots for workspace ${workspaceId}`)
21
21
 
22
+ const workspaceSdk = sdkForWorkspace(sdk, workspaceId)
22
23
  let slotDuration = duration
23
24
 
24
25
  if (serviceId) {
25
26
  const serviceResources = await getBookingResources({
26
27
  schemaId: BookingSchema.service,
27
28
  belongsTo: workspaceId,
28
- user: ResourceStream.system('booking-public'),
29
+ sdk: workspaceSdk,
29
30
  })
30
31
  const service = serviceResources.find(r => r.id === serviceId)
31
- if (service?.content?.duration) {
32
- slotDuration = service.content.duration
32
+ if (service?.content?.duration != null && service.content.duration !== '') {
33
+ // Coerce legacy string select values ('30'|'60'|'90') to minutes.
34
+ slotDuration = Number(service.content.duration)
33
35
  }
34
36
  }
35
37
 
36
38
  const availabilityResources = await getBookingResources({
37
39
  schemaId: BookingSchema.availability,
38
40
  belongsTo: workspaceId,
39
- user: ResourceStream.system('booking-public'),
41
+ sdk: workspaceSdk,
40
42
  })
41
43
 
42
44
  if (!availabilityResources.length) {
@@ -76,7 +78,7 @@ export async function run ({ payload, log }) {
76
78
  const allBookingResources = await getBookingResources({
77
79
  schemaId: BookingSchema.booking,
78
80
  belongsTo: workspaceId,
79
- user: ResourceStream.system('booking-public'),
81
+ sdk: workspaceSdk,
80
82
  })
81
83
 
82
84
  const confirmedBookings = allBookingResources
@@ -91,7 +93,7 @@ export async function run ({ payload, log }) {
91
93
  ? (configResource.content.sessionDurations ?? [DEFAULT_DURATION])
92
94
  : [firstResource?.content?.sessionDuration ?? DEFAULT_DURATION]
93
95
 
94
- const resolvedDuration = slotDuration ?? sessionDurations[0] ?? DEFAULT_DURATION
96
+ const resolvedDuration = Number(slotDuration ?? sessionDurations[0] ?? DEFAULT_DURATION) || DEFAULT_DURATION
95
97
 
96
98
  const slots = getAvailableSlots({
97
99
  availability,
@@ -1,11 +1,11 @@
1
- import { ResourceStream } from '@ossy/resources/server'
2
1
  import { getBookingResources } from './booking-resources.js'
3
2
  import { BookingSchema } from './schema-ids.js'
4
3
  import { resolveWorkspaceContact, resolveWorkspaceId } from './resolve-workspace-contact.js'
4
+ import { sdkForWorkspace } from './sdk-for-workspace.js'
5
5
 
6
6
  export const metadata = { id: '@ossy/booking/tasks/get-services' }
7
7
 
8
- export async function run ({ payload, req, log }) {
8
+ export async function run ({ payload, req, log, sdk }) {
9
9
  const workspaceId = await resolveWorkspaceId(payload) ?? payload?.workspaceId ?? req?.workspaceId
10
10
 
11
11
  if (!workspaceId) {
@@ -17,7 +17,7 @@ export async function run ({ payload, req, log }) {
17
17
  const resources = await getBookingResources({
18
18
  schemaId: BookingSchema.service,
19
19
  belongsTo: workspaceId,
20
- user: ResourceStream.system('booking-public'),
20
+ sdk: sdkForWorkspace(sdk, workspaceId),
21
21
  })
22
22
 
23
23
  const includeInactive = payload?.includeInactive === true
@@ -26,7 +26,7 @@ export async function run ({ payload, req, log }) {
26
26
  .map(r => ({
27
27
  id: r.id,
28
28
  name: r.content?.name ?? r.name,
29
- duration: r.content?.duration ?? 60,
29
+ duration: Number(r.content?.duration ?? 60) || 60,
30
30
  price: r.content?.price ?? 0,
31
31
  currency: r.content?.currency ?? 'SEK',
32
32
  description: r.content?.description ?? '',
@@ -1,5 +1,4 @@
1
1
  import { getProjection } from '@ossy/event-store'
2
- import { ResourceStream } from '@ossy/resources/server'
3
2
  import { getBookingResources } from './booking-resources.js'
4
3
  import { BookingListProjection } from './booking-list.aggregate.js'
5
4
  import { BookingSchema } from './schema-ids.js'
@@ -7,12 +6,18 @@ import { toMs } from './time.js'
7
6
 
8
7
  export const metadata = { id: '@ossy/booking/tasks/list' }
9
8
 
10
- export async function run({ payload, req, log }) {
9
+ function isWorkspaceMember (req, payload, workspaceId) {
10
+ const user = payload?.user ?? req?.user
11
+ if (user) return Boolean(user.workspaces?.includes(workspaceId))
12
+ const userId = payload?.userId ?? req?.userId
13
+ return userId === 'system'
14
+ }
15
+
16
+ export async function run({ payload, req, log, sdk }) {
11
17
  const workspaceId = req?.workspaceId
12
18
  const status = payload?.status ?? null
13
19
 
14
- const actor = ResourceStream.actor({ req, payload })
15
- const member = actor.kind === 'system' || actor.user?.workspaces?.includes(workspaceId)
20
+ const member = isWorkspaceMember(req, payload, workspaceId)
16
21
  log?.info(`[booking/tasks/list] Loading bookings for workspace ${workspaceId}`, { status })
17
22
 
18
23
  if (!member) return []
@@ -24,7 +29,7 @@ export async function run({ payload, req, log }) {
24
29
  const resources = await getBookingResources({
25
30
  schemaId: BookingSchema.booking,
26
31
  belongsTo: workspaceId,
27
- user: actor.kind === 'system' ? actor : actor.user,
32
+ sdk,
28
33
  })
29
34
  bookings = resources.map(r => ({
30
35
  id: r.id,
@@ -37,7 +37,8 @@ export default {
37
37
  { action: OpenCreateService },
38
38
  { result: { selector: '[data-services-form="open"]', timeout: 10000 } },
39
39
  { result: { action: CreateService, timeout: 15000 } },
40
- { form: ServiceForm },
40
+ // Pin duration to a catalog select option ('30'|'60'|'90').
41
+ { form: ServiceForm, fields: { duration: '60' } },
41
42
  { action: CreateService },
42
43
  { result: { action: OpenDeleteService, timeout: 15000 } },
43
44
  ],
@@ -1,17 +1,17 @@
1
- import { nanoid } from 'nanoid'
2
- import { ResourceStream, ResourcesEvents } from '@ossy/resources/server'
1
+ import { CreateResource, PatchResourceContent } from '@ossy/resources'
3
2
  import { BookingSchema } from './schema-ids.js'
4
3
  import { getBookingResources } from './booking-resources.js'
5
4
  import { availability } from './locations.js'
6
5
 
7
6
  export const metadata = { id: '@ossy/booking/tasks/save-availability' }
8
7
 
9
- export async function run ({ payload, req, log }) {
8
+ export async function run ({ payload, req, log, sdk }) {
10
9
  const workspaceId = req?.workspaceId
11
10
 
12
11
  if (!workspaceId) {
13
12
  throw Object.assign(new Error('workspaceId is required'), { status: 400 })
14
13
  }
14
+ if (!sdk?.invoke) throw Object.assign(new Error('sdk is required'), { status: 500 })
15
15
 
16
16
  const { weeklyWindows, sessionDurations, bufferMinutes, timezone } = payload ?? {}
17
17
 
@@ -30,11 +30,10 @@ export async function run ({ payload, req, log }) {
30
30
  timezone: timezone ?? 'Europe/Stockholm',
31
31
  }
32
32
 
33
- const actor = ResourceStream.actor({ req, payload })
34
33
  const existing = await getBookingResources({
35
34
  schemaId: BookingSchema.availability,
36
35
  belongsTo: workspaceId,
37
- user: actor.kind === 'system' ? actor : actor.user,
36
+ sdk,
38
37
  })
39
38
 
40
39
  const configResource = existing.find(r => Array.isArray(r.content?.weeklyWindows))
@@ -42,34 +41,26 @@ export async function run ({ payload, req, log }) {
42
41
  if (configResource) {
43
42
  log?.info(`[booking/tasks/save-availability] Updating existing resource ${configResource.id}`)
44
43
 
45
- await ResourceStream.mutate(
46
- configResource.id,
47
- ResourcesEvents.Patched({
48
- createdBy: req?.userId ?? 'system',
49
- content,
50
- }),
51
- actor,
52
- )
44
+ await sdk.invoke(PatchResourceContent, {
45
+ resourceId: configResource.id,
46
+ content,
47
+ })
53
48
 
54
49
  return { id: configResource.id, content }
55
50
  }
56
51
 
57
- const resourceId = nanoid()
58
- log?.info(`[booking/tasks/save-availability] Creating new resource ${resourceId}`)
52
+ // Schema includes weeklyWindows / sessionDurations / bufferMinutes — create atomically.
53
+ log?.info(`[booking/tasks/save-availability] Creating new availability config`)
59
54
 
60
- const event = ResourcesEvents.Created({
61
- resourceId,
62
- schemaId: BookingSchema.availability,
63
- createdBy: req?.userId ?? 'system',
64
- belongsTo: workspaceId,
55
+ const resource = await sdk.invoke(CreateResource, {
56
+ workspaceId,
57
+ type: BookingSchema.availability,
65
58
  location: availability,
66
59
  name: 'availability-config.json',
67
60
  content,
68
61
  })
69
62
 
70
- await ResourceStream.commit(event, actor)
71
-
72
- log?.info(`[booking/tasks/save-availability] Resource ${resourceId} created`)
63
+ log?.info(`[booking/tasks/save-availability] Resource ${resource.id} created`)
73
64
 
74
- return { id: resourceId, content }
65
+ return { id: resource.id, content }
75
66
  }
@@ -0,0 +1,101 @@
1
+ import { beforeEach, describe, expect, it, jest } from '@jest/globals'
2
+
3
+ const CreateResource = { id: '@ossy/resources/actions/create' }
4
+ const PatchResourceContent = { id: '@ossy/resources/actions/patch-content' }
5
+
6
+ await jest.unstable_mockModule('@ossy/resources', () => ({
7
+ CreateResource,
8
+ PatchResourceContent,
9
+ }))
10
+
11
+ await jest.unstable_mockModule('./booking-resources.js', () => ({
12
+ getBookingResources: jest.fn(),
13
+ }))
14
+
15
+ const { run } = await import('./save-availability.task.js')
16
+ const { getBookingResources } = await import('./booking-resources.js')
17
+ const { BookingSchema } = await import('./schema-ids.js')
18
+
19
+ describe('save-availability task', () => {
20
+ beforeEach(() => {
21
+ jest.clearAllMocks()
22
+ })
23
+
24
+ it('creates availability with full content in one CreateResource', async () => {
25
+ getBookingResources.mockResolvedValue([])
26
+ const invoke = jest.fn(async (action, payload) => {
27
+ if (action === CreateResource) {
28
+ return { id: 'avail-1', content: payload.content }
29
+ }
30
+ throw new Error(`unexpected action ${action?.id ?? action}`)
31
+ })
32
+
33
+ const result = await run({
34
+ payload: {
35
+ weeklyWindows: [{ dayOfWeek: 1, startTime: '09:00', endTime: '17:00' }],
36
+ sessionDurations: [30, 60],
37
+ bufferMinutes: 15,
38
+ timezone: 'Europe/Stockholm',
39
+ },
40
+ req: { workspaceId: 'ws-1' },
41
+ sdk: { invoke },
42
+ })
43
+
44
+ expect(invoke).toHaveBeenCalledTimes(1)
45
+ expect(invoke.mock.calls[0][0]).toBe(CreateResource)
46
+ expect(invoke.mock.calls[0][1]).toMatchObject({
47
+ workspaceId: 'ws-1',
48
+ type: BookingSchema.availability,
49
+ name: 'availability-config.json',
50
+ content: {
51
+ weeklyWindows: [{ dayOfWeek: 1, startTime: '09:00', endTime: '17:00' }],
52
+ sessionDurations: [30, 60],
53
+ bufferMinutes: 15,
54
+ timezone: 'Europe/Stockholm',
55
+ },
56
+ })
57
+ expect(result).toEqual({
58
+ id: 'avail-1',
59
+ content: {
60
+ weeklyWindows: [{ dayOfWeek: 1, startTime: '09:00', endTime: '17:00' }],
61
+ sessionDurations: [30, 60],
62
+ bufferMinutes: 15,
63
+ timezone: 'Europe/Stockholm',
64
+ },
65
+ })
66
+ })
67
+
68
+ it('patches an existing weeklyWindows config resource', async () => {
69
+ getBookingResources.mockResolvedValue([
70
+ { id: 'avail-existing', content: { weeklyWindows: [] } },
71
+ ])
72
+ const invoke = jest.fn(async (action, payload) => {
73
+ if (action === PatchResourceContent) {
74
+ return { id: payload.resourceId, content: payload.content }
75
+ }
76
+ throw new Error(`unexpected action ${action?.id ?? action}`)
77
+ })
78
+
79
+ const result = await run({
80
+ payload: {
81
+ weeklyWindows: [{ dayOfWeek: 2, startTime: '10:00', endTime: '16:00' }],
82
+ bufferMinutes: 0,
83
+ },
84
+ req: { workspaceId: 'ws-1' },
85
+ sdk: { invoke },
86
+ })
87
+
88
+ expect(invoke).toHaveBeenCalledTimes(1)
89
+ expect(invoke.mock.calls[0][0]).toBe(PatchResourceContent)
90
+ expect(invoke.mock.calls[0][1]).toMatchObject({
91
+ resourceId: 'avail-existing',
92
+ content: {
93
+ weeklyWindows: [{ dayOfWeek: 2, startTime: '10:00', endTime: '16:00' }],
94
+ sessionDurations: [60],
95
+ bufferMinutes: 0,
96
+ timezone: 'Europe/Stockholm',
97
+ },
98
+ })
99
+ expect(result.id).toBe('avail-existing')
100
+ })
101
+ })
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Bot limited to one workspace. Public booking and email-token flows use this
3
+ * so the visitor is not the resource actor.
4
+ *
5
+ * @param {{ forWorkspace?: Function }} sdk
6
+ * @param {string} workspaceId
7
+ */
8
+ export function sdkForWorkspace (sdk, workspaceId) {
9
+ if (!workspaceId) {
10
+ throw Object.assign(new Error('workspaceId is required'), { status: 400 })
11
+ }
12
+ if (typeof sdk?.forWorkspace !== 'function') {
13
+ throw Object.assign(new Error('sdk.forWorkspace is required'), { status: 500 })
14
+ }
15
+ return sdk.forWorkspace(workspaceId)
16
+ }
@@ -1,4 +1,4 @@
1
- import { ResourceStream } from '@ossy/resources/server'
1
+ import { PatchResourceContent } from '@ossy/resources'
2
2
  import { getBookingResources } from './booking-resources.js'
3
3
  import { BookingSchema } from './schema-ids.js'
4
4
  import BookingReminderEmail from './booking-reminder.email.jsx'
@@ -20,7 +20,7 @@ export async function run({ sdk, log, integrations }) {
20
20
 
21
21
  const allBookings = await getBookingResources({
22
22
  schemaId: BookingSchema.booking,
23
- user: ResourceStream.system('booking-reminder'),
23
+ sdk,
24
24
  })
25
25
 
26
26
  const upcoming = allBookings.filter(b => {
@@ -82,13 +82,10 @@ export async function run({ sdk, log, integrations }) {
82
82
  )
83
83
  }
84
84
 
85
- // Mark reminder as sent via SDK if available, otherwise skip to avoid
86
- // needing direct DB writes in a scheduled task
87
- if (sdk) {
88
- await sdk.actions.run('@ossy/resources/actions/update-content', {
85
+ if (sdk?.invoke) {
86
+ await sdk.invoke(PatchResourceContent, {
89
87
  resourceId: booking.id,
90
- content: { ...booking.content, reminderSentAt: new Date().toISOString() },
91
- workspaceId,
88
+ content: { reminderSentAt: new Date().toISOString() },
92
89
  })
93
90
  }
94
91
 
@@ -0,0 +1,18 @@
1
+ /** Allowed catalog durations (minutes). UI may still present these as select strings. */
2
+ export const SERVICE_DURATION_MINUTES = [30, 60, 90]
3
+
4
+ const ALLOWED = new Set(SERVICE_DURATION_MINUTES)
5
+
6
+ /**
7
+ * Normalize create/update payloads to a number of minutes.
8
+ * Accepts number or numeric string; unknown values fall back to 60.
9
+ *
10
+ * @param {unknown} duration
11
+ * @returns {number}
12
+ */
13
+ export function serviceDurationMinutes (duration) {
14
+ const minutes = Number(duration)
15
+ if (!Number.isFinite(minutes)) return 60
16
+ const rounded = Math.round(minutes)
17
+ return ALLOWED.has(rounded) ? rounded : 60
18
+ }
@@ -0,0 +1,25 @@
1
+ import { describe, it, expect } from '@jest/globals'
2
+ import { serviceDurationMinutes } from './service-duration.js'
3
+
4
+ describe('serviceDurationMinutes', () => {
5
+ it('stores create and update paths as minutes (number)', () => {
6
+ expect(serviceDurationMinutes(30)).toBe(30)
7
+ expect(serviceDurationMinutes(60)).toBe(60)
8
+ expect(serviceDurationMinutes(90)).toBe(90)
9
+ })
10
+
11
+ it('accepts numeric strings from the select UI', () => {
12
+ expect(serviceDurationMinutes('30')).toBe(30)
13
+ expect(serviceDurationMinutes('60')).toBe(60)
14
+ expect(serviceDurationMinutes('90')).toBe(90)
15
+ })
16
+
17
+ it('falls back to 60 for empty or unknown values', () => {
18
+ expect(serviceDurationMinutes(undefined)).toBe(60)
19
+ expect(serviceDurationMinutes(null)).toBe(60)
20
+ expect(serviceDurationMinutes('')).toBe(60)
21
+ expect(serviceDurationMinutes('45')).toBe(60)
22
+ expect(serviceDurationMinutes(45)).toBe(60)
23
+ expect(serviceDurationMinutes(NaN)).toBe(60)
24
+ })
25
+ })
@@ -5,7 +5,10 @@ export default {
5
5
  icon: 'calendar',
6
6
  fields: [
7
7
  { name: 'name', type: 'text', required: true },
8
- { name: 'duration', type: 'select', required: true, options: ['30', '60', '90'] },
8
+ // Minutes as a number on create and update. `options` constrain schema
9
+ // mock / flows to catalog durations (without them faker invents 1–9999).
10
+ // The services form still presents these as a 30/60/90 select.
11
+ { name: 'duration', type: 'number', required: true, options: [30, 60, 90] },
9
12
  { name: 'price', type: 'number' },
10
13
  { name: 'currency', type: 'select', options: ['SEK', 'EUR', 'USD', 'NOK', 'DKK'] },
11
14
  { name: 'description', type: 'textarea' },
@@ -1,4 +1,4 @@
1
- import React, { useState, useEffect, useCallback } from 'react'
1
+ import React, { useState, useEffect, useCallback, useMemo } from 'react'
2
2
  import { View, Text, Button, Alert, Form, FieldFactory, FormStatus, ContentHeader, Page, Overlay, Guide, useLocale } from '@ossy/design-system'
3
3
  import { useSdk } from '@ossy/sdk-react'
4
4
  import { useDocumentValidator } from '@ossy/resources'
@@ -13,6 +13,7 @@ import { metadata as GetServices } from './get-services.action.js'
13
13
  import { metadata as OpenCreateService } from './open-create-service.action.js'
14
14
  import { metadata as ServiceForm } from './service.form.js'
15
15
  import serviceTemplate from './service.schema.js'
16
+ import { SERVICE_DURATION_MINUTES, serviceDurationMinutes } from './service-duration.js'
16
17
  import { invokeErrorMessage } from './invoke-error-message.js'
17
18
 
18
19
  export const metadata = {
@@ -32,6 +33,25 @@ const EMPTY_FORM = {
32
33
  active: true,
33
34
  }
34
35
 
36
+ // Schema stores minutes as a number; the form still presents the catalog as a select.
37
+ const SERVICE_FORM_FIELDS = serviceTemplate.fields.map((field) => (
38
+ field.name === 'duration'
39
+ ? {
40
+ name: 'duration',
41
+ type: 'select',
42
+ required: true,
43
+ options: SERVICE_DURATION_MINUTES.map(String),
44
+ }
45
+ : field
46
+ ))
47
+
48
+ function withDurationMinutes (data) {
49
+ return {
50
+ ...data,
51
+ duration: serviceDurationMinutes(data?.duration),
52
+ }
53
+ }
54
+
35
55
  export default function ServicesPage () {
36
56
  const { t } = useLocale()
37
57
  const sdk = useSdk()
@@ -44,7 +64,11 @@ export default function ServicesPage () {
44
64
  const [saving, setSaving] = useState(false)
45
65
  const [serviceToDelete, setServiceToDelete] = useState(null)
46
66
  const [deleting, setDeleting] = useState(false)
47
- const validate = useDocumentValidator(serviceTemplate)
67
+ const validateDocument = useDocumentValidator(serviceTemplate)
68
+ const validate = useMemo(
69
+ () => (data) => validateDocument(withDurationMinutes(data)),
70
+ [validateDocument],
71
+ )
48
72
 
49
73
  const loadServices = useCallback(async () => {
50
74
  setLoading(true)
@@ -73,7 +97,7 @@ export default function ServicesPage () {
73
97
  setEditingId(service.id)
74
98
  setFormDefaults({
75
99
  name: service.name ?? '',
76
- duration: String(service.duration ?? 60),
100
+ duration: String(serviceDurationMinutes(service.duration)),
77
101
  price: service.price ?? 0,
78
102
  currency: service.currency ?? 'SEK',
79
103
  description: service.description ?? '',
@@ -87,7 +111,8 @@ export default function ServicesPage () {
87
111
  setError(null)
88
112
  try {
89
113
  const bookingAction = editingId ? UpdateService : CreateService
90
- const body = editingId ? { serviceId: editingId, ...data } : data
114
+ const normalized = withDurationMinutes(data)
115
+ const body = editingId ? { serviceId: editingId, ...normalized } : normalized
91
116
  await sdk.invoke(bookingAction, body)
92
117
  setFormOpen(false)
93
118
  await loadServices()
@@ -139,7 +164,7 @@ export default function ServicesPage () {
139
164
  key={editingId ?? 'new'}
140
165
  id={ServiceForm.id}
141
166
  schemaId={ServiceForm.schemaId}
142
- fields={serviceTemplate.fields}
167
+ fields={SERVICE_FORM_FIELDS}
143
168
  defaultData={formDefaults}
144
169
  onSubmit={handleSave}
145
170
  validate={validate}
@@ -23,7 +23,7 @@ export default {
23
23
  { result: { action: OpenEditService, timeout: 10000 } },
24
24
  { action: OpenEditService },
25
25
  { result: { action: UpdateService, timeout: 10000 } },
26
- { form: ServiceForm, fields: { name: 'e2e-updated-service' } },
26
+ { form: ServiceForm, fields: { name: 'e2e-updated-service', duration: '60' } },
27
27
  { action: UpdateService },
28
28
  {
29
29
  result: {
@@ -1,10 +1,11 @@
1
- import { ResourceStream, ResourcesEvents } from '@ossy/resources/server'
1
+ import { PatchResourceContent } from '@ossy/resources'
2
2
  import { BookingSchema } from './schema-ids.js'
3
3
  import { getBookingResources } from './booking-resources.js'
4
+ import { serviceDurationMinutes } from './service-duration.js'
4
5
 
5
6
  export const metadata = { id: '@ossy/booking/tasks/update-service' }
6
7
 
7
- export async function run ({ payload, req, log }) {
8
+ export async function run ({ payload, req, log, sdk }) {
8
9
  const workspaceId = req?.workspaceId
9
10
  const { serviceId, name, duration, price, currency, description, active } = payload ?? {}
10
11
 
@@ -14,12 +15,12 @@ export async function run ({ payload, req, log }) {
14
15
  if (!serviceId) {
15
16
  throw Object.assign(new Error('serviceId is required'), { status: 400 })
16
17
  }
18
+ if (!sdk?.invoke) throw Object.assign(new Error('sdk is required'), { status: 500 })
17
19
 
18
- const actor = ResourceStream.actor({ req, payload })
19
20
  const existing = await getBookingResources({
20
21
  schemaId: BookingSchema.service,
21
22
  belongsTo: workspaceId,
22
- user: actor.kind === 'system' ? actor : actor.user,
23
+ sdk,
23
24
  })
24
25
 
25
26
  const resource = existing.find(r => r.id === serviceId)
@@ -30,7 +31,7 @@ export async function run ({ payload, req, log }) {
30
31
  const content = {
31
32
  ...resource.content,
32
33
  ...(name != null ? { name: String(name).trim() } : {}),
33
- ...(duration != null ? { duration: Number(duration) || 60 } : {}),
34
+ ...(duration != null ? { duration: serviceDurationMinutes(duration) } : {}),
34
35
  ...(price != null ? { price: Number(price) || 0 } : {}),
35
36
  ...(currency != null ? { currency } : {}),
36
37
  ...(description != null ? { description: String(description).trim() } : {}),
@@ -39,14 +40,10 @@ export async function run ({ payload, req, log }) {
39
40
 
40
41
  log?.info(`[booking/tasks/update-service] Updating service ${serviceId}`)
41
42
 
42
- await ResourceStream.mutate(
43
- serviceId,
44
- ResourcesEvents.Patched({
45
- createdBy: req?.userId ?? 'system',
46
- content,
47
- }),
48
- actor,
49
- )
43
+ await sdk.invoke(PatchResourceContent, {
44
+ resourceId: serviceId,
45
+ content,
46
+ })
50
47
 
51
48
  return { id: serviceId, ...content }
52
49
  }