feat(F-096): completed feature
This commit is contained in:
@@ -257,6 +257,43 @@ export async function registerCatalogRoutes(
|
||||
return reply.send(serializeProduct(product, productImages));
|
||||
});
|
||||
|
||||
app.post('/products/:id/generate-seo', async (request, reply) => {
|
||||
const user = await deps.authenticate(request);
|
||||
requireRole(user, 'admin');
|
||||
const { id } = parseJson(idParamSchema, request.params);
|
||||
const product = await repository.findById(id);
|
||||
if (!product) throw new AppError(404, 'NOT_FOUND', 'Product not found');
|
||||
|
||||
const settingsResult = await deps.pool.query<{ key: string; value: string }>(
|
||||
`SELECT key, value FROM store_settings WHERE key = ANY($1::text[])`,
|
||||
[['ai_base_url', 'ai_model', 'ai_api_key', 'ai_seo_title_prompt', 'ai_seo_description_prompt']],
|
||||
);
|
||||
const settings = Object.fromEntries(settingsResult.rows.map((row) => [row.key, row.value]));
|
||||
const baseUrl = settings.ai_base_url?.trim();
|
||||
const model = settings.ai_model?.trim();
|
||||
const apiKey = settings.ai_api_key?.trim();
|
||||
if (!baseUrl || !model || !apiKey) {
|
||||
throw new AppError(422, 'AI_NOT_CONFIGURED', 'Configura proveedor, URL base, modelo y API key en Ajustes → IA para SEO');
|
||||
}
|
||||
|
||||
const replacements: Record<string, string> = {
|
||||
name: product.name,
|
||||
description: product.description ?? '',
|
||||
brand: product.brand?.name ?? '',
|
||||
};
|
||||
const promptFor = (template: string | undefined, fallback: string) =>
|
||||
(template || fallback).replace(/\{\{(name|description|brand)\}\}/g, (_, key: string) => replacements[key] ?? '');
|
||||
const patch: { seoTitle?: string; seoDescription?: string } = {};
|
||||
if (!product.seoTitle?.trim()) {
|
||||
patch.seoTitle = (await generateWithModel(baseUrl, model, apiKey, promptFor(settings.ai_seo_title_prompt, 'Genera un título SEO breve para {{name}}. Devuelve solo el título.'))).slice(0, 200);
|
||||
}
|
||||
if (!product.seoDescription?.trim()) {
|
||||
patch.seoDescription = (await generateWithModel(baseUrl, model, apiKey, promptFor(settings.ai_seo_description_prompt, 'Genera una meta descripción SEO en español para {{name}}. Devuelve solo la descripción.'))).slice(0, 500);
|
||||
}
|
||||
const updated = await repository.update(id, patch);
|
||||
return reply.send(serializeProduct(updated ?? product));
|
||||
});
|
||||
|
||||
const searchSchema: FastifySchema = {
|
||||
tags: ['Catalog'],
|
||||
summary: 'Search products (público)',
|
||||
@@ -635,6 +672,20 @@ function mapProductError(error: unknown): Error {
|
||||
return error instanceof Error ? error : new Error('Unknown product error');
|
||||
}
|
||||
|
||||
async function generateWithModel(baseUrl: string, model: string, apiKey: string, prompt: string): Promise<string> {
|
||||
const response = await fetch(`${baseUrl.replace(/\/$/, '')}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ model, messages: [{ role: 'user', content: prompt }], temperature: 0.4 }),
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
});
|
||||
const payload = await response.json().catch(() => null) as { choices?: Array<{ message?: { content?: unknown } }>; error?: { message?: string } } | null;
|
||||
if (!response.ok) throw new AppError(502, 'AI_PROVIDER_ERROR', payload?.error?.message ?? `El proveedor IA respondió ${response.status}`);
|
||||
const content = payload?.choices?.[0]?.message?.content;
|
||||
if (typeof content !== 'string' || !content.trim()) throw new AppError(502, 'AI_EMPTY_RESPONSE', 'El modelo IA no devolvió contenido');
|
||||
return content.trim();
|
||||
}
|
||||
|
||||
function sanitizeSearchTelemetryQuery(query: string | undefined): string | undefined {
|
||||
if (query === undefined) {
|
||||
return undefined;
|
||||
|
||||
Reference in New Issue
Block a user