Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions api/prisma/migrations/20260409183000_global_assets/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
-- CreateTable
CREATE TABLE "global_assets" (
"id" UUID NOT NULL,
"user_id" UUID NOT NULL,
"art_key" TEXT NOT NULL,
"s3_key" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,

CONSTRAINT "global_assets_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "global_assets_user_id_art_key_key" ON "global_assets"("user_id", "art_key");

-- CreateIndex
CREATE INDEX "global_assets_user_id_idx" ON "global_assets"("user_id");

-- AddForeignKey
ALTER TABLE "global_assets" ADD CONSTRAINT "global_assets_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
19 changes: 18 additions & 1 deletion api/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,24 @@ model User {
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")

projects Project[]
projects Project[]
globalAssets GlobalAsset[]
}

/// User-wide images; project assets with the same normalized art key shadow these.
model GlobalAsset {
id String @id @default(uuid()) @db.Uuid
userId String @map("user_id") @db.Uuid
artKey String @map("art_key")
s3Key String @map("s3_key")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")

user User @relation(fields: [userId], references: [id], onDelete: Cascade)

@@unique([userId, artKey])
@@index([userId])
@@map("global_assets")
}

/// Optional CSV dataset: { "headers": string[], "rows": Record<string,string>[] }
Expand Down
22 changes: 22 additions & 0 deletions api/src/lib/assetResolve.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { describe, expect, it } from 'vitest';
import { mergeAssetS3KeysByNormalizedKey, normalizeArtLookupKey } from './assetResolve.js';

describe('normalizeArtLookupKey', () => {
it('lowercases and strips extension', () => {
expect(normalizeArtLookupKey('Hero.PNG')).toBe('hero');
});

it('strips mustache tokens', () => {
expect(normalizeArtLookupKey('{{ Gold }}')).toBe('gold');
});
});

describe('mergeAssetS3KeysByNormalizedKey', () => {
it('project shadows global', () => {
const m = mergeAssetS3KeysByNormalizedKey(
[{ artKey: 'hero', s3Key: 'p/hero' }],
[{ artKey: 'Hero', s3Key: 'g/hero' }]
);
expect(m.get('hero')).toBe('p/hero');
});
});
25 changes: 25 additions & 0 deletions api/src/lib/assetResolve.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/** Normalize for case-insensitive matching; strips common image extensions. */
export function normalizeArtLookupKey(raw: string): string {
let s = raw.trim().toLowerCase();
s = s.replace(/\{\{|\}\}/g, '').trim();
s = s.replace(/\.(png|jpe?g|gif|webp|svg|bmp)$/i, '');
return s;
}

export type AssetKeyRow = { artKey: string; s3Key: string };

/** Build map normalizedKey -> s3Key (project rows win over global when both match). */
export function mergeAssetS3KeysByNormalizedKey(
projectAssets: AssetKeyRow[],
globalAssets: AssetKeyRow[]
): Map<string, string> {
const m = new Map<string, string>();
for (const a of globalAssets) {
const k = normalizeArtLookupKey(a.artKey);
if (!m.has(k)) m.set(k, a.s3Key);
}
for (const a of projectAssets) {
m.set(normalizeArtLookupKey(a.artKey), a.s3Key);
}
return m;
}
50 changes: 49 additions & 1 deletion api/src/lib/layoutArtKeys.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { collectArtKeysFromLayoutState } from './layoutArtKeys.js';
import { collectArtKeysFromLayoutState, collectPdfPrefetchArtKeys } from './layoutArtKeys.js';

describe('collectArtKeysFromLayoutState', () => {
it('collects image art keys from v2 root', () => {
Expand Down Expand Up @@ -59,4 +59,52 @@ describe('collectArtKeysFromLayoutState', () => {
});
expect(keys).toEqual(['art']);
});

it('collects fallback art key', () => {
const keys = collectArtKeysFromLayoutState({
root: [
{
type: 'image',
id: 'i',
x: 0,
y: 0,
width: 1,
height: 1,
artKey: 'hero',
fallbackArtKey: 'backup.png',
},
],
});
expect(keys.sort()).toEqual(['backup.png', 'hero'].sort());
});
});

describe('collectPdfPrefetchArtKeys', () => {
it('adds dynamic column cell values', () => {
const layout = {
version: 2,
width: 10,
height: 10,
root: [
{
type: 'image',
id: 'i',
x: 0,
y: 0,
width: 1,
height: 1,
artKey: 'x',
dynamicSourceColumn: 'Photo',
},
],
};
const rows = [
{ Photo: ' a.png ', Name: 'A' },
{ Photo: 'b.png', Name: 'B' },
];
const keys = collectPdfPrefetchArtKeys(layout, rows);
expect(keys).toContain('x');
expect(keys).toContain('a.png');
expect(keys).toContain('b.png');
});
});
52 changes: 50 additions & 2 deletions api/src/lib/layoutArtKeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,14 @@ export function collectArtKeysFromLayoutState(state: unknown): string[] {
function visitNode(n: unknown): void {
if (!n || typeof n !== 'object') return;
const o = n as Record<string, unknown>;
if (o.type === 'image' && typeof o.artKey === 'string' && o.artKey.trim()) {
keys.add(o.artKey.trim());
if (o.type === 'image') {
if (typeof o.artKey === 'string' && o.artKey.trim()) {
keys.add(o.artKey.trim());
}
const fb = (o as { fallbackArtKey?: unknown }).fallbackArtKey;
if (typeof fb === 'string' && fb.trim()) {
keys.add(fb.trim());
}
}
if (o.type === 'group' && Array.isArray(o.children)) {
for (const c of o.children) visitNode(c);
Expand All @@ -24,3 +30,45 @@ export function collectArtKeysFromLayoutState(state: unknown): string[] {
visitState(state as Record<string, unknown>);
return [...keys];
}

/**
* All strings that may need signed asset URLs for PDF export: layout art keys, fallbacks,
* and every non-empty cell value for each image’s `dynamicSourceColumn` across `rows`.
*/
export function collectPdfPrefetchArtKeys(
layout: unknown,
rows: Record<string, string>[]
): string[] {
const keys = new Set<string>();
for (const k of collectArtKeysFromLayoutState(layout)) {
keys.add(k);
}

function visitNode(n: unknown): void {
if (!n || typeof n !== 'object') return;
const o = n as Record<string, unknown>;
if (o.type === 'image') {
const col = o.dynamicSourceColumn;
if (typeof col === 'string' && col.trim()) {
const c = col.trim();
for (const row of rows) {
const v = (row[c] ?? '').trim();
if (v) keys.add(v);
}
}
}
if (o.type === 'group' && Array.isArray(o.children)) {
for (const c of o.children) visitNode(c);
}
}

function visitState(s: Record<string, unknown>): void {
if (Array.isArray(s.root)) for (const n of s.root) visitNode(n);
if (Array.isArray(s.elements)) for (const n of s.elements) visitNode(n);
}

if (layout && typeof layout === 'object') {
visitState(layout as Record<string, unknown>);
}
return [...keys];
}
2 changes: 2 additions & 0 deletions api/src/lib/pdfExportPayload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,13 @@ describe('buildPdfExportPayload', () => {
},
]);
prisma.asset.findMany.mockResolvedValueOnce([{ artKey: 'art1', s3Key: 'k1' }]);
prisma.globalAsset.findMany.mockResolvedValueOnce([]);

const r = await buildPdfExportPayload('p', 'u', { dpi: 200 });
if ('error' in r) throw new Error(String(r.error));
expect(r.payload.type).toBe('export-pdf');
expect(r.payload.dpi).toBe(200);
expect(r.payload.assetUrls).toEqual({ art1: 'https://signed.example/asset' });
expect(r.payload.assetResolveOrder).toEqual(['art1']);
});
});
42 changes: 34 additions & 8 deletions api/src/lib/pdfExportPayload.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { mergeAssetS3KeysByNormalizedKey, normalizeArtLookupKey } from './assetResolve.js';
import { prisma } from './prisma.js';
import { collectArtKeysFromLayoutState } from './layoutArtKeys.js';
import { collectPdfPrefetchArtKeys } from './layoutArtKeys.js';
import { getAssetsBucket, getSignedGetUrl } from './s3.js';

