diff --git a/config/sites/andebol.net.example.json b/config/sites/andebol.net.example.json new file mode 100644 index 0000000..cfaded6 --- /dev/null +++ b/config/sites/andebol.net.example.json @@ -0,0 +1,24 @@ +{ + "name": "andebol.net", + "writing_tone": "formal", + "audience_level": "general", + "wp_transport": "rest", + "wp_url": "https://andebol.net/wp-json", + "site_domain": "andebol.net", + "user": "writer-bot", + "password": "application-password-from-vault", + "category_default": 1, + "category_infer": "andebol", + "category_map": { + "nacional": 1, + "internacional": 2, + "selecao": 3, + "clubes": 4, + "competicoes": 5, + "resultados": 6 + }, + "status_default": "publish", + "tags_auto": true, + "tags_infer": "andebol", + "lang": "pt" +} diff --git a/package-lock.json b/package-lock.json index cd1c4e5..a91c044 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,7 +8,7 @@ "name": "ai-news-writer", "version": "0.1.0", "dependencies": { - "axios": "^1.7.9", + "axios": "^1.18.0", "cheerio": "^1.0.0", "dotenv": "^16.4.7", "fast-xml-parser": "^5.7.2", @@ -325,6 +325,18 @@ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, "node_modules/agentkeepalive": { "version": "4.6.0", "license": "MIT", @@ -414,11 +426,14 @@ "license": "MIT" }, "node_modules/axios": { - "version": "1.15.2", + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.18.0.tgz", + "integrity": "sha512-E32NzpYKp++W7XRe52rHiXV2ehxmh3wbdgO7MHeFM+vqxLBYHzt0ElkiImtOBxtOmyp0yoC8C6uESVV84Y2/hw==", "license": "MIT", "dependencies": { - "follow-redirects": "^1.15.11", + "follow-redirects": "^1.16.0", "form-data": "^4.0.5", + "https-proxy-agent": "^5.0.1", "proxy-from-env": "^2.1.0" } }, @@ -715,7 +730,6 @@ }, "node_modules/debug": { "version": "4.4.3", - "dev": true, "license": "MIT", "dependencies": { "ms": "^2.1.3" @@ -1241,14 +1255,16 @@ } }, "node_modules/form-data": { - "version": "4.0.5", + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", "license": "MIT", "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", - "hasown": "^2.0.2", - "mime-types": "^2.1.12" + "hasown": "^2.0.4", + "mime-types": "^2.1.35" }, "engines": { "node": ">= 6" @@ -1450,7 +1466,9 @@ } }, "node_modules/hasown": { - "version": "2.0.2", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", "license": "MIT", "dependencies": { "function-bind": "^1.1.2" @@ -1491,6 +1509,19 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "license": "MIT", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/humanize-ms": { "version": "1.2.1", "license": "MIT", @@ -2648,7 +2679,9 @@ "license": "MIT" }, "node_modules/undici": { - "version": "7.24.5", + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.28.0.tgz", + "integrity": "sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==", "license": "MIT", "engines": { "node": ">=20.18.1" diff --git a/package.json b/package.json index 53ca508..401a3d2 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,8 @@ "x:test": "node src/index.js x:test", "ops:check": "bash tools/ops-check.sh", "seed:smoke-verification": "node tools/seed-smoke-verification-article.js", + "wp:backfill-categories": "node tools/backfill-wp-categories.js", + "wp:backfill-meta": "node tools/backfill-wp-meta.js", "deploy:lxc": "bash tools/deploy-lxc.sh", "test": "c8 --reporter=text --reporter=html --reporter=lcov node --test --test-concurrency=1 $(find src -type f -name '*.test.js' | sort | tr '\\n' ' ')", "lint": "eslint src/", @@ -23,7 +25,7 @@ "format": "prettier --write ." }, "dependencies": { - "axios": "^1.7.9", + "axios": "^1.18.0", "cheerio": "^1.0.0", "dotenv": "^16.4.7", "fast-xml-parser": "^5.7.2", @@ -42,5 +44,9 @@ }, "engines": { "node": ">=20" + }, + "overrides": { + "form-data": ">=4.0.6", + "undici": "^7.28.0" } } diff --git a/src/pipeline/persist-generated-article.js b/src/pipeline/persist-generated-article.js index bb0d8fd..1c551d7 100644 --- a/src/pipeline/persist-generated-article.js +++ b/src/pipeline/persist-generated-article.js @@ -5,6 +5,7 @@ const { metrics } = require('../monitoring/metrics'); const { scoreArticleQuality } = require('./quality-scorer'); const { verifyArticle } = require('../research'); const { appendArticleRecord } = require('../store/article-log'); +const { sanitizeArticleMeta } = require('../publisher/article-meta'); const { serializeVerificationReport } = require('../store/verification-report'); function getQualityThresholds() { @@ -31,8 +32,9 @@ function getQualityThresholds() { */ async function persistGeneratedArticle(article, site, mode, wp_link, voice = {}) { try { + const normalized = sanitizeArticleMeta(article, site || {}); const thresholds = getQualityThresholds(); - const quality = scoreArticleQuality(article, { + const quality = scoreArticleQuality(normalized, { minWordCount: thresholds.minWordCount, maxReadabilityGrade: thresholds.maxReadabilityGrade }); @@ -46,7 +48,7 @@ async function persistGeneratedArticle(article, site, mode, wp_link, voice = {}) let verification_report = null; try { - const rawV = await verifyArticle(article); + const rawV = await verifyArticle(normalized); verification_report = serializeVerificationReport(rawV); } catch (vErr) { logger.warn(`verification orchestration failed (non-fatal): ${vErr.message}`); @@ -59,10 +61,12 @@ async function persistGeneratedArticle(article, site, mode, wp_link, voice = {}) } appendArticleRecord({ - title: article.title, - subtitle: article.subtitle, - slug: article.slug, - summary: article.summary, + title: normalized.title, + subtitle: normalized.subtitle, + slug: normalized.slug, + summary: normalized.summary, + tags: normalized.tags, + category: normalized.category || null, wp_link: wp_link || null, site_name: site?.name || 'default', mode, diff --git a/src/publisher/article-meta.js b/src/publisher/article-meta.js new file mode 100644 index 0000000..e9acd1d --- /dev/null +++ b/src/publisher/article-meta.js @@ -0,0 +1,253 @@ +'use strict'; + +const ANDEBOL_ENTITY_RULES = [ + { tag: 'FC Porto', pattern: /\b(?:fc porto|f\.?\s*c\.?\s*porto)\b/i }, + { tag: 'Benfica', pattern: /\b(?:sl benfica|benfica)\b/i }, + { tag: 'Sporting CP', pattern: /\b(?:sporting cp|sporting)\b/i }, + { tag: 'SC Braga', pattern: /\b(?:sc braga|vitória\s+sc)\b/i }, + { tag: 'Seleção Nacional', pattern: /\bseleç(?:ão|ões)\s+nacionais?\b/i }, + { tag: 'Portugal', pattern: /\bportugal\b/i }, + { tag: 'Liga dos Campeões', pattern: /\bliga\s+dos\s+campeões\b/i }, + { tag: 'Taça de Portugal', pattern: /\btaça\s+de\s+portugal\b/i }, + { tag: 'Campeonato Nacional', pattern: /\bcampeonato\s+nacional\b/i }, + { tag: 'EHF', pattern: /\behf\b/i }, + { tag: 'IHF', pattern: /\bihf\b/i }, + { tag: 'Andebol', pattern: /\bandebol\b/i } +]; + +const SKIP_NAME_FRAGMENTS = new Set([ + 'federação de', 'federação portuguesa', 'european portuguese', 'source material', + 'fonte original', 'fonte federação' +]); + +function foldAccents(value) { + return String(value || '') + .normalize('NFD') + .replace(/\p{M}/gu, ''); +} + +function plainTextFromHtml(html) { + return String(html || '') + .replace(/<[^>]+>/g, ' ') + .replace(/\[[^\]]+\]/g, ' ') + .replace(/\s+/g, ' ') + .trim(); +} + +function articleCorpus(article) { + return plainTextFromHtml([ + article?.title, + article?.subtitle, + article?.summary, + article?.excerpt, + article?.body, + article?.content + ].filter(Boolean).join(' ')); +} + +function tagMentionedInCorpus(tag, corpus) { + const normalizedTag = foldAccents(tag).toLowerCase().trim(); + if (normalizedTag.length < 2) { + return false; + } + const normalizedCorpus = foldAccents(corpus).toLowerCase(); + return normalizedCorpus.includes(normalizedTag); +} + +/** + * Keep only tags that literally appear in the published article text. + * + * @param {string[]} tags + * @param {string} corpus + * @param {number} [maxTags] + * @returns {string[]} + */ +function sanitizeTags(tags, corpus, maxTags = 8) { + if (!Array.isArray(tags)) { + return []; + } + const seen = new Set(); + const out = []; + for (const raw of tags) { + const tag = String(raw || '').trim(); + if (!tag || tag.length > 60) { + continue; + } + const key = foldAccents(tag).toLowerCase(); + if (seen.has(key)) { + continue; + } + if (tagMentionedInCorpus(tag, corpus)) { + seen.add(key); + out.push(tag); + } + } + return out.slice(0, maxTags); +} + +/** + * Extract editorial tags from article text (teams, competitions, people mentioned). + * + * @param {Object} article + * @returns {string[]} + */ +function inferAndebolTags(article) { + const corpus = articleCorpus(article); + if (!corpus) { + return ['Andebol']; + } + + const seen = new Set(); + const tags = []; + + function pushTag(tag) { + const trimmed = String(tag || '').trim(); + if (!trimmed) { + return; + } + const key = foldAccents(trimmed).toLowerCase(); + if (seen.has(key)) { + return; + } + seen.add(key); + tags.push(trimmed); + } + + for (const rule of ANDEBOL_ENTITY_RULES) { + if (rule.pattern.test(corpus)) { + pushTag(rule.tag); + } + } + + const namePattern = /\b([A-ZÁÉÍÓÚÀÂÊÔÃÕÇ][a-záéíóúàâêôãõç]+(?:\s+(?:de|da|do|dos|das|e)\s+)?(?:[A-ZÁÉÍÓÚÀÂÊÔÃÕÇ][a-záéíóúàâêôãõç]+)+)\b/g; + let match; + while ((match = namePattern.exec(corpus)) !== null) { + const candidate = match[1].trim(); + const lower = foldAccents(candidate).toLowerCase(); + if (candidate.split(/\s+/).length < 2 || candidate.length > 40) { + continue; + } + if ([...SKIP_NAME_FRAGMENTS].some((frag) => lower.includes(frag))) { + continue; + } + if (tagMentionedInCorpus(candidate, corpus)) { + pushTag(candidate); + } + } + + if (tags.length === 0) { + pushTag('Andebol'); + } + + return tags.slice(0, 8); +} + +function truncateAtWord(text, maxLen) { + const trimmed = String(text || '').trim(); + if (trimmed.length <= maxLen) { + return trimmed; + } + const slice = trimmed.slice(0, maxLen); + const lastSpace = slice.lastIndexOf(' '); + if (lastSpace > maxLen * 0.6) { + return `${slice.slice(0, lastSpace).trim()}…`; + } + return `${slice.trim()}…`; +} + +function deriveSeoTitle(article) { + const title = plainTextFromHtml(article?.seo_title || article?.title || ''); + return truncateAtWord(title, 60); +} + +function seoDescriptionGrounded(text, corpus) { + const plain = plainTextFromHtml(text); + if (!plain) { + return false; + } + const namePattern = /\b([A-ZÁÉÍÓÚÀÂÊÔÃÕÇ][a-záéíóúàâêôãõç]+(?:\s+[A-ZÁÉÍÓÚÀÂÊÔÃÕÇ][a-záéíóúàâêôãõç]+)+)\b/g; + let match; + while ((match = namePattern.exec(plain)) !== null) { + const candidate = match[1].trim(); + if (candidate.split(/\s+/).length >= 2 && !tagMentionedInCorpus(candidate, corpus)) { + return false; + } + } + return true; +} + +function deriveSeoDescription(article) { + const corpus = articleCorpus(article); + const candidates = [ + article?.summary, + article?.excerpt, + plainTextFromHtml(article?.body || article?.content || '').slice(0, 220), + article?.seo_description + ]; + for (const candidate of candidates) { + const text = plainTextFromHtml(candidate); + if (!text || text.length < 40) { + continue; + } + if (!seoDescriptionGrounded(text, corpus)) { + continue; + } + return truncateAtWord(text, 155); + } + return truncateAtWord(corpus.slice(0, 155), 155); +} + +function deriveFocusKeyword(article) { + const title = plainTextFromHtml(article?.title || ''); + const words = title + .split(/\s+/) + .map((w) => w.replace(/[^a-záéíóúàâêôãõç0-9-]/gi, '')) + .filter((w) => w.length > 3); + if (words.length === 0) { + return 'andebol'; + } + const corpus = articleCorpus(article); + for (const word of words) { + if (tagMentionedInCorpus(word, corpus)) { + return word.toLowerCase(); + } + } + return words[0].toLowerCase(); +} + +/** + * Sanitize tags and SEO fields so meta-info only references on-page content. + * + * @param {Object} article + * @param {{ tags_infer?: string }} [siteConfig] + * @returns {Object} shallow copy with sanitized meta fields + */ +function sanitizeArticleMeta(article, siteConfig = {}) { + const next = { ...article }; + const corpus = articleCorpus(article); + const inferMode = siteConfig?.tags_infer || siteConfig?.category_infer; + + let tags = sanitizeTags(next.tags, corpus); + if (tags.length === 0 && (inferMode === 'andebol' || siteConfig?.tags_auto)) { + tags = inferAndebolTags(next); + } + + next.tags = tags; + next.seo_title = deriveSeoTitle(next); + next.seo_description = deriveSeoDescription(next); + next.focus_keyword = deriveFocusKeyword(next); + return next; +} + +module.exports = { + sanitizeArticleMeta, + sanitizeTags, + inferAndebolTags, + deriveSeoTitle, + deriveSeoDescription, + deriveFocusKeyword, + tagMentionedInCorpus, + plainTextFromHtml, + articleCorpus, + ANDEBOL_ENTITY_RULES +}; diff --git a/src/publisher/article-meta.test.js b/src/publisher/article-meta.test.js new file mode 100644 index 0000000..fece91e --- /dev/null +++ b/src/publisher/article-meta.test.js @@ -0,0 +1,52 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const test = require('node:test'); +const { + sanitizeTags, + inferAndebolTags, + sanitizeArticleMeta +} = require('./article-meta'); + +test('sanitizeTags drops tags not present in article body', () => { + const corpus = 'O FC Porto venceu o Benfica por 28-25 na Liga dos Campeões.'; + const tags = sanitizeTags(['FC Porto', 'João Silva', 'Benfica', 'Cristiano Ronaldo'], corpus); + assert.deepEqual(tags, ['FC Porto', 'Benfica']); +}); + +test('inferAndebolTags extracts teams and competitions from text', () => { + const tags = inferAndebolTags({ + title: 'FC Porto vence Benfica na Liga dos Campeões', + body: '
O FC Porto confirmou a vitória sobre o Benfica na Liga dos Campeões.
' + }); + assert.ok(tags.includes('FC Porto')); + assert.ok(tags.includes('Benfica')); + assert.ok(tags.includes('Liga dos Campeões')); +}); + +test('sanitizeArticleMeta removes hallucinated player tags', () => { + const result = sanitizeArticleMeta({ + title: 'Festa do Andebol regressa a Lagoa', + body: 'A Festa do Andebol junta seleções regionais sub-14 em Lagoa.
', + summary: 'Evento desportivo reunirá jovens atletas na região.', + tags: ['Marta Costa', 'João Rodrigues', 'Andebol'], + seo_description: 'Marta Costa brilhou na competição internacional' + }, { tags_infer: 'andebol', tags_auto: true }); + + assert.ok(!result.tags.includes('Marta Costa')); + assert.ok(!result.tags.includes('João Rodrigues')); + assert.ok(result.tags.includes('Andebol')); + assert.ok(!result.seo_description.includes('Marta Costa')); +}); + +test('sanitizeArticleMeta keeps valid LLM tags', () => { + const result = sanitizeArticleMeta({ + title: 'Carlos Ribeiro renova com Sporting CP', + body: 'Carlos Ribeiro assinou renovação com o Sporting CP.
', + tags: ['Carlos Ribeiro', 'Sporting CP', 'Pedro Santos'] + }, { tags_auto: true }); + + assert.ok(result.tags.includes('Carlos Ribeiro')); + assert.ok(result.tags.includes('Sporting CP')); + assert.equal(result.tags.includes('Pedro Santos'), false); +}); diff --git a/src/publisher/category-infer.js b/src/publisher/category-infer.js new file mode 100644 index 0000000..e90cb6f --- /dev/null +++ b/src/publisher/category-infer.js @@ -0,0 +1,158 @@ +'use strict'; + +const INTERNATIONAL_SOURCE_HOSTS = new Set([ + 'ihf.info', + 'www.ihf.info', + 'eurohandball.com', + 'www.eurohandball.com', + 'handball-planet.com', + 'www.handball-planet.com', + 'feeds.bbci.co.uk', + 'bbc.co.uk', + 'bbci.co.uk' +]); + +const RULES = [ + { + slug: 'selecao', + patterns: [ + /\bseleç(?:ão|ões)\s+nacionais?\b/i, + /\bseleção\s+portuguesa\b/i, + /\btorneio\s+(?:4|quatro)\s+naç(?:ões|oes)\b/i, + /\bportugal\s+(?:vence|perde|empata|enfrenta|defronta|soma|regista)\b/i, + /\bnational team\b/i + ] + }, + { + slug: 'resultados', + patterns: [ + /\bresultado(?:s)?\b/i, + /\b(?:venceu|vence|derrota|derrotado|empate|empatou|goleada)\b/i, + /\b\d+\s*[-–]\s*\d+\b/, + /\b(?:final|semi-?final|meias-?finais)\s+(?:termina|fica|ficou)\b/i + ] + }, + { + slug: 'competicoes', + patterns: [ + /\b(?:taça|taca|campeonato|liga|competiç(?:ão|ões)|competicoes)\b/i, + /\b(?:play-?offs?|wild card|champions league|european masters|mundial|world championship)\b/i, + /\b(?:ehf|ihf)\s+(?:cup|cl|final)\b/i + ] + }, + { + slug: 'clubes', + patterns: [ + /\b(?:fc porto|f\.?\s*c\.?\s*porto|porto)\b/i, + /\b(?:sl benfica|benfica)\b/i, + /\b(?:sporting cp|sporting)\b/i, + /\b(?:sc braga|vitória|marítimo|madeira andebol)\b/i + ] + }, + { + slug: 'internacional', + patterns: [ + /\b(?:internacional|international|mundial|world championship|euro(?:pean)?)\b/i, + /\b(?:ihf|eurohandball|handball planet)\b/i + ] + } +]; + +const DEFAULT_SLUG = 'nacional'; + +function hostFromUrl(url) { + if (!url || typeof url !== 'string') { + return ''; + } + try { + return new URL(url).hostname.toLowerCase(); + } catch { + return ''; + } +} + +function firstSourceHost(sources) { + if (!Array.isArray(sources) || sources.length === 0) { + return ''; + } + for (const src of sources) { + const host = hostFromUrl(src.url || src.link || ''); + if (host) { + return host; + } + } + return ''; +} + +function isInternationalSource(sourceUrl, sources) { + const host = hostFromUrl(sourceUrl) || firstSourceHost(sources); + if (!host) { + return false; + } + if (INTERNATIONAL_SOURCE_HOSTS.has(host)) { + return true; + } + return host.endsWith('.info') && host.includes('handball'); +} + +function normalizeText(parts) { + return parts + .filter((p) => typeof p === 'string' && p.trim().length > 0) + .join(' ') + .replace(/\s+/g, ' ') + .trim(); +} + +/** + * Infer editorial category slug for andebol.net-style sites. + * + * @param {Object} params + * @param {string} [params.title] + * @param {string} [params.body] + * @param {string} [params.summary] + * @param {string} [params.excerpt] + * @param {string} [params.sourceUrl] + * @param {Array<{url?: string, link?: string}>} [params.sources] + * @param {string} [params.sourceCategory] - RSS / pipeline category hint + * @returns {string} Category slug (nacional, internacional, selecao, clubes, competicoes, resultados) + */ +function inferAndebolCategorySlug({ + title = '', + body = '', + summary = '', + excerpt = '', + sourceUrl = '', + sources = [], + sourceCategory = '' +} = {}) { + const text = normalizeText([title, summary, excerpt, body]); + + if (sourceCategory && typeof sourceCategory === 'string') { + const hint = sourceCategory.trim().toLowerCase(); + if (['nacional', 'internacional', 'selecao', 'clubes', 'competicoes', 'resultados'].includes(hint)) { + return hint; + } + if (hint === 'international' || hint === 'en') { + return 'internacional'; + } + } + + if (isInternationalSource(sourceUrl, sources) && !/\bportugal\b/i.test(text)) { + return 'internacional'; + } + + for (const rule of RULES) { + if (rule.patterns.some((re) => re.test(text))) { + return rule.slug; + } + } + + return DEFAULT_SLUG; +} + +module.exports = { + inferAndebolCategorySlug, + DEFAULT_SLUG, + INTERNATIONAL_SOURCE_HOSTS, + RULES +}; diff --git a/src/publisher/category-infer.test.js b/src/publisher/category-infer.test.js new file mode 100644 index 0000000..6be240d --- /dev/null +++ b/src/publisher/category-infer.test.js @@ -0,0 +1,55 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const test = require('node:test'); +const { inferAndebolCategorySlug } = require('../publisher/category-infer'); + +test('inferAndebolCategorySlug — seleção nacional', () => { + const slug = inferAndebolCategorySlug({ + title: 'Seleção Nacional vence França no Torneio 4 Nações', + summary: 'Portugal soma primeira vitória na competição.' + }); + assert.equal(slug, 'selecao'); +}); + +test('inferAndebolCategorySlug — clubes', () => { + const slug = inferAndebolCategorySlug({ + title: 'Carlos Martingo é o novo treinador de andebol do FC Porto', + summary: 'Clube azul e branco anuncia contratação.' + }); + assert.equal(slug, 'clubes'); +}); + +test('inferAndebolCategorySlug — competicoes', () => { + const slug = inferAndebolCategorySlug({ + title: 'Liga dos Campeões 2026/27: 27 clubes registados', + summary: 'EHF confirma lista de participantes.' + }); + assert.equal(slug, 'competicoes'); +}); + +test('inferAndebolCategorySlug — internacional from source host', () => { + const slug = inferAndebolCategorySlug({ + title: 'EHF announces new format for club competitions', + summary: 'Changes apply from next season.', + sourceUrl: 'https://www.eurohandball.com/en/news/123' + }); + assert.equal(slug, 'internacional'); +}); + +test('inferAndebolCategorySlug — nacional default for PT domestic', () => { + const slug = inferAndebolCategorySlug({ + title: 'Festa do Andebol regressa a Lagoa', + summary: 'Evento junta seleções regionais sub-14.', + sourceUrl: 'https://portal.fpa.pt/2026/06/festa-do-andebol/' + }); + assert.equal(slug, 'nacional'); +}); + +test('inferAndebolCategorySlug — honors explicit sourceCategory hint', () => { + const slug = inferAndebolCategorySlug({ + title: 'Generic headline', + sourceCategory: 'resultados' + }); + assert.equal(slug, 'resultados'); +}); diff --git a/src/publisher/wordpress.js b/src/publisher/wordpress.js index 1011cc1..ac6849c 100644 --- a/src/publisher/wordpress.js +++ b/src/publisher/wordpress.js @@ -7,6 +7,8 @@ const HttpRetryConfig = require('../util/http-retry-config'); const { resolveWpTransport } = require('./wp-transport'); const { publishArticleXmlRpc, testConnectionXmlRpc } = require('./xmlrpc-client'); const { resolveWpStatus } = require('./wp-publish-hours'); +const { resolvePostCategoryIds } = require('./wp-categories'); +const { sanitizeArticleMeta } = require('./article-meta'); const { metrics } = require('../monitoring/metrics'); function wpRestDraftFallbackEnabled() { @@ -34,10 +36,11 @@ function wpOriginForLogs(wp_url) { * @returns {Promise