feat(F-096): completed feature
This commit is contained in:
@@ -8,6 +8,7 @@ const TABS = [
|
||||
{ id: 'general', label: 'General', icon: '⚙️' },
|
||||
{ id: 'social', label: 'Redes sociales', icon: '🌐' },
|
||||
{ id: 'footer', label: 'Footer', icon: '📄' },
|
||||
{ id: 'ai', label: 'IA para SEO', icon: '✨' },
|
||||
] as const;
|
||||
type TabId = (typeof TABS)[number]['id'];
|
||||
|
||||
@@ -31,7 +32,8 @@ export default function SettingsPage() {
|
||||
if (!form) return;
|
||||
setSaving(true); setErr(''); setMsg('');
|
||||
try {
|
||||
const updated = await settingsApi.update(form);
|
||||
const { aiApiKey, ...settingsWithoutKey } = form;
|
||||
const updated = await settingsApi.update(aiApiKey ? form : settingsWithoutKey);
|
||||
setData(updated); setForm(updated);
|
||||
setMsg('Cambios guardados correctamente');
|
||||
setTimeout(() => setMsg(''), 4000);
|
||||
@@ -42,7 +44,7 @@ export default function SettingsPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const field = (key: keyof FormData, label: string, opts?: { type?: string; placeholder?: string; rows?: number; hint?: string }) => (
|
||||
const field = (key: Exclude<keyof FormData, 'aiApiKeyConfigured'>, label: string, opts?: { type?: string; placeholder?: string; rows?: number; hint?: string }) => (
|
||||
<div key={key}>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">{label}</label>
|
||||
{opts?.rows ? (
|
||||
@@ -129,6 +131,23 @@ export default function SettingsPage() {
|
||||
</>
|
||||
)}
|
||||
|
||||
{tab === 'ai' && (
|
||||
<>
|
||||
<div className="px-6 py-4 bg-gray-50 border-b border-gray-200">
|
||||
<h2 className="text-base font-semibold text-gray-800">Modelo de IA para SEO</h2>
|
||||
<p className="text-xs text-gray-400 mt-0.5">Se usa solo para completar campos SEO que estén vacíos.</p>
|
||||
</div>
|
||||
<div className="p-6 space-y-5">
|
||||
{field('aiProvider', 'Proveedor', { placeholder: 'OpenAI compatible' })}
|
||||
{field('aiBaseUrl', 'URL base de la API', { type: 'url', placeholder: 'https://api.openai.com/v1' })}
|
||||
{field('aiModel', 'Modelo', { placeholder: 'gpt-4o-mini' })}
|
||||
{field('aiApiKey', 'API key', { type: 'password', placeholder: form?.aiApiKeyConfigured ? 'API key configurada (escribe para reemplazar)' : 'sk-...' })}
|
||||
{field('aiSeoTitlePrompt', 'Prompt para Título SEO', { rows: 4, hint: 'Usa {{name}}, {{description}} y {{brand}} como variables.' })}
|
||||
{field('aiSeoDescriptionPrompt', 'Prompt para Descripción SEO (Google)', { rows: 5, hint: 'Usa {{name}}, {{description}} y {{brand}} como variables.' })}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{tab === 'footer' && (
|
||||
<>
|
||||
<div className="px-6 py-4 bg-gray-50 border-b border-gray-200">
|
||||
|
||||
@@ -152,13 +152,22 @@ export function ProductEditor({ productId }: ProductEditorProps) {
|
||||
featured,
|
||||
attributes,
|
||||
state,
|
||||
seoTitle: seoTitle || undefined,
|
||||
seoDescription: seoDesc || undefined,
|
||||
seoTitle: seoTitle.trim() || null,
|
||||
seoDescription: seoDesc.trim() || null,
|
||||
expirationDate: expirationDate || undefined,
|
||||
};
|
||||
let saved: Product;
|
||||
if (isCreate) saved = await productsApi.create(payload);
|
||||
else saved = await productsApi.update(productId, payload);
|
||||
if (!seoTitle.trim() || !seoDesc.trim()) {
|
||||
try {
|
||||
saved = await productsApi.generateSeo(saved.id);
|
||||
setSeoTitle(saved.seoTitle ?? '');
|
||||
setSeoDesc(saved.seoDescription ?? '');
|
||||
} catch (generationError) {
|
||||
setError(generationError instanceof Error ? generationError.message : 'No se pudieron generar los campos SEO');
|
||||
}
|
||||
}
|
||||
snapRef.current = getSnap();
|
||||
dirtyRef.current = false;
|
||||
setSuccess(isCreate ? '¡Producto creado!' : 'Cambios guardados');
|
||||
|
||||
@@ -80,6 +80,8 @@ export const productsApi = {
|
||||
create: (data: unknown) => api.post<import('@/types').Product>('/api/products', data),
|
||||
update: (id: string, data: unknown) =>
|
||||
api.patch<import('@/types').Product>(`/api/products/${id}`, data),
|
||||
generateSeo: (id: string) =>
|
||||
api.post<import('@/types').Product>(`/api/products/${id}/generate-seo`),
|
||||
setState: (id: string, state: 'active' | 'archived') =>
|
||||
api.patch(`/api/products/${id}/state`, { state }),
|
||||
delete: (id: string) => api.delete(`/api/products/${id}`),
|
||||
@@ -325,6 +327,13 @@ export interface StoreSettings {
|
||||
footerText: string;
|
||||
facebookUrl: string;
|
||||
instagramUrl: string;
|
||||
aiProvider: string;
|
||||
aiBaseUrl: string;
|
||||
aiModel: string;
|
||||
aiApiKey: string;
|
||||
aiApiKeyConfigured?: boolean;
|
||||
aiSeoTitlePrompt: string;
|
||||
aiSeoDescriptionPrompt: string;
|
||||
}
|
||||
|
||||
export const settingsApi = {
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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;
|
||||
|
||||
@@ -21,6 +21,12 @@ const updateSettingsSchema = z.object({
|
||||
footerText: z.string().max(400).optional(),
|
||||
facebookUrl: z.string().url().optional().or(z.literal('')),
|
||||
instagramUrl: z.string().url().optional().or(z.literal('')),
|
||||
aiProvider: z.string().max(80).optional(),
|
||||
aiBaseUrl: z.string().url().optional().or(z.literal('')),
|
||||
aiModel: z.string().max(120).optional(),
|
||||
aiApiKey: z.string().max(500).optional(),
|
||||
aiSeoTitlePrompt: z.string().max(2000).optional(),
|
||||
aiSeoDescriptionPrompt: z.string().max(4000).optional(),
|
||||
});
|
||||
|
||||
const SETTING_KEYS: Record<string, string> = {
|
||||
@@ -32,6 +38,12 @@ const SETTING_KEYS: Record<string, string> = {
|
||||
footerText: 'footer_text',
|
||||
facebookUrl: 'facebook_url',
|
||||
instagramUrl: 'instagram_url',
|
||||
aiProvider: 'ai_provider',
|
||||
aiBaseUrl: 'ai_base_url',
|
||||
aiModel: 'ai_model',
|
||||
aiApiKey: 'ai_api_key',
|
||||
aiSeoTitlePrompt: 'ai_seo_title_prompt',
|
||||
aiSeoDescriptionPrompt: 'ai_seo_description_prompt',
|
||||
};
|
||||
|
||||
export async function registerStoreSettingsRoutes(
|
||||
@@ -63,6 +75,13 @@ export async function registerStoreSettingsRoutes(
|
||||
footerText: map['footer_text'] ?? '',
|
||||
facebookUrl: map['facebook_url'] ?? '',
|
||||
instagramUrl: map['instagram_url'] ?? '',
|
||||
aiProvider: map['ai_provider'] ?? '',
|
||||
aiBaseUrl: map['ai_base_url'] ?? '',
|
||||
aiModel: map['ai_model'] ?? '',
|
||||
aiApiKey: '',
|
||||
aiApiKeyConfigured: Boolean(map['ai_api_key']),
|
||||
aiSeoTitlePrompt: map['ai_seo_title_prompt'] ?? 'Genera un título SEO breve y atractivo para este producto: {{name}}. Devuelve solo el título.',
|
||||
aiSeoDescriptionPrompt: map['ai_seo_description_prompt'] ?? 'Genera una meta descripción SEO en español, clara y persuasiva, para este producto: {{name}}. Devuelve solo la descripción.',
|
||||
});
|
||||
});
|
||||
|
||||
@@ -118,6 +137,13 @@ export async function registerStoreSettingsRoutes(
|
||||
footerText: map['footer_text'] ?? '',
|
||||
facebookUrl: map['facebook_url'] ?? '',
|
||||
instagramUrl: map['instagram_url'] ?? '',
|
||||
aiProvider: map['ai_provider'] ?? '',
|
||||
aiBaseUrl: map['ai_base_url'] ?? '',
|
||||
aiModel: map['ai_model'] ?? '',
|
||||
aiApiKey: '',
|
||||
aiApiKeyConfigured: Boolean(map['ai_api_key']),
|
||||
aiSeoTitlePrompt: map['ai_seo_title_prompt'] ?? 'Genera un título SEO breve y atractivo para este producto: {{name}}. Devuelve solo el título.',
|
||||
aiSeoDescriptionPrompt: map['ai_seo_description_prompt'] ?? 'Genera una meta descripción SEO en español, clara y persuasiva, para este producto: {{name}}. Devuelve solo la descripción.',
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user