Files
SupplierSystem/server/src/services/skuImageService.ts
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

141 lines
4.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { Request } from 'express';
import {
callWithText,
generateImage,
isLlmServiceError,
resolveLlmRuntimeConfig,
type LlmCallOptions,
} from './llmService';
import { saveSkuImageToDb } from './skuImageDbService';
import { saveSkuImageToStorage } from './skuImageStorageService';
import { isObjectStorageEnabled } from './storageProvider';
import { resolvePrompt } from './promptRegistryService';
import { getSkuAiImageConfig } from './skuImageConfigService';
const DEFAULT_SKU_IMAGE_SIZE = '1024x1024';
const ALLOWED_IMAGE_SIZES = new Set(['256x256', '512x512', '768x768', '1024x1024']);
function getImageSize(requestedSize?: string, configuredSize?: string) {
const size = requestedSize || configuredSize || DEFAULT_SKU_IMAGE_SIZE;
return ALLOWED_IMAGE_SIZES.has(size) ? size : DEFAULT_SKU_IMAGE_SIZE;
}
async function buildProductImagePrompt(params: {
skuName: string;
categoryName?: string;
spec?: string;
unit?: string;
}, options?: LlmCallOptions): Promise<string> {
const detailParts = [`商品名称:${params.skuName}`];
if (params.categoryName) detailParts.push(`分类:${params.categoryName}`);
if (params.spec) detailParts.push(`规格:${params.spec}`);
if (params.unit) detailParts.push(`单位:${params.unit}`);
const meta = await resolvePrompt('catalog.sku.image_meta', { branchCode: options?.branchCode });
const llmPrompt = await callWithText(
meta.systemPrompt,
detailParts.join(','),
options
).catch((error) => {
if (isLlmServiceError(error)) throw error;
return '';
});
if (llmPrompt?.trim()) {
return llmPrompt.trim();
}
return `${params.skuName},生鲜食材商品摄影,单件居中,白色背景,自然光,高清真实,无文字无水印`;
}
async function requestGeneratedImage(prompt: string, size?: string, options?: LlmCallOptions): Promise<Buffer | null> {
const runtime = await resolveLlmRuntimeConfig(options);
const resolvedSize = getImageSize(size, runtime.imageSize);
return generateImage(prompt, { ...options, size: resolvedSize });
}
function escapeSvgText(value: string) {
return value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
function buildFallbackSvg(params: { skuName: string; categoryName?: string; unit?: string }) {
const title = escapeSvgText(params.skuName).slice(0, 18);
const subtitle = escapeSvgText([params.categoryName, params.unit].filter(Boolean).join(' / ')).slice(0, 24);
return Buffer.from(
`<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#f8fafc"/>
<stop offset="1" stop-color="#e2e8f0"/>
</linearGradient>
</defs>
<rect width="512" height="512" rx="48" fill="url(#bg)"/>
<circle cx="256" cy="210" r="88" fill="#cbd5e1"/>
<path d="M164 350c34-58 150-58 184 0" fill="none" stroke="#94a3b8" stroke-width="24" stroke-linecap="round"/>
<text x="256" y="420" text-anchor="middle" font-family="Arial, sans-serif" font-size="34" font-weight="700" fill="#334155">${title}</text>
<text x="256" y="462" text-anchor="middle" font-family="Arial, sans-serif" font-size="22" fill="#64748b">${subtitle}</text>
</svg>`,
'utf8'
);
}
export async function generateSkuProductImage(
body: {
sku_name?: string;
sku_code?: string;
category_name?: string;
spec?: string;
unit?: string;
size?: string;
branchCode?: string | null;
},
_req?: Request
) {
const skuName = String(body.sku_name || '').trim();
if (!skuName) {
throw new Error('商品名称不能为空');
}
const skuCode = String(body.sku_code || '').trim();
if (!skuCode) {
throw new Error('商品编码不能为空(AI 生图将保存到数据库)');
}
const skuAi = await getSkuAiImageConfig(body.branchCode);
if (!skuAi.enabled) {
throw new Error('该公司未开启商品 AI 生图');
}
const prompt = await buildProductImagePrompt({
skuName,
categoryName: body.category_name?.trim(),
spec: body.spec?.trim(),
unit: body.unit?.trim(),
}, { branchCode: body.branchCode });
const buffer = await requestGeneratedImage(prompt, body.size, { branchCode: body.branchCode });
const generatedByAi = Boolean(buffer);
const imageBuffer = buffer || buildFallbackSvg({
skuName,
categoryName: body.category_name?.trim(),
unit: body.unit?.trim(),
});
const mimeType = generatedByAi ? 'image/jpeg' : 'image/svg+xml';
const useCos = isObjectStorageEnabled();
const imageUrl = useCos
? await saveSkuImageToStorage(skuCode, imageBuffer, mimeType)
: await saveSkuImageToDb(skuCode, imageBuffer, mimeType);
return {
imageUrl,
prompt,
generatedByAi,
storedInDb: !useCos,
storedInCos: useCos,
};
}