import { Button, Notice, ToggleControl } from '@wordpress/components'; import { __, _n, sprintf } from '@wordpress/i18n'; import { useState } from 'react'; import { api, toApiError } from '../api'; import { Section, Table, count, dateTime, money } from './Ui'; import { useResource } from '../useResource'; import type { AdsOverview, CopilotRule, ProductSetSuggestion } from '../types'; /** * Copilote, etapes 2 et 3: agir sur les publicites depuis l'ecran ou vit la marge. * * Ce bloc est dans l'ecran Rentabilite, et pas dans un onglet a lui, parce que c'est exactement * ce qui le justifie: aujourd'hui, pour couper un produit qui perd de l'argent, le marchand doit * quitter Convrail et decider dans Ads Manager, qui ne connait ni son cout d'achat ni son stock. * La decision se prend ici, devant le chiffre qui la motive. * * Deux regles de conduite visibles a l'ecran: * * - **chaque action demande une confirmation**, et aucune n'est declenchee par un affichage; * - **un echec affiche la reponse d'OpenAI telle quelle**. « Une erreur est survenue » renverrait * le marchand chercher a l'aveugle, alors que le message d'OpenAI dit si le compte n'est pas * active ou si la cle est refusee. * * Les encheres sont AFFICHEES, plus modifiees, depuis le 2026-11-06 : OpenAI remplace les encheres * maximales par un cout moyen vise (Target CPA / CPC) a partir du 2026-11-18, et ecrire l'ancien * champ ferait basculer le groupe avec notre valeur comme cible (article d'aide OpenAI 20001634). */ /** Ce que la colonne « Encheres » dit d'un groupe, a partir de la strategie rendue par OpenAI. */ function bidLabel( group: { bidStrategy?: string | null; maxBid: number | null }, currency: string | null, ): string { const strategy = group.bidStrategy ?? ''; if (strategy.startsWith('maximize')) return __('Intelligent bidding, set by OpenAI', 'convrail'); if (strategy.includes('target')) return __('Average cost target', 'convrail'); if ((strategy === 'fixed_bid' || strategy === '') && group.maxBid !== null) { return sprintf( /* translators: %s: fixed bid amount with its currency. */ __('Fixed bid: %s', 'convrail'), money(group.maxBid, currency), ); } return __('Set in Ads Manager', 'convrail'); } /** Objectif de campagne lisible. Une valeur inconnue s'affiche telle quelle. */ function objectiveLabel(objective: string): string { switch (objective) { case 'clicks': return __('Clicks', 'convrail'); case 'conversions': return __('Conversions', 'convrail'); case 'impressions': return __('Views', 'convrail'); default: return objective; } } export function AdsControls({ spendKnown = true, showSettingsLink = true, }: { spendKnown?: boolean; /** * L'ecran parent a-t-il DEJA un bouton vers les Reglages. Trois boutons « Ouvrir les réglages » * sur le meme ecran, pour la meme cle manquante, faisaient desordre: un seul suffit. */ showSettingsLink?: boolean; }) { const overview = useResource(() => api.copilotAds()); const productSet = useResource(() => api.copilotProductSet(30)); const rules = useResource<{ rules: CopilotRule[] }>(() => api.copilotRules()); const [busy, setBusy] = useState(null); const [message, setMessage] = useState<{ tone: 'success' | 'error'; text: string } | null>(null); const toSettings = () => (window.location.hash = 'settings'); const run = async (key: string, body: Record) => { setBusy(key); setMessage(null); try { const result = await api.copilotApply(body); if (!result.ok) { setMessage({ tone: 'error', // Le texte brut d'OpenAI n'est jamais montre au marchand (il reste dans les journaux). text: result.reason === 'too_many_products' ? sprintf( /* translators: %s: maximum number of products and variants. */ __( 'You advertise more than %s products and variants, the most this action applies in one go. Choose the categories you advertise on the Product feed screen, and it becomes available.', 'convrail', ), count(500), ) : __('OpenAI refused this change.', 'convrail'), }); return; } setMessage({ tone: 'success', text: __('Done. The change is live at OpenAI.', 'convrail') }); overview.reload(); } catch (error) { setMessage({ tone: 'error', text: toApiError(error).message }); } finally { setBusy(null); } }; const toggleRule = async ( rule: CopilotRule, enabled: boolean, config: Record = rule.config, ) => { setBusy(rule.kind); try { await api.saveCopilotRule({ kind: rule.kind, enabled, config }); rules.reload(); } catch (error) { setMessage({ tone: 'error', text: toApiError(error).message }); } finally { setBusy(null); } }; const ads = overview.data; const suggestion = productSet.data; // Sans cle Ads Manager, un garde-fou active ne pourrait rien faire: on le dit, avec le chemin. const hasKey = ads?.configured === true; return ( <> {message ? ( setMessage(null)}> {message.text} ) : null}

{__('Live from your ChatGPT Ads account.', 'convrail')}{' '} {__('Bids and cost targets are set in ChatGPT Ads Manager.', 'convrail')}

{ads && !ads.configured ? (

{__( 'No Ads Manager key saved yet. Add it in Settings to pause or resume your campaigns from here.', 'convrail', )}

{showSettingsLink ? ( ) : null}
) : null} {ads?.detail ? ( {__( 'Your ChatGPT Ads account could not be read right now. Your settings are kept; try again in a moment.', 'convrail', )} ) : null} {ads?.configured && !ads.detail && ads.campaigns.length === 0 ? (

{__( 'No campaign yet. Create one in ChatGPT Ads Manager and it shows up here, ready to pause or to narrow to what pays.', 'convrail', )}

) : null} {(ads?.campaigns ?? []).map((campaign) => (

{campaign.name ?? campaign.id} · {campaign.status} {campaign.objective ? ` · ${objectiveLabel(campaign.objective)}` : ''}{' '}

[ group.name ?? group.id, group.status ?? '', bidLabel(group, ads?.currency ?? null), // Aucun filtre: le groupe diffuse tout le flux. group.productSetSize === null ? __('Whole feed', 'convrail') : count(group.productSetSize), , ])} empty={__('This campaign has no ad group yet.', 'convrail')} /> ))} {suggestion && hasKey ? (
{spendKnown ? ( <>

{sprintf( /* translators: 1: products and variants kept, 2: taken out, 3: window in days. */ _n( '%1$s product or variant kept in your ads, %2$s taken out because it lost money over the last %3$s days.', '%1$s products and variants kept in your ads, %2$s taken out because they lost money over the last %3$s days.', suggestion.kept, 'convrail', ), count(suggestion.kept), count(suggestion.losing.length), count(suggestion.window), )}

{__( 'Products that lose money are taken out of your ads. Products still being tested stay live, so nothing promising is cut early.', 'convrail', )}

{suggestion.truncated ? (

{sprintf( /* translators: %s: most products and variants the action applies at once. */ __( 'You advertise more than %s products and variants, the most this action applies in one go. Choose the categories you advertise on the Product feed screen, and it becomes available.', 'convrail', ), count(500), )}

) : null} {suggestion.unknown.length > 0 ? ( {sprintf( /* translators: %s: number of advertised products with an unknown margin. */ _n( 'Add a purchase cost to %s advertised product and the copilot will optimize it too.', 'Add a purchase cost to %s advertised products and the copilot will optimize them too.', suggestion.unknown.length, 'convrail', ), count(suggestion.unknown.length), )} ) : null}
[ row.title, row.netMargin === null ? __('Cannot be calculated', 'convrail') : money(row.netMargin, ads?.currency ?? null), money(row.spend, ads?.currency ?? null), ])} empty={__('No product is losing money over this period.', 'convrail')} /> ) : (

{__( 'Once ad spend is imported, this shows which products and variants would stay in your ads, and which lose money.', 'convrail', )}

)} ) : null}

{__( 'Guardrails run once a day. Turn on the ones you want; every action they take is written to the log below.', 'convrail', )}

{hasKey ? null : ( {__( 'Guardrails act on your ChatGPT Ads campaigns, so they need your Ads Manager key. Add it in Settings to turn them on.', 'convrail', )} )} {(rules.data?.rules ?? []).map((rule) => (
void toggleRule(rule, value)} />
))}
); } /** Libelle lisible d'une action du journal. Un type inconnu s'affiche tel quel, jamais vide. */ function actionLabel(kind: string): string { switch (kind) { case 'pause_campaign': return __('Campaign paused', 'convrail'); case 'activate_campaign': return __('Campaign resumed', 'convrail'); case 'pause_ad_group': return __('Ad group paused', 'convrail'); case 'activate_ad_group': return __('Ad group resumed', 'convrail'); case 'set_bid': return __('Bid changed', 'convrail'); case 'set_product_set': return __('Products advertised narrowed to what pays', 'convrail'); default: return kind; } } /** Journal des actions: la reponse a « qu'est-ce qui a change ma campagne ». */ function History() { const history = useResource<{ actions: import('../types').CopilotActionRow[] }>(() => api.copilotHistory(), ); return (
[ dateTime(action.createdAt), actionLabel(action.kind), action.targetExternalId, action.status === 'applied' ? __('Applied', 'convrail') : __('Not applied: OpenAI refused this change', 'convrail'), action.source === 'rule' ? __('A guardrail', 'convrail') : __('You', 'convrail'), ])} empty={__('Nothing has been changed from here yet.', 'convrail')} /> ); }