import React, { useCallback, useEffect, useRef, useState } from 'react'; import { __, _n, sprintf } from '@wordpress/i18n'; import { api } from '../api'; import { Card, Button, Badge, Notice, Bar, Switch, PageState, Panel, SectionTitle } from '../components/ui'; import rkSvg from '../icons/vendors/rk.svg?raw'; import aioSvg from '../icons/vendors/aio.svg?raw'; import tsfSvg from '../icons/vendors/seo-framework.svg?raw'; import suSvg from '../icons/vendors/seo-ultimate.svg?raw'; import slimSvg from '../icons/vendors/slim-seo.svg?raw'; import yoastSvg from '../icons/vendors/yoast.svg?raw'; import seopressSvg from '../icons/vendors/seopress.svg?raw'; /** * The vendor mark for a migration card. Real artwork where we have it, * bundled inline so the admin stays a single file; a tinted initial tile * for the rest — never an empty square. */ export function VendorIcon({ id, label }) { const art = { rankmath: rkSvg, aioseo: aioSvg, seoframework: tsfSvg, seoultimate: suSvg, slimseo: slimSvg, yoast: yoastSvg, seopress: seopressSvg }[id]; if (art) { return ( ); } const tint = { yoast: '#a4286a', seopress: '#5b43d6', smartcrawl: '#d63638', wpmetaseo: '#c150ba', squirrly: '#0e7c5a', jetpack: '#069e08', genesis: '#ff5000', woocommerce: '#7f54b3', redirection: '#2271b1' }[id] || 'var(--ars-brand)'; return ( {(label || '?').charAt(0)} ); } const num = (n) => Number(n || 0).toLocaleString(); const when = (ts) => (ts ? new Date(ts * 1000).toLocaleString() : ''); /** What a source holds, in one line the reader can check. */ function sourceSummary(s) { const parts = []; if (s.posts) parts.push(sprintf(_n('%s page', '%s pages', s.posts, 'ai-rank-suite'), num(s.posts))); if (s.terms) parts.push(sprintf(_n('%s term', '%s terms', s.terms, 'ai-rank-suite'), num(s.terms))); if (s.redirects) parts.push(sprintf(_n('%s redirect', '%s redirects', s.redirects, 'ai-rank-suite'), num(s.redirects))); if (s.settings) parts.push(__('site-wide settings', 'ai-rank-suite')); return parts.join(' · '); } /** * The fields a run wrote, named rather than counted — and pluralised, because * "1 titles" is the kind of detail that makes a report look machine-made. */ function fieldSummary(fields = {}) { const label = (key, n) => { switch (key) { case 'title': return sprintf(_n('%s title', '%s titles', n, 'ai-rank-suite'), num(n)); case 'desc': return sprintf(_n('%s description', '%s descriptions', n, 'ai-rank-suite'), num(n)); case 'keywords': return sprintf(_n('%s keyword set', '%s keyword sets', n, 'ai-rank-suite'), num(n)); case 'canonical': return sprintf(_n('%s canonical', '%s canonicals', n, 'ai-rank-suite'), num(n)); case 'robots': return sprintf(_n('%s robots directive', '%s robots directives', n, 'ai-rank-suite'), num(n)); case 'social': return sprintf(_n('%s social card', '%s social cards', n, 'ai-rank-suite'), num(n)); case 'breadcrumb': return sprintf(_n('%s breadcrumb title', '%s breadcrumb titles', n, 'ai-rank-suite'), num(n)); case 'schema': return sprintf(_n('%s schema type', '%s schema types', n, 'ai-rank-suite'), num(n)); case 'sitemap': return sprintf(_n('%s sitemap exclusion', '%s sitemap exclusions', n, 'ai-rank-suite'), num(n)); case 'term_title': return sprintf(_n('%s term title', '%s term titles', n, 'ai-rank-suite'), num(n)); case 'term_desc': return sprintf(_n('%s term description', '%s term descriptions', n, 'ai-rank-suite'), num(n)); case 'term_canonical': return sprintf(_n('%s term canonical', '%s term canonicals', n, 'ai-rank-suite'), num(n)); case 'term_robots': return sprintf(_n('%s term robots directive', '%s term robots directives', n, 'ai-rank-suite'), num(n)); case 'term_social': return sprintf(_n('%s term social card', '%s term social cards', n, 'ai-rank-suite'), num(n)); case 'redirects': return sprintf(_n('%s redirect', '%s redirects', n, 'ai-rank-suite'), num(n)); case 'settings': return sprintf(_n('%s setting', '%s settings', n, 'ai-rank-suite'), num(n)); default: return `${num(n)} ${key}`; } }; return Object.entries(fields) .filter(([, v]) => v > 0) .map(([k, v]) => label(k, v)) .join(' · '); } export default function Import() { const [data, setData] = useState(null); const [overwrite, setOverwrite] = useState(false); const [parts, setParts] = useState({ settings: true, posts: true, terms: true, redirects: true }); const [job, setJob] = useState(null); const [progress, setProgress] = useState(null); const [error, setError] = useState(null); const [backup, setBackup] = useState(null); const [busy, setBusy] = useState(false); const [file, setFile] = useState(null); const running = useRef(false); const fileRef = useRef(null); const dataFileRef = useRef(null); const load = useCallback( () => api .get('/import/detect') .then((d) => { setData(d); setJob(d.job && d.job.state === 'running' ? d.job : null); }) .catch((e) => setError(e.message)), [] ); useEffect(() => { load(); api.get('/settings/backup').then(setBackup).catch(() => {}); }, [load]); /** * Start a run and tick it to the end. The server does the work in slices; * this loop only keeps asking, so closing the tab pauses rather than * breaks — cron picks the same run up from its cursor. */ const pump = async (body, label) => { if (running.current) return; running.current = true; setError(null); setProgress({ label, counts: {}, done: false }); try { let s = await api.post('/import/start', body); setJob(s); const carry = (state, done) => ({ label, source: body.source || state.source || '', dryRun: !!body.dry_run, total: state.total || 0, counts: state.counts || {}, fields: state.fields || {}, importId: state.import_id, errors: state.errors || [], done, }); while (s.state === 'running') { s = await api.post('/import/tick', {}); setJob(s.state === 'running' ? s : null); setProgress(carry(s, s.state !== 'running')); if (s.busy || s.error) await new Promise((r) => setTimeout(r, 1500)); } setProgress(carry(s, true)); } catch (e) { setError(e.message); } finally { running.current = false; setJob(null); load(); } }; const chosenParts = Object.entries(parts) .filter(([, on]) => on) .map(([k]) => k); const runImport = (source, dryRun) => pump( { source, mode: overwrite ? 'overwrite' : 'fill', dry_run: dryRun, parts: chosenParts }, dryRun ? __('Preview', 'ai-rank-suite') : __('Import', 'ai-rank-suite') ); const undo = (importId) => pump({ undo: importId }, __('Undo', 'ai-rank-suite')); const cancel = async () => { try { await api.post('/import/cancel', {}); } catch (e) { setError(e.message); } }; // --- CSV/JSON --------------------------------------------------------- const readFile = async (f) => { setError(null); try { const content = await f.text(); const format = /\.json$/i.test(f.name) ? 'json' : 'csv'; const parsed = await api.post('/import/preview-file', { content, format }); if (parsed.error) { setError(parsed.error); return; } // Guess the mapping from the column names: an export from this // plugin, or a spreadsheet whose headers say what they hold, needs // no mapping at all. const guess = {}; (parsed.columns || []).forEach((c) => { const k = c.toLowerCase(); if (/^(seo[_ ]?)?title$/.test(k)) guess[c] = 'title'; else if (/desc/.test(k)) guess[c] = 'desc'; else if (/keyword|keyphrase/.test(k)) guess[c] = 'keywords'; else if (/canonical/.test(k)) guess[c] = 'canonical'; else if (/robots|noindex/.test(k)) guess[c] = 'robots'; else if (/og[_ ]?image/.test(k)) guess[c] = 'og_image'; else if (/og[_ ]?title/.test(k)) guess[c] = 'og_title'; }); const match = (parsed.columns || []).includes('id') ? 'id' : (parsed.columns || []).includes('url') ? 'url' : 'slug'; setFile({ name: f.name, content, format, ...parsed, map: guess, match }); } catch (e) { setError(e.message); } finally { if (dataFileRef.current) dataFileRef.current.value = ''; } }; const runFileImport = (dryRun) => pump( { source: 'file', mode: overwrite ? 'overwrite' : 'fill', dry_run: dryRun, file: { content: file.content, format: file.format, match: file.match, map: file.map }, }, dryRun ? __('Preview', 'ai-rank-suite') : __('File import', 'ai-rank-suite') ); // --- export / backup (unchanged behaviour) ---------------------------- const download = (blob, name) => { const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = name; a.click(); URL.revokeObjectURL(a.href); }; const stamp = () => new Date().toISOString().slice(0, 10); const exportSettings = async () => { setBusy(true); try { const payload = await api.get('/settings/export'); download(new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' }), `ai-rank-suite-settings-${stamp()}.json`); } catch (e) { setError(e.message); } finally { setBusy(false); } }; const exportCsv = async () => { setBusy(true); try { const cols = ['id', 'title', 'url', 'seo_title', 'seo_desc', 'keyword']; const rows = []; let after = 0; let total = null; for (let guard = 0; guard < 400; guard++) { const r = await api.get(`/content/csv?after=${after}&per_page=500`); rows.push(...(r.rows || [])); total = r.total ?? total; setProgress({ exported: rows.length, of: total }); if (r.next === null || r.next === undefined) break; after = r.next; } // Spreadsheets execute a cell that begins with = + - @ or a tab; a // title typed as "=HYPERLINK(...)" must open as text. const cell = (v) => { let s = String(v ?? '').replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, ''); if (/^[=+\-@\t]/.test(s)) s = "'" + s; return `"${s.replace(/"/g, '""')}"`; }; const lines = [cols.join(','), ...rows.map((row) => cols.map((c) => cell(row[c])).join(','))]; download(new Blob(['\ufeff' + lines.join('\r\n')], { type: 'text/csv;charset=utf-8' }), `ai-rank-suite-seo-data-${stamp()}.csv`); setProgress({ exported: rows.length, of: total, done: true }); } catch (e) { setError(e.message); } finally { setBusy(false); } }; const importSettings = async (f) => { setBusy(true); setError(null); try { const payload = JSON.parse(await f.text()); const r = await api.post('/settings/import', { payload }); setProgress({ settings: r.applied }); } catch (e) { setError(e.message); } finally { setBusy(false); if (fileRef.current) fileRef.current.value = ''; } }; const restore = async () => { setBusy(true); try { await api.post('/settings/backup'); setProgress({ restored: true }); } catch (e) { setError(e.message); } finally { setBusy(false); } }; if (!data) return ; const runs = data.runs || []; const conflicts = data.conflicts || {}; return (
{error && {error}} {conflicts.emitting && ( {sprintf( /* translators: %s: name of the other SEO plugin. */ __('%s is still active and writing the meta tags on your pages. Import your data first, check a few pages, then deactivate it — this plugin never switches another one off for you.', 'ai-rank-suite'), conflicts.emitting )} )} } >
{[ ['settings', __('Site-wide settings and templates', 'ai-rank-suite')], ['posts', __('Pages and posts', 'ai-rank-suite')], ['terms', __('Category and tag archives', 'ai-rank-suite')], ['redirects', __('Redirects', 'ai-rank-suite')], ].map(([key, label]) => ( setParts((p) => ({ ...p, [key]: v }))} label={label} /> ))}
{/* The same progress panel the bulk screen uses — heading, counted subtitle, full-width bar with the percentage and what is left, and the failures listed underneath. A run this long needs a state you can see from across the room, not a grey caption. */} {(job || progress) && (() => { const counts = (job ? job.counts : progress?.counts) || {}; const fields = (job ? job.fields : progress?.fields) || {}; const total = Number(job?.total || progress?.total || 0); const seen = Number(counts.seen || 0); const failed = Number(counts.errors || 0); const kept = Number(counts.kept || 0); const running = !!job; const pct = total > 0 ? Math.min(running ? 99 : 100, Math.round((seen / total) * 100)) : running ? 0 : 100; const remaining = Math.max(0, total - seen); const written = fieldSummary(fields); return ( {__('Cancel', 'ai-rank-suite')} ) : ( {failed ? sprintf(_n('%s failed', '%s failed', failed, 'ai-rank-suite'), Number(failed).toLocaleString()) : __('Complete', 'ai-rank-suite')} ) } >
{pct}% {running ? sprintf( /* translators: %s: number of records still to process. */ __('%s remaining', 'ai-rank-suite'), Number(remaining).toLocaleString() ) : written || __('Nothing needed changing.', 'ai-rank-suite')}
{!running && written && (
{written}
)} {!running && kept > 0 && (
{sprintf( _n( '%s value was left alone because this plugin already holds one for that field.', '%s values were left alone because this plugin already holds one for those fields.', kept, 'ai-rank-suite' ), Number(kept).toLocaleString() )}
)} {!running && counts.unmatched ? (
{sprintf( _n('%s row could not be matched to a page.', '%s rows could not be matched to a page.', counts.unmatched, 'ai-rank-suite'), Number(counts.unmatched).toLocaleString() )}
) : null} {(progress?.errors || []).length > 0 && (
    {progress.errors.slice(0, 8).map((e, i) => (
  • {e.what} — {e.message}
  • ))}
)} {!running && progress?.importId && !progress?.dryRun && (
{__('Run the content analysis afterwards so the scores use the imported data.', 'ai-rank-suite')}
)}
); })()} {/* * Two lists, not one grid of nine identical cards. * * The plugin that is installed, or has left data behind, is the * reason somebody opened this screen; it gets a card with the * numbers and the buttons. The seven that are not on this site * are a fact, not a choice, and a fact fits on one line each. */} {(data.sources || []).some((s) => !!sourceSummary(s)) ? null : (

{__('No other SEO plugin, and no data left behind by one, was found on this site. When one is installed its card appears here with what it holds.', 'ai-rank-suite')}

)}
{(data.sources || []).filter((s) => !!sourceSummary(s)).map((s) => { const summary = sourceSummary(s); const nothing = !summary; return (
{s.label} {s.active && {__('Active', 'ai-rank-suite')}}
{nothing ? s.active ? __('Active, but nothing is stored here to import — this plugin only saves values somebody typed by hand.', 'ai-rank-suite') : __('Supported. Nothing from it on this site — no plugin, no leftover data.', 'ai-rank-suite') : summary}
{!nothing && ( )}
); })}
{(data.sources || []).some((s) => !sourceSummary(s)) && (
{__('Also supported, nothing from them on this site', 'ai-rank-suite')}
{(data.sources || []).filter((s) => !sourceSummary(s)).map((s) => ( {s.label} {s.active && {__('Active', 'ai-rank-suite')}} ))}
)}

