@open-mercato/core 0.6.6-develop.6403.1.b57089b6fe → 0.6.6-develop.6406.1.a0bd770daf
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/dist/modules/attachments/api/route.js +10 -4
- package/dist/modules/attachments/api/route.js.map +2 -2
- package/dist/modules/catalog/widgets/injection/product-seo/state.js +9 -0
- package/dist/modules/catalog/widgets/injection/product-seo/state.js.map +2 -2
- package/dist/modules/catalog/widgets/injection/product-seo/validation.js +29 -15
- package/dist/modules/catalog/widgets/injection/product-seo/validation.js.map +2 -2
- package/dist/modules/catalog/widgets/injection/product-seo/widget.client.js +5 -1
- package/dist/modules/catalog/widgets/injection/product-seo/widget.client.js.map +2 -2
- package/dist/modules/catalog/widgets/injection/product-seo/widget.js +2 -2
- package/dist/modules/catalog/widgets/injection/product-seo/widget.js.map +2 -2
- package/dist/modules/customers/api/pipeline-stages/route.js +6 -4
- package/dist/modules/customers/api/pipeline-stages/route.js.map +2 -2
- package/dist/modules/customers/api/pipelines/route.js +5 -3
- package/dist/modules/customers/api/pipelines/route.js.map +2 -2
- package/dist/modules/staff/api/team-members/assignable/route.js +7 -11
- package/dist/modules/staff/api/team-members/assignable/route.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/attachments/api/route.ts +20 -4
- package/src/modules/attachments/i18n/de.json +1 -0
- package/src/modules/attachments/i18n/en.json +1 -0
- package/src/modules/attachments/i18n/es.json +1 -0
- package/src/modules/attachments/i18n/pl.json +1 -0
- package/src/modules/catalog/i18n/de.json +10 -0
- package/src/modules/catalog/i18n/en.json +10 -0
- package/src/modules/catalog/i18n/es.json +10 -0
- package/src/modules/catalog/i18n/pl.json +10 -0
- package/src/modules/catalog/widgets/injection/product-seo/state.ts +17 -0
- package/src/modules/catalog/widgets/injection/product-seo/validation.ts +38 -15
- package/src/modules/catalog/widgets/injection/product-seo/widget.client.tsx +7 -1
- package/src/modules/catalog/widgets/injection/product-seo/widget.ts +2 -2
- package/src/modules/customers/api/pipeline-stages/route.ts +6 -4
- package/src/modules/customers/api/pipelines/route.ts +5 -3
- package/src/modules/staff/api/team-members/assignable/route.ts +8 -12
package/.turbo/turbo-build.log
CHANGED
|
@@ -232,7 +232,12 @@ async function GET(req) {
|
|
|
232
232
|
async function POST(req) {
|
|
233
233
|
const { t } = await resolveTranslations();
|
|
234
234
|
const auth = await getAuthFromRequest(req);
|
|
235
|
-
if (!auth || !auth.tenantId || !auth.orgId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
235
|
+
if (!auth || !auth.tenantId || !auth.orgId && !auth.isSuperAdmin) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
236
|
+
if (!auth.orgId) {
|
|
237
|
+
return NextResponse.json({
|
|
238
|
+
error: t("attachments.errors.selectOrganization", "Select a specific organization before uploading an attachment.")
|
|
239
|
+
}, { status: 400 });
|
|
240
|
+
}
|
|
236
241
|
const tenantId = auth.tenantId;
|
|
237
242
|
const orgId = auth.orgId;
|
|
238
243
|
const contentType = req.headers.get("content-type") || "";
|
|
@@ -471,7 +476,7 @@ async function readTenantAttachmentUsageBytes(em, tenantId) {
|
|
|
471
476
|
}
|
|
472
477
|
async function DELETE(req) {
|
|
473
478
|
const auth = await getAuthFromRequest(req);
|
|
474
|
-
if (!auth || !auth.tenantId || !auth.orgId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
479
|
+
if (!auth || !auth.tenantId || !auth.orgId && !auth.isSuperAdmin) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
475
480
|
const url = new URL(req.url);
|
|
476
481
|
const id = url.searchParams.get("id") || "";
|
|
477
482
|
if (!id) return NextResponse.json({ error: "Attachment id is required" }, { status: 400 });
|
|
@@ -479,7 +484,8 @@ async function DELETE(req) {
|
|
|
479
484
|
const em = resolve("em");
|
|
480
485
|
const dataEngine = resolve("dataEngine");
|
|
481
486
|
const storageDriverFactory = resolve("storageDriverFactory") ?? new StorageDriverFactory(em);
|
|
482
|
-
const deleteFilter = { id, tenantId: auth.tenantId
|
|
487
|
+
const deleteFilter = { id, tenantId: auth.tenantId };
|
|
488
|
+
if (auth.orgId) deleteFilter.organizationId = auth.orgId;
|
|
483
489
|
const record = await em.findOne(Attachment, deleteFilter);
|
|
484
490
|
if (!record) return NextResponse.json({ error: "Attachment not found" }, { status: 404 });
|
|
485
491
|
await em.remove(record).flush();
|
|
@@ -489,7 +495,7 @@ async function DELETE(req) {
|
|
|
489
495
|
if (record.storagePath) {
|
|
490
496
|
const delDriver = await storageDriverFactory.resolveForPartition(record.partitionCode, {
|
|
491
497
|
tenantId: record.tenantId ?? auth.tenantId,
|
|
492
|
-
organizationId: record.organizationId ?? auth.orgId
|
|
498
|
+
organizationId: record.organizationId ?? auth.orgId ?? ""
|
|
493
499
|
});
|
|
494
500
|
await delDriver.delete(record.partitionCode, record.storagePath);
|
|
495
501
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/attachments/api/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { z } from 'zod'\nimport { sql } from 'kysely'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { buildAttachmentFileUrl, buildAttachmentImageUrl, slugifyAttachmentFileName } from '../lib/imageUrls'\nimport { ensureDefaultPartitions, resolveDefaultPartitionCode, sanitizePartitionCode } from '../lib/partitions'\nimport { Attachment, AttachmentPartition } from '../data/entities'\nimport { extractAttachmentContent } from '../lib/textExtraction'\nimport { requestOcrProcessing } from '../lib/ocrQueue'\nimport { StorageDriverFactory } from '../lib/drivers'\nimport { OcrService, shouldUseLlmOcr } from '../lib/ocrService'\nimport { clearAttachmentThumbnailCache } from '../lib/thumbnailCache'\nimport { assertAttachmentScopeInvariant } from '../lib/access'\nimport {\n mergeAttachmentMetadata,\n normalizeAttachmentAssignments,\n normalizeAttachmentTags,\n readAttachmentMetadata,\n upsertAssignment,\n type AttachmentAssignment,\n} from '../lib/metadata'\nimport { randomUUID } from 'crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { splitCustomFieldPayload } from '@open-mercato/shared/lib/crud/custom-fields'\nimport { emitCrudSideEffects, setCustomFieldsIfAny } from '@open-mercato/shared/lib/commands/helpers'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { attachmentCrudEvents, attachmentCrudIndexer } from '../lib/crud'\nimport { E } from '#generated/entities.ids.generated'\nimport { resolveDefaultAttachmentOcrEnabled } from '../lib/ocrConfig'\nimport {\n detectAttachmentMimeType,\n hasDangerousExecutableExtension,\n isActiveContentAttachment,\n sanitizeUploadedFileName,\n} from '../lib/security'\nimport {\n isMultipartRequestWithinUploadLimit,\n resolveAttachmentMaxBytes,\n willExceedAttachmentTenantQuota,\n} from '../lib/upload-limits'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['attachments.view'] },\n POST: { requireAuth: true, requireFeatures: ['attachments.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['attachments.manage'] },\n}\n\nconst attachmentQuerySchema = z.object({\n entityId: z.string().min(1).describe('Entity identifier that owns the attachments'),\n recordId: z.string().min(1).describe('Record identifier within the entity'),\n page: z.coerce.number().min(1).optional(),\n pageSize: z.coerce.number().min(1).max(100).optional(),\n})\n\nconst attachmentAssignmentSchema = z.object({\n type: z.string().describe('Assignment type identifier'),\n id: z.string().describe('Assignment record identifier'),\n href: z.string().nullable().optional().describe('Optional link to the related record'),\n label: z.string().nullable().optional().describe('Optional label for the assignment'),\n})\n\nconst attachmentItemSchema = z.object({\n id: z.string().describe('Attachment identifier'),\n url: z.string().describe('Public path to the stored asset'),\n fileName: z.string().describe('Original filename'),\n fileSize: z.number().int().nonnegative().describe('File size in bytes'),\n createdAt: z.string().describe('Upload timestamp (ISO 8601)'),\n mimeType: z.string().nullable().optional().describe('MIME type of the file'),\n thumbnailUrl: z.string().optional().describe('Helper route that renders a thumbnail'),\n partitionCode: z.string().optional().describe('Partition identifier'),\n tags: z.array(z.string()).optional().describe('Tags assigned to the attachment'),\n content: z.string().nullable().optional().describe('Extracted text or markdown content'),\n assignments: z.array(attachmentAssignmentSchema).optional().describe('Records that reference this attachment'),\n})\n\nconst attachmentListResponseSchema = z.object({\n items: z.array(attachmentItemSchema),\n total: z.number().int().nonnegative().optional(),\n page: z.number().int().min(1).optional(),\n pageSize: z.number().int().min(1).optional(),\n totalPages: z.number().int().min(1).optional(),\n})\n\nconst attachmentUploadBodySchema = z.object({\n entityId: z.string().min(1),\n recordId: z.string().min(1),\n fieldKey: z.string().optional(),\n file: z.string().min(1).describe('Binary file payload; supplied as multipart form-data'),\n customFields: z\n .string()\n .optional()\n .describe('JSON encoded map of custom field values collected from the upload form.'),\n})\n\nconst attachmentDeleteQuerySchema = z.object({\n id: z.string().uuid(),\n})\n\nconst uploadResponseSchema = z.object({\n ok: z.literal(true),\n item: z.object({\n id: z.string(),\n url: z.string(),\n fileName: z.string(),\n fileSize: z.number().int().nonnegative(),\n thumbnailUrl: z.string().optional(),\n content: z.string().nullable().optional(),\n tags: z.array(z.string()).optional(),\n assignments: z.array(attachmentAssignmentSchema).optional(),\n customFields: z.record(z.string(), z.unknown()).optional(),\n }),\n})\n\nconst errorSchema = z.object({\n error: z.string(),\n})\n\nconst LIBRARY_ENTITY_ID = 'attachments:library'\n\nfunction parseCustomFieldsEntry(value: FormDataEntryValue | null): Record<string, unknown> {\n if (!value) return {}\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (!trimmed) return {}\n try {\n const parsed = JSON.parse(trimmed)\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>\n }\n } catch {\n return {}\n }\n }\n if (typeof value === 'object' && !Array.isArray(value) && !(value instanceof File)) {\n return { ...(value as Record<string, unknown>) }\n }\n return {}\n}\n\nfunction buildFormPayload(form: FormData): Record<string, unknown> {\n const payload: Record<string, unknown> = {}\n form.forEach((value, key) => {\n if (key === 'customFields') {\n payload.customFields = parseCustomFieldsEntry(value)\n return\n }\n payload[key] = value\n })\n return payload\n}\n\nfunction parseFormTags(value: FormDataEntryValue | null): string[] {\n if (!value) return []\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (!trimmed) return []\n try {\n const parsed = JSON.parse(trimmed)\n return normalizeAttachmentTags(parsed)\n } catch {\n return normalizeAttachmentTags(value)\n }\n }\n return []\n}\n\nfunction parseFormAssignments(value: FormDataEntryValue | null): AttachmentAssignment[] {\n if (!value) return []\n if (typeof value !== 'string') return []\n const trimmed = value.trim()\n if (!trimmed) return []\n try {\n const parsed = JSON.parse(trimmed)\n return normalizeAttachmentAssignments(parsed)\n } catch {\n return []\n }\n}\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId || (!auth.orgId && !auth.isSuperAdmin)) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const url = new URL(req.url)\n const parsedQuery = attachmentQuerySchema.safeParse({\n entityId: url.searchParams.get('entityId') || '',\n recordId: url.searchParams.get('recordId') || '',\n page: url.searchParams.get('page') ?? undefined,\n pageSize: url.searchParams.get('pageSize') ?? undefined,\n })\n if (!parsedQuery.success) {\n return NextResponse.json({ error: 'entityId and recordId are required' }, { status: 400 })\n }\n const { entityId, recordId, page, pageSize } = parsedQuery.data\n\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as EntityManager\n const filter: Record<string, unknown> = { entityId, recordId, tenantId: auth.tenantId! }\n if (auth.orgId) filter.organizationId = auth.orgId\n const orderBy: Record<string, 'ASC' | 'DESC'> = { createdAt: 'DESC' }\n const usePaging = typeof page === 'number' && typeof pageSize === 'number'\n const total = usePaging ? await em.count(Attachment, filter) : null\n const currentPage = usePaging ? Math.max(1, page) : null\n const currentPageSize = usePaging ? pageSize : null\n const totalPages = usePaging && total !== null ? Math.max(1, Math.ceil(total / currentPageSize!)) : null\n const pageOffset = usePaging ? (Math.min(currentPage!, totalPages!) - 1) * currentPageSize! : undefined\n const items = await findWithDecryption(\n em,\n Attachment,\n filter,\n {\n orderBy,\n ...(usePaging\n ? {\n limit: currentPageSize!,\n offset: pageOffset,\n }\n : {}),\n },\n {\n tenantId: auth.tenantId ?? null,\n organizationId: auth.orgId ?? null,\n },\n )\n return NextResponse.json({\n items: items.map((a: any) => {\n const metadata = readAttachmentMetadata(a.storageMetadata)\n return {\n id: a.id,\n url: a.url,\n fileName: a.fileName,\n fileSize: a.fileSize,\n createdAt: a.createdAt,\n mimeType: a.mimeType ?? null,\n partitionCode: a.partitionCode,\n content: a.content ?? null,\n thumbnailUrl: buildAttachmentImageUrl(a.id, {\n width: 320,\n height: 320,\n slug: slugifyAttachmentFileName(a.fileName),\n }),\n tags: metadata.tags ?? [],\n assignments: metadata.assignments ?? [],\n }\n }),\n ...(usePaging\n ? {\n total,\n page: Math.min(currentPage!, totalPages!),\n pageSize: currentPageSize,\n totalPages,\n }\n : {}),\n })\n}\n\nexport async function POST(req: Request) {\n const { t } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId || !auth.orgId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const tenantId = auth.tenantId\n const orgId = auth.orgId\n\n const contentType = req.headers.get('content-type') || ''\n if (!contentType.toLowerCase().includes('multipart/form-data')) {\n return NextResponse.json({ error: 'Expected multipart/form-data' }, { status: 400 })\n }\n if (!isMultipartRequestWithinUploadLimit(req.headers.get('content-length'))) {\n return NextResponse.json({ error: 'Attachment exceeds the maximum upload size.' }, { status: 413 })\n }\n\n const form = await req.formData()\n const formPayload = buildFormPayload(form)\n const customFieldValues = splitCustomFieldPayload(formPayload).custom\n const entityId = String(form.get('entityId') || '')\n const recordId = String(form.get('recordId') || '')\n const fieldKey = String(form.get('fieldKey') || '')\n const file = form.get('file') as unknown as File | null\n if (!entityId || !recordId || !file) return NextResponse.json({ error: 'entityId, recordId and file are required' }, { status: 400 })\n const partitionOverrideRaw = form.get('partitionCode')\n const partitionOverride =\n typeof partitionOverrideRaw === 'string' && partitionOverrideRaw.trim().length > 0\n ? sanitizePartitionCode(partitionOverrideRaw)\n : null\n const tags = parseFormTags(form.get('tags'))\n const assignmentsFromForm = parseFormAssignments(form.get('assignments'))\n\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as EntityManager\n const dataEngine = resolve('dataEngine')\n const storageDriverFactory =\n (resolve('storageDriverFactory') as StorageDriverFactory | null) ?? new StorageDriverFactory(em)\n await ensureDefaultPartitions(em)\n // Optional per-field validations\n let partitionFromField: string | null = null\n let fieldMaxAttachmentSizeMb: number | null = null\n if (fieldKey) {\n try {\n const { CustomFieldDef } = await import('@open-mercato/core/modules/entities/data/entities')\n const def = await em.findOne(CustomFieldDef, {\n entityId,\n key: fieldKey,\n $and: [\n { $or: [ { tenantId: auth.tenantId }, { tenantId: null } ] },\n ],\n isActive: true,\n })\n const cfg = (def as any)?.configJson || {}\n const ext = (file.name || '').split('.').pop()?.toLowerCase() || ''\n if (Array.isArray(cfg.acceptExtensions) && cfg.acceptExtensions.length) {\n const allowed = new Set((cfg.acceptExtensions as any[]).map((x: any) => String(x).toLowerCase().replace(/^\\./, '')))\n if (!allowed.has(ext)) return NextResponse.json({ error: 'File type not allowed' }, { status: 400 })\n }\n if (typeof cfg.maxAttachmentSizeMb === 'number' && cfg.maxAttachmentSizeMb > 0) {\n fieldMaxAttachmentSizeMb = cfg.maxAttachmentSizeMb\n }\n if (typeof cfg.partitionCode === 'string' && cfg.partitionCode.trim().length > 0) {\n partitionFromField = sanitizePartitionCode(cfg.partitionCode)\n }\n } catch {}\n }\n if (hasDangerousExecutableExtension(file.name)) {\n return NextResponse.json({\n error: t('attachments.errors.dangerousExecutable', 'Executable file types are not allowed as attachments.'),\n }, { status: 400 })\n }\n const effectiveMaxBytes = resolveAttachmentMaxBytes(fieldMaxAttachmentSizeMb)\n if (file.size > effectiveMaxBytes) {\n return NextResponse.json({\n error: t('attachments.errors.maxUploadSize', 'Attachment exceeds the maximum upload size.'),\n }, { status: 413 })\n }\n const tenantUsageBytes = await readTenantAttachmentUsageBytes(em, tenantId)\n if (willExceedAttachmentTenantQuota(tenantUsageBytes, file.size)) {\n return NextResponse.json({\n error: t('attachments.errors.quotaExceeded', 'Attachment storage quota exceeded for this tenant.'),\n }, { status: 413 })\n }\n const buf = Buffer.from(await file.arrayBuffer())\n const safeName = sanitizeUploadedFileName(file.name)\n const fileMimeType = detectAttachmentMimeType(buf, safeName, (file as any).type)\n if (isActiveContentAttachment(buf, safeName, fileMimeType)) {\n return NextResponse.json({ error: t('attachments.errors.activeContentBlocked', 'Active content uploads are not allowed.') }, { status: 400 })\n }\n const defaultPartitionCode = resolveDefaultPartitionCode(entityId)\n const resolvedPartitionCode = partitionOverride ?? partitionFromField ?? defaultPartitionCode\n const partitionCodeCandidates = Array.from(\n new Set(\n [partitionOverride, partitionFromField, resolvedPartitionCode].filter(\n (code): code is string => typeof code === 'string' && code.length > 0,\n ),\n ),\n )\n let partition: AttachmentPartition | null = null\n for (const code of partitionCodeCandidates) {\n const record = await em.findOne(AttachmentPartition, { code })\n if (record) {\n partition = record\n break\n }\n }\n if (!partition) {\n partition = await em.findOne(AttachmentPartition, { code: defaultPartitionCode })\n }\n if (!partition) {\n return NextResponse.json({ error: 'Storage partition is not configured.' }, { status: 400 })\n }\n const requestedPublicOverride =\n typeof partitionOverride === 'string' &&\n partitionOverride.length > 0 &&\n partition.code === partitionOverride &&\n partition.isPublic === true &&\n partition.code !== defaultPartitionCode &&\n partition.code !== partitionFromField\n if (requestedPublicOverride) {\n return NextResponse.json({ error: t('attachments.errors.publicPartitionBlocked', 'Public storage partitions cannot be selected explicitly for this upload.') }, { status: 403 })\n }\n const uploadDriver = await storageDriverFactory.resolveForPartition(partition.code, { tenantId, organizationId: orgId })\n let storedPath: string\n try {\n const stored = await uploadDriver.store({\n partitionCode: partition.code,\n orgId,\n tenantId,\n fileName: safeName,\n buffer: buf,\n })\n storedPath = stored.storagePath\n } catch (error) {\n console.error('[attachments] failed to persist file', error)\n return NextResponse.json({ error: 'Failed to persist attachment.' }, { status: 500 })\n }\n\n const requiresOcr =\n typeof (partition as any).requiresOcr === 'boolean'\n ? Boolean((partition as any).requiresOcr)\n : resolveDefaultAttachmentOcrEnabled()\n let extractedContent: string | null = null\n const wantsLlmOcr = requiresOcr && shouldUseLlmOcr(fileMimeType, safeName)\n const ocrService = wantsLlmOcr ? new OcrService() : null\n const useLlmOcr = Boolean(wantsLlmOcr && ocrService?.available)\n\n if (requiresOcr && !useLlmOcr) {\n const { filePath: localPath, cleanup } = await uploadDriver.toLocalPath(partition.code, storedPath)\n try {\n extractedContent = await extractAttachmentContent({\n filePath: localPath,\n mimeType: fileMimeType,\n })\n } catch (error) {\n console.error('[attachments] failed to extract attachment content', error)\n } finally {\n await cleanup().catch(() => {})\n }\n }\n\n let assignments = assignmentsFromForm.slice()\n if (entityId !== LIBRARY_ENTITY_ID) {\n assignments = upsertAssignment(assignments, { type: entityId, id: recordId })\n }\n const metadata = mergeAttachmentMetadata(null, { assignments, tags })\n const attachmentId = randomUUID()\n assertAttachmentScopeInvariant({ tenantId: auth.tenantId, organizationId: auth.orgId })\n const att = em.create(Attachment, {\n id: attachmentId,\n entityId,\n recordId,\n organizationId: auth.orgId!,\n tenantId: auth.tenantId!,\n fileName: safeName,\n mimeType: fileMimeType,\n fileSize: buf.length,\n partitionCode: partition.code,\n storageDriver: partition.storageDriver || 'local',\n storagePath: storedPath,\n url: buildAttachmentFileUrl(attachmentId),\n content: extractedContent,\n storageMetadata: metadata,\n })\n // Persist the attachment row and its custom-field values atomically so a\n // custom-field failure cannot leave behind a committed orphan attachment.\n try {\n await em.transactional(async (tx) => {\n await tx.persist(att).flush()\n if (dataEngine) {\n await setCustomFieldsIfAny({\n dataEngine,\n entityId: E.attachments.attachment,\n recordId: attachmentId,\n tenantId,\n organizationId: orgId,\n values: customFieldValues,\n })\n }\n })\n } catch (error) {\n console.error('[attachments] failed to persist attachment with custom attributes', error)\n return NextResponse.json({ error: 'Failed to save attachment attributes.' }, { status: 500 })\n }\n\n if (useLlmOcr) {\n requestOcrProcessing(em, att, uploadDriver, storedPath).catch((error) => {\n console.error('[attachments] failed to queue OCR processing', error)\n })\n } else if (wantsLlmOcr) {\n console.warn('[attachments] OCR requested but OPENAI_API_KEY not configured, falling back to text extraction when available')\n }\n\n if (dataEngine) {\n await emitCrudSideEffects({\n dataEngine,\n action: 'created',\n entity: att,\n identifiers: {\n id: att.id,\n organizationId: att.organizationId ?? null,\n tenantId: att.tenantId ?? null,\n },\n events: attachmentCrudEvents,\n indexer: attachmentCrudIndexer,\n })\n await dataEngine.flushOrmEntityChanges()\n }\n\n return NextResponse.json({\n ok: true,\n item: {\n id: attachmentId,\n url: att.url,\n fileName: safeName,\n fileSize: buf.length,\n partitionCode: partition.code,\n thumbnailUrl: buildAttachmentImageUrl(attachmentId, {\n width: 320,\n height: 320,\n slug: slugifyAttachmentFileName(safeName),\n }),\n content: extractedContent ?? null,\n tags: metadata.tags ?? [],\n assignments: metadata.assignments ?? [],\n customFields: Object.keys(customFieldValues).length ? customFieldValues : undefined,\n },\n })\n}\n\nasync function readTenantAttachmentUsageBytes(em: EntityManager, tenantId: string): Promise<number> {\n try {\n const db = em.getKysely<any>() as any\n const row = await db\n .selectFrom('attachments')\n .select(sql<string>`sum(file_size)`.as('total_size'))\n .where('tenant_id', '=', tenantId)\n .executeTakeFirst() as { total_size: string | number | null } | undefined\n const total = row?.total_size\n if (typeof total === 'number') return Number.isFinite(total) ? total : 0\n if (typeof total === 'string') {\n const parsed = Number(total)\n return Number.isFinite(parsed) ? parsed : 0\n }\n return 0\n } catch {\n return 0\n }\n}\n\nexport async function DELETE(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId || !auth.orgId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const url = new URL(req.url)\n const id = url.searchParams.get('id') || ''\n if (!id) return NextResponse.json({ error: 'Attachment id is required' }, { status: 400 })\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as EntityManager\n const dataEngine = resolve('dataEngine')\n const storageDriverFactory =\n (resolve('storageDriverFactory') as StorageDriverFactory | null) ?? new StorageDriverFactory(em)\n const deleteFilter: Record<string, unknown> = { id, tenantId: auth.tenantId!, organizationId: auth.orgId }\n const record = await em.findOne(Attachment, deleteFilter)\n if (!record) return NextResponse.json({ error: 'Attachment not found' }, { status: 404 })\n await em.remove(record).flush()\n await clearAttachmentThumbnailCache(record.partitionCode, record.id).catch((error) => {\n console.error('[attachments] failed to cleanup cached thumbnails', error)\n })\n if (record.storagePath) {\n const delDriver = await storageDriverFactory.resolveForPartition(record.partitionCode, {\n tenantId: record.tenantId ?? auth.tenantId!,\n organizationId: record.organizationId ?? auth.orgId,\n })\n await delDriver.delete(record.partitionCode, record.storagePath)\n }\n if (dataEngine) {\n await emitCrudSideEffects({\n dataEngine,\n action: 'deleted',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId ?? null,\n tenantId: record.tenantId ?? null,\n },\n events: attachmentCrudEvents,\n indexer: attachmentCrudIndexer,\n })\n await dataEngine.flushOrmEntityChanges()\n }\n return NextResponse.json({ ok: true })\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Manage entity attachments',\n description: 'Upload and list attachments associated with module entities and records.',\n methods: {\n GET: {\n summary: 'List attachments for a record',\n description: 'Returns uploaded attachments for the given entity record, ordered by newest first.',\n query: attachmentQuerySchema,\n responses: [\n { status: 200, description: 'Attachments found for the record', schema: attachmentListResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Missing entity or record identifiers', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n ],\n },\n POST: {\n summary: 'Upload attachment',\n description: 'Uploads a new attachment using multipart form-data and stores metadata for later retrieval.',\n requestBody: {\n contentType: 'multipart/form-data',\n schema: attachmentUploadBodySchema,\n },\n responses: [\n { status: 200, description: 'Attachment stored successfully', schema: uploadResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Payload validation error', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n { status: 403, description: 'Attachment violates field constraints', schema: errorSchema },\n ],\n },\n DELETE: {\n summary: 'Delete attachment',\n description: 'Removes an uploaded attachment and deletes the stored asset.',\n query: attachmentDeleteQuerySchema,\n responses: [\n { status: 200, description: 'Attachment deleted', schema: z.object({ ok: z.literal(true) }) },\n { status: 404, description: 'Attachment not found', schema: errorSchema },\n ],\n errors: [\n { status: 400, description: 'Missing attachment identifier', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,SAAS;AAClB,SAAS,WAAW;AAEpB,SAAS,wBAAwB,yBAAyB,iCAAiC;AAC3F,SAAS,yBAAyB,6BAA6B,6BAA6B;AAC5F,SAAS,YAAY,2BAA2B;AAChD,SAAS,gCAAgC;AACzC,SAAS,4BAA4B;AACrC,SAAS,4BAA4B;AACrC,SAAS,YAAY,uBAAuB;AAC5C,SAAS,qCAAqC;AAC9C,SAAS,sCAAsC;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,kBAAkB;AAE3B,SAAS,+BAA+B;AACxC,SAAS,qBAAqB,4BAA4B;AAC1D,SAAS,2BAA2B;AACpC,SAAS,sBAAsB,6BAA6B;AAC5D,SAAS,SAAS;AAClB,SAAS,0CAA0C;AACnD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;A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getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { z } from 'zod'\nimport { sql } from 'kysely'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { buildAttachmentFileUrl, buildAttachmentImageUrl, slugifyAttachmentFileName } from '../lib/imageUrls'\nimport { ensureDefaultPartitions, resolveDefaultPartitionCode, sanitizePartitionCode } from '../lib/partitions'\nimport { Attachment, AttachmentPartition } from '../data/entities'\nimport { extractAttachmentContent } from '../lib/textExtraction'\nimport { requestOcrProcessing } from '../lib/ocrQueue'\nimport { StorageDriverFactory } from '../lib/drivers'\nimport { OcrService, shouldUseLlmOcr } from '../lib/ocrService'\nimport { clearAttachmentThumbnailCache } from '../lib/thumbnailCache'\nimport { assertAttachmentScopeInvariant } from '../lib/access'\nimport {\n mergeAttachmentMetadata,\n normalizeAttachmentAssignments,\n normalizeAttachmentTags,\n readAttachmentMetadata,\n upsertAssignment,\n type AttachmentAssignment,\n} from '../lib/metadata'\nimport { randomUUID } from 'crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { splitCustomFieldPayload } from '@open-mercato/shared/lib/crud/custom-fields'\nimport { emitCrudSideEffects, setCustomFieldsIfAny } from '@open-mercato/shared/lib/commands/helpers'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { attachmentCrudEvents, attachmentCrudIndexer } from '../lib/crud'\nimport { E } from '#generated/entities.ids.generated'\nimport { resolveDefaultAttachmentOcrEnabled } from '../lib/ocrConfig'\nimport {\n detectAttachmentMimeType,\n hasDangerousExecutableExtension,\n isActiveContentAttachment,\n sanitizeUploadedFileName,\n} from '../lib/security'\nimport {\n isMultipartRequestWithinUploadLimit,\n resolveAttachmentMaxBytes,\n willExceedAttachmentTenantQuota,\n} from '../lib/upload-limits'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['attachments.view'] },\n POST: { requireAuth: true, requireFeatures: ['attachments.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['attachments.manage'] },\n}\n\nconst attachmentQuerySchema = z.object({\n entityId: z.string().min(1).describe('Entity identifier that owns the attachments'),\n recordId: z.string().min(1).describe('Record identifier within the entity'),\n page: z.coerce.number().min(1).optional(),\n pageSize: z.coerce.number().min(1).max(100).optional(),\n})\n\nconst attachmentAssignmentSchema = z.object({\n type: z.string().describe('Assignment type identifier'),\n id: z.string().describe('Assignment record identifier'),\n href: z.string().nullable().optional().describe('Optional link to the related record'),\n label: z.string().nullable().optional().describe('Optional label for the assignment'),\n})\n\nconst attachmentItemSchema = z.object({\n id: z.string().describe('Attachment identifier'),\n url: z.string().describe('Public path to the stored asset'),\n fileName: z.string().describe('Original filename'),\n fileSize: z.number().int().nonnegative().describe('File size in bytes'),\n createdAt: z.string().describe('Upload timestamp (ISO 8601)'),\n mimeType: z.string().nullable().optional().describe('MIME type of the file'),\n thumbnailUrl: z.string().optional().describe('Helper route that renders a thumbnail'),\n partitionCode: z.string().optional().describe('Partition identifier'),\n tags: z.array(z.string()).optional().describe('Tags assigned to the attachment'),\n content: z.string().nullable().optional().describe('Extracted text or markdown content'),\n assignments: z.array(attachmentAssignmentSchema).optional().describe('Records that reference this attachment'),\n})\n\nconst attachmentListResponseSchema = z.object({\n items: z.array(attachmentItemSchema),\n total: z.number().int().nonnegative().optional(),\n page: z.number().int().min(1).optional(),\n pageSize: z.number().int().min(1).optional(),\n totalPages: z.number().int().min(1).optional(),\n})\n\nconst attachmentUploadBodySchema = z.object({\n entityId: z.string().min(1),\n recordId: z.string().min(1),\n fieldKey: z.string().optional(),\n file: z.string().min(1).describe('Binary file payload; supplied as multipart form-data'),\n customFields: z\n .string()\n .optional()\n .describe('JSON encoded map of custom field values collected from the upload form.'),\n})\n\nconst attachmentDeleteQuerySchema = z.object({\n id: z.string().uuid(),\n})\n\nconst uploadResponseSchema = z.object({\n ok: z.literal(true),\n item: z.object({\n id: z.string(),\n url: z.string(),\n fileName: z.string(),\n fileSize: z.number().int().nonnegative(),\n thumbnailUrl: z.string().optional(),\n content: z.string().nullable().optional(),\n tags: z.array(z.string()).optional(),\n assignments: z.array(attachmentAssignmentSchema).optional(),\n customFields: z.record(z.string(), z.unknown()).optional(),\n }),\n})\n\nconst errorSchema = z.object({\n error: z.string(),\n})\n\nconst LIBRARY_ENTITY_ID = 'attachments:library'\n\nfunction parseCustomFieldsEntry(value: FormDataEntryValue | null): Record<string, unknown> {\n if (!value) return {}\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (!trimmed) return {}\n try {\n const parsed = JSON.parse(trimmed)\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>\n }\n } catch {\n return {}\n }\n }\n if (typeof value === 'object' && !Array.isArray(value) && !(value instanceof File)) {\n return { ...(value as Record<string, unknown>) }\n }\n return {}\n}\n\nfunction buildFormPayload(form: FormData): Record<string, unknown> {\n const payload: Record<string, unknown> = {}\n form.forEach((value, key) => {\n if (key === 'customFields') {\n payload.customFields = parseCustomFieldsEntry(value)\n return\n }\n payload[key] = value\n })\n return payload\n}\n\nfunction parseFormTags(value: FormDataEntryValue | null): string[] {\n if (!value) return []\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (!trimmed) return []\n try {\n const parsed = JSON.parse(trimmed)\n return normalizeAttachmentTags(parsed)\n } catch {\n return normalizeAttachmentTags(value)\n }\n }\n return []\n}\n\nfunction parseFormAssignments(value: FormDataEntryValue | null): AttachmentAssignment[] {\n if (!value) return []\n if (typeof value !== 'string') return []\n const trimmed = value.trim()\n if (!trimmed) return []\n try {\n const parsed = JSON.parse(trimmed)\n return normalizeAttachmentAssignments(parsed)\n } catch {\n return []\n }\n}\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId || (!auth.orgId && !auth.isSuperAdmin)) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const url = new URL(req.url)\n const parsedQuery = attachmentQuerySchema.safeParse({\n entityId: url.searchParams.get('entityId') || '',\n recordId: url.searchParams.get('recordId') || '',\n page: url.searchParams.get('page') ?? undefined,\n pageSize: url.searchParams.get('pageSize') ?? undefined,\n })\n if (!parsedQuery.success) {\n return NextResponse.json({ error: 'entityId and recordId are required' }, { status: 400 })\n }\n const { entityId, recordId, page, pageSize } = parsedQuery.data\n\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as EntityManager\n const filter: Record<string, unknown> = { entityId, recordId, tenantId: auth.tenantId! }\n if (auth.orgId) filter.organizationId = auth.orgId\n const orderBy: Record<string, 'ASC' | 'DESC'> = { createdAt: 'DESC' }\n const usePaging = typeof page === 'number' && typeof pageSize === 'number'\n const total = usePaging ? await em.count(Attachment, filter) : null\n const currentPage = usePaging ? Math.max(1, page) : null\n const currentPageSize = usePaging ? pageSize : null\n const totalPages = usePaging && total !== null ? Math.max(1, Math.ceil(total / currentPageSize!)) : null\n const pageOffset = usePaging ? (Math.min(currentPage!, totalPages!) - 1) * currentPageSize! : undefined\n const items = await findWithDecryption(\n em,\n Attachment,\n filter,\n {\n orderBy,\n ...(usePaging\n ? {\n limit: currentPageSize!,\n offset: pageOffset,\n }\n : {}),\n },\n {\n tenantId: auth.tenantId ?? null,\n organizationId: auth.orgId ?? null,\n },\n )\n return NextResponse.json({\n items: items.map((a: any) => {\n const metadata = readAttachmentMetadata(a.storageMetadata)\n return {\n id: a.id,\n url: a.url,\n fileName: a.fileName,\n fileSize: a.fileSize,\n createdAt: a.createdAt,\n mimeType: a.mimeType ?? null,\n partitionCode: a.partitionCode,\n content: a.content ?? null,\n thumbnailUrl: buildAttachmentImageUrl(a.id, {\n width: 320,\n height: 320,\n slug: slugifyAttachmentFileName(a.fileName),\n }),\n tags: metadata.tags ?? [],\n assignments: metadata.assignments ?? [],\n }\n }),\n ...(usePaging\n ? {\n total,\n page: Math.min(currentPage!, totalPages!),\n pageSize: currentPageSize,\n totalPages,\n }\n : {}),\n })\n}\n\nexport async function POST(req: Request) {\n const { t } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId || (!auth.orgId && !auth.isSuperAdmin)) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n // A superadmin browsing with \"All organizations\" selected has no concrete\n // organization scope, but an attachment must be stored under exactly one\n // organization (the scope invariant forbids partial-null rows). Reject with a\n // clear, actionable error instead of a 401 \u2014 a 401 makes the client-side\n // fetch layer treat it as session expiry, show a misleading toast, and reset\n // the in-progress form (#3764).\n if (!auth.orgId) {\n return NextResponse.json({\n error: t('attachments.errors.selectOrganization', 'Select a specific organization before uploading an attachment.'),\n }, { status: 400 })\n }\n const tenantId = auth.tenantId\n const orgId = auth.orgId\n\n const contentType = req.headers.get('content-type') || ''\n if (!contentType.toLowerCase().includes('multipart/form-data')) {\n return NextResponse.json({ error: 'Expected multipart/form-data' }, { status: 400 })\n }\n if (!isMultipartRequestWithinUploadLimit(req.headers.get('content-length'))) {\n return NextResponse.json({ error: 'Attachment exceeds the maximum upload size.' }, { status: 413 })\n }\n\n const form = await req.formData()\n const formPayload = buildFormPayload(form)\n const customFieldValues = splitCustomFieldPayload(formPayload).custom\n const entityId = String(form.get('entityId') || '')\n const recordId = String(form.get('recordId') || '')\n const fieldKey = String(form.get('fieldKey') || '')\n const file = form.get('file') as unknown as File | null\n if (!entityId || !recordId || !file) return NextResponse.json({ error: 'entityId, recordId and file are required' }, { status: 400 })\n const partitionOverrideRaw = form.get('partitionCode')\n const partitionOverride =\n typeof partitionOverrideRaw === 'string' && partitionOverrideRaw.trim().length > 0\n ? sanitizePartitionCode(partitionOverrideRaw)\n : null\n const tags = parseFormTags(form.get('tags'))\n const assignmentsFromForm = parseFormAssignments(form.get('assignments'))\n\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as EntityManager\n const dataEngine = resolve('dataEngine')\n const storageDriverFactory =\n (resolve('storageDriverFactory') as StorageDriverFactory | null) ?? new StorageDriverFactory(em)\n await ensureDefaultPartitions(em)\n // Optional per-field validations\n let partitionFromField: string | null = null\n let fieldMaxAttachmentSizeMb: number | null = null\n if (fieldKey) {\n try {\n const { CustomFieldDef } = await import('@open-mercato/core/modules/entities/data/entities')\n const def = await em.findOne(CustomFieldDef, {\n entityId,\n key: fieldKey,\n $and: [\n { $or: [ { tenantId: auth.tenantId }, { tenantId: null } ] },\n ],\n isActive: true,\n })\n const cfg = (def as any)?.configJson || {}\n const ext = (file.name || '').split('.').pop()?.toLowerCase() || ''\n if (Array.isArray(cfg.acceptExtensions) && cfg.acceptExtensions.length) {\n const allowed = new Set((cfg.acceptExtensions as any[]).map((x: any) => String(x).toLowerCase().replace(/^\\./, '')))\n if (!allowed.has(ext)) return NextResponse.json({ error: 'File type not allowed' }, { status: 400 })\n }\n if (typeof cfg.maxAttachmentSizeMb === 'number' && cfg.maxAttachmentSizeMb > 0) {\n fieldMaxAttachmentSizeMb = cfg.maxAttachmentSizeMb\n }\n if (typeof cfg.partitionCode === 'string' && cfg.partitionCode.trim().length > 0) {\n partitionFromField = sanitizePartitionCode(cfg.partitionCode)\n }\n } catch {}\n }\n if (hasDangerousExecutableExtension(file.name)) {\n return NextResponse.json({\n error: t('attachments.errors.dangerousExecutable', 'Executable file types are not allowed as attachments.'),\n }, { status: 400 })\n }\n const effectiveMaxBytes = resolveAttachmentMaxBytes(fieldMaxAttachmentSizeMb)\n if (file.size > effectiveMaxBytes) {\n return NextResponse.json({\n error: t('attachments.errors.maxUploadSize', 'Attachment exceeds the maximum upload size.'),\n }, { status: 413 })\n }\n const tenantUsageBytes = await readTenantAttachmentUsageBytes(em, tenantId)\n if (willExceedAttachmentTenantQuota(tenantUsageBytes, file.size)) {\n return NextResponse.json({\n error: t('attachments.errors.quotaExceeded', 'Attachment storage quota exceeded for this tenant.'),\n }, { status: 413 })\n }\n const buf = Buffer.from(await file.arrayBuffer())\n const safeName = sanitizeUploadedFileName(file.name)\n const fileMimeType = detectAttachmentMimeType(buf, safeName, (file as any).type)\n if (isActiveContentAttachment(buf, safeName, fileMimeType)) {\n return NextResponse.json({ error: t('attachments.errors.activeContentBlocked', 'Active content uploads are not allowed.') }, { status: 400 })\n }\n const defaultPartitionCode = resolveDefaultPartitionCode(entityId)\n const resolvedPartitionCode = partitionOverride ?? partitionFromField ?? defaultPartitionCode\n const partitionCodeCandidates = Array.from(\n new Set(\n [partitionOverride, partitionFromField, resolvedPartitionCode].filter(\n (code): code is string => typeof code === 'string' && code.length > 0,\n ),\n ),\n )\n let partition: AttachmentPartition | null = null\n for (const code of partitionCodeCandidates) {\n const record = await em.findOne(AttachmentPartition, { code })\n if (record) {\n partition = record\n break\n }\n }\n if (!partition) {\n partition = await em.findOne(AttachmentPartition, { code: defaultPartitionCode })\n }\n if (!partition) {\n return NextResponse.json({ error: 'Storage partition is not configured.' }, { status: 400 })\n }\n const requestedPublicOverride =\n typeof partitionOverride === 'string' &&\n partitionOverride.length > 0 &&\n partition.code === partitionOverride &&\n partition.isPublic === true &&\n partition.code !== defaultPartitionCode &&\n partition.code !== partitionFromField\n if (requestedPublicOverride) {\n return NextResponse.json({ error: t('attachments.errors.publicPartitionBlocked', 'Public storage partitions cannot be selected explicitly for this upload.') }, { status: 403 })\n }\n const uploadDriver = await storageDriverFactory.resolveForPartition(partition.code, { tenantId, organizationId: orgId })\n let storedPath: string\n try {\n const stored = await uploadDriver.store({\n partitionCode: partition.code,\n orgId,\n tenantId,\n fileName: safeName,\n buffer: buf,\n })\n storedPath = stored.storagePath\n } catch (error) {\n console.error('[attachments] failed to persist file', error)\n return NextResponse.json({ error: 'Failed to persist attachment.' }, { status: 500 })\n }\n\n const requiresOcr =\n typeof (partition as any).requiresOcr === 'boolean'\n ? Boolean((partition as any).requiresOcr)\n : resolveDefaultAttachmentOcrEnabled()\n let extractedContent: string | null = null\n const wantsLlmOcr = requiresOcr && shouldUseLlmOcr(fileMimeType, safeName)\n const ocrService = wantsLlmOcr ? new OcrService() : null\n const useLlmOcr = Boolean(wantsLlmOcr && ocrService?.available)\n\n if (requiresOcr && !useLlmOcr) {\n const { filePath: localPath, cleanup } = await uploadDriver.toLocalPath(partition.code, storedPath)\n try {\n extractedContent = await extractAttachmentContent({\n filePath: localPath,\n mimeType: fileMimeType,\n })\n } catch (error) {\n console.error('[attachments] failed to extract attachment content', error)\n } finally {\n await cleanup().catch(() => {})\n }\n }\n\n let assignments = assignmentsFromForm.slice()\n if (entityId !== LIBRARY_ENTITY_ID) {\n assignments = upsertAssignment(assignments, { type: entityId, id: recordId })\n }\n const metadata = mergeAttachmentMetadata(null, { assignments, tags })\n const attachmentId = randomUUID()\n assertAttachmentScopeInvariant({ tenantId: auth.tenantId, organizationId: auth.orgId })\n const att = em.create(Attachment, {\n id: attachmentId,\n entityId,\n recordId,\n organizationId: auth.orgId!,\n tenantId: auth.tenantId!,\n fileName: safeName,\n mimeType: fileMimeType,\n fileSize: buf.length,\n partitionCode: partition.code,\n storageDriver: partition.storageDriver || 'local',\n storagePath: storedPath,\n url: buildAttachmentFileUrl(attachmentId),\n content: extractedContent,\n storageMetadata: metadata,\n })\n // Persist the attachment row and its custom-field values atomically so a\n // custom-field failure cannot leave behind a committed orphan attachment.\n try {\n await em.transactional(async (tx) => {\n await tx.persist(att).flush()\n if (dataEngine) {\n await setCustomFieldsIfAny({\n dataEngine,\n entityId: E.attachments.attachment,\n recordId: attachmentId,\n tenantId,\n organizationId: orgId,\n values: customFieldValues,\n })\n }\n })\n } catch (error) {\n console.error('[attachments] failed to persist attachment with custom attributes', error)\n return NextResponse.json({ error: 'Failed to save attachment attributes.' }, { status: 500 })\n }\n\n if (useLlmOcr) {\n requestOcrProcessing(em, att, uploadDriver, storedPath).catch((error) => {\n console.error('[attachments] failed to queue OCR processing', error)\n })\n } else if (wantsLlmOcr) {\n console.warn('[attachments] OCR requested but OPENAI_API_KEY not configured, falling back to text extraction when available')\n }\n\n if (dataEngine) {\n await emitCrudSideEffects({\n dataEngine,\n action: 'created',\n entity: att,\n identifiers: {\n id: att.id,\n organizationId: att.organizationId ?? null,\n tenantId: att.tenantId ?? null,\n },\n events: attachmentCrudEvents,\n indexer: attachmentCrudIndexer,\n })\n await dataEngine.flushOrmEntityChanges()\n }\n\n return NextResponse.json({\n ok: true,\n item: {\n id: attachmentId,\n url: att.url,\n fileName: safeName,\n fileSize: buf.length,\n partitionCode: partition.code,\n thumbnailUrl: buildAttachmentImageUrl(attachmentId, {\n width: 320,\n height: 320,\n slug: slugifyAttachmentFileName(safeName),\n }),\n content: extractedContent ?? null,\n tags: metadata.tags ?? [],\n assignments: metadata.assignments ?? [],\n customFields: Object.keys(customFieldValues).length ? customFieldValues : undefined,\n },\n })\n}\n\nasync function readTenantAttachmentUsageBytes(em: EntityManager, tenantId: string): Promise<number> {\n try {\n const db = em.getKysely<any>() as any\n const row = await db\n .selectFrom('attachments')\n .select(sql<string>`sum(file_size)`.as('total_size'))\n .where('tenant_id', '=', tenantId)\n .executeTakeFirst() as { total_size: string | number | null } | undefined\n const total = row?.total_size\n if (typeof total === 'number') return Number.isFinite(total) ? total : 0\n if (typeof total === 'string') {\n const parsed = Number(total)\n return Number.isFinite(parsed) ? parsed : 0\n }\n return 0\n } catch {\n return 0\n }\n}\n\nexport async function DELETE(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId || (!auth.orgId && !auth.isSuperAdmin)) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const url = new URL(req.url)\n const id = url.searchParams.get('id') || ''\n if (!id) return NextResponse.json({ error: 'Attachment id is required' }, { status: 400 })\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as EntityManager\n const dataEngine = resolve('dataEngine')\n const storageDriverFactory =\n (resolve('storageDriverFactory') as StorageDriverFactory | null) ?? new StorageDriverFactory(em)\n // Mirror the GET handler's superadmin bypass: a superadmin browsing with \"All\n // organizations\" selected has no concrete org, so scope the delete by tenant\n // only and let them remove any attachment in the tenant. Non-superadmins stay\n // scoped to their own organization (#3764).\n const deleteFilter: Record<string, unknown> = { id, tenantId: auth.tenantId! }\n if (auth.orgId) deleteFilter.organizationId = auth.orgId\n const record = await em.findOne(Attachment, deleteFilter)\n if (!record) return NextResponse.json({ error: 'Attachment not found' }, { status: 404 })\n await em.remove(record).flush()\n await clearAttachmentThumbnailCache(record.partitionCode, record.id).catch((error) => {\n console.error('[attachments] failed to cleanup cached thumbnails', error)\n })\n if (record.storagePath) {\n const delDriver = await storageDriverFactory.resolveForPartition(record.partitionCode, {\n tenantId: record.tenantId ?? auth.tenantId!,\n organizationId: record.organizationId ?? auth.orgId ?? '',\n })\n await delDriver.delete(record.partitionCode, record.storagePath)\n }\n if (dataEngine) {\n await emitCrudSideEffects({\n dataEngine,\n action: 'deleted',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId ?? null,\n tenantId: record.tenantId ?? null,\n },\n events: attachmentCrudEvents,\n indexer: attachmentCrudIndexer,\n })\n await dataEngine.flushOrmEntityChanges()\n }\n return NextResponse.json({ ok: true })\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Manage entity attachments',\n description: 'Upload and list attachments associated with module entities and records.',\n methods: {\n GET: {\n summary: 'List attachments for a record',\n description: 'Returns uploaded attachments for the given entity record, ordered by newest first.',\n query: attachmentQuerySchema,\n responses: [\n { status: 200, description: 'Attachments found for the record', schema: attachmentListResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Missing entity or record identifiers', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n ],\n },\n POST: {\n summary: 'Upload attachment',\n description: 'Uploads a new attachment using multipart form-data and stores metadata for later retrieval.',\n requestBody: {\n contentType: 'multipart/form-data',\n schema: attachmentUploadBodySchema,\n },\n responses: [\n { status: 200, description: 'Attachment stored successfully', schema: uploadResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Payload validation error', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n { status: 403, description: 'Attachment violates field constraints', schema: errorSchema },\n ],\n },\n DELETE: {\n summary: 'Delete attachment',\n description: 'Removes an uploaded attachment and deletes the stored asset.',\n query: attachmentDeleteQuerySchema,\n responses: [\n { status: 200, description: 'Attachment deleted', schema: z.object({ ok: z.literal(true) }) },\n { status: 404, description: 'Attachment not found', schema: errorSchema },\n ],\n errors: [\n { status: 400, description: 'Missing attachment identifier', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,SAAS;AAClB,SAAS,WAAW;AAEpB,SAAS,wBAAwB,yBAAyB,iCAAiC;AAC3F,SAAS,yBAAyB,6BAA6B,6BAA6B;AAC5F,SAAS,YAAY,2BAA2B;AAChD,SAAS,gCAAgC;AACzC,SAAS,4BAA4B;AACrC,SAAS,4BAA4B;AACrC,SAAS,YAAY,uBAAuB;AAC5C,SAAS,qCAAqC;AAC9C,SAAS,sCAAsC;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,kBAAkB;AAE3B,SAAS,+BAA+B;AACxC,SAAS,qBAAqB,4BAA4B;AAC1D,SAAS,2BAA2B;AACpC,SAAS,sBAAsB,6BAA6B;AAC5D,SAAS,SAAS;AAClB,SAAS,0CAA0C;AACnD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0BAA0B;AAE5B,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,kBAAkB,EAAE;AAAA,EAChE,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,oBAAoB,EAAE;AAAA,EACnE,QAAQ,EAAE,aAAa,MAAM,iBAAiB,CAAC,oBAAoB,EAAE;AACvE;AAEA,MAAM,wBAAwB,EAAE,OAAO;AAAA,EACrC,UAAU,EAAE,OAAO,EAAE,IAAI,C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|
6
|
+
return productSeoTranslator ?? void 0;
|
|
7
|
+
}
|
|
1
8
|
const listeners = /* @__PURE__ */ new Set();
|
|
2
9
|
function publishProductSeoValidation(payload) {
|
|
3
10
|
listeners.forEach((listener) => {
|
|
@@ -13,7 +20,9 @@ function subscribeProductSeoValidation(listener) {
|
|
|
13
20
|
return () => listeners.delete(listener);
|
|
14
21
|
}
|
|
15
22
|
export {
|
|
23
|
+
getProductSeoTranslator,
|
|
16
24
|
publishProductSeoValidation,
|
|
25
|
+
setProductSeoTranslator,
|
|
17
26
|
subscribeProductSeoValidation
|
|
18
27
|
};
|
|
19
28
|
//# sourceMappingURL=state.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/catalog/widgets/injection/product-seo/state.ts"],
|
|
4
|
-
"sourcesContent": ["
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import type { TranslateFn } from '@open-mercato/shared/lib/i18n/context'\n\nexport type ProductSeoValidationPayload = {\n ok: boolean\n issues: string[]\n message?: string\n}\n\n// The `onBeforeSave` validation hook (widget.ts) is a plain side-effect handler\n// with no React context, so it cannot call `useT`. The widget component (which\n// does have `useT`) publishes its translator here on mount; the hook reads it to\n// localize the save-block message (#3299). Undefined until the widget mounts \u2014\n// callers fall back to English via `evaluateProductSeo`'s default translator.\nlet productSeoTranslator: TranslateFn | null = null\n\nexport function setProductSeoTranslator(t: TranslateFn | null) {\n productSeoTranslator = t\n}\n\nexport function getProductSeoTranslator(): TranslateFn | undefined {\n return productSeoTranslator ?? undefined\n}\n\ntype Listener = (payload: ProductSeoValidationPayload) => void\n\nconst listeners = new Set<Listener>()\n\nexport function publishProductSeoValidation(payload: ProductSeoValidationPayload) {\n listeners.forEach((listener) => {\n try {\n listener(payload)\n } catch (err) {\n console.error('[product-seo] Failed to notify listener', err)\n }\n })\n}\n\nexport function subscribeProductSeoValidation(listener: Listener): () => void {\n listeners.add(listener)\n return () => listeners.delete(listener)\n}\n"],
|
|
5
|
+
"mappings": "AAaA,IAAI,uBAA2C;AAExC,SAAS,wBAAwB,GAAuB;AAC7D,yBAAuB;AACzB;AAEO,SAAS,0BAAmD;AACjE,SAAO,wBAAwB;AACjC;AAIA,MAAM,YAAY,oBAAI,IAAc;AAE7B,SAAS,4BAA4B,SAAsC;AAChF,YAAU,QAAQ,CAAC,aAAa;AAC9B,QAAI;AACF,eAAS,OAAO;AAAA,IAClB,SAAS,KAAK;AACZ,cAAQ,MAAM,2CAA2C,GAAG;AAAA,IAC9D;AAAA,EACF,CAAC;AACH;AAEO,SAAS,8BAA8B,UAAgC;AAC5E,YAAU,IAAI,QAAQ;AACtB,SAAO,MAAM,UAAU,OAAO,QAAQ;AACxC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,34 +1,48 @@
|
|
|
1
|
-
const
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
if (
|
|
5
|
-
return
|
|
1
|
+
const englishFallback = (_key, fallbackOrParams, params) => {
|
|
2
|
+
const template = typeof fallbackOrParams === "string" ? fallbackOrParams : "";
|
|
3
|
+
const resolvedParams = typeof fallbackOrParams === "string" ? params : fallbackOrParams;
|
|
4
|
+
if (!resolvedParams) return template;
|
|
5
|
+
return template.replace(/\{\{(\w+)\}\}|\{(\w+)\}/g, (match, doubleKey, singleKey) => {
|
|
6
|
+
const key = doubleKey ?? singleKey;
|
|
7
|
+
const value = resolvedParams[key];
|
|
8
|
+
return value === void 0 ? match : String(value);
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
const K = "catalog.products.create.seoWidget.validation";
|
|
12
|
+
function buildSeoBlockMessage(issues, t = englishFallback) {
|
|
13
|
+
if (issues.length <= 3) {
|
|
14
|
+
return t(`${K}.block.list`, "SEO helper: {{issues}}", { issues: issues.join(" ") });
|
|
15
|
+
}
|
|
16
|
+
return t(`${K}.block.summary`, "SEO helper: {{count}} issues found. {{issues}}", {
|
|
17
|
+
count: issues.length,
|
|
18
|
+
issues: issues.slice(0, 2).join(" ")
|
|
19
|
+
});
|
|
6
20
|
}
|
|
7
|
-
function evaluateProductSeo(data) {
|
|
21
|
+
function evaluateProductSeo(data, t = englishFallback) {
|
|
8
22
|
const issues = [];
|
|
9
23
|
const fieldErrors = {};
|
|
10
24
|
const title = data?.title || data?.name;
|
|
11
25
|
if (typeof title === "string" && title.length > 0) {
|
|
12
26
|
if (title.length < 10) {
|
|
13
|
-
issues.push("Title is too short (min 10 characters).");
|
|
14
|
-
fieldErrors.title = "Title is too short for good SEO (min 10 characters).";
|
|
27
|
+
issues.push(t(`${K}.issue.titleTooShort`, "Title is too short (min 10 characters)."));
|
|
28
|
+
fieldErrors.title = t(`${K}.fieldError.titleTooShort`, "Title is too short for good SEO (min 10 characters).");
|
|
15
29
|
} else if (title.length > 60) {
|
|
16
|
-
issues.push("Title is too long (max 60 characters recommended).");
|
|
17
|
-
fieldErrors.title = "Title is too long for optimal SEO (max 60 characters).";
|
|
30
|
+
issues.push(t(`${K}.issue.titleTooLong`, "Title is too long (max 60 characters recommended)."));
|
|
31
|
+
fieldErrors.title = t(`${K}.fieldError.titleTooLong`, "Title is too long for optimal SEO (max 60 characters).");
|
|
18
32
|
}
|
|
19
33
|
}
|
|
20
34
|
const description = data?.description;
|
|
21
35
|
if (typeof description === "string") {
|
|
22
36
|
if (description.trim().length === 0) {
|
|
23
|
-
issues.push("Add a product description for better SEO.");
|
|
24
|
-
fieldErrors.description = "Provide a description to help search engines understand this product.";
|
|
37
|
+
issues.push(t(`${K}.issue.descriptionMissing`, "Add a product description for better SEO."));
|
|
38
|
+
fieldErrors.description = t(`${K}.fieldError.descriptionMissing`, "Provide a description to help search engines understand this product.");
|
|
25
39
|
} else if (description.length < 50) {
|
|
26
|
-
issues.push("Description is too short (min 50 characters).");
|
|
27
|
-
fieldErrors.description = "Description is too short for good SEO (min 50 characters).";
|
|
40
|
+
issues.push(t(`${K}.issue.descriptionTooShort`, "Description is too short (min 50 characters)."));
|
|
41
|
+
fieldErrors.description = t(`${K}.fieldError.descriptionTooShort`, "Description is too short for good SEO (min 50 characters).");
|
|
28
42
|
}
|
|
29
43
|
}
|
|
30
44
|
if (issues.length) {
|
|
31
|
-
return { ok: false, issues, fieldErrors, message: buildSeoBlockMessage(issues) };
|
|
45
|
+
return { ok: false, issues, fieldErrors, message: buildSeoBlockMessage(issues, t) };
|
|
32
46
|
}
|
|
33
47
|
return { ok: true, issues: [], fieldErrors: {} };
|
|
34
48
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/catalog/widgets/injection/product-seo/validation.ts"],
|
|
4
|
-
"sourcesContent": ["
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import type { TranslateFn } from '@open-mercato/shared/lib/i18n/context'\n\nexport type ProductSeoEvaluation = {\n ok: boolean\n issues: string[]\n fieldErrors: Record<string, string>\n message?: string\n}\n\n// English-fallback translator: keeps this pure module usable (and unit-testable)\n// when no real `t` is threaded in \u2014 every string still ships its English default,\n// interpolating `{{param}}` placeholders the same way the real translator does.\nconst englishFallback: TranslateFn = (_key, fallbackOrParams, params) => {\n const template = typeof fallbackOrParams === 'string' ? fallbackOrParams : ''\n const resolvedParams = typeof fallbackOrParams === 'string' ? params : fallbackOrParams\n if (!resolvedParams) return template\n return template.replace(/\\{\\{(\\w+)\\}\\}|\\{(\\w+)\\}/g, (match, doubleKey, singleKey) => {\n const key = doubleKey ?? singleKey\n const value = resolvedParams[key]\n return value === undefined ? match : String(value)\n })\n}\n\nconst K = 'catalog.products.create.seoWidget.validation'\n\nexport function buildSeoBlockMessage(issues: string[], t: TranslateFn = englishFallback): string {\n if (issues.length <= 3) {\n return t(`${K}.block.list`, 'SEO helper: {{issues}}', { issues: issues.join(' ') })\n }\n return t(`${K}.block.summary`, 'SEO helper: {{count}} issues found. {{issues}}', {\n count: issues.length,\n issues: issues.slice(0, 2).join(' '),\n })\n}\n\nexport function evaluateProductSeo(\n data: Record<string, unknown> | null | undefined,\n t: TranslateFn = englishFallback,\n): ProductSeoEvaluation {\n const issues: string[] = []\n const fieldErrors: Record<string, string> = {}\n\n const title = (data?.title as unknown) || (data?.name as unknown)\n if (typeof title === 'string' && title.length > 0) {\n if (title.length < 10) {\n issues.push(t(`${K}.issue.titleTooShort`, 'Title is too short (min 10 characters).'))\n fieldErrors.title = t(`${K}.fieldError.titleTooShort`, 'Title is too short for good SEO (min 10 characters).')\n } else if (title.length > 60) {\n issues.push(t(`${K}.issue.titleTooLong`, 'Title is too long (max 60 characters recommended).'))\n fieldErrors.title = t(`${K}.fieldError.titleTooLong`, 'Title is too long for optimal SEO (max 60 characters).')\n }\n }\n\n const description = data?.description\n if (typeof description === 'string') {\n if (description.trim().length === 0) {\n issues.push(t(`${K}.issue.descriptionMissing`, 'Add a product description for better SEO.'))\n fieldErrors.description = t(`${K}.fieldError.descriptionMissing`, 'Provide a description to help search engines understand this product.')\n } else if (description.length < 50) {\n issues.push(t(`${K}.issue.descriptionTooShort`, 'Description is too short (min 50 characters).'))\n fieldErrors.description = t(`${K}.fieldError.descriptionTooShort`, 'Description is too short for good SEO (min 50 characters).')\n }\n }\n\n if (issues.length) {\n return { ok: false, issues, fieldErrors, message: buildSeoBlockMessage(issues, t) }\n }\n\n return { ok: true, issues: [], fieldErrors: {} }\n}\n"],
|
|
5
|
+
"mappings": "AAYA,MAAM,kBAA+B,CAAC,MAAM,kBAAkB,WAAW;AACvE,QAAM,WAAW,OAAO,qBAAqB,WAAW,mBAAmB;AAC3E,QAAM,iBAAiB,OAAO,qBAAqB,WAAW,SAAS;AACvE,MAAI,CAAC,eAAgB,QAAO;AAC5B,SAAO,SAAS,QAAQ,4BAA4B,CAAC,OAAO,WAAW,cAAc;AACnF,UAAM,MAAM,aAAa;AACzB,UAAM,QAAQ,eAAe,GAAG;AAChC,WAAO,UAAU,SAAY,QAAQ,OAAO,KAAK;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AA,IACjI;AAAA,EACF;AAEA,MAAI,OAAO,QAAQ;AACjB,WAAO,EAAE,IAAI,OAAO,QAAQ,aAAa,SAAS,qBAAqB,QAAQ,CAAC,EAAE;AAAA,EACpF;AAEA,SAAO,EAAE,IAAI,MAAM,QAAQ,CAAC,GAAG,aAAa,CAAC,EAAE;AACjD;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
3
3
|
import * as React from "react";
|
|
4
|
-
import { subscribeProductSeoValidation } from "./state.js";
|
|
4
|
+
import { subscribeProductSeoValidation, setProductSeoTranslator } from "./state.js";
|
|
5
5
|
import { useT } from "@open-mercato/shared/lib/i18n/context";
|
|
6
6
|
import { StatusBadge } from "@open-mercato/ui/primitives/status-badge";
|
|
7
7
|
import { Alert } from "@open-mercato/ui/primitives/alert";
|
|
@@ -22,6 +22,10 @@ function computeIssueKeys(title, description) {
|
|
|
22
22
|
}
|
|
23
23
|
function ProductSeoWidget({ data }) {
|
|
24
24
|
const t = useT();
|
|
25
|
+
React.useEffect(() => {
|
|
26
|
+
setProductSeoTranslator(t);
|
|
27
|
+
return () => setProductSeoTranslator(null);
|
|
28
|
+
}, [t]);
|
|
25
29
|
const title = (data?.title || data?.name || "") ?? "";
|
|
26
30
|
const description = data?.description ?? "";
|
|
27
31
|
const baselineIssueKeys = React.useMemo(() => computeIssueKeys(title, description), [title, description]);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/catalog/widgets/injection/product-seo/widget.client.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use client\"\nimport * as React from 'react'\nimport type { InjectionWidgetComponentProps } from '@open-mercato/shared/modules/widgets/injection'\nimport { subscribeProductSeoValidation } from './state'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { StatusBadge, type StatusBadgeVariant } from '@open-mercato/ui/primitives/status-badge'\nimport { Alert } from '@open-mercato/ui/primitives/alert'\n\ntype SeoData = {\n title?: string | null\n name?: string | null\n description?: string | null\n}\n\ntype ValidationState = { ok: boolean; issues: string[]; message?: string }\n\ntype IssueKey = 'addTitle' | 'titleTooShort' | 'titleTooLong' | 'addDescription' | 'descriptionTooShort'\n\ntype SeoScore = { text: string; variant: StatusBadgeVariant }\n\nfunction computeIssueKeys(title: string, description: string): IssueKey[] {\n const issues: IssueKey[] = []\n if (!title) {\n issues.push('addTitle')\n } else {\n if (title.length < 10) issues.push('titleTooShort')\n if (title.length > 60) issues.push('titleTooLong')\n }\n if (!description) {\n issues.push('addDescription')\n } else if (description.length < 50) {\n issues.push('descriptionTooShort')\n }\n return issues\n}\n\nexport default function ProductSeoWidget({ data }: InjectionWidgetComponentProps<unknown, SeoData>) {\n const t = useT()\n const title = (data?.title || data?.name || '') ?? ''\n const description = data?.description ?? ''\n const baselineIssueKeys = React.useMemo(() => computeIssueKeys(title, description), [title, description])\n const [validation, setValidation] = React.useState<ValidationState>({ ok: baselineIssueKeys.length === 0, issues: baselineIssueKeys })\n\n React.useEffect(() => {\n setValidation({ ok: baselineIssueKeys.length === 0, issues: baselineIssueKeys })\n }, [baselineIssueKeys])\n\n React.useEffect(() => {\n return subscribeProductSeoValidation((payload) => {\n setValidation({\n ok: payload.ok,\n issues: payload.issues,\n message: payload.message,\n })\n })\n }, [])\n\n const titleScore = React.useMemo<SeoScore>(() => {\n if (!title) return { text: t('catalog.products.create.seoWidget.missing', 'Missing'), variant: 'error' }\n if (title.length < 10) return { text: t('catalog.products.create.seoWidget.tooShort', 'Too short'), variant: 'warning' }\n if (title.length > 60) return { text: t('catalog.products.create.seoWidget.tooLong', 'Too long'), variant: 'warning' }\n return { text: t('catalog.products.create.seoWidget.good', 'Good'), variant: 'success' }\n }, [title, t])\n\n const descScore = React.useMemo<SeoScore>(() => {\n if (!description) return { text: t('catalog.products.create.seoWidget.missing', 'Missing'), variant: 'error' }\n if (description.length < 50) return { text: t('catalog.products.create.seoWidget.tooShort', 'Too short'), variant: 'warning' }\n return { text: t('catalog.products.create.seoWidget.good', 'Good'), variant: 'success' }\n }, [description, t])\n\n const statusBadge = validation.ok ? (\n <StatusBadge variant=\"success\">\n {t('catalog.products.create.seoWidget.ready', 'Ready')}\n </StatusBadge>\n ) : (\n <StatusBadge variant=\"warning\">\n {t('catalog.products.create.seoWidget.needsAttention', 'Needs attention')}\n </StatusBadge>\n )\n\n const translateIssue = (issueKey: string): string => {\n return t(`catalog.products.create.seoWidget.issues.${issueKey}`, issueKey)\n }\n\n return (\n <div className=\"mt-4 w-full space-y-3 rounded-lg border bg-card p-4 shadow-sm\">\n <div className=\"flex items-start justify-between gap-3\">\n <div>\n <div className=\"text-sm font-semibold text-foreground\">{t('catalog.products.create.seoWidget.title', 'SEO Optimization')}</div>\n <p className=\"text-xs text-muted-foreground\">{t('catalog.products.create.seoWidget.hint', 'Keep titles 10\u201360 chars and descriptions 50+ chars.')}</p>\n </div>\n {statusBadge}\n </div>\n\n {validation.message || validation.issues.length ? (\n <Alert\n status={validation.ok ? 'success' : 'warning'}\n style=\"lighter\"\n size=\"sm\"\n showIcon={false}\n className=\"text-xs\"\n >\n {validation.message ? <div className=\"font-medium\">{validation.message}</div> : null}\n {validation.issues.length ? (\n <ul className=\"ml-4 list-disc space-y-1 pt-1\">\n {validation.issues.map((issue) => (\n <li key={issue}>{translateIssue(issue)}</li>\n ))}\n </ul>\n ) : null}\n </Alert>\n ) : null}\n\n <div className=\"rounded border bg-muted/30 p-3 text-sm\">\n <div className=\"flex items-center justify-between\">\n <span className=\"text-muted-foreground\">{t('catalog.products.create.seoWidget.titleLabel', 'Title ({{count}} chars)', { count: title.length })}</span>\n <StatusBadge variant={titleScore.variant}>{titleScore.text}</StatusBadge>\n </div>\n <div className=\"mt-2 flex items-center justify-between\">\n <span className=\"text-muted-foreground\">{t('catalog.products.create.seoWidget.descriptionLabel', 'Description ({{count}} chars)', { count: description.length })}</span>\n <StatusBadge variant={descScore.variant}>{descScore.text}</StatusBadge>\n </div>\n </div>\n\n <p className=\"text-overline text-muted-foreground\">\n {t('catalog.products.create.seoWidget.footer', 'Example widget powered by the injection system.')}{' '}\n <a className=\"text-primary underline\" href=\"/docs/framework/admin-ui/widget-injection\" target=\"_blank\" rel=\"noreferrer\">\n {t('catalog.products.create.seoWidget.learnMore', 'Learn how to build your own')}\n </a>\n .\n </p>\n </div>\n )\n}\n"],
|
|
5
|
-
"mappings": ";
|
|
4
|
+
"sourcesContent": ["\"use client\"\nimport * as React from 'react'\nimport type { InjectionWidgetComponentProps } from '@open-mercato/shared/modules/widgets/injection'\nimport { subscribeProductSeoValidation, setProductSeoTranslator } from './state'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { StatusBadge, type StatusBadgeVariant } from '@open-mercato/ui/primitives/status-badge'\nimport { Alert } from '@open-mercato/ui/primitives/alert'\n\ntype SeoData = {\n title?: string | null\n name?: string | null\n description?: string | null\n}\n\ntype ValidationState = { ok: boolean; issues: string[]; message?: string }\n\ntype IssueKey = 'addTitle' | 'titleTooShort' | 'titleTooLong' | 'addDescription' | 'descriptionTooShort'\n\ntype SeoScore = { text: string; variant: StatusBadgeVariant }\n\nfunction computeIssueKeys(title: string, description: string): IssueKey[] {\n const issues: IssueKey[] = []\n if (!title) {\n issues.push('addTitle')\n } else {\n if (title.length < 10) issues.push('titleTooShort')\n if (title.length > 60) issues.push('titleTooLong')\n }\n if (!description) {\n issues.push('addDescription')\n } else if (description.length < 50) {\n issues.push('descriptionTooShort')\n }\n return issues\n}\n\nexport default function ProductSeoWidget({ data }: InjectionWidgetComponentProps<unknown, SeoData>) {\n const t = useT()\n // Expose the translator to the module's `onBeforeSave` hook (which has no React\n // context) so the save-block message is localized (#3299).\n React.useEffect(() => {\n setProductSeoTranslator(t)\n return () => setProductSeoTranslator(null)\n }, [t])\n const title = (data?.title || data?.name || '') ?? ''\n const description = data?.description ?? ''\n const baselineIssueKeys = React.useMemo(() => computeIssueKeys(title, description), [title, description])\n const [validation, setValidation] = React.useState<ValidationState>({ ok: baselineIssueKeys.length === 0, issues: baselineIssueKeys })\n\n React.useEffect(() => {\n setValidation({ ok: baselineIssueKeys.length === 0, issues: baselineIssueKeys })\n }, [baselineIssueKeys])\n\n React.useEffect(() => {\n return subscribeProductSeoValidation((payload) => {\n setValidation({\n ok: payload.ok,\n issues: payload.issues,\n message: payload.message,\n })\n })\n }, [])\n\n const titleScore = React.useMemo<SeoScore>(() => {\n if (!title) return { text: t('catalog.products.create.seoWidget.missing', 'Missing'), variant: 'error' }\n if (title.length < 10) return { text: t('catalog.products.create.seoWidget.tooShort', 'Too short'), variant: 'warning' }\n if (title.length > 60) return { text: t('catalog.products.create.seoWidget.tooLong', 'Too long'), variant: 'warning' }\n return { text: t('catalog.products.create.seoWidget.good', 'Good'), variant: 'success' }\n }, [title, t])\n\n const descScore = React.useMemo<SeoScore>(() => {\n if (!description) return { text: t('catalog.products.create.seoWidget.missing', 'Missing'), variant: 'error' }\n if (description.length < 50) return { text: t('catalog.products.create.seoWidget.tooShort', 'Too short'), variant: 'warning' }\n return { text: t('catalog.products.create.seoWidget.good', 'Good'), variant: 'success' }\n }, [description, t])\n\n const statusBadge = validation.ok ? (\n <StatusBadge variant=\"success\">\n {t('catalog.products.create.seoWidget.ready', 'Ready')}\n </StatusBadge>\n ) : (\n <StatusBadge variant=\"warning\">\n {t('catalog.products.create.seoWidget.needsAttention', 'Needs attention')}\n </StatusBadge>\n )\n\n const translateIssue = (issueKey: string): string => {\n return t(`catalog.products.create.seoWidget.issues.${issueKey}`, issueKey)\n }\n\n return (\n <div className=\"mt-4 w-full space-y-3 rounded-lg border bg-card p-4 shadow-sm\">\n <div className=\"flex items-start justify-between gap-3\">\n <div>\n <div className=\"text-sm font-semibold text-foreground\">{t('catalog.products.create.seoWidget.title', 'SEO Optimization')}</div>\n <p className=\"text-xs text-muted-foreground\">{t('catalog.products.create.seoWidget.hint', 'Keep titles 10\u201360 chars and descriptions 50+ chars.')}</p>\n </div>\n {statusBadge}\n </div>\n\n {validation.message || validation.issues.length ? (\n <Alert\n status={validation.ok ? 'success' : 'warning'}\n style=\"lighter\"\n size=\"sm\"\n showIcon={false}\n className=\"text-xs\"\n >\n {validation.message ? <div className=\"font-medium\">{validation.message}</div> : null}\n {validation.issues.length ? (\n <ul className=\"ml-4 list-disc space-y-1 pt-1\">\n {validation.issues.map((issue) => (\n <li key={issue}>{translateIssue(issue)}</li>\n ))}\n </ul>\n ) : null}\n </Alert>\n ) : null}\n\n <div className=\"rounded border bg-muted/30 p-3 text-sm\">\n <div className=\"flex items-center justify-between\">\n <span className=\"text-muted-foreground\">{t('catalog.products.create.seoWidget.titleLabel', 'Title ({{count}} chars)', { count: title.length })}</span>\n <StatusBadge variant={titleScore.variant}>{titleScore.text}</StatusBadge>\n </div>\n <div className=\"mt-2 flex items-center justify-between\">\n <span className=\"text-muted-foreground\">{t('catalog.products.create.seoWidget.descriptionLabel', 'Description ({{count}} chars)', { count: description.length })}</span>\n <StatusBadge variant={descScore.variant}>{descScore.text}</StatusBadge>\n </div>\n </div>\n\n <p className=\"text-overline text-muted-foreground\">\n {t('catalog.products.create.seoWidget.footer', 'Example widget powered by the injection system.')}{' '}\n <a className=\"text-primary underline\" href=\"/docs/framework/admin-ui/widget-injection\" target=\"_blank\" rel=\"noreferrer\">\n {t('catalog.products.create.seoWidget.learnMore', 'Learn how to build your own')}\n </a>\n .\n </p>\n </div>\n )\n}\n"],
|
|
5
|
+
"mappings": ";AA6EI,cAgBI,YAhBJ;AA5EJ,YAAY,WAAW;AAEvB,SAAS,+BAA+B,+BAA+B;AACvE,SAAS,YAAY;AACrB,SAAS,mBAA4C;AACrD,SAAS,aAAa;AActB,SAAS,iBAAiB,OAAe,aAAiC;AACxE,QAAM,SAAqB,CAAC;AAC5B,MAAI,CAAC,OAAO;AACV,WAAO,KAAK,UAAU;AAAA,EACxB,OAAO;AACL,QAAI,MAAM,S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AS;AAAA,UAC/E,WAAW,OAAO,SACjB,oBAAC,QAAG,WAAU,iCACX,qBAAW,OAAO,IAAI,CAAC,UACtB,oBAAC,QAAgB,yBAAe,KAAK,KAA5B,KAA8B,CACxC,GACH,IACE;AAAA;AAAA;AAAA,IACN,IACE;AAAA,IAEJ,qBAAC,SAAI,WAAU,0CACb;AAAA,2BAAC,SAAI,WAAU,qCACb;AAAA,4BAAC,UAAK,WAAU,yBAAyB,YAAE,gDAAgD,2BAA2B,EAAE,OAAO,MAAM,OAAO,CAAC,GAAE;AAAA,QAC/I,oBAAC,eAAY,SAAS,WAAW,SAAU,qBAAW,MAAK;AAAA,SAC7D;AAAA,MACA,qBAAC,SAAI,WAAU,0CACb;AAAA,4BAAC,UAAK,WAAU,yBAAyB,YAAE,sDAAsD,iCAAiC,EAAE,OAAO,YAAY,OAAO,CAAC,GAAE;AAAA,QACjK,oBAAC,eAAY,SAAS,UAAU,SAAU,oBAAU,MAAK;AAAA,SAC3D;AAAA,OACF;AAAA,IAEA,qBAAC,OAAE,WAAU,uCACV;AAAA,QAAE,4CAA4C,iDAAiD;AAAA,MAAG;AAAA,MACnG,oBAAC,OAAE,WAAU,0BAAyB,MAAK,6CAA4C,QAAO,UAAS,KAAI,cACxG,YAAE,+CAA+C,6BAA6B,GACjF;AAAA,MAAI;AAAA,OAEN;AAAA,KACF;AAEJ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import ProductSeoWidget from "./widget.client.js";
|
|
2
|
-
import { publishProductSeoValidation } from "./state.js";
|
|
2
|
+
import { publishProductSeoValidation, getProductSeoTranslator } from "./state.js";
|
|
3
3
|
import { evaluateProductSeo } from "./validation.js";
|
|
4
4
|
const widget = {
|
|
5
5
|
metadata: {
|
|
@@ -14,7 +14,7 @@ const widget = {
|
|
|
14
14
|
Widget: ProductSeoWidget,
|
|
15
15
|
eventHandlers: {
|
|
16
16
|
onBeforeSave: async (data) => {
|
|
17
|
-
const evaluation = evaluateProductSeo(data);
|
|
17
|
+
const evaluation = evaluateProductSeo(data, getProductSeoTranslator());
|
|
18
18
|
if (!evaluation.ok) {
|
|
19
19
|
publishProductSeoValidation({ ok: false, issues: evaluation.issues, message: evaluation.message });
|
|
20
20
|
return { ok: false, message: evaluation.message, fieldErrors: evaluation.fieldErrors };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/catalog/widgets/injection/product-seo/widget.ts"],
|
|
4
|
-
"sourcesContent": ["import type { InjectionWidgetModule } from '@open-mercato/shared/modules/widgets/injection'\nimport ProductSeoWidget from './widget.client'\nimport { publishProductSeoValidation } from './state'\nimport { evaluateProductSeo } from './validation'\n\nconst widget: InjectionWidgetModule<any, any> = {\n metadata: {\n id: 'catalog.injection.product-seo',\n title: 'Product SEO Helper',\n description: 'Helps optimize product metadata for search engines',\n features: ['catalog.products.edit'],\n priority: 90,\n enabled: true,\n requiredFields: ['description'],\n },\n Widget: ProductSeoWidget,\n eventHandlers: {\n onBeforeSave: async (data) => {\n const evaluation = evaluateProductSeo(data as Record<string, unknown
|
|
5
|
-
"mappings": "AACA,OAAO,sBAAsB;AAC7B,SAAS,
|
|
4
|
+
"sourcesContent": ["import type { InjectionWidgetModule } from '@open-mercato/shared/modules/widgets/injection'\nimport ProductSeoWidget from './widget.client'\nimport { publishProductSeoValidation, getProductSeoTranslator } from './state'\nimport { evaluateProductSeo } from './validation'\n\nconst widget: InjectionWidgetModule<any, any> = {\n metadata: {\n id: 'catalog.injection.product-seo',\n title: 'Product SEO Helper',\n description: 'Helps optimize product metadata for search engines',\n features: ['catalog.products.edit'],\n priority: 90,\n enabled: true,\n requiredFields: ['description'],\n },\n Widget: ProductSeoWidget,\n eventHandlers: {\n onBeforeSave: async (data) => {\n const evaluation = evaluateProductSeo(data as Record<string, unknown>, getProductSeoTranslator())\n\n if (!evaluation.ok) {\n publishProductSeoValidation({ ok: false, issues: evaluation.issues, message: evaluation.message })\n return { ok: false, message: evaluation.message, fieldErrors: evaluation.fieldErrors }\n }\n\n publishProductSeoValidation({ ok: true, issues: [] })\n return { ok: true }\n },\n },\n}\n\nexport default widget\n"],
|
|
5
|
+
"mappings": "AACA,OAAO,sBAAsB;AAC7B,SAAS,6BAA6B,+BAA+B;AACrE,SAAS,0BAA0B;AAEnC,MAAM,SAA0C;AAAA,EAC9C,UAAU;AAAA,IACR,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,aAAa;AAAA,IACb,UAAU,CAAC,uBAAuB;AAAA,IAClC,UAAU;AAAA,IACV,SAAS;AAAA,IACT,gBAAgB,CAAC,aAAa;AAAA,EAChC;AAAA,EACA,QAAQ;AAAA,EACR,eAAe;AAAA,IACb,cAAc,OAAO,SAAS;AAC5B,YAAM,aAAa,mBAAmB,MAAiC,wBAAwB,CAAC;AAEhG,UAAI,CAAC,WAAW,IAAI;AAClB,oCAA4B,EAAE,IAAI,OAAO,QAAQ,WAAW,QAAQ,SAAS,WAAW,QAAQ,CAAC;AACjG,eAAO,EAAE,IAAI,OAAO,SAAS,WAAW,SAAS,aAAa,WAAW,YAAY;AAAA,MACvF;AAEA,kCAA4B,EAAE,IAAI,MAAM,QAAQ,CAAC,EAAE,CAAC;AACpD,aAAO,EAAE,IAAI,KAAK;AAAA,IACpB;AAAA,EACF;AACF;AAEA,IAAO,iBAAQ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -3,6 +3,7 @@ import { z } from "zod";
|
|
|
3
3
|
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
|
|
4
4
|
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
|
|
5
5
|
import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
|
|
6
|
+
import { resolveOrganizationScopeFilter } from "@open-mercato/core/modules/directory/utils/organizationScopeFilter";
|
|
6
7
|
import { CustomerPipelineStage, CustomerDictionaryEntry } from "../../data/entities.js";
|
|
7
8
|
import {
|
|
8
9
|
pipelineStageCreateSchema,
|
|
@@ -44,20 +45,21 @@ async function buildContext(req) {
|
|
|
44
45
|
}
|
|
45
46
|
async function GET(req) {
|
|
46
47
|
try {
|
|
47
|
-
const { ctx,
|
|
48
|
-
if (!
|
|
48
|
+
const { ctx, tenantId, translate } = await buildContext(req);
|
|
49
|
+
if (!tenantId) {
|
|
49
50
|
return NextResponse.json({ error: translate("customers.errors.context_required", "Organization and tenant context required") }, { status: 400 });
|
|
50
51
|
}
|
|
52
|
+
const orgFilter = resolveOrganizationScopeFilter(ctx.organizationScope, ctx.auth);
|
|
51
53
|
const url = new URL(req.url);
|
|
52
54
|
const pipelineId = url.searchParams.get("pipelineId");
|
|
53
55
|
const em = ctx.container.resolve("em");
|
|
54
|
-
const where = {
|
|
56
|
+
const where = { tenantId, ...orgFilter.where };
|
|
55
57
|
if (pipelineId) where.pipelineId = pipelineId;
|
|
56
58
|
const stages = await em.find(CustomerPipelineStage, where, { orderBy: { order: "ASC" } });
|
|
57
59
|
const stageLabels = stages.map((s) => s.label.trim().toLowerCase());
|
|
58
60
|
const dictEntries = stageLabels.length ? await em.find(CustomerDictionaryEntry, {
|
|
59
|
-
organizationId,
|
|
60
61
|
tenantId,
|
|
62
|
+
...orgFilter.where,
|
|
61
63
|
kind: "pipeline_stage",
|
|
62
64
|
normalizedValue: { $in: stageLabels }
|
|
63
65
|
}) : [];
|