@open-mercato/core 0.6.6-develop.6171.1.17de2dc37a → 0.6.6-develop.6176.1.4507b99c2f
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/.turbo/turbo-build.log +1 -1
- package/AGENTS.md +5 -3
- package/agentic/standalone-guide.md +4 -2
- package/dist/modules/customers/api/interactions/encryptedSortPage.js +24 -0
- package/dist/modules/customers/api/interactions/encryptedSortPage.js.map +7 -0
- package/dist/modules/customers/api/interactions/route.js +160 -82
- package/dist/modules/customers/api/interactions/route.js.map +2 -2
- package/dist/modules/customers/api/labels/route.js +24 -2
- package/dist/modules/customers/api/labels/route.js.map +2 -2
- package/dist/modules/resources/backend/resources/resource-types/page.js +25 -2
- package/dist/modules/resources/backend/resources/resource-types/page.js.map +2 -2
- package/dist/modules/resources/backend/resources/resources/[id]/page.js +88 -37
- package/dist/modules/resources/backend/resources/resources/[id]/page.js.map +2 -2
- package/dist/modules/resources/backend/resources/resources/page.js +27 -4
- package/dist/modules/resources/backend/resources/resources/page.js.map +2 -2
- package/dist/modules/resources/components/detail/activitiesAdapter.js +30 -13
- package/dist/modules/resources/components/detail/activitiesAdapter.js.map +2 -2
- package/dist/modules/resources/components/detail/notesAdapter.js +45 -29
- package/dist/modules/resources/components/detail/notesAdapter.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/customers/api/interactions/encryptedSortPage.ts +34 -0
- package/src/modules/customers/api/interactions/route.ts +195 -99
- package/src/modules/customers/api/labels/route.ts +27 -3
- package/src/modules/resources/backend/resources/resource-types/page.tsx +38 -4
- package/src/modules/resources/backend/resources/resources/[id]/page.tsx +102 -37
- package/src/modules/resources/backend/resources/resources/page.tsx +40 -6
- package/src/modules/resources/components/detail/activitiesAdapter.ts +46 -13
- package/src/modules/resources/components/detail/notesAdapter.ts +61 -29
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/customers/api/labels/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { CustomerLabel, CustomerLabelAssignment } from '../../data/entities'\nimport { labelCreateCommandSchema, labelCreateSchema, type LabelCreateCommandInput } from '../../data/validators'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { serializeOperationMetadata } from '@open-mercato/shared/lib/commands/operationMetadata'\nimport { findWithDecryption, findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { resolveLabelActorUserId } from './auth'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport {\n createMissingCustomerLabelTablesError,\n isMissingCustomerLabelTable,\n} from './table-errors'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['customers.people.view'] },\n POST: { requireAuth: true, requireFeatures: ['customers.people.manage'] },\n}\n\nconst querySchema = z.object({\n entityId: z.string().uuid().optional(),\n organizationId: z.string().uuid().optional(),\n ids: z.string().optional(),\n page: z.coerce.number().min(1).default(1),\n pageSize: z.coerce.number().min(1).max(100).default(50),\n search: z.string().optional(),\n})\n\nconst createLabelRequestSchema = labelCreateSchema.extend({\n organizationId: z.string().uuid().optional(),\n})\n\nexport async function GET(req: Request) {\n const { translate } = await resolveTranslations()\n try {\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n const actorUserId = resolveLabelActorUserId(auth)\n if (!auth || !auth.tenantId || !actorUserId) {\n return NextResponse.json({ error: translate('customers.errors.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n\n const em = container.resolve('em') as EntityManager\n const url = new URL(req.url)\n const query = querySchema.parse({\n entityId: url.searchParams.get('entityId') ?? undefined,\n organizationId: url.searchParams.get('organizationId') ?? undefined,\n ids: url.searchParams.get('ids') ?? undefined,\n page: url.searchParams.get('page') ?? undefined,\n pageSize: url.searchParams.get('pageSize') ?? undefined,\n search: url.searchParams.get('search') ?? undefined,\n })\n const scope = await resolveOrganizationScopeForRequest({\n container,\n auth,\n request: req,\n selectedId: query.organizationId ?? undefined,\n })\n const organizationId = scope?.selectedId ?? auth.orgId ?? null\n if (!organizationId) {\n throw new CrudHttpError(400, { error: translate('customers.errors.organization_required', 'Organization context is required') })\n }\n\n // Load all labels for this user\n const labels = await findWithDecryption(em, CustomerLabel, {\n tenantId: auth.tenantId,\n organizationId,\n userId: actorUserId,\n }, { orderBy: { label: 'asc' } }, { tenantId: auth.tenantId, organizationId })\n\n // If entityId provided, also load assignments for that entity\n let assignedLabelIds: string[] = []\n if (query.entityId) {\n const assignments = await findWithDecryption(em, CustomerLabelAssignment, {\n tenantId: auth.tenantId,\n organizationId,\n userId: actorUserId,\n entity: query.entityId,\n } as FilterQuery<CustomerLabelAssignment>, {}, { tenantId: auth.tenantId, organizationId })\n assignedLabelIds = assignments.map((a) => {\n try { return a.label.id } catch { return '' }\n })\n // Handle unloaded references\n if (assignedLabelIds.some((id) => !id)) {\n const loaded = await findWithDecryption(em, CustomerLabelAssignment, {\n tenantId: auth.tenantId,\n organizationId,\n userId: actorUserId,\n entity: query.entityId,\n } as FilterQuery<CustomerLabelAssignment>, { populate: ['label'] }, { tenantId: auth.tenantId, organizationId })\n assignedLabelIds = loaded.map((a) => a.label.id)\n }\n }\n\n const requestedIds = query.ids\n ? new Set(\n query.ids\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean),\n )\n : null\n const scopedLabels = requestedIds\n ? labels.filter((label) => requestedIds.has(label.id))\n : labels\n const filteredLabels = query.search?.trim().length\n ? scopedLabels.filter((label) => label.label.toLowerCase().includes(query.search!.trim().toLowerCase()))\n : scopedLabels\n const total = filteredLabels.length\n const totalPages = Math.max(1, Math.ceil(total / query.pageSize))\n const page = Math.min(query.page, totalPages)\n const start = (page - 1) * query.pageSize\n const items = filteredLabels.slice(start, start + query.pageSize)\n\n return NextResponse.json({\n items: items.map((l) => ({\n id: l.id,\n slug: l.slug,\n label: l.label,\n })),\n assignedIds: assignedLabelIds.filter(Boolean),\n total,\n page,\n pageSize: query.pageSize,\n totalPages,\n })\n } catch (err) {\n if (isMissingCustomerLabelTable(err)) {\n return NextResponse.json({ items: [], assignedIds: [] })\n }\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n console.error('[customers/labels.GET]', err)\n return NextResponse.json({ error: translate('customers.errors.labels_load_failed', 'Failed to load labels') }, { status: 500 })\n }\n}\n\nfunction slugifyLabel(value: string): string {\n return value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n}\n\nexport async function POST(req: Request) {\n try {\n const { translate } = await resolveTranslations()\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n const actorUserId = resolveLabelActorUserId(auth)\n if (!auth || !auth.tenantId || !actorUserId) {\n return NextResponse.json({ error: translate('customers.errors.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n\n const body = createLabelRequestSchema.parse(await readJsonSafe(req, {}))\n const scope = await resolveOrganizationScopeForRequest({\n container,\n auth,\n request: req,\n selectedId: body.organizationId ?? undefined,\n })\n const organizationId = scope?.selectedId ?? auth.orgId ?? null\n if (!organizationId) {\n throw new CrudHttpError(400, { error: translate('customers.errors.organization_required', 'Organization context is required') })\n }\n const slug = body.slug || slugifyLabel(body.label)\n\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId: auth.tenantId,\n organizationId,\n userId: actorUserId,\n resourceKind: 'customers.label',\n resourceId: organizationId,\n operation: 'custom',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: body,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n const commandInput = labelCreateCommandSchema.parse({\n tenantId: auth.tenantId,\n organizationId,\n userId: actorUserId,\n slug,\n label: body.label,\n } satisfies LabelCreateCommandInput)\n\n const commandBus = container.resolve('commandBus') as CommandBus\n const { result, logEntry } = await commandBus.execute<LabelCreateCommandInput, { labelId: string; slug: string; label: string }>(\n 'customers.labels.create',\n {\n input: commandInput,\n ctx: {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: organizationId,\n organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),\n request: req,\n },\n },\n )\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId: auth.tenantId,\n organizationId,\n userId: actorUserId,\n resourceKind: 'customers.label',\n resourceId: organizationId,\n operation: 'custom',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n const response = NextResponse.json({\n id: result.labelId,\n slug: result.slug,\n label: result.label,\n }, { status: 201 })\n if (logEntry?.undoToken && logEntry.id && logEntry.commandId) {\n response.headers.set(\n 'x-om-operation',\n serializeOperationMetadata({\n id: logEntry.id,\n undoToken: logEntry.undoToken,\n commandId: logEntry.commandId,\n actionLabel: logEntry.actionLabel ?? null,\n resourceKind: logEntry.resourceKind ?? 'customers.label',\n resourceId: logEntry.resourceId ?? result.labelId,\n executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : new Date().toISOString(),\n }),\n )\n }\n return response\n } catch (err) {\n if (isMissingCustomerLabelTable(err)) {\n const migrationError = await createMissingCustomerLabelTablesError()\n return NextResponse.json(migrationError.body, { status: migrationError.status })\n }\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n console.error('[customers/labels.POST]', err)\n return NextResponse.json({ error: 'Failed to create label' }, { status: 500 })\n }\n}\n\nconst labelSchema = z.object({\n id: z.string().uuid(),\n slug: z.string(),\n label: z.string(),\n})\n\nconst labelsListSchema = z.object({\n items: z.array(labelSchema),\n assignedIds: z.array(z.string().uuid()),\n total: z.number().int().nonnegative(),\n page: z.number().int().min(1),\n pageSize: z.number().int().min(1),\n totalPages: z.number().int().min(1),\n})\n\nconst errorSchema = z.object({ error: z.string() })\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Customers',\n summary: 'Customer labels (user- and organization-scoped)',\n methods: {\n GET: {\n summary: 'List labels',\n description: 'Returns labels for the current user within the selected organization. Optionally includes assignment status for a specific entity.',\n responses: [\n { status: 200, description: 'Labels list', schema: labelsListSchema },\n ],\n errors: [\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n ],\n },\n POST: {\n summary: 'Create label',\n description: 'Creates a new label scoped to the current user and selected organization.',\n requestBody: { contentType: 'application/json', schema: createLabelRequestSchema },\n responses: [\n { status: 201, description: 'Label created', schema: labelSchema },\n ],\n errors: [\n { status: 409, description: 'Duplicate slug', schema: errorSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,eAAe,+BAA+B;AACvD,SAAS,0BAA0B,yBAAuD;AAC1F,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AACnD,SAAS,eAAe,uBAAuB;AAI/C,SAAS,kCAAkC;AAC3C,SAAS,0BAAiD;AAC1D,SAAS,+BAA+B;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AAE7B,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,u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AAa,IAAI,MAAM,KAAK;AAAA,MACtC,UAAU,IAAI,aAAa,IAAI,UAAU,KAAK;AAAA,MAC9C,QAAQ,IAAI,aAAa,IAAI,QAAQ,KAAK;AAAA,IAC5C,CAAC;AACD,UAAM,QAAQ,MAAM,mCAAmC;AAAA,MACrD;AAAA,MACA;AAAA,MACA,SAAS;AAAA,MACT,YAAY,MAAM,kBAAkB;AAAA,IACtC,CAAC;AACD,UAAM,iBAAiB,OAAO,cAAc,KAAK,SAAS;AAC1D,QAAI,CAAC,gBAAgB;AACnB,YAAM,IAAI,cAAc,KAAK,EAAE,OAAO,UAAU,0CAA0C,kCAAkC,EAAE,CAAC;AAAA,IACjI;
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { CustomerLabel, CustomerLabelAssignment } from '../../data/entities'\nimport { labelCreateCommandSchema, labelCreateSchema, type LabelCreateCommandInput } from '../../data/validators'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { serializeOperationMetadata } from '@open-mercato/shared/lib/commands/operationMetadata'\nimport { findWithDecryption, findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { decryptEntitiesWithFallbackScope } from '@open-mercato/shared/lib/encryption/subscriber'\nimport { mapWithConcurrency } from '@open-mercato/shared/lib/query/bounded-decrypt'\nimport { resolveEncryptedSortMaxRows, sortRowsInMemory } from '@open-mercato/shared/lib/query/encrypted-sort'\nimport { SortDir } from '@open-mercato/shared/lib/query/types'\nimport { resolveLabelActorUserId } from './auth'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport {\n createMissingCustomerLabelTablesError,\n isMissingCustomerLabelTable,\n} from './table-errors'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['customers.people.view'] },\n POST: { requireAuth: true, requireFeatures: ['customers.people.manage'] },\n}\n\nconst DECRYPT_CONCURRENCY = 8\n\nconst querySchema = z.object({\n entityId: z.string().uuid().optional(),\n organizationId: z.string().uuid().optional(),\n ids: z.string().optional(),\n page: z.coerce.number().min(1).default(1),\n pageSize: z.coerce.number().min(1).max(100).default(50),\n search: z.string().optional(),\n})\n\nconst createLabelRequestSchema = labelCreateSchema.extend({\n organizationId: z.string().uuid().optional(),\n})\n\nexport async function GET(req: Request) {\n const { translate } = await resolveTranslations()\n try {\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n const actorUserId = resolveLabelActorUserId(auth)\n if (!auth || !auth.tenantId || !actorUserId) {\n return NextResponse.json({ error: translate('customers.errors.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n\n const em = container.resolve('em') as EntityManager\n const url = new URL(req.url)\n const query = querySchema.parse({\n entityId: url.searchParams.get('entityId') ?? undefined,\n organizationId: url.searchParams.get('organizationId') ?? undefined,\n ids: url.searchParams.get('ids') ?? undefined,\n page: url.searchParams.get('page') ?? undefined,\n pageSize: url.searchParams.get('pageSize') ?? undefined,\n search: url.searchParams.get('search') ?? undefined,\n })\n const scope = await resolveOrganizationScopeForRequest({\n container,\n auth,\n request: req,\n selectedId: query.organizationId ?? undefined,\n })\n const organizationId = scope?.selectedId ?? auth.orgId ?? null\n if (!organizationId) {\n throw new CrudHttpError(400, { error: translate('customers.errors.organization_required', 'Organization context is required') })\n }\n\n // `label` is encrypted at rest; SQL can't sort it meaningfully, so the\n // candidate set is decrypted and sorted in memory below.\n const cap = resolveEncryptedSortMaxRows()\n const candidateLabels = await em.find(CustomerLabel, {\n tenantId: auth.tenantId,\n organizationId,\n userId: actorUserId,\n } as FilterQuery<CustomerLabel>, cap !== null ? { limit: cap, orderBy: { id: 'asc' } } : {})\n if (cap !== null && candidateLabels.length >= cap) {\n console.warn('[customers/labels.GET] encrypted sort candidate scan hit OM_ENCRYPTED_SORT_MAX_ROWS cap; results may be incomplete', {\n cap,\n tenantId: auth.tenantId,\n organizationId,\n })\n }\n\n await mapWithConcurrency(candidateLabels, DECRYPT_CONCURRENCY, (label) =>\n decryptEntitiesWithFallbackScope(label, { em, tenantId: auth.tenantId, organizationId }),\n )\n\n const labels = sortRowsInMemory(\n candidateLabels as unknown as Record<string, unknown>[],\n [{ field: 'label', dir: SortDir.Asc }],\n ) as unknown as CustomerLabel[]\n\n // If entityId provided, also load assignments for that entity\n let assignedLabelIds: string[] = []\n if (query.entityId) {\n const assignments = await findWithDecryption(em, CustomerLabelAssignment, {\n tenantId: auth.tenantId,\n organizationId,\n userId: actorUserId,\n entity: query.entityId,\n } as FilterQuery<CustomerLabelAssignment>, {}, { tenantId: auth.tenantId, organizationId })\n assignedLabelIds = assignments.map((a) => {\n try { return a.label.id } catch { return '' }\n })\n // Handle unloaded references\n if (assignedLabelIds.some((id) => !id)) {\n const loaded = await findWithDecryption(em, CustomerLabelAssignment, {\n tenantId: auth.tenantId,\n organizationId,\n userId: actorUserId,\n entity: query.entityId,\n } as FilterQuery<CustomerLabelAssignment>, { populate: ['label'] }, { tenantId: auth.tenantId, organizationId })\n assignedLabelIds = loaded.map((a) => a.label.id)\n }\n }\n\n const requestedIds = query.ids\n ? new Set(\n query.ids\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean),\n )\n : null\n const scopedLabels = requestedIds\n ? labels.filter((label) => requestedIds.has(label.id))\n : labels\n const filteredLabels = query.search?.trim().length\n ? scopedLabels.filter((label) => label.label.toLowerCase().includes(query.search!.trim().toLowerCase()))\n : scopedLabels\n const total = filteredLabels.length\n const totalPages = Math.max(1, Math.ceil(total / query.pageSize))\n const page = Math.min(query.page, totalPages)\n const start = (page - 1) * query.pageSize\n const items = filteredLabels.slice(start, start + query.pageSize)\n\n return NextResponse.json({\n items: items.map((l) => ({\n id: l.id,\n slug: l.slug,\n label: l.label,\n })),\n assignedIds: assignedLabelIds.filter(Boolean),\n total,\n page,\n pageSize: query.pageSize,\n totalPages,\n })\n } catch (err) {\n if (isMissingCustomerLabelTable(err)) {\n return NextResponse.json({ items: [], assignedIds: [] })\n }\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n console.error('[customers/labels.GET]', err)\n return NextResponse.json({ error: translate('customers.errors.labels_load_failed', 'Failed to load labels') }, { status: 500 })\n }\n}\n\nfunction slugifyLabel(value: string): string {\n return value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n}\n\nexport async function POST(req: Request) {\n try {\n const { translate } = await resolveTranslations()\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n const actorUserId = resolveLabelActorUserId(auth)\n if (!auth || !auth.tenantId || !actorUserId) {\n return NextResponse.json({ error: translate('customers.errors.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n\n const body = createLabelRequestSchema.parse(await readJsonSafe(req, {}))\n const scope = await resolveOrganizationScopeForRequest({\n container,\n auth,\n request: req,\n selectedId: body.organizationId ?? undefined,\n })\n const organizationId = scope?.selectedId ?? auth.orgId ?? null\n if (!organizationId) {\n throw new CrudHttpError(400, { error: translate('customers.errors.organization_required', 'Organization context is required') })\n }\n const slug = body.slug || slugifyLabel(body.label)\n\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId: auth.tenantId,\n organizationId,\n userId: actorUserId,\n resourceKind: 'customers.label',\n resourceId: organizationId,\n operation: 'custom',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: body,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n const commandInput = labelCreateCommandSchema.parse({\n tenantId: auth.tenantId,\n organizationId,\n userId: actorUserId,\n slug,\n label: body.label,\n } satisfies LabelCreateCommandInput)\n\n const commandBus = container.resolve('commandBus') as CommandBus\n const { result, logEntry } = await commandBus.execute<LabelCreateCommandInput, { labelId: string; slug: string; label: string }>(\n 'customers.labels.create',\n {\n input: commandInput,\n ctx: {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: organizationId,\n organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),\n request: req,\n },\n },\n )\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId: auth.tenantId,\n organizationId,\n userId: actorUserId,\n resourceKind: 'customers.label',\n resourceId: organizationId,\n operation: 'custom',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n const response = NextResponse.json({\n id: result.labelId,\n slug: result.slug,\n label: result.label,\n }, { status: 201 })\n if (logEntry?.undoToken && logEntry.id && logEntry.commandId) {\n response.headers.set(\n 'x-om-operation',\n serializeOperationMetadata({\n id: logEntry.id,\n undoToken: logEntry.undoToken,\n commandId: logEntry.commandId,\n actionLabel: logEntry.actionLabel ?? null,\n resourceKind: logEntry.resourceKind ?? 'customers.label',\n resourceId: logEntry.resourceId ?? result.labelId,\n executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : new Date().toISOString(),\n }),\n )\n }\n return response\n } catch (err) {\n if (isMissingCustomerLabelTable(err)) {\n const migrationError = await createMissingCustomerLabelTablesError()\n return NextResponse.json(migrationError.body, { status: migrationError.status })\n }\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n console.error('[customers/labels.POST]', err)\n return NextResponse.json({ error: 'Failed to create label' }, { status: 500 })\n }\n}\n\nconst labelSchema = z.object({\n id: z.string().uuid(),\n slug: z.string(),\n label: z.string(),\n})\n\nconst labelsListSchema = z.object({\n items: z.array(labelSchema),\n assignedIds: z.array(z.string().uuid()),\n total: z.number().int().nonnegative(),\n page: z.number().int().min(1),\n pageSize: z.number().int().min(1),\n totalPages: z.number().int().min(1),\n})\n\nconst errorSchema = z.object({ error: z.string() })\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Customers',\n summary: 'Customer labels (user- and organization-scoped)',\n methods: {\n GET: {\n summary: 'List labels',\n description: 'Returns labels for the current user within the selected organization. Optionally includes assignment status for a specific entity.',\n responses: [\n { status: 200, description: 'Labels list', schema: labelsListSchema },\n ],\n errors: [\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n ],\n },\n POST: {\n summary: 'Create label',\n description: 'Creates a new label scoped to the current user and selected organization.',\n requestBody: { contentType: 'application/json', schema: createLabelRequestSchema },\n responses: [\n { status: 201, description: 'Label created', schema: labelSchema },\n ],\n errors: [\n { status: 409, description: 'Duplicate slug', schema: errorSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,eAAe,+BAA+B;AACvD,SAAS,0BAA0B,yBAAuD;AAC1F,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AACnD,SAAS,eAAe,uBAAuB;AAI/C,SAAS,kCAAkC;AAC3C,SAAS,0BAAiD;AAC1D,SAAS,wCAAwC;AACjD,SAAS,0BAA0B;AACnC,SAAS,6BAA6B,wBAAwB;AAC9D,SAAS,eAAe;AACxB,SAAS,+BAA+B;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AAE7B,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,uBAAuB,EAAE;AAAA,EACrE,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAA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1B,aAAa,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC;AAAA,EACtC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY;AAAA,EACpC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,EAC5B,UAAU,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,EAChC,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AACpC,CAAC;AAED,MAAM,cAAc,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAE3C,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aAAa;AAAA,MACb,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,eAAe,QAAQ,iBAAiB;AAAA,MACtE;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,YAAY;AAAA,MAClE;AAAA,IACF;AAAA,IACA,MAAM;AAAA,MACJ,SAAS;AAAA,MACT,aAAa;AAAA,MACb,aAAa,EAAE,aAAa,oBAAoB,QAAQ,yBAAyB;AAAA,MACjF,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,iBAAiB,QAAQ,YAAY;AAAA,MACnE;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,YAAY;AAAA,MACpE;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -12,6 +12,7 @@ import { flash } from "@open-mercato/ui/backend/FlashMessages";
|
|
|
12
12
|
import { readApiResultOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
|
|
13
13
|
import { deleteCrud } from "@open-mercato/ui/backend/utils/crud";
|
|
14
14
|
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
|
|
15
|
+
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
|
|
15
16
|
import { renderDictionaryColor, renderDictionaryIcon } from "@open-mercato/core/modules/dictionaries/components/dictionaryAppearance";
|
|
16
17
|
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
|
|
17
18
|
import { Package } from "lucide-react";
|
|
@@ -21,6 +22,7 @@ import { formatDateTime } from "@open-mercato/shared/lib/time";
|
|
|
21
22
|
const PAGE_SIZE = 50;
|
|
22
23
|
const DESCRIPTION_CLASSNAME = "line-clamp-3 whitespace-pre-line text-sm text-foreground";
|
|
23
24
|
const SUBTEXT_CLASSNAME = "line-clamp-2 text-xs text-muted-foreground";
|
|
25
|
+
const RESOURCE_TYPES_MUTATION_CONTEXT_ID = "resources.resource-types.list";
|
|
24
26
|
function ResourcesResourceTypesPage() {
|
|
25
27
|
const translate = useT();
|
|
26
28
|
const { confirm, ConfirmDialogElement } = useConfirmDialog();
|
|
@@ -34,6 +36,23 @@ function ResourcesResourceTypesPage() {
|
|
|
34
36
|
const [search, setSearch] = React.useState("");
|
|
35
37
|
const [isLoading, setIsLoading] = React.useState(true);
|
|
36
38
|
const [reloadToken, setReloadToken] = React.useState(0);
|
|
39
|
+
const { runMutation, retryLastMutation } = useGuardedMutation({
|
|
40
|
+
contextId: RESOURCE_TYPES_MUTATION_CONTEXT_ID,
|
|
41
|
+
blockedMessage: translate("ui.forms.flash.saveBlocked", "Save blocked by validation")
|
|
42
|
+
});
|
|
43
|
+
const runResourceTypeMutation = React.useCallback(
|
|
44
|
+
async (operation, mutationPayload, resourceId) => runMutation({
|
|
45
|
+
operation,
|
|
46
|
+
mutationPayload,
|
|
47
|
+
context: {
|
|
48
|
+
formId: RESOURCE_TYPES_MUTATION_CONTEXT_ID,
|
|
49
|
+
resourceKind: "resources.resourceType",
|
|
50
|
+
resourceId,
|
|
51
|
+
retryLastMutation
|
|
52
|
+
}
|
|
53
|
+
}),
|
|
54
|
+
[retryLastMutation, runMutation]
|
|
55
|
+
);
|
|
37
56
|
const translations = React.useMemo(() => ({
|
|
38
57
|
title: translate("resources.resourceTypes.page.title", "Resource types"),
|
|
39
58
|
description: translate("resources.resourceTypes.page.description", "Organize shared resources by category."),
|
|
@@ -190,14 +209,18 @@ function ResourcesResourceTypesPage() {
|
|
|
190
209
|
if (!confirmed) return;
|
|
191
210
|
try {
|
|
192
211
|
const headers = buildOptimisticLockHeader(entry.updatedAt);
|
|
193
|
-
await
|
|
212
|
+
await runResourceTypeMutation(
|
|
213
|
+
() => withScopedApiRequestHeaders(headers, () => deleteCrud("resources/resource-types", entry.id, { errorMessage: translations.errors.delete })),
|
|
214
|
+
{ operation: "deleteResourceType", id: entry.id, updatedAt: entry.updatedAt ?? null },
|
|
215
|
+
entry.id
|
|
216
|
+
);
|
|
194
217
|
flash(translations.messages.deleted, "success");
|
|
195
218
|
handleRefresh();
|
|
196
219
|
} catch (error) {
|
|
197
220
|
console.error("resources.resource-types.delete", error);
|
|
198
221
|
flash(translations.errors.delete, "error");
|
|
199
222
|
}
|
|
200
|
-
}, [confirm, handleRefresh, translations.actions.deleteConfirm, translations.errors.delete, translations.errors.deleteAssigned, translations.messages.deleted]);
|
|
223
|
+
}, [confirm, handleRefresh, runResourceTypeMutation, translations.actions.deleteConfirm, translations.errors.delete, translations.errors.deleteAssigned, translations.messages.deleted]);
|
|
201
224
|
return /* @__PURE__ */ jsxs(Page, { children: [
|
|
202
225
|
/* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
|
|
203
226
|
DataTable,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/resources/backend/resources/resource-types/page.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { useRouter } from 'next/navigation'\nimport Link from 'next/link'\nimport type { ColumnDef, SortingState } from '@tanstack/react-table'\nimport { Page, PageBody } from '@open-mercato/ui/backend/Page'\nimport { markdownToPlainText } from '@open-mercato/ui/backend/markdown/markdownToPlainText'\nimport { DataTable, withDataTableNamespaces } from '@open-mercato/ui/backend/DataTable'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { RowActions } from '@open-mercato/ui/backend/RowActions'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { readApiResultOrThrow, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { deleteCrud } from '@open-mercato/ui/backend/utils/crud'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { renderDictionaryColor, renderDictionaryIcon } from '@open-mercato/core/modules/dictionaries/components/dictionaryAppearance'\nimport { useConfirmDialog } from '@open-mercato/ui/backend/confirm-dialog'\nimport { Package } from 'lucide-react'\nimport { useOrganizationScopeVersion } from '@open-mercato/shared/lib/frontend/useOrganizationScope'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { formatDateTime } from '@open-mercato/shared/lib/time'\n\nconst PAGE_SIZE = 50\nconst DESCRIPTION_CLASSNAME = 'line-clamp-3 whitespace-pre-line text-sm text-foreground'\nconst SUBTEXT_CLASSNAME = 'line-clamp-2 text-xs text-muted-foreground'\n\ntype ResourceTypeRow = {\n id: string\n name: string\n description: string | null\n appearanceIcon: string | null\n appearanceColor: string | null\n updatedAt: string | null\n resourceCount: number\n}\n\ntype ResourceTypesResponse = {\n items?: Array<Record<string, unknown>>\n total?: number\n totalPages?: number\n}\n\nexport default function ResourcesResourceTypesPage() {\n const translate = useT()\n const { confirm, ConfirmDialogElement } = useConfirmDialog()\n const router = useRouter()\n const scopeVersion = useOrganizationScopeVersion()\n const [rows, setRows] = React.useState<ResourceTypeRow[]>([])\n const [page, setPage] = React.useState(1)\n const [total, setTotal] = React.useState(0)\n const [totalPages, setTotalPages] = React.useState(1)\n const [sorting, setSorting] = React.useState<SortingState>([{ id: 'name', desc: false }])\n const [search, setSearch] = React.useState('')\n const [isLoading, setIsLoading] = React.useState(true)\n const [reloadToken, setReloadToken] = React.useState(0)\n\n const translations = React.useMemo(() => ({\n title: translate('resources.resourceTypes.page.title', 'Resource types'),\n description: translate('resources.resourceTypes.page.description', 'Organize shared resources by category.'),\n table: {\n name: translate('resources.resourceTypes.table.name', 'Name'),\n description: translate('resources.resourceTypes.table.description', 'Description'),\n appearance: translate('resources.resourceTypes.table.appearance', 'Appearance'),\n resources: translate('resources.resourceTypes.table.resources', 'Resources'),\n updatedAt: translate('resources.resourceTypes.table.updatedAt', 'Updated'),\n empty: translate('resources.resourceTypes.table.empty', 'No resource types yet.'),\n search: translate('resources.resourceTypes.table.search', 'Search resource types\u2026'),\n },\n actions: {\n add: translate('resources.resourceTypes.actions.add', 'Add resource type'),\n edit: translate('resources.resourceTypes.actions.edit', 'Edit'),\n delete: translate('resources.resourceTypes.actions.delete', 'Delete'),\n deleteConfirm: translate('resources.resourceTypes.actions.deleteConfirm', 'Delete resource type \"{{name}}\"?'),\n showResources: translate('resources.resourceTypes.actions.showResources', 'Show resources ({{count}})'),\n refresh: translate('resources.resourceTypes.actions.refresh', 'Refresh'),\n },\n form: {\n createTitle: translate('resources.resourceTypes.form.createTitle', 'Add resource type'),\n editTitle: translate('resources.resourceTypes.form.editTitle', 'Edit resource type'),\n name: translate('resources.resourceTypes.form.name', 'Name'),\n description: translate('resources.resourceTypes.form.description', 'Description'),\n save: translate('resources.resourceTypes.form.save', 'Save'),\n cancel: translate('resources.resourceTypes.form.cancel', 'Cancel'),\n },\n messages: {\n saved: translate('resources.resourceTypes.messages.saved', 'Resource type saved.'),\n deleted: translate('resources.resourceTypes.messages.deleted', 'Resource type deleted.'),\n },\n errors: {\n load: translate('resources.resourceTypes.errors.load', 'Failed to load resource types.'),\n save: translate('resources.resourceTypes.errors.save', 'Failed to save resource type.'),\n delete: translate('resources.resourceTypes.errors.delete', 'Failed to delete resource type.'),\n deleteAssigned: translate('resources.resourceTypes.errors.deleteAssigned', 'Resource type has assigned resources.'),\n },\n }), [translate])\n\n const columns = React.useMemo<ColumnDef<ResourceTypeRow>[]>(() => [\n {\n accessorKey: 'name',\n header: translations.table.name,\n meta: { priority: 1, sticky: true },\n cell: ({ row }) => (\n <div className=\"flex flex-col\">\n <span className=\"font-medium\">{row.original.name}</span>\n {row.original.description ? (\n <span className={SUBTEXT_CLASSNAME}>\n {markdownToPlainText(row.original.description)}\n </span>\n ) : null}\n </div>\n ),\n },\n {\n accessorKey: 'appearance',\n header: translations.table.appearance,\n meta: { priority: 2 },\n cell: ({ row }) => {\n const icon = row.original.appearanceIcon\n const color = row.original.appearanceColor\n if (!icon && !color) {\n return <span className=\"text-xs text-muted-foreground\">\u2014</span>\n }\n return (\n <div className=\"flex items-center gap-2\">\n {color ? renderDictionaryColor(color) : null}\n {icon ? renderDictionaryIcon(icon) : null}\n </div>\n )\n },\n },\n {\n accessorKey: 'resourceCount',\n header: translations.table.resources,\n meta: { priority: 3 },\n cell: ({ row }) => (\n <Link\n className=\"inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground\"\n href={`/backend/resources/resources?resourceTypeId=${encodeURIComponent(row.original.id)}`}\n onClick={(event) => event.stopPropagation()}\n >\n <Package className=\"h-4 w-4\" aria-hidden />\n {translations.actions.showResources.replace('{{count}}', String(row.original.resourceCount))}\n </Link>\n ),\n },\n {\n accessorKey: 'description',\n header: translations.table.description,\n meta: { priority: 5 },\n cell: ({ row }) => row.original.description ? (\n <span className={DESCRIPTION_CLASSNAME}>\n {markdownToPlainText(row.original.description)}\n </span>\n ) : (\n <span className=\"text-xs text-muted-foreground\">\u2014</span>\n ),\n },\n {\n accessorKey: 'updatedAt',\n header: translations.table.updatedAt,\n meta: { priority: 4 },\n cell: ({ row }) => row.original.updatedAt\n ? <span className=\"text-xs text-muted-foreground\">{formatDateTime(row.original.updatedAt)}</span>\n : <span className=\"text-xs text-muted-foreground\">\u2014</span>,\n },\n ], [\n translations.actions.showResources,\n translations.table.appearance,\n translations.table.description,\n translations.table.name,\n translations.table.resources,\n translations.table.updatedAt,\n ])\n\n const loadResourceTypes = React.useCallback(async () => {\n setIsLoading(true)\n try {\n const params = new URLSearchParams({\n page: String(page),\n pageSize: String(PAGE_SIZE),\n })\n const sort = sorting[0]\n if (sort?.id) {\n params.set('sortField', sort.id)\n params.set('sortDir', sort.desc ? 'desc' : 'asc')\n }\n if (search.trim()) {\n params.set('search', search.trim())\n }\n const payload = await readApiResultOrThrow<ResourceTypesResponse>(\n `/api/resources/resource-types?${params.toString()}`,\n undefined,\n { errorMessage: translations.errors.load, fallback: { items: [], total: 0, totalPages: 1 } },\n )\n const items = Array.isArray(payload.items) ? payload.items : []\n setRows(items.map(mapApiResourceType))\n setTotal(typeof payload.total === 'number' ? payload.total : items.length)\n setTotalPages(typeof payload.totalPages === 'number' ? payload.totalPages : Math.max(1, Math.ceil(items.length / PAGE_SIZE)))\n } catch (error) {\n console.error('resources.resource-types.list', error)\n flash(translations.errors.load, 'error')\n } finally {\n setIsLoading(false)\n }\n }, [page, search, sorting, translations.errors.load])\n\n React.useEffect(() => {\n void loadResourceTypes()\n }, [loadResourceTypes, scopeVersion, reloadToken])\n\n const handleSearchChange = React.useCallback((value: string) => {\n setSearch(value)\n setPage(1)\n }, [])\n\n const handleRefresh = React.useCallback(() => {\n setReloadToken((token) => token + 1)\n }, [])\n\n const handleDelete = React.useCallback(async (entry: ResourceTypeRow) => {\n if (entry.resourceCount > 0) {\n flash(translations.errors.deleteAssigned, 'error')\n return\n }\n const message = translations.actions.deleteConfirm.replace('{{name}}', entry.name)\n const confirmed = await confirm({\n title: message,\n variant: 'destructive',\n })\n if (!confirmed) return\n try {\n const headers = buildOptimisticLockHeader(entry.updatedAt)\n await withScopedApiRequestHeaders(headers, () => (\n deleteCrud('resources/resource-types', entry.id, { errorMessage: translations.errors.delete })\n ))\n flash(translations.messages.deleted, 'success')\n handleRefresh()\n } catch (error) {\n console.error('resources.resource-types.delete', error)\n flash(translations.errors.delete, 'error')\n }\n }, [confirm, handleRefresh, translations.actions.deleteConfirm, translations.errors.delete, translations.errors.deleteAssigned, translations.messages.deleted])\n\n return (\n <Page>\n <PageBody>\n <DataTable<ResourceTypeRow>\n title={translations.title}\n data={rows}\n columns={columns}\n isLoading={isLoading}\n searchValue={search}\n onSearchChange={handleSearchChange}\n searchPlaceholder={translations.table.search}\n emptyState={<p className=\"py-8 text-center text-sm text-muted-foreground\">{translations.table.empty}</p>}\n actions={(\n <Button asChild size=\"sm\">\n <Link href=\"/backend/resources/resource-types/create\">\n {translations.actions.add}\n </Link>\n </Button>\n )}\n refreshButton={{\n label: translations.actions.refresh,\n onRefresh: handleRefresh,\n isRefreshing: isLoading,\n }}\n sortable\n sorting={sorting}\n onSortingChange={setSorting}\n pagination={{ page, pageSize: PAGE_SIZE, total, totalPages, onPageChange: setPage }}\n rowActions={(row) => (\n <RowActions\n items={[\n { id: 'edit', label: translations.actions.edit, href: `/backend/resources/resource-types/${row.id}/edit` },\n ...(row.resourceCount > 0\n ? []\n : [{ id: 'delete', label: translations.actions.delete, destructive: true, onSelect: () => handleDelete(row) }]),\n ]}\n />\n )}\n onRowClick={(row) => router.push(`/backend/resources/resource-types/${row.id}/edit`)}\n perspective={{ tableId: 'resources.resource-types.list' }}\n />\n </PageBody>\n {ConfirmDialogElement}\n </Page>\n )\n}\n\nfunction mapApiResourceType(item: Record<string, unknown>): ResourceTypeRow {\n const id = typeof item.id === 'string' ? item.id : ''\n const name = typeof item.name === 'string' && item.name.length ? item.name : id\n const description = typeof item.description === 'string' && item.description.length\n ? item.description\n : typeof item.description === 'string'\n ? item.description\n : null\n const appearanceIcon = typeof item.appearanceIcon === 'string'\n ? item.appearanceIcon\n : typeof item.appearance_icon === 'string'\n ? item.appearance_icon\n : null\n const appearanceColor = typeof item.appearanceColor === 'string'\n ? item.appearanceColor\n : typeof item.appearance_color === 'string'\n ? item.appearance_color\n : null\n const updatedAt = typeof item.updatedAt === 'string'\n ? item.updatedAt\n : typeof item.updated_at === 'string'\n ? item.updated_at\n : null\n const resourceCount = typeof item.resourceCount === 'number'\n ? item.resourceCount\n : typeof item.resource_count === 'number'\n ? item.resource_count\n : 0\n return withDataTableNamespaces({ id, name, description, appearanceIcon, appearanceColor, updatedAt, resourceCount }, item)\n}\n"],
|
|
5
|
-
"mappings": ";
|
|
4
|
+
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { useRouter } from 'next/navigation'\nimport Link from 'next/link'\nimport type { ColumnDef, SortingState } from '@tanstack/react-table'\nimport { Page, PageBody } from '@open-mercato/ui/backend/Page'\nimport { markdownToPlainText } from '@open-mercato/ui/backend/markdown/markdownToPlainText'\nimport { DataTable, withDataTableNamespaces } from '@open-mercato/ui/backend/DataTable'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { RowActions } from '@open-mercato/ui/backend/RowActions'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { readApiResultOrThrow, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { deleteCrud } from '@open-mercato/ui/backend/utils/crud'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { renderDictionaryColor, renderDictionaryIcon } from '@open-mercato/core/modules/dictionaries/components/dictionaryAppearance'\nimport { useConfirmDialog } from '@open-mercato/ui/backend/confirm-dialog'\nimport { Package } from 'lucide-react'\nimport { useOrganizationScopeVersion } from '@open-mercato/shared/lib/frontend/useOrganizationScope'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { formatDateTime } from '@open-mercato/shared/lib/time'\n\nconst PAGE_SIZE = 50\nconst DESCRIPTION_CLASSNAME = 'line-clamp-3 whitespace-pre-line text-sm text-foreground'\nconst SUBTEXT_CLASSNAME = 'line-clamp-2 text-xs text-muted-foreground'\nconst RESOURCE_TYPES_MUTATION_CONTEXT_ID = 'resources.resource-types.list'\n\ntype ResourceTypeRow = {\n id: string\n name: string\n description: string | null\n appearanceIcon: string | null\n appearanceColor: string | null\n updatedAt: string | null\n resourceCount: number\n}\n\ntype ResourceTypesResponse = {\n items?: Array<Record<string, unknown>>\n total?: number\n totalPages?: number\n}\n\ntype ResourceTypesMutationContext = {\n formId: string\n resourceKind: string\n resourceId?: string\n retryLastMutation: () => Promise<boolean>\n}\n\nexport default function ResourcesResourceTypesPage() {\n const translate = useT()\n const { confirm, ConfirmDialogElement } = useConfirmDialog()\n const router = useRouter()\n const scopeVersion = useOrganizationScopeVersion()\n const [rows, setRows] = React.useState<ResourceTypeRow[]>([])\n const [page, setPage] = React.useState(1)\n const [total, setTotal] = React.useState(0)\n const [totalPages, setTotalPages] = React.useState(1)\n const [sorting, setSorting] = React.useState<SortingState>([{ id: 'name', desc: false }])\n const [search, setSearch] = React.useState('')\n const [isLoading, setIsLoading] = React.useState(true)\n const [reloadToken, setReloadToken] = React.useState(0)\n const { runMutation, retryLastMutation } = useGuardedMutation<ResourceTypesMutationContext>({\n contextId: RESOURCE_TYPES_MUTATION_CONTEXT_ID,\n blockedMessage: translate('ui.forms.flash.saveBlocked', 'Save blocked by validation'),\n })\n const runResourceTypeMutation = React.useCallback(\n async <T,>(\n operation: () => Promise<T>,\n mutationPayload: Record<string, unknown>,\n resourceId?: string,\n ): Promise<T> => runMutation({\n operation,\n mutationPayload,\n context: {\n formId: RESOURCE_TYPES_MUTATION_CONTEXT_ID,\n resourceKind: 'resources.resourceType',\n resourceId,\n retryLastMutation,\n },\n }),\n [retryLastMutation, runMutation],\n )\n\n const translations = React.useMemo(() => ({\n title: translate('resources.resourceTypes.page.title', 'Resource types'),\n description: translate('resources.resourceTypes.page.description', 'Organize shared resources by category.'),\n table: {\n name: translate('resources.resourceTypes.table.name', 'Name'),\n description: translate('resources.resourceTypes.table.description', 'Description'),\n appearance: translate('resources.resourceTypes.table.appearance', 'Appearance'),\n resources: translate('resources.resourceTypes.table.resources', 'Resources'),\n updatedAt: translate('resources.resourceTypes.table.updatedAt', 'Updated'),\n empty: translate('resources.resourceTypes.table.empty', 'No resource types yet.'),\n search: translate('resources.resourceTypes.table.search', 'Search resource types\u2026'),\n },\n actions: {\n add: translate('resources.resourceTypes.actions.add', 'Add resource type'),\n edit: translate('resources.resourceTypes.actions.edit', 'Edit'),\n delete: translate('resources.resourceTypes.actions.delete', 'Delete'),\n deleteConfirm: translate('resources.resourceTypes.actions.deleteConfirm', 'Delete resource type \"{{name}}\"?'),\n showResources: translate('resources.resourceTypes.actions.showResources', 'Show resources ({{count}})'),\n refresh: translate('resources.resourceTypes.actions.refresh', 'Refresh'),\n },\n form: {\n createTitle: translate('resources.resourceTypes.form.createTitle', 'Add resource type'),\n editTitle: translate('resources.resourceTypes.form.editTitle', 'Edit resource type'),\n name: translate('resources.resourceTypes.form.name', 'Name'),\n description: translate('resources.resourceTypes.form.description', 'Description'),\n save: translate('resources.resourceTypes.form.save', 'Save'),\n cancel: translate('resources.resourceTypes.form.cancel', 'Cancel'),\n },\n messages: {\n saved: translate('resources.resourceTypes.messages.saved', 'Resource type saved.'),\n deleted: translate('resources.resourceTypes.messages.deleted', 'Resource type deleted.'),\n },\n errors: {\n load: translate('resources.resourceTypes.errors.load', 'Failed to load resource types.'),\n save: translate('resources.resourceTypes.errors.save', 'Failed to save resource type.'),\n delete: translate('resources.resourceTypes.errors.delete', 'Failed to delete resource type.'),\n deleteAssigned: translate('resources.resourceTypes.errors.deleteAssigned', 'Resource type has assigned resources.'),\n },\n }), [translate])\n\n const columns = React.useMemo<ColumnDef<ResourceTypeRow>[]>(() => [\n {\n accessorKey: 'name',\n header: translations.table.name,\n meta: { priority: 1, sticky: true },\n cell: ({ row }) => (\n <div className=\"flex flex-col\">\n <span className=\"font-medium\">{row.original.name}</span>\n {row.original.description ? (\n <span className={SUBTEXT_CLASSNAME}>\n {markdownToPlainText(row.original.description)}\n </span>\n ) : null}\n </div>\n ),\n },\n {\n accessorKey: 'appearance',\n header: translations.table.appearance,\n meta: { priority: 2 },\n cell: ({ row }) => {\n const icon = row.original.appearanceIcon\n const color = row.original.appearanceColor\n if (!icon && !color) {\n return <span className=\"text-xs text-muted-foreground\">\u2014</span>\n }\n return (\n <div className=\"flex items-center gap-2\">\n {color ? renderDictionaryColor(color) : null}\n {icon ? renderDictionaryIcon(icon) : null}\n </div>\n )\n },\n },\n {\n accessorKey: 'resourceCount',\n header: translations.table.resources,\n meta: { priority: 3 },\n cell: ({ row }) => (\n <Link\n className=\"inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground\"\n href={`/backend/resources/resources?resourceTypeId=${encodeURIComponent(row.original.id)}`}\n onClick={(event) => event.stopPropagation()}\n >\n <Package className=\"h-4 w-4\" aria-hidden />\n {translations.actions.showResources.replace('{{count}}', String(row.original.resourceCount))}\n </Link>\n ),\n },\n {\n accessorKey: 'description',\n header: translations.table.description,\n meta: { priority: 5 },\n cell: ({ row }) => row.original.description ? (\n <span className={DESCRIPTION_CLASSNAME}>\n {markdownToPlainText(row.original.description)}\n </span>\n ) : (\n <span className=\"text-xs text-muted-foreground\">\u2014</span>\n ),\n },\n {\n accessorKey: 'updatedAt',\n header: translations.table.updatedAt,\n meta: { priority: 4 },\n cell: ({ row }) => row.original.updatedAt\n ? <span className=\"text-xs text-muted-foreground\">{formatDateTime(row.original.updatedAt)}</span>\n : <span className=\"text-xs text-muted-foreground\">\u2014</span>,\n },\n ], [\n translations.actions.showResources,\n translations.table.appearance,\n translations.table.description,\n translations.table.name,\n translations.table.resources,\n translations.table.updatedAt,\n ])\n\n const loadResourceTypes = React.useCallback(async () => {\n setIsLoading(true)\n try {\n const params = new URLSearchParams({\n page: String(page),\n pageSize: String(PAGE_SIZE),\n })\n const sort = sorting[0]\n if (sort?.id) {\n params.set('sortField', sort.id)\n params.set('sortDir', sort.desc ? 'desc' : 'asc')\n }\n if (search.trim()) {\n params.set('search', search.trim())\n }\n const payload = await readApiResultOrThrow<ResourceTypesResponse>(\n `/api/resources/resource-types?${params.toString()}`,\n undefined,\n { errorMessage: translations.errors.load, fallback: { items: [], total: 0, totalPages: 1 } },\n )\n const items = Array.isArray(payload.items) ? payload.items : []\n setRows(items.map(mapApiResourceType))\n setTotal(typeof payload.total === 'number' ? payload.total : items.length)\n setTotalPages(typeof payload.totalPages === 'number' ? payload.totalPages : Math.max(1, Math.ceil(items.length / PAGE_SIZE)))\n } catch (error) {\n console.error('resources.resource-types.list', error)\n flash(translations.errors.load, 'error')\n } finally {\n setIsLoading(false)\n }\n }, [page, search, sorting, translations.errors.load])\n\n React.useEffect(() => {\n void loadResourceTypes()\n }, [loadResourceTypes, scopeVersion, reloadToken])\n\n const handleSearchChange = React.useCallback((value: string) => {\n setSearch(value)\n setPage(1)\n }, [])\n\n const handleRefresh = React.useCallback(() => {\n setReloadToken((token) => token + 1)\n }, [])\n\n const handleDelete = React.useCallback(async (entry: ResourceTypeRow) => {\n if (entry.resourceCount > 0) {\n flash(translations.errors.deleteAssigned, 'error')\n return\n }\n const message = translations.actions.deleteConfirm.replace('{{name}}', entry.name)\n const confirmed = await confirm({\n title: message,\n variant: 'destructive',\n })\n if (!confirmed) return\n try {\n const headers = buildOptimisticLockHeader(entry.updatedAt)\n await runResourceTypeMutation(\n () => withScopedApiRequestHeaders(headers, () => (\n deleteCrud('resources/resource-types', entry.id, { errorMessage: translations.errors.delete })\n )),\n { operation: 'deleteResourceType', id: entry.id, updatedAt: entry.updatedAt ?? null },\n entry.id,\n )\n flash(translations.messages.deleted, 'success')\n handleRefresh()\n } catch (error) {\n console.error('resources.resource-types.delete', error)\n flash(translations.errors.delete, 'error')\n }\n }, [confirm, handleRefresh, runResourceTypeMutation, translations.actions.deleteConfirm, translations.errors.delete, translations.errors.deleteAssigned, translations.messages.deleted])\n\n return (\n <Page>\n <PageBody>\n <DataTable<ResourceTypeRow>\n title={translations.title}\n data={rows}\n columns={columns}\n isLoading={isLoading}\n searchValue={search}\n onSearchChange={handleSearchChange}\n searchPlaceholder={translations.table.search}\n emptyState={<p className=\"py-8 text-center text-sm text-muted-foreground\">{translations.table.empty}</p>}\n actions={(\n <Button asChild size=\"sm\">\n <Link href=\"/backend/resources/resource-types/create\">\n {translations.actions.add}\n </Link>\n </Button>\n )}\n refreshButton={{\n label: translations.actions.refresh,\n onRefresh: handleRefresh,\n isRefreshing: isLoading,\n }}\n sortable\n sorting={sorting}\n onSortingChange={setSorting}\n pagination={{ page, pageSize: PAGE_SIZE, total, totalPages, onPageChange: setPage }}\n rowActions={(row) => (\n <RowActions\n items={[\n { id: 'edit', label: translations.actions.edit, href: `/backend/resources/resource-types/${row.id}/edit` },\n ...(row.resourceCount > 0\n ? []\n : [{ id: 'delete', label: translations.actions.delete, destructive: true, onSelect: () => handleDelete(row) }]),\n ]}\n />\n )}\n onRowClick={(row) => router.push(`/backend/resources/resource-types/${row.id}/edit`)}\n perspective={{ tableId: 'resources.resource-types.list' }}\n />\n </PageBody>\n {ConfirmDialogElement}\n </Page>\n )\n}\n\nfunction mapApiResourceType(item: Record<string, unknown>): ResourceTypeRow {\n const id = typeof item.id === 'string' ? item.id : ''\n const name = typeof item.name === 'string' && item.name.length ? item.name : id\n const description = typeof item.description === 'string' && item.description.length\n ? item.description\n : typeof item.description === 'string'\n ? item.description\n : null\n const appearanceIcon = typeof item.appearanceIcon === 'string'\n ? item.appearanceIcon\n : typeof item.appearance_icon === 'string'\n ? item.appearance_icon\n : null\n const appearanceColor = typeof item.appearanceColor === 'string'\n ? item.appearanceColor\n : typeof item.appearance_color === 'string'\n ? item.appearance_color\n : null\n const updatedAt = typeof item.updatedAt === 'string'\n ? item.updatedAt\n : typeof item.updated_at === 'string'\n ? item.updated_at\n : null\n const resourceCount = typeof item.resourceCount === 'number'\n ? item.resourceCount\n : typeof item.resource_count === 'number'\n ? item.resource_count\n : 0\n return withDataTableNamespaces({ id, name, description, appearanceIcon, appearanceColor, updatedAt, resourceCount }, item)\n}\n"],
|
|
5
|
+
"mappings": ";AAoIQ,SACE,KADF;AAlIR,YAAY,WAAW;AACvB,SAAS,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ACzB,KAAK,aACL;AACN,QAAM,gBAAgB,OAAO,KAAK,kBAAkB,WAChD,KAAK,gBACL,OAAO,KAAK,mBAAmB,WAC7B,KAAK,iBACL;AACN,SAAO,wBAAwB,EAAE,IAAI,MAAM,aAAa,gBAAgB,iBAAiB,WAAW,cAAc,GAAG,IAAI;AAC3H;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -12,6 +12,7 @@ import { createCrudFormError } from "@open-mercato/ui/backend/utils/serverErrors
|
|
|
12
12
|
import { updateCrud, deleteCrud } from "@open-mercato/ui/backend/utils/crud";
|
|
13
13
|
import { flash } from "@open-mercato/ui/backend/FlashMessages";
|
|
14
14
|
import { ActivitiesSection, NotesSection, RecordNotFoundState } from "@open-mercato/ui/backend/detail";
|
|
15
|
+
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
|
|
15
16
|
import { VersionHistoryAction } from "@open-mercato/ui/backend/version-history";
|
|
16
17
|
import { SendObjectMessageDialog } from "@open-mercato/ui/backend/messages";
|
|
17
18
|
import { useT } from "@open-mercato/shared/lib/i18n/context";
|
|
@@ -61,8 +62,40 @@ function ResourcesResourceDetailPage({ params }) {
|
|
|
61
62
|
const [activityTypeEntries, setActivityTypeEntries] = React.useState([]);
|
|
62
63
|
const flashShownRef = React.useRef(false);
|
|
63
64
|
const availabilityMode = "availability";
|
|
64
|
-
const
|
|
65
|
-
|
|
65
|
+
const mutationContextId = React.useMemo(
|
|
66
|
+
() => resourceId ? `resources.resource:${resourceId}` : "resources.resource:pending",
|
|
67
|
+
[resourceId]
|
|
68
|
+
);
|
|
69
|
+
const { runMutation, retryLastMutation } = useGuardedMutation({
|
|
70
|
+
contextId: mutationContextId,
|
|
71
|
+
blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
|
|
72
|
+
});
|
|
73
|
+
const mutationContext = React.useMemo(
|
|
74
|
+
() => ({
|
|
75
|
+
formId: mutationContextId,
|
|
76
|
+
resourceKind: "resources.resource",
|
|
77
|
+
resourceId,
|
|
78
|
+
data: initialValues,
|
|
79
|
+
retryLastMutation
|
|
80
|
+
}),
|
|
81
|
+
[initialValues, mutationContextId, resourceId, retryLastMutation]
|
|
82
|
+
);
|
|
83
|
+
const runMutationWithContext = React.useCallback(
|
|
84
|
+
async (operation, mutationPayload) => runMutation({
|
|
85
|
+
operation,
|
|
86
|
+
mutationPayload,
|
|
87
|
+
context: mutationContext
|
|
88
|
+
}),
|
|
89
|
+
[mutationContext, runMutation]
|
|
90
|
+
);
|
|
91
|
+
const notesAdapter = React.useMemo(
|
|
92
|
+
() => createResourceNotesAdapter(detailTranslator, { runMutation: runMutationWithContext }),
|
|
93
|
+
[detailTranslator, runMutationWithContext]
|
|
94
|
+
);
|
|
95
|
+
const activitiesAdapter = React.useMemo(
|
|
96
|
+
() => createResourceActivitiesAdapter(detailTranslator, { runMutation: runMutationWithContext }),
|
|
97
|
+
[detailTranslator, runMutationWithContext]
|
|
98
|
+
);
|
|
66
99
|
const activityTypeLabels = React.useMemo(() => ({
|
|
67
100
|
placeholder: t("resources.resources.detail.activities.dictionary.placeholder", "Select an activity type"),
|
|
68
101
|
addLabel: t("resources.resources.detail.activities.dictionary.add", "Add type"),
|
|
@@ -258,14 +291,18 @@ function ResourcesResourceDetailPage({ params }) {
|
|
|
258
291
|
if (!trimmed.length) {
|
|
259
292
|
throw new Error(t("resources.resources.tags.labelRequired", "Tag name is required."));
|
|
260
293
|
}
|
|
261
|
-
const
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
294
|
+
const requestBody = { label: trimmed };
|
|
295
|
+
const response = await runMutationWithContext(
|
|
296
|
+
() => apiCallOrThrow(
|
|
297
|
+
"/api/resources/tags",
|
|
298
|
+
{
|
|
299
|
+
method: "POST",
|
|
300
|
+
headers: { "content-type": "application/json" },
|
|
301
|
+
body: JSON.stringify(requestBody)
|
|
302
|
+
},
|
|
303
|
+
{ errorMessage: t("resources.resources.tags.createError", "Failed to create tag.") }
|
|
304
|
+
),
|
|
305
|
+
{ operation: "createTag", label: trimmed }
|
|
269
306
|
);
|
|
270
307
|
const payload = response.result ?? {};
|
|
271
308
|
const id = typeof payload?.id === "string" ? payload.id : typeof payload?.tagId === "string" ? payload.tagId : "";
|
|
@@ -273,32 +310,40 @@ function ResourcesResourceDetailPage({ params }) {
|
|
|
273
310
|
const color = typeof payload?.color === "string" && payload.color.trim().length ? payload.color.trim() : null;
|
|
274
311
|
return { id, label: trimmed, color };
|
|
275
312
|
},
|
|
276
|
-
[t]
|
|
313
|
+
[runMutationWithContext, t]
|
|
277
314
|
);
|
|
278
315
|
const assignTag = React.useCallback(async (tagId) => {
|
|
279
316
|
if (!resourceId) return;
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
317
|
+
const requestBody = { tagId, resourceId };
|
|
318
|
+
await runMutationWithContext(
|
|
319
|
+
() => apiCallOrThrow(
|
|
320
|
+
"/api/resources/resources/tags/assign",
|
|
321
|
+
{
|
|
322
|
+
method: "POST",
|
|
323
|
+
headers: { "content-type": "application/json" },
|
|
324
|
+
body: JSON.stringify(requestBody)
|
|
325
|
+
},
|
|
326
|
+
{ errorMessage: t("resources.resources.tags.updateError", "Failed to update tags.") }
|
|
327
|
+
),
|
|
328
|
+
{ operation: "assignTag", resourceId, tagId }
|
|
288
329
|
);
|
|
289
|
-
}, [resourceId, t]);
|
|
330
|
+
}, [resourceId, runMutationWithContext, t]);
|
|
290
331
|
const unassignTag = React.useCallback(async (tagId) => {
|
|
291
332
|
if (!resourceId) return;
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
333
|
+
const requestBody = { tagId, resourceId };
|
|
334
|
+
await runMutationWithContext(
|
|
335
|
+
() => apiCallOrThrow(
|
|
336
|
+
"/api/resources/resources/tags/unassign",
|
|
337
|
+
{
|
|
338
|
+
method: "POST",
|
|
339
|
+
headers: { "content-type": "application/json" },
|
|
340
|
+
body: JSON.stringify(requestBody)
|
|
341
|
+
},
|
|
342
|
+
{ errorMessage: t("resources.resources.tags.updateError", "Failed to update tags.") }
|
|
343
|
+
),
|
|
344
|
+
{ operation: "unassignTag", resourceId, tagId }
|
|
300
345
|
);
|
|
301
|
-
}, [resourceId, t]);
|
|
346
|
+
}, [resourceId, runMutationWithContext, t]);
|
|
302
347
|
const handleTagsSave = React.useCallback(
|
|
303
348
|
async ({ next, added, removed }) => {
|
|
304
349
|
if (!resourceId) return;
|
|
@@ -390,12 +435,19 @@ function ResourcesResourceDetailPage({ params }) {
|
|
|
390
435
|
}, [resourceId, resourceTypesLoaded, resolveFieldsetCode, t]);
|
|
391
436
|
const handleDelete = React.useCallback(async () => {
|
|
392
437
|
if (!resourceId) return;
|
|
393
|
-
|
|
438
|
+
const resourceOptimisticLockHeader = buildOptimisticLockHeader(
|
|
439
|
+
typeof initialValues?.updatedAt === "string" ? initialValues.updatedAt : null
|
|
440
|
+
);
|
|
441
|
+
const deleteResource = () => deleteCrud("resources/resources", resourceId, {
|
|
394
442
|
errorMessage: t("resources.resources.form.errors.delete", "Failed to delete resource.")
|
|
395
443
|
});
|
|
444
|
+
await runMutationWithContext(
|
|
445
|
+
() => Object.keys(resourceOptimisticLockHeader).length > 0 ? withScopedApiRequestHeaders(resourceOptimisticLockHeader, deleteResource) : deleteResource(),
|
|
446
|
+
{ operation: "deleteResource", id: resourceId, updatedAt: initialValues?.updatedAt ?? null }
|
|
447
|
+
);
|
|
396
448
|
flash(t("resources.resources.form.flash.deleted", "Resource deleted."), "success");
|
|
397
449
|
router.push("/backend/resources/resources");
|
|
398
|
-
}, [resourceId, router, t]);
|
|
450
|
+
}, [initialValues?.updatedAt, resourceId, router, runMutationWithContext, t]);
|
|
399
451
|
const handleRulesetChange = React.useCallback(async (nextId) => {
|
|
400
452
|
if (!resourceId) return;
|
|
401
453
|
const updateSchedule = () => updateCrud("resources/resources", { id: resourceId, availabilityRuleSetId: nextId }, {
|
|
@@ -404,14 +456,13 @@ function ResourcesResourceDetailPage({ params }) {
|
|
|
404
456
|
const resourceOptimisticLockHeader = buildOptimisticLockHeader(
|
|
405
457
|
typeof initialValues?.updatedAt === "string" ? initialValues.updatedAt : null
|
|
406
458
|
);
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
}
|
|
459
|
+
await runMutationWithContext(
|
|
460
|
+
() => Object.keys(resourceOptimisticLockHeader).length > 0 ? withScopedApiRequestHeaders(resourceOptimisticLockHeader, updateSchedule) : updateSchedule(),
|
|
461
|
+
{ operation: "updateAvailabilityRuleSet", id: resourceId, availabilityRuleSetId: nextId }
|
|
462
|
+
);
|
|
412
463
|
setAvailabilityRuleSetId(nextId);
|
|
413
464
|
flash(t("resources.resources.availability.ruleset.updateSuccess", "Schedule updated."), "success");
|
|
414
|
-
}, [initialValues?.updatedAt, resourceId, t]);
|
|
465
|
+
}, [initialValues?.updatedAt, resourceId, runMutationWithContext, t]);
|
|
415
466
|
const resourceTitle = typeof initialValues?.name === "string" && initialValues.name.trim().length > 0 ? initialValues.name.trim() : t("resources.resources.detail.untitled", "Unnamed resource");
|
|
416
467
|
if (isNotFound) {
|
|
417
468
|
return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
|