@interware/content-generator 0.6.1 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_chunks/App-Cwr5ra5m.js +1380 -0
- package/dist/_chunks/App-h4_txTsI.mjs +1362 -0
- package/dist/_chunks/{ImageStudioTabs-BLAH3KYv.mjs → ImageStudioTabs-B-mOwDfY.mjs} +687 -682
- package/dist/_chunks/{ImageStudioTabs-DtusqpQO.js → ImageStudioTabs-CG4KTn1S.js} +683 -678
- package/dist/_chunks/{Settings-o2GngLaW.mjs → Settings-BT-EqvXs.mjs} +2 -2
- package/dist/_chunks/{Settings-BQXxV3LO.js → Settings-D4NGBTk1.js} +4 -4
- package/dist/_chunks/{StudioApp-BaySMwrk.js → StudioApp-_ViSAwCm.js} +2 -2
- package/dist/_chunks/{StudioApp-C_znlQRo.mjs → StudioApp-xaEy-uIk.mjs} +2 -2
- package/dist/_chunks/{index-BKigRXm3.mjs → index-D67xWUPz.mjs} +3 -28
- package/dist/_chunks/{index-BKhe-Jyx.js → index-NA9OuMGs.js} +3 -28
- package/dist/admin/index.js +1 -1
- package/dist/admin/index.mjs +1 -1
- package/dist/admin/src/features/articles/ArticlePage.d.ts +5 -0
- package/dist/admin/src/features/articles/ArticlesPage.d.ts +7 -0
- package/dist/admin/src/features/articles/NewArticlePage.d.ts +6 -0
- package/dist/admin/src/features/articles/SharePreview.d.ts +19 -0
- package/dist/admin/src/features/articles/articlesApi.d.ts +94 -0
- package/dist/admin/src/features/articles/model.d.ts +24 -0
- package/dist/admin/src/features/articles/useArticlesApi.d.ts +19 -0
- package/dist/admin/src/features/library/LibraryImagePicker.d.ts +6 -1
- package/dist/admin/src/lib/postText.d.ts +25 -0
- package/dist/server/index.js +534 -327
- package/dist/server/index.mjs +535 -328
- package/dist/server/src/articles/generation.d.ts +135 -0
- package/dist/server/src/articles/schedule.d.ts +12 -0
- package/dist/server/src/articles/sources.d.ts +12 -0
- package/dist/server/src/bootstrap.d.ts +2 -0
- package/dist/server/src/controllers/articles.d.ts +30 -0
- package/dist/server/src/controllers/controller.d.ts +0 -4
- package/dist/server/src/controllers/index.d.ts +92 -4
- package/dist/server/src/index.d.ts +122 -67
- package/dist/server/src/services/articles.d.ts +126 -0
- package/dist/server/src/services/image-studio.d.ts +6 -11
- package/dist/server/src/services/index.d.ts +30 -63
- package/dist/server/src/services/service.d.ts +1 -62
- package/package.json +1 -1
- package/dist/_chunks/App-CJxSC8yt.js +0 -1105
- package/dist/_chunks/App-qbgUXlOZ.mjs +0 -1087
- package/dist/_chunks/getTranslation-B6Bsu-uq.mjs +0 -5
- package/dist/_chunks/getTranslation-BRVMWSf8.js +0 -4
- package/dist/admin/src/components/commons/dialog/index.d.ts +0 -12
- package/dist/admin/src/components/commons/generate-image-dialog/index.d.ts +0 -5
- package/dist/admin/src/components/generate-content/Form.d.ts +0 -15
- package/dist/admin/src/components/home/table.d.ts +0 -13
- package/dist/admin/src/components/index.d.ts +0 -12
- package/dist/admin/src/containers/generate-content/index.d.ts +0 -2
- package/dist/admin/src/containers/home/index.d.ts +0 -2
- package/dist/admin/src/hooks/useDialog.d.ts +0 -11
- package/dist/admin/src/lib/use-cases/articles/index.d.ts +0 -16
- package/dist/admin/src/lib/use-cases/categories/index.d.ts +0 -16
- package/dist/admin/src/lib/use-cases/facebook/index.d.ts +0 -5
- package/dist/admin/src/lib/use-cases/generate-content/index.d.ts +0 -6
- package/dist/admin/src/lib/use-cases/linkedin/index.d.ts +0 -5
- package/dist/admin/src/lib/use-cases/users/index.d.ts +0 -16
- package/dist/admin/src/pages/GenerateContent.d.ts +0 -2
- package/dist/admin/src/pages/HomePage.d.ts +0 -2
- package/dist/admin/src/reducers/dialog/index.d.ts +0 -6
- package/dist/admin/src/types/reducers.d.ts +0 -4
package/dist/server/index.js
CHANGED
|
@@ -41,7 +41,20 @@ const ensureFolder = async (strapi, name2) => {
|
|
|
41
41
|
const created = await strapi.plugin("upload").service("folder").create({ name: name2, parent: null });
|
|
42
42
|
return created.id;
|
|
43
43
|
};
|
|
44
|
+
const SCHEDULE_CRON = "content-generator-publicar-programados";
|
|
44
45
|
const bootstrap = async ({ strapi }) => {
|
|
46
|
+
strapi.cron.add({
|
|
47
|
+
[SCHEDULE_CRON]: {
|
|
48
|
+
task: async () => {
|
|
49
|
+
try {
|
|
50
|
+
await strapi.plugin(PLUGIN_ID).service("articles").publishDue();
|
|
51
|
+
} catch (err) {
|
|
52
|
+
strapi.log.error(`[content-generator] publicar programados: ${err.message}`);
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
options: { rule: "* * * * *" }
|
|
56
|
+
}
|
|
57
|
+
});
|
|
45
58
|
strapi.admin.services.permission.actionProvider.registerMany([
|
|
46
59
|
{
|
|
47
60
|
section: "plugins",
|
|
@@ -100,26 +113,29 @@ const template = { schema };
|
|
|
100
113
|
const contentTypes = {
|
|
101
114
|
template
|
|
102
115
|
};
|
|
116
|
+
const POST_MAX = 3e3;
|
|
117
|
+
const hashtags = (keywords) => keywords.map((k) => k.trim().replace(/\s+/g, "").replace(/[^\p{L}\p{N}_]/gu, "")).filter(Boolean).map((k) => `#${k}`).join(" ");
|
|
118
|
+
const defaultPostText = ({ titulo, descripcion, keywords }, red) => [red === "facebook" ? titulo : "", descripcion, hashtags(keywords)].filter(Boolean).join("\n\n");
|
|
119
|
+
const checkPostText = (input) => {
|
|
120
|
+
const text2 = typeof input === "string" ? input.trim() : "";
|
|
121
|
+
if (!text2) return { ok: true, text: null };
|
|
122
|
+
if ([...text2].length > POST_MAX) return { ok: false, error: `El texto de la publicación puede tener hasta ${POST_MAX} caracteres.` };
|
|
123
|
+
return { ok: true, text: text2 };
|
|
124
|
+
};
|
|
125
|
+
const validarMensaje = (ctx) => {
|
|
126
|
+
const check = checkPostText(ctx.request.body?.mensaje);
|
|
127
|
+
if ("error" in check) {
|
|
128
|
+
ctx.status = 400;
|
|
129
|
+
ctx.body = { data: null, error: { status: 400, name: "ValidationError", message: check.error } };
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
ctx.request.body = { ...ctx.request.body, mensaje: check.text ?? void 0 };
|
|
133
|
+
if (!check.text) delete ctx.request.body.mensaje;
|
|
134
|
+
return true;
|
|
135
|
+
};
|
|
103
136
|
const controller = ({ strapi }) => {
|
|
104
137
|
const pluginService = () => strapi.plugin("strapi-content-generator-gemini").service("service");
|
|
105
138
|
return {
|
|
106
|
-
async getArticles(ctx) {
|
|
107
|
-
const contentType = strapi.contentType("api::articulo.articulo");
|
|
108
|
-
await strapi.contentAPI.validate.query(ctx.query, contentType, {
|
|
109
|
-
auth: ctx.state.auth
|
|
110
|
-
});
|
|
111
|
-
const sanitizedQueryParams = await strapi.contentAPI.sanitize.query(
|
|
112
|
-
ctx.query,
|
|
113
|
-
contentType,
|
|
114
|
-
{
|
|
115
|
-
auth: ctx.state.auth
|
|
116
|
-
}
|
|
117
|
-
);
|
|
118
|
-
const documents = await pluginService().getArticulos(sanitizedQueryParams);
|
|
119
|
-
return await strapi.contentAPI.sanitize.output(documents, contentType, {
|
|
120
|
-
auth: ctx.state.auth
|
|
121
|
-
});
|
|
122
|
-
},
|
|
123
139
|
async getCategories(ctx) {
|
|
124
140
|
const contentType = strapi.contentType("api::categoria.categoria");
|
|
125
141
|
await strapi.contentAPI.validate.query(ctx.query, contentType, {
|
|
@@ -137,29 +153,6 @@ const controller = ({ strapi }) => {
|
|
|
137
153
|
auth: ctx.state.auth
|
|
138
154
|
});
|
|
139
155
|
},
|
|
140
|
-
async getUsers(ctx) {
|
|
141
|
-
const contentType = strapi.contentType("plugin::users-permissions.user");
|
|
142
|
-
await strapi.contentAPI.validate.query(ctx.query, contentType, {
|
|
143
|
-
auth: ctx.state.auth
|
|
144
|
-
});
|
|
145
|
-
const sanitizedQueryParams = await strapi.contentAPI.sanitize.query(
|
|
146
|
-
ctx.query,
|
|
147
|
-
contentType,
|
|
148
|
-
{
|
|
149
|
-
auth: ctx.state.auth
|
|
150
|
-
}
|
|
151
|
-
);
|
|
152
|
-
const documents = await pluginService().getUsuarios(sanitizedQueryParams);
|
|
153
|
-
return await strapi.contentAPI.sanitize.output(documents, contentType, {
|
|
154
|
-
auth: ctx.state.auth
|
|
155
|
-
});
|
|
156
|
-
},
|
|
157
|
-
async generateArticle(ctx) {
|
|
158
|
-
ctx.body = await pluginService().generateArticle(ctx);
|
|
159
|
-
},
|
|
160
|
-
async generateImageForArticle(ctx) {
|
|
161
|
-
ctx.body = await pluginService().generateImageForArticle(ctx);
|
|
162
|
-
},
|
|
163
156
|
async downloadFile(ctx) {
|
|
164
157
|
await pluginService().downloadFile(ctx);
|
|
165
158
|
},
|
|
@@ -167,10 +160,10 @@ const controller = ({ strapi }) => {
|
|
|
167
160
|
ctx.body = await pluginService().generateVideo(ctx);
|
|
168
161
|
},
|
|
169
162
|
async publishToLinkedIn(ctx) {
|
|
170
|
-
ctx.body = await pluginService().publishToLinkedIn(ctx);
|
|
163
|
+
if (validarMensaje(ctx)) ctx.body = await pluginService().publishToLinkedIn(ctx);
|
|
171
164
|
},
|
|
172
165
|
async publishToFacebook(ctx) {
|
|
173
|
-
ctx.body = await pluginService().publishToFacebook(ctx);
|
|
166
|
+
if (validarMensaje(ctx)) ctx.body = await pluginService().publishToFacebook(ctx);
|
|
174
167
|
}
|
|
175
168
|
};
|
|
176
169
|
};
|
|
@@ -273,14 +266,11 @@ const safetySettings = (safety) => HARM_CATEGORIES.map((category) => ({
|
|
|
273
266
|
category,
|
|
274
267
|
threshold: safety ? genai.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE : genai.HarmBlockThreshold.BLOCK_ONLY_HIGH
|
|
275
268
|
}));
|
|
276
|
-
const
|
|
277
|
-
none: "ALLOW_NONE",
|
|
278
|
-
adults: genai.PersonGeneration.ALLOW_ADULT
|
|
279
|
-
};
|
|
269
|
+
const NO_PEOPLE = "ALLOW_NONE";
|
|
280
270
|
const imageConfig = ({ aspectRatio, imageSize, allowPeople }, backend = "gemini-api") => ({
|
|
281
271
|
...aspectRatio ? { aspectRatio } : {},
|
|
282
272
|
...imageSize ? { imageSize } : {},
|
|
283
|
-
...backend === "vertex"
|
|
273
|
+
...backend === "vertex" && !allowPeople ? { personGeneration: NO_PEOPLE } : {}
|
|
284
274
|
});
|
|
285
275
|
const promptPart = (text2, allowPeople, backend = "gemini-api") => ({
|
|
286
276
|
text: backend === "gemini-api" && !allowPeople ? `${text2} ${PEOPLE_CLAUSE}` : text2
|
|
@@ -331,7 +321,7 @@ const INVISIBLE = /[----]/g;
|
|
|
331
321
|
const TAG = /<\/?[a-z][^>]*>/gi;
|
|
332
322
|
const sanitizePrompt = (text2) => text2.normalize("NFC").replace(CONTROL, "").replace(INVISIBLE, "").replace(TAG, "").replace(/\s+/g, " ").trim();
|
|
333
323
|
const PROMPT_LABELS = { label: "El prompt", empty: "Escribe un prompt." };
|
|
334
|
-
const INSTRUCTION_LABELS = { label: "La instrucción", empty: "Describe el cambio que quieres." };
|
|
324
|
+
const INSTRUCTION_LABELS$1 = { label: "La instrucción", empty: "Describe el cambio que quieres." };
|
|
335
325
|
const checkPrompt = (text2, { label, empty } = PROMPT_LABELS) => {
|
|
336
326
|
const clean2 = sanitizePrompt(text2);
|
|
337
327
|
if (!clean2) return { ok: false, error: empty };
|
|
@@ -346,6 +336,10 @@ const EXPAND_INSTRUCTION = (concept) => [
|
|
|
346
336
|
`Concepto: ${concept}`
|
|
347
337
|
].join("\n");
|
|
348
338
|
class BlockedError extends Error {
|
|
339
|
+
constructor(message, detail) {
|
|
340
|
+
super(message);
|
|
341
|
+
this.detail = detail;
|
|
342
|
+
}
|
|
349
343
|
}
|
|
350
344
|
const sourceOf = (chunk) => {
|
|
351
345
|
if (chunk.web?.uri) return { title: chunk.web.title || new URL(chunk.web.uri).hostname, uri: chunk.web.uri };
|
|
@@ -367,12 +361,21 @@ const BLOCK_REASONS = {
|
|
|
367
361
|
PROHIBITED_CONTENT: "El modelo bloqueó la solicitud por contenido no permitido.",
|
|
368
362
|
IMAGE_SAFETY: "El modelo bloqueó la imagen resultante por seguridad."
|
|
369
363
|
};
|
|
364
|
+
const blockMessage = (reason, googleMessage) => {
|
|
365
|
+
const code = googleMessage.match(/Support code:\s*(\d+)/i)?.[1];
|
|
366
|
+
const suffix = code ? ` (Código de Google: ${code})` : "";
|
|
367
|
+
if (/PersonGeneration/i.test(googleMessage)) {
|
|
368
|
+
return /input image/i.test(googleMessage) ? `Google rechazó la imagen de referencia por la configuración de «Personas». Prueba con otra imagen o cambia «Personas».${suffix}` : `Google filtró la imagen generada por la configuración de «Personas». Cambia el prompt o «Personas».${suffix}`;
|
|
369
|
+
}
|
|
370
|
+
return `${BLOCK_REASONS[reason] ?? "El modelo no devolvió una imagen. Intenta con otro prompt."}${suffix}`;
|
|
371
|
+
};
|
|
370
372
|
const imageFrom = (res, model) => {
|
|
371
373
|
const parts = res.candidates?.[0]?.content?.parts ?? [];
|
|
372
374
|
const part = parts.find((p) => p.inlineData?.data && (p.inlineData.mimeType ?? "").startsWith("image/"));
|
|
373
375
|
if (part?.inlineData?.data) return { image: part.inlineData.data, mimeType: part.inlineData.mimeType ?? "image/png", model };
|
|
374
|
-
const reason = res.promptFeedback?.blockReason ?? res.candidates?.[0]?.finishReason;
|
|
375
|
-
|
|
376
|
+
const reason = String(res.promptFeedback?.blockReason ?? res.candidates?.[0]?.finishReason ?? "");
|
|
377
|
+
const googleMessage = [res.candidates?.[0]?.finishMessage, res.promptFeedback?.blockReasonMessage].filter(Boolean).join(" ");
|
|
378
|
+
throw new BlockedError(blockMessage(reason, googleMessage), [reason, googleMessage].filter(Boolean).join(": ") || void 0);
|
|
376
379
|
};
|
|
377
380
|
const inline = async (file, read) => inlinePart(await read(file.filepath), file.mimetype ?? "image/png");
|
|
378
381
|
const userTurn = (parts) => [{ role: "user", parts }];
|
|
@@ -387,25 +390,6 @@ const createImageStudio = (getClient, read = (p) => fs.promises.readFile(p)) =>
|
|
|
387
390
|
return availableModels(null);
|
|
388
391
|
}
|
|
389
392
|
},
|
|
390
|
-
/**
|
|
391
|
-
* Imagen para un artículo (S4.12): antes usaba Imagen 4, que Google apagó. Usa el primer modelo
|
|
392
|
-
* disponible del catálogo y ajusta proporción y tamaño a lo que admite. Devuelve base64.
|
|
393
|
-
*/
|
|
394
|
-
async generateForArticle(prompt, aspectRatio, imageSize) {
|
|
395
|
-
const [model] = (await this.models()).models;
|
|
396
|
-
const { image } = await this.generate({
|
|
397
|
-
prompt,
|
|
398
|
-
model,
|
|
399
|
-
aspectRatio: model.aspectRatios.includes(aspectRatio) ? aspectRatio : "16:9",
|
|
400
|
-
imageSize: model.sizes.includes(imageSize) ? imageSize : void 0,
|
|
401
|
-
safety: true,
|
|
402
|
-
// El estilo de marca de los artículos no lleva personas (su JSON ya lo pide); ahora también el parámetro.
|
|
403
|
-
allowPeople: false,
|
|
404
|
-
grounding: false,
|
|
405
|
-
references: []
|
|
406
|
-
});
|
|
407
|
-
return image;
|
|
408
|
-
},
|
|
409
393
|
async generate(input) {
|
|
410
394
|
const { models: api, backend } = await getClient();
|
|
411
395
|
const text2 = cleanPrompt(input.prompt);
|
|
@@ -483,7 +467,7 @@ const parseGenerateInput = (fields, files) => {
|
|
|
483
467
|
};
|
|
484
468
|
};
|
|
485
469
|
const parseEditInput = (fields, files) => {
|
|
486
|
-
const instruction = clean(str(fields.instruction), INSTRUCTION_LABELS);
|
|
470
|
+
const instruction = clean(str(fields.instruction), INSTRUCTION_LABELS$1);
|
|
487
471
|
const [image] = list(files.image);
|
|
488
472
|
if (!image) throw new InputError("Falta la imagen a editar.");
|
|
489
473
|
const model = editModelFor(str(fields.model) || void 0);
|
|
@@ -501,7 +485,7 @@ const parseEditInput = (fields, files) => {
|
|
|
501
485
|
aspectRatio: model.aspectRatios.includes(str(fields.aspectRatio)) ? str(fields.aspectRatio) : void 0
|
|
502
486
|
};
|
|
503
487
|
};
|
|
504
|
-
const fail$
|
|
488
|
+
const fail$3 = (ctx, status, name2, message) => {
|
|
505
489
|
ctx.status = status;
|
|
506
490
|
ctx.body = { data: null, error: { status, name: name2, message } };
|
|
507
491
|
};
|
|
@@ -511,10 +495,13 @@ const imageStudio = ({ strapi }) => {
|
|
|
511
495
|
try {
|
|
512
496
|
ctx.body = await work();
|
|
513
497
|
} catch (err) {
|
|
514
|
-
if (err instanceof InputError) return fail$
|
|
515
|
-
if (err instanceof BlockedError)
|
|
498
|
+
if (err instanceof InputError) return fail$3(ctx, 400, "BadRequestError", err.message);
|
|
499
|
+
if (err instanceof BlockedError) {
|
|
500
|
+
strapi.log.warn(`[image-studio] bloqueo: ${err.detail ?? err.message}`);
|
|
501
|
+
return fail$3(ctx, 422, "UnprocessableEntityError", err.message);
|
|
502
|
+
}
|
|
516
503
|
strapi.log.error(`[image-studio] ${err instanceof Error ? err.message : String(err)}`);
|
|
517
|
-
return fail$
|
|
504
|
+
return fail$3(ctx, 502, "BadGatewayError", "El servicio de imágenes no respondió. Intenta de nuevo en un momento.");
|
|
518
505
|
}
|
|
519
506
|
};
|
|
520
507
|
return {
|
|
@@ -528,6 +515,454 @@ const imageStudio = ({ strapi }) => {
|
|
|
528
515
|
})
|
|
529
516
|
};
|
|
530
517
|
};
|
|
518
|
+
const MAX_URLS = 3;
|
|
519
|
+
const isHttp = (value) => {
|
|
520
|
+
try {
|
|
521
|
+
const { protocol } = new URL(value);
|
|
522
|
+
return protocol === "http:" || protocol === "https:";
|
|
523
|
+
} catch {
|
|
524
|
+
return false;
|
|
525
|
+
}
|
|
526
|
+
};
|
|
527
|
+
const hostOf = (url) => {
|
|
528
|
+
try {
|
|
529
|
+
return new URL(url).hostname;
|
|
530
|
+
} catch {
|
|
531
|
+
return url;
|
|
532
|
+
}
|
|
533
|
+
};
|
|
534
|
+
const parseReferenceUrls = (input) => {
|
|
535
|
+
const list2 = (Array.isArray(input) ? input : []).filter((v) => typeof v === "string").map((v) => v.trim()).filter(Boolean);
|
|
536
|
+
const unique = [...new Set(list2)];
|
|
537
|
+
if (unique.length > MAX_URLS) throw new InputError(`Puedes dar hasta ${MAX_URLS} URLs de referencia.`);
|
|
538
|
+
const invalid = unique.find((u) => !isHttp(u));
|
|
539
|
+
if (invalid) throw new InputError(`La URL «${invalid}» no es válida.`);
|
|
540
|
+
return unique;
|
|
541
|
+
};
|
|
542
|
+
const sourcesFrom = (urls, res) => {
|
|
543
|
+
const referencias = urls.map((url) => ({ titulo: hostOf(url), url, tipo: "referencia" }));
|
|
544
|
+
const busqueda = (res?.candidates?.[0]?.groundingMetadata?.groundingChunks ?? []).map((chunk) => chunk.web).filter((web) => Boolean(web?.uri)).map((web) => ({ titulo: web.title || hostOf(web.uri), url: web.uri, tipo: "busqueda" }));
|
|
545
|
+
return [...referencias, ...busqueda].filter((f, i, all3) => all3.findIndex((o) => o.url === f.url) === i);
|
|
546
|
+
};
|
|
547
|
+
const ARTICLE_MODEL = "gemini-2.5-pro";
|
|
548
|
+
const ENRICH_MODEL = "gemini-2.5-flash";
|
|
549
|
+
const BASE_PROMPT_MAX = 2e4;
|
|
550
|
+
const INSTRUCTION_LABELS = { label: "Las instrucciones", empty: "Escribe las instrucciones del artículo." };
|
|
551
|
+
const parseCategoria = (input) => {
|
|
552
|
+
const c = input ?? {};
|
|
553
|
+
if (typeof c.id === "string" && c.id.trim()) return { id: c.id.trim() };
|
|
554
|
+
if (typeof c.nueva === "string" && c.nueva.trim()) return { nueva: c.nueva.trim().slice(0, 80) };
|
|
555
|
+
throw new InputError("Elige o escribe una categoría.");
|
|
556
|
+
};
|
|
557
|
+
const parseTemperatura = (input) => {
|
|
558
|
+
const n = typeof input === "number" ? input : typeof input === "string" ? Number(input) : NaN;
|
|
559
|
+
return Number.isFinite(n) ? Math.min(2, Math.max(0, n)) : 0.5;
|
|
560
|
+
};
|
|
561
|
+
const parseArticleInput = (body) => {
|
|
562
|
+
const check = checkPrompt(typeof body.instrucciones === "string" ? body.instrucciones : "", INSTRUCTION_LABELS);
|
|
563
|
+
if ("error" in check) throw new InputError(check.error);
|
|
564
|
+
return {
|
|
565
|
+
titulo: typeof body.titulo === "string" ? body.titulo.trim().slice(0, 200) : "",
|
|
566
|
+
categoria: parseCategoria(body.categoria),
|
|
567
|
+
temperatura: parseTemperatura(body.temperatura),
|
|
568
|
+
instrucciones: check.text,
|
|
569
|
+
urls: parseReferenceUrls(body.urls),
|
|
570
|
+
busqueda: body.busqueda === true || body.busqueda === "true",
|
|
571
|
+
usarPromptBase: !(body.usarPromptBase === false || body.usarPromptBase === "false"),
|
|
572
|
+
...optionalBase(body.promptBase)
|
|
573
|
+
};
|
|
574
|
+
};
|
|
575
|
+
const optionalBase = (input) => {
|
|
576
|
+
const text2 = typeof input === "string" ? input.trim() : "";
|
|
577
|
+
if (!text2) return {};
|
|
578
|
+
if (text2.length > BASE_PROMPT_MAX) throw new InputError(`El prompt base puede tener hasta ${BASE_PROMPT_MAX} caracteres.`);
|
|
579
|
+
return { promptBase: text2 };
|
|
580
|
+
};
|
|
581
|
+
const parseBasePrompt = (input) => {
|
|
582
|
+
const base = optionalBase(input).promptBase;
|
|
583
|
+
if (!base) throw new InputError("Escribe el prompt base.");
|
|
584
|
+
return base;
|
|
585
|
+
};
|
|
586
|
+
const researchTools = ({ urls, busqueda }) => [
|
|
587
|
+
...busqueda ? [{ googleSearch: {} }] : [],
|
|
588
|
+
...urls.length ? [{ urlContext: {} }] : []
|
|
589
|
+
];
|
|
590
|
+
const temaLines = ({ titulo, categoria, instrucciones }) => [
|
|
591
|
+
titulo ? `- Título sugerido: "${titulo}"` : "",
|
|
592
|
+
categoria ? `- Categoría o tópico: "${categoria}"` : "",
|
|
593
|
+
instrucciones ? `- Instrucciones: "${instrucciones}"` : ""
|
|
594
|
+
].filter(Boolean).join("\n");
|
|
595
|
+
const researchPrompt = (tema) => `
|
|
596
|
+
Eres analista de investigación de InterWare. Reúne la información que respaldará una columna de opinión para
|
|
597
|
+
directores de TI, operaciones y finanzas.
|
|
598
|
+
|
|
599
|
+
Tema:
|
|
600
|
+
${temaLines(tema)}
|
|
601
|
+
${tema.urls.length ? `
|
|
602
|
+
Lee y usa como referencia principal estas páginas:
|
|
603
|
+
${tema.urls.map((u) => `- ${u}`).join("\n")}
|
|
604
|
+
` : ""}
|
|
605
|
+
Entrega notas en español, concisas: hechos, cifras con su fuente, tendencias y ejemplos relevantes. No escribas el
|
|
606
|
+
artículo. Si un dato no está respaldado por una fuente, no lo incluyas.
|
|
607
|
+
`;
|
|
608
|
+
const DEFAULT_BASE_PROMPT = `# ROL Y PERSONA (EL FONDO)
|
|
609
|
+
Actúa como un Estratega Tecnológico de nivel C-Level y Arquitecto de Negocios de élite para 'InterWare'. Eres un columnista de opinión experto, escribiendo para una audiencia exclusiva de tomadores de decisión: Directores de TI (CTOs), Directores de Operaciones (COOs) y Directores Financieros (CFOs/FinOps).
|
|
610
|
+
No eres un redactor de marketing ni un vendedor de software; eres un consultor de alto nivel que diagnostica problemas sistémicos complejos y ofrece perspectivas de valor incalculable. Tu objetivo es hacer que el lector cuestione la madurez de su propia infraestructura.
|
|
611
|
+
|
|
612
|
+
# FILOSOFÍA DE MARCA: "ORQUESTACIÓN LATENTE"
|
|
613
|
+
Toda tu narrativa debe estar impregnada de nuestra visión de negocio: "Evolución por Continuidad"
|
|
614
|
+
- InterWare no inventa necesidades ni vende catálogos de servicios; InterWare resuelve la complejidad operativa con responsabilidad
|
|
615
|
+
- Somos el orquestador invisible que garantiza que ecosistemas heterogéneos trabajen en perfecta armonía.
|
|
616
|
+
- Tu ancla absoluta de confianza y diferenciador es: "El código tiene alma". Esto significa que no entregamos simple software; entregamos sistemas de misión crítica que no fallan, respaldados por equipos humanos de excelencia.
|
|
617
|
+
- Tu respaldo de autoridad (menciónelo sutilmente como validación, nunca como presunción): Nos avalan casi 30 años de historia, más de 9,000 proyectos exitosos, primer centro autorizado de Java en LATAM y más de 25 años como Partners Gold de IBM. Nuestra prueba de lealtad es que promediamos relaciones de más de 10 años con nuestros clientes.
|
|
618
|
+
|
|
619
|
+
# REGLAS DE TONO Y LÉXICO (LA FORMA)
|
|
620
|
+
1. El Tono: Profundamente autoritario, frío, elegante, quirúrgico y sofisticado. Escribe con la certeza de quien ha visto todas las fallas posibles en la industria y sabe cómo prevenirlas.
|
|
621
|
+
2. Vocabulario Obligatorio (Usa al menos 4 de forma natural): Orquestación, resiliencia, fricción operativa, deuda técnica, telemetría, anticipación, interoperabilidad, misión crítica, observabilidad profunda, ecosistemas híbridos, primitivas de orquestación.
|
|
622
|
+
3. Prohibición de Léxico Barato (Zero-Clutter Text): PROHIBIDO usar palabras literales o burdas como "fierros", "cables", "hardware", "servidores físicos" o "computadoras". En su lugar, usa "nodos", "infraestructura", "arquitecturas distribuidas", "activos digitales".
|
|
623
|
+
|
|
624
|
+
# RESTRICCIONES ESTRICTAS ANTI-IA (EL ESTILO)
|
|
625
|
+
- Cero Clichés de Marketing: NUNCA uses frases trilladas como "en el mundo digital de hoy", "en la era actual", "desata el poder", "revolucionar el mercado", "lleva tu empresa al siguiente nivel" o "somos tu mejor opción".
|
|
626
|
+
- Cero Estructuras Robóticas: Evita transiciones predecibles como "En resumen", "En conclusión", "En primer lugar", "En segundo lugar".
|
|
627
|
+
- Fluidez Orgánica: No abuses de las listas de viñetas (bullets). Si debes listar beneficios, intégralos en la prosa de manera fluida o usa negritas sutiles dentro de un párrafo.
|
|
628
|
+
- Espacio Negativo Textual: Los tomadores de decisión no leen bloques densos de texto. Usa párrafos cortos (máximo 3 o 4 líneas). El texto debe "respirar".
|
|
629
|
+
|
|
630
|
+
# INSTRUCCIÓN DE EJECUCIÓN: LA NARRATIVA DE LA COLUMNA
|
|
631
|
+
Redacta una columna de opinión profunda y analítica sobre el tema de la sección «TEMA DEL ARTÍCULO».
|
|
632
|
+
|
|
633
|
+
Tu artículo debe seguir este arco narrativo impecable (entre 600 y 800 palabras):
|
|
634
|
+
|
|
635
|
+
1. EL TÍTULO ABSTRACTO: Crea un título de menos de 10 palabras que evoque un dolor de negocio o una revelación financiera, no una característica de software. Debe sonar a un artículo de *Harvard Business Review*.
|
|
636
|
+
2. LA FRICCIÓN (El Diagnóstico Crudo): Abre el artículo sin introducciones banales. Golpea directamente diagnosticando el dolor del negocio (ej. la pérdida de rentabilidad por cuellos de botella operativos o el riesgo inminente de sistemas legados que nadie sabe mantener). Haz que el lector sienta que estás describiendo su empresa.
|
|
637
|
+
3. LA ORQUESTACIÓN (El Núcleo): Desarrolla tu argumento explicando cómo una arquitectura inteligente (ya sea a través de microservicios, DevSecOps, automatización inteligente de negocio, o monitoreo sintético con herramientas como iwRobot) resuelve este problema de raíz. Transmite la idea de que la tecnología debe ser un habilitador transparente, no una carga.
|
|
638
|
+
4. EL IMPACTO LATENTE: Teje dentro de la prosa (sin usar viñetas obvias de IA) los tres impactos estratégicos del tema. Habla de cómo se logra la Resiliencia, la Fluidez operativa, la Eficiencia financiera o la Anticipación ante el riesgo.
|
|
639
|
+
5. EL CIERRE SUTIL (El CTA Elegante): En lugar de un llamado a la acción desesperado de ventas, cierra con una reflexión ejecutiva o una pregunta abierta que invite al lector a auditar mentalmente la madurez de su propia infraestructura. Una despedida que demuestre que, para orquestar la complejidad, se requiere la maestría de tres décadas.
|
|
640
|
+
|
|
641
|
+
Recuerda: Eres un experto hablando con otro experto. Sé denso en valor y conciso en palabras`;
|
|
642
|
+
const investigacionBlock = (investigacion) => investigacion ? `
|
|
643
|
+
|
|
644
|
+
# INVESTIGACIÓN DE APOYO
|
|
645
|
+
Usa estos datos como base factual. No inventes cifras, nombres ni estudios que no aparezcan aquí:
|
|
646
|
+
${investigacion}` : "";
|
|
647
|
+
const articlePrompt = ({ base = DEFAULT_BASE_PROMPT, investigacion, ...tema }) => `${base}
|
|
648
|
+
|
|
649
|
+
# TEMA DEL ARTÍCULO
|
|
650
|
+
${temaLines(tema)}${investigacionBlock(investigacion)}`;
|
|
651
|
+
const rawPrompt = ({ instrucciones, investigacion }) => `${instrucciones}${investigacionBlock(investigacion)}`;
|
|
652
|
+
const enrichPrompt = (texto) => `
|
|
653
|
+
Eres editor de contenidos de InterWare, empresa mexicana de tecnología. Convierte esta idea en instrucciones claras
|
|
654
|
+
para redactar un artículo de blog.
|
|
655
|
+
|
|
656
|
+
Idea: "${texto}"
|
|
657
|
+
|
|
658
|
+
Responde solo con las instrucciones, en español y en texto plano, con estas líneas:
|
|
659
|
+
Tema: …
|
|
660
|
+
Público: …
|
|
661
|
+
Cubrir: …
|
|
662
|
+
Tono: …
|
|
663
|
+
Cierre: …
|
|
664
|
+
Máximo 1500 caracteres. Sin comillas ni Markdown.
|
|
665
|
+
`;
|
|
666
|
+
const ARTICLE_SCHEMA = {
|
|
667
|
+
type: "object",
|
|
668
|
+
required: ["titulo", "descripcion", "content", "seo", "minute_read"],
|
|
669
|
+
properties: {
|
|
670
|
+
seo: {
|
|
671
|
+
type: "object",
|
|
672
|
+
required: ["metaTitle", "metaDescription", "metadata"],
|
|
673
|
+
properties: {
|
|
674
|
+
metaTitle: { type: "string" },
|
|
675
|
+
metaDescription: { type: "string" },
|
|
676
|
+
metadata: {
|
|
677
|
+
type: "array",
|
|
678
|
+
items: {
|
|
679
|
+
type: "object",
|
|
680
|
+
required: ["name", "content"],
|
|
681
|
+
properties: { name: { type: "string" }, content: { type: "string" } }
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
},
|
|
686
|
+
titulo: { type: "string", minLength: 40, maxLength: 70, description: "Título del artículo" },
|
|
687
|
+
descripcion: { type: "string", minLength: 80, maxLength: 160, description: "Descripción breve del artículo" },
|
|
688
|
+
slug: {
|
|
689
|
+
type: "string",
|
|
690
|
+
minLength: 80,
|
|
691
|
+
maxLength: 160,
|
|
692
|
+
description: "URL-friendly basado en el título (ej: estrategias-migracion-nube)"
|
|
693
|
+
},
|
|
694
|
+
content: { type: "string", description: "Contenido HTML compatible con CKEditor" },
|
|
695
|
+
minute_read: {
|
|
696
|
+
type: "integer",
|
|
697
|
+
minimum: 1,
|
|
698
|
+
maximum: 30,
|
|
699
|
+
description: "Tiempo de lectura calculado usando 200 palabras por minuto"
|
|
700
|
+
},
|
|
701
|
+
keywords: {
|
|
702
|
+
type: "array",
|
|
703
|
+
minItems: 3,
|
|
704
|
+
maxItems: 5,
|
|
705
|
+
items: { type: "object", required: ["name"], properties: { name: { type: "string" } } },
|
|
706
|
+
description: "Hash tags y palabras clave para la publicación en LinkedIn y Facebook"
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
};
|
|
710
|
+
const ZONA = "America/Mexico_City";
|
|
711
|
+
const UN_ANIO_MS = 365 * 24 * 60 * 60 * 1e3;
|
|
712
|
+
const fechaEnMexico = (date) => new Intl.DateTimeFormat("en-CA", { timeZone: ZONA, year: "numeric", month: "2-digit", day: "2-digit" }).format(date);
|
|
713
|
+
const parseScheduleAt = (input, now) => {
|
|
714
|
+
const date = typeof input === "string" ? new Date(input) : /* @__PURE__ */ new Date(NaN);
|
|
715
|
+
if (Number.isNaN(date.getTime())) throw new InputError("La fecha y hora no son válidas.");
|
|
716
|
+
if (date.getTime() <= now.getTime()) throw new InputError("Elige una fecha y hora futuras.");
|
|
717
|
+
if (date.getTime() - now.getTime() > UN_ANIO_MS) throw new InputError("Programa con menos de un año de anticipación.");
|
|
718
|
+
return date;
|
|
719
|
+
};
|
|
720
|
+
const estadoDe = ({ publicado, programada }) => publicado ? "publicado" : programada ? "programado" : "borrador";
|
|
721
|
+
class NotFoundError extends Error {
|
|
722
|
+
}
|
|
723
|
+
const memoryStore = () => {
|
|
724
|
+
let value = null;
|
|
725
|
+
return {
|
|
726
|
+
get: async () => value,
|
|
727
|
+
set: async (v) => {
|
|
728
|
+
value = v;
|
|
729
|
+
},
|
|
730
|
+
remove: async () => {
|
|
731
|
+
value = null;
|
|
732
|
+
}
|
|
733
|
+
};
|
|
734
|
+
};
|
|
735
|
+
const ROW_FIELDS = ["titulo", "fecha_publicacion", "publicacion_programada", "linkedInPostId", "facebookPostId"];
|
|
736
|
+
const DETAIL_POPULATE = { image: true, categoria: true, seo: true, keywords: true };
|
|
737
|
+
const silentLog = { info: () => void 0, warn: () => void 0, error: () => void 0 };
|
|
738
|
+
const slugify = (text2) => text2.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
739
|
+
const textOf = (res) => (res.text ?? res.candidates?.[0]?.content?.parts?.[0]?.text ?? "").trim();
|
|
740
|
+
const toRow = (d, publicado) => ({
|
|
741
|
+
documentId: d.documentId,
|
|
742
|
+
titulo: d.titulo ?? "",
|
|
743
|
+
categoria: d.categoria?.categoria ?? null,
|
|
744
|
+
estado: estadoDe({ publicado, programada: d.publicacion_programada }),
|
|
745
|
+
imagen: Boolean(d.image),
|
|
746
|
+
fechaPublicacion: d.fecha_publicacion ?? null,
|
|
747
|
+
programadaPara: d.publicacion_programada ?? null,
|
|
748
|
+
linkedInPostId: d.linkedInPostId ?? null,
|
|
749
|
+
facebookPostId: d.facebookPostId ?? null
|
|
750
|
+
});
|
|
751
|
+
const toDetail = (d, publicado) => ({
|
|
752
|
+
...toRow(d, publicado),
|
|
753
|
+
descripcion: d.descripcion ?? "",
|
|
754
|
+
content: d.content ?? "",
|
|
755
|
+
minuteRead: d.minute_read ?? null,
|
|
756
|
+
slug: d.slug ?? null,
|
|
757
|
+
imageUrl: d.image ? d.image.formats?.small?.url ?? d.image.formats?.thumbnail?.url ?? d.image.url ?? null : null,
|
|
758
|
+
imageName: d.image?.name ?? null,
|
|
759
|
+
seo: d.seo ? { metaTitle: d.seo.metaTitle, metaDescription: d.seo.metaDescription } : null,
|
|
760
|
+
keywords: (d.keywords ?? []).map((k) => k.name ?? "").filter(Boolean),
|
|
761
|
+
fuentes: Array.isArray(d.fuentes) ? d.fuentes : []
|
|
762
|
+
});
|
|
763
|
+
const createArticles = ({ articulos, categorias, getModels, now = () => /* @__PURE__ */ new Date(), log = silentLog, promptStore = memoryStore() }) => {
|
|
764
|
+
const draftOf = async (documentId, populate = DETAIL_POPULATE) => {
|
|
765
|
+
const d = await articulos.findOne({ documentId, status: "draft", populate });
|
|
766
|
+
if (!d) throw new NotFoundError("El artículo no existe.");
|
|
767
|
+
return d;
|
|
768
|
+
};
|
|
769
|
+
const isPublished = async (documentId) => Boolean(await articulos.findOne({ documentId, status: "published", fields: ["titulo"] }));
|
|
770
|
+
const detail = async (documentId) => {
|
|
771
|
+
const d = await draftOf(documentId);
|
|
772
|
+
return toDetail(d, await isPublished(documentId));
|
|
773
|
+
};
|
|
774
|
+
const resolveCategoria = async (input) => {
|
|
775
|
+
if ("id" in input) {
|
|
776
|
+
const c = await categorias.findOne({ documentId: input.id });
|
|
777
|
+
if (!c) throw new InputError("La categoría elegida ya no existe.");
|
|
778
|
+
return { id: c.documentId, nombre: c.categoria };
|
|
779
|
+
}
|
|
780
|
+
const found = await categorias.findFirst({ filters: { categoria: { $eqi: input.nueva } } });
|
|
781
|
+
if (found) return { id: found.documentId, nombre: found.categoria };
|
|
782
|
+
const created = await categorias.create({ data: { categoria: input.nueva, slug: slugify(input.nueva) } });
|
|
783
|
+
return { id: created.documentId, nombre: input.nueva };
|
|
784
|
+
};
|
|
785
|
+
const basePrompt = async () => {
|
|
786
|
+
const guardado = await promptStore.get();
|
|
787
|
+
return { prompt: guardado || DEFAULT_BASE_PROMPT, personalizado: Boolean(guardado) };
|
|
788
|
+
};
|
|
789
|
+
return {
|
|
790
|
+
basePrompt,
|
|
791
|
+
async saveBasePrompt(prompt) {
|
|
792
|
+
await promptStore.set(prompt);
|
|
793
|
+
return basePrompt();
|
|
794
|
+
},
|
|
795
|
+
async resetBasePrompt() {
|
|
796
|
+
await promptStore.remove();
|
|
797
|
+
return basePrompt();
|
|
798
|
+
},
|
|
799
|
+
async list() {
|
|
800
|
+
const [drafts, published] = await Promise.all([
|
|
801
|
+
articulos.findMany({ status: "draft", fields: ROW_FIELDS, populate: { image: { fields: ["id"] }, categoria: { fields: ["categoria"] } }, sort: ["createdAt:desc"] }),
|
|
802
|
+
articulos.findMany({ status: "published", fields: ["titulo"] })
|
|
803
|
+
]);
|
|
804
|
+
const publicados = new Set(published.map((p) => p.documentId));
|
|
805
|
+
return { articles: drafts.map((d) => toRow(d, publicados.has(d.documentId))) };
|
|
806
|
+
},
|
|
807
|
+
detail,
|
|
808
|
+
async generate(input) {
|
|
809
|
+
const categoria = await resolveCategoria(input.categoria);
|
|
810
|
+
const models = await getModels();
|
|
811
|
+
const tema = { titulo: input.titulo, categoria: categoria.nombre, instrucciones: input.instrucciones };
|
|
812
|
+
const tools = researchTools(input);
|
|
813
|
+
let investigacion;
|
|
814
|
+
let fuentes = [];
|
|
815
|
+
if (tools.length) {
|
|
816
|
+
const research = await models.generateContent({ model: ARTICLE_MODEL, contents: researchPrompt({ ...tema, urls: input.urls }), config: { tools, temperature: 0.2 } });
|
|
817
|
+
investigacion = textOf(research) || void 0;
|
|
818
|
+
fuentes = sourcesFrom(input.urls, research);
|
|
819
|
+
}
|
|
820
|
+
const contents = input.usarPromptBase === false ? rawPrompt({ instrucciones: input.instrucciones, investigacion }) : articlePrompt({ ...tema, investigacion, base: input.promptBase ?? (await basePrompt()).prompt });
|
|
821
|
+
const res = await models.generateContent({
|
|
822
|
+
model: ARTICLE_MODEL,
|
|
823
|
+
contents,
|
|
824
|
+
config: { responseMimeType: "application/json", temperature: input.temperatura, responseSchema: ARTICLE_SCHEMA }
|
|
825
|
+
});
|
|
826
|
+
let parsed;
|
|
827
|
+
try {
|
|
828
|
+
parsed = JSON.parse(textOf(res));
|
|
829
|
+
} catch {
|
|
830
|
+
throw new Error("La respuesta del modelo no es un JSON válido.");
|
|
831
|
+
}
|
|
832
|
+
const created = await articulos.create({
|
|
833
|
+
data: {
|
|
834
|
+
titulo: parsed.titulo,
|
|
835
|
+
descripcion: parsed.descripcion,
|
|
836
|
+
content: parsed.content,
|
|
837
|
+
seo: parsed.seo,
|
|
838
|
+
minute_read: parsed.minute_read,
|
|
839
|
+
slug: parsed.slug,
|
|
840
|
+
keywords: parsed.keywords,
|
|
841
|
+
categoria: categoria.id,
|
|
842
|
+
image: null,
|
|
843
|
+
fuentes
|
|
844
|
+
},
|
|
845
|
+
status: "draft"
|
|
846
|
+
});
|
|
847
|
+
return { documentId: created.documentId };
|
|
848
|
+
},
|
|
849
|
+
async enrich(texto) {
|
|
850
|
+
const models = await getModels();
|
|
851
|
+
const res = await models.generateContent({ model: ENRICH_MODEL, contents: enrichPrompt(texto) });
|
|
852
|
+
const out = textOf(res).replace(/^["'«“]+|["'»”]+$/g, "").trim();
|
|
853
|
+
if (!out) throw new InputError("No se pudieron enriquecer las instrucciones. Intenta de nuevo.");
|
|
854
|
+
return out.slice(0, 2e3);
|
|
855
|
+
},
|
|
856
|
+
async setImage(documentId, fileId) {
|
|
857
|
+
const id = typeof fileId === "number" ? fileId : Number(fileId);
|
|
858
|
+
if (!Number.isInteger(id) || id <= 0) throw new InputError("Elige una imagen válida.");
|
|
859
|
+
await draftOf(documentId, {});
|
|
860
|
+
await articulos.update({ documentId, data: { image: id } });
|
|
861
|
+
if (await isPublished(documentId)) await articulos.publish({ documentId });
|
|
862
|
+
return detail(documentId);
|
|
863
|
+
},
|
|
864
|
+
async publish(documentId) {
|
|
865
|
+
const d = await draftOf(documentId);
|
|
866
|
+
if (!d.image) throw new InputError("Elige una imagen antes de publicar.");
|
|
867
|
+
await articulos.update({ documentId, data: { fecha_publicacion: fechaEnMexico(now()), publicacion_programada: null } });
|
|
868
|
+
await articulos.publish({ documentId });
|
|
869
|
+
return detail(documentId);
|
|
870
|
+
},
|
|
871
|
+
async schedule(documentId, at) {
|
|
872
|
+
const date = parseScheduleAt(at, now());
|
|
873
|
+
const d = await draftOf(documentId);
|
|
874
|
+
if (!d.image) throw new InputError("Elige una imagen antes de programar.");
|
|
875
|
+
if (await isPublished(documentId)) throw new InputError("El artículo ya está publicado.");
|
|
876
|
+
await articulos.update({ documentId, data: { publicacion_programada: date.toISOString(), fecha_publicacion: fechaEnMexico(date) } });
|
|
877
|
+
return detail(documentId);
|
|
878
|
+
},
|
|
879
|
+
async unschedule(documentId) {
|
|
880
|
+
await draftOf(documentId, {});
|
|
881
|
+
await articulos.update({ documentId, data: { publicacion_programada: null, fecha_publicacion: null } });
|
|
882
|
+
return detail(documentId);
|
|
883
|
+
},
|
|
884
|
+
/** D4: publica los borradores con programación vencida. Devuelve cuántos publicó. */
|
|
885
|
+
async publishDue() {
|
|
886
|
+
const due = await articulos.findMany({
|
|
887
|
+
status: "draft",
|
|
888
|
+
filters: { publicacion_programada: { $notNull: true, $lte: now().toISOString() } },
|
|
889
|
+
fields: ["publicacion_programada"],
|
|
890
|
+
populate: { image: { fields: ["id"] } }
|
|
891
|
+
});
|
|
892
|
+
let count = 0;
|
|
893
|
+
for (const d of due) {
|
|
894
|
+
if (!d.image) {
|
|
895
|
+
log.warn(`[articles] ${d.documentId} está programado pero no tiene imagen; no se publicó.`);
|
|
896
|
+
continue;
|
|
897
|
+
}
|
|
898
|
+
try {
|
|
899
|
+
await articulos.update({ documentId: d.documentId, data: { publicacion_programada: null } });
|
|
900
|
+
await articulos.publish({ documentId: d.documentId });
|
|
901
|
+
count += 1;
|
|
902
|
+
} catch (err) {
|
|
903
|
+
log.error(`[articles] no se pudo publicar ${d.documentId}: ${err instanceof Error ? err.message : String(err)}`);
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
if (count) log.info(`[articles] ${count} artículo(s) programado(s) publicados.`);
|
|
907
|
+
return count;
|
|
908
|
+
}
|
|
909
|
+
};
|
|
910
|
+
};
|
|
911
|
+
const articles$1 = ({ strapi }) => createArticles({
|
|
912
|
+
articulos: strapi.documents("api::articulo.articulo"),
|
|
913
|
+
categorias: strapi.documents("api::categoria.categoria"),
|
|
914
|
+
getModels: async () => (await strapi.plugin("strapi-content-generator-gemini").service("service").geminiClient()).ai.models,
|
|
915
|
+
log: strapi.log,
|
|
916
|
+
promptStore: /* @__PURE__ */ (() => {
|
|
917
|
+
const store = () => strapi.store({ type: "plugin", name: "strapi-content-generator-gemini" });
|
|
918
|
+
const key = "ARTICLE_BASE_PROMPT";
|
|
919
|
+
return {
|
|
920
|
+
get: async () => await store().get({ key }) ?? null,
|
|
921
|
+
set: async (value) => {
|
|
922
|
+
await store().set({ key, value });
|
|
923
|
+
},
|
|
924
|
+
remove: async () => {
|
|
925
|
+
await store().delete({ key });
|
|
926
|
+
}
|
|
927
|
+
};
|
|
928
|
+
})()
|
|
929
|
+
});
|
|
930
|
+
const fail$2 = (ctx, status, name2, message) => {
|
|
931
|
+
ctx.status = status;
|
|
932
|
+
ctx.body = { data: null, error: { status, name: name2, message } };
|
|
933
|
+
};
|
|
934
|
+
const articles = ({ strapi }) => {
|
|
935
|
+
const articles2 = () => strapi.plugin("strapi-content-generator-gemini").service("articles");
|
|
936
|
+
const id = (ctx) => ctx.params?.documentId ?? "";
|
|
937
|
+
const run = async (ctx, work) => {
|
|
938
|
+
try {
|
|
939
|
+
ctx.body = await work();
|
|
940
|
+
} catch (err) {
|
|
941
|
+
if (err instanceof InputError) return fail$2(ctx, 400, "BadRequestError", err.message);
|
|
942
|
+
if (err instanceof NotFoundError) return fail$2(ctx, 404, "NotFoundError", err.message);
|
|
943
|
+
if (err instanceof Error && err.name === "ValidationError") return fail$2(ctx, 400, "ValidationError", err.message);
|
|
944
|
+
strapi.log.error(`[articles] ${err instanceof Error ? err.message : String(err)}`);
|
|
945
|
+
return fail$2(ctx, 502, "BadGatewayError", "El servicio de generación no respondió. Intenta de nuevo en un momento.");
|
|
946
|
+
}
|
|
947
|
+
};
|
|
948
|
+
return {
|
|
949
|
+
list: (ctx) => run(ctx, () => articles2().list()),
|
|
950
|
+
detail: (ctx) => run(ctx, () => articles2().detail(id(ctx))),
|
|
951
|
+
generate: (ctx) => run(ctx, () => articles2().generate(parseArticleInput(ctx.request.body ?? {}))),
|
|
952
|
+
enrich: (ctx) => run(ctx, async () => {
|
|
953
|
+
const raw = typeof ctx.request.body?.texto === "string" ? ctx.request.body.texto : "";
|
|
954
|
+
const texto = clean(raw, { label: "La idea", empty: "Escribe una idea para enriquecer." });
|
|
955
|
+
return { texto: await articles2().enrich(texto) };
|
|
956
|
+
}),
|
|
957
|
+
basePrompt: (ctx) => run(ctx, () => articles2().basePrompt()),
|
|
958
|
+
saveBasePrompt: (ctx) => run(ctx, () => articles2().saveBasePrompt(parseBasePrompt(ctx.request.body?.prompt))),
|
|
959
|
+
resetBasePrompt: (ctx) => run(ctx, () => articles2().resetBasePrompt()),
|
|
960
|
+
setImage: (ctx) => run(ctx, () => articles2().setImage(id(ctx), ctx.request.body?.fileId)),
|
|
961
|
+
publish: (ctx) => run(ctx, () => articles2().publish(id(ctx))),
|
|
962
|
+
schedule: (ctx) => run(ctx, () => articles2().schedule(id(ctx), ctx.request.body?.at)),
|
|
963
|
+
unschedule: (ctx) => run(ctx, () => articles2().unschedule(id(ctx)))
|
|
964
|
+
};
|
|
965
|
+
};
|
|
531
966
|
const NAVY = "#1F2A44";
|
|
532
967
|
const RED = "#E4002B";
|
|
533
968
|
const TEAL = "#00C7B1";
|
|
@@ -891,7 +1326,8 @@ const controllers = {
|
|
|
891
1326
|
controller,
|
|
892
1327
|
config: config$1,
|
|
893
1328
|
"image-studio": imageStudio,
|
|
894
|
-
templates
|
|
1329
|
+
templates,
|
|
1330
|
+
articles
|
|
895
1331
|
};
|
|
896
1332
|
const middlewares = {};
|
|
897
1333
|
const policies = {};
|
|
@@ -905,12 +1341,20 @@ const ADMIN_ACCESS_POLICIES = [
|
|
|
905
1341
|
];
|
|
906
1342
|
const config = { policies: ADMIN_ACCESS_POLICIES };
|
|
907
1343
|
const admin = [
|
|
908
|
-
{ method: "GET", path: "/
|
|
1344
|
+
{ method: "GET", path: "/articles", handler: "articles.list", config },
|
|
1345
|
+
// Las rutas fijas van antes de `/articles/:documentId` para que no las tome como id.
|
|
1346
|
+
{ method: "POST", path: "/articles/generate", handler: "articles.generate", config },
|
|
1347
|
+
{ method: "POST", path: "/articles/enrich", handler: "articles.enrich", config },
|
|
1348
|
+
{ method: "GET", path: "/articles/base-prompt", handler: "articles.basePrompt", config },
|
|
1349
|
+
{ method: "PUT", path: "/articles/base-prompt", handler: "articles.saveBasePrompt", config },
|
|
1350
|
+
{ method: "DELETE", path: "/articles/base-prompt", handler: "articles.resetBasePrompt", config },
|
|
1351
|
+
{ method: "GET", path: "/articles/:documentId", handler: "articles.detail", config },
|
|
1352
|
+
{ method: "PUT", path: "/articles/:documentId/image", handler: "articles.setImage", config },
|
|
1353
|
+
{ method: "POST", path: "/articles/:documentId/publish", handler: "articles.publish", config },
|
|
1354
|
+
{ method: "POST", path: "/articles/:documentId/schedule", handler: "articles.schedule", config },
|
|
1355
|
+
{ method: "DELETE", path: "/articles/:documentId/schedule", handler: "articles.unschedule", config },
|
|
909
1356
|
{ method: "GET", path: "/categories", handler: "controller.getCategories", config },
|
|
910
|
-
{ method: "GET", path: "/users", handler: "controller.getUsers", config },
|
|
911
1357
|
{ method: "POST", path: "/download-file", handler: "controller.downloadFile", config },
|
|
912
|
-
{ method: "POST", path: "/generate-article", handler: "controller.generateArticle", config },
|
|
913
|
-
{ method: "POST", path: "/generate-image", handler: "controller.generateImageForArticle", config },
|
|
914
1358
|
{ method: "GET", path: "/image-studio/models", handler: "image-studio.models", config },
|
|
915
1359
|
{ method: "POST", path: "/image-studio/generate", handler: "image-studio.generate", config },
|
|
916
1360
|
{ method: "POST", path: "/image-studio/edit", handler: "image-studio.edit", config },
|
|
@@ -4189,6 +4633,11 @@ const createGeminiClient = ({ serviceAccount, apiKey, allowVertex = true }, Ctor
|
|
|
4189
4633
|
allowVertex ? "Configura la cuenta de servicio de Vertex AI o la llave de Gemini en Ajustes del plugin." : "El video necesita la llave de Gemini en Ajustes del plugin."
|
|
4190
4634
|
);
|
|
4191
4635
|
};
|
|
4636
|
+
const postData = (article) => ({
|
|
4637
|
+
titulo: article.titulo ?? "",
|
|
4638
|
+
descripcion: article.descripcion ?? "",
|
|
4639
|
+
keywords: (Array.isArray(article.keywords) ? article.keywords : []).map((k) => k?.name ?? "")
|
|
4640
|
+
});
|
|
4192
4641
|
const service = ({ strapi }) => {
|
|
4193
4642
|
return {
|
|
4194
4643
|
// ───────────────────────────────
|
|
@@ -4208,15 +4657,9 @@ const service = ({ strapi }) => {
|
|
|
4208
4657
|
async geminiConfig() {
|
|
4209
4658
|
return (await this.geminiClient()).ai;
|
|
4210
4659
|
},
|
|
4211
|
-
async getArticulos(sanitizedQueryParams) {
|
|
4212
|
-
return await strapi.entityService.findMany("api::articulo.articulo", sanitizedQueryParams);
|
|
4213
|
-
},
|
|
4214
4660
|
async getCategorias(sanitizedQueryParams) {
|
|
4215
4661
|
return await strapi.entityService.findMany("api::categoria.categoria", sanitizedQueryParams);
|
|
4216
4662
|
},
|
|
4217
|
-
async getUsuarios(sanitizedQueryParams) {
|
|
4218
|
-
return await strapi.documents("plugin::users-permissions.user").findMany(sanitizedQueryParams);
|
|
4219
|
-
},
|
|
4220
4663
|
// ───────────────────────────────
|
|
4221
4664
|
// 📥 Proxy File Download (bypasses browser CORS)
|
|
4222
4665
|
// ───────────────────────────────
|
|
@@ -4286,232 +4729,6 @@ const service = ({ strapi }) => {
|
|
|
4286
4729
|
}
|
|
4287
4730
|
return uploadedFiles[0];
|
|
4288
4731
|
},
|
|
4289
|
-
// ───────────────────────────────
|
|
4290
|
-
// 🧠 Generate Article with AI
|
|
4291
|
-
// ───────────────────────────────
|
|
4292
|
-
async generateArticle(ctx) {
|
|
4293
|
-
const { titulo, categoria, autor, temperatura = 0.5, instrucciones } = ctx.request.body;
|
|
4294
|
-
const promptArticulo = `
|
|
4295
|
-
# ROL Y PERSONA (EL FONDO)
|
|
4296
|
-
Actúa como un Estratega Tecnológico de nivel C-Level y Arquitecto de Negocios de élite para 'InterWare'. Eres un columnista de opinión experto, escribiendo para una audiencia exclusiva de tomadores de decisión: Directores de TI (CTOs), Directores de Operaciones (COOs) y Directores Financieros (CFOs/FinOps).
|
|
4297
|
-
No eres un redactor de marketing ni un vendedor de software; eres un consultor de alto nivel que diagnostica problemas sistémicos complejos y ofrece perspectivas de valor incalculable. Tu objetivo es hacer que el lector cuestione la madurez de su propia infraestructura.
|
|
4298
|
-
|
|
4299
|
-
# FILOSOFÍA DE MARCA: "ORQUESTACIÓN LATENTE"
|
|
4300
|
-
Toda tu narrativa debe estar impregnada de nuestra visión de negocio: "Evolución por Continuidad"
|
|
4301
|
-
- InterWare no inventa necesidades ni vende catálogos de servicios; InterWare resuelve la complejidad operativa con responsabilidad
|
|
4302
|
-
- Somos el orquestador invisible que garantiza que ecosistemas heterogéneos trabajen en perfecta armonía.
|
|
4303
|
-
- Tu ancla absoluta de confianza y diferenciador es: "El código tiene alma". Esto significa que no entregamos simple software; entregamos sistemas de misión crítica que no fallan, respaldados por equipos humanos de excelencia.
|
|
4304
|
-
- Tu respaldo de autoridad (menciónelo sutilmente como validación, nunca como presunción): Nos avalan casi 30 años de historia, más de 9,000 proyectos exitosos, primer centro autorizado de Java en LATAM y más de 25 años como Partners Gold de IBM. Nuestra prueba de lealtad es que promediamos relaciones de más de 10 años con nuestros clientes.
|
|
4305
|
-
|
|
4306
|
-
# REGLAS DE TONO Y LÉXICO (LA FORMA)
|
|
4307
|
-
1. El Tono: Profundamente autoritario, frío, elegante, quirúrgico y sofisticado. Escribe con la certeza de quien ha visto todas las fallas posibles en la industria y sabe cómo prevenirlas.
|
|
4308
|
-
2. Vocabulario Obligatorio (Usa al menos 4 de forma natural): Orquestación, resiliencia, fricción operativa, deuda técnica, telemetría, anticipación, interoperabilidad, misión crítica, observabilidad profunda, ecosistemas híbridos, primitivas de orquestación.
|
|
4309
|
-
3. Prohibición de Léxico Barato (Zero-Clutter Text): PROHIBIDO usar palabras literales o burdas como "fierros", "cables", "hardware", "servidores físicos" o "computadoras". En su lugar, usa "nodos", "infraestructura", "arquitecturas distribuidas", "activos digitales".
|
|
4310
|
-
|
|
4311
|
-
# RESTRICCIONES ESTRICTAS ANTI-IA (EL ESTILO)
|
|
4312
|
-
- Cero Clichés de Marketing: NUNCA uses frases trilladas como "en el mundo digital de hoy", "en la era actual", "desata el poder", "revolucionar el mercado", "lleva tu empresa al siguiente nivel" o "somos tu mejor opción".
|
|
4313
|
-
- Cero Estructuras Robóticas: Evita transiciones predecibles como "En resumen", "En conclusión", "En primer lugar", "En segundo lugar".
|
|
4314
|
-
- Fluidez Orgánica: No abuses de las listas de viñetas (bullets). Si debes listar beneficios, intégralos en la prosa de manera fluida o usa negritas sutiles dentro de un párrafo.
|
|
4315
|
-
- Espacio Negativo Textual: Los tomadores de decisión no leen bloques densos de texto. Usa párrafos cortos (máximo 3 o 4 líneas). El texto debe "respirar".
|
|
4316
|
-
|
|
4317
|
-
# INSTRUCCIÓN DE EJECUCIÓN: LA NARRATIVA DE LA COLUMNA
|
|
4318
|
-
Redacta una columna de opinión profunda y analítica sobre el siguiente tema:
|
|
4319
|
-
${titulo ? `- Título sugerido: "${titulo}"` : ""}
|
|
4320
|
-
${categoria ? `- Categoría or tópico: "${categoria}"` : ""}
|
|
4321
|
-
${instrucciones ? `- Instrucciones adicionales: "${instrucciones}"` : ""}
|
|
4322
|
-
|
|
4323
|
-
Tu artículo debe seguir este arco narrativo impecable (entre 600 y 800 palabras):
|
|
4324
|
-
|
|
4325
|
-
1. EL TÍTULO ABSTRACTO: Crea un título de menos de 10 palabras que evoque un dolor de negocio o una revelación financiera, no una característica de software. Debe sonar a un artículo de *Harvard Business Review*.
|
|
4326
|
-
2. LA FRICCIÓN (El Diagnóstico Crudo): Abre el artículo sin introducciones banales. Golpea directamente diagnosticando el dolor del negocio (ej. la pérdida de rentabilidad por cuellos de botella operativos o el riesgo inminente de sistemas legados que nadie sabe mantener). Haz que el lector sienta que estás describiendo su empresa.
|
|
4327
|
-
3. LA ORQUESTACIÓN (El Núcleo): Desarrolla tu argumento explicando cómo una arquitectura inteligente (ya sea a través de microservicios, DevSecOps, automatización inteligente de negocio, o monitoreo sintético con herramientas como iwRobot) resuelve este problema de raíz. Transmite la idea de que la tecnología debe ser un habilitador transparente, no una carga.
|
|
4328
|
-
4. EL IMPACTO LATENTE: Teje dentro de la prosa (sin usar viñetas obvias de IA) los tres impactos estratégicos del tema. Habla de cómo se logra la Resiliencia, la Fluidez operativa, la Eficiencia financiera o la Anticipación ante el riesgo.
|
|
4329
|
-
5. EL CIERRE SUTIL (El CTA Elegante): En lugar de un llamado a la acción desesperado de ventas, cierra con una reflexión ejecutiva o una pregunta abierta que invite al lector a auditar mentalmente la madurez de su propia infraestructura. Una despedida que demuestre que, para orquestar la complejidad, se requiere la maestría de tres décadas.
|
|
4330
|
-
|
|
4331
|
-
Recuerda: Eres un experto hablando con otro experto. Sé denso en valor y conciso en palabras
|
|
4332
|
-
`;
|
|
4333
|
-
try {
|
|
4334
|
-
const ai = await this.geminiConfig();
|
|
4335
|
-
const result = await ai.models.generateContent({
|
|
4336
|
-
model: "gemini-2.5-pro",
|
|
4337
|
-
contents: promptArticulo,
|
|
4338
|
-
config: {
|
|
4339
|
-
responseMimeType: "application/json",
|
|
4340
|
-
temperature: temperatura,
|
|
4341
|
-
responseSchema: {
|
|
4342
|
-
type: "object",
|
|
4343
|
-
required: ["titulo", "descripcion", "content", "seo", "minute_read"],
|
|
4344
|
-
properties: {
|
|
4345
|
-
seo: {
|
|
4346
|
-
type: "object",
|
|
4347
|
-
required: ["metaTitle", "metaDescription", "metadata"],
|
|
4348
|
-
properties: {
|
|
4349
|
-
metaTitle: {
|
|
4350
|
-
type: "string"
|
|
4351
|
-
},
|
|
4352
|
-
metaDescription: {
|
|
4353
|
-
type: "string"
|
|
4354
|
-
},
|
|
4355
|
-
metadata: {
|
|
4356
|
-
type: "array",
|
|
4357
|
-
items: {
|
|
4358
|
-
type: "object",
|
|
4359
|
-
required: ["name", "content"],
|
|
4360
|
-
properties: {
|
|
4361
|
-
name: { type: "string" },
|
|
4362
|
-
content: { type: "string" }
|
|
4363
|
-
}
|
|
4364
|
-
}
|
|
4365
|
-
}
|
|
4366
|
-
}
|
|
4367
|
-
},
|
|
4368
|
-
titulo: {
|
|
4369
|
-
type: "string",
|
|
4370
|
-
minLength: 40,
|
|
4371
|
-
maxLength: 70,
|
|
4372
|
-
description: "Título del artículo"
|
|
4373
|
-
},
|
|
4374
|
-
descripcion: {
|
|
4375
|
-
type: "string",
|
|
4376
|
-
minLength: 80,
|
|
4377
|
-
maxLength: 160,
|
|
4378
|
-
description: "Descripción breve del artículo"
|
|
4379
|
-
},
|
|
4380
|
-
slug: {
|
|
4381
|
-
type: "string",
|
|
4382
|
-
minLength: 80,
|
|
4383
|
-
maxLength: 160,
|
|
4384
|
-
description: "URL-friendly basado en el título (ej: estrategias-migracion-nube)"
|
|
4385
|
-
},
|
|
4386
|
-
content: {
|
|
4387
|
-
type: "string",
|
|
4388
|
-
description: "Contenido HTML compatible con CKEditor"
|
|
4389
|
-
},
|
|
4390
|
-
minute_read: {
|
|
4391
|
-
type: "integer",
|
|
4392
|
-
minimum: 1,
|
|
4393
|
-
maximum: 30,
|
|
4394
|
-
description: "Tiempo de lectura calculado usando 200 palabras por minuto"
|
|
4395
|
-
},
|
|
4396
|
-
keywords: {
|
|
4397
|
-
type: "array",
|
|
4398
|
-
minItems: 3,
|
|
4399
|
-
maxItems: 5,
|
|
4400
|
-
items: {
|
|
4401
|
-
type: "object",
|
|
4402
|
-
required: ["name"],
|
|
4403
|
-
properties: {
|
|
4404
|
-
name: { type: "string" }
|
|
4405
|
-
}
|
|
4406
|
-
},
|
|
4407
|
-
description: "Hash tags y palabras clave para la publicación en LinkedIn y Facebook"
|
|
4408
|
-
}
|
|
4409
|
-
}
|
|
4410
|
-
}
|
|
4411
|
-
}
|
|
4412
|
-
});
|
|
4413
|
-
const rawText = result.candidates?.[0]?.content?.parts?.[0]?.text ?? "";
|
|
4414
|
-
if (!rawText) {
|
|
4415
|
-
throw new Error(
|
|
4416
|
-
"La IA no generó texto. Revisa el prompt o el modelo."
|
|
4417
|
-
);
|
|
4418
|
-
}
|
|
4419
|
-
const parsed = JSON.parse(rawText);
|
|
4420
|
-
const article = await strapi.documents("api::articulo.articulo").create({
|
|
4421
|
-
data: {
|
|
4422
|
-
titulo: parsed.titulo,
|
|
4423
|
-
descripcion: parsed.descripcion,
|
|
4424
|
-
content: parsed.content,
|
|
4425
|
-
seo: parsed.seo,
|
|
4426
|
-
minute_read: parsed.minute_read,
|
|
4427
|
-
slug: parsed.slug,
|
|
4428
|
-
categoria,
|
|
4429
|
-
autor,
|
|
4430
|
-
image: null,
|
|
4431
|
-
keywords: parsed.keywords
|
|
4432
|
-
},
|
|
4433
|
-
status: "draft"
|
|
4434
|
-
});
|
|
4435
|
-
return article;
|
|
4436
|
-
} catch (err) {
|
|
4437
|
-
console.error("🚀 ~ generateArticle ~ err:", err);
|
|
4438
|
-
throw new Error(
|
|
4439
|
-
"Error al generar el artículo. Revisa el prompt, el modelo o el JSON generado."
|
|
4440
|
-
);
|
|
4441
|
-
}
|
|
4442
|
-
},
|
|
4443
|
-
// ───────────────────────────────
|
|
4444
|
-
// 🖼️ Generate Image for Article
|
|
4445
|
-
// ───────────────────────────────
|
|
4446
|
-
async generateImageForArticle(ctx) {
|
|
4447
|
-
const { articleId, aspectRatio, imageSize } = ctx.request.body;
|
|
4448
|
-
if (!articleId) {
|
|
4449
|
-
throw new Error(
|
|
4450
|
-
"Se requiere 'articleId' en el cuerpo de la petición."
|
|
4451
|
-
);
|
|
4452
|
-
}
|
|
4453
|
-
try {
|
|
4454
|
-
const article = await strapi.documents("api::articulo.articulo").findOne({
|
|
4455
|
-
documentId: articleId
|
|
4456
|
-
});
|
|
4457
|
-
const promptJson = {
|
|
4458
|
-
label: `blog-header-${articleId}`,
|
|
4459
|
-
task: "generate_image",
|
|
4460
|
-
canvas: {
|
|
4461
|
-
resolution: imageSize || "1K",
|
|
4462
|
-
aspect_ratio: aspectRatio || "16:9"
|
|
4463
|
-
},
|
|
4464
|
-
style: {
|
|
4465
|
-
type: "architectural software engineering visualization",
|
|
4466
|
-
aesthetic: "high-end technical 3D render / octane style",
|
|
4467
|
-
background: "view of a bright white minimalist architectural gallery, sun-drenched space, white polished floors and tall glass windows",
|
|
4468
|
-
lighting: "intense natural daylight, soft global illumination, clean diffused light with subtle volumetric rays from windows"
|
|
4469
|
-
},
|
|
4470
|
-
concept_brief: `Create a sophisticated 3D visualization that metaphorically represents the concept: "${article.titulo}" — ${article.descripcion}`,
|
|
4471
|
-
subject: [
|
|
4472
|
-
"a complex holographic or architectural 3D structure floating at the center of the gallery, inspired by the concept brief above",
|
|
4473
|
-
"materials: frosted glass panels, white matte ceramic components, and polished metal accents",
|
|
4474
|
-
"glowing energy connections and data filaments in red #E4002B and teal #00C7B1 connecting the structural elements",
|
|
4475
|
-
"the structure casts a sharp, clean reflection on the white polished gallery floor",
|
|
4476
|
-
"STRICTLY NO people, NO humans, NO hands, NO chairs",
|
|
4477
|
-
"STRICTLY NO text, NO labels, NO words, NO letters, NO numbers",
|
|
4478
|
-
"high-end 3D render, architectural photography style, 4k quality"
|
|
4479
|
-
],
|
|
4480
|
-
camera: {
|
|
4481
|
-
perspective: "three-quarter wide shot, slightly elevated, eye-level with the structure, showing both the subject and the gallery environment",
|
|
4482
|
-
depth_of_field: "the main structure in sharp focus, gallery background beautifully blurred"
|
|
4483
|
-
},
|
|
4484
|
-
render: {
|
|
4485
|
-
engine: "Octane or Cinema 4D",
|
|
4486
|
-
effects: "bloom on glowing filaments and energy elements, ray-traced reflections on the white polished floor, subsurface scattering on frosted glass panels, volumetric light rays from gallery windows",
|
|
4487
|
-
quality: "masterpiece, hyper-detailed"
|
|
4488
|
-
},
|
|
4489
|
-
output_format: "image/png"
|
|
4490
|
-
};
|
|
4491
|
-
const promptText = JSON.stringify(promptJson);
|
|
4492
|
-
const generatedBase64Image = await strapi.plugin("strapi-content-generator-gemini").service("image-studio").generateForArticle(promptText, aspectRatio || "16:9", imageSize || "1K");
|
|
4493
|
-
const buffer = Buffer.from(generatedBase64Image, "base64");
|
|
4494
|
-
const uploadedFile = await this._uploadGeneratedFile(buffer, `article-${articleId}.png`, "image/png");
|
|
4495
|
-
const articleModel = await strapi.getModel("api::articulo.articulo");
|
|
4496
|
-
const sanitizedData = await strapi.contentAPI.sanitize.input(
|
|
4497
|
-
{
|
|
4498
|
-
image: uploadedFile.id
|
|
4499
|
-
},
|
|
4500
|
-
articleModel
|
|
4501
|
-
);
|
|
4502
|
-
await strapi.documents("api::articulo.articulo").update({
|
|
4503
|
-
documentId: articleId,
|
|
4504
|
-
data: sanitizedData
|
|
4505
|
-
});
|
|
4506
|
-
return {
|
|
4507
|
-
message: "Imagen generada y asociada correctamente.",
|
|
4508
|
-
image: uploadedFile
|
|
4509
|
-
};
|
|
4510
|
-
} catch (err) {
|
|
4511
|
-
console.log("🚀 ~ service ~ err:", err);
|
|
4512
|
-
throw new Error("Error al generar la imagen para el artículo.");
|
|
4513
|
-
}
|
|
4514
|
-
},
|
|
4515
4732
|
// 🎞️ Internal Veo Video Generation / Extension Helper
|
|
4516
4733
|
async _callVeoVideoGeneration(promptText, aspectRatio, durationSeconds, sceneRefs, previousVideo) {
|
|
4517
4734
|
const { ai } = await this.geminiClient({ allowVertex: false });
|
|
@@ -4601,7 +4818,7 @@ const service = ({ strapi }) => {
|
|
|
4601
4818
|
// 🌐 Social Media Publishing
|
|
4602
4819
|
// ───────────────────────────────
|
|
4603
4820
|
async publishToLinkedIn(ctx) {
|
|
4604
|
-
const { articleId } = ctx.request.body;
|
|
4821
|
+
const { articleId, mensaje } = ctx.request.body;
|
|
4605
4822
|
const pluginStore = strapi.store({
|
|
4606
4823
|
type: "plugin",
|
|
4607
4824
|
name: "strapi-content-generator-gemini"
|
|
@@ -4616,7 +4833,6 @@ const service = ({ strapi }) => {
|
|
|
4616
4833
|
populate: ["image", "keywords"]
|
|
4617
4834
|
});
|
|
4618
4835
|
if (!article) throw new Error(`Artículo con ID ${articleId} no encontrado.`);
|
|
4619
|
-
const hashtags = article.keywords.map((k) => `#${k.name.trim().replace(/\s+/g, "").replace(/[^\w]/g, "")}`).join(" ");
|
|
4620
4836
|
const articleUrl = `https://interware.com.mx/blog/${article.slug}`;
|
|
4621
4837
|
const imageUrl = article.image?.url;
|
|
4622
4838
|
if (!imageUrl) throw new Error("El artículo no tiene imagen.");
|
|
@@ -4651,9 +4867,7 @@ const service = ({ strapi }) => {
|
|
|
4651
4867
|
});
|
|
4652
4868
|
const postBody = {
|
|
4653
4869
|
author: `urn:li:organization:${linkedInOrganizationId}`,
|
|
4654
|
-
commentary:
|
|
4655
|
-
|
|
4656
|
-
${hashtags}`,
|
|
4870
|
+
commentary: typeof mensaje === "string" && mensaje.trim() || defaultPostText(postData(article), "linkedin"),
|
|
4657
4871
|
visibility: "PUBLIC",
|
|
4658
4872
|
distribution: {
|
|
4659
4873
|
feedDistribution: "MAIN_FEED",
|
|
@@ -4691,7 +4905,7 @@ ${hashtags}`,
|
|
|
4691
4905
|
}
|
|
4692
4906
|
},
|
|
4693
4907
|
async publishToFacebook(ctx) {
|
|
4694
|
-
const { articleId } = ctx.request.body;
|
|
4908
|
+
const { articleId, mensaje } = ctx.request.body;
|
|
4695
4909
|
const pluginStore = strapi.store({
|
|
4696
4910
|
type: "plugin",
|
|
4697
4911
|
name: "strapi-content-generator-gemini"
|
|
@@ -4720,16 +4934,8 @@ ${hashtags}`,
|
|
|
4720
4934
|
throw new Error(`Artículo con ID ${articleId} no encontrado.`);
|
|
4721
4935
|
}
|
|
4722
4936
|
const articleUrl = `https://interware.com.mx/blog/${article.slug}`;
|
|
4723
|
-
const hashtags = article.keywords.map(
|
|
4724
|
-
(keyword) => `#${keyword.name.trim().replace(/\s+/g, "").replace(/[^\w]/g, "")}`
|
|
4725
|
-
// quita caracteres raros
|
|
4726
|
-
).join(" ");
|
|
4727
4937
|
const postBody = {
|
|
4728
|
-
message:
|
|
4729
|
-
|
|
4730
|
-
${article.descripcion}
|
|
4731
|
-
|
|
4732
|
-
${hashtags}`,
|
|
4938
|
+
message: typeof mensaje === "string" && mensaje.trim() || defaultPostText(postData(article), "facebook"),
|
|
4733
4939
|
link: articleUrl,
|
|
4734
4940
|
access_token: facebookAccessToken
|
|
4735
4941
|
};
|
|
@@ -4766,7 +4972,8 @@ ${hashtags}`,
|
|
|
4766
4972
|
const services = {
|
|
4767
4973
|
service,
|
|
4768
4974
|
"image-studio": imageStudio$1,
|
|
4769
|
-
templates: templates$1
|
|
4975
|
+
templates: templates$1,
|
|
4976
|
+
articles: articles$1
|
|
4770
4977
|
};
|
|
4771
4978
|
const index = {
|
|
4772
4979
|
register,
|