@open-mercato/core 0.6.6-develop.6257.1.6d0af84d26 → 0.6.6-develop.6286.1.d985c5c374
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 +2 -2
- package/dist/generated/entities/carrier_shipment_idempotency_key/index.js +19 -0
- package/dist/generated/entities/carrier_shipment_idempotency_key/index.js.map +7 -0
- package/dist/generated/entities.ids.generated.js +2 -1
- package/dist/generated/entities.ids.generated.js.map +2 -2
- package/dist/generated/entity-fields-registry.js +10 -0
- package/dist/generated/entity-fields-registry.js.map +2 -2
- package/dist/modules/catalog/lib/productResolution.js +45 -0
- package/dist/modules/catalog/lib/productResolution.js.map +7 -0
- package/dist/modules/communication_channels/workers/channel-import-history.js +1 -1
- package/dist/modules/communication_channels/workers/channel-import-history.js.map +2 -2
- package/dist/modules/currencies/api/fetch-configs/route.js +34 -0
- package/dist/modules/currencies/api/fetch-configs/route.js.map +2 -2
- package/dist/modules/currencies/components/CurrencyFetchingConfig.js +17 -15
- package/dist/modules/currencies/components/CurrencyFetchingConfig.js.map +2 -2
- package/dist/modules/customers/api/companies/[id]/route.js +176 -161
- package/dist/modules/customers/api/companies/[id]/route.js.map +2 -2
- package/dist/modules/customers/api/people/[id]/route.js +75 -59
- package/dist/modules/customers/api/people/[id]/route.js.map +2 -2
- package/dist/modules/customers/backend/config/customers/pipeline-stages/page.js +17 -10
- package/dist/modules/customers/backend/config/customers/pipeline-stages/page.js.map +2 -2
- package/dist/modules/customers/components/detail/ActivitiesAddNewMenu.js +6 -4
- package/dist/modules/customers/components/detail/ActivitiesAddNewMenu.js.map +2 -2
- package/dist/modules/customers/components/detail/AiActionChips.js +5 -2
- package/dist/modules/customers/components/detail/AiActionChips.js.map +2 -2
- package/dist/modules/customers/components/detail/schedule/ParticipantsField.js +19 -21
- package/dist/modules/customers/components/detail/schedule/ParticipantsField.js.map +2 -2
- package/dist/modules/data_sync/api/runs/[id]/cancel.js +1 -1
- package/dist/modules/data_sync/api/runs/[id]/cancel.js.map +2 -2
- package/dist/modules/data_sync/backend/data-sync/page.js +9 -45
- package/dist/modules/data_sync/backend/data-sync/page.js.map +2 -2
- package/dist/modules/data_sync/backend/data-sync/runs/[id]/page.js +11 -17
- package/dist/modules/data_sync/backend/data-sync/runs/[id]/page.js.map +2 -2
- package/dist/modules/data_sync/components/IntegrationScheduleTab.js +12 -10
- package/dist/modules/data_sync/components/IntegrationScheduleTab.js.map +2 -2
- package/dist/modules/data_sync/lib/id-mapping.js +46 -1
- package/dist/modules/data_sync/lib/id-mapping.js.map +2 -2
- package/dist/modules/data_sync/lib/sync-engine.js +2 -2
- package/dist/modules/data_sync/lib/sync-engine.js.map +2 -2
- package/dist/modules/data_sync/lib/syncRunStatus.js +30 -0
- package/dist/modules/data_sync/lib/syncRunStatus.js.map +7 -0
- package/dist/modules/entities/api/records.js +6 -0
- package/dist/modules/entities/api/records.js.map +2 -2
- package/dist/modules/feature_toggles/api/global/route.js +17 -15
- package/dist/modules/feature_toggles/api/global/route.js.map +2 -2
- package/dist/modules/feature_toggles/api/openapi.js +2 -2
- package/dist/modules/feature_toggles/api/openapi.js.map +2 -2
- package/dist/modules/feature_toggles/commands/global.js +14 -0
- package/dist/modules/feature_toggles/commands/global.js.map +2 -2
- package/dist/modules/inbox_ops/backend/inbox-ops/page.js +6 -0
- package/dist/modules/inbox_ops/backend/inbox-ops/page.js.map +2 -2
- package/dist/modules/messages/components/message-detail/hooks/useMessageDetails.js +3 -1
- package/dist/modules/messages/components/message-detail/hooks/useMessageDetails.js.map +2 -2
- package/dist/modules/messages/components/message-detail/hooks/useMessageDetailsActions.js +12 -5
- package/dist/modules/messages/components/message-detail/hooks/useMessageDetailsActions.js.map +2 -2
- package/dist/modules/messages/components/message-detail/hooks/useMessageDetailsQueries.js +10 -1
- package/dist/modules/messages/components/message-detail/hooks/useMessageDetailsQueries.js.map +2 -2
- package/dist/modules/payment_gateways/api/cancel/route.js +5 -0
- package/dist/modules/payment_gateways/api/cancel/route.js.map +2 -2
- package/dist/modules/payment_gateways/api/capture/route.js +5 -0
- package/dist/modules/payment_gateways/api/capture/route.js.map +2 -2
- package/dist/modules/payment_gateways/api/refund/route.js +5 -0
- package/dist/modules/payment_gateways/api/refund/route.js.map +2 -2
- package/dist/modules/payment_gateways/lib/gateway-service.js +52 -25
- package/dist/modules/payment_gateways/lib/gateway-service.js.map +2 -2
- package/dist/modules/payment_gateways/lib/status-machine.js +13 -0
- package/dist/modules/payment_gateways/lib/status-machine.js.map +2 -2
- package/dist/modules/perspectives/api/[tableId]/route.js +8 -2
- package/dist/modules/perspectives/api/[tableId]/route.js.map +2 -2
- package/dist/modules/perspectives/data/entities.js +33 -3
- package/dist/modules/perspectives/data/entities.js.map +2 -2
- package/dist/modules/perspectives/migrations/Migration20260619120000_perspectives_live_row_uniqueness.js +63 -0
- package/dist/modules/perspectives/migrations/Migration20260619120000_perspectives_live_row_uniqueness.js.map +7 -0
- package/dist/modules/perspectives/services/perspectiveService.js +17 -0
- package/dist/modules/perspectives/services/perspectiveService.js.map +2 -2
- package/dist/modules/planner/commands/availability-weekly.js +33 -1
- package/dist/modules/planner/commands/availability-weekly.js.map +2 -2
- package/dist/modules/planner/components/AvailabilityRulesEditor.js +14 -2
- package/dist/modules/planner/components/AvailabilityRulesEditor.js.map +2 -2
- package/dist/modules/progress/api/active/route.js +1 -1
- package/dist/modules/progress/api/active/route.js.map +2 -2
- package/dist/modules/progress/lib/progressService.js.map +1 -1
- package/dist/modules/progress/lib/progressServiceImpl.js +33 -8
- package/dist/modules/progress/lib/progressServiceImpl.js.map +2 -2
- package/dist/modules/query_index/api/status.js +19 -24
- package/dist/modules/query_index/api/status.js.map +3 -3
- package/dist/modules/query_index/lib/coverage.js +35 -0
- package/dist/modules/query_index/lib/coverage.js.map +2 -2
- package/dist/modules/query_index/lib/engine.js +11 -6
- package/dist/modules/query_index/lib/engine.js.map +2 -2
- package/dist/modules/resources/api/resource-types.js +5 -37
- package/dist/modules/resources/api/resource-types.js.map +2 -2
- package/dist/modules/resources/api/resourceTypeCounts.js +35 -0
- package/dist/modules/resources/api/resourceTypeCounts.js.map +7 -0
- package/dist/modules/resources/backend/resources/resource-types/[id]/edit/page.js +1 -1
- package/dist/modules/resources/backend/resources/resource-types/[id]/edit/page.js.map +1 -1
- package/dist/modules/resources/backend/resources/resource-types/page.js +2 -1
- package/dist/modules/resources/backend/resources/resource-types/page.js.map +2 -2
- package/dist/modules/sales/components/documents/ReturnDialog.js +4 -1
- package/dist/modules/sales/components/documents/ReturnDialog.js.map +2 -2
- package/dist/modules/sales/components/documents/ShipmentDialog.js +17 -2
- package/dist/modules/sales/components/documents/ShipmentDialog.js.map +2 -2
- package/dist/modules/sales/di.js +4 -0
- package/dist/modules/sales/di.js.map +2 -2
- package/dist/modules/sales/services/salesOrderService.js +26 -0
- package/dist/modules/sales/services/salesOrderService.js.map +7 -0
- package/dist/modules/shipping_carriers/api/shipments/route.js +8 -0
- package/dist/modules/shipping_carriers/api/shipments/route.js.map +2 -2
- package/dist/modules/shipping_carriers/data/entities.js +38 -0
- package/dist/modules/shipping_carriers/data/entities.js.map +2 -2
- package/dist/modules/shipping_carriers/data/validators.js +2 -1
- package/dist/modules/shipping_carriers/data/validators.js.map +2 -2
- package/dist/modules/shipping_carriers/lib/shipment-idempotency.js +76 -0
- package/dist/modules/shipping_carriers/lib/shipment-idempotency.js.map +7 -0
- package/dist/modules/shipping_carriers/lib/shipment-wizard/hooks/shipmentApi.js +2 -1
- package/dist/modules/shipping_carriers/lib/shipment-wizard/hooks/shipmentApi.js.map +2 -2
- package/dist/modules/shipping_carriers/lib/shipment-wizard/hooks/useShipmentWizard.js +20 -2
- package/dist/modules/shipping_carriers/lib/shipment-wizard/hooks/useShipmentWizard.js.map +2 -2
- package/dist/modules/shipping_carriers/lib/shipping-service.js +82 -43
- package/dist/modules/shipping_carriers/lib/shipping-service.js.map +2 -2
- package/dist/modules/shipping_carriers/migrations/Migration20260618173616_shipping_carriers.js +14 -0
- package/dist/modules/shipping_carriers/migrations/Migration20260618173616_shipping_carriers.js.map +7 -0
- package/dist/modules/staff/lib/timesheets-ui/ListView.js +15 -6
- package/dist/modules/staff/lib/timesheets-ui/ListView.js.map +2 -2
- package/dist/modules/translations/components/TranslationManager.js +9 -18
- package/dist/modules/translations/components/TranslationManager.js.map +2 -2
- package/generated/entities/carrier_shipment_idempotency_key/index.ts +8 -0
- package/generated/entities.ids.generated.ts +2 -1
- package/generated/entity-fields-registry.ts +10 -0
- package/package.json +9 -8
- package/src/modules/catalog/lib/productResolution.ts +75 -0
- package/src/modules/communication_channels/workers/channel-import-history.ts +1 -1
- package/src/modules/currencies/api/fetch-configs/route.ts +36 -0
- package/src/modules/currencies/components/CurrencyFetchingConfig.tsx +20 -17
- package/src/modules/currencies/i18n/de.json +2 -1
- package/src/modules/currencies/i18n/en.json +2 -1
- package/src/modules/currencies/i18n/es.json +2 -1
- package/src/modules/currencies/i18n/pl.json +2 -1
- package/src/modules/customers/api/companies/[id]/route.ts +214 -189
- package/src/modules/customers/api/people/[id]/route.ts +106 -80
- package/src/modules/customers/backend/config/customers/pipeline-stages/page.tsx +19 -12
- package/src/modules/customers/components/detail/ActivitiesAddNewMenu.tsx +8 -6
- package/src/modules/customers/components/detail/AiActionChips.tsx +6 -3
- package/src/modules/customers/components/detail/schedule/ParticipantsField.tsx +16 -18
- package/src/modules/data_sync/api/runs/[id]/cancel.ts +1 -1
- package/src/modules/data_sync/backend/data-sync/page.tsx +11 -58
- package/src/modules/data_sync/backend/data-sync/runs/[id]/page.tsx +13 -20
- package/src/modules/data_sync/components/IntegrationScheduleTab.tsx +10 -8
- package/src/modules/data_sync/lib/id-mapping.ts +58 -1
- package/src/modules/data_sync/lib/sync-engine.ts +2 -2
- package/src/modules/data_sync/lib/syncRunStatus.ts +39 -0
- package/src/modules/entities/api/records.ts +14 -0
- package/src/modules/feature_toggles/api/global/route.ts +16 -14
- package/src/modules/feature_toggles/api/openapi.ts +2 -2
- package/src/modules/feature_toggles/commands/global.ts +15 -0
- package/src/modules/inbox_ops/backend/inbox-ops/page.tsx +7 -0
- package/src/modules/messages/components/message-detail/hooks/useMessageDetails.ts +2 -0
- package/src/modules/messages/components/message-detail/hooks/useMessageDetailsActions.ts +14 -4
- package/src/modules/messages/components/message-detail/hooks/useMessageDetailsQueries.ts +15 -1
- package/src/modules/payment_gateways/api/cancel/route.ts +5 -0
- package/src/modules/payment_gateways/api/capture/route.ts +5 -0
- package/src/modules/payment_gateways/api/refund/route.ts +5 -0
- package/src/modules/payment_gateways/lib/gateway-service.ts +58 -25
- package/src/modules/payment_gateways/lib/status-machine.ts +16 -0
- package/src/modules/perspectives/api/[tableId]/route.ts +8 -2
- package/src/modules/perspectives/data/entities.ts +43 -3
- package/src/modules/perspectives/migrations/.snapshot-open-mercato.json +69 -25
- package/src/modules/perspectives/migrations/Migration20260619120000_perspectives_live_row_uniqueness.ts +65 -0
- package/src/modules/perspectives/services/perspectiveService.ts +17 -0
- package/src/modules/planner/commands/availability-weekly.ts +48 -1
- package/src/modules/planner/components/AvailabilityRulesEditor.tsx +31 -10
- package/src/modules/progress/api/active/route.ts +1 -1
- package/src/modules/progress/lib/progressService.ts +2 -2
- package/src/modules/progress/lib/progressServiceImpl.ts +33 -8
- package/src/modules/query_index/api/status.ts +28 -32
- package/src/modules/query_index/lib/coverage.ts +63 -0
- package/src/modules/query_index/lib/engine.ts +37 -24
- package/src/modules/resources/api/resource-types.ts +4 -44
- package/src/modules/resources/api/resourceTypeCounts.ts +74 -0
- package/src/modules/resources/backend/resources/resource-types/[id]/edit/page.tsx +1 -1
- package/src/modules/resources/backend/resources/resource-types/page.tsx +1 -0
- package/src/modules/sales/components/documents/ReturnDialog.tsx +4 -1
- package/src/modules/sales/components/documents/ShipmentDialog.tsx +20 -2
- package/src/modules/sales/di.ts +6 -0
- package/src/modules/sales/services/salesOrderService.ts +38 -0
- package/src/modules/shipping_carriers/api/shipments/route.ts +8 -0
- package/src/modules/shipping_carriers/data/entities.ts +33 -0
- package/src/modules/shipping_carriers/data/validators.ts +1 -0
- package/src/modules/shipping_carriers/i18n/de.json +1 -0
- package/src/modules/shipping_carriers/i18n/en.json +1 -0
- package/src/modules/shipping_carriers/i18n/es.json +1 -0
- package/src/modules/shipping_carriers/i18n/pl.json +1 -0
- package/src/modules/shipping_carriers/lib/shipment-idempotency.ts +119 -0
- package/src/modules/shipping_carriers/lib/shipment-wizard/hooks/shipmentApi.ts +3 -1
- package/src/modules/shipping_carriers/lib/shipment-wizard/hooks/useShipmentWizard.ts +24 -2
- package/src/modules/shipping_carriers/lib/shipping-service.ts +87 -43
- package/src/modules/shipping_carriers/migrations/.snapshot-open-mercato.json +197 -0
- package/src/modules/shipping_carriers/migrations/Migration20260618173616_shipping_carriers.ts +14 -0
- package/src/modules/staff/i18n/de.json +1 -0
- package/src/modules/staff/i18n/en.json +1 -0
- package/src/modules/staff/i18n/es.json +1 -0
- package/src/modules/staff/i18n/pl.json +1 -0
- package/src/modules/staff/lib/timesheets-ui/ListView.tsx +15 -7
- package/src/modules/translations/components/TranslationManager.tsx +17 -24
- package/src/modules/translations/i18n/de.json +1 -0
- package/src/modules/translations/i18n/en.json +1 -0
- package/src/modules/translations/i18n/es.json +1 -0
- package/src/modules/translations/i18n/pl.json +1 -0
|
@@ -3,10 +3,10 @@ import { makeCrudRoute } from "@open-mercato/shared/lib/crud/factory";
|
|
|
3
3
|
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
|
|
4
4
|
import { resolveCrudRecordId, parseScopedCommandInput } from "@open-mercato/shared/lib/api/scoped";
|
|
5
5
|
import { escapeLikePattern } from "@open-mercato/shared/lib/db/escapeLikePattern";
|
|
6
|
-
import {
|
|
7
|
-
import { ResourcesResource, ResourcesResourceType } from "../data/entities.js";
|
|
6
|
+
import { ResourcesResourceType } from "../data/entities.js";
|
|
8
7
|
import { resourcesResourceTypeCreateSchema, resourcesResourceTypeUpdateSchema } from "../data/validators.js";
|
|
9
8
|
import { sanitizeSearchTerm } from "./helpers.js";
|
|
9
|
+
import { attachResourceTypeCounts } from "./resourceTypeCounts.js";
|
|
10
10
|
import { E } from "../../../generated/entities.ids.generated.js";
|
|
11
11
|
import { createResourcesCrudOpenApi, createPagedListResponseSchema, defaultOkResponseSchema } from "./openapi.js";
|
|
12
12
|
const F = {
|
|
@@ -38,7 +38,8 @@ const listSchema = z.object({
|
|
|
38
38
|
search: z.string().optional(),
|
|
39
39
|
ids: z.string().optional(),
|
|
40
40
|
sortField: z.string().optional(),
|
|
41
|
-
sortDir: z.enum(["asc", "desc"]).optional()
|
|
41
|
+
sortDir: z.enum(["asc", "desc"]).optional(),
|
|
42
|
+
withResourceCounts: z.string().optional()
|
|
42
43
|
}).passthrough();
|
|
43
44
|
const crud = makeCrudRoute({
|
|
44
45
|
metadata: routeMetadata,
|
|
@@ -118,40 +119,7 @@ const crud = makeCrudRoute({
|
|
|
118
119
|
}
|
|
119
120
|
},
|
|
120
121
|
hooks: {
|
|
121
|
-
afterList:
|
|
122
|
-
const items = Array.isArray(payload?.items) ? payload.items : [];
|
|
123
|
-
if (!items.length) return;
|
|
124
|
-
const typeIds = items.map((item) => typeof item.id === "string" ? item.id : null).filter((id) => typeof id === "string" && id.length > 0);
|
|
125
|
-
if (!typeIds.length) return;
|
|
126
|
-
const em = ctx.container.resolve("em").fork();
|
|
127
|
-
const tenantId = ctx.organizationScope?.tenantId ?? ctx.auth?.tenantId ?? null;
|
|
128
|
-
const orgIds = ctx.organizationIds ?? ctx.organizationScope?.filterIds ?? null;
|
|
129
|
-
const orgFilter = Array.isArray(orgIds) && orgIds.length > 0 ? { $in: orgIds } : ctx.selectedOrganizationId ?? ctx.organizationScope?.selectedId ?? null;
|
|
130
|
-
const scope = { tenantId, organizationId: ctx.selectedOrganizationId ?? ctx.organizationScope?.selectedId ?? null };
|
|
131
|
-
const resources = await findWithDecryption(
|
|
132
|
-
em,
|
|
133
|
-
ResourcesResource,
|
|
134
|
-
{
|
|
135
|
-
resourceTypeId: { $in: typeIds },
|
|
136
|
-
deletedAt: null,
|
|
137
|
-
...tenantId ? { tenantId } : {},
|
|
138
|
-
...orgFilter ? { organizationId: orgFilter } : {}
|
|
139
|
-
},
|
|
140
|
-
{ fields: ["id", "resourceTypeId"] },
|
|
141
|
-
scope
|
|
142
|
-
);
|
|
143
|
-
const countMap = /* @__PURE__ */ new Map();
|
|
144
|
-
resources.forEach((resource) => {
|
|
145
|
-
const typeId = resource.resourceTypeId ?? null;
|
|
146
|
-
if (!typeId) return;
|
|
147
|
-
countMap.set(typeId, (countMap.get(typeId) ?? 0) + 1);
|
|
148
|
-
});
|
|
149
|
-
items.forEach((item) => {
|
|
150
|
-
const id = typeof item.id === "string" ? item.id : null;
|
|
151
|
-
if (!id) return;
|
|
152
|
-
item.resourceCount = countMap.get(id) ?? 0;
|
|
153
|
-
});
|
|
154
|
-
}
|
|
122
|
+
afterList: (payload, ctx) => attachResourceTypeCounts(payload, ctx)
|
|
155
123
|
}
|
|
156
124
|
});
|
|
157
125
|
const GET = crud.GET;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/resources/api/resource-types.ts"],
|
|
4
|
-
"sourcesContent": ["import { z } from 'zod'\nimport { makeCrudRoute } from '@open-mercato/shared/lib/crud/factory'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { resolveCrudRecordId, parseScopedCommandInput } from '@open-mercato/shared/lib/api/scoped'\nimport { escapeLikePattern } from '@open-mercato/shared/lib/db/escapeLikePattern'\nimport
|
|
5
|
-
"mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,qBAAqB,+BAA+B;AAC7D,SAAS,yBAAyB;
|
|
4
|
+
"sourcesContent": ["import { z } from 'zod'\nimport { makeCrudRoute } from '@open-mercato/shared/lib/crud/factory'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { resolveCrudRecordId, parseScopedCommandInput } from '@open-mercato/shared/lib/api/scoped'\nimport { escapeLikePattern } from '@open-mercato/shared/lib/db/escapeLikePattern'\nimport { ResourcesResourceType } from '../data/entities'\nimport { resourcesResourceTypeCreateSchema, resourcesResourceTypeUpdateSchema } from '../data/validators'\nimport { sanitizeSearchTerm } from './helpers'\nimport { attachResourceTypeCounts } from './resourceTypeCounts'\nimport { E } from '#generated/entities.ids.generated'\nimport { createResourcesCrudOpenApi, createPagedListResponseSchema, defaultOkResponseSchema } from './openapi'\n\n// Field constants for ResourcesResourceType entity\nconst F = {\n id: \"id\",\n tenant_id: \"tenant_id\",\n organization_id: \"organization_id\",\n name: \"name\",\n description: \"description\",\n default_duration: \"default_duration\",\n default_buffer: \"default_buffer\",\n appearance_icon: \"appearance_icon\",\n appearance_color: \"appearance_color\",\n is_active: \"is_active\",\n created_at: \"created_at\",\n updated_at: \"updated_at\",\n deleted_at: \"deleted_at\",\n} as const\n\nconst routeMetadata = {\n GET: { requireAuth: true, requireFeatures: ['resources.view'] },\n POST: { requireAuth: true, requireFeatures: ['resources.manage_resources'] },\n PUT: { requireAuth: true, requireFeatures: ['resources.manage_resources'] },\n DELETE: { requireAuth: true, requireFeatures: ['resources.manage_resources'] },\n}\n\nexport const metadata = routeMetadata\n\nconst rawBodySchema = z.object({}).passthrough()\n\nconst listSchema = z\n .object({\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 ids: z.string().optional(),\n sortField: z.string().optional(),\n sortDir: z.enum(['asc', 'desc']).optional(),\n withResourceCounts: z.string().optional(),\n })\n .passthrough()\n\nconst crud = makeCrudRoute({\n metadata: routeMetadata,\n orm: {\n entity: ResourcesResourceType,\n idField: 'id',\n orgField: 'organizationId',\n tenantField: 'tenantId',\n softDeleteField: 'deletedAt',\n },\n indexer: { entityType: E.resources.resources_resource_type },\n list: {\n schema: listSchema,\n entityId: E.resources.resources_resource_type,\n fields: [\n F.id,\n F.organization_id,\n F.tenant_id,\n F.name,\n F.description,\n 'appearance_icon',\n 'appearance_color',\n F.created_at,\n F.updated_at,\n ],\n sortFieldMap: {\n name: F.name,\n createdAt: F.created_at,\n updatedAt: F.updated_at,\n },\n buildFilters: async (query) => {\n const filters: Record<string, unknown> = {}\n if (typeof query.ids === 'string' && query.ids.trim().length > 0) {\n const ids = query.ids\n .split(',')\n .map((value) => value.trim())\n .filter((value) => value.length > 0)\n if (ids.length > 0) {\n filters[F.id] = { $in: ids }\n }\n }\n const term = sanitizeSearchTerm(query.search)\n if (term) {\n const like = `%${escapeLikePattern(term)}%`\n filters[F.name] = { $ilike: like }\n }\n return filters\n },\n decorateCustomFields: { entityIds: [E.resources.resources_resource_type] },\n },\n actions: {\n create: {\n commandId: 'resources.resourceTypes.create',\n schema: rawBodySchema,\n mapInput: async ({ raw, ctx }) => {\n const { translate } = await resolveTranslations()\n return parseScopedCommandInput(resourcesResourceTypeCreateSchema, raw ?? {}, ctx, translate)\n },\n response: ({ result }) => ({ id: result?.resourceTypeId ?? null }),\n status: 201,\n },\n update: {\n commandId: 'resources.resourceTypes.update',\n schema: rawBodySchema,\n mapInput: async ({ raw, ctx }) => {\n const { translate } = await resolveTranslations()\n return parseScopedCommandInput(resourcesResourceTypeUpdateSchema, raw ?? {}, ctx, translate)\n },\n response: () => ({ ok: true }),\n },\n delete: {\n commandId: 'resources.resourceTypes.delete',\n schema: rawBodySchema,\n mapInput: async ({ parsed, ctx }) => {\n const { translate } = await resolveTranslations()\n const id = resolveCrudRecordId(parsed, ctx, translate)\n return { id }\n },\n response: () => ({ ok: true }),\n },\n },\n hooks: {\n afterList: (payload, ctx) => attachResourceTypeCounts(payload, ctx),\n },\n})\n\nexport const GET = crud.GET\nexport const POST = crud.POST\nexport const PUT = crud.PUT\nexport const DELETE = crud.DELETE\n\nconst resourceTypeListItemSchema = z.object({\n id: z.string().uuid().nullable().optional(),\n organization_id: z.string().uuid().nullable().optional(),\n tenant_id: z.string().uuid().nullable().optional(),\n name: z.string().nullable().optional(),\n description: z.string().nullable().optional(),\n appearance_icon: z.string().nullable().optional(),\n appearance_color: z.string().nullable().optional(),\n created_at: z.string().nullable().optional(),\n updated_at: z.string().nullable().optional(),\n resourceCount: z.number().nullable().optional(),\n})\n\nexport const openApi = createResourcesCrudOpenApi({\n resourceName: 'Resource type',\n pluralName: 'Resource types',\n querySchema: listSchema,\n listResponseSchema: createPagedListResponseSchema(resourceTypeListItemSchema),\n create: {\n schema: resourcesResourceTypeCreateSchema,\n description: 'Creates a resource type for resources resources.',\n },\n update: {\n schema: resourcesResourceTypeUpdateSchema,\n responseSchema: defaultOkResponseSchema,\n description: 'Updates a resource type by id.',\n },\n del: {\n schema: z.object({ id: z.string().uuid() }),\n responseSchema: defaultOkResponseSchema,\n description: 'Deletes a resource type by id.',\n },\n})\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,qBAAqB,+BAA+B;AAC7D,SAAS,yBAAyB;AAClC,SAAS,6BAA6B;AACtC,SAAS,mCAAmC,yCAAyC;AACrF,SAAS,0BAA0B;AACnC,SAAS,gCAAgC;AACzC,SAAS,SAAS;AAClB,SAAS,4BAA4B,+BAA+B,+BAA+B;AAGnG,MAAM,IAAI;AAAA,EACR,IAAI;AAAA,EACJ,WAAW;AAAA,EACX,iBAAiB;AAAA,EACjB,MAAM;AAAA,EACN,aAAa;AAAA,EACb,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,EACjB,kBAAkB;AAAA,EAClB,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,YAAY;AACd;AAEA,MAAM,gBAAgB;AAAA,EACpB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,gBAAgB,EAAE;AAAA,EAC9D,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,4BAA4B,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A,EAC5E,QAAQ;AAAA,IACN,QAAQ;AAAA,IACR,aAAa;AAAA,EACf;AAAA,EACA,QAAQ;AAAA,IACN,QAAQ;AAAA,IACR,gBAAgB;AAAA,IAChB,aAAa;AAAA,EACf;AAAA,EACA,KAAK;AAAA,IACH,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,IAC1C,gBAAgB;AAAA,IAChB,aAAa;AAAA,EACf;AACF,CAAC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { sql } from "kysely";
|
|
2
|
+
import { parseBooleanFromUnknown } from "@open-mercato/shared/lib/boolean";
|
|
3
|
+
async function attachResourceTypeCounts(payload, ctx) {
|
|
4
|
+
if (!parseBooleanFromUnknown(ctx.query?.withResourceCounts)) return;
|
|
5
|
+
const items = Array.isArray(payload?.items) ? payload.items : [];
|
|
6
|
+
if (!items.length) return;
|
|
7
|
+
const typeIds = items.map((item) => typeof item.id === "string" ? item.id : null).filter((id) => typeof id === "string" && id.length > 0);
|
|
8
|
+
if (!typeIds.length) return;
|
|
9
|
+
const tenantId = ctx.organizationScope?.tenantId ?? ctx.auth?.tenantId ?? null;
|
|
10
|
+
const orgIds = ctx.organizationIds ?? ctx.organizationScope?.filterIds ?? null;
|
|
11
|
+
const singleOrgId = ctx.selectedOrganizationId ?? ctx.organizationScope?.selectedId ?? null;
|
|
12
|
+
const db = ctx.container.resolve("em").getKysely();
|
|
13
|
+
let query = db.selectFrom("resources_resources").select(["resource_type_id", sql`count(*)`.as("count")]).where("resource_type_id", "in", typeIds).where("deleted_at", "is", null);
|
|
14
|
+
if (tenantId) query = query.where("tenant_id", "=", tenantId);
|
|
15
|
+
if (Array.isArray(orgIds) && orgIds.length > 0) {
|
|
16
|
+
query = query.where("organization_id", "in", orgIds);
|
|
17
|
+
} else if (singleOrgId) {
|
|
18
|
+
query = query.where("organization_id", "=", singleOrgId);
|
|
19
|
+
}
|
|
20
|
+
const rows = await query.groupBy("resource_type_id").execute();
|
|
21
|
+
const countMap = /* @__PURE__ */ new Map();
|
|
22
|
+
for (const row of rows) {
|
|
23
|
+
if (typeof row.resource_type_id !== "string") continue;
|
|
24
|
+
const count = typeof row.count === "string" ? Number.parseInt(row.count, 10) : Number(row.count);
|
|
25
|
+
countMap.set(row.resource_type_id, Number.isFinite(count) ? count : 0);
|
|
26
|
+
}
|
|
27
|
+
for (const item of items) {
|
|
28
|
+
if (typeof item.id !== "string") continue;
|
|
29
|
+
item.resourceCount = countMap.get(item.id) ?? 0;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export {
|
|
33
|
+
attachResourceTypeCounts
|
|
34
|
+
};
|
|
35
|
+
//# sourceMappingURL=resourceTypeCounts.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/modules/resources/api/resourceTypeCounts.ts"],
|
|
4
|
+
"sourcesContent": ["import type { Kysely } from 'kysely'\nimport { sql } from 'kysely'\nimport { parseBooleanFromUnknown } from '@open-mercato/shared/lib/boolean'\nimport type { CrudCtx } from '@open-mercato/shared/lib/crud/factory'\n\ntype ResourceCountDatabase = {\n resources_resources: {\n resource_type_id: string | null\n deleted_at: Date | null\n tenant_id: string | null\n organization_id: string | null\n }\n}\n\ntype KyselyCapableEntityManager = { getKysely: () => Kysely<ResourceCountDatabase> }\n\ntype ResourceTypeCountContext = Pick<\n CrudCtx,\n 'container' | 'auth' | 'organizationScope' | 'organizationIds' | 'selectedOrganizationId'\n> & { query?: { withResourceCounts?: unknown } }\n\ntype ResourceTypeListPayload = { items?: unknown } | null | undefined\n\ntype ResourceCountRow = { resource_type_id: string | null; count: string | number }\n\nexport async function attachResourceTypeCounts(\n payload: ResourceTypeListPayload,\n ctx: ResourceTypeCountContext,\n): Promise<void> {\n // Resource counts are opt-in: only callers that render the count (the\n // resource-types admin table and its delete gate) pass `withResourceCounts`.\n // Select/filter callers (resource dropdowns, group labels) skip the scan\n // entirely so ordinary type lookups no longer pay an O(resources) cost.\n if (!parseBooleanFromUnknown(ctx.query?.withResourceCounts)) return\n\n const items = Array.isArray(payload?.items)\n ? (payload!.items as Array<Record<string, unknown>>)\n : []\n if (!items.length) return\n\n const typeIds = items\n .map((item) => (typeof item.id === 'string' ? item.id : null))\n .filter((id): id is string => typeof id === 'string' && id.length > 0)\n if (!typeIds.length) return\n\n const tenantId = ctx.organizationScope?.tenantId ?? ctx.auth?.tenantId ?? null\n const orgIds = ctx.organizationIds ?? ctx.organizationScope?.filterIds ?? null\n const singleOrgId = ctx.selectedOrganizationId ?? ctx.organizationScope?.selectedId ?? null\n\n const db = (ctx.container.resolve('em') as unknown as KyselyCapableEntityManager).getKysely()\n let query = db\n .selectFrom('resources_resources')\n .select(['resource_type_id', sql<string>`count(*)`.as('count')])\n .where('resource_type_id', 'in', typeIds)\n .where('deleted_at', 'is', null)\n if (tenantId) query = query.where('tenant_id', '=', tenantId)\n if (Array.isArray(orgIds) && orgIds.length > 0) {\n query = query.where('organization_id', 'in', orgIds)\n } else if (singleOrgId) {\n query = query.where('organization_id', '=', singleOrgId)\n }\n const rows = (await query.groupBy('resource_type_id').execute()) as ResourceCountRow[]\n\n const countMap = new Map<string, number>()\n for (const row of rows) {\n if (typeof row.resource_type_id !== 'string') continue\n const count = typeof row.count === 'string' ? Number.parseInt(row.count, 10) : Number(row.count)\n countMap.set(row.resource_type_id, Number.isFinite(count) ? count : 0)\n }\n for (const item of items) {\n if (typeof item.id !== 'string') continue\n item.resourceCount = countMap.get(item.id) ?? 0\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,WAAW;AACpB,SAAS,+BAA+B;AAuBxC,eAAsB,yBACpB,SACA,KACe;AAKf,MAAI,CAAC,wBAAwB,IAAI,OAAO,kBAAkB,EAAG;AAE7D,QAAM,QAAQ,MAAM,QAAQ,SAAS,KAAK,IACrC,QAAS,QACV,CA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AU;AACjC,SAAK,gBAAgB,SAAS,IAAI,KAAK,EAAE,KAAK;AAAA,EAChD;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -28,7 +28,7 @@ function ResourcesResourceTypeEditPage({ params }) {
|
|
|
28
28
|
setIsNotFound(false);
|
|
29
29
|
try {
|
|
30
30
|
const payload = await readApiResultOrThrow(
|
|
31
|
-
`/api/resources/resource-types?ids=${encodeURIComponent(resourceTypeId)}&page=1&pageSize=1`,
|
|
31
|
+
`/api/resources/resource-types?ids=${encodeURIComponent(resourceTypeId)}&page=1&pageSize=1&withResourceCounts=true`,
|
|
32
32
|
void 0,
|
|
33
33
|
{ errorMessage: t("resources.resourceTypes.errors.load", "Failed to load resource types.") }
|
|
34
34
|
);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../../src/modules/resources/backend/resources/resource-types/%5Bid%5D/edit/page.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { useRouter } from 'next/navigation'\nimport { Page, PageBody } from '@open-mercato/ui/backend/Page'\nimport { ErrorMessage, RecordNotFoundState } from '@open-mercato/ui/backend/detail'\nimport { readApiResultOrThrow } from '@open-mercato/ui/backend/utils/apiCall'\nimport { updateCrud, deleteCrud } from '@open-mercato/ui/backend/utils/crud'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { extractCustomFieldValues } from '@open-mercato/core/modules/sales/components/documents/customFieldHelpers'\nimport { buildResourceTypePayload, ResourceTypeCrudForm, type ResourceTypeFormValues } from '@open-mercato/core/modules/resources/components/ResourceTypeCrudForm'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\n\ntype ResourceTypesResponse = {\n items?: Array<Record<string, unknown>>\n}\n\nexport default function ResourcesResourceTypeEditPage({ params }: { params?: { id?: string } }) {\n const resourceTypeId = params?.id ?? ''\n const t = useT()\n const router = useRouter()\n const [initialValues, setInitialValues] = React.useState<ResourceTypeFormValues | null>(null)\n const [loading, setLoading] = React.useState(true)\n const [error, setError] = React.useState<string | null>(null)\n const [isNotFound, setIsNotFound] = React.useState(false)\n const [resourceCount, setResourceCount] = React.useState(0)\n\n React.useEffect(() => {\n if (!resourceTypeId) return\n let cancelled = false\n async function load() {\n setLoading(true)\n setError(null)\n setIsNotFound(false)\n try {\n const payload = await readApiResultOrThrow<ResourceTypesResponse>(\n `/api/resources/resource-types?ids=${encodeURIComponent(resourceTypeId)}&page=1&pageSize=1`,\n undefined,\n { errorMessage: t('resources.resourceTypes.errors.load', 'Failed to load resource types.') },\n )\n const item = Array.isArray(payload.items) ? payload.items[0] : null\n if (!item) {\n if (!cancelled) setIsNotFound(true)\n return\n }\n if (!cancelled) {\n const customValues = extractCustomFieldValues(item)\n setInitialValues({\n id: typeof item.id === 'string' ? item.id : resourceTypeId,\n name: typeof item.name === 'string' ? item.name : '',\n description: typeof item.description === 'string' ? item.description : '',\n appearance: {\n icon: typeof item.appearanceIcon === 'string'\n ? item.appearanceIcon\n : typeof item.appearance_icon === 'string'\n ? item.appearance_icon\n : null,\n color: typeof item.appearanceColor === 'string'\n ? item.appearanceColor\n : typeof item.appearance_color === 'string'\n ? item.appearance_color\n : null,\n },\n updatedAt: typeof item.updatedAt === 'string'\n ? item.updatedAt\n : typeof item.updated_at === 'string'\n ? item.updated_at\n : null,\n ...customValues,\n })\n setResourceCount(typeof item.resourceCount === 'number'\n ? item.resourceCount\n : typeof item.resource_count === 'number'\n ? item.resource_count\n : 0)\n }\n } catch (err) {\n console.error('resources.resource-types.load', err)\n if (!cancelled) setError(t('resources.resourceTypes.errors.load', 'Failed to load resource types.'))\n } finally {\n if (!cancelled) setLoading(false)\n }\n }\n void load()\n return () => { cancelled = true }\n }, [resourceTypeId, t])\n\n const handleSubmit = React.useCallback(async (values: ResourceTypeFormValues) => {\n if (!resourceTypeId) return\n const payload = buildResourceTypePayload(values, { id: resourceTypeId })\n await updateCrud('resources/resource-types', payload, {\n errorMessage: t('resources.resourceTypes.errors.save', 'Failed to save resource type.'),\n })\n flash(t('resources.resourceTypes.messages.saved', 'Resource type saved.'), 'success')\n router.push('/backend/resources/resource-types')\n }, [resourceTypeId, router, t])\n\n const handleDelete = React.useCallback(async () => {\n if (!resourceTypeId) return\n if (resourceCount > 0) {\n flash(t('resources.resourceTypes.errors.deleteAssigned', 'Resource type has assigned resources.'), 'error')\n return\n }\n await deleteCrud('resources/resource-types', resourceTypeId, {\n errorMessage: t('resources.resourceTypes.errors.delete', 'Failed to delete resource type.'),\n })\n flash(t('resources.resourceTypes.messages.deleted', 'Resource type deleted.'), 'success')\n router.push('/backend/resources/resource-types')\n }, [resourceCount, resourceTypeId, router, t])\n\n if (isNotFound) {\n return (\n <Page>\n <PageBody>\n <RecordNotFoundState\n label={t('resources.resourceTypes.errors.notFound', 'Resource type not found.')}\n backHref=\"/backend/resources/resource-types\"\n backLabel={t('resources.resourceTypes.actions.backToList', 'Back to resource types')}\n />\n </PageBody>\n </Page>\n )\n }\n\n return (\n <Page>\n <PageBody>\n {error ? (\n <ErrorMessage label={error} />\n ) : null}\n {/* optimistic-lock: ResourceTypeCrudForm forwards optimisticLockUpdatedAt from initialValues.updatedAt (auto-derives the header on save + delete). */}\n <ResourceTypeCrudForm\n mode=\"edit\"\n initialValues={initialValues ?? { id: resourceTypeId, name: '', description: '', appearance: { icon: null, color: null } }}\n isLoading={loading}\n onSubmit={handleSubmit}\n onDelete={handleDelete}\n deleteVisible={resourceCount === 0}\n />\n </PageBody>\n </Page>\n )\n}\n"],
|
|
4
|
+
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { useRouter } from 'next/navigation'\nimport { Page, PageBody } from '@open-mercato/ui/backend/Page'\nimport { ErrorMessage, RecordNotFoundState } from '@open-mercato/ui/backend/detail'\nimport { readApiResultOrThrow } from '@open-mercato/ui/backend/utils/apiCall'\nimport { updateCrud, deleteCrud } from '@open-mercato/ui/backend/utils/crud'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { extractCustomFieldValues } from '@open-mercato/core/modules/sales/components/documents/customFieldHelpers'\nimport { buildResourceTypePayload, ResourceTypeCrudForm, type ResourceTypeFormValues } from '@open-mercato/core/modules/resources/components/ResourceTypeCrudForm'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\n\ntype ResourceTypesResponse = {\n items?: Array<Record<string, unknown>>\n}\n\nexport default function ResourcesResourceTypeEditPage({ params }: { params?: { id?: string } }) {\n const resourceTypeId = params?.id ?? ''\n const t = useT()\n const router = useRouter()\n const [initialValues, setInitialValues] = React.useState<ResourceTypeFormValues | null>(null)\n const [loading, setLoading] = React.useState(true)\n const [error, setError] = React.useState<string | null>(null)\n const [isNotFound, setIsNotFound] = React.useState(false)\n const [resourceCount, setResourceCount] = React.useState(0)\n\n React.useEffect(() => {\n if (!resourceTypeId) return\n let cancelled = false\n async function load() {\n setLoading(true)\n setError(null)\n setIsNotFound(false)\n try {\n const payload = await readApiResultOrThrow<ResourceTypesResponse>(\n `/api/resources/resource-types?ids=${encodeURIComponent(resourceTypeId)}&page=1&pageSize=1&withResourceCounts=true`,\n undefined,\n { errorMessage: t('resources.resourceTypes.errors.load', 'Failed to load resource types.') },\n )\n const item = Array.isArray(payload.items) ? payload.items[0] : null\n if (!item) {\n if (!cancelled) setIsNotFound(true)\n return\n }\n if (!cancelled) {\n const customValues = extractCustomFieldValues(item)\n setInitialValues({\n id: typeof item.id === 'string' ? item.id : resourceTypeId,\n name: typeof item.name === 'string' ? item.name : '',\n description: typeof item.description === 'string' ? item.description : '',\n appearance: {\n icon: typeof item.appearanceIcon === 'string'\n ? item.appearanceIcon\n : typeof item.appearance_icon === 'string'\n ? item.appearance_icon\n : null,\n color: typeof item.appearanceColor === 'string'\n ? item.appearanceColor\n : typeof item.appearance_color === 'string'\n ? item.appearance_color\n : null,\n },\n updatedAt: typeof item.updatedAt === 'string'\n ? item.updatedAt\n : typeof item.updated_at === 'string'\n ? item.updated_at\n : null,\n ...customValues,\n })\n setResourceCount(typeof item.resourceCount === 'number'\n ? item.resourceCount\n : typeof item.resource_count === 'number'\n ? item.resource_count\n : 0)\n }\n } catch (err) {\n console.error('resources.resource-types.load', err)\n if (!cancelled) setError(t('resources.resourceTypes.errors.load', 'Failed to load resource types.'))\n } finally {\n if (!cancelled) setLoading(false)\n }\n }\n void load()\n return () => { cancelled = true }\n }, [resourceTypeId, t])\n\n const handleSubmit = React.useCallback(async (values: ResourceTypeFormValues) => {\n if (!resourceTypeId) return\n const payload = buildResourceTypePayload(values, { id: resourceTypeId })\n await updateCrud('resources/resource-types', payload, {\n errorMessage: t('resources.resourceTypes.errors.save', 'Failed to save resource type.'),\n })\n flash(t('resources.resourceTypes.messages.saved', 'Resource type saved.'), 'success')\n router.push('/backend/resources/resource-types')\n }, [resourceTypeId, router, t])\n\n const handleDelete = React.useCallback(async () => {\n if (!resourceTypeId) return\n if (resourceCount > 0) {\n flash(t('resources.resourceTypes.errors.deleteAssigned', 'Resource type has assigned resources.'), 'error')\n return\n }\n await deleteCrud('resources/resource-types', resourceTypeId, {\n errorMessage: t('resources.resourceTypes.errors.delete', 'Failed to delete resource type.'),\n })\n flash(t('resources.resourceTypes.messages.deleted', 'Resource type deleted.'), 'success')\n router.push('/backend/resources/resource-types')\n }, [resourceCount, resourceTypeId, router, t])\n\n if (isNotFound) {\n return (\n <Page>\n <PageBody>\n <RecordNotFoundState\n label={t('resources.resourceTypes.errors.notFound', 'Resource type not found.')}\n backHref=\"/backend/resources/resource-types\"\n backLabel={t('resources.resourceTypes.actions.backToList', 'Back to resource types')}\n />\n </PageBody>\n </Page>\n )\n }\n\n return (\n <Page>\n <PageBody>\n {error ? (\n <ErrorMessage label={error} />\n ) : null}\n {/* optimistic-lock: ResourceTypeCrudForm forwards optimisticLockUpdatedAt from initialValues.updatedAt (auto-derives the header on save + delete). */}\n <ResourceTypeCrudForm\n mode=\"edit\"\n initialValues={initialValues ?? { id: resourceTypeId, name: '', description: '', appearance: { icon: null, color: null } }}\n isLoading={loading}\n onSubmit={handleSubmit}\n onDelete={handleDelete}\n deleteVisible={resourceCount === 0}\n />\n </PageBody>\n </Page>\n )\n}\n"],
|
|
5
5
|
"mappings": ";AAkHU,cAYJ,YAZI;AAhHV,YAAY,WAAW;AACvB,SAAS,iBAAiB;AAC1B,SAAS,MAAM,gBAAgB;AAC/B,SAAS,cAAc,2BAA2B;AAClD,SAAS,4BAA4B;AACrC,SAAS,YAAY,kBAAkB;AACvC,SAAS,aAAa;AACtB,SAAS,gCAAgC;AACzC,SAAS,0BAA0B,4BAAyD;AAC5F,SAAS,YAAY;AAMN,SAAR,8BAA+C,EAAE,OAAO,GAAiC;AAC9F,QAAM,iBAAiB,QAAQ,MAAM;AACrC,QAAM,IAAI,KAAK;AACf,QAAM,SAAS,UAAU;AACzB,QAAM,CAAC,eAAe,gBAAgB,IAAI,MAAM,SAAwC,IAAI;AAC5F,QAAM,CAAC,SAAS,UAAU,IAAI,MAAM,SAAS,IAAI;AACjD,QAAM,CAAC,OAAO,QAAQ,IAAI,MAAM,SAAwB,IAAI;AAC5D,QAAM,CAAC,YAAY,aAAa,IAAI,MAAM,SAAS,KAAK;AACxD,QAAM,CAAC,eAAe,gBAAgB,IAAI,MAAM,SAAS,CAAC;AAE1D,QAAM,UAAU,MAAM;AACpB,QAAI,CAAC,eAAgB;AACrB,QAAI,YAAY;AAChB,mBAAe,OAAO;AACpB,iBAAW,IAAI;AACf,eAAS,IAAI;AACb,oBAAc,KAAK;AACnB,UAAI;AACF,cAAM,UAAU,MAAM;AAAA,UACpB,qCAAqC,mBAAmB,cAAc,CAAC;AAAA,UACvE;AAAA,UACA,EAAE,cAAc,EAAE,uCAAuC,gCAAgC,EAAE;AAAA,QAC7F;AACA,cAAM,OAAO,MAAM,QAAQ,QAAQ,KAAK,IAAI,QAAQ,MAAM,CAAC,IAAI;AAC/D,YAAI,CAAC,MAAM;AACT,cAAI,CAAC,UAAW,eAAc,IAAI;AAClC;AAAA,Q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AsB,GAAG,SAAS;AACpF,WAAO,KAAK,mCAAmC;AAAA,EACjD,GAAG,CAAC,gBAAgB,QAAQ,CAAC,CAAC;AAE9B,QAAM,eAAe,MAAM,YAAY,YAAY;AACjD,QAAI,CAAC,eAAgB;AACrB,QAAI,gBAAgB,GAAG;AACrB,YAAM,EAAE,iDAAiD,uCAAuC,GAAG,OAAO;AAC1G;AAAA,IACF;AACA,UAAM,WAAW,4BAA4B,gBAAgB;AAAA,MAC3D,cAAc,EAAE,yCAAyC,iCAAiC;AAAA,IAC5F,CAAC;AACD,UAAM,EAAE,4CAA4C,wBAAwB,GAAG,SAAS;AACxF,WAAO,KAAK,mCAAmC;AAAA,EACjD,GAAG,CAAC,eAAe,gBAAgB,QAAQ,CAAC,CAAC;AAE7C,MAAI,YAAY;AACd,WACE,oBAAC,QACC,8BAAC,YACC;AAAA,MAAC;AAAA;AAAA,QACC,OAAO,EAAE,2CAA2C,0BAA0B;AAAA,QAC9E,UAAS;AAAA,QACT,WAAW,EAAE,8CAA8C,wBAAwB;AAAA;AAAA,IACrF,GACF,GACF;AAAA,EAEJ;AAEA,SACE,oBAAC,QACC,+BAAC,YACE;AAAA,YACC,oBAAC,gBAAa,OAAO,OAAO,IAC1B;AAAA,IAEJ;AAAA,MAAC;AAAA;AAAA,QACC,MAAK;AAAA,QACL,eAAe,iBAAiB,EAAE,IAAI,gBAAgB,MAAM,IAAI,aAAa,IAAI,YAAY,EAAE,MAAM,MAAM,OAAO,KAAK,EAAE;AAAA,QACzH,WAAW;AAAA,QACX,UAAU;AAAA,QACV,UAAU;AAAA,QACV,eAAe,kBAAkB;AAAA;AAAA,IACnC;AAAA,KACF,GACF;AAEJ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -160,7 +160,8 @@ function ResourcesResourceTypesPage() {
|
|
|
160
160
|
try {
|
|
161
161
|
const params = new URLSearchParams({
|
|
162
162
|
page: String(page),
|
|
163
|
-
pageSize: String(PAGE_SIZE)
|
|
163
|
+
pageSize: String(PAGE_SIZE),
|
|
164
|
+
withResourceCounts: "true"
|
|
164
165
|
});
|
|
165
166
|
const sort = sorting[0];
|
|
166
167
|
if (sort?.id) {
|
|
@@ -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 { 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;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,UAAU,OAAO,SAAS;AAAA,
|
|
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 withResourceCounts: 'true',\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,iBAAiB;AAC1B,OAAO,UAAU;AAEjB,SAAS,MAAM,gBAAgB;AAC/B,SAAS,2BAA2B;AACpC,SAAS,WAAW,+BAA+B;AACnD,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAC3B,SAAS,aAA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IAAI,MAAM,aAAa,gBAAgB,iBAAiB,WAAW,cAAc,GAAG,IAAI;AAC3H;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -11,6 +11,7 @@ import { useT } from "@open-mercato/shared/lib/i18n/context";
|
|
|
11
11
|
import { apiCallOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
|
|
12
12
|
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
|
|
13
13
|
import { flash } from "@open-mercato/ui/backend/FlashMessages";
|
|
14
|
+
import { normalizeCrudServerError } from "@open-mercato/ui/backend/utils/serverErrors";
|
|
14
15
|
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
|
|
15
16
|
import { computeAvailableReturnQuantity } from "@open-mercato/core/modules/sales/lib/returnQuantity";
|
|
16
17
|
import { handleSectionMutationError } from "./optimisticLock.js";
|
|
@@ -106,7 +107,9 @@ function ReturnDialog({ open, orderId, lines, documentUpdatedAt, onClose, onSave
|
|
|
106
107
|
onClose();
|
|
107
108
|
return;
|
|
108
109
|
}
|
|
109
|
-
|
|
110
|
+
const normalized = normalizeCrudServerError(err);
|
|
111
|
+
const fallback = t("sales.returns.errors.create", "Failed to create return.");
|
|
112
|
+
flash(normalized.message || fallback, "error");
|
|
110
113
|
} finally {
|
|
111
114
|
setSaving(false);
|
|
112
115
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/sales/components/documents/ReturnDialog.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { Dialog, DialogContent, DialogHeader, DialogTitle } from '@open-mercato/ui/primitives/dialog'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { CounterInput } from '@open-mercato/ui/primitives/counter-input'\nimport { Textarea } from '@open-mercato/ui/primitives/textarea'\nimport { Label } from '@open-mercato/ui/primitives/label'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { apiCallOrThrow, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { computeAvailableReturnQuantity } from '@open-mercato/core/modules/sales/lib/returnQuantity'\nimport { handleSectionMutationError } from './optimisticLock'\n\nexport type ReturnOrderLine = {\n id: string\n title: string\n lineNumber: number | null\n quantity: number\n returnedQuantity: number\n thumbnail?: string | null\n}\n\ntype ReturnDialogProps = {\n open: boolean\n orderId: string\n lines: ReturnOrderLine[]\n documentUpdatedAt?: string | null\n onClose: () => void\n onSaved: () => Promise<void>\n}\n\nconst normalizeNumber = (value: unknown): number => {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string' && value.trim().length) {\n const parsed = Number(value)\n if (Number.isFinite(parsed)) return parsed\n }\n return 0\n}\n\nexport function ReturnDialog({ open, orderId, lines, documentUpdatedAt, onClose, onSaved }: ReturnDialogProps) {\n const t = useT()\n const { runMutation } = useGuardedMutation({ contextId: `sales-returns-${orderId}` })\n const [reason, setReason] = React.useState('')\n const [notes, setNotes] = React.useState('')\n const [quantities, setQuantities] = React.useState<Record<string, string>>({})\n const [saving, setSaving] = React.useState(false)\n\n const availableLines = React.useMemo(() => {\n return lines\n .map((line) => {\n const available = computeAvailableReturnQuantity(line)\n return { ...line, available }\n })\n .filter((line) => line.available > 0)\n }, [lines])\n\n React.useEffect(() => {\n if (!open) return\n setReason('')\n setNotes('')\n setQuantities({})\n }, [open])\n\n const submit = React.useCallback(async () => {\n if (saving) return\n let hasInvalidQuantity = false\n let hasNonInteger = false\n const linesForRequest: Array<{ orderLineId: string; quantity: string }> = []\n availableLines.forEach((line) => {\n const raw = quantities[line.id]\n const qty = normalizeNumber(raw)\n if (!Number.isFinite(qty) || qty <= 0) return\n if (!Number.isInteger(qty)) {\n hasNonInteger = true\n return\n }\n if (qty > line.available) {\n hasInvalidQuantity = true\n return\n }\n linesForRequest.push({ orderLineId: line.id, quantity: qty.toString() })\n })\n\n if (hasNonInteger) {\n flash(t('sales.returns.errors.quantityNotInteger', 'Return quantity must be a whole number.'), 'error')\n return\n }\n\n if (hasInvalidQuantity) {\n flash(t('sales.returns.errors.quantityExceeded', 'Cannot return more than available quantity.'), 'error')\n return\n }\n\n if (!linesForRequest.length) {\n flash(t('sales.returns.errors.linesRequired', 'Select at least one line to return.'), 'error')\n return\n }\n\n setSaving(true)\n try {\n await runMutation({\n context: { kind: 'order', record: { id: orderId } },\n mutationPayload: { orderId, lines: linesForRequest, reason, notes },\n operation: async () => {\n const response = await withScopedApiRequestHeaders(\n buildOptimisticLockHeader(documentUpdatedAt),\n () =>\n apiCallOrThrow<{ id: string | null }>(\n '/api/sales/returns',\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n orderId,\n lines: linesForRequest,\n ...(reason.trim().length ? { reason: reason.trim() } : {}),\n ...(notes.trim().length ? { notes: notes.trim() } : {}),\n }),\n },\n { errorMessage: t('sales.returns.errors.create', 'Failed to create return.') },\n ),\n )\n return response.result?.id ?? null\n },\n })\n flash(t('sales.returns.created', 'Return created.'), 'success')\n onClose()\n await onSaved()\n } catch (err) {\n if (handleSectionMutationError(err, t, () => void onSaved())) {\n onClose()\n return\n }\n flash(t('sales.returns.errors.create', 'Failed to create return.'), 'error')\n } finally {\n setSaving(false)\n }\n }, [availableLines, documentUpdatedAt, notes, onClose, onSaved, orderId, quantities, reason, runMutation, saving, t])\n\n const onKeyDown = React.useCallback(\n (e: React.KeyboardEvent) => {\n if (e.key === 'Escape') onClose()\n if ((e.key === 'Enter' || e.key === 'NumpadEnter') && (e.metaKey || e.ctrlKey)) {\n e.preventDefault()\n submit()\n }\n },\n [onClose, submit],\n )\n\n return (\n <Dialog open={open} onOpenChange={(next) => (!next ? onClose() : undefined)}>\n <DialogContent onKeyDown={onKeyDown} className=\"max-w-2xl\">\n <DialogHeader>\n <DialogTitle>{t('sales.returns.create.title', 'Create return')}</DialogTitle>\n </DialogHeader>\n\n <div className=\"space-y-4\">\n <div className=\"space-y-2\">\n <div className=\"text-sm font-medium\">{t('sales.returns.create.lines', 'Lines')}</div>\n {!availableLines.length ? (\n <div className=\"text-sm text-muted-foreground\">{t('sales.returns.empty.available', 'No items available to return.')}</div>\n ) : (\n <div className=\"max-h-[280px] overflow-auto rounded-md border\">\n <div className=\"divide-y\">\n {availableLines.map((line) => {\n const value = quantities[line.id] ?? ''\n return (\n <div key={line.id} className=\"flex items-center gap-3 p-3\">\n <div className=\"min-w-0 flex-1\">\n <div className=\"truncate text-sm font-medium\">\n {line.lineNumber ? `#${line.lineNumber} \u00B7 ` : ''}\n {line.title}\n </div>\n <div className=\"text-xs text-muted-foreground\">\n {t('sales.returns.available', 'Available')}: {line.available}\n </div>\n </div>\n <div className=\"w-32\">\n <Label className=\"sr-only\" htmlFor={`return-qty-${line.id}`}>\n {t('sales.returns.quantity', 'Quantity')}\n </Label>\n <CounterInput\n id={`return-qty-${line.id}`}\n min={1}\n max={line.available}\n step={1}\n placeholder=\"0\"\n value={value === '' ? null : Number(value)}\n onChange={(next) => {\n setQuantities((prev) => ({\n ...prev,\n [line.id]: next === null ? '' : String(next),\n }))\n }}\n decrementAriaLabel={t('sales.returns.qty.decrease', 'Decrease quantity')}\n incrementAriaLabel={t('sales.returns.qty.increase', 'Increase quantity')}\n />\n </div>\n </div>\n )\n })}\n </div>\n </div>\n )}\n </div>\n\n <div className=\"grid grid-cols-1 gap-4 md:grid-cols-2\">\n <div className=\"space-y-1.5\">\n <Label htmlFor=\"return-reason\">{t('sales.returns.reason', 'Reason')}</Label>\n <Input\n id=\"return-reason\"\n value={reason}\n onChange={(e) => setReason(e.target.value)}\n placeholder={t('sales.returns.reason.placeholder', 'Optional')}\n />\n </div>\n <div className=\"space-y-1.5 md:col-span-2\">\n <Label htmlFor=\"return-notes\">{t('sales.returns.notes', 'Notes')}</Label>\n <Textarea\n id=\"return-notes\"\n value={notes}\n onChange={(e) => setNotes(e.target.value)}\n placeholder={t('sales.returns.notes.placeholder', 'Optional')}\n rows={3}\n />\n </div>\n </div>\n\n <div className=\"flex items-center justify-end gap-2\">\n <Button type=\"button\" variant=\"outline\" onClick={onClose} disabled={saving}>\n {t('common.cancel', 'Cancel')}\n </Button>\n <Button type=\"button\" onClick={submit} disabled={saving || !availableLines.length}>\n {saving ? t('common.saving', 'Saving\u2026') : t('sales.returns.create.submit', 'Create return')}\n </Button>\n </div>\n </div>\n </DialogContent>\n </Dialog>\n )\n}\n\n"],
|
|
5
|
-
"mappings": ";
|
|
4
|
+
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { Dialog, DialogContent, DialogHeader, DialogTitle } from '@open-mercato/ui/primitives/dialog'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { CounterInput } from '@open-mercato/ui/primitives/counter-input'\nimport { Textarea } from '@open-mercato/ui/primitives/textarea'\nimport { Label } from '@open-mercato/ui/primitives/label'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { apiCallOrThrow, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { normalizeCrudServerError } from '@open-mercato/ui/backend/utils/serverErrors'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { computeAvailableReturnQuantity } from '@open-mercato/core/modules/sales/lib/returnQuantity'\nimport { handleSectionMutationError } from './optimisticLock'\n\nexport type ReturnOrderLine = {\n id: string\n title: string\n lineNumber: number | null\n quantity: number\n returnedQuantity: number\n thumbnail?: string | null\n}\n\ntype ReturnDialogProps = {\n open: boolean\n orderId: string\n lines: ReturnOrderLine[]\n documentUpdatedAt?: string | null\n onClose: () => void\n onSaved: () => Promise<void>\n}\n\nconst normalizeNumber = (value: unknown): number => {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string' && value.trim().length) {\n const parsed = Number(value)\n if (Number.isFinite(parsed)) return parsed\n }\n return 0\n}\n\nexport function ReturnDialog({ open, orderId, lines, documentUpdatedAt, onClose, onSaved }: ReturnDialogProps) {\n const t = useT()\n const { runMutation } = useGuardedMutation({ contextId: `sales-returns-${orderId}` })\n const [reason, setReason] = React.useState('')\n const [notes, setNotes] = React.useState('')\n const [quantities, setQuantities] = React.useState<Record<string, string>>({})\n const [saving, setSaving] = React.useState(false)\n\n const availableLines = React.useMemo(() => {\n return lines\n .map((line) => {\n const available = computeAvailableReturnQuantity(line)\n return { ...line, available }\n })\n .filter((line) => line.available > 0)\n }, [lines])\n\n React.useEffect(() => {\n if (!open) return\n setReason('')\n setNotes('')\n setQuantities({})\n }, [open])\n\n const submit = React.useCallback(async () => {\n if (saving) return\n let hasInvalidQuantity = false\n let hasNonInteger = false\n const linesForRequest: Array<{ orderLineId: string; quantity: string }> = []\n availableLines.forEach((line) => {\n const raw = quantities[line.id]\n const qty = normalizeNumber(raw)\n if (!Number.isFinite(qty) || qty <= 0) return\n if (!Number.isInteger(qty)) {\n hasNonInteger = true\n return\n }\n if (qty > line.available) {\n hasInvalidQuantity = true\n return\n }\n linesForRequest.push({ orderLineId: line.id, quantity: qty.toString() })\n })\n\n if (hasNonInteger) {\n flash(t('sales.returns.errors.quantityNotInteger', 'Return quantity must be a whole number.'), 'error')\n return\n }\n\n if (hasInvalidQuantity) {\n flash(t('sales.returns.errors.quantityExceeded', 'Cannot return more than available quantity.'), 'error')\n return\n }\n\n if (!linesForRequest.length) {\n flash(t('sales.returns.errors.linesRequired', 'Select at least one line to return.'), 'error')\n return\n }\n\n setSaving(true)\n try {\n await runMutation({\n context: { kind: 'order', record: { id: orderId } },\n mutationPayload: { orderId, lines: linesForRequest, reason, notes },\n operation: async () => {\n const response = await withScopedApiRequestHeaders(\n buildOptimisticLockHeader(documentUpdatedAt),\n () =>\n apiCallOrThrow<{ id: string | null }>(\n '/api/sales/returns',\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n orderId,\n lines: linesForRequest,\n ...(reason.trim().length ? { reason: reason.trim() } : {}),\n ...(notes.trim().length ? { notes: notes.trim() } : {}),\n }),\n },\n { errorMessage: t('sales.returns.errors.create', 'Failed to create return.') },\n ),\n )\n return response.result?.id ?? null\n },\n })\n flash(t('sales.returns.created', 'Return created.'), 'success')\n onClose()\n await onSaved()\n } catch (err) {\n if (handleSectionMutationError(err, t, () => void onSaved())) {\n onClose()\n return\n }\n const normalized = normalizeCrudServerError(err)\n const fallback = t('sales.returns.errors.create', 'Failed to create return.')\n flash(normalized.message || fallback, 'error')\n } finally {\n setSaving(false)\n }\n }, [availableLines, documentUpdatedAt, notes, onClose, onSaved, orderId, quantities, reason, runMutation, saving, t])\n\n const onKeyDown = React.useCallback(\n (e: React.KeyboardEvent) => {\n if (e.key === 'Escape') onClose()\n if ((e.key === 'Enter' || e.key === 'NumpadEnter') && (e.metaKey || e.ctrlKey)) {\n e.preventDefault()\n submit()\n }\n },\n [onClose, submit],\n )\n\n return (\n <Dialog open={open} onOpenChange={(next) => (!next ? onClose() : undefined)}>\n <DialogContent onKeyDown={onKeyDown} className=\"max-w-2xl\">\n <DialogHeader>\n <DialogTitle>{t('sales.returns.create.title', 'Create return')}</DialogTitle>\n </DialogHeader>\n\n <div className=\"space-y-4\">\n <div className=\"space-y-2\">\n <div className=\"text-sm font-medium\">{t('sales.returns.create.lines', 'Lines')}</div>\n {!availableLines.length ? (\n <div className=\"text-sm text-muted-foreground\">{t('sales.returns.empty.available', 'No items available to return.')}</div>\n ) : (\n <div className=\"max-h-[280px] overflow-auto rounded-md border\">\n <div className=\"divide-y\">\n {availableLines.map((line) => {\n const value = quantities[line.id] ?? ''\n return (\n <div key={line.id} className=\"flex items-center gap-3 p-3\">\n <div className=\"min-w-0 flex-1\">\n <div className=\"truncate text-sm font-medium\">\n {line.lineNumber ? `#${line.lineNumber} \u00B7 ` : ''}\n {line.title}\n </div>\n <div className=\"text-xs text-muted-foreground\">\n {t('sales.returns.available', 'Available')}: {line.available}\n </div>\n </div>\n <div className=\"w-32\">\n <Label className=\"sr-only\" htmlFor={`return-qty-${line.id}`}>\n {t('sales.returns.quantity', 'Quantity')}\n </Label>\n <CounterInput\n id={`return-qty-${line.id}`}\n min={1}\n max={line.available}\n step={1}\n placeholder=\"0\"\n value={value === '' ? null : Number(value)}\n onChange={(next) => {\n setQuantities((prev) => ({\n ...prev,\n [line.id]: next === null ? '' : String(next),\n }))\n }}\n decrementAriaLabel={t('sales.returns.qty.decrease', 'Decrease quantity')}\n incrementAriaLabel={t('sales.returns.qty.increase', 'Increase quantity')}\n />\n </div>\n </div>\n )\n })}\n </div>\n </div>\n )}\n </div>\n\n <div className=\"grid grid-cols-1 gap-4 md:grid-cols-2\">\n <div className=\"space-y-1.5\">\n <Label htmlFor=\"return-reason\">{t('sales.returns.reason', 'Reason')}</Label>\n <Input\n id=\"return-reason\"\n value={reason}\n onChange={(e) => setReason(e.target.value)}\n placeholder={t('sales.returns.reason.placeholder', 'Optional')}\n />\n </div>\n <div className=\"space-y-1.5 md:col-span-2\">\n <Label htmlFor=\"return-notes\">{t('sales.returns.notes', 'Notes')}</Label>\n <Textarea\n id=\"return-notes\"\n value={notes}\n onChange={(e) => setNotes(e.target.value)}\n placeholder={t('sales.returns.notes.placeholder', 'Optional')}\n rows={3}\n />\n </div>\n </div>\n\n <div className=\"flex items-center justify-end gap-2\">\n <Button type=\"button\" variant=\"outline\" onClick={onClose} disabled={saving}>\n {t('common.cancel', 'Cancel')}\n </Button>\n <Button type=\"button\" onClick={submit} disabled={saving || !availableLines.length}>\n {saving ? t('common.saving', 'Saving\u2026') : t('sales.returns.create.submit', 'Create return')}\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EJ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -147,6 +147,17 @@ const extractShipmentAddressSnapshot = (metadata) => {
|
|
|
147
147
|
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
|
|
148
148
|
return normalizeAddressSnapshot(raw);
|
|
149
149
|
};
|
|
150
|
+
const addressOptionsSignature = (options) => options.map((option) => `${snapshotKey(option.snapshot) ?? ""}::${option.id}`).join("||");
|
|
151
|
+
function useStableAddressOptions(options) {
|
|
152
|
+
const signature = addressOptionsSignature(options);
|
|
153
|
+
const stableRef = React.useRef(options);
|
|
154
|
+
const signatureRef = React.useRef(signature);
|
|
155
|
+
if (signatureRef.current !== signature) {
|
|
156
|
+
signatureRef.current = signature;
|
|
157
|
+
stableRef.current = options;
|
|
158
|
+
}
|
|
159
|
+
return stableRef.current;
|
|
160
|
+
}
|
|
150
161
|
function ShipmentDialog({
|
|
151
162
|
open,
|
|
152
163
|
mode,
|
|
@@ -206,7 +217,7 @@ function ShipmentDialog({
|
|
|
206
217
|
}),
|
|
207
218
|
[shipmentAddressSnapshot, t]
|
|
208
219
|
);
|
|
209
|
-
const
|
|
220
|
+
const computedBaseAddressOptions = React.useMemo(
|
|
210
221
|
() => dedupeAddressOptions(
|
|
211
222
|
[shippingAddressOption, shipmentAddressOption].filter(
|
|
212
223
|
(entry) => Boolean(entry)
|
|
@@ -214,6 +225,7 @@ function ShipmentDialog({
|
|
|
214
225
|
),
|
|
215
226
|
[shipmentAddressOption, shippingAddressOption]
|
|
216
227
|
);
|
|
228
|
+
const baseAddressOptions = useStableAddressOptions(computedBaseAddressOptions);
|
|
217
229
|
const preferredAddressId = React.useMemo(() => {
|
|
218
230
|
const shipmentKey = snapshotKey(shipmentAddressSnapshot);
|
|
219
231
|
if (shipmentKey) {
|
|
@@ -319,7 +331,10 @@ function ShipmentDialog({
|
|
|
319
331
|
[t]
|
|
320
332
|
);
|
|
321
333
|
const mergeAddressOptions = React.useCallback(
|
|
322
|
-
(options) => setAddressOptions((prev) =>
|
|
334
|
+
(options) => setAddressOptions((prev) => {
|
|
335
|
+
const next = dedupeAddressOptions([...prev, ...options]);
|
|
336
|
+
return next.length === prev.length ? prev : next;
|
|
337
|
+
}),
|
|
323
338
|
[]
|
|
324
339
|
);
|
|
325
340
|
const loadAddressOptions = React.useCallback(async () => {
|