/** UI / server default; slider range is 150–300. */
Expand Down Expand Up @@ -77,18 +78,42 @@ export async function buildPdfExportPayload(

const artKeys = new Set<string>();
for (const eg of exportGroups) {
for (const k of collectArtKeysFromLayoutState(eg.layout)) artKeys.add(k);
for (const k of collectPdfPrefetchArtKeys(eg.layout, eg.rows)) artKeys.add(k);
}

const assets = await prisma.asset.findMany({
where: { projectId, artKey: { in: [...artKeys] } },
select: { artKey: true, s3Key: true },
});
const [projectAssets, globalAssets] = await Promise.all([
prisma.asset.findMany({
where: { projectId },
select: { artKey: true, s3Key: true },
}),
prisma.globalAsset.findMany({
where: { userId },
select: { artKey: true, s3Key: true },
}),
]);

const merged = mergeAssetS3KeysByNormalizedKey(projectAssets, globalAssets);
const seenOrder = new Set<string>();
const assetResolveOrder: string[] = [];
for (const a of projectAssets) {
const n = normalizeArtLookupKey(a.artKey);
if (seenOrder.has(n)) continue;
seenOrder.add(n);
assetResolveOrder.push(a.artKey);
}
for (const a of globalAssets) {
const n = normalizeArtLookupKey(a.artKey);
if (seenOrder.has(n)) continue;
seenOrder.add(n);
assetResolveOrder.push(a.artKey);
}

const assetsBucket = getAssetsBucket();
const assetUrls: Record<string, string> = {};
for (const a of assets) {
assetUrls[a.artKey] = await getSignedGetUrl(assetsBucket, a.s3Key, 3600);
for (const rk of artKeys) {
const sk = merged.get(normalizeArtLookupKey(rk));
if (!sk) continue;
assetUrls[rk.trim()] = await getSignedGetUrl(assetsBucket, sk, 3600);
}

const timestamp = new Date().toISOString();
Expand All @@ -102,6 +127,7 @@ export async function buildPdfExportPayload(
dpi: resolveExportPdfDpi(options?.dpi),
groups: exportGroups,
assetUrls,
assetResolveOrder,
};

return { payload, timestamp };
Expand Down
17 changes: 15 additions & 2 deletions api/src/lib/s3.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ vi.mock('@aws-sdk/client-s3', () => ({
PutObjectCommand: class {
constructor(public input: unknown) {}
},
PutBucketCorsCommand: class {
constructor(public input: unknown) {}
},
GetObjectCommand: class {
constructor(public input: unknown) {}
},
Expand Down Expand Up @@ -92,7 +95,12 @@ describe('s3 helpers', () => {
const prevAws = process.env.AWS_ENDPOINT_URL;
process.env.NODE_ENV = 'development';
process.env.AWS_ENDPOINT_URL = 'http://localhost:4566';
send.mockRejectedValueOnce(new Error('no bucket')).mockResolvedValueOnce({});
send
.mockRejectedValueOnce(new Error('no bucket'))
.mockResolvedValueOnce({})
.mockRejectedValueOnce(new Error('no bucket'))
.mockResolvedValueOnce({})
.mockResolvedValue({});
const { ensureDevLocalStackBuckets } = await import('./s3.js');
await ensureDevLocalStackBuckets();
expect(send.mock.calls.length).toBeGreaterThan(0);
Expand All @@ -107,7 +115,12 @@ describe('s3 helpers', () => {
process.env.AWS_ENDPOINT_URL = 'http://127.0.0.1:4566';
const err = new Error('exists');
(err as Error & { name: string }).name = 'BucketAlreadyOwnedByYou';
send.mockRejectedValueOnce(new Error('no head')).mockRejectedValueOnce(err);
send
.mockRejectedValueOnce(new Error('no head'))
.mockRejectedValueOnce(err)
.mockRejectedValueOnce(new Error('no head'))
.mockRejectedValueOnce(err)
.mockResolvedValue({});
const { ensureDevLocalStackBuckets } = await import('./s3.js');
await ensureDevLocalStackBuckets();
process.env.NODE_ENV = prevNode;
Expand Down
Loading
Loading