-
Notifications
You must be signed in to change notification settings - Fork 254
Expand file tree
/
Copy pathsampleCollectionService.ts
More file actions
322 lines (278 loc) · 11.2 KB
/
Copy pathsampleCollectionService.ts
File metadata and controls
322 lines (278 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
import fs from 'fs/promises';
import path from 'path';
import sharp from 'sharp';
import { createCollection, getAllCollections } from '@/lib/repositories/collectionRepository';
import { createField } from '@/lib/repositories/collectionFieldRepository';
import { createItemsBulk, enrichItemsWithStatus } from '@/lib/repositories/collectionItemRepository';
import { insertValuesBulk } from '@/lib/repositories/collectionItemValueRepository';
import { findStatusFieldId } from '@/lib/collection-field-utils';
import { createAsset } from '@/lib/repositories/assetRepository';
import { getSupabaseAdmin } from '@/lib/supabase-server';
import { STORAGE_BUCKET, STORAGE_FOLDERS } from '@/lib/asset-constants';
import { getSampleCollectionById } from '@/lib/sample-collections';
import type { SampleCollectionDefinition, SampleFieldDefinition, SampleItemDefinition } from '@/lib/sample-collections';
import type { Asset, Collection, CollectionField, CollectionItemWithValues } from '@/types';
const SAMPLES_DIR = path.join(process.cwd(), 'storage', 'collections');
/**
* Sample Collection Service
*
* Creates a fully populated collection from a sample template.
* Uses batch inserts for items and values for performance.
*/
/** Built-in fields before custom fields */
const BUILT_IN_FIELDS_START: SampleFieldDefinition[] = [
{ name: 'ID', key: 'id', type: 'number', fillable: false, hidden: false, order: 0 },
{ name: 'Status', key: 'status', type: 'status', fillable: false, hidden: false, order: 1, is_computed: true },
{ name: 'Name', key: 'name', type: 'text', fillable: true, hidden: false, order: 2 },
{ name: 'Slug', key: 'slug', type: 'text', fillable: true, hidden: false, order: 3 },
];
/** Built-in fields after custom fields (always at the end) */
const BUILT_IN_FIELDS_END: SampleFieldDefinition[] = [
{ name: 'Created Date', key: 'created_at', type: 'date', fillable: false, hidden: false, order: 0 },
{ name: 'Updated Date', key: 'updated_at', type: 'date', fillable: false, hidden: false, order: 0 },
];
export interface SampleCollectionResult {
collection: Collection;
fields: CollectionField[];
assets: Asset[];
items: CollectionItemWithValues[];
}
/**
* Create a sample collection with fields and items from a template.
* @param sampleId - ID of the sample template (e.g. 'blog-posts')
* @param existingNames - Names of existing collections (to avoid duplicates)
*/
export async function createSampleCollection(
sampleId: string,
existingNames: string[] = []
): Promise<SampleCollectionResult> {
const sample = getSampleCollectionById(sampleId);
if (!sample) {
throw new Error(`Sample collection "${sampleId}" not found`);
}
// Generate unique name if needed
const collectionName = getUniqueName(sample.name, existingNames);
// Compute next order by finding the max order among existing collections
const existing = await getAllCollections({ is_published: false, deleted: false });
const maxOrder = existing.reduce((max, c) => Math.max(max, c.order ?? 0), -1);
// 1. Create collection at the end of the list
const collection = await createCollection({
name: collectionName,
order: maxOrder + 1,
is_published: false,
});
// 2. Create all fields with sequential ordering: start built-ins, custom, end built-ins.
// Built-in fields persist their `key` (which locks them from editing/deletion), while
// custom fields persist `key: null` so they remain editable like user-created fields.
// The sample key is retained separately (`lookupKey`) only to map sample item values.
const customFieldsReordered = sample.customFields.map((f, i) => ({
...f,
order: BUILT_IN_FIELDS_START.length + i,
lookupKey: f.key,
persistKey: null as string | null,
}));
const startFields = BUILT_IN_FIELDS_START.map(f => ({ ...f, lookupKey: f.key, persistKey: f.key }));
const endFieldsReordered = BUILT_IN_FIELDS_END.map((f, i) => ({
...f,
order: BUILT_IN_FIELDS_START.length + sample.customFields.length + i,
lookupKey: f.key,
persistKey: f.key,
}));
const allFieldDefs = [...startFields, ...customFieldsReordered, ...endFieldsReordered];
const fields = await Promise.all(
allFieldDefs.map(field =>
createField({
name: field.name,
key: field.persistKey,
type: field.type,
fillable: field.fillable,
hidden: field.hidden,
order: field.order,
is_computed: field.is_computed,
collection_id: collection.id,
is_published: false,
})
)
);
// 3. Build field key-to-id lookup using the sample key (fields share the order of allFieldDefs)
const fieldKeyToId: Record<string, string> = {};
allFieldDefs.forEach((def, i) => {
if (def.lookupKey) {
fieldKeyToId[def.lookupKey] = fields[i].id;
}
});
// 4. Create assets for image fields in parallel
const { assetIdMap, assets } = await createImageAssets(sample.items, fieldKeyToId);
// 5. Batch create items
const now = new Date().toISOString();
const items = await createItemsBulk(
sample.items.map((_, index) => ({
collection_id: collection.id,
manual_order: index + 1,
is_published: false,
}))
);
// 6. Batch insert all values (text + image asset IDs) in one query
const valuesToInsert = buildItemValues(sample, items, fieldKeyToId, assetIdMap, now);
if (valuesToInsert.length > 0) {
await insertValuesBulk(valuesToInsert);
}
// 7. Assemble items with values for the frontend (avoids a second API call)
const itemsWithValues: CollectionItemWithValues[] = items.map(item => {
const itemValues: Record<string, string> = {};
for (const v of valuesToInsert) {
if (v.item_id === item.id && v.value != null) {
itemValues[v.field_id] = v.value;
}
}
return { ...item, values: itemValues };
});
// 8. Enrich items with computed status values
const statusFieldId = findStatusFieldId(fields);
await enrichItemsWithStatus(itemsWithValues, collection.id, statusFieldId);
return { collection, fields, assets, items: itemsWithValues };
}
/**
* Find an existing draft asset by filename and source, or upload and create a new one.
* Avoids duplicate storage files and DB records for the same sample image.
*/
async function getOrUploadSampleImage(filename: string): Promise<Asset> {
const supabase = await getSupabaseAdmin();
if (!supabase) {
throw new Error('Supabase not configured');
}
// Check for existing draft asset with the same filename and source
const { data: existing } = await supabase
.from('assets')
.select('*')
.eq('filename', filename)
.eq('source', 'sample-collection')
.eq('is_published', false)
.is('deleted_at', null)
.limit(1)
.single();
if (existing) return existing as Asset;
// No existing asset — upload and create
const filePath = path.join(SAMPLES_DIR, filename);
const buffer = await fs.readFile(filePath);
const metadata = await sharp(buffer).metadata();
const width = metadata.width ?? 0;
const height = metadata.height ?? 0;
const timestamp = Date.now();
const random = Math.random().toString(36).substring(2, 15);
const ext = path.extname(filename).slice(1) || 'jpg';
const storagePath = `${STORAGE_FOLDERS.WEBSITE}/${timestamp}-${random}.${ext}`;
const { data, error } = await supabase.storage
.from(STORAGE_BUCKET)
.upload(storagePath, buffer, {
cacheControl: '3600',
upsert: false,
contentType: `image/${ext === 'jpg' ? 'jpeg' : ext}`,
});
if (error) {
throw new Error(`Failed to upload sample image "${filename}": ${error.message}`);
}
const { data: urlData } = supabase.storage
.from(STORAGE_BUCKET)
.getPublicUrl(data.path);
return createAsset({
filename,
source: 'sample-collection',
storage_path: data.path,
public_url: urlData.publicUrl,
file_size: buffer.length,
mime_type: `image/${ext === 'jpg' ? 'jpeg' : ext}`,
width,
height,
is_published: false,
});
}
/**
* Create assets for all image fields across all items.
* Deduplicates uploads -- if the same filename appears multiple times, it's uploaded once.
* Returns an ID map ("itemIndex:fieldKey" -> asset ID) and the full asset objects.
*/
async function createImageAssets(
sampleItems: SampleItemDefinition[],
fieldKeyToId: Record<string, string>
): Promise<{ assetIdMap: Record<string, string>; assets: Asset[] }> {
// Collect unique filenames and which entries reference them
const entries: Array<{ key: string; filename: string }> = [];
sampleItems.forEach((item, index) => {
if (!item.images) return;
for (const [fieldKey, filename] of Object.entries(item.images)) {
if (!fieldKeyToId[fieldKey]) continue;
entries.push({ key: `${index}:${fieldKey}`, filename });
}
});
if (entries.length === 0) return { assetIdMap: {}, assets: [] };
// Deduplicate: upload each unique filename once
const uniqueFilenames = [...new Set(entries.map(e => e.filename))];
const uploadedAssets = await Promise.all(uniqueFilenames.map(getOrUploadSampleImage));
const filenameToAsset: Record<string, Asset> = {};
uniqueFilenames.forEach((fn, i) => {
filenameToAsset[fn] = uploadedAssets[i];
});
// Build ID map
const assetIdMap: Record<string, string> = {};
for (const entry of entries) {
assetIdMap[entry.key] = filenameToAsset[entry.filename].id;
}
return { assetIdMap, assets: uploadedAssets };
}
/**
* Build flat array of item values for bulk insert.
* Merges built-in auto-values, sample text values, and image asset IDs.
* Values are stored as-is (rich_text content is already in TipTap JSON format).
*/
function buildItemValues(
sample: SampleCollectionDefinition,
items: Array<{ id: string }>,
fieldKeyToId: Record<string, string>,
imageAssetIds: Record<string, string>,
now: string
): Array<{ item_id: string; field_id: string; value: string | null; is_published: boolean }> {
const values: Array<{ item_id: string; field_id: string; value: string | null; is_published: boolean }> = [];
items.forEach((item, index) => {
const sampleItem = sample.items[index];
if (!sampleItem) return;
// Auto-generated built-in values
const autoValues: Record<string, string> = {
id: String(index + 1),
created_at: now,
updated_at: now,
};
// Merge auto-values with sample item text values
const allValues: Record<string, string> = { ...autoValues, ...sampleItem.values };
// Add image asset IDs
if (sampleItem.images) {
for (const fieldKey of Object.keys(sampleItem.images)) {
const assetId = imageAssetIds[`${index}:${fieldKey}`];
if (assetId) {
allValues[fieldKey] = assetId;
}
}
}
for (const [key, value] of Object.entries(allValues)) {
const fieldId = fieldKeyToId[key];
if (fieldId && value != null) {
values.push({
item_id: item.id,
field_id: fieldId,
value,
is_published: false,
});
}
}
});
return values;
}
/** Generate a unique collection name by appending a number if needed */
function getUniqueName(baseName: string, existingNames: string[]): string {
if (!existingNames.includes(baseName)) return baseName;
let counter = 1;
while (existingNames.includes(`${baseName} ${counter}`)) {
counter++;
}
return `${baseName} ${counter}`;
}