@open-mercato/core 0.6.6-develop.6088.1.e6193c2018 → 0.6.6-develop.6094.1.28b081ea16

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.
@@ -32,7 +32,7 @@ import { Button } from '@open-mercato/ui/primitives/button'
32
32
  import { IconButton } from '@open-mercato/ui/primitives/icon-button'
33
33
  import { SearchInput } from '@open-mercato/ui/primitives/search-input'
34
34
  import { Spinner } from '@open-mercato/ui/primitives/spinner'
35
- import { ErrorNotice } from '@open-mercato/ui/primitives/ErrorNotice'
35
+ import { Alert, AlertDescription, AlertTitle } from '@open-mercato/ui/primitives/alert'
36
36
  import { EmptyState } from '@open-mercato/ui/primitives/empty-state'
37
37
  import {
38
38
  Select,
@@ -2734,17 +2734,18 @@ export default function DealsKanbanPage(): React.ReactElement {
2734
2734
  </div>
2735
2735
  ) : firstError ? (
2736
2736
  <div className="max-w-xl">
2737
- <ErrorNotice
2738
- message={
2739
- firstError instanceof Error
2737
+ <Alert variant="destructive">
2738
+ <AlertTitle>{translateWithFallback(t, 'ui.errors.defaultTitle', 'Something went wrong')}</AlertTitle>
2739
+ <AlertDescription>
2740
+ {firstError instanceof Error
2740
2741
  ? firstError.message
2741
2742
  : translateWithFallback(
2742
2743
  t,
2743
2744
  'customers.deals.pipeline.loadError',
2744
2745
  'Failed to load deals.',
2745
- )
2746
- }
2747
- />
2746
+ )}
2747
+ </AlertDescription>
2748
+ </Alert>
2748
2749
  </div>
2749
2750
  ) : (
2750
2751
  <DndContext
@@ -9,7 +9,7 @@ import { invalidateCustomFieldDefs } from '@open-mercato/ui/backend/utils/custom
9
9
  import { upsertCustomEntitySchema, upsertCustomFieldDefSchema } from '@open-mercato/core/modules/entities/data/validators'
10
10
  import { z } from 'zod'
11
11
  import { Page, PageBody } from '@open-mercato/ui/backend/Page'
12
- import { ErrorNotice } from '@open-mercato/ui/primitives/ErrorNotice'
12
+ import { Alert, AlertDescription, AlertTitle } from '@open-mercato/ui/primitives/alert'
13
13
  import Link from 'next/link'
14
14
  import { Button } from '@open-mercato/ui/primitives/button'
15
15
  import { loadGeneratedFieldRegistrations } from '@open-mercato/ui/backend/fields/registry'
@@ -522,7 +522,10 @@ export default function EditDefinitionsPage({ params }: { params?: { entityId?:
522
522
  <Page>
523
523
  <PageBody>
524
524
  <div className="p-6">
525
- <ErrorNotice title="Invalid entity" message="The requested entity ID is missing or invalid." />
525
+ <Alert variant="destructive">
526
+ <AlertTitle>Invalid entity</AlertTitle>
527
+ <AlertDescription>The requested entity ID is missing or invalid.</AlertDescription>
528
+ </Alert>
526
529
  </div>
527
530
  </PageBody>
528
531
  </Page>
@@ -1,6 +1,7 @@
1
1
  "use client"
2
2
  import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@open-mercato/ui/primitives/card'
3
- import { DataLoader, ErrorNotice } from "@open-mercato/ui";
3
+ import { DataLoader } from "@open-mercato/ui";
4
+ import { Alert, AlertDescription, AlertTitle } from "@open-mercato/ui/primitives/alert";
4
5
  import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
5
6
  import { apiCall, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
6
7
  import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
@@ -68,7 +69,10 @@ export function FeatureToggleOverrideCard({ toggleId }: { toggleId: string }) {
68
69
  <CardTitle>{t('feature_toggles.override.title', 'Override')}</CardTitle>
69
70
  </CardHeader>
70
71
  <CardContent>
71
- <ErrorNotice message={error.message} />
72
+ <Alert variant="destructive">
73
+ <AlertTitle>{t('ui.errors.defaultTitle', 'Something went wrong')}</AlertTitle>
74
+ <AlertDescription>{error.message}</AlertDescription>
75
+ </Alert>
72
76
  </CardContent>
73
77
  </Card>
74
78
  )
@@ -15,6 +15,13 @@ import {
15
15
  import { getMessageType } from '../lib/message-types-registry'
16
16
  import { assertOrganizationAccess, type MessageScopeInput } from './shared'
17
17
 
18
+ const actionStateSnapshotSchema = z.object({
19
+ actionTaken: z.string().nullable(),
20
+ actionTakenByUserId: z.string().nullable(),
21
+ actionTakenAt: z.string().nullable(),
22
+ actionResult: z.record(z.string(), z.unknown()).nullable(),
23
+ })
24
+
18
25
  const recordTerminalActionSchema = z.object({
19
26
  messageId: z.string().uuid(),
20
27
  actionId: z.string().min(1),
@@ -22,6 +29,10 @@ const recordTerminalActionSchema = z.object({
22
29
  tenantId: z.string().uuid(),
23
30
  organizationId: z.string().uuid().nullable(),
24
31
  userId: z.string().uuid(),
32
+ // Optional pre-claim snapshot supplied by `messages.actions.execute` so the
33
+ // undo log records the true (un-taken) state even though the terminal action
34
+ // was atomically claimed before this finalizer runs.
35
+ previousState: actionStateSnapshotSchema.optional(),
25
36
  })
26
37
 
27
38
  type RecordTerminalActionInput = z.infer<typeof recordTerminalActionSchema>
@@ -121,12 +132,35 @@ const recordTerminalActionCommand: CommandHandler<unknown, { ok: true }> = {
121
132
  const input = recordTerminalActionSchema.parse(rawInput)
122
133
  const em = (ctx.container.resolve('em') as EntityManager).fork()
123
134
  const message = await requireActionTarget(em, input)
124
- if (message.actionTaken) {
125
- throw new Error('Action already taken')
135
+ const claimedByCaller =
136
+ message.actionTaken === input.actionId && message.actionTakenByUserId === input.userId
137
+ if (!claimedByCaller) {
138
+ if (message.actionTaken) {
139
+ throw new Error('Action already taken')
140
+ }
141
+ // Atomic compare-and-set: only one concurrent request transitions the
142
+ // message out of the un-taken state. nativeUpdate runs as a single
143
+ // `UPDATE ... WHERE action_taken IS NULL` so the loser matches 0 rows.
144
+ const claimedRows = await em.nativeUpdate(
145
+ Message,
146
+ { id: input.messageId, tenantId: input.tenantId, actionTaken: null, deletedAt: null },
147
+ {
148
+ actionTaken: input.actionId,
149
+ actionTakenByUserId: input.userId,
150
+ actionTakenAt: new Date(),
151
+ },
152
+ )
153
+ if (claimedRows === 0) {
154
+ throw new Error('Action already taken')
155
+ }
156
+ message.actionTaken = input.actionId
157
+ message.actionTakenByUserId = input.userId
158
+ }
159
+ if (!message.actionTakenAt) {
160
+ message.actionTakenAt = new Date()
126
161
  }
127
- message.actionTaken = input.actionId
128
- message.actionTakenByUserId = input.userId
129
- message.actionTakenAt = new Date()
162
+ // action_result is an encrypted column, so it must be written through the
163
+ // flush path (the encryption subscriber) rather than nativeUpdate.
130
164
  message.actionResult = input.result
131
165
  await em.flush()
132
166
  return { ok: true }
@@ -139,6 +173,13 @@ const recordTerminalActionCommand: CommandHandler<unknown, { ok: true }> = {
139
173
  },
140
174
  buildLog: async ({ input, snapshots }) => {
141
175
  const parsed = recordTerminalActionSchema.parse(input)
176
+ // When the action was pre-claimed by `messages.actions.execute`, the
177
+ // prepare-captured snapshot already reflects the claimed state, so prefer
178
+ // the explicit pre-claim snapshot for the undo baseline.
179
+ const before =
180
+ (parsed.previousState as ActionStateSnapshot | undefined) ??
181
+ (snapshots.before as ActionStateSnapshot | undefined) ??
182
+ null
142
183
  return {
143
184
  actionLabel: 'Execute message terminal action',
144
185
  resourceKind: 'messages.message',
@@ -147,11 +188,11 @@ const recordTerminalActionCommand: CommandHandler<unknown, { ok: true }> = {
147
188
  organizationId: parsed.organizationId,
148
189
  payload: {
149
190
  undo: {
150
- before: (snapshots.before as ActionStateSnapshot | undefined) ?? null,
191
+ before,
151
192
  after: (snapshots.after as ActionStateSnapshot | undefined) ?? null,
152
193
  } satisfies UndoPayload<ActionStateSnapshot>,
153
194
  },
154
- snapshotBefore: snapshots.before ?? null,
195
+ snapshotBefore: before,
155
196
  snapshotAfter: snapshots.after ?? null,
156
197
  }
157
198
  },
@@ -209,6 +250,52 @@ const executeActionCommand: CommandHandler<
209
250
  }
210
251
  }
211
252
 
253
+ // Capture the un-taken state for the undo log before reserving the action.
254
+ const previousState = snapshotActionState(message)
255
+ let claimedTerminal = false
256
+ const releaseTerminalClaim = async () => {
257
+ if (!claimedTerminal) return
258
+ claimedTerminal = false
259
+ await em.nativeUpdate(
260
+ Message,
261
+ {
262
+ id: message.id,
263
+ tenantId: input.tenantId,
264
+ actionTaken: action.id,
265
+ actionTakenByUserId: input.userId,
266
+ },
267
+ { actionTaken: null, actionTakenByUserId: null, actionTakenAt: null },
268
+ )
269
+ }
270
+
271
+ if (shouldRecordActionTaken) {
272
+ // Atomically reserve the terminal action BEFORE running the target
273
+ // command so concurrent requests cannot both execute it. The losing
274
+ // request matches 0 rows and surfaces the existing 409 response.
275
+ const claimedRows = await em.nativeUpdate(
276
+ Message,
277
+ { id: message.id, tenantId: input.tenantId, actionTaken: null, deletedAt: null },
278
+ {
279
+ actionTaken: action.id,
280
+ actionTakenByUserId: input.userId,
281
+ actionTakenAt: new Date(),
282
+ },
283
+ )
284
+ if (claimedRows === 0) {
285
+ const current = await findOneWithDecryption(
286
+ em,
287
+ Message,
288
+ { id: message.id, tenantId: input.tenantId, deletedAt: null },
289
+ undefined,
290
+ { tenantId: input.tenantId, organizationId: input.organizationId },
291
+ )
292
+ throw Object.assign(new Error('Action already taken'), {
293
+ actionTaken: current?.actionTaken ?? message.actionTaken ?? action.id,
294
+ })
295
+ }
296
+ claimedTerminal = true
297
+ }
298
+
212
299
  const commandBus = ctx.container.resolve('commandBus') as {
213
300
  execute: (
214
301
  commandId: string,
@@ -263,6 +350,9 @@ const executeActionCommand: CommandHandler<
263
350
  operationLogEntry = commandResult.logEntry ?? null
264
351
  } catch (err) {
265
352
  console.error('[messages] executeActionCommand sub-command failed', err)
353
+ // The target command never completed — release the reservation so the
354
+ // action stays retryable, matching the pre-claim failure semantics.
355
+ await releaseTerminalClaim()
266
356
  throw new Error('Action failed')
267
357
  }
268
358
  } else if (action.href) {
@@ -272,10 +362,12 @@ const executeActionCommand: CommandHandler<
272
362
  userId: input.userId,
273
363
  })
274
364
  if (!safeRedirect) {
365
+ await releaseTerminalClaim()
275
366
  throw new Error('Action has an unsafe redirect target')
276
367
  }
277
368
  result = { redirect: safeRedirect }
278
369
  } else {
370
+ await releaseTerminalClaim()
279
371
  throw new Error('Action has no executable target')
280
372
  }
281
373
 
@@ -288,6 +380,7 @@ const executeActionCommand: CommandHandler<
288
380
  tenantId: input.tenantId,
289
381
  organizationId: input.organizationId,
290
382
  userId: input.userId,
383
+ previousState,
291
384
  },
292
385
  ctx: {
293
386
  container: ctx.container,