{__('Template variables such as %%title%% are translated into this plugin’s own. A variable nothing here can resolve is dropped rather than printed into your pages. Run the content analysis afterwards so the scores reflect the imported data.', 'ai-rank-suite')}

e.target.files?.[0] && readFile(e.target.files[0])} /> {file && ( {sprintf(_n('%s row', '%s rows', file.rows, 'ai-rank-suite'), num(file.rows))} )}
{file && (
{__('Match rows to pages by', 'ai-rank-suite')}
{__('Columns', 'ai-rank-suite')}
{(file.columns || []).map((c) => ( ))}
)}
{runs.length > 0 && (
{runs.map((r) => (
{r.source === 'file' ? __('Spreadsheet', 'ai-rank-suite') : (data.sources || []).find((s) => s.id === r.source)?.label || r.source} {r.dry_run ? ` · ${__('preview only', 'ai-rank-suite')}` : ''} {r.mode === 'overwrite' ? ` · ${__('overwrite', 'ai-rank-suite')}` : ''}
{when(r.started)} · {fieldSummary(r.fields) || __('nothing changed', 'ai-rank-suite')} {r.counts?.errors ? ` · ${sprintf(_n('%s error', '%s errors', r.counts.errors, 'ai-rank-suite'), num(r.counts.errors))}` : ''}
{Array.isArray(r.errors) && r.errors.length > 0 && (
    {r.errors.map((e, i) => (
  • {e.what} — {e.message}
  • ))}
)}
{r.undone ? ( {__('Undone', 'ai-rank-suite')} ) : r.undoable ? ( ) : ( {__('Preview', 'ai-rank-suite')} )}
))}
)}
{progress?.done && progress?.exported !== undefined && ( {sprintf(__('%s rows exported', 'ai-rank-suite'), num(progress.exported))} )} e.target.files?.[0] && importSettings(e.target.files[0])} /> {backup?.exists && ( )} {progress?.settings !== undefined && {sprintf(__('%s settings applied', 'ai-rank-suite'), num(progress.settings))}} {progress?.restored && {__('Restored', 'ai-rank-suite')}}

{__('API keys and license data are never included in an export.', 'ai-rank-suite')} {backup?.exists && ` ${sprintf(__('A backup from version %s was taken automatically before the last update.', 'ai-rank-suite'), backup.from)}`}

); }