Files
ai-news-writer/tools/backfill-wp-categories.js
Xika 478d82b070
ai-news-writer-ci / test (pull_request) Failing after 34s
feat(publisher): BIT-25574 category inference + WP resolver + backfill tool
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)
2026-06-18 16:10:57 +00:00

133 lines
4.5 KiB
JavaScript

#!/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);
});