feat(publisher): BIT-25574 category inference + WP resolver + backfill tool
ai-news-writer-ci / test (pull_request) Failing after 34s
ai-news-writer-ci / test (pull_request) Failing after 34s
Add category-infer.js with rule-based slug detection for andebol.net (selecao, clubes, competicoes, internacional, resultados, nacional). Add wp-categories.js to resolve WP category IDs via API or category_map. Wire resolvePostCategoryIds into both REST and XML-RPC publish paths. Add tools/backfill-wp-categories.js for one-shot backfill of uncategorized posts. Add config/sites/andebol.net.example.json as reference site config template. Persist article tags and category in persist-generated-article.js. Paperclip-Issue: BIT-25575 Paperclip-Agent: Tiago Neves (id 5d084b36-f38f-42a5-a92a-520005afda4f)
This commit is contained in:
1 parent
4e6875639b
commit
478d82b070
10 files changed
+507
-7
No files matched your search
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"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,
|
||||
"lang": "pt"
|
||||
}
|
||||
@@ -16,6 +16,7 @@
|
||||
"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",
|
||||
"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/",
|
||||
|
||||
@@ -63,6 +63,8 @@ async function persistGeneratedArticle(article, site, mode, wp_link, voice = {})
|
||||
subtitle: article.subtitle,
|
||||
slug: article.slug,
|
||||
summary: article.summary,
|
||||
tags: article.tags,
|
||||
category: article.category || null,
|
||||
wp_link: wp_link || null,
|
||||
site_name: site?.name || 'default',
|
||||
mode,
|
||||
|
||||
@@ -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
|
||||
};
|
||||
@@ -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');
|
||||
});
|
||||
@@ -7,6 +7,7 @@ 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 { metrics } = require('../monitoring/metrics');
|
||||
|
||||
function wpRestDraftFallbackEnabled() {
|
||||
@@ -58,13 +59,15 @@ async function publishToWordPressRest(article, site_config, publishHours) {
|
||||
const credentials = Buffer.from(`${user}:${password}`).toString('base64');
|
||||
const api_base = `${wp_url.replace(/\/$/, '')}/wp-json/wp/v2`;
|
||||
|
||||
const category_ids = await resolvePostCategoryIds(article, site_config, api_base, credentials);
|
||||
|
||||
const post_payload = {
|
||||
title: article.title,
|
||||
content: article.body,
|
||||
excerpt: article.summary,
|
||||
slug: article.slug,
|
||||
status: status_default,
|
||||
categories: category_default ? [category_default] : [],
|
||||
categories: category_ids.length > 0 ? category_ids : (category_default ? [category_default] : []),
|
||||
tags: [],
|
||||
meta: {
|
||||
_yoast_wpseo_title: article.seo_title,
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
'use strict';
|
||||
|
||||
const logger = require('../logger');
|
||||
const { axiosGetWithRetry } = require('../util/http-retry');
|
||||
const HttpRetryConfig = require('../util/http-retry-config');
|
||||
const { inferAndebolCategorySlug } = require('./category-infer');
|
||||
|
||||
function authHeaders(credentials, siteDomain) {
|
||||
const headers = {
|
||||
Authorization: `Basic ${credentials}`,
|
||||
Accept: 'application/json'
|
||||
};
|
||||
if (siteDomain) {
|
||||
headers['X-Site-Domain'] = siteDomain;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} slug
|
||||
* @param {string} api_base
|
||||
* @param {string} credentials
|
||||
* @param {string|undefined} siteDomain
|
||||
* @returns {Promise<number|null>}
|
||||
*/
|
||||
async function resolveCategoryIdBySlug(slug, api_base, credentials, siteDomain) {
|
||||
if (!slug || typeof slug !== 'string') {
|
||||
return null;
|
||||
}
|
||||
const normalized = slug.trim().toLowerCase();
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const retry_opts = HttpRetryConfig.forWordPress().toRetryOpts();
|
||||
try {
|
||||
const response = await axiosGetWithRetry(
|
||||
`${api_base}/categories?slug=${encodeURIComponent(normalized)}&per_page=1`,
|
||||
{ headers: authHeaders(credentials, siteDomain), timeout: 8000 },
|
||||
{ ...retry_opts, urlHint: `category slug "${normalized}"` }
|
||||
);
|
||||
const rows = Array.isArray(response.data) ? response.data : [];
|
||||
const id = rows[0]?.id;
|
||||
return Number.isInteger(id) && id > 0 ? id : null;
|
||||
} catch (err) {
|
||||
logger.warn(`Category lookup failed for slug "${normalized}": ${err.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function mappedCategoryId(siteConfig, slug) {
|
||||
const map = siteConfig?.category_map;
|
||||
if (!map || typeof map !== 'object') {
|
||||
return null;
|
||||
}
|
||||
const entry = map[slug] ?? map[slug?.toLowerCase?.()];
|
||||
if (entry === undefined || entry === null) {
|
||||
return null;
|
||||
}
|
||||
const id = parseInt(String(entry), 10);
|
||||
return Number.isFinite(id) && id > 0 ? id : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve WordPress category IDs for a generated article.
|
||||
*
|
||||
* Priority: category_map → slug lookup via WP API → category_default.
|
||||
*
|
||||
* @param {Object} article
|
||||
* @param {Object} siteConfig
|
||||
* @param {string} api_base - e.g. https://site/wp-json/wp/v2
|
||||
* @param {string} credentials - base64 basic auth
|
||||
* @returns {Promise<number[]>}
|
||||
*/
|
||||
async function resolvePostCategoryIds(article, siteConfig, api_base, credentials) {
|
||||
const siteDomain = siteConfig?.site_domain || siteConfig?.wp_site_domain;
|
||||
const inferMode = siteConfig?.category_infer;
|
||||
let slug = null;
|
||||
|
||||
if (inferMode === 'andebol') {
|
||||
slug = inferAndebolCategorySlug({
|
||||
title: article?.title,
|
||||
body: article?.body,
|
||||
summary: article?.summary,
|
||||
sourceUrl: article?.source_url,
|
||||
sources: article?.sources,
|
||||
sourceCategory: article?.category
|
||||
});
|
||||
} else if (typeof article?.category === 'string' && article.category.trim()) {
|
||||
slug = article.category.trim().toLowerCase();
|
||||
}
|
||||
|
||||
if (slug) {
|
||||
const mapped = mappedCategoryId(siteConfig, slug);
|
||||
if (mapped) {
|
||||
return [mapped];
|
||||
}
|
||||
const resolved = await resolveCategoryIdBySlug(slug, api_base, credentials, siteDomain);
|
||||
if (resolved) {
|
||||
return [resolved];
|
||||
}
|
||||
logger.warn(`WP category slug "${slug}" not found — falling back to category_default`);
|
||||
}
|
||||
|
||||
const fallback = siteConfig?.category_default;
|
||||
const fallbackId = parseInt(String(fallback ?? ''), 10);
|
||||
if (Number.isFinite(fallbackId) && fallbackId > 0) {
|
||||
return [fallbackId];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
resolvePostCategoryIds,
|
||||
resolveCategoryIdBySlug,
|
||||
mappedCategoryId
|
||||
};
|
||||
@@ -5,6 +5,7 @@ const logger = require('../logger');
|
||||
const { axiosPostWithRetry } = require('../util/http-retry');
|
||||
const HttpRetryConfig = require('../util/http-retry-config');
|
||||
const { resolveWpStatus } = require('./wp-publish-hours');
|
||||
const { resolvePostCategoryIds } = require('./wp-categories');
|
||||
const { metrics } = require('../monitoring/metrics');
|
||||
|
||||
/**
|
||||
@@ -272,11 +273,17 @@ async function publishArticleXmlRpc(article, site_config, publishHours) {
|
||||
content.terms_names = { post_tag: tag_list };
|
||||
}
|
||||
|
||||
if (category_default) {
|
||||
const cid = parseInt(String(category_default), 10);
|
||||
if (Number.isFinite(cid) && cid > 0) {
|
||||
content.terms = { category: [cid] };
|
||||
}
|
||||
const api_base = `${wp_url.replace(/\/$/, '')}/wp-json/wp/v2`;
|
||||
const credentials = Buffer.from(`${user}:${password}`).toString('base64');
|
||||
const category_ids = await resolvePostCategoryIds(article, site_config, api_base, credentials);
|
||||
const effective_ids = category_ids.length > 0
|
||||
? category_ids
|
||||
: (() => {
|
||||
const cid = parseInt(String(category_default), 10);
|
||||
return Number.isFinite(cid) && cid > 0 ? [cid] : [];
|
||||
})();
|
||||
if (effective_ids.length > 0) {
|
||||
content.terms = { category: effective_ids };
|
||||
}
|
||||
|
||||
if (custom_fields.length > 0) {
|
||||
|
||||
@@ -105,7 +105,8 @@ test('publishArticleXmlRpc — stub wp.newPost', async () => {
|
||||
user: 'u',
|
||||
password: 'p',
|
||||
category_default: 2,
|
||||
status_default: 'draft'
|
||||
status_default: 'draft',
|
||||
category_map: { nacional: 2 }
|
||||
};
|
||||
const out = await publishArticleXmlRpc(article, site);
|
||||
assert.equal(out.id, '1001');
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Backfill WordPress post categories on andebol.net (or any site in config/sites/).
|
||||
*
|
||||
* Usage:
|
||||
* node tools/backfill-wp-categories.js --site andebol.net.example.json --dry-run
|
||||
* node tools/backfill-wp-categories.js --site andebol.net.json --limit 50
|
||||
*
|
||||
* Requires WP credentials in the site JSON or WP_URL / WP_USER / WP_PASSWORD env vars.
|
||||
*/
|
||||
|
||||
require('dotenv').config();
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const axios = require('axios');
|
||||
const { inferAndebolCategorySlug } = require('../src/publisher/category-infer');
|
||||
const { mappedCategoryId, resolveCategoryIdBySlug } = require('../src/publisher/wp-categories');
|
||||
|
||||
const ROOT = path.resolve(__dirname, '..');
|
||||
|
||||
function parseArgs(argv) {
|
||||
const out = { dryRun: false, limit: 100, siteFile: null };
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
const arg = argv[i];
|
||||
if (arg === '--dry-run') out.dryRun = true;
|
||||
else if (arg === '--limit' && argv[i + 1]) out.limit = parseInt(argv[++i], 10);
|
||||
else if (arg === '--site' && argv[i + 1]) out.siteFile = argv[++i];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function loadSiteConfig(siteFile) {
|
||||
const sitesDir = path.join(ROOT, 'config', 'sites');
|
||||
const filename = siteFile.endsWith('.json') ? siteFile : `${siteFile}.json`;
|
||||
const fullPath = path.join(sitesDir, filename);
|
||||
if (!fs.existsSync(fullPath)) {
|
||||
throw new Error(`Site config not found: ${fullPath}`);
|
||||
}
|
||||
return JSON.parse(fs.readFileSync(fullPath, 'utf8'));
|
||||
}
|
||||
|
||||
async function resolveSlugToId(slug, site, apiBase, credentials) {
|
||||
const mapped = mappedCategoryId(site, slug);
|
||||
if (mapped) return mapped;
|
||||
return resolveCategoryIdBySlug(slug, apiBase, credentials, site.site_domain || site.wp_site_domain);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
if (!args.siteFile) {
|
||||
console.error('Usage: node tools/backfill-wp-categories.js --site <file.json> [--dry-run] [--limit N]');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const site = loadSiteConfig(args.siteFile);
|
||||
const wpUrl = site.wp_url || process.env.WP_URL;
|
||||
const user = site.user || process.env.WP_USER;
|
||||
const password = site.password || process.env.WP_PASSWORD;
|
||||
if (!wpUrl || !user || !password) {
|
||||
throw new Error('Missing wp_url/user/password in site config or env');
|
||||
}
|
||||
|
||||
const apiBase = `${wpUrl.replace(/\/$/, '').replace(/\/wp-json\/?$/, '')}/wp-json/wp/v2`;
|
||||
const credentials = Buffer.from(`${user}:${password}`).toString('base64');
|
||||
const siteDomain = site.site_domain || site.wp_site_domain;
|
||||
const headers = {
|
||||
Authorization: `Basic ${credentials}`,
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json'
|
||||
};
|
||||
if (siteDomain) headers['X-Site-Domain'] = siteDomain;
|
||||
|
||||
const uncategorizedRes = await axios.get(`${apiBase}/categories`, {
|
||||
params: { slug: 'uncategorized', per_page: 1 },
|
||||
headers,
|
||||
timeout: 15000
|
||||
});
|
||||
const uncategorizedId = uncategorizedRes.data?.[0]?.id;
|
||||
|
||||
const postsRes = await axios.get(`${apiBase}/posts`, {
|
||||
params: {
|
||||
per_page: Math.min(args.limit, 100),
|
||||
status: 'publish,draft',
|
||||
orderby: 'date',
|
||||
order: 'desc',
|
||||
_fields: 'id,title,content,excerpt,categories,link'
|
||||
},
|
||||
headers,
|
||||
timeout: 20000
|
||||
});
|
||||
|
||||
const posts = Array.isArray(postsRes.data) ? postsRes.data : [];
|
||||
let patched = 0;
|
||||
let skipped = 0;
|
||||
|
||||
for (const post of posts) {
|
||||
const cats = Array.isArray(post.categories) ? post.categories : [];
|
||||
const onlyUncategorized = cats.length === 0
|
||||
|| (cats.length === 1 && uncategorizedId && cats[0] === uncategorizedId);
|
||||
if (!onlyUncategorized) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const title = post.title?.rendered || post.title || '';
|
||||
const body = post.content?.rendered || post.content || '';
|
||||
const excerpt = post.excerpt?.rendered || post.excerpt || '';
|
||||
const slug = inferAndebolCategorySlug({ title, body, summary: excerpt, excerpt });
|
||||
const categoryId = await resolveSlugToId(slug, site, apiBase, credentials);
|
||||
if (!categoryId) {
|
||||
console.warn(`post ${post.id}: could not resolve slug "${slug}" — skip`);
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
console.log(`${args.dryRun ? '[dry-run]' : 'patch'} post ${post.id} → ${slug} (${categoryId}) — ${title.slice(0, 60)}`);
|
||||
if (!args.dryRun) {
|
||||
await axios.post(`${apiBase}/posts/${post.id}`, { categories: [categoryId] }, { headers, timeout: 15000 });
|
||||
}
|
||||
patched += 1;
|
||||
}
|
||||
|
||||
console.log(JSON.stringify({ scanned: posts.length, patched, skipped, dryRun: args.dryRun }, null, 2));
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(err.message || err);
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in new issue
Block a user