uniweb 1.34.11 → 1.35.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +6 -6
- package/partials/agents.md +2 -1
- package/partials/guides/backend.md +60 -5
- package/partials/guides/index.json +5 -0
- package/partials/guides/promote.md +142 -0
- package/src/backend/client.js +140 -7
- package/src/backend/promote-drafts.js +992 -0
- package/src/backend/site-published.js +142 -0
- package/src/backend/site-sync.js +2 -1
- package/src/commands/dev.js +42 -3
- package/src/commands/doctor.js +21 -5
- package/src/commands/promote.js +1598 -0
- package/src/commands/pull.js +72 -2
- package/src/commands/site.js +1 -1
- package/src/commands/status.js +169 -2
- package/src/framework-index.json +5 -5
- package/src/index.js +17 -1
- package/src/utils/flag-guard.js +7 -1
- package/src/utils/status-next.js +2 -2
|
@@ -0,0 +1,1598 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `uniweb promote` — a site's Promote, on the backend you are logged in to: getting it found,
|
|
3
|
+
* posts and ads on social networks and search engines, and what they brought.
|
|
4
|
+
*
|
|
5
|
+
* uniweb promote status [--json] the site's Promote on one screen, and what needs a person
|
|
6
|
+
* uniweb promote check <step> [--json] check one getting-found step (`sitemap`, say)
|
|
7
|
+
* uniweb promote connect <network> the address where a person connects an account
|
|
8
|
+
* uniweb promote post <file> make a post's draft, or update the one the file names
|
|
9
|
+
* uniweb promote campaign <file> the same for a campaign, its ad groups and ads
|
|
10
|
+
* uniweb promote show <id> [--json] one post or campaign, as a draft holds it
|
|
11
|
+
* uniweb promote delete <id> delete a post, a campaign, an ad group or an ad
|
|
12
|
+
* uniweb promote send <post> [--at <time> | --now] post it now, or at a time
|
|
13
|
+
* uniweb promote unschedule <post> a scheduled post a draft again, its time kept
|
|
14
|
+
* uniweb promote start | resume <campaign> [--yes] spend: say what, ask, then start
|
|
15
|
+
* uniweb promote pause <campaign> pause it wherever it runs
|
|
16
|
+
*
|
|
17
|
+
* The site is the one this project is synced to on that backend, or `--site <uuid>`. The
|
|
18
|
+
* workspace is `--org @x` or `--personal`, else the login's — as for every site request.
|
|
19
|
+
*
|
|
20
|
+
* ⭐ THE CLI IS A SECOND CLIENT OF THE SITE'S PROMOTE, BESIDE THE APP, AND KEEPS NO COPY OF IT.
|
|
21
|
+
* The backend holds the only one. Each command reads it fresh, and a write names the version of
|
|
22
|
+
* each item it read (`if_unmodified_since`), so a change made in the app since is refused, never
|
|
23
|
+
* written over. Nothing is synced, so there is nothing in the project to fall out of step.
|
|
24
|
+
*
|
|
25
|
+
* ⭐ AN ACCOUNT IS CONNECTED BY ITS PERSON, IN A BROWSER. `connect` hands over the network's
|
|
26
|
+
* consent page; the tokens it yields stay with the backend and never pass through the CLI.
|
|
27
|
+
*
|
|
28
|
+
* ⭐ AN AGENT SENDS AND SPENDS FOR ITS PERSON [Diego, 2026-11-16: "agents represent their users"].
|
|
29
|
+
* `start` and `resume` say what they will spend and ask at a terminal; `--yes` answers for an
|
|
30
|
+
* agent its person has agreed with, and without either they refuse rather than spend unseen.
|
|
31
|
+
*
|
|
32
|
+
* Auth: the session of the backend you are logged in to (`uniweb login`) / UNIWEB_TOKEN.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs'
|
|
36
|
+
import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
|
|
37
|
+
import yaml from 'js-yaml'
|
|
38
|
+
import { mintUuidV7 } from '@uniweb/build/uwx'
|
|
39
|
+
import { BackendClient, WorkspaceMismatchError, describeWorkspace } from '../backend/client.js'
|
|
40
|
+
import { resolveWorkspace } from '../backend/workspace.js'
|
|
41
|
+
import {
|
|
42
|
+
YAML_READ,
|
|
43
|
+
campaignDeliveries,
|
|
44
|
+
connectionOf,
|
|
45
|
+
conversionNotes,
|
|
46
|
+
campaignOf,
|
|
47
|
+
campaignShape,
|
|
48
|
+
checkDraft,
|
|
49
|
+
REASONS,
|
|
50
|
+
reasonWords,
|
|
51
|
+
reviewWords,
|
|
52
|
+
deliveryOf,
|
|
53
|
+
fileWithFields,
|
|
54
|
+
fileWithIdentity,
|
|
55
|
+
findItem,
|
|
56
|
+
formatOf,
|
|
57
|
+
idMatches,
|
|
58
|
+
indexPromotion,
|
|
59
|
+
isAddress,
|
|
60
|
+
kindOf,
|
|
61
|
+
pageRoute,
|
|
62
|
+
parseDraft,
|
|
63
|
+
picturesOf,
|
|
64
|
+
planCampaign,
|
|
65
|
+
planPost,
|
|
66
|
+
postMarkdown,
|
|
67
|
+
postShape,
|
|
68
|
+
resolvePage,
|
|
69
|
+
shapeYaml,
|
|
70
|
+
shortIds,
|
|
71
|
+
sitePages,
|
|
72
|
+
splitFrontmatter,
|
|
73
|
+
versionOf,
|
|
74
|
+
viaResolver,
|
|
75
|
+
wentOut
|
|
76
|
+
} from '../backend/promote-drafts.js'
|
|
77
|
+
import { checkFlags } from '../utils/flag-guard.js'
|
|
78
|
+
import { confirm, isNonInteractive } from '../utils/interactive.js'
|
|
79
|
+
import { readSiteIdentity } from '../utils/site-identity.js'
|
|
80
|
+
import { projectSiteDir } from './site.js'
|
|
81
|
+
|
|
82
|
+
const c = {
|
|
83
|
+
reset: '\x1b[0m',
|
|
84
|
+
bold: '\x1b[1m',
|
|
85
|
+
dim: '\x1b[2m',
|
|
86
|
+
red: '\x1b[31m',
|
|
87
|
+
green: '\x1b[32m',
|
|
88
|
+
yellow: '\x1b[33m',
|
|
89
|
+
cyan: '\x1b[36m'
|
|
90
|
+
}
|
|
91
|
+
// As in every verb: errors on stderr, the rest on stdout — and under `--json` nothing but
|
|
92
|
+
// the JSON on stdout.
|
|
93
|
+
const say = {
|
|
94
|
+
ok: (m) => console.log(`${c.green}✓${c.reset} ${m}`),
|
|
95
|
+
info: (m) => console.log(`${c.cyan}→${c.reset} ${m}`),
|
|
96
|
+
warn: (m) => console.log(`${c.yellow}⚠${c.reset} ${m}`),
|
|
97
|
+
err: (m) => console.error(`${c.red}✗${c.reset} ${m}`),
|
|
98
|
+
dim: (m) => console.log(` ${c.dim}${m}${c.reset}`)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const USAGE = [
|
|
102
|
+
'uniweb promote <command>',
|
|
103
|
+
' status The site\'s Promote: getting found, networks, posts, campaigns,',
|
|
104
|
+
' and what needs a person',
|
|
105
|
+
' check <step> Check one getting-found step, e.g. uniweb promote check sitemap',
|
|
106
|
+
' connect <network> The address where a person connects an account at a network',
|
|
107
|
+
' post <file> Make a post\'s draft (Markdown, YAML or JSON), or update the one',
|
|
108
|
+
' the file names; the file gets its id and version back',
|
|
109
|
+
' campaign <file> The same for a campaign (YAML or JSON), its ad groups and ads',
|
|
110
|
+
' show <id> One post or campaign, as a draft holds it',
|
|
111
|
+
' delete <id> Delete a post, a campaign, an ad group or an ad',
|
|
112
|
+
' send <post> Post it now, or at its send_at; --at <time> sets the time,',
|
|
113
|
+
' --now sends it now whatever its time',
|
|
114
|
+
' unschedule <post> A scheduled post a draft again, its time kept',
|
|
115
|
+
' start <campaign> Start it in its ad accounts — it says what it will spend and',
|
|
116
|
+
' asks; --yes answers for you',
|
|
117
|
+
' resume <campaign> Resume it where it was paused, the same way',
|
|
118
|
+
' pause <campaign> Pause it wherever it runs',
|
|
119
|
+
'',
|
|
120
|
+
'--json gives any command\'s answer as JSON. An <id> is the one a command shows, a file',
|
|
121
|
+
'a draft was written from, or a campaign\'s name.',
|
|
122
|
+
'The site is the one this project is synced to, or --site <uuid>.',
|
|
123
|
+
'The workspace is --org @x or --personal, else the one chosen at login.'
|
|
124
|
+
].join('\n')
|
|
125
|
+
|
|
126
|
+
/** A site-content uuid, loosely: enough to tell one from anything else. */
|
|
127
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
128
|
+
|
|
129
|
+
/** Flags that take a value, so the value is not read as an argument. */
|
|
130
|
+
const VALUED = new Set(['--org', '--site', '--at'])
|
|
131
|
+
|
|
132
|
+
/** The arguments that are not flags, skipping the values of the flags that take one. */
|
|
133
|
+
function positionals(args) {
|
|
134
|
+
const out = []
|
|
135
|
+
for (let i = 0; i < args.length; i++) {
|
|
136
|
+
const a = args[i]
|
|
137
|
+
if (VALUED.has(a)) {
|
|
138
|
+
i++
|
|
139
|
+
continue
|
|
140
|
+
}
|
|
141
|
+
// A lone `-` is stdin, a value rather than a flag.
|
|
142
|
+
if (a.startsWith('-') && a !== '-') continue
|
|
143
|
+
out.push(a)
|
|
144
|
+
}
|
|
145
|
+
return out
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** The value of `--name <value>`, or undefined. */
|
|
149
|
+
function flagValue(args, name) {
|
|
150
|
+
const i = args.indexOf(name)
|
|
151
|
+
return i !== -1 ? args[i + 1] : undefined
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** A client on the backend you are logged in to, working in the command's workspace. */
|
|
155
|
+
async function open(args, command) {
|
|
156
|
+
const client = new BackendClient({ args, command })
|
|
157
|
+
const ws = await resolveWorkspace({ client, args })
|
|
158
|
+
if (ws.refused) return { refused: ws.reason }
|
|
159
|
+
client.setWorkspace(ws.workspace, { source: ws.source })
|
|
160
|
+
return { client, workspace: ws.workspace }
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* The site a command acts on: `--site <uuid>`, else this project's site on the backend the
|
|
165
|
+
* client goes to. Null, with the reason said, when there is neither.
|
|
166
|
+
*/
|
|
167
|
+
async function targetSite(args, client, verb) {
|
|
168
|
+
const given = flagValue(args, '--site')
|
|
169
|
+
if (given !== undefined) {
|
|
170
|
+
if (!UUID.test(given || '')) {
|
|
171
|
+
say.err(`\`--site\` takes a site's uuid${given ? `, and \`${given}\` is not one` : ''}.`)
|
|
172
|
+
say.dim('`uniweb site list` shows each site with its uuid.')
|
|
173
|
+
return null
|
|
174
|
+
}
|
|
175
|
+
return given
|
|
176
|
+
}
|
|
177
|
+
const project = await projectSiteDir()
|
|
178
|
+
if (project.many) {
|
|
179
|
+
say.err(`This workspace has ${project.many.length} sites — run it inside one, or name it: uniweb promote ${verb} --site <uuid>`)
|
|
180
|
+
return null
|
|
181
|
+
}
|
|
182
|
+
const uuid = project.dir ? readSiteIdentity(project.dir, client.origin).uuid : null
|
|
183
|
+
if (!uuid) {
|
|
184
|
+
say.err(
|
|
185
|
+
project.dir
|
|
186
|
+
? `This project has no site on ${client.origin} yet — push it first (uniweb push), or name one: uniweb promote ${verb} --site <uuid>`
|
|
187
|
+
: `No site named, and this is not a Uniweb project — name one: uniweb promote ${verb} --site <uuid>`
|
|
188
|
+
)
|
|
189
|
+
say.dim('`uniweb site list` shows each site with its uuid.')
|
|
190
|
+
return null
|
|
191
|
+
}
|
|
192
|
+
return uuid
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* What the backend said about a refused request, in words, and its own beside them.
|
|
197
|
+
*
|
|
198
|
+
* @param {Response} res
|
|
199
|
+
* @param {{ site: string, origin: string, what: string, index?: object }} ctx - `what` completes
|
|
200
|
+
* "You may not …"; `index` names a campaign a refusal names by uuid
|
|
201
|
+
*/
|
|
202
|
+
async function sayRefusal(res, { site, origin, what, index = null, notFound = null }) {
|
|
203
|
+
const body = await res.clone().json().catch(() => null)
|
|
204
|
+
const reason = typeof body?.reason === 'string' ? body.reason : null
|
|
205
|
+
const own = [reason, body?.detail ?? body?.message ?? body?.title].filter((x) => typeof x === 'string' && x).join(': ')
|
|
206
|
+
if (res.status === 401) {
|
|
207
|
+
say.err(`Your session on ${origin} is not accepted — sign in again: uniweb login`)
|
|
208
|
+
} else if (res.status === 402) {
|
|
209
|
+
say.err(`${REASONS.feature_not_subscribed}.`)
|
|
210
|
+
} else if (res.status === 403 && body?.op === 'admin') {
|
|
211
|
+
say.err(`Only an admin of the site may ${what}. What is written stays, for one of them to do it.`)
|
|
212
|
+
} else if (res.status === 403 && body?.op === 'edit' && body?.target) {
|
|
213
|
+
say.err(`The account it goes out through is not shared with you for that. Use one you can use, or ask whoever connected it to share it.`)
|
|
214
|
+
} else if (res.status === 403) {
|
|
215
|
+
say.err(`You may not ${what} on this site${body?.op ? ` (it takes ${body.op})` : ''}.`)
|
|
216
|
+
} else if (res.status === 404) {
|
|
217
|
+
say.err(notFound ?? `${origin} has no site ${site}, or no longer has what was named — \`uniweb promote status\` shows what it has.`)
|
|
218
|
+
} else if (res.status === 409 && reason === 'campaign_started') {
|
|
219
|
+
const name = index?.byUuid.get(body?.campaign)?.data?.name
|
|
220
|
+
say.err(
|
|
221
|
+
`${name ? `“${name}”` : 'The campaign'} has started in an ad account, and what runs there is fixed, so the write is refused — nothing changed. ` +
|
|
222
|
+
'Add an ad account to its `via`, or draft a new campaign.'
|
|
223
|
+
)
|
|
224
|
+
} else if (res.status === 409) {
|
|
225
|
+
say.err(`Refused, nothing changed: what was named changed since it was read — in the app, or by another run${own ? ` (${own})` : ''}. Read it again: uniweb promote show <id>`)
|
|
226
|
+
} else {
|
|
227
|
+
say.err(`The backend refused: HTTP ${res.status}${own ? ` — ${own}` : ''}`)
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** A 404 on reading a site's Promote: no such site there, or a backend without these routes. */
|
|
232
|
+
const notOffered = (origin, site) => `${origin} has no site ${site}, or does not offer Promote to this CLI yet.`
|
|
233
|
+
|
|
234
|
+
/** The networks the deployment offers to connect, as tokens; null when it does not say. */
|
|
235
|
+
async function offeredNetworks(client) {
|
|
236
|
+
const config = await client.discover().catch(() => null)
|
|
237
|
+
const list = config?.promote?.networks
|
|
238
|
+
if (!Array.isArray(list)) return config && typeof config === 'object' ? [] : null
|
|
239
|
+
return list.map((n) => (typeof n === 'string' ? n : n?.network ?? n?.token)).filter(Boolean)
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// ── The promotion, read into the shape a person and an agent reason about ──────────────
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* The promotion's items, grouped: the site's networks, its getting-found steps with their
|
|
246
|
+
* readings, its posts with their parts and delivery, its campaigns with their deliveries, ad
|
|
247
|
+
* groups and ads. Backend's fields (a delivery, a reading, a campaign's tag) are read, never
|
|
248
|
+
* written.
|
|
249
|
+
*
|
|
250
|
+
* @param {{ uuid: string, items: object[] } | null} promotion
|
|
251
|
+
*/
|
|
252
|
+
export function readView(promotion) {
|
|
253
|
+
const items = Array.isArray(promotion?.items) ? promotion.items : []
|
|
254
|
+
const bySection = (section) => items.filter((i) => i.section === section)
|
|
255
|
+
const childrenOf = (section, parent) => items.filter((i) => i.section === section && i.parent === parent)
|
|
256
|
+
const one = (section, parent) => childrenOf(section, parent)[0] ?? null
|
|
257
|
+
|
|
258
|
+
const networks = bySection('networks').map((i) => ({ uuid: i.uuid, updated_at: i.updated_at, ...i.data }))
|
|
259
|
+
|
|
260
|
+
const steps = bySection('getting_found').map((i) => {
|
|
261
|
+
const reading = one('getting_found/reading', i.uuid)
|
|
262
|
+
return {
|
|
263
|
+
uuid: i.uuid,
|
|
264
|
+
updated_at: i.updated_at,
|
|
265
|
+
step: i.data?.step ?? null,
|
|
266
|
+
skipped: i.data?.skipped === true,
|
|
267
|
+
reading: reading ? reading.data : null
|
|
268
|
+
}
|
|
269
|
+
})
|
|
270
|
+
|
|
271
|
+
const posts = bySection('posts').map((i) => {
|
|
272
|
+
const delivery = one('posts/delivery', i.uuid)
|
|
273
|
+
return {
|
|
274
|
+
uuid: i.uuid,
|
|
275
|
+
updated_at: i.updated_at,
|
|
276
|
+
...i.data,
|
|
277
|
+
parts: childrenOf('posts/parts', i.uuid).map((p) => ({ uuid: p.uuid, ...p.data })),
|
|
278
|
+
delivery: delivery ? delivery.data : null,
|
|
279
|
+
state: delivery?.data?.status ?? 'draft'
|
|
280
|
+
}
|
|
281
|
+
})
|
|
282
|
+
|
|
283
|
+
const campaigns = bySection('campaigns').map((i) => {
|
|
284
|
+
const deliveries = childrenOf('campaigns/delivery', i.uuid).map((d) => d.data)
|
|
285
|
+
const adGroups = childrenOf('campaigns/ad_groups', i.uuid).map((g) => ({
|
|
286
|
+
uuid: g.uuid,
|
|
287
|
+
...g.data,
|
|
288
|
+
ads: childrenOf('campaigns/ad_groups/ads', g.uuid).map((a) => {
|
|
289
|
+
const delivery = one('campaigns/ad_groups/ads/delivery', a.uuid)
|
|
290
|
+
return { uuid: a.uuid, ...a.data, delivery: delivery ? delivery.data : null }
|
|
291
|
+
})
|
|
292
|
+
}))
|
|
293
|
+
return {
|
|
294
|
+
uuid: i.uuid,
|
|
295
|
+
updated_at: i.updated_at,
|
|
296
|
+
...i.data,
|
|
297
|
+
deliveries,
|
|
298
|
+
adGroups,
|
|
299
|
+
state: campaignState(deliveries),
|
|
300
|
+
started: deliveries.some((d) => d?.external_id)
|
|
301
|
+
}
|
|
302
|
+
})
|
|
303
|
+
|
|
304
|
+
return { uuid: promotion?.uuid ?? null, networks, steps, posts, campaigns }
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** One word for a campaign: `draft` until it runs anywhere, else what its deliveries say. */
|
|
308
|
+
function campaignState(deliveries) {
|
|
309
|
+
if (!deliveries.length) return 'draft'
|
|
310
|
+
const states = new Set(deliveries.map((d) => d?.status).filter(Boolean))
|
|
311
|
+
if (states.has('attention')) return 'attention'
|
|
312
|
+
if (states.has('active')) return 'active'
|
|
313
|
+
if (states.size === 1) return [...states][0]
|
|
314
|
+
return [...states].join(', ') || 'draft'
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Spend rows summed per currency — `{ CAD: '16.00' }` — from the days the backend has read. */
|
|
318
|
+
export function sumSpend(rows) {
|
|
319
|
+
const out = {}
|
|
320
|
+
for (const r of Array.isArray(rows) ? rows : []) {
|
|
321
|
+
if (!r?.currency || r.amount == null) continue
|
|
322
|
+
const cents = Math.round(Number(r.amount) * 100)
|
|
323
|
+
if (!Number.isFinite(cents)) continue
|
|
324
|
+
out[r.currency] = (out[r.currency] ?? 0) + cents
|
|
325
|
+
}
|
|
326
|
+
return Object.fromEntries(Object.entries(out).map(([cur, cents]) => [cur, (cents / 100).toFixed(2)]))
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// ── status ─────────────────────────────────────────────────────────────────────────
|
|
330
|
+
|
|
331
|
+
async function status(args) {
|
|
332
|
+
const json = args.includes('--json')
|
|
333
|
+
const conn = await open(args, 'Reading the site\'s Promote')
|
|
334
|
+
if (conn.refused) {
|
|
335
|
+
say.err(conn.refused)
|
|
336
|
+
return { exitCode: 2 }
|
|
337
|
+
}
|
|
338
|
+
const { client, workspace } = conn
|
|
339
|
+
const site = await targetSite(args, client, 'status')
|
|
340
|
+
if (!site) return { exitCode: 2 }
|
|
341
|
+
|
|
342
|
+
const [res, connectionsRes, offered] = await Promise.all([
|
|
343
|
+
client.readPromotion(site),
|
|
344
|
+
client.listConnections().catch(() => null),
|
|
345
|
+
offeredNetworks(client)
|
|
346
|
+
])
|
|
347
|
+
if (!res.ok) {
|
|
348
|
+
await sayRefusal(res, { site, origin: client.origin, what: 'read Promote', notFound: notOffered(client.origin, site) })
|
|
349
|
+
return { exitCode: 1 }
|
|
350
|
+
}
|
|
351
|
+
const promotion = (await res.json().catch(() => null))?.promotion ?? null
|
|
352
|
+
const view = readView(promotion)
|
|
353
|
+
const connections = connectionsRes?.ok ? (await connectionsRes.json().catch(() => null))?.connections ?? [] : null
|
|
354
|
+
// Each post and campaign by the id the other commands take.
|
|
355
|
+
const ids = shortIds((promotion?.items ?? []).map((i) => i?.uuid))
|
|
356
|
+
for (const x of [...view.posts, ...view.campaigns]) x.short = ids.get(x.uuid)
|
|
357
|
+
|
|
358
|
+
// Spend, for the campaigns that run somewhere: what each network last reported.
|
|
359
|
+
for (const campaign of view.campaigns.filter((x) => x.started)) {
|
|
360
|
+
const spent = await client.campaignSpend(site, campaign.uuid).catch(() => null)
|
|
361
|
+
const rows = spent?.ok ? (await spent.json().catch(() => null))?.spend : null
|
|
362
|
+
campaign.spend = Array.isArray(rows) ? { total: sumSpend(rows), days: rows.length } : null
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const needs = needsPerson(view, connections)
|
|
366
|
+
if (json) {
|
|
367
|
+
console.log(JSON.stringify({
|
|
368
|
+
backend: client.origin,
|
|
369
|
+
workspace: workspace ?? null,
|
|
370
|
+
site,
|
|
371
|
+
networksOffered: offered,
|
|
372
|
+
connections,
|
|
373
|
+
promotion: promotion ? view : null,
|
|
374
|
+
needsPerson: needs
|
|
375
|
+
}))
|
|
376
|
+
return { exitCode: 0 }
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
console.log(`${c.bold}Promote${c.reset} ${c.dim}— site ${site} in ${describeWorkspace(workspace)} on ${client.origin}${c.reset}`)
|
|
380
|
+
if (!promotion) {
|
|
381
|
+
say.info('This site has not used Promote yet: no networks, posts or campaigns.')
|
|
382
|
+
}
|
|
383
|
+
printSteps(view.steps)
|
|
384
|
+
printNetworks(view.networks, connections)
|
|
385
|
+
printPosts(view.posts)
|
|
386
|
+
printCampaigns(view.campaigns)
|
|
387
|
+
if (offered !== null) {
|
|
388
|
+
console.log(` ${c.dim}Can connect here:${c.reset} ${offered.length ? offered.join(', ') : 'no network yet, on this deployment'}`)
|
|
389
|
+
}
|
|
390
|
+
if (needs.length) {
|
|
391
|
+
console.log()
|
|
392
|
+
console.log(`${c.yellow}Ask the person first:${c.reset}`)
|
|
393
|
+
for (const n of needs) console.log(` • ${n.say}`)
|
|
394
|
+
}
|
|
395
|
+
return { exitCode: 0 }
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* The steps only a person can take, as status shows them: an account to reconnect or hand on,
|
|
400
|
+
* and the capability to turn on. A getting-found step is not among them by itself — which steps
|
|
401
|
+
* the backend can check is its own to say, so status shows each step's reading instead.
|
|
402
|
+
*/
|
|
403
|
+
function needsPerson(view, connections) {
|
|
404
|
+
const needs = []
|
|
405
|
+
for (const k of Array.isArray(connections) ? connections : []) {
|
|
406
|
+
const state = k?.card?.state
|
|
407
|
+
if (state === 'needs_reconnect' || state === 'stopped') {
|
|
408
|
+
const who = k.card?.name || k.card?.handle || k.uuid
|
|
409
|
+
needs.push({
|
|
410
|
+
kind: 'connection',
|
|
411
|
+
connection: k.uuid,
|
|
412
|
+
state,
|
|
413
|
+
say: state === 'stopped'
|
|
414
|
+
? `${k.card?.network ?? 'a'} connection “${who}” stopped: its person left; an admin of the workspace hands it on, in the app`
|
|
415
|
+
: `${k.card?.network ?? 'a'} connection “${who}” needs reconnecting, by its person, in the app`
|
|
416
|
+
})
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
for (const p of view.posts) {
|
|
420
|
+
if (p.state === 'failed' && p.delivery?.reason === 'promote_off') {
|
|
421
|
+
needs.push({ kind: 'capability', post: p.uuid, say: 'a scheduled post failed because the site has no Promote: it comes with the site\'s Analytics, turned on in the app' })
|
|
422
|
+
break
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
return needs
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function printSteps(steps) {
|
|
429
|
+
if (!steps.length) {
|
|
430
|
+
console.log(` ${c.bold}Getting found${c.reset} ${c.dim}no step checked yet — uniweb promote check sitemap${c.reset}`)
|
|
431
|
+
return
|
|
432
|
+
}
|
|
433
|
+
steps.forEach((s, i) => {
|
|
434
|
+
const head = i === 0 ? `${c.bold}Getting found${c.reset} ` : ' '.repeat(15)
|
|
435
|
+
const r = s.reading
|
|
436
|
+
const what = s.skipped ? `${c.dim}skipped${c.reset}` : r ? `${r.state}${r.address ? ` — ${r.address}` : ''}${r.found && r.state !== 'done' ? ` (${foundWords(r.found)})` : ''}` : `${c.dim}not checked${c.reset}`
|
|
437
|
+
console.log(` ${head}${s.step}: ${what}`)
|
|
438
|
+
})
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function printNetworks(networks, connections) {
|
|
442
|
+
if (!networks.length) {
|
|
443
|
+
console.log(` ${c.bold}Networks${c.reset} ${c.dim}none chosen yet${c.reset}`)
|
|
444
|
+
return
|
|
445
|
+
}
|
|
446
|
+
const byUuid = new Map((connections ?? []).map((k) => [k.uuid, k]))
|
|
447
|
+
networks.forEach((n, i) => {
|
|
448
|
+
const head = i === 0 ? `${c.bold}Networks${c.reset} ` : ' '.repeat(15)
|
|
449
|
+
const via = connectionOf(n.connection)
|
|
450
|
+
const k = byUuid.get(via.uuid)
|
|
451
|
+
const account = n.target?.name || via.name || k?.card?.name || via.handle || k?.card?.handle || 'no account chosen'
|
|
452
|
+
const known = k?.card?.state ?? via.state
|
|
453
|
+
const state = known && known !== 'connected' ? ` ${c.yellow}(${known})${c.reset}` : ''
|
|
454
|
+
console.log(` ${head}${n.use ?? '?'} through ${n.network ?? '?'}, “${account}”${state}`)
|
|
455
|
+
})
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function printPosts(posts) {
|
|
459
|
+
const count = (state) => posts.filter((p) => p.state === state).length
|
|
460
|
+
const scheduled = posts
|
|
461
|
+
.filter((p) => p.state === 'scheduled')
|
|
462
|
+
.map((p) => p.send_at)
|
|
463
|
+
.filter(Boolean)
|
|
464
|
+
.sort()
|
|
465
|
+
const parts = [
|
|
466
|
+
`${count('draft')} draft${count('draft') === 1 ? '' : 's'}`,
|
|
467
|
+
`${count('scheduled')} scheduled${scheduled[0] ? ` (next ${scheduled[0]})` : ''}`,
|
|
468
|
+
`${count('published')} published`
|
|
469
|
+
]
|
|
470
|
+
if (count('failed')) parts.push(`${c.red}${count('failed')} failed${c.reset}`)
|
|
471
|
+
console.log(` ${c.bold}Posts${c.reset} ${parts.join(' · ')}`)
|
|
472
|
+
// What can still be acted on, each by its id: a draft, a scheduled post, one that failed.
|
|
473
|
+
for (const p of posts.filter((x) => x.state !== 'published' && x.state !== 'review')) {
|
|
474
|
+
const first = String(p.parts?.[0]?.text ?? '').replace(/\s+/g, ' ').trim()
|
|
475
|
+
const words = first ? `“${first.length > 40 ? `${first.slice(0, 39)}…` : first}”` : '(no words yet)'
|
|
476
|
+
const when = p.state === 'scheduled' && p.send_at ? ` ${p.send_at}` : ''
|
|
477
|
+
const why = p.state === 'failed' && p.delivery?.reason ? ` — ${reasonWords(p.delivery.reason)}` : ''
|
|
478
|
+
console.log(`${' '.repeat(17)}${c.cyan}${p.short ?? p.uuid}${c.reset} ${p.state}${when} ${words}${why}`)
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
function printCampaigns(campaigns) {
|
|
483
|
+
if (!campaigns.length) {
|
|
484
|
+
console.log(` ${c.bold}Campaigns${c.reset} ${c.dim}none${c.reset}`)
|
|
485
|
+
return
|
|
486
|
+
}
|
|
487
|
+
campaigns.forEach((x, i) => {
|
|
488
|
+
const head = i === 0 ? `${c.bold}Campaigns${c.reset} ` : ' '.repeat(15)
|
|
489
|
+
const spent = x.spend?.total && Object.keys(x.spend.total).length
|
|
490
|
+
? ` · spent ${Object.entries(x.spend.total).map(([cur, amt]) => `${amt} ${cur}`).join(' + ')}`
|
|
491
|
+
: ''
|
|
492
|
+
console.log(` ${head}${c.cyan}${x.short ?? x.uuid}${c.reset} ${x.name ?? x.uuid}: ${x.state}${spent}`)
|
|
493
|
+
})
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/** A getting-found reading's code, in words; an unknown one is shown as it is. */
|
|
497
|
+
function foundWords(found) {
|
|
498
|
+
return {
|
|
499
|
+
sitemap_named: 'the site\'s robots.txt names its sitemap',
|
|
500
|
+
no_sitemap: 'the site\'s robots.txt names no sitemap',
|
|
501
|
+
no_robots: 'the site has no robots.txt',
|
|
502
|
+
site_unreachable: 'the live site did not answer',
|
|
503
|
+
no_address: 'the site has no live address yet — publish it first'
|
|
504
|
+
}[found] ?? found
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
// ── check ──────────────────────────────────────────────────────────────────────────
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* `uniweb promote check <step>` — check one getting-found step, and show its reading.
|
|
511
|
+
*
|
|
512
|
+
* ⭐ A STEP IS NAMED BY ITS TOKEN (`sitemap`), AND THE BACKEND KEEPS ONE ITEM FOR IT: the check
|
|
513
|
+
* finds the step's item, or makes it on its first check, so neither client makes one to check it,
|
|
514
|
+
* and a second is refused. A step the backend cannot check is `400`, with nothing made.
|
|
515
|
+
*/
|
|
516
|
+
async function check(args) {
|
|
517
|
+
const json = args.includes('--json')
|
|
518
|
+
const step = positionals(args)[1]
|
|
519
|
+
if (!step) {
|
|
520
|
+
say.err('Name the step or the page: uniweb promote check sitemap, or uniweb promote check /holiday')
|
|
521
|
+
return { exitCode: 2 }
|
|
522
|
+
}
|
|
523
|
+
if (step.startsWith('/') || step.startsWith('page:/')) return checkLanding(args, step.replace(/^page:/, ''))
|
|
524
|
+
const at = await begin(args, 'Checking a getting-found step', `check ${step}`)
|
|
525
|
+
if (!at.client) return at
|
|
526
|
+
const { client, site } = at
|
|
527
|
+
|
|
528
|
+
const checked = await client.checkPromotionStep(site, step)
|
|
529
|
+
if (!checked.ok) {
|
|
530
|
+
if (checked.status === 400) {
|
|
531
|
+
say.err(`The backend cannot check \`${step}\` yet. The person does that step at the service, and marks it in the app.`)
|
|
532
|
+
return { exitCode: 1 }
|
|
533
|
+
}
|
|
534
|
+
await sayRefusal(checked, { site, origin: client.origin, what: 'check a step', notFound: notOffered(client.origin, site) })
|
|
535
|
+
return { exitCode: 1 }
|
|
536
|
+
}
|
|
537
|
+
const reading = (await checked.json().catch(() => null))?.reading ?? null
|
|
538
|
+
if (json) {
|
|
539
|
+
console.log(JSON.stringify({ backend: client.origin, site, step, reading }))
|
|
540
|
+
return { exitCode: 0 }
|
|
541
|
+
}
|
|
542
|
+
if (!reading) {
|
|
543
|
+
say.warn(`Checked \`${step}\`, and the backend answered no reading.`)
|
|
544
|
+
return { exitCode: 0 }
|
|
545
|
+
}
|
|
546
|
+
const words = foundWords(reading.found)
|
|
547
|
+
if (reading.state === 'done') {
|
|
548
|
+
say.ok(`${step}: done — ${words}${reading.address ? `: ${reading.address}` : ''}`)
|
|
549
|
+
} else {
|
|
550
|
+
say.warn(`${step}: ${reading.state} — ${words}`)
|
|
551
|
+
if (reading.detail) say.dim(reading.detail)
|
|
552
|
+
}
|
|
553
|
+
return { exitCode: 0 }
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// ── a landing page: check <route> ──────────────────────────────────────────────────
|
|
557
|
+
|
|
558
|
+
/** The site's directory, when the site a command acts on is this project's; else null. */
|
|
559
|
+
async function siteFilesFor(site, origin) {
|
|
560
|
+
const project = await projectSiteDir().catch(() => null)
|
|
561
|
+
if (!project?.dir) return null
|
|
562
|
+
if (site && readSiteIdentity(project.dir, origin).uuid !== site) return null
|
|
563
|
+
return project.dir
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
function readSiteYml(dir) {
|
|
567
|
+
for (const name of ['site.yml', 'site.yaml']) {
|
|
568
|
+
const path = join(dir, name)
|
|
569
|
+
if (!existsSync(path)) continue
|
|
570
|
+
try {
|
|
571
|
+
return yaml.load(readFileSync(path, 'utf8'), YAML_READ) ?? null
|
|
572
|
+
} catch {
|
|
573
|
+
return null
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
return null
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* Notes on the pages a post or an ad lands on, from the site's files — each page's card, by
|
|
581
|
+
* doctor's rules for one page — and on what the site reports for a network to hear. Each is a
|
|
582
|
+
* note, never a gate: whoever sends or starts decides, with the notes in front of them.
|
|
583
|
+
*
|
|
584
|
+
* @param {string} dir - the site's directory
|
|
585
|
+
* @param {string[]} routes
|
|
586
|
+
* @param {{ networks?: string[]|null, goal?: string|null, quiet?: boolean }} [opts]
|
|
587
|
+
* @returns {Promise<{ issues: object[], notes: object[] }>}
|
|
588
|
+
*/
|
|
589
|
+
async function landingNotes(dir, routes, { networks = null, goal = null, quiet = false } = {}) {
|
|
590
|
+
const { checkLinkPreviews } = await import('./doctor.js')
|
|
591
|
+
const issues = []
|
|
592
|
+
const consoleLog = console.log
|
|
593
|
+
if (quiet) console.log = () => {}
|
|
594
|
+
try {
|
|
595
|
+
for (const route of routes) {
|
|
596
|
+
const before = issues.length
|
|
597
|
+
if (!quiet) console.log(`${c.bold}${route}${c.reset}${c.dim}, as a landing page, from the site's files:${c.reset}`)
|
|
598
|
+
await checkLinkPreviews({ sitePath: dir, siteName: basename(dir), issues, route })
|
|
599
|
+
if (!quiet && issues.length === before) say.ok('its card has an image and a description')
|
|
600
|
+
}
|
|
601
|
+
} finally {
|
|
602
|
+
console.log = consoleLog
|
|
603
|
+
}
|
|
604
|
+
const notes = conversionNotes(readSiteYml(dir), { networks, goal })
|
|
605
|
+
if (!quiet) for (const n of notes) (n.ok ? say.ok : say.warn)(n.text)
|
|
606
|
+
return { issues, notes }
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/**
|
|
610
|
+
* `uniweb promote check <route>` — a page as a landing page, from the site's files, on any site:
|
|
611
|
+
* one Uniweb hosts or a static one. Its card, by doctor's rules for one page, and what the site
|
|
612
|
+
* reports for a network to hear. It needs no backend.
|
|
613
|
+
*/
|
|
614
|
+
async function checkLanding(args, route) {
|
|
615
|
+
const json = args.includes('--json')
|
|
616
|
+
const project = await projectSiteDir().catch(() => ({}))
|
|
617
|
+
if (project?.many) {
|
|
618
|
+
say.err(`This workspace has ${project.many.length} sites — run it inside the one the page is in.`)
|
|
619
|
+
return { exitCode: 2 }
|
|
620
|
+
}
|
|
621
|
+
if (!project?.dir) {
|
|
622
|
+
say.err('Run it in the site\'s project: a landing page is checked in its files.')
|
|
623
|
+
return { exitCode: 2 }
|
|
624
|
+
}
|
|
625
|
+
const found = await landingNotes(project.dir, [route], { goal: 'conversions', quiet: json })
|
|
626
|
+
const unknown = found.issues.some((i) => i.id === 'page-unknown')
|
|
627
|
+
if (json) console.log(JSON.stringify({ route, issues: found.issues, notes: found.notes }))
|
|
628
|
+
return { exitCode: unknown ? 1 : 0 }
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
// ── connect ────────────────────────────────────────────────────────────────────────
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* `uniweb promote connect <network>` — the address where a person connects an account.
|
|
635
|
+
*
|
|
636
|
+
* ⛔ THE CONSENT FINISHES ONLY IN A BROWSER SIGNED IN TO THE APP AS THE SAME PERSON. The backend
|
|
637
|
+
* answers a consent once, for whoever started it, within minutes; a browser signed in as anyone
|
|
638
|
+
* else, or not at all, spends it. So the command says that before the address, and an agent passes
|
|
639
|
+
* the address to its person rather than opening it somewhere they are not.
|
|
640
|
+
*/
|
|
641
|
+
async function connectNetwork(args) {
|
|
642
|
+
const network = positionals(args)[1]
|
|
643
|
+
const conn = await open(args, 'Connecting an account')
|
|
644
|
+
if (conn.refused) {
|
|
645
|
+
say.err(conn.refused)
|
|
646
|
+
return { exitCode: 2 }
|
|
647
|
+
}
|
|
648
|
+
const { client } = conn
|
|
649
|
+
const offered = await offeredNetworks(client)
|
|
650
|
+
if (!network) {
|
|
651
|
+
say.err('Name the network: uniweb promote connect <network>')
|
|
652
|
+
if (offered?.length) say.dim(`${client.origin} can connect: ${offered.join(', ')}`)
|
|
653
|
+
return { exitCode: 2 }
|
|
654
|
+
}
|
|
655
|
+
if (offered && !offered.includes(network)) {
|
|
656
|
+
say.err(
|
|
657
|
+
offered.length
|
|
658
|
+
? `${client.origin} cannot connect \`${network}\` — it offers ${offered.join(', ')}.`
|
|
659
|
+
: `${client.origin} cannot connect any network yet.`
|
|
660
|
+
)
|
|
661
|
+
return { exitCode: 2 }
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
const res = await client.startConnectionConsent({ network })
|
|
665
|
+
if (!res.ok) {
|
|
666
|
+
if (res.status === 404) {
|
|
667
|
+
say.err(`${client.origin} does not offer \`${network}\`.`)
|
|
668
|
+
} else {
|
|
669
|
+
await sayRefusal(res, { site: '', origin: client.origin, what: 'connect an account' })
|
|
670
|
+
}
|
|
671
|
+
return { exitCode: 1 }
|
|
672
|
+
}
|
|
673
|
+
const address = (await res.json().catch(() => null))?.address
|
|
674
|
+
if (!address) {
|
|
675
|
+
say.err('The backend started the consent but gave no address to open.')
|
|
676
|
+
return { exitCode: 1 }
|
|
677
|
+
}
|
|
678
|
+
say.info(`Connect ${network}, in a browser signed in to the app as you:`)
|
|
679
|
+
console.log(` ${address}`)
|
|
680
|
+
say.dim('The consent finishes only there, once, and only for whoever started it — open it soon.')
|
|
681
|
+
if (isNonInteractive(args)) {
|
|
682
|
+
say.dim('An agent hands this address to its person, who opens it.')
|
|
683
|
+
} else {
|
|
684
|
+
try {
|
|
685
|
+
const { openBrowser } = await import('../utils/registry-auth.js')
|
|
686
|
+
await openBrowser(address)
|
|
687
|
+
} catch {
|
|
688
|
+
/* the address is printed; opening it is a convenience */
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
return { exitCode: 0 }
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
// ── shared by the commands below ───────────────────────────────────────────────────
|
|
695
|
+
|
|
696
|
+
/** The client and the site a command acts on — or its exit code, the reason said. */
|
|
697
|
+
async function begin(args, command, verb) {
|
|
698
|
+
const conn = await open(args, command)
|
|
699
|
+
if (conn.refused) {
|
|
700
|
+
say.err(conn.refused)
|
|
701
|
+
return { exitCode: 2 }
|
|
702
|
+
}
|
|
703
|
+
const site = await targetSite(args, conn.client, verb)
|
|
704
|
+
if (!site) return { exitCode: 2 }
|
|
705
|
+
return { client: conn.client, workspace: conn.workspace, site }
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/** The site's Promote, read fresh and indexed — or null, the refusal said. */
|
|
709
|
+
async function readIndex(client, site) {
|
|
710
|
+
const res = await client.readPromotion(site)
|
|
711
|
+
if (!res.ok) {
|
|
712
|
+
await sayRefusal(res, { site, origin: client.origin, what: 'read Promote', notFound: notOffered(client.origin, site) })
|
|
713
|
+
return null
|
|
714
|
+
}
|
|
715
|
+
return indexPromotion((await res.json().catch(() => null))?.promotion ?? null)
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/** The site's pages as pushed — null when it has none there, or they could not be read. */
|
|
719
|
+
async function readPages(client, site) {
|
|
720
|
+
try {
|
|
721
|
+
const res = await client.pullSiteContent(site)
|
|
722
|
+
if (!res?.ok) return null
|
|
723
|
+
const { entityDocFromUwx } = await import('../backend/site-sync.js')
|
|
724
|
+
const doc = entityDocFromUwx(Buffer.from(await res.arrayBuffer()))
|
|
725
|
+
return doc ? sitePages(doc) : null
|
|
726
|
+
} catch {
|
|
727
|
+
return null
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
/** The caller's connections — null when they could not be listed. */
|
|
732
|
+
async function listedConnections(client) {
|
|
733
|
+
const res = await client.listConnections().catch(() => null)
|
|
734
|
+
return res?.ok ? ((await res.json().catch(() => null))?.connections ?? []) : null
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/** An item's name in a line: a post's first words, a campaign's or an ad group's name, an ad's headline. */
|
|
738
|
+
function labelOf(index, item) {
|
|
739
|
+
const words = (text) => {
|
|
740
|
+
const t = String(text ?? '').replace(/\s+/g, ' ').trim()
|
|
741
|
+
return t.length > 48 ? `${t.slice(0, 47)}…` : t
|
|
742
|
+
}
|
|
743
|
+
if (item.section === 'posts') {
|
|
744
|
+
const first = index.children('posts/parts', item.uuid)[0]?.data?.text
|
|
745
|
+
return first ? `“${words(first)}”` : '(no words yet)'
|
|
746
|
+
}
|
|
747
|
+
if (item.section === 'campaigns/ad_groups/ads') {
|
|
748
|
+
const headline = item.data?.headlines?.[0] ?? index.children('campaigns/ad_groups/ads/parts', item.uuid)[0]?.data?.text
|
|
749
|
+
return headline ? `“${words(headline)}”` : '(no words yet)'
|
|
750
|
+
}
|
|
751
|
+
return item.data?.name ? `“${item.data.name}”` : '(no name)'
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
/** A `networks` item as a person reads it: `facebook “Maple Bakery Ads”`. */
|
|
755
|
+
function accountName(index, uuid, connections) {
|
|
756
|
+
const n = index.byUuid.get(uuid)
|
|
757
|
+
if (!n) return `account ${uuid}`
|
|
758
|
+
const via = connectionOf(n.data?.connection)
|
|
759
|
+
const k = (connections ?? []).find((c) => c.uuid === via.uuid)
|
|
760
|
+
const name = n.data?.target?.name || via.name || k?.card?.name || via.handle || k?.card?.handle
|
|
761
|
+
return `${n.data?.network ?? '?'}${name ? ` “${name}”` : ''}`
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
/** The file a command names, when it names one: its path, text and format. */
|
|
765
|
+
function draftFile(arg) {
|
|
766
|
+
const path = resolve(arg)
|
|
767
|
+
if (!existsSync(path) || !statSync(path).isFile()) return null
|
|
768
|
+
const text = readFileSync(path, 'utf8')
|
|
769
|
+
return { path, text, format: formatOf(path, text) }
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/** The id in a file a draft was written from, else null. */
|
|
773
|
+
function idInFile(text, format) {
|
|
774
|
+
try {
|
|
775
|
+
if (format === 'json') return JSON.parse(text)?.id ?? null
|
|
776
|
+
const src = format === 'markdown' ? splitFrontmatter(text).front : text
|
|
777
|
+
const obj = src ? yaml.load(src, YAML_READ) : null
|
|
778
|
+
return typeof obj?.id === 'string' ? obj.id : null
|
|
779
|
+
} catch {
|
|
780
|
+
return null
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
/**
|
|
785
|
+
* The item a command names — by the id a command shows, a campaign's name, or the file a draft
|
|
786
|
+
* was written from — or null, with what it matched said.
|
|
787
|
+
*/
|
|
788
|
+
function pick(index, arg, kinds) {
|
|
789
|
+
let ref = arg
|
|
790
|
+
const path = resolve(arg)
|
|
791
|
+
if (existsSync(path) && statSync(path).isFile()) {
|
|
792
|
+
const text = readFileSync(path, 'utf8')
|
|
793
|
+
ref = idInFile(text, formatOf(path, text))
|
|
794
|
+
if (!ref) {
|
|
795
|
+
say.err(`${arg} holds no id yet — write it first: uniweb promote ${kinds.includes('post') ? 'post' : 'campaign'} ${arg}`)
|
|
796
|
+
return null
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
const found = findItem(index, ref, { kinds })
|
|
800
|
+
if (found.item) return found.item
|
|
801
|
+
const ids = shortIds(index.items.map((i) => i.uuid))
|
|
802
|
+
if (found.many) {
|
|
803
|
+
say.err(`\`${ref}\` names ${found.many.length} things — give more of its id:`)
|
|
804
|
+
for (const i of found.many) say.dim(`${ids.get(i.uuid)} ${kindOf(i)} ${labelOf(index, i)}`)
|
|
805
|
+
return null
|
|
806
|
+
}
|
|
807
|
+
say.err(`This site's Promote has no ${kinds.join(' or ')} \`${ref}\` — \`uniweb promote status\` lists what it has.`)
|
|
808
|
+
return null
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
/** Whether `--at`'s value is a time with its offset, as the backend takes one. */
|
|
812
|
+
function isTime(value) {
|
|
813
|
+
return typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})$/.test(value) && !Number.isNaN(Date.parse(value))
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
const sameInstant = (a, b) => typeof a === 'string' && typeof b === 'string' && Date.parse(a) === Date.parse(b)
|
|
817
|
+
|
|
818
|
+
/** An amount as money reads: `10.00` for the `10` YAML reads `10.00` as; a string as written. */
|
|
819
|
+
const money = (v) => (typeof v === 'number' && Number.isFinite(v) ? v.toFixed(2) : String(v))
|
|
820
|
+
|
|
821
|
+
/** Amounts summed in cents, kept as the decimal text a network reads: `15.00`; null when none is given. */
|
|
822
|
+
function sumAmounts(values) {
|
|
823
|
+
let cents = 0
|
|
824
|
+
let any = false
|
|
825
|
+
for (const v of values) {
|
|
826
|
+
const n = Math.round(Number(v) * 100)
|
|
827
|
+
if (v === null || v === undefined || v === '' || !Number.isFinite(n)) continue
|
|
828
|
+
cents += n
|
|
829
|
+
any = true
|
|
830
|
+
}
|
|
831
|
+
return any ? (cents / 100).toFixed(2) : null
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
// ── drafts: post, campaign, show, delete ───────────────────────────────────────────
|
|
835
|
+
|
|
836
|
+
/** A draft's text, from the file a command names or from stdin for `-`. */
|
|
837
|
+
function readInput(args, kind) {
|
|
838
|
+
const file = positionals(args)[1]
|
|
839
|
+
if (!file) return { error: `Name the draft: uniweb promote ${kind} <file>, or - to read it from stdin` }
|
|
840
|
+
if (file === '-') {
|
|
841
|
+
try {
|
|
842
|
+
return { file: null, shown: 'stdin', text: readFileSync(0, 'utf8'), dir: process.cwd() }
|
|
843
|
+
} catch (err) {
|
|
844
|
+
return { error: `Could not read stdin: ${err.message}` }
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
const path = resolve(file)
|
|
848
|
+
if (!existsSync(path) || !statSync(path).isFile()) return { error: `No file ${file}.` }
|
|
849
|
+
return { file: path, shown: file, text: readFileSync(path, 'utf8'), dir: dirname(path) }
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
/**
|
|
853
|
+
* A draft in the backend's terms: `via` as the site's `networks` item (made in the same write
|
|
854
|
+
* where the site has none for that network), `page` as the page's item, an ad's account one of its
|
|
855
|
+
* campaign's. Pictures stay as written until they are uploaded.
|
|
856
|
+
*/
|
|
857
|
+
function translateDraft(draft, { index, pages, connections }) {
|
|
858
|
+
const errors = []
|
|
859
|
+
const out = structuredClone(draft)
|
|
860
|
+
const via = viaResolver({ networks: index.top('networks'), connections, mint: mintUuidV7 })
|
|
861
|
+
const page = (raw, where) => {
|
|
862
|
+
if (raw && !pages) {
|
|
863
|
+
errors.push(`${where} links to a page, and the site has no content pushed here yet — push it first (uniweb push).`)
|
|
864
|
+
return undefined
|
|
865
|
+
}
|
|
866
|
+
const r = resolvePage(raw, pages, where)
|
|
867
|
+
if (r.error) errors.push(r.error)
|
|
868
|
+
return r.error ? undefined : r.uuid
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
if (draft.kind === 'post') {
|
|
872
|
+
if (draft.fields.via !== undefined || !draft.id) {
|
|
873
|
+
const r = via.resolve(draft.fields.via, 'posts', 'The post')
|
|
874
|
+
if (r.error) errors.push(r.error)
|
|
875
|
+
else out.fields.via = r.uuid
|
|
876
|
+
}
|
|
877
|
+
if (draft.fields.page !== undefined) out.fields.page = page(draft.fields.page, 'The post')
|
|
878
|
+
return { draft: out, creates: via.creates(), errors }
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
let campaignVia
|
|
882
|
+
if (draft.fields.via !== undefined) {
|
|
883
|
+
const list = draft.fields.via === null ? [] : Array.isArray(draft.fields.via) ? draft.fields.via : [draft.fields.via]
|
|
884
|
+
const uuids = []
|
|
885
|
+
list.forEach((raw, i) => {
|
|
886
|
+
const r = via.resolve(raw, 'ads', list.length > 1 ? `The campaign's account ${i + 1}` : 'The campaign')
|
|
887
|
+
if (r.error) errors.push(r.error)
|
|
888
|
+
else uuids.push(r.uuid)
|
|
889
|
+
})
|
|
890
|
+
out.fields.via = [...new Set(uuids)]
|
|
891
|
+
campaignVia = out.fields.via
|
|
892
|
+
} else {
|
|
893
|
+
const stored = draft.id ? index.byUuid.get(draft.id) : null
|
|
894
|
+
campaignVia = Array.isArray(stored?.data?.via) ? stored.data.via : []
|
|
895
|
+
}
|
|
896
|
+
const made = () => via.creates()
|
|
897
|
+
const accounts = campaignVia.map((u) => index.byUuid.get(u) ?? made().find((op) => op.uuid === u) ?? { uuid: u, data: {} })
|
|
898
|
+
|
|
899
|
+
for (const [i, g] of (draft.adGroups ?? []).entries()) {
|
|
900
|
+
for (const [j, a] of (g.ads ?? []).entries()) {
|
|
901
|
+
const where = `Ad ${j + 1} of ad group ${i + 1}`
|
|
902
|
+
const ad = out.adGroups[i].ads[j]
|
|
903
|
+
if (a.fields.via !== undefined && a.fields.via !== null) {
|
|
904
|
+
const raw = a.fields.via
|
|
905
|
+
const want = typeof raw === 'object' ? raw : { network: raw }
|
|
906
|
+
const matches = accounts.filter((n) =>
|
|
907
|
+
typeof raw === 'string' && idMatches(n.uuid, raw)
|
|
908
|
+
? true
|
|
909
|
+
: n.data?.network === want.network && (!want.connection || idMatches(n.data?.connection, String(want.connection)))
|
|
910
|
+
)
|
|
911
|
+
if (matches.length === 1) ad.fields.via = matches[0].uuid
|
|
912
|
+
else if (!matches.length) errors.push(`${where} goes through ${typeof raw === 'string' ? raw : want.network}, and the campaign does not run there — add it to the campaign's \`via\`.`)
|
|
913
|
+
else errors.push(`${where}: the campaign runs in ${matches.length} ${want.network} accounts — name the ad's by its id.`)
|
|
914
|
+
} else if (!a.id) {
|
|
915
|
+
if (accounts.length === 1) ad.fields.via = accounts[0].uuid
|
|
916
|
+
else if (accounts.length > 1) errors.push(`${where}: the campaign runs in ${accounts.length} ad accounts — name the one the ad runs in, \`via:\`.`)
|
|
917
|
+
}
|
|
918
|
+
if (a.fields.page !== undefined) ad.fields.page = page(a.fields.page, where)
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
return { draft: out, creates: via.creates(), errors }
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
/**
|
|
925
|
+
* Upload the pictures a draft names as files, each as one of the site's own and kept in its
|
|
926
|
+
* format, as the app uploads a post's picture. An address is kept as written.
|
|
927
|
+
*
|
|
928
|
+
* @returns {Promise<{ map: Map<string,string> } | { error: string }>} picture as written → its address
|
|
929
|
+
*/
|
|
930
|
+
async function uploadPictures(client, site, pictures, dir) {
|
|
931
|
+
const map = new Map()
|
|
932
|
+
const located = []
|
|
933
|
+
const used = new Set()
|
|
934
|
+
for (const p of pictures) {
|
|
935
|
+
if (isAddress(p)) continue
|
|
936
|
+
const path = isAbsolute(p) ? p : resolve(dir, p)
|
|
937
|
+
if (!existsSync(path) || !statSync(path).isFile()) {
|
|
938
|
+
// An address on the backend's own origin, as a read gives one back, is kept.
|
|
939
|
+
if (p.startsWith('/')) continue
|
|
940
|
+
return { error: `No picture ${p} (looked for ${path}).` }
|
|
941
|
+
}
|
|
942
|
+
// The name the upload is planned under: the file's own, never where it sits on this machine.
|
|
943
|
+
let name = basename(path)
|
|
944
|
+
for (let n = 2; used.has(name); n++) name = `${n}-${basename(path)}`
|
|
945
|
+
used.add(name)
|
|
946
|
+
located.push({ picture: p, ref: `/promote/${name}`, path })
|
|
947
|
+
}
|
|
948
|
+
if (!located.length) return { map }
|
|
949
|
+
const { uploadSiteMedia, describeAssetRefusal } = await import('../backend/site-media.js')
|
|
950
|
+
const refs = located.map(({ ref, path }) => ({ ref, path }))
|
|
951
|
+
const keepFormat = new Set(located.map((l) => l.ref))
|
|
952
|
+
let result
|
|
953
|
+
try {
|
|
954
|
+
// Charged to the site, which this command read: its owner exists before the bytes do.
|
|
955
|
+
result = await uploadSiteMedia(client, process.cwd(), refs, { siteUuid: site, keepFormat, warn: (m) => say.warn(m) })
|
|
956
|
+
} catch (err) {
|
|
957
|
+
const lines = describeAssetRefusal?.(err)
|
|
958
|
+
return { error: Array.isArray(lines) && lines.length ? lines.join('\n') : `The pictures could not be uploaded: ${err.message}` }
|
|
959
|
+
}
|
|
960
|
+
for (const l of located) {
|
|
961
|
+
const address = result.map?.[l.ref]
|
|
962
|
+
if (!address) return { error: `The picture ${l.picture} could not be uploaded${result.failed?.length ? ` (HTTP ${result.failed[0].status})` : ''}.` }
|
|
963
|
+
map.set(l.picture, address)
|
|
964
|
+
}
|
|
965
|
+
return { map }
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
/** Each picture as written replaced by its address. */
|
|
969
|
+
function withPictures(draft, map) {
|
|
970
|
+
const swap = (parts) => {
|
|
971
|
+
for (const p of parts ?? []) p.pictures = p.pictures.map((x) => map.get(x) ?? x)
|
|
972
|
+
}
|
|
973
|
+
swap(draft.parts)
|
|
974
|
+
for (const g of draft.adGroups ?? []) for (const a of g.ads ?? []) swap(a.parts)
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
/** The index after a write, from the write's own answer, for when it cannot be read again. */
|
|
978
|
+
function indexAfterWrite(index, ops, results) {
|
|
979
|
+
const items = new Map(index.items.map((i) => [i.uuid, { ...i }]))
|
|
980
|
+
ops.forEach((op, n) => {
|
|
981
|
+
const at = results?.[n]?.updated_at ?? null
|
|
982
|
+
if (op.kind === 'delete') items.delete(op.uuid)
|
|
983
|
+
else if (op.kind === 'update') items.set(op.uuid, { ...items.get(op.uuid), data: op.data, updated_at: at })
|
|
984
|
+
else items.set(op.uuid, { uuid: op.uuid, section: op.section, ...(op.parent ? { parent: op.parent } : {}), data: op.data, updated_at: at })
|
|
985
|
+
})
|
|
986
|
+
return indexPromotion({ uuid: index.uuid, items: [...items.values()] })
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
/**
|
|
990
|
+
* `uniweb promote post <file>` and `campaign <file>` — make a draft, or update the one the file
|
|
991
|
+
* names, and write its ids and versions back into the file.
|
|
992
|
+
*/
|
|
993
|
+
async function writeDraft(args, kind) {
|
|
994
|
+
const json = args.includes('--json')
|
|
995
|
+
const input = readInput(args, kind)
|
|
996
|
+
if (input.error) {
|
|
997
|
+
say.err(input.error)
|
|
998
|
+
return { exitCode: 2 }
|
|
999
|
+
}
|
|
1000
|
+
const format = formatOf(input.file, input.text)
|
|
1001
|
+
const parsed = parseDraft(input.text, { format, kind })
|
|
1002
|
+
if (parsed.error) {
|
|
1003
|
+
say.err(parsed.error)
|
|
1004
|
+
return { exitCode: 2 }
|
|
1005
|
+
}
|
|
1006
|
+
const draft = parsed.draft
|
|
1007
|
+
|
|
1008
|
+
const at = await begin(args, kind === 'post' ? 'Writing a post' : 'Writing a campaign', kind)
|
|
1009
|
+
if (!at.client) return at
|
|
1010
|
+
const { client, site } = at
|
|
1011
|
+
const index = await readIndex(client, site)
|
|
1012
|
+
if (!index) return { exitCode: 1 }
|
|
1013
|
+
const problems = checkDraft(index, draft)
|
|
1014
|
+
if (problems.length) {
|
|
1015
|
+
for (const p of problems) say.err(p)
|
|
1016
|
+
return { exitCode: 1 }
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
const [pages, connections] = await Promise.all([readPages(client, site), listedConnections(client)])
|
|
1020
|
+
const translated = translateDraft(draft, { index, pages, connections })
|
|
1021
|
+
if (translated.errors.length) {
|
|
1022
|
+
for (const e of translated.errors) say.err(e)
|
|
1023
|
+
return { exitCode: 2 }
|
|
1024
|
+
}
|
|
1025
|
+
const pictures = await uploadPictures(client, site, picturesOf(draft), input.dir)
|
|
1026
|
+
if (pictures.error) {
|
|
1027
|
+
say.err(pictures.error)
|
|
1028
|
+
return { exitCode: 1 }
|
|
1029
|
+
}
|
|
1030
|
+
withPictures(translated.draft, pictures.map)
|
|
1031
|
+
|
|
1032
|
+
const plan = (kind === 'post' ? planPost : planCampaign)(index, translated.draft, { mint: mintUuidV7, language: pages?.language })
|
|
1033
|
+
const ops = [...translated.creates, ...plan.ops]
|
|
1034
|
+
const wasScheduled = kind === 'post' && deliveryOf(index, index.byUuid.get(plan.uuid))?.status === 'scheduled'
|
|
1035
|
+
|
|
1036
|
+
let after = index
|
|
1037
|
+
if (ops.length) {
|
|
1038
|
+
const res = await client.writePromotionItems(site, ops)
|
|
1039
|
+
if (!res.ok) {
|
|
1040
|
+
await sayRefusal(res, { site, origin: client.origin, what: `write this site's ${kind}s`, index })
|
|
1041
|
+
return { exitCode: 1 }
|
|
1042
|
+
}
|
|
1043
|
+
const written = await res.json().catch(() => null)
|
|
1044
|
+
after = (await readIndex(client, site).catch(() => null)) ?? indexAfterWrite(index, ops, written?.results)
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
// The file keeps what it was written at, so the next run updates the same draft.
|
|
1048
|
+
const version = (uuid) => {
|
|
1049
|
+
const item = after.byUuid.get(uuid)
|
|
1050
|
+
return item ? versionOf(after, item) : null
|
|
1051
|
+
}
|
|
1052
|
+
let fileNote = null
|
|
1053
|
+
if (input.file) {
|
|
1054
|
+
const next = fileWithIdentity(input.text, { format, kind }, { uuid: plan.uuid, groups: plan.groups }, version)
|
|
1055
|
+
if (!next) fileNote = `Could not write the ids into ${input.shown} — its next run would make another draft. Add \`id: ${plan.uuid}\` and \`version: ${version(plan.uuid)}\` to it.`
|
|
1056
|
+
else if (next.text !== input.text) {
|
|
1057
|
+
writeFileSync(input.file, next.text)
|
|
1058
|
+
if (next.whole) fileNote = `Wrote ${input.shown} again whole, with its ids: its layout could not be kept.`
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
const ids = shortIds(after.items.map((i) => i.uuid))
|
|
1063
|
+
const item = after.byUuid.get(plan.uuid)
|
|
1064
|
+
const id = ids.get(plan.uuid) ?? plan.uuid
|
|
1065
|
+
if (json) {
|
|
1066
|
+
console.log(JSON.stringify({
|
|
1067
|
+
backend: client.origin,
|
|
1068
|
+
site,
|
|
1069
|
+
kind,
|
|
1070
|
+
id: plan.uuid,
|
|
1071
|
+
short: id,
|
|
1072
|
+
version: version(plan.uuid),
|
|
1073
|
+
made: !draft.id,
|
|
1074
|
+
writes: ops.length,
|
|
1075
|
+
file: input.file ? input.shown : null,
|
|
1076
|
+
kept: (plan.kept ?? []).map((k) => ({ ...k, short: ids.get(k.uuid) }))
|
|
1077
|
+
}))
|
|
1078
|
+
return { exitCode: 0 }
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
if (!ops.length) {
|
|
1082
|
+
say.ok(`Nothing to change: ${kind} ${id} already says what ${input.shown} says.`)
|
|
1083
|
+
} else if (kind === 'post') {
|
|
1084
|
+
const via = after.byUuid.get(item?.data?.via)
|
|
1085
|
+
const route = pageRoute(item?.data?.page, pages)
|
|
1086
|
+
say.ok(
|
|
1087
|
+
`${draft.id ? 'Updated' : 'Drafted'} post ${id}${via ? ` on ${via.data?.network}` : ''}` +
|
|
1088
|
+
`${route ? `, linking to ${route}` : ', linking to no page'}${item?.data?.language ? ` (${item.data.language})` : ''}.`
|
|
1089
|
+
)
|
|
1090
|
+
if (wasScheduled && deliveryOf(after, item)?.status !== 'scheduled') {
|
|
1091
|
+
say.warn(`It was scheduled, and a change makes it a draft again, its time kept: uniweb promote send ${id} schedules it again.`)
|
|
1092
|
+
}
|
|
1093
|
+
} else {
|
|
1094
|
+
const groups = after.children('campaigns/ad_groups', plan.uuid)
|
|
1095
|
+
const ads = groups.flatMap((g) => after.children('campaigns/ad_groups/ads', g.uuid))
|
|
1096
|
+
const accounts = (Array.isArray(item?.data?.via) ? item.data.via : []).map((u) => accountName(after, u, connections))
|
|
1097
|
+
say.ok(
|
|
1098
|
+
`${draft.id ? 'Updated' : 'Drafted'} campaign ${labelOf(after, item)} (${id}): ${groups.length} ad group${groups.length === 1 ? '' : 's'}, ` +
|
|
1099
|
+
`${ads.length} ad${ads.length === 1 ? '' : 's'}, ${accounts.length ? `in ${accounts.join(', ')}` : 'in no ad account yet'}.`
|
|
1100
|
+
)
|
|
1101
|
+
for (const k of plan.kept) {
|
|
1102
|
+
say.info(`Kept, not in your file: ${k.kind} ${k.name ? `“${k.name}” ` : ''}(${ids.get(k.uuid)}). \`uniweb promote delete ${ids.get(k.uuid)}\` deletes it.`)
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
if (fileNote) say.warn(fileNote)
|
|
1106
|
+
else if (!input.file && ops.length) say.dim(`From stdin, so no file keeps its ids: give your next draft of it \`id: ${plan.uuid}\` and \`version: ${version(plan.uuid)}\`.`)
|
|
1107
|
+
// The pages it lands on, checked in the site's files where this project holds them.
|
|
1108
|
+
const landing = landingOf(after, item, pages)
|
|
1109
|
+
const dir = landing.routes.length ? await siteFilesFor(site, client.origin) : null
|
|
1110
|
+
if (dir) {
|
|
1111
|
+
console.log()
|
|
1112
|
+
await landingNotes(dir, landing.routes, { networks: landing.networks, goal: landing.goal })
|
|
1113
|
+
}
|
|
1114
|
+
if (kind === 'post' && wentOut(deliveryOf(after, item)) === false) {
|
|
1115
|
+
const sendAt = item?.data?.send_at
|
|
1116
|
+
if (deliveryOf(after, item)?.status === 'scheduled') say.dim(`Scheduled for ${sendAt}: \`uniweb promote unschedule ${id}\` makes it a draft again`)
|
|
1117
|
+
else say.dim(sendAt ? `Send it at its time, ${sendAt}: uniweb promote send ${id}` : `Send it: uniweb promote send ${id} [--at <time>]`)
|
|
1118
|
+
} else if (kind === 'campaign') {
|
|
1119
|
+
say.dim(`Start it: uniweb promote start ${id} — it says what it will spend, and asks first`)
|
|
1120
|
+
}
|
|
1121
|
+
return { exitCode: 0 }
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
/** The routes a post or a campaign lands on, the networks it goes out on, and a campaign's goal. */
|
|
1125
|
+
function landingOf(index, item, pages) {
|
|
1126
|
+
if (!item) return { routes: [], networks: [], goal: null }
|
|
1127
|
+
const networkOf = (uuid) => index.byUuid.get(uuid)?.data?.network
|
|
1128
|
+
if (item.section === 'posts') {
|
|
1129
|
+
const route = pages?.byUuid.get(item.data?.page)?.route
|
|
1130
|
+
return { routes: route ? [route] : [], networks: [networkOf(item.data?.via)].filter(Boolean), goal: null }
|
|
1131
|
+
}
|
|
1132
|
+
const ads = index.children('campaigns/ad_groups', item.uuid).flatMap((g) => index.children('campaigns/ad_groups/ads', g.uuid))
|
|
1133
|
+
const routes = [...new Set(ads.map((a) => pages?.byUuid.get(a.data?.page)?.route).filter(Boolean))]
|
|
1134
|
+
const via = Array.isArray(item.data?.via) ? item.data.via : []
|
|
1135
|
+
return { routes, networks: [...new Set(via.map(networkOf).filter(Boolean))], goal: item.data?.goal ?? null }
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
/** What a post or a campaign is doing, in lines: its state, and each delivery's. */
|
|
1139
|
+
function stateLines(index, target, connections) {
|
|
1140
|
+
const ids = shortIds(index.items.map((i) => i.uuid))
|
|
1141
|
+
const lines = []
|
|
1142
|
+
if (target.section === 'posts') {
|
|
1143
|
+
const d = deliveryOf(index, target)
|
|
1144
|
+
const state = d?.status ?? 'draft'
|
|
1145
|
+
lines.push(`Post ${ids.get(target.uuid)}: ${state}${d?.status === 'scheduled' && target.data?.send_at ? ` for ${target.data.send_at}` : ''}${d?.sent_at ? ` at ${d.sent_at}` : ''}`)
|
|
1146
|
+
if (d?.network_url) lines.push(` on the network: ${d.network_url}`)
|
|
1147
|
+
if (d?.link) lines.push(` it links to: ${d.link}`)
|
|
1148
|
+
if (d?.reason) lines.push(` ${reasonWords(d.reason)}${d.detail ? ` — ${d.detail}` : ''}`)
|
|
1149
|
+
return lines
|
|
1150
|
+
}
|
|
1151
|
+
const deliveries = campaignDeliveries(index, target)
|
|
1152
|
+
const state = deliveries.length ? [...new Set(deliveries.map((d) => d.status))].join(', ') : 'draft'
|
|
1153
|
+
lines.push(`Campaign ${ids.get(target.uuid)} ${labelOf(index, target)}: ${state}${target.data?.tag ? ` (tag ${target.data.tag})` : ''}`)
|
|
1154
|
+
for (const d of deliveries) {
|
|
1155
|
+
lines.push(` ${accountName(index, d.via, connections)}: ${d.status}${d.review ? `, the network's review: ${reviewWords(d.review)}` : ''}${d.currency ? `, in ${d.currency}` : ''}${d.reason ? ` — ${reasonWords(d.reason)}` : ''}${d.detail ? ` (${d.detail})` : ''}`)
|
|
1156
|
+
}
|
|
1157
|
+
for (const g of index.children('campaigns/ad_groups', target.uuid)) {
|
|
1158
|
+
for (const a of index.children('campaigns/ad_groups/ads', g.uuid)) {
|
|
1159
|
+
const d = deliveryOf(index, a)
|
|
1160
|
+
if (d) lines.push(` ad ${ids.get(a.uuid)} ${labelOf(index, a)}: ${d.status}${d.reason ? ` — ${reasonWords(d.reason)}` : ''}${d.network_url ? ` ${d.network_url}` : ''}`)
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
return lines
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
/**
|
|
1167
|
+
* `uniweb promote show <id>` — one post or campaign as a draft holds it, so it round-trips: a
|
|
1168
|
+
* post as Markdown, a campaign as YAML. What it is doing goes to stderr, so `show <id> > file`
|
|
1169
|
+
* keeps the draft alone.
|
|
1170
|
+
*/
|
|
1171
|
+
async function show(args) {
|
|
1172
|
+
const json = args.includes('--json')
|
|
1173
|
+
const arg = positionals(args)[1]
|
|
1174
|
+
if (!arg) {
|
|
1175
|
+
say.err('Name it: uniweb promote show <id>')
|
|
1176
|
+
return { exitCode: 2 }
|
|
1177
|
+
}
|
|
1178
|
+
const at = await begin(args, 'Reading the site\'s Promote', `show ${arg}`)
|
|
1179
|
+
if (!at.client) return at
|
|
1180
|
+
const { client, site } = at
|
|
1181
|
+
const index = await readIndex(client, site)
|
|
1182
|
+
if (!index) return { exitCode: 1 }
|
|
1183
|
+
const item = pick(index, arg, ['post', 'campaign', 'ad group', 'ad'])
|
|
1184
|
+
if (!item) return { exitCode: 2 }
|
|
1185
|
+
const target = item.section === 'posts' ? item : campaignOf(index, item)
|
|
1186
|
+
const [pages, connections] = await Promise.all([readPages(client, site), listedConnections(client)])
|
|
1187
|
+
const shape = target.section === 'posts' ? postShape(index, target, pages) : campaignShape(index, target, pages)
|
|
1188
|
+
if (json) {
|
|
1189
|
+
const ids = shortIds(index.items.map((i) => i.uuid))
|
|
1190
|
+
console.log(JSON.stringify({
|
|
1191
|
+
backend: client.origin,
|
|
1192
|
+
site,
|
|
1193
|
+
kind: kindOf(target),
|
|
1194
|
+
short: ids.get(target.uuid),
|
|
1195
|
+
draft: shape,
|
|
1196
|
+
...(target.section === 'posts'
|
|
1197
|
+
? { delivery: deliveryOf(index, target) }
|
|
1198
|
+
: {
|
|
1199
|
+
tag: target.data?.tag ?? null,
|
|
1200
|
+
deliveries: campaignDeliveries(index, target),
|
|
1201
|
+
ads: index.children('campaigns/ad_groups', target.uuid).flatMap((g) =>
|
|
1202
|
+
index.children('campaigns/ad_groups/ads', g.uuid).map((a) => ({ id: a.uuid, short: ids.get(a.uuid), delivery: deliveryOf(index, a) }))
|
|
1203
|
+
)
|
|
1204
|
+
})
|
|
1205
|
+
}))
|
|
1206
|
+
return { exitCode: 0 }
|
|
1207
|
+
}
|
|
1208
|
+
for (const line of stateLines(index, target, connections)) console.error(`${c.dim}${line}${c.reset}`)
|
|
1209
|
+
const text = target.section === 'posts' ? (postMarkdown(shape) ?? shapeYaml(shape)) : shapeYaml(shape)
|
|
1210
|
+
console.log(text.replace(/\n$/, ''))
|
|
1211
|
+
return { exitCode: 0 }
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
/** `uniweb promote delete <id>` — a post, a campaign, an ad group or an ad. */
|
|
1215
|
+
async function deleteItem(args) {
|
|
1216
|
+
const json = args.includes('--json')
|
|
1217
|
+
const arg = positionals(args)[1]
|
|
1218
|
+
if (!arg) {
|
|
1219
|
+
say.err('Name it: uniweb promote delete <id>')
|
|
1220
|
+
return { exitCode: 2 }
|
|
1221
|
+
}
|
|
1222
|
+
const at = await begin(args, 'Deleting a draft', `delete ${arg}`)
|
|
1223
|
+
if (!at.client) return at
|
|
1224
|
+
const { client, site } = at
|
|
1225
|
+
const index = await readIndex(client, site)
|
|
1226
|
+
if (!index) return { exitCode: 1 }
|
|
1227
|
+
const item = pick(index, arg, ['post', 'campaign', 'ad group', 'ad'])
|
|
1228
|
+
if (!item) return { exitCode: 2 }
|
|
1229
|
+
const ids = shortIds(index.items.map((i) => i.uuid))
|
|
1230
|
+
const what = `${kindOf(item)} ${labelOf(index, item)} (${ids.get(item.uuid)})`
|
|
1231
|
+
if (item.section === 'posts' && wentOut(deliveryOf(index, item))) {
|
|
1232
|
+
say.err(`The ${what} went out: deleting its record here would not take it off the network, and it is the site's history. It stays.`)
|
|
1233
|
+
return { exitCode: 2 }
|
|
1234
|
+
}
|
|
1235
|
+
const res = await client.writePromotionItems(site, [{ kind: 'delete', uuid: item.uuid, if_unmodified_since: item.updated_at }])
|
|
1236
|
+
if (!res.ok) {
|
|
1237
|
+
await sayRefusal(res, { site, origin: client.origin, what: 'delete it', index })
|
|
1238
|
+
return { exitCode: 1 }
|
|
1239
|
+
}
|
|
1240
|
+
if (json) console.log(JSON.stringify({ backend: client.origin, site, kind: kindOf(item), id: item.uuid, deleted: true }))
|
|
1241
|
+
else say.ok(`Deleted the ${what}.`)
|
|
1242
|
+
return { exitCode: 0 }
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
// ── going out: send, unschedule, start, resume, pause ─────────────────────────────
|
|
1246
|
+
|
|
1247
|
+
/** A post's delivery, said: where it went out, when it will, or why it didn't. */
|
|
1248
|
+
function sayDelivery(index, post, delivery, id) {
|
|
1249
|
+
const network = index.byUuid.get(post.data?.via)?.data?.network ?? 'its network'
|
|
1250
|
+
if (delivery?.status === 'published') {
|
|
1251
|
+
say.ok(`Posted ${id} on ${network}${delivery.network_url ? `: ${delivery.network_url}` : ''}`)
|
|
1252
|
+
if (delivery.link) say.dim(`It links to ${delivery.link}`)
|
|
1253
|
+
return 0
|
|
1254
|
+
}
|
|
1255
|
+
if (delivery?.status === 'scheduled') {
|
|
1256
|
+
say.ok(`Scheduled ${id} on ${network} for ${post.data?.send_at ?? 'its time'}. It goes out then as it stands, under your name.`)
|
|
1257
|
+
return 0
|
|
1258
|
+
}
|
|
1259
|
+
if (delivery?.status === 'failed' || delivery?.status === 'refused') {
|
|
1260
|
+
say.err(`Not posted: ${reasonWords(delivery.reason)}${delivery.detail ? ` — ${delivery.detail}` : ''}`)
|
|
1261
|
+
return 1
|
|
1262
|
+
}
|
|
1263
|
+
say.warn(`The backend answered ${delivery?.status ?? 'no delivery'} for ${id}.`)
|
|
1264
|
+
return 0
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
/**
|
|
1268
|
+
* `uniweb promote send <post> [--at <time> | --now]` — post it now, or at a time.
|
|
1269
|
+
*
|
|
1270
|
+
* ⭐ A POST WITH A TIME GOES OUT AT ITS TIME. Its `send_at` is the draft's own field, so `send`
|
|
1271
|
+
* schedules a post that holds one and posts one that holds none; `--at` sets the time first, and
|
|
1272
|
+
* `--now` posts it now whatever its time.
|
|
1273
|
+
*/
|
|
1274
|
+
async function send(args) {
|
|
1275
|
+
const json = args.includes('--json')
|
|
1276
|
+
const arg = positionals(args)[1]
|
|
1277
|
+
const now = args.includes('--now')
|
|
1278
|
+
const atGiven = args.includes('--at')
|
|
1279
|
+
const time = flagValue(args, '--at')
|
|
1280
|
+
if (!arg) {
|
|
1281
|
+
say.err('Name the post: uniweb promote send <post> [--at <time> | --now]')
|
|
1282
|
+
return { exitCode: 2 }
|
|
1283
|
+
}
|
|
1284
|
+
if (now && atGiven) {
|
|
1285
|
+
say.err('`--now` and `--at` each say when — give one.')
|
|
1286
|
+
return { exitCode: 2 }
|
|
1287
|
+
}
|
|
1288
|
+
if (atGiven && !isTime(time)) {
|
|
1289
|
+
say.err('`--at` takes a time with its offset, such as 2026-11-24T09:00-05:00.')
|
|
1290
|
+
return { exitCode: 2 }
|
|
1291
|
+
}
|
|
1292
|
+
if (atGiven && Date.parse(time) <= Date.now()) {
|
|
1293
|
+
say.err(`\`--at ${time}\` has passed: give a time ahead, or send it now with --now.`)
|
|
1294
|
+
return { exitCode: 2 }
|
|
1295
|
+
}
|
|
1296
|
+
const at = await begin(args, 'Sending a post', `send ${arg}`)
|
|
1297
|
+
if (!at.client) return at
|
|
1298
|
+
const { client, site } = at
|
|
1299
|
+
const index = await readIndex(client, site)
|
|
1300
|
+
if (!index) return { exitCode: 1 }
|
|
1301
|
+
const post = pick(index, arg, ['post'])
|
|
1302
|
+
if (!post) return { exitCode: 2 }
|
|
1303
|
+
const id = shortIds(index.items.map((i) => i.uuid)).get(post.uuid)
|
|
1304
|
+
const before = deliveryOf(index, post)
|
|
1305
|
+
const out = (delivery, exitCode) => {
|
|
1306
|
+
if (json) console.log(JSON.stringify({ backend: client.origin, site, id: post.uuid, short: id, delivery }))
|
|
1307
|
+
return { exitCode }
|
|
1308
|
+
}
|
|
1309
|
+
if (wentOut(before)) {
|
|
1310
|
+
if (!json) say.warn(`Post ${id} went out already${before.network_url ? `: ${before.network_url}` : ''}. A new post is a new draft.`)
|
|
1311
|
+
return out(before, 0)
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
const when = now ? null : atGiven ? time : (post.data?.send_at ?? null)
|
|
1315
|
+
if (when && !atGiven && Date.parse(when) <= Date.now()) {
|
|
1316
|
+
say.err(`Post ${id} holds send_at ${when}, which has passed: send it now with --now, or at another time with --at <time>.`)
|
|
1317
|
+
return { exitCode: 2 }
|
|
1318
|
+
}
|
|
1319
|
+
let res
|
|
1320
|
+
let moved = false
|
|
1321
|
+
if (when) {
|
|
1322
|
+
if (before?.status === 'scheduled' && sameInstant(post.data?.send_at, when)) {
|
|
1323
|
+
if (!json) say.ok(`Post ${id} is scheduled for ${post.data.send_at} already.`)
|
|
1324
|
+
return out(before, 0)
|
|
1325
|
+
}
|
|
1326
|
+
if (!sameInstant(post.data?.send_at, when)) {
|
|
1327
|
+
// The time is the post's own field, written first. A write makes a scheduled post a draft again.
|
|
1328
|
+
const wrote = await client.writePromotionItems(site, [
|
|
1329
|
+
{ kind: 'update', uuid: post.uuid, data: { ...post.data, send_at: when }, if_unmodified_since: post.updated_at }
|
|
1330
|
+
])
|
|
1331
|
+
if (!wrote.ok) {
|
|
1332
|
+
await sayRefusal(wrote, { site, origin: client.origin, what: 'set its time', index })
|
|
1333
|
+
return { exitCode: 1 }
|
|
1334
|
+
}
|
|
1335
|
+
post.data = { ...post.data, send_at: when }
|
|
1336
|
+
moved = true
|
|
1337
|
+
}
|
|
1338
|
+
res = await client.postAction(site, post.uuid, 'schedule')
|
|
1339
|
+
} else {
|
|
1340
|
+
res = await client.postAction(site, post.uuid, 'publish')
|
|
1341
|
+
}
|
|
1342
|
+
if (!res.ok) {
|
|
1343
|
+
await sayRefusal(res, { site, origin: client.origin, what: 'send posts', index })
|
|
1344
|
+
return { exitCode: 1 }
|
|
1345
|
+
}
|
|
1346
|
+
const delivery = (await res.json().catch(() => null))?.delivery ?? null
|
|
1347
|
+
// A file the post was drafted in keeps its new time and version, so its next run is not stale.
|
|
1348
|
+
const file = moved ? draftFile(arg) : null
|
|
1349
|
+
if (file) {
|
|
1350
|
+
const after = await readIndex(client, site).catch(() => null)
|
|
1351
|
+
const item = after?.byUuid.get(post.uuid)
|
|
1352
|
+
const next = item ? fileWithFields(file.text, file.format, { send_at: when, version: versionOf(after, item) }) : null
|
|
1353
|
+
if (next) writeFileSync(file.path, next)
|
|
1354
|
+
else if (!json) say.warn(`Could not write its new time into ${arg}: run \`uniweb promote show ${id} > ${arg}\` before you edit it again.`)
|
|
1355
|
+
}
|
|
1356
|
+
if (json) return out(delivery, delivery?.status === 'failed' || delivery?.status === 'refused' ? 1 : 0)
|
|
1357
|
+
return { exitCode: sayDelivery(index, post, delivery, id) }
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
/** `uniweb promote unschedule <post>` — a scheduled post a draft again, its time kept. */
|
|
1361
|
+
async function unschedule(args) {
|
|
1362
|
+
const json = args.includes('--json')
|
|
1363
|
+
const arg = positionals(args)[1]
|
|
1364
|
+
if (!arg) {
|
|
1365
|
+
say.err('Name the post: uniweb promote unschedule <post>')
|
|
1366
|
+
return { exitCode: 2 }
|
|
1367
|
+
}
|
|
1368
|
+
const at = await begin(args, 'Unscheduling a post', `unschedule ${arg}`)
|
|
1369
|
+
if (!at.client) return at
|
|
1370
|
+
const { client, site } = at
|
|
1371
|
+
const index = await readIndex(client, site)
|
|
1372
|
+
if (!index) return { exitCode: 1 }
|
|
1373
|
+
const post = pick(index, arg, ['post'])
|
|
1374
|
+
if (!post) return { exitCode: 2 }
|
|
1375
|
+
const id = shortIds(index.items.map((i) => i.uuid)).get(post.uuid)
|
|
1376
|
+
const before = deliveryOf(index, post)
|
|
1377
|
+
if (before?.status !== 'scheduled') {
|
|
1378
|
+
if (json) console.log(JSON.stringify({ backend: client.origin, site, id: post.uuid, short: id, delivery: before }))
|
|
1379
|
+
else say.info(`Post ${id} is not scheduled (${before?.status ?? 'a draft'}): nothing to do.`)
|
|
1380
|
+
return { exitCode: 0 }
|
|
1381
|
+
}
|
|
1382
|
+
const res = await client.postAction(site, post.uuid, 'unschedule')
|
|
1383
|
+
if (!res.ok) {
|
|
1384
|
+
await sayRefusal(res, { site, origin: client.origin, what: 'unschedule posts', index })
|
|
1385
|
+
return { exitCode: 1 }
|
|
1386
|
+
}
|
|
1387
|
+
const delivery = (await res.json().catch(() => null))?.delivery ?? null
|
|
1388
|
+
if (json) console.log(JSON.stringify({ backend: client.origin, site, id: post.uuid, short: id, delivery }))
|
|
1389
|
+
else say.ok(`Post ${id} is a draft again, its time kept (${post.data?.send_at ?? 'none'}): uniweb promote send ${id} schedules it again.`)
|
|
1390
|
+
return { exitCode: 0 }
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
/**
|
|
1394
|
+
* What starting (or resuming) a campaign in these ad accounts will spend, as far as the draft
|
|
1395
|
+
* says: its dates, and per account the ad groups whose ads run there, with their daily budgets
|
|
1396
|
+
* and the most that comes to. The currency is the account's, which the network knows.
|
|
1397
|
+
*/
|
|
1398
|
+
function spendSummary(index, campaign, accounts, { connections, pages }) {
|
|
1399
|
+
const starts = campaign.data?.starts ?? null
|
|
1400
|
+
const ends = campaign.data?.ends ?? null
|
|
1401
|
+
const days = starts && ends ? Math.round((Date.parse(ends) - Date.parse(starts)) / 86400000) + 1 : null
|
|
1402
|
+
return {
|
|
1403
|
+
name: campaign.data?.name ?? null,
|
|
1404
|
+
starts,
|
|
1405
|
+
ends,
|
|
1406
|
+
days: Number.isFinite(days) && days > 0 ? days : null,
|
|
1407
|
+
accounts: accounts.map((via) => {
|
|
1408
|
+
const groups = index
|
|
1409
|
+
.children('campaigns/ad_groups', campaign.uuid)
|
|
1410
|
+
.map((g) => ({ g, ads: index.children('campaigns/ad_groups/ads', g.uuid).filter((a) => a.data?.via === via) }))
|
|
1411
|
+
.filter((x) => x.ads.length)
|
|
1412
|
+
const daily = sumAmounts(groups.map((x) => x.g.data?.daily_budget))
|
|
1413
|
+
const total = daily !== null && Number.isFinite(days) && days > 0 ? (Math.round(Number(daily) * 100) * days / 100).toFixed(2) : null
|
|
1414
|
+
return {
|
|
1415
|
+
via,
|
|
1416
|
+
account: accountName(index, via, connections),
|
|
1417
|
+
groups: groups.map((x) => ({ name: x.g.data?.name ?? null, daily_budget: x.g.data?.daily_budget ?? null, ads: x.ads.length })),
|
|
1418
|
+
daily,
|
|
1419
|
+
upTo: total,
|
|
1420
|
+
pages: [...new Set(groups.flatMap((x) => x.ads.map((a) => pageRoute(a.data?.page, pages) ?? '(no page)')))]
|
|
1421
|
+
}
|
|
1422
|
+
})
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
function printSummary(summary, act) {
|
|
1427
|
+
const dates = summary.starts || summary.ends
|
|
1428
|
+
? `${summary.starts ?? 'now'} – ${summary.ends ?? 'until paused'}${summary.days ? `, ${summary.days} day${summary.days === 1 ? '' : 's'}` : ''}`
|
|
1429
|
+
: 'no dates: it runs from now until paused'
|
|
1430
|
+
console.log(`${act === 'start' ? 'Starting' : 'Resuming'} “${summary.name ?? '?'}”, ${dates}, in the owner's ad account${summary.accounts.length === 1 ? '' : 's'}:`)
|
|
1431
|
+
for (const a of summary.accounts) {
|
|
1432
|
+
if (!a.groups.length) {
|
|
1433
|
+
console.log(` ${a.account}: no ad runs there yet`)
|
|
1434
|
+
continue
|
|
1435
|
+
}
|
|
1436
|
+
const budgets = a.groups.map((g) => (g.daily_budget == null ? 'no daily budget' : money(g.daily_budget))).join(' + ')
|
|
1437
|
+
console.log(` ${a.account}: ${a.groups.length} ad group${a.groups.length === 1 ? '' : 's'}, ${budgets} a day in the account's currency${a.upTo ? ` — up to ${a.upTo}` : summary.ends ? '' : ', until paused'}`)
|
|
1438
|
+
const ads = a.groups.reduce((n, g) => n + g.ads, 0)
|
|
1439
|
+
console.log(` ${ads} ad${ads === 1 ? '' : 's'}, linking to ${a.pages.join(', ')}`)
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
/** A campaign's deliveries, said: where it runs, where it waits, and why. */
|
|
1444
|
+
function sayDeliveries(index, deliveries, connections, act) {
|
|
1445
|
+
let running = 0
|
|
1446
|
+
for (const d of deliveries) {
|
|
1447
|
+
const account = accountName(index, d.via, connections)
|
|
1448
|
+
if (d.status === 'active') {
|
|
1449
|
+
running++
|
|
1450
|
+
say.ok(`Running in ${account}${d.review ? `, the network's review: ${reviewWords(d.review)}` : ''}${d.currency ? `, spending in ${d.currency}` : ''}`)
|
|
1451
|
+
} else if (d.status === 'paused') {
|
|
1452
|
+
say.ok(`Paused in ${account}${d.reason ? ` — ${reasonWords(d.reason)}` : ''}`)
|
|
1453
|
+
} else {
|
|
1454
|
+
say.warn(`${d.status === 'attention' ? 'Not running' : d.status} in ${account}${d.reason ? `: ${reasonWords(d.reason)}` : ''}${d.detail ? ` — ${d.detail}` : ''}`)
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
if (act === 'start' && running) say.dim('What runs in an account is fixed there now: a change is a new ad account in its `via`, or a new campaign.')
|
|
1458
|
+
return deliveries.length && !running && act !== 'pause' ? 1 : 0
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
/**
|
|
1462
|
+
* `uniweb promote start | resume <campaign> [--yes]` — spend in the owner's ad accounts.
|
|
1463
|
+
*
|
|
1464
|
+
* ⭐ IT SAYS WHAT IT WILL SPEND, THEN ASKS [Diego, 2026-11-16: "if you thing we need confirmation,
|
|
1465
|
+
* it can be done, with `--yes` as a way to skip it"]. At a terminal it asks; `--yes` answers, as an
|
|
1466
|
+
* agent passes it once its person has agreed; with neither it refuses rather than spend unseen.
|
|
1467
|
+
*/
|
|
1468
|
+
async function spend(args, act) {
|
|
1469
|
+
const json = args.includes('--json')
|
|
1470
|
+
const arg = positionals(args)[1]
|
|
1471
|
+
if (!arg) {
|
|
1472
|
+
say.err(`Name the campaign: uniweb promote ${act} <campaign> [--yes]`)
|
|
1473
|
+
return { exitCode: 2 }
|
|
1474
|
+
}
|
|
1475
|
+
const at = await begin(args, act === 'start' ? 'Starting a campaign' : 'Resuming a campaign', `${act} ${arg}`)
|
|
1476
|
+
if (!at.client) return at
|
|
1477
|
+
const { client, site } = at
|
|
1478
|
+
const index = await readIndex(client, site)
|
|
1479
|
+
if (!index) return { exitCode: 1 }
|
|
1480
|
+
const campaign = pick(index, arg, ['campaign'])
|
|
1481
|
+
if (!campaign) return { exitCode: 2 }
|
|
1482
|
+
const deliveries = campaignDeliveries(index, campaign)
|
|
1483
|
+
const via = Array.isArray(campaign.data?.via) ? campaign.data.via : []
|
|
1484
|
+
const accounts =
|
|
1485
|
+
act === 'start'
|
|
1486
|
+
? via.filter((u) => !deliveries.some((d) => d.via === u && d.external_id))
|
|
1487
|
+
: deliveries.filter((d) => d.external_id && d.status === 'paused').map((d) => d.via)
|
|
1488
|
+
const name = labelOf(index, campaign)
|
|
1489
|
+
if (!accounts.length) {
|
|
1490
|
+
const why =
|
|
1491
|
+
act === 'resume'
|
|
1492
|
+
? `${name} is paused nowhere.`
|
|
1493
|
+
: via.length
|
|
1494
|
+
? `${name} runs in every ad account of its \`via\` already.`
|
|
1495
|
+
: `${name} names no ad account yet — give it one in its \`via\`: uniweb promote campaign <file>`
|
|
1496
|
+
if (json) console.log(JSON.stringify({ backend: client.origin, site, id: campaign.uuid, act, accounts: [], deliveries }))
|
|
1497
|
+
else say.info(why)
|
|
1498
|
+
return { exitCode: act === 'start' && !via.length ? 2 : 0 }
|
|
1499
|
+
}
|
|
1500
|
+
const [connections, pages] = await Promise.all([listedConnections(client), readPages(client, site)])
|
|
1501
|
+
const summary = spendSummary(index, campaign, accounts, { connections, pages })
|
|
1502
|
+
if (!json) printSummary(summary, act)
|
|
1503
|
+
// What the campaign's pages show and what its networks will hear, before anything is spent.
|
|
1504
|
+
const landing = landingOf(index, campaign, pages)
|
|
1505
|
+
const dir = !json && landing.routes.length ? await siteFilesFor(site, client.origin) : null
|
|
1506
|
+
if (dir) await landingNotes(dir, landing.routes, { networks: landing.networks, goal: landing.goal })
|
|
1507
|
+
|
|
1508
|
+
if (!args.includes('--yes')) {
|
|
1509
|
+
if (json || isNonInteractive(args)) {
|
|
1510
|
+
say.err(`\`uniweb promote ${act}\` spends in the owner's ad accounts, so it asks first — pass --yes once your person has agreed to what it will spend.`)
|
|
1511
|
+
return { exitCode: 2 }
|
|
1512
|
+
}
|
|
1513
|
+
if (!(await confirm(`${act === 'start' ? 'Start' : 'Resume'} it?`, false))) {
|
|
1514
|
+
say.info(`Cancelled — nothing ${act === 'start' ? 'started' : 'resumed'}.`)
|
|
1515
|
+
return { exitCode: 0 }
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
const res = await client.campaignAction(site, campaign.uuid, act)
|
|
1519
|
+
if (!res.ok) {
|
|
1520
|
+
await sayRefusal(res, { site, origin: client.origin, what: `${act} campaigns`, index })
|
|
1521
|
+
return { exitCode: 1 }
|
|
1522
|
+
}
|
|
1523
|
+
const answered = (await res.json().catch(() => null))?.deliveries ?? []
|
|
1524
|
+
if (json) {
|
|
1525
|
+
console.log(JSON.stringify({ backend: client.origin, site, id: campaign.uuid, act, summary, deliveries: answered }))
|
|
1526
|
+
return { exitCode: answered.length && !answered.some((d) => d.status === 'active') ? 1 : 0 }
|
|
1527
|
+
}
|
|
1528
|
+
return { exitCode: sayDeliveries(index, answered, connections, act) }
|
|
1529
|
+
}
|
|
1530
|
+
|
|
1531
|
+
/** `uniweb promote pause <campaign>` — wherever it runs. It stops the spending and asks nothing. */
|
|
1532
|
+
async function pause(args) {
|
|
1533
|
+
const json = args.includes('--json')
|
|
1534
|
+
const arg = positionals(args)[1]
|
|
1535
|
+
if (!arg) {
|
|
1536
|
+
say.err('Name the campaign: uniweb promote pause <campaign>')
|
|
1537
|
+
return { exitCode: 2 }
|
|
1538
|
+
}
|
|
1539
|
+
const at = await begin(args, 'Pausing a campaign', `pause ${arg}`)
|
|
1540
|
+
if (!at.client) return at
|
|
1541
|
+
const { client, site } = at
|
|
1542
|
+
const index = await readIndex(client, site)
|
|
1543
|
+
if (!index) return { exitCode: 1 }
|
|
1544
|
+
const campaign = pick(index, arg, ['campaign'])
|
|
1545
|
+
if (!campaign) return { exitCode: 2 }
|
|
1546
|
+
if (!campaignDeliveries(index, campaign).some((d) => d.external_id && d.status !== 'paused')) {
|
|
1547
|
+
if (json) console.log(JSON.stringify({ backend: client.origin, site, id: campaign.uuid, act: 'pause', deliveries: campaignDeliveries(index, campaign) }))
|
|
1548
|
+
else say.info(`${labelOf(index, campaign)} runs nowhere: nothing to pause.`)
|
|
1549
|
+
return { exitCode: 0 }
|
|
1550
|
+
}
|
|
1551
|
+
const res = await client.campaignAction(site, campaign.uuid, 'pause')
|
|
1552
|
+
if (!res.ok) {
|
|
1553
|
+
await sayRefusal(res, { site, origin: client.origin, what: 'pause campaigns', index })
|
|
1554
|
+
return { exitCode: 1 }
|
|
1555
|
+
}
|
|
1556
|
+
const answered = (await res.json().catch(() => null))?.deliveries ?? []
|
|
1557
|
+
if (json) {
|
|
1558
|
+
console.log(JSON.stringify({ backend: client.origin, site, id: campaign.uuid, act: 'pause', deliveries: answered }))
|
|
1559
|
+
return { exitCode: 0 }
|
|
1560
|
+
}
|
|
1561
|
+
const connections = await listedConnections(client)
|
|
1562
|
+
return { exitCode: sayDeliveries(index, answered, connections, 'pause') }
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
// ── the command ────────────────────────────────────────────────────────────────────
|
|
1566
|
+
|
|
1567
|
+
export async function promote(args = []) {
|
|
1568
|
+
const badFlag = checkFlags('promote', args)
|
|
1569
|
+
if (badFlag) {
|
|
1570
|
+
say.err(badFlag.message)
|
|
1571
|
+
return { exitCode: 2 }
|
|
1572
|
+
}
|
|
1573
|
+
const sub = positionals(args)[0]
|
|
1574
|
+
try {
|
|
1575
|
+
if (sub === 'status') return await status(args)
|
|
1576
|
+
if (sub === 'check') return await check(args)
|
|
1577
|
+
if (sub === 'connect') return await connectNetwork(args)
|
|
1578
|
+
if (sub === 'post' || sub === 'campaign') return await writeDraft(args, sub)
|
|
1579
|
+
if (sub === 'show') return await show(args)
|
|
1580
|
+
if (sub === 'delete') return await deleteItem(args)
|
|
1581
|
+
if (sub === 'send') return await send(args)
|
|
1582
|
+
if (sub === 'unschedule') return await unschedule(args)
|
|
1583
|
+
if (sub === 'start' || sub === 'resume') return await spend(args, sub)
|
|
1584
|
+
if (sub === 'pause') return await pause(args)
|
|
1585
|
+
} catch (err) {
|
|
1586
|
+
say.err(err instanceof WorkspaceMismatchError ? err.message : err?.message || String(err))
|
|
1587
|
+
return { exitCode: 1 }
|
|
1588
|
+
}
|
|
1589
|
+
if (sub) {
|
|
1590
|
+
say.err(`Unknown command: uniweb promote ${sub}`)
|
|
1591
|
+
console.error(USAGE)
|
|
1592
|
+
return { exitCode: 2 }
|
|
1593
|
+
}
|
|
1594
|
+
console.log(USAGE)
|
|
1595
|
+
return { exitCode: 0 }
|
|
1596
|
+
}
|
|
1597
|
+
|
|
1598
|
+
export default promote
|