Sync static image slots from the live website catalog.

Refresh now imports keys from the storefront and deletes unused slots plus their files.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Alireza Hassani
2026-08-17 09:55:03 +03:30
co-authored by Cursor
parent 1c7678ce67
commit 5e5bfc4aa3
8 changed files with 474 additions and 2 deletions
+181 -1
View File
@@ -9,8 +9,14 @@ import { Prisma } from '@prisma/client';
import { AuthUser } from '../auth/auth.types';
import { PermissionsService } from '../auth/permissions.service';
import { normalizeSpecialGroupKey } from '../common/special-group-key';
import { MediaService } from '../media/media.service';
import { PrismaService } from '../prisma/prisma.service';
import { TenantService } from '../tenant/tenant.service';
import {
parseWebsiteStaticImageCatalog,
WEBSITE_STATIC_IMAGE_CATALOG_PATH,
websiteCatalogUrls,
} from './website-static-image-catalog';
import {
CreateWebsiteStaticImageSlotDto,
ListWebsiteStaticImageSlotsDto,
@@ -51,6 +57,7 @@ export class WebsiteStaticImagesService {
private readonly prisma: PrismaService,
private readonly permissions: PermissionsService,
private readonly tenant: TenantService,
private readonly media: MediaService,
) {}
async listPublic(host: string, pageKey?: string) {
@@ -172,6 +179,106 @@ export class WebsiteStaticImagesService {
};
}
async syncFromWebsite(businessIdRaw: string, actor: AuthUser) {
const businessId = BigInt(businessIdRaw);
await this.assertPermission(businessId, actor.id, 'website.update');
const hosts = await this.listWebsiteHosts(businessId);
if (hosts.length === 0) {
throw new BadRequestException('This business has no website domain to read slots from');
}
const catalog = await this.fetchWebsiteCatalog(hosts);
const existing = await this.prisma.website_image_slots.findMany({
where: { business_id: businessId },
include: slotInclude,
});
const existingByKey = new Map(existing.map((slot) => [slot.slot_key, slot]));
const catalogKeys = new Set(catalog.map((slot) => slot.key));
const stale = existing.filter((slot) => !catalogKeys.has(slot.slot_key));
const staleMediaIds = stale.flatMap((slot) =>
slot.website_image_slot_items.map((item) => item.image_media_id),
);
let created = 0;
let updated = 0;
const deleted = stale.length;
await this.prisma.$transaction(async (tx) => {
for (const [index, slot] of catalog.entries()) {
const current = existingByKey.get(slot.key);
const itemCount = resolveItemCount(slot.kind, slot.itemCount);
if (!current) {
await tx.website_image_slots.create({
data: {
business_id: businessId,
slot_key: slot.key,
kind: slot.kind,
label: slot.label,
aspect_ratio: slot.aspectRatio,
recommended_width: slot.recommendedWidth,
item_count: itemCount,
page_key: resolvePageKey(slot.pageKey),
sort_order: index,
},
});
created += 1;
continue;
}
const imageCount = current.website_image_slot_items.length;
const nextKind =
slot.kind === 'single' && imageCount > 1 ? current.kind : slot.kind;
const nextItemCount =
nextKind === 'single'
? 1
: itemCount != null && imageCount > itemCount
? current.item_count
: itemCount;
await tx.website_image_slots.update({
where: { id: current.id },
data: {
kind: nextKind,
label: slot.label,
aspect_ratio: slot.aspectRatio,
recommended_width: slot.recommendedWidth,
item_count: nextItemCount,
page_key: resolvePageKey(slot.pageKey),
sort_order: index,
},
});
updated += 1;
}
if (stale.length > 0) {
await tx.website_image_slots.deleteMany({
where: {
business_id: businessId,
id: { in: stale.map((slot) => slot.id) },
},
});
}
});
await this.media.deleteUnused(businessId, staleMediaIds);
const listed = await this.prisma.website_image_slots.findMany({
where: { business_id: businessId },
orderBy: [{ sort_order: 'asc' }, { created_at: 'asc' }],
include: slotInclude,
});
return {
message: 'Static image slots refreshed from the website',
created,
updated,
deleted,
items: listed.map((slot) => this.serializeSlot(slot, false)),
};
}
async update(
businessIdRaw: string,
slotIdRaw: string,
@@ -215,6 +322,17 @@ export class WebsiteStaticImagesService {
);
}
const previousMediaIds =
dto.items !== undefined
? existing.website_image_slot_items.map((item) => item.image_media_id)
: [];
const nextMediaIds = new Set(
(dto.items ?? []).map((item) => item.imageMediaId),
);
const removedMediaIds = previousMediaIds.filter(
(id) => !nextMediaIds.has(id.toString()),
);
const updated = await this.prisma.$transaction(async (tx) => {
await tx.website_image_slots.update({
where: { id: slotId },
@@ -248,6 +366,8 @@ export class WebsiteStaticImagesService {
});
});
await this.media.deleteUnused(businessId, removedMediaIds);
return {
message: 'Static image slot updated successfully',
slot: this.serializeSlot(updated, false),
@@ -259,8 +379,12 @@ export class WebsiteStaticImagesService {
const slotId = BigInt(slotIdRaw);
await this.assertPermission(businessId, actor.id, 'website.update');
await this.findSlotOrThrow(businessId, slotId);
const existing = await this.findSlotOrThrow(businessId, slotId);
const mediaIds = existing.website_image_slot_items.map(
(item) => item.image_media_id,
);
await this.prisma.website_image_slots.delete({ where: { id: slotId } });
await this.media.deleteUnused(businessId, mediaIds);
return { message: 'Static image slot deleted successfully' };
}
@@ -395,6 +519,62 @@ export class WebsiteStaticImagesService {
};
}
private async listWebsiteHosts(businessId: bigint): Promise<string[]> {
const domains = await this.prisma.domain.findMany({
where: { businessId, isActive: true },
orderBy: [{ isPrimary: 'desc' }, { host: 'asc' }],
select: { host: true },
});
return domains
.map((domain) => domain.host.toLowerCase().trim())
.filter(
(host) =>
host &&
!host.startsWith('business.') &&
!host.startsWith('customer.'),
);
}
private async fetchWebsiteCatalog(hosts: string[]) {
const urls = websiteCatalogUrls(hosts);
let lastError = 'Website slot catalog was not found';
for (const url of urls) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 8000);
try {
const response = await fetch(url, {
method: 'GET',
redirect: 'follow',
signal: controller.signal,
headers: {
Accept: 'application/json',
'User-Agent': 'Meshkee-CMS/1.0',
},
});
if (!response.ok) {
lastError = `Website returned ${response.status} for ${WEBSITE_STATIC_IMAGE_CATALOG_PATH}`;
continue;
}
const payload: unknown = await response.json();
return parseWebsiteStaticImageCatalog(payload);
} catch (error) {
if (error instanceof Error && error.message.startsWith('Slot catalog')) {
lastError = error.message;
continue;
}
lastError = `Could not read ${WEBSITE_STATIC_IMAGE_CATALOG_PATH} from the website`;
} finally {
clearTimeout(timer);
}
}
throw new BadRequestException(
`${lastError}. The site must publish GET ${WEBSITE_STATIC_IMAGE_CATALOG_PATH} on its main domain.`,
);
}
private async assertPermission(
businessId: bigint,
userId: bigint,