@interware/content-generator 0.6.1 → 0.7.0
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 +514 -320
- package/dist/server/index.mjs +514 -320
- 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 +0 -10
- 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
|
};
|
|
@@ -331,7 +324,7 @@ const INVISIBLE = /[----]/g;
|
|
|
331
324
|
const TAG = /<\/?[a-z][^>]*>/gi;
|
|
332
325
|
const sanitizePrompt = (text2) => text2.normalize("NFC").replace(CONTROL, "").replace(INVISIBLE, "").replace(TAG, "").replace(/\s+/g, " ").trim();
|
|
333
326
|
const PROMPT_LABELS = { label: "El prompt", empty: "Escribe un prompt." };
|
|
334
|
-
const INSTRUCTION_LABELS = { label: "La instrucción", empty: "Describe el cambio que quieres." };
|
|
327
|
+
const INSTRUCTION_LABELS$1 = { label: "La instrucción", empty: "Describe el cambio que quieres." };
|
|
335
328
|
const checkPrompt = (text2, { label, empty } = PROMPT_LABELS) => {
|
|
336
329
|
const clean2 = sanitizePrompt(text2);
|
|
337
330
|
if (!clean2) return { ok: false, error: empty };
|
|
@@ -387,25 +380,6 @@ const createImageStudio = (getClient, read = (p) => fs.promises.readFile(p)) =>
|
|
|
387
380
|
return availableModels(null);
|
|
388
381
|
}
|
|
389
382
|
},
|
|
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
383
|
async generate(input) {
|
|
410
384
|
const { models: api, backend } = await getClient();
|
|
411
385
|
const text2 = cleanPrompt(input.prompt);
|
|
@@ -483,7 +457,7 @@ const parseGenerateInput = (fields, files) => {
|
|
|
483
457
|
};
|
|
484
458
|
};
|
|
485
459
|
const parseEditInput = (fields, files) => {
|
|
486
|
-
const instruction = clean(str(fields.instruction), INSTRUCTION_LABELS);
|
|
460
|
+
const instruction = clean(str(fields.instruction), INSTRUCTION_LABELS$1);
|
|
487
461
|
const [image] = list(files.image);
|
|
488
462
|
if (!image) throw new InputError("Falta la imagen a editar.");
|
|
489
463
|
const model = editModelFor(str(fields.model) || void 0);
|
|
@@ -501,7 +475,7 @@ const parseEditInput = (fields, files) => {
|
|
|
501
475
|
aspectRatio: model.aspectRatios.includes(str(fields.aspectRatio)) ? str(fields.aspectRatio) : void 0
|
|
502
476
|
};
|
|
503
477
|
};
|
|
504
|
-
const fail$
|
|
478
|
+
const fail$3 = (ctx, status, name2, message) => {
|
|
505
479
|
ctx.status = status;
|
|
506
480
|
ctx.body = { data: null, error: { status, name: name2, message } };
|
|
507
481
|
};
|
|
@@ -511,10 +485,10 @@ const imageStudio = ({ strapi }) => {
|
|
|
511
485
|
try {
|
|
512
486
|
ctx.body = await work();
|
|
513
487
|
} catch (err) {
|
|
514
|
-
if (err instanceof InputError) return fail$
|
|
515
|
-
if (err instanceof BlockedError) return fail$
|
|
488
|
+
if (err instanceof InputError) return fail$3(ctx, 400, "BadRequestError", err.message);
|
|
489
|
+
if (err instanceof BlockedError) return fail$3(ctx, 422, "UnprocessableEntityError", err.message);
|
|
516
490
|
strapi.log.error(`[image-studio] ${err instanceof Error ? err.message : String(err)}`);
|
|
517
|
-
return fail$
|
|
491
|
+
return fail$3(ctx, 502, "BadGatewayError", "El servicio de imágenes no respondió. Intenta de nuevo en un momento.");
|
|
518
492
|
}
|
|
519
493
|
};
|
|
520
494
|
return {
|
|
@@ -528,6 +502,454 @@ const imageStudio = ({ strapi }) => {
|
|
|
528
502
|
})
|
|
529
503
|
};
|
|
530
504
|
};
|
|
505
|
+
const MAX_URLS = 3;
|
|
506
|
+
const isHttp = (value) => {
|
|
507
|
+
try {
|
|
508
|
+
const { protocol } = new URL(value);
|
|
509
|
+
return protocol === "http:" || protocol === "https:";
|
|
510
|
+
} catch {
|
|
511
|
+
return false;
|
|
512
|
+
}
|
|
513
|
+
};
|
|
514
|
+
const hostOf = (url) => {
|
|
515
|
+
try {
|
|
516
|
+
return new URL(url).hostname;
|
|
517
|
+
} catch {
|
|
518
|
+
return url;
|
|
519
|
+
}
|
|
520
|
+
};
|
|
521
|
+
const parseReferenceUrls = (input) => {
|
|
522
|
+
const list2 = (Array.isArray(input) ? input : []).filter((v) => typeof v === "string").map((v) => v.trim()).filter(Boolean);
|
|
523
|
+
const unique = [...new Set(list2)];
|
|
524
|
+
if (unique.length > MAX_URLS) throw new InputError(`Puedes dar hasta ${MAX_URLS} URLs de referencia.`);
|
|
525
|
+
const invalid = unique.find((u) => !isHttp(u));
|
|
526
|
+
if (invalid) throw new InputError(`La URL «${invalid}» no es válida.`);
|
|
527
|
+
return unique;
|
|
528
|
+
};
|
|
529
|
+
const sourcesFrom = (urls, res) => {
|
|
530
|
+
const referencias = urls.map((url) => ({ titulo: hostOf(url), url, tipo: "referencia" }));
|
|
531
|
+
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" }));
|
|
532
|
+
return [...referencias, ...busqueda].filter((f, i, all3) => all3.findIndex((o) => o.url === f.url) === i);
|
|
533
|
+
};
|
|
534
|
+
const ARTICLE_MODEL = "gemini-2.5-pro";
|
|
535
|
+
const ENRICH_MODEL = "gemini-2.5-flash";
|
|
536
|
+
const BASE_PROMPT_MAX = 2e4;
|
|
537
|
+
const INSTRUCTION_LABELS = { label: "Las instrucciones", empty: "Escribe las instrucciones del artículo." };
|
|
538
|
+
const parseCategoria = (input) => {
|
|
539
|
+
const c = input ?? {};
|
|
540
|
+
if (typeof c.id === "string" && c.id.trim()) return { id: c.id.trim() };
|
|
541
|
+
if (typeof c.nueva === "string" && c.nueva.trim()) return { nueva: c.nueva.trim().slice(0, 80) };
|
|
542
|
+
throw new InputError("Elige o escribe una categoría.");
|
|
543
|
+
};
|
|
544
|
+
const parseTemperatura = (input) => {
|
|
545
|
+
const n = typeof input === "number" ? input : typeof input === "string" ? Number(input) : NaN;
|
|
546
|
+
return Number.isFinite(n) ? Math.min(2, Math.max(0, n)) : 0.5;
|
|
547
|
+
};
|
|
548
|
+
const parseArticleInput = (body) => {
|
|
549
|
+
const check = checkPrompt(typeof body.instrucciones === "string" ? body.instrucciones : "", INSTRUCTION_LABELS);
|
|
550
|
+
if ("error" in check) throw new InputError(check.error);
|
|
551
|
+
return {
|
|
552
|
+
titulo: typeof body.titulo === "string" ? body.titulo.trim().slice(0, 200) : "",
|
|
553
|
+
categoria: parseCategoria(body.categoria),
|
|
554
|
+
temperatura: parseTemperatura(body.temperatura),
|
|
555
|
+
instrucciones: check.text,
|
|
556
|
+
urls: parseReferenceUrls(body.urls),
|
|
557
|
+
busqueda: body.busqueda === true || body.busqueda === "true",
|
|
558
|
+
usarPromptBase: !(body.usarPromptBase === false || body.usarPromptBase === "false"),
|
|
559
|
+
...optionalBase(body.promptBase)
|
|
560
|
+
};
|
|
561
|
+
};
|
|
562
|
+
const optionalBase = (input) => {
|
|
563
|
+
const text2 = typeof input === "string" ? input.trim() : "";
|
|
564
|
+
if (!text2) return {};
|
|
565
|
+
if (text2.length > BASE_PROMPT_MAX) throw new InputError(`El prompt base puede tener hasta ${BASE_PROMPT_MAX} caracteres.`);
|
|
566
|
+
return { promptBase: text2 };
|
|
567
|
+
};
|
|
568
|
+
const parseBasePrompt = (input) => {
|
|
569
|
+
const base = optionalBase(input).promptBase;
|
|
570
|
+
if (!base) throw new InputError("Escribe el prompt base.");
|
|
571
|
+
return base;
|
|
572
|
+
};
|
|
573
|
+
const researchTools = ({ urls, busqueda }) => [
|
|
574
|
+
...busqueda ? [{ googleSearch: {} }] : [],
|
|
575
|
+
...urls.length ? [{ urlContext: {} }] : []
|
|
576
|
+
];
|
|
577
|
+
const temaLines = ({ titulo, categoria, instrucciones }) => [
|
|
578
|
+
titulo ? `- Título sugerido: "${titulo}"` : "",
|
|
579
|
+
categoria ? `- Categoría o tópico: "${categoria}"` : "",
|
|
580
|
+
instrucciones ? `- Instrucciones: "${instrucciones}"` : ""
|
|
581
|
+
].filter(Boolean).join("\n");
|
|
582
|
+
const researchPrompt = (tema) => `
|
|
583
|
+
Eres analista de investigación de InterWare. Reúne la información que respaldará una columna de opinión para
|
|
584
|
+
directores de TI, operaciones y finanzas.
|
|
585
|
+
|
|
586
|
+
Tema:
|
|
587
|
+
${temaLines(tema)}
|
|
588
|
+
${tema.urls.length ? `
|
|
589
|
+
Lee y usa como referencia principal estas páginas:
|
|
590
|
+
${tema.urls.map((u) => `- ${u}`).join("\n")}
|
|
591
|
+
` : ""}
|
|
592
|
+
Entrega notas en español, concisas: hechos, cifras con su fuente, tendencias y ejemplos relevantes. No escribas el
|
|
593
|
+
artículo. Si un dato no está respaldado por una fuente, no lo incluyas.
|
|
594
|
+
`;
|
|
595
|
+
const DEFAULT_BASE_PROMPT = `# ROL Y PERSONA (EL FONDO)
|
|
596
|
+
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).
|
|
597
|
+
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.
|
|
598
|
+
|
|
599
|
+
# FILOSOFÍA DE MARCA: "ORQUESTACIÓN LATENTE"
|
|
600
|
+
Toda tu narrativa debe estar impregnada de nuestra visión de negocio: "Evolución por Continuidad"
|
|
601
|
+
- InterWare no inventa necesidades ni vende catálogos de servicios; InterWare resuelve la complejidad operativa con responsabilidad
|
|
602
|
+
- Somos el orquestador invisible que garantiza que ecosistemas heterogéneos trabajen en perfecta armonía.
|
|
603
|
+
- 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.
|
|
604
|
+
- 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.
|
|
605
|
+
|
|
606
|
+
# REGLAS DE TONO Y LÉXICO (LA FORMA)
|
|
607
|
+
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.
|
|
608
|
+
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.
|
|
609
|
+
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".
|
|
610
|
+
|
|
611
|
+
# RESTRICCIONES ESTRICTAS ANTI-IA (EL ESTILO)
|
|
612
|
+
- 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".
|
|
613
|
+
- Cero Estructuras Robóticas: Evita transiciones predecibles como "En resumen", "En conclusión", "En primer lugar", "En segundo lugar".
|
|
614
|
+
- 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.
|
|
615
|
+
- 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".
|
|
616
|
+
|
|
617
|
+
# INSTRUCCIÓN DE EJECUCIÓN: LA NARRATIVA DE LA COLUMNA
|
|
618
|
+
Redacta una columna de opinión profunda y analítica sobre el tema de la sección «TEMA DEL ARTÍCULO».
|
|
619
|
+
|
|
620
|
+
Tu artículo debe seguir este arco narrativo impecable (entre 600 y 800 palabras):
|
|
621
|
+
|
|
622
|
+
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*.
|
|
623
|
+
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.
|
|
624
|
+
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.
|
|
625
|
+
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.
|
|
626
|
+
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.
|
|
627
|
+
|
|
628
|
+
Recuerda: Eres un experto hablando con otro experto. Sé denso en valor y conciso en palabras`;
|
|
629
|
+
const investigacionBlock = (investigacion) => investigacion ? `
|
|
630
|
+
|
|
631
|
+
# INVESTIGACIÓN DE APOYO
|
|
632
|
+
Usa estos datos como base factual. No inventes cifras, nombres ni estudios que no aparezcan aquí:
|
|
633
|
+
${investigacion}` : "";
|
|
634
|
+
const articlePrompt = ({ base = DEFAULT_BASE_PROMPT, investigacion, ...tema }) => `${base}
|
|
635
|
+
|
|
636
|
+
# TEMA DEL ARTÍCULO
|
|
637
|
+
${temaLines(tema)}${investigacionBlock(investigacion)}`;
|
|
638
|
+
const rawPrompt = ({ instrucciones, investigacion }) => `${instrucciones}${investigacionBlock(investigacion)}`;
|
|
639
|
+
const enrichPrompt = (texto) => `
|
|
640
|
+
Eres editor de contenidos de InterWare, empresa mexicana de tecnología. Convierte esta idea en instrucciones claras
|
|
641
|
+
para redactar un artículo de blog.
|
|
642
|
+
|
|
643
|
+
Idea: "${texto}"
|
|
644
|
+
|
|
645
|
+
Responde solo con las instrucciones, en español y en texto plano, con estas líneas:
|
|
646
|
+
Tema: …
|
|
647
|
+
Público: …
|
|
648
|
+
Cubrir: …
|
|
649
|
+
Tono: …
|
|
650
|
+
Cierre: …
|
|
651
|
+
Máximo 1500 caracteres. Sin comillas ni Markdown.
|
|
652
|
+
`;
|
|
653
|
+
const ARTICLE_SCHEMA = {
|
|
654
|
+
type: "object",
|
|
655
|
+
required: ["titulo", "descripcion", "content", "seo", "minute_read"],
|
|
656
|
+
properties: {
|
|
657
|
+
seo: {
|
|
658
|
+
type: "object",
|
|
659
|
+
required: ["metaTitle", "metaDescription", "metadata"],
|
|
660
|
+
properties: {
|
|
661
|
+
metaTitle: { type: "string" },
|
|
662
|
+
metaDescription: { type: "string" },
|
|
663
|
+
metadata: {
|
|
664
|
+
type: "array",
|
|
665
|
+
items: {
|
|
666
|
+
type: "object",
|
|
667
|
+
required: ["name", "content"],
|
|
668
|
+
properties: { name: { type: "string" }, content: { type: "string" } }
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
},
|
|
673
|
+
titulo: { type: "string", minLength: 40, maxLength: 70, description: "Título del artículo" },
|
|
674
|
+
descripcion: { type: "string", minLength: 80, maxLength: 160, description: "Descripción breve del artículo" },
|
|
675
|
+
slug: {
|
|
676
|
+
type: "string",
|
|
677
|
+
minLength: 80,
|
|
678
|
+
maxLength: 160,
|
|
679
|
+
description: "URL-friendly basado en el título (ej: estrategias-migracion-nube)"
|
|
680
|
+
},
|
|
681
|
+
content: { type: "string", description: "Contenido HTML compatible con CKEditor" },
|
|
682
|
+
minute_read: {
|
|
683
|
+
type: "integer",
|
|
684
|
+
minimum: 1,
|
|
685
|
+
maximum: 30,
|
|
686
|
+
description: "Tiempo de lectura calculado usando 200 palabras por minuto"
|
|
687
|
+
},
|
|
688
|
+
keywords: {
|
|
689
|
+
type: "array",
|
|
690
|
+
minItems: 3,
|
|
691
|
+
maxItems: 5,
|
|
692
|
+
items: { type: "object", required: ["name"], properties: { name: { type: "string" } } },
|
|
693
|
+
description: "Hash tags y palabras clave para la publicación en LinkedIn y Facebook"
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
};
|
|
697
|
+
const ZONA = "America/Mexico_City";
|
|
698
|
+
const UN_ANIO_MS = 365 * 24 * 60 * 60 * 1e3;
|
|
699
|
+
const fechaEnMexico = (date) => new Intl.DateTimeFormat("en-CA", { timeZone: ZONA, year: "numeric", month: "2-digit", day: "2-digit" }).format(date);
|
|
700
|
+
const parseScheduleAt = (input, now) => {
|
|
701
|
+
const date = typeof input === "string" ? new Date(input) : /* @__PURE__ */ new Date(NaN);
|
|
702
|
+
if (Number.isNaN(date.getTime())) throw new InputError("La fecha y hora no son válidas.");
|
|
703
|
+
if (date.getTime() <= now.getTime()) throw new InputError("Elige una fecha y hora futuras.");
|
|
704
|
+
if (date.getTime() - now.getTime() > UN_ANIO_MS) throw new InputError("Programa con menos de un año de anticipación.");
|
|
705
|
+
return date;
|
|
706
|
+
};
|
|
707
|
+
const estadoDe = ({ publicado, programada }) => publicado ? "publicado" : programada ? "programado" : "borrador";
|
|
708
|
+
class NotFoundError extends Error {
|
|
709
|
+
}
|
|
710
|
+
const memoryStore = () => {
|
|
711
|
+
let value = null;
|
|
712
|
+
return {
|
|
713
|
+
get: async () => value,
|
|
714
|
+
set: async (v) => {
|
|
715
|
+
value = v;
|
|
716
|
+
},
|
|
717
|
+
remove: async () => {
|
|
718
|
+
value = null;
|
|
719
|
+
}
|
|
720
|
+
};
|
|
721
|
+
};
|
|
722
|
+
const ROW_FIELDS = ["titulo", "fecha_publicacion", "publicacion_programada", "linkedInPostId", "facebookPostId"];
|
|
723
|
+
const DETAIL_POPULATE = { image: true, categoria: true, seo: true, keywords: true };
|
|
724
|
+
const silentLog = { info: () => void 0, warn: () => void 0, error: () => void 0 };
|
|
725
|
+
const slugify = (text2) => text2.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
726
|
+
const textOf = (res) => (res.text ?? res.candidates?.[0]?.content?.parts?.[0]?.text ?? "").trim();
|
|
727
|
+
const toRow = (d, publicado) => ({
|
|
728
|
+
documentId: d.documentId,
|
|
729
|
+
titulo: d.titulo ?? "",
|
|
730
|
+
categoria: d.categoria?.categoria ?? null,
|
|
731
|
+
estado: estadoDe({ publicado, programada: d.publicacion_programada }),
|
|
732
|
+
imagen: Boolean(d.image),
|
|
733
|
+
fechaPublicacion: d.fecha_publicacion ?? null,
|
|
734
|
+
programadaPara: d.publicacion_programada ?? null,
|
|
735
|
+
linkedInPostId: d.linkedInPostId ?? null,
|
|
736
|
+
facebookPostId: d.facebookPostId ?? null
|
|
737
|
+
});
|
|
738
|
+
const toDetail = (d, publicado) => ({
|
|
739
|
+
...toRow(d, publicado),
|
|
740
|
+
descripcion: d.descripcion ?? "",
|
|
741
|
+
content: d.content ?? "",
|
|
742
|
+
minuteRead: d.minute_read ?? null,
|
|
743
|
+
slug: d.slug ?? null,
|
|
744
|
+
imageUrl: d.image ? d.image.formats?.small?.url ?? d.image.formats?.thumbnail?.url ?? d.image.url ?? null : null,
|
|
745
|
+
imageName: d.image?.name ?? null,
|
|
746
|
+
seo: d.seo ? { metaTitle: d.seo.metaTitle, metaDescription: d.seo.metaDescription } : null,
|
|
747
|
+
keywords: (d.keywords ?? []).map((k) => k.name ?? "").filter(Boolean),
|
|
748
|
+
fuentes: Array.isArray(d.fuentes) ? d.fuentes : []
|
|
749
|
+
});
|
|
750
|
+
const createArticles = ({ articulos, categorias, getModels, now = () => /* @__PURE__ */ new Date(), log = silentLog, promptStore = memoryStore() }) => {
|
|
751
|
+
const draftOf = async (documentId, populate = DETAIL_POPULATE) => {
|
|
752
|
+
const d = await articulos.findOne({ documentId, status: "draft", populate });
|
|
753
|
+
if (!d) throw new NotFoundError("El artículo no existe.");
|
|
754
|
+
return d;
|
|
755
|
+
};
|
|
756
|
+
const isPublished = async (documentId) => Boolean(await articulos.findOne({ documentId, status: "published", fields: ["titulo"] }));
|
|
757
|
+
const detail = async (documentId) => {
|
|
758
|
+
const d = await draftOf(documentId);
|
|
759
|
+
return toDetail(d, await isPublished(documentId));
|
|
760
|
+
};
|
|
761
|
+
const resolveCategoria = async (input) => {
|
|
762
|
+
if ("id" in input) {
|
|
763
|
+
const c = await categorias.findOne({ documentId: input.id });
|
|
764
|
+
if (!c) throw new InputError("La categoría elegida ya no existe.");
|
|
765
|
+
return { id: c.documentId, nombre: c.categoria };
|
|
766
|
+
}
|
|
767
|
+
const found = await categorias.findFirst({ filters: { categoria: { $eqi: input.nueva } } });
|
|
768
|
+
if (found) return { id: found.documentId, nombre: found.categoria };
|
|
769
|
+
const created = await categorias.create({ data: { categoria: input.nueva, slug: slugify(input.nueva) } });
|
|
770
|
+
return { id: created.documentId, nombre: input.nueva };
|
|
771
|
+
};
|
|
772
|
+
const basePrompt = async () => {
|
|
773
|
+
const guardado = await promptStore.get();
|
|
774
|
+
return { prompt: guardado || DEFAULT_BASE_PROMPT, personalizado: Boolean(guardado) };
|
|
775
|
+
};
|
|
776
|
+
return {
|
|
777
|
+
basePrompt,
|
|
778
|
+
async saveBasePrompt(prompt) {
|
|
779
|
+
await promptStore.set(prompt);
|
|
780
|
+
return basePrompt();
|
|
781
|
+
},
|
|
782
|
+
async resetBasePrompt() {
|
|
783
|
+
await promptStore.remove();
|
|
784
|
+
return basePrompt();
|
|
785
|
+
},
|
|
786
|
+
async list() {
|
|
787
|
+
const [drafts, published] = await Promise.all([
|
|
788
|
+
articulos.findMany({ status: "draft", fields: ROW_FIELDS, populate: { image: { fields: ["id"] }, categoria: { fields: ["categoria"] } }, sort: ["createdAt:desc"] }),
|
|
789
|
+
articulos.findMany({ status: "published", fields: ["titulo"] })
|
|
790
|
+
]);
|
|
791
|
+
const publicados = new Set(published.map((p) => p.documentId));
|
|
792
|
+
return { articles: drafts.map((d) => toRow(d, publicados.has(d.documentId))) };
|
|
793
|
+
},
|
|
794
|
+
detail,
|
|
795
|
+
async generate(input) {
|
|
796
|
+
const categoria = await resolveCategoria(input.categoria);
|
|
797
|
+
const models = await getModels();
|
|
798
|
+
const tema = { titulo: input.titulo, categoria: categoria.nombre, instrucciones: input.instrucciones };
|
|
799
|
+
const tools = researchTools(input);
|
|
800
|
+
let investigacion;
|
|
801
|
+
let fuentes = [];
|
|
802
|
+
if (tools.length) {
|
|
803
|
+
const research = await models.generateContent({ model: ARTICLE_MODEL, contents: researchPrompt({ ...tema, urls: input.urls }), config: { tools, temperature: 0.2 } });
|
|
804
|
+
investigacion = textOf(research) || void 0;
|
|
805
|
+
fuentes = sourcesFrom(input.urls, research);
|
|
806
|
+
}
|
|
807
|
+
const contents = input.usarPromptBase === false ? rawPrompt({ instrucciones: input.instrucciones, investigacion }) : articlePrompt({ ...tema, investigacion, base: input.promptBase ?? (await basePrompt()).prompt });
|
|
808
|
+
const res = await models.generateContent({
|
|
809
|
+
model: ARTICLE_MODEL,
|
|
810
|
+
contents,
|
|
811
|
+
config: { responseMimeType: "application/json", temperature: input.temperatura, responseSchema: ARTICLE_SCHEMA }
|
|
812
|
+
});
|
|
813
|
+
let parsed;
|
|
814
|
+
try {
|
|
815
|
+
parsed = JSON.parse(textOf(res));
|
|
816
|
+
} catch {
|
|
817
|
+
throw new Error("La respuesta del modelo no es un JSON válido.");
|
|
818
|
+
}
|
|
819
|
+
const created = await articulos.create({
|
|
820
|
+
data: {
|
|
821
|
+
titulo: parsed.titulo,
|
|
822
|
+
descripcion: parsed.descripcion,
|
|
823
|
+
content: parsed.content,
|
|
824
|
+
seo: parsed.seo,
|
|
825
|
+
minute_read: parsed.minute_read,
|
|
826
|
+
slug: parsed.slug,
|
|
827
|
+
keywords: parsed.keywords,
|
|
828
|
+
categoria: categoria.id,
|
|
829
|
+
image: null,
|
|
830
|
+
fuentes
|
|
831
|
+
},
|
|
832
|
+
status: "draft"
|
|
833
|
+
});
|
|
834
|
+
return { documentId: created.documentId };
|
|
835
|
+
},
|
|
836
|
+
async enrich(texto) {
|
|
837
|
+
const models = await getModels();
|
|
838
|
+
const res = await models.generateContent({ model: ENRICH_MODEL, contents: enrichPrompt(texto) });
|
|
839
|
+
const out = textOf(res).replace(/^["'«“]+|["'»”]+$/g, "").trim();
|
|
840
|
+
if (!out) throw new InputError("No se pudieron enriquecer las instrucciones. Intenta de nuevo.");
|
|
841
|
+
return out.slice(0, 2e3);
|
|
842
|
+
},
|
|
843
|
+
async setImage(documentId, fileId) {
|
|
844
|
+
const id = typeof fileId === "number" ? fileId : Number(fileId);
|
|
845
|
+
if (!Number.isInteger(id) || id <= 0) throw new InputError("Elige una imagen válida.");
|
|
846
|
+
await draftOf(documentId, {});
|
|
847
|
+
await articulos.update({ documentId, data: { image: id } });
|
|
848
|
+
if (await isPublished(documentId)) await articulos.publish({ documentId });
|
|
849
|
+
return detail(documentId);
|
|
850
|
+
},
|
|
851
|
+
async publish(documentId) {
|
|
852
|
+
const d = await draftOf(documentId);
|
|
853
|
+
if (!d.image) throw new InputError("Elige una imagen antes de publicar.");
|
|
854
|
+
await articulos.update({ documentId, data: { fecha_publicacion: fechaEnMexico(now()), publicacion_programada: null } });
|
|
855
|
+
await articulos.publish({ documentId });
|
|
856
|
+
return detail(documentId);
|
|
857
|
+
},
|
|
858
|
+
async schedule(documentId, at) {
|
|
859
|
+
const date = parseScheduleAt(at, now());
|
|
860
|
+
const d = await draftOf(documentId);
|
|
861
|
+
if (!d.image) throw new InputError("Elige una imagen antes de programar.");
|
|
862
|
+
if (await isPublished(documentId)) throw new InputError("El artículo ya está publicado.");
|
|
863
|
+
await articulos.update({ documentId, data: { publicacion_programada: date.toISOString(), fecha_publicacion: fechaEnMexico(date) } });
|
|
864
|
+
return detail(documentId);
|
|
865
|
+
},
|
|
866
|
+
async unschedule(documentId) {
|
|
867
|
+
await draftOf(documentId, {});
|
|
868
|
+
await articulos.update({ documentId, data: { publicacion_programada: null, fecha_publicacion: null } });
|
|
869
|
+
return detail(documentId);
|
|
870
|
+
},
|
|
871
|
+
/** D4: publica los borradores con programación vencida. Devuelve cuántos publicó. */
|
|
872
|
+
async publishDue() {
|
|
873
|
+
const due = await articulos.findMany({
|
|
874
|
+
status: "draft",
|
|
875
|
+
filters: { publicacion_programada: { $notNull: true, $lte: now().toISOString() } },
|
|
876
|
+
fields: ["publicacion_programada"],
|
|
877
|
+
populate: { image: { fields: ["id"] } }
|
|
878
|
+
});
|
|
879
|
+
let count = 0;
|
|
880
|
+
for (const d of due) {
|
|
881
|
+
if (!d.image) {
|
|
882
|
+
log.warn(`[articles] ${d.documentId} está programado pero no tiene imagen; no se publicó.`);
|
|
883
|
+
continue;
|
|
884
|
+
}
|
|
885
|
+
try {
|
|
886
|
+
await articulos.update({ documentId: d.documentId, data: { publicacion_programada: null } });
|
|
887
|
+
await articulos.publish({ documentId: d.documentId });
|
|
888
|
+
count += 1;
|
|
889
|
+
} catch (err) {
|
|
890
|
+
log.error(`[articles] no se pudo publicar ${d.documentId}: ${err instanceof Error ? err.message : String(err)}`);
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
if (count) log.info(`[articles] ${count} artículo(s) programado(s) publicados.`);
|
|
894
|
+
return count;
|
|
895
|
+
}
|
|
896
|
+
};
|
|
897
|
+
};
|
|
898
|
+
const articles$1 = ({ strapi }) => createArticles({
|
|
899
|
+
articulos: strapi.documents("api::articulo.articulo"),
|
|
900
|
+
categorias: strapi.documents("api::categoria.categoria"),
|
|
901
|
+
getModels: async () => (await strapi.plugin("strapi-content-generator-gemini").service("service").geminiClient()).ai.models,
|
|
902
|
+
log: strapi.log,
|
|
903
|
+
promptStore: /* @__PURE__ */ (() => {
|
|
904
|
+
const store = () => strapi.store({ type: "plugin", name: "strapi-content-generator-gemini" });
|
|
905
|
+
const key = "ARTICLE_BASE_PROMPT";
|
|
906
|
+
return {
|
|
907
|
+
get: async () => await store().get({ key }) ?? null,
|
|
908
|
+
set: async (value) => {
|
|
909
|
+
await store().set({ key, value });
|
|
910
|
+
},
|
|
911
|
+
remove: async () => {
|
|
912
|
+
await store().delete({ key });
|
|
913
|
+
}
|
|
914
|
+
};
|
|
915
|
+
})()
|
|
916
|
+
});
|
|
917
|
+
const fail$2 = (ctx, status, name2, message) => {
|
|
918
|
+
ctx.status = status;
|
|
919
|
+
ctx.body = { data: null, error: { status, name: name2, message } };
|
|
920
|
+
};
|
|
921
|
+
const articles = ({ strapi }) => {
|
|
922
|
+
const articles2 = () => strapi.plugin("strapi-content-generator-gemini").service("articles");
|
|
923
|
+
const id = (ctx) => ctx.params?.documentId ?? "";
|
|
924
|
+
const run = async (ctx, work) => {
|
|
925
|
+
try {
|
|
926
|
+
ctx.body = await work();
|
|
927
|
+
} catch (err) {
|
|
928
|
+
if (err instanceof InputError) return fail$2(ctx, 400, "BadRequestError", err.message);
|
|
929
|
+
if (err instanceof NotFoundError) return fail$2(ctx, 404, "NotFoundError", err.message);
|
|
930
|
+
if (err instanceof Error && err.name === "ValidationError") return fail$2(ctx, 400, "ValidationError", err.message);
|
|
931
|
+
strapi.log.error(`[articles] ${err instanceof Error ? err.message : String(err)}`);
|
|
932
|
+
return fail$2(ctx, 502, "BadGatewayError", "El servicio de generación no respondió. Intenta de nuevo en un momento.");
|
|
933
|
+
}
|
|
934
|
+
};
|
|
935
|
+
return {
|
|
936
|
+
list: (ctx) => run(ctx, () => articles2().list()),
|
|
937
|
+
detail: (ctx) => run(ctx, () => articles2().detail(id(ctx))),
|
|
938
|
+
generate: (ctx) => run(ctx, () => articles2().generate(parseArticleInput(ctx.request.body ?? {}))),
|
|
939
|
+
enrich: (ctx) => run(ctx, async () => {
|
|
940
|
+
const raw = typeof ctx.request.body?.texto === "string" ? ctx.request.body.texto : "";
|
|
941
|
+
const texto = clean(raw, { label: "La idea", empty: "Escribe una idea para enriquecer." });
|
|
942
|
+
return { texto: await articles2().enrich(texto) };
|
|
943
|
+
}),
|
|
944
|
+
basePrompt: (ctx) => run(ctx, () => articles2().basePrompt()),
|
|
945
|
+
saveBasePrompt: (ctx) => run(ctx, () => articles2().saveBasePrompt(parseBasePrompt(ctx.request.body?.prompt))),
|
|
946
|
+
resetBasePrompt: (ctx) => run(ctx, () => articles2().resetBasePrompt()),
|
|
947
|
+
setImage: (ctx) => run(ctx, () => articles2().setImage(id(ctx), ctx.request.body?.fileId)),
|
|
948
|
+
publish: (ctx) => run(ctx, () => articles2().publish(id(ctx))),
|
|
949
|
+
schedule: (ctx) => run(ctx, () => articles2().schedule(id(ctx), ctx.request.body?.at)),
|
|
950
|
+
unschedule: (ctx) => run(ctx, () => articles2().unschedule(id(ctx)))
|
|
951
|
+
};
|
|
952
|
+
};
|
|
531
953
|
const NAVY = "#1F2A44";
|
|
532
954
|
const RED = "#E4002B";
|
|
533
955
|
const TEAL = "#00C7B1";
|
|
@@ -891,7 +1313,8 @@ const controllers = {
|
|
|
891
1313
|
controller,
|
|
892
1314
|
config: config$1,
|
|
893
1315
|
"image-studio": imageStudio,
|
|
894
|
-
templates
|
|
1316
|
+
templates,
|
|
1317
|
+
articles
|
|
895
1318
|
};
|
|
896
1319
|
const middlewares = {};
|
|
897
1320
|
const policies = {};
|
|
@@ -905,12 +1328,20 @@ const ADMIN_ACCESS_POLICIES = [
|
|
|
905
1328
|
];
|
|
906
1329
|
const config = { policies: ADMIN_ACCESS_POLICIES };
|
|
907
1330
|
const admin = [
|
|
908
|
-
{ method: "GET", path: "/
|
|
1331
|
+
{ method: "GET", path: "/articles", handler: "articles.list", config },
|
|
1332
|
+
// Las rutas fijas van antes de `/articles/:documentId` para que no las tome como id.
|
|
1333
|
+
{ method: "POST", path: "/articles/generate", handler: "articles.generate", config },
|
|
1334
|
+
{ method: "POST", path: "/articles/enrich", handler: "articles.enrich", config },
|
|
1335
|
+
{ method: "GET", path: "/articles/base-prompt", handler: "articles.basePrompt", config },
|
|
1336
|
+
{ method: "PUT", path: "/articles/base-prompt", handler: "articles.saveBasePrompt", config },
|
|
1337
|
+
{ method: "DELETE", path: "/articles/base-prompt", handler: "articles.resetBasePrompt", config },
|
|
1338
|
+
{ method: "GET", path: "/articles/:documentId", handler: "articles.detail", config },
|
|
1339
|
+
{ method: "PUT", path: "/articles/:documentId/image", handler: "articles.setImage", config },
|
|
1340
|
+
{ method: "POST", path: "/articles/:documentId/publish", handler: "articles.publish", config },
|
|
1341
|
+
{ method: "POST", path: "/articles/:documentId/schedule", handler: "articles.schedule", config },
|
|
1342
|
+
{ method: "DELETE", path: "/articles/:documentId/schedule", handler: "articles.unschedule", config },
|
|
909
1343
|
{ method: "GET", path: "/categories", handler: "controller.getCategories", config },
|
|
910
|
-
{ method: "GET", path: "/users", handler: "controller.getUsers", config },
|
|
911
1344
|
{ 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
1345
|
{ method: "GET", path: "/image-studio/models", handler: "image-studio.models", config },
|
|
915
1346
|
{ method: "POST", path: "/image-studio/generate", handler: "image-studio.generate", config },
|
|
916
1347
|
{ method: "POST", path: "/image-studio/edit", handler: "image-studio.edit", config },
|
|
@@ -4189,6 +4620,11 @@ const createGeminiClient = ({ serviceAccount, apiKey, allowVertex = true }, Ctor
|
|
|
4189
4620
|
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
4621
|
);
|
|
4191
4622
|
};
|
|
4623
|
+
const postData = (article) => ({
|
|
4624
|
+
titulo: article.titulo ?? "",
|
|
4625
|
+
descripcion: article.descripcion ?? "",
|
|
4626
|
+
keywords: (Array.isArray(article.keywords) ? article.keywords : []).map((k) => k?.name ?? "")
|
|
4627
|
+
});
|
|
4192
4628
|
const service = ({ strapi }) => {
|
|
4193
4629
|
return {
|
|
4194
4630
|
// ───────────────────────────────
|
|
@@ -4208,15 +4644,9 @@ const service = ({ strapi }) => {
|
|
|
4208
4644
|
async geminiConfig() {
|
|
4209
4645
|
return (await this.geminiClient()).ai;
|
|
4210
4646
|
},
|
|
4211
|
-
async getArticulos(sanitizedQueryParams) {
|
|
4212
|
-
return await strapi.entityService.findMany("api::articulo.articulo", sanitizedQueryParams);
|
|
4213
|
-
},
|
|
4214
4647
|
async getCategorias(sanitizedQueryParams) {
|
|
4215
4648
|
return await strapi.entityService.findMany("api::categoria.categoria", sanitizedQueryParams);
|
|
4216
4649
|
},
|
|
4217
|
-
async getUsuarios(sanitizedQueryParams) {
|
|
4218
|
-
return await strapi.documents("plugin::users-permissions.user").findMany(sanitizedQueryParams);
|
|
4219
|
-
},
|
|
4220
4650
|
// ───────────────────────────────
|
|
4221
4651
|
// 📥 Proxy File Download (bypasses browser CORS)
|
|
4222
4652
|
// ───────────────────────────────
|
|
@@ -4286,232 +4716,6 @@ const service = ({ strapi }) => {
|
|
|
4286
4716
|
}
|
|
4287
4717
|
return uploadedFiles[0];
|
|
4288
4718
|
},
|
|
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
4719
|
// 🎞️ Internal Veo Video Generation / Extension Helper
|
|
4516
4720
|
async _callVeoVideoGeneration(promptText, aspectRatio, durationSeconds, sceneRefs, previousVideo) {
|
|
4517
4721
|
const { ai } = await this.geminiClient({ allowVertex: false });
|
|
@@ -4601,7 +4805,7 @@ const service = ({ strapi }) => {
|
|
|
4601
4805
|
// 🌐 Social Media Publishing
|
|
4602
4806
|
// ───────────────────────────────
|
|
4603
4807
|
async publishToLinkedIn(ctx) {
|
|
4604
|
-
const { articleId } = ctx.request.body;
|
|
4808
|
+
const { articleId, mensaje } = ctx.request.body;
|
|
4605
4809
|
const pluginStore = strapi.store({
|
|
4606
4810
|
type: "plugin",
|
|
4607
4811
|
name: "strapi-content-generator-gemini"
|
|
@@ -4616,7 +4820,6 @@ const service = ({ strapi }) => {
|
|
|
4616
4820
|
populate: ["image", "keywords"]
|
|
4617
4821
|
});
|
|
4618
4822
|
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
4823
|
const articleUrl = `https://interware.com.mx/blog/${article.slug}`;
|
|
4621
4824
|
const imageUrl = article.image?.url;
|
|
4622
4825
|
if (!imageUrl) throw new Error("El artículo no tiene imagen.");
|
|
@@ -4651,9 +4854,7 @@ const service = ({ strapi }) => {
|
|
|
4651
4854
|
});
|
|
4652
4855
|
const postBody = {
|
|
4653
4856
|
author: `urn:li:organization:${linkedInOrganizationId}`,
|
|
4654
|
-
commentary:
|
|
4655
|
-
|
|
4656
|
-
${hashtags}`,
|
|
4857
|
+
commentary: typeof mensaje === "string" && mensaje.trim() || defaultPostText(postData(article), "linkedin"),
|
|
4657
4858
|
visibility: "PUBLIC",
|
|
4658
4859
|
distribution: {
|
|
4659
4860
|
feedDistribution: "MAIN_FEED",
|
|
@@ -4691,7 +4892,7 @@ ${hashtags}`,
|
|
|
4691
4892
|
}
|
|
4692
4893
|
},
|
|
4693
4894
|
async publishToFacebook(ctx) {
|
|
4694
|
-
const { articleId } = ctx.request.body;
|
|
4895
|
+
const { articleId, mensaje } = ctx.request.body;
|
|
4695
4896
|
const pluginStore = strapi.store({
|
|
4696
4897
|
type: "plugin",
|
|
4697
4898
|
name: "strapi-content-generator-gemini"
|
|
@@ -4720,16 +4921,8 @@ ${hashtags}`,
|
|
|
4720
4921
|
throw new Error(`Artículo con ID ${articleId} no encontrado.`);
|
|
4721
4922
|
}
|
|
4722
4923
|
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
4924
|
const postBody = {
|
|
4728
|
-
message:
|
|
4729
|
-
|
|
4730
|
-
${article.descripcion}
|
|
4731
|
-
|
|
4732
|
-
${hashtags}`,
|
|
4925
|
+
message: typeof mensaje === "string" && mensaje.trim() || defaultPostText(postData(article), "facebook"),
|
|
4733
4926
|
link: articleUrl,
|
|
4734
4927
|
access_token: facebookAccessToken
|
|
4735
4928
|
};
|
|
@@ -4766,7 +4959,8 @@ ${hashtags}`,
|
|
|
4766
4959
|
const services = {
|
|
4767
4960
|
service,
|
|
4768
4961
|
"image-studio": imageStudio$1,
|
|
4769
|
-
templates: templates$1
|
|
4962
|
+
templates: templates$1,
|
|
4963
|
+
articles: articles$1
|
|
4770
4964
|
};
|
|
4771
4965
|
const index = {
|
|
4772
4966
|
register,
|