@aglyn/plugins-marketing 1.19.0 → 1.20.1

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.
@@ -19,9 +19,10 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
19
19
  import { ICON_VARIANT_CLOSE } from "@aglyn/shared-data-enums";
20
20
  import { Container, MdiIcon, SrOnly } from "@aglyn/shared-ui-jsx";
21
21
  import { NavigationDrawerComponent } from "@aglyn/shared-ui-jsx/components/navigation-drawer.component";
22
+ import { SiteSharingField } from "@aglyn/shared-ui-jsx/components/site-sharing-field.component";
22
23
  import { Alert, Button, Chip, FormControlLabel, IconButton, MenuItem, Stack, Switch, TextField, Typography } from "@mui/material";
23
- import { useEffect, useState } from "react";
24
- import { campaignListUnsubscribe, campaignSiteIds, campaignUtmLabels } from "../model/campaign-container.js";
24
+ import { useEffect, useMemo, useState } from "react";
25
+ import { campaignListUnsubscribe, campaignSharingChoice, campaignSharingKey, campaignSharingWrite, campaignUtmLabels } from "../model/campaign-container.js";
25
26
  /**
26
27
  * The `YYYY-MM-DD` a `date` input wants, from epoch ms.
27
28
  *
@@ -61,7 +62,7 @@ import { campaignListUnsubscribe, campaignSiteIds, campaignUtmLabels } from "../
61
62
  * changes the default for the next email written in it and nothing about the
62
63
  * ones already sent.
63
64
  */ export function CampaignEditDrawer(props) {
64
- const { open, onClose, campaign, lists, topics, sites, busy, error, onSubmit } = props;
65
+ const { open, onClose, campaign, lists, topics, sites, sitesReady = true, busy, error, onSubmit } = props;
65
66
  const [name, setName] = useState('');
66
67
  const [startAt, setStartAt] = useState('');
67
68
  const [endAt, setEndAt] = useState('');
@@ -69,19 +70,44 @@ import { campaignListUnsubscribe, campaignSiteIds, campaignUtmLabels } from "../
69
70
  const [topicId, setTopicId] = useState('');
70
71
  const [listUnsubscribe, setListUnsubscribe] = useState(true);
71
72
  /** The utm_campaign labels, as the field holds them: one per line or comma. */ const [utmLabels, setUtmLabels] = useState('');
72
- /** The chosen sites; empty is every site, as the create drawer reads it. */ const [siteIds, setSiteIds] = useState([]);
73
73
  /*
74
- * Whether the placement was CHANGED here. An untouched field submits
75
- * nothing, so saving a name cannot rewrite where a campaign is offered —
76
- * least of all turn a campaign placed on no site (an absent `visibleTo`,
77
- * which the field has no way to draw) into one on every site.
78
- */ const [sitesTouched, setSitesTouched] = useState(false);
74
+ * Who it is shared with, as edited here: null while it stores none (an
75
+ * absent `visibleTo`, which no reader matches), so no choice shows as picked
76
+ * until someone picks one. Only a CHANGED choice is submitted, so saving a
77
+ * name cannot rewrite where a campaign is offered.
78
+ */ const [sharing, setSharing] = useState(null);
79
+ const sharingSites = useMemo(()=>(sites != null ? sites : []).map((site)=>({
80
+ id: site.value,
81
+ name: site.label
82
+ })), [
83
+ sites
84
+ ]);
85
+ const sharingChanged = Boolean(sites) && sharing !== null && campaignSharingKey(sharing) !== campaignSharingKey(campaignSharingChoice(campaign));
86
+ /*
87
+ * Why the choice cannot be saved, the same answer the manage route gives
88
+ * from the sites it reads itself. The sites a choice leaves out stay known
89
+ * here even where this list cannot name them, so they aren't taken for sites
90
+ * that are gone. Nothing to say about leaving sites out until they are read.
91
+ */ const sharingProblem = useMemo(()=>{
92
+ if (!sharingChanged || !sharing) return null;
93
+ if (sharing.mode === 'allExcept' && !sitesReady) return null;
94
+ const leftOut = sharing.mode === 'allExcept' ? sharing.exceptHostIds : [];
95
+ return campaignSharingWrite(sharing, [
96
+ ...sharingSites.map((site)=>site.id),
97
+ ...leftOut
98
+ ]).problem;
99
+ }, [
100
+ sharing,
101
+ sharingChanged,
102
+ sharingSites,
103
+ sitesReady
104
+ ]);
79
105
  /*
80
106
  * Re-seeded whenever the drawer opens rather than held from the last time.
81
107
  * The campaign arrives asynchronously and can change under a closed drawer,
82
108
  * so seeding once at mount would open it on a stale name.
83
109
  */ useEffect(()=>{
84
- var _ref, _ref1, _ref2, _campaignSiteIds;
110
+ var _ref, _ref1, _ref2;
85
111
  if (!open) return;
86
112
  setName(String((_ref = campaign == null ? void 0 : campaign.name) != null ? _ref : ''));
87
113
  setStartAt(dayInputValue(campaign == null ? void 0 : campaign.startAtMs));
@@ -90,8 +116,7 @@ import { campaignListUnsubscribe, campaignSiteIds, campaignUtmLabels } from "../
90
116
  setTopicId(String((_ref2 = campaign == null ? void 0 : campaign.topicId) != null ? _ref2 : ''));
91
117
  setListUnsubscribe(campaignListUnsubscribe(campaign));
92
118
  setUtmLabels(campaignUtmLabels(campaign == null ? void 0 : campaign.utmCampaigns).join(', '));
93
- setSiteIds((_campaignSiteIds = campaignSiteIds(campaign)) != null ? _campaignSiteIds : []);
94
- setSitesTouched(false);
119
+ setSharing(campaignSharingChoice(campaign));
95
120
  }, [
96
121
  open,
97
122
  campaign
@@ -104,7 +129,7 @@ import { campaignListUnsubscribe, campaignSiteIds, campaignUtmLabels } from "../
104
129
  * window no state in `campaignWindowState` describes, so it would draw as
105
130
  * "Ended" from the day it was made.
106
131
  */ const backwards = startAtMs !== null && endAtMs !== null && endAtMs < startAtMs;
107
- const submittable = name.trim().length > 0 && !backwards && !busy;
132
+ const submittable = name.trim().length > 0 && !backwards && !busy && !sharingProblem && !(sharingChanged && (sharing == null ? void 0 : sharing.mode) === 'allExcept' && !sitesReady);
108
133
  return /*#__PURE__*/ _jsx(NavigationDrawerComponent, {
109
134
  open: open,
110
135
  anchor: "right",
@@ -266,45 +291,23 @@ import { campaignListUnsubscribe, campaignSiteIds, campaignUtmLabels } from "../
266
291
  severity: "warning",
267
292
  children: 'Without it, Gmail and Yahoo can reject or spam-folder these ' + 'emails once your organization sends in bulk, and more ' + 'people mark you as spam when their mail app offers no ' + 'unsubscribe button. It is turned back on automatically for ' + 'any email that would make your organization a bulk sender, ' + 'and the campaign page says so when it is.'
268
293
  }) : null,
269
- sites ? /*#__PURE__*/ _jsx(TextField, {
270
- select: true,
271
- label: "Sites",
272
- value: siteIds,
273
- onChange: (event)=>{
274
- setSitesTouched(true);
275
- setSiteIds(event.target.value.map(String));
276
- },
277
- helperText: "The sites this campaign is offered on. Leave empty for every site.",
278
- slotProps: {
279
- select: {
280
- multiple: true,
281
- displayEmpty: true,
282
- renderValue: (selected)=>selected.length ? /*#__PURE__*/ _jsx(Stack, {
283
- useFlexGap: true,
284
- direction: "row",
285
- spacing: 0.5,
286
- sx: {
287
- flexWrap: 'wrap'
288
- },
289
- children: selected.map((id)=>{
290
- var _ref;
291
- var _sites_find;
292
- return /*#__PURE__*/ _jsx(Chip, {
293
- size: "small",
294
- label: (_ref = (_sites_find = sites.find((site)=>site.value === id)) == null ? void 0 : _sites_find.label) != null ? _ref : id
295
- }, id);
296
- })
297
- }) : 'Every site'
298
- },
299
- inputLabel: {
300
- shrink: true
301
- }
302
- },
303
- fullWidth: true,
304
- children: sites.map((site)=>/*#__PURE__*/ _jsx(MenuItem, {
305
- value: site.value,
306
- children: site.label
307
- }, site.value))
294
+ sites ? /*#__PURE__*/ _jsxs(Stack, {
295
+ spacing: 0.5,
296
+ children: [
297
+ /*#__PURE__*/ _jsx(SiteSharingField, {
298
+ label: "Shared with",
299
+ value: sharing,
300
+ onChange: setSharing,
301
+ sites: sharingSites,
302
+ sitesReady: sitesReady,
303
+ problem: sharingProblem
304
+ }),
305
+ /*#__PURE__*/ _jsx(Typography, {
306
+ variant: "caption",
307
+ color: "text.secondary",
308
+ children: 'The sites this campaign is offered on.'
309
+ })
310
+ ]
308
311
  }) : null,
309
312
  backwards ? /*#__PURE__*/ _jsx(Alert, {
310
313
  severity: "warning",
@@ -325,8 +328,8 @@ import { campaignListUnsubscribe, campaignSiteIds, campaignUtmLabels } from "../
325
328
  topicId,
326
329
  listUnsubscribe,
327
330
  utmCampaigns: campaignUtmLabels(utmLabels)
328
- }, sites && sitesTouched ? {
329
- siteIds: siteIds.length ? siteIds : null
331
+ }, sharingChanged && sharing ? {
332
+ sharing
330
333
  } : {})),
331
334
  children: busy ? 'Saving…' : 'Save campaign'
332
335
  })
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/campaign-edit-drawer.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { ICON_VARIANT_CLOSE } from '@aglyn/shared-data-enums'\nimport { Container, MdiIcon, SrOnly } from '@aglyn/shared-ui-jsx'\nimport { NavigationDrawerComponent } from '@aglyn/shared-ui-jsx/components/navigation-drawer.component'\nimport {\n Alert,\n Button,\n Chip,\n FormControlLabel,\n IconButton,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport { useEffect, useState } from 'react'\nimport {\n campaignListUnsubscribe,\n campaignSiteIds,\n campaignUtmLabels,\n} from '../model/campaign-container'\n\n/** One option in the list or topic picker. */\nexport interface CampaignEditOption {\n value: string\n label: string\n}\n\n/** What the drawer collects — the container's whole editable surface. */\nexport interface CampaignEditValues {\n name: string\n startAtMs: number | null\n endAtMs: number | null\n listIds: string[]\n topicId: string\n /** Whether its emails carry the mail-client unsubscribe button (AGL-3307). */\n listUnsubscribe: boolean\n /**\n * The `utm_campaign` labels that mean this campaign (AGL-3461), as typed —\n * the save normalizes them with `campaignUtmLabels`.\n */\n utmCampaigns: string[]\n /**\n * The sites it is placed on — `null` for every site. Present only when the\n * drawer was handed `sites`, which only the org hub does (a site hub never\n * moves a campaign's placement), and only when the field was changed.\n */\n siteIds?: string[] | null\n}\n\nexport interface CampaignEditDrawerProps {\n open: boolean\n onClose: () => void\n /** The campaign as stored, for the fields to open on. */\n campaign: {\n name?: string\n startAtMs?: number | null\n endAtMs?: number | null\n listIds?: string[]\n topicId?: string\n visibleTo?: string[]\n listUnsubscribe?: boolean\n utmCampaigns?: string[]\n } | null\n /** The org's email lists, which this campaign may be aimed at. */\n lists: CampaignEditOption[]\n /** The org's active topics — the stream its emails open on. */\n topics: CampaignEditOption[]\n /**\n * The org's sites, which turns on the placement field. Passed by the org\n * hub alone: moving a campaign between sites is an org-wide decision, and\n * the rules refuse it from anyone narrower.\n */\n sites?: CampaignEditOption[]\n busy?: boolean\n /** A refusal from the write, shown where the form still is. */\n error?: string | null\n onSubmit: (values: CampaignEditValues) => void\n}\n\n/**\n * The `YYYY-MM-DD` a `date` input wants, from epoch ms.\n *\n * UTC, matching the writer: the create drawer stores `Date.parse('2026-03-01')`,\n * which is UTC midnight, so reading it back in local time shows the previous\n * day to everyone west of Greenwich — a campaign that changed its own start\n * date by being opened.\n */\nfunction dayInputValue(ms: number | null | undefined): string {\n if (typeof ms !== 'number' || !Number.isFinite(ms)) return ''\n const at = new Date(ms)\n return Number.isNaN(at.getTime()) ? '' : at.toISOString().slice(0, 10)\n}\n\n/** Epoch ms for a `YYYY-MM-DD` a `date` input produced, or null for empty. */\nfunction dayInputMs(value: string): number | null {\n if (!value) return null\n const parsed = Date.parse(value)\n return Number.isFinite(parsed) ? parsed : null\n}\n\n/**\n * EDITING ONE CAMPAIGN, IN A DRAWER ON THE CAMPAIGN'S OWN PAGE.\n *\n * A drawer and not a form above the campaigns table: a record is edited on\n * its own surface in this console, and a list with a form on top of it is\n * the shape the whole surface was routed to stop.\n *\n * ## Everything a container holds is editable, and that is the whole point\n *\n * A campaign is a name, a window, the lists it is aimed at and the stream its\n * emails open on. None of it describes mail that has already been delivered —\n * that lives on the SENDS, which record their own subject, audience and topic\n * at send time and are never rewritten. So unlike an email, where only the\n * console-only display name stays editable after it goes out, a campaign has\n * no field that could come to disagree with somebody's inbox.\n *\n * Changing the topic is the one that reads as though it might. It does not:\n * the topic here is what the composer's picker OPENS ON, and each send\n * records the topic it actually went out under. Re-pointing a campaign\n * changes the default for the next email written in it and nothing about the\n * ones already sent.\n */\nexport function CampaignEditDrawer(props: CampaignEditDrawerProps) {\n const { open, onClose, campaign, lists, topics, sites, busy, error, onSubmit } =\n props\n\n const [name, setName] = useState('')\n const [startAt, setStartAt] = useState('')\n const [endAt, setEndAt] = useState('')\n const [listIds, setListIds] = useState<string[]>([])\n const [topicId, setTopicId] = useState('')\n const [listUnsubscribe, setListUnsubscribe] = useState(true)\n /** The utm_campaign labels, as the field holds them: one per line or comma. */\n const [utmLabels, setUtmLabels] = useState('')\n /** The chosen sites; empty is every site, as the create drawer reads it. */\n const [siteIds, setSiteIds] = useState<string[]>([])\n /*\n * Whether the placement was CHANGED here. An untouched field submits\n * nothing, so saving a name cannot rewrite where a campaign is offered —\n * least of all turn a campaign placed on no site (an absent `visibleTo`,\n * which the field has no way to draw) into one on every site.\n */\n const [sitesTouched, setSitesTouched] = useState(false)\n\n /*\n * Re-seeded whenever the drawer opens rather than held from the last time.\n * The campaign arrives asynchronously and can change under a closed drawer,\n * so seeding once at mount would open it on a stale name.\n */\n useEffect(() => {\n if (!open) return\n setName(String(campaign?.name ?? ''))\n setStartAt(dayInputValue(campaign?.startAtMs))\n setEndAt(dayInputValue(campaign?.endAtMs))\n setListIds((campaign?.listIds ?? []).map(String))\n setTopicId(String(campaign?.topicId ?? ''))\n setListUnsubscribe(campaignListUnsubscribe(campaign))\n setUtmLabels(campaignUtmLabels(campaign?.utmCampaigns).join(', '))\n setSiteIds(campaignSiteIds(campaign) ?? [])\n setSitesTouched(false)\n }, [open, campaign])\n\n const startAtMs = dayInputMs(startAt)\n const endAtMs = dayInputMs(endAt)\n /*\n * Refused in the form rather than stored and rendered, exactly as the\n * create drawer refuses it: a campaign that ends before it starts is a\n * window no state in `campaignWindowState` describes, so it would draw as\n * \"Ended\" from the day it was made.\n */\n const backwards = startAtMs !== null && endAtMs !== null && endAtMs < startAtMs\n const submittable = name.trim().length > 0 && !backwards && !busy\n\n return (\n <NavigationDrawerComponent\n open={open}\n anchor=\"right\"\n variant=\"temporary\"\n onClose={onClose}\n AppBarProps={{ color: 'surface' }}\n appBarLeft={\n <>\n <IconButton\n color=\"inherit\"\n edge=\"start\"\n onClick={onClose}\n sx={{ mr: 2 }}\n >\n <MdiIcon path={ICON_VARIANT_CLOSE.path} />\n <SrOnly>close drawer</SrOnly>\n </IconButton>\n <Typography variant=\"h6\" component=\"div\">\n {'Edit campaign'}\n </Typography>\n </>\n }\n appBarRight={\n <Button variant=\"outlined\" color=\"inherit\" onClick={onClose}>\n {'Cancel'}\n </Button>\n }\n >\n <Container gutterY>\n <Stack spacing={2}>\n <TextField\n label=\"Name\"\n value={name}\n onChange={(event) => setName(event.target.value)}\n helperText=\"What you call this campaign in the console\"\n fullWidth\n />\n <TextField\n type=\"date\"\n label=\"Starts\"\n value={startAt}\n onChange={(event) => setStartAt(event.target.value)}\n helperText=\"When the campaign window opens\"\n slotProps={{ inputLabel: { shrink: true } }}\n fullWidth\n />\n <TextField\n type=\"date\"\n label=\"Ends\"\n value={endAt}\n onChange={(event) => setEndAt(event.target.value)}\n helperText=\"Leave empty for an open-ended campaign\"\n slotProps={{ inputLabel: { shrink: true } }}\n fullWidth\n />\n <TextField\n select\n label=\"Lists\"\n value={listIds}\n onChange={(event) =>\n setListIds(\n // A multiple select hands back an array; the typing on the\n // change event does not know that.\n (event.target.value as unknown as string[]).map(String),\n )\n }\n // A campaign with no list is legitimate: its emails can go to\n // leads, to site members, or to a segment.\n helperText=\"The lists this campaign is aimed at\"\n slotProps={{\n select: {\n multiple: true,\n renderValue: (selected: unknown) => (\n <Stack useFlexGap direction=\"row\" spacing={0.5} sx={{ flexWrap: 'wrap' }}>\n {(selected as string[]).map((id) => (\n <Chip\n key={id}\n size=\"small\"\n label={\n lists.find((list) => list.value === id)?.label ?? id\n }\n />\n ))}\n </Stack>\n ),\n },\n }}\n fullWidth\n >\n {lists.map((list) => (\n <MenuItem key={list.value} value={list.value}>\n {list.label}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n select\n label=\"Topic\"\n value={topicId}\n onChange={(event) => setTopicId(event.target.value)}\n helperText=\"The stream its emails open on — each one can change it\"\n fullWidth\n >\n {/*\n An explicit \"no default\" option rather than only the topics.\n A campaign is allowed to carry none — the send resolves the\n org's default when the composer names nothing — and a select\n with no way back to empty makes the first choice permanent.\n */}\n <MenuItem value=\"\">{'No default — each email chooses'}</MenuItem>\n {topics.map((topic) => (\n <MenuItem key={topic.value} value={topic.value}>\n {topic.label}\n </MenuItem>\n ))}\n </TextField>\n {/*\n THE LABELS THAT MEAN THIS CAMPAIGN (AGL-3461). An ad or a social\n post carries `utm_campaign=…`; a label named here credits this\n campaign the way a page filed under it does. Lowercased and\n deduped on save, which is how the lookup matches them.\n */}\n <TextField\n label=\"utm_campaign labels\"\n value={utmLabels}\n onChange={(event) => setUtmLabels(event.target.value)}\n helperText={\n 'Links carrying one of these utm_campaign values credit this ' +\n 'campaign. Separate them with commas. A label two campaigns ' +\n 'both list credits neither.'\n }\n placeholder=\"spring-launch, spring-retargeting\"\n fullWidth\n />\n {/*\n The mail-client unsubscribe button (AGL-3307), the setting a\n sequence carries too with the same label. ON for a campaign,\n because campaigns are bulk mail. Off warns, and the send path\n turns it back on for any email that would make the organization\n a bulk sender — the page says so when it does.\n */}\n <Stack spacing={0}>\n <FormControlLabel\n control={\n <Switch\n checked={listUnsubscribe}\n onChange={(event) => setListUnsubscribe(event.target.checked)}\n />\n }\n label=\"Add a mail-client unsubscribe button\"\n />\n <Typography variant=\"caption\" color=\"text.secondary\">\n Adds the List-Unsubscribe header, so the recipient’s mail app\n shows its own Unsubscribe button. It’s the easiest way out for\n them, and Gmail and Yahoo require it from bulk senders. The\n unsubscribe link in the footer is always there, either way.\n </Typography>\n </Stack>\n {!listUnsubscribe ? (\n <Alert severity=\"warning\">\n {'Without it, Gmail and Yahoo can reject or spam-folder these ' +\n 'emails once your organization sends in bulk, and more ' +\n 'people mark you as spam when their mail app offers no ' +\n 'unsubscribe button. It is turned back on automatically for ' +\n 'any email that would make your organization a bulk sender, ' +\n 'and the campaign page says so when it is.'}\n </Alert>\n ) : null}\n {sites ? (\n <TextField\n select\n label=\"Sites\"\n value={siteIds}\n onChange={(event) => {\n setSitesTouched(true)\n setSiteIds(\n (event.target.value as unknown as string[]).map(String),\n )\n }}\n helperText=\"The sites this campaign is offered on. Leave empty for every site.\"\n slotProps={{\n select: {\n multiple: true,\n displayEmpty: true,\n renderValue: (selected: unknown) =>\n (selected as string[]).length ? (\n <Stack\n useFlexGap\n direction=\"row\"\n spacing={0.5}\n sx={{ flexWrap: 'wrap' }}\n >\n {(selected as string[]).map((id) => (\n <Chip\n key={id}\n size=\"small\"\n label={\n sites.find((site) => site.value === id)?.label ??\n id\n }\n />\n ))}\n </Stack>\n ) : (\n 'Every site'\n ),\n },\n inputLabel: { shrink: true },\n }}\n fullWidth\n >\n {sites.map((site) => (\n <MenuItem key={site.value} value={site.value}>\n {site.label}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n {backwards ? (\n <Alert severity=\"warning\">\n {'The end date is before the start date.'}\n </Alert>\n ) : null}\n {error ? <Alert severity=\"error\">{error}</Alert> : null}\n <Button\n variant=\"contained\"\n disabled={!submittable}\n onClick={() =>\n onSubmit({\n name: name.trim(),\n startAtMs,\n endAtMs,\n listIds,\n topicId,\n listUnsubscribe,\n utmCampaigns: campaignUtmLabels(utmLabels),\n ...(sites && sitesTouched\n ? { siteIds: siteIds.length ? siteIds : null }\n : {}),\n })\n }\n >\n {busy ? 'Saving…' : 'Save campaign'}\n </Button>\n </Stack>\n </Container>\n </NavigationDrawerComponent>\n )\n}\nCampaignEditDrawer.displayName = 'CampaignEditDrawer'\n\nexport default CampaignEditDrawer\n"],"names":["ICON_VARIANT_CLOSE","Container","MdiIcon","SrOnly","NavigationDrawerComponent","Alert","Button","Chip","FormControlLabel","IconButton","MenuItem","Stack","Switch","TextField","Typography","useEffect","useState","campaignListUnsubscribe","campaignSiteIds","campaignUtmLabels","dayInputValue","ms","Number","isFinite","at","Date","isNaN","getTime","toISOString","slice","dayInputMs","value","parsed","parse","CampaignEditDrawer","props","open","onClose","campaign","lists","topics","sites","busy","error","onSubmit","name","setName","startAt","setStartAt","endAt","setEndAt","listIds","setListIds","topicId","setTopicId","listUnsubscribe","setListUnsubscribe","utmLabels","setUtmLabels","siteIds","setSiteIds","sitesTouched","setSitesTouched","String","startAtMs","endAtMs","map","utmCampaigns","join","backwards","submittable","trim","length","anchor","variant","AppBarProps","color","appBarLeft","edge","onClick","sx","mr","path","component","appBarRight","gutterY","spacing","label","onChange","event","target","helperText","fullWidth","type","slotProps","inputLabel","shrink","select","multiple","renderValue","selected","useFlexGap","direction","flexWrap","id","size","find","list","topic","placeholder","control","checked","severity","displayEmpty","site","disabled","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,kBAAkB,QAAQ,2BAA0B;AAC7D,SAASC,SAAS,EAAEC,OAAO,EAAEC,MAAM,QAAQ,uBAAsB;AACjE,SAASC,yBAAyB,QAAQ,8DAA6D;AACvG,SACEC,KAAK,EACLC,MAAM,EACNC,IAAI,EACJC,gBAAgB,EAChBC,UAAU,EACVC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AAC3C,SACEC,uBAAuB,EACvBC,eAAe,EACfC,iBAAiB,QACZ,iCAA6B;AA4DpC;;;;;;;CAOC,GACD,SAASC,cAAcC,EAA6B;IAClD,IAAI,OAAOA,OAAO,YAAY,CAACC,OAAOC,QAAQ,CAACF,KAAK,OAAO;IAC3D,MAAMG,KAAK,IAAIC,KAAKJ;IACpB,OAAOC,OAAOI,KAAK,CAACF,GAAGG,OAAO,MAAM,KAAKH,GAAGI,WAAW,GAAGC,KAAK,CAAC,GAAG;AACrE;AAEA,4EAA4E,GAC5E,SAASC,WAAWC,KAAa;IAC/B,IAAI,CAACA,O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AAC,CAACgD,qBACV,KAACxG;gCAA0BqB,OAAOmF,KAAKnF,KAAK;0CACzCmF,KAAK3B,KAAK;+BADE2B,KAAKnF,KAAK;yBAK3B;oBACHsC,0BACC,KAAChE;wBAAM2G,UAAS;kCACb;yBAED;oBACHrE,sBAAQ,KAACtC;wBAAM2G,UAAS;kCAASrE;yBAAiB;kCACnD,KAACrC;wBACCoE,SAAQ;wBACRyC,UAAU,CAAC7C;wBACXS,SAAS,IACPnC,SAAS;gCACPC,MAAMA,KAAK0B,IAAI;gCACfP;gCACAC;gCACAd;gCACAE;gCACAE;gCACAY,cAAchD,kBAAkBsC;+BAC5BhB,SAASoB,eACT;gCAAEF,SAASA,QAAQa,MAAM,GAAGb,UAAU;4BAAK,IAC3C,CAAC;kCAIRjB,OAAO,YAAY;;;;;;AAMhC;AACAR,mBAAmBkF,WAAW,GAAG;AAEjC,eAAelF,mBAAkB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/campaign-edit-drawer.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { ICON_VARIANT_CLOSE } from '@aglyn/shared-data-enums'\nimport { Container, MdiIcon, SrOnly } from '@aglyn/shared-ui-jsx'\nimport { NavigationDrawerComponent } from '@aglyn/shared-ui-jsx/components/navigation-drawer.component'\nimport { SiteSharingField } from '@aglyn/shared-ui-jsx/components/site-sharing-field.component'\nimport type { ScopeSharingChoice } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport {\n Alert,\n Button,\n Chip,\n FormControlLabel,\n IconButton,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport { useEffect, useMemo, useState } from 'react'\nimport {\n campaignListUnsubscribe,\n campaignSharingChoice,\n campaignSharingKey,\n campaignSharingWrite,\n campaignUtmLabels,\n} from '../model/campaign-container'\n\n/** One option in the list or topic picker. */\nexport interface CampaignEditOption {\n value: string\n label: string\n}\n\n/** What the drawer collects — the container's whole editable surface. */\nexport interface CampaignEditValues {\n name: string\n startAtMs: number | null\n endAtMs: number | null\n listIds: string[]\n topicId: string\n /** Whether its emails carry the mail-client unsubscribe button (AGL-3307). */\n listUnsubscribe: boolean\n /**\n * The `utm_campaign` labels that mean this campaign (AGL-3461), as typed —\n * the save normalizes them with `campaignUtmLabels`.\n */\n utmCampaigns: string[]\n /**\n * Who it is shared with: all sites, the sites chosen, or all sites except\n * some (AGL-4047). Present only when the drawer was handed `sites`, which\n * only the org hub does (a site hub never moves a campaign's placement), and\n * only when the choice was changed. The manage route writes it, never the\n * client: a marker is the server's alone.\n */\n sharing?: ScopeSharingChoice\n}\n\nexport interface CampaignEditDrawerProps {\n open: boolean\n onClose: () => void\n /** The campaign as stored, for the fields to open on. */\n campaign: {\n name?: string\n startAtMs?: number | null\n endAtMs?: number | null\n listIds?: string[]\n topicId?: string\n visibleTo?: string[]\n scopeMode?: string | null\n scopeExcept?: string[] | null\n listUnsubscribe?: boolean\n utmCampaigns?: string[]\n } | null\n /** The org's email lists, which this campaign may be aimed at. */\n lists: CampaignEditOption[]\n /** The org's active topics — the stream its emails open on. */\n topics: CampaignEditOption[]\n /**\n * The org's sites, which turns on the placement field. Passed by the org\n * hub alone: moving a campaign between sites is an org-wide decision, and\n * the rules refuse it from anyone narrower.\n */\n sites?: CampaignEditOption[]\n /** False while `sites` is still being read. */\n sitesReady?: boolean\n busy?: boolean\n /** A refusal from the write, shown where the form still is. */\n error?: string | null\n onSubmit: (values: CampaignEditValues) => void\n}\n\n/**\n * The `YYYY-MM-DD` a `date` input wants, from epoch ms.\n *\n * UTC, matching the writer: the create drawer stores `Date.parse('2026-03-01')`,\n * which is UTC midnight, so reading it back in local time shows the previous\n * day to everyone west of Greenwich — a campaign that changed its own start\n * date by being opened.\n */\nfunction dayInputValue(ms: number | null | undefined): string {\n if (typeof ms !== 'number' || !Number.isFinite(ms)) return ''\n const at = new Date(ms)\n return Number.isNaN(at.getTime()) ? '' : at.toISOString().slice(0, 10)\n}\n\n/** Epoch ms for a `YYYY-MM-DD` a `date` input produced, or null for empty. */\nfunction dayInputMs(value: string): number | null {\n if (!value) return null\n const parsed = Date.parse(value)\n return Number.isFinite(parsed) ? parsed : null\n}\n\n/**\n * EDITING ONE CAMPAIGN, IN A DRAWER ON THE CAMPAIGN'S OWN PAGE.\n *\n * A drawer and not a form above the campaigns table: a record is edited on\n * its own surface in this console, and a list with a form on top of it is\n * the shape the whole surface was routed to stop.\n *\n * ## Everything a container holds is editable, and that is the whole point\n *\n * A campaign is a name, a window, the lists it is aimed at and the stream its\n * emails open on. None of it describes mail that has already been delivered —\n * that lives on the SENDS, which record their own subject, audience and topic\n * at send time and are never rewritten. So unlike an email, where only the\n * console-only display name stays editable after it goes out, a campaign has\n * no field that could come to disagree with somebody's inbox.\n *\n * Changing the topic is the one that reads as though it might. It does not:\n * the topic here is what the composer's picker OPENS ON, and each send\n * records the topic it actually went out under. Re-pointing a campaign\n * changes the default for the next email written in it and nothing about the\n * ones already sent.\n */\nexport function CampaignEditDrawer(props: CampaignEditDrawerProps) {\n const {\n open,\n onClose,\n campaign,\n lists,\n topics,\n sites,\n sitesReady = true,\n busy,\n error,\n onSubmit,\n } = props\n\n const [name, setName] = useState('')\n const [startAt, setStartAt] = useState('')\n const [endAt, setEndAt] = useState('')\n const [listIds, setListIds] = useState<string[]>([])\n const [topicId, setTopicId] = useState('')\n const [listUnsubscribe, setListUnsubscribe] = useState(true)\n /** The utm_campaign labels, as the field holds them: one per line or comma. */\n const [utmLabels, setUtmLabels] = useState('')\n /*\n * Who it is shared with, as edited here: null while it stores none (an\n * absent `visibleTo`, which no reader matches), so no choice shows as picked\n * until someone picks one. Only a CHANGED choice is submitted, so saving a\n * name cannot rewrite where a campaign is offered.\n */\n const [sharing, setSharing] = useState<ScopeSharingChoice | null>(null)\n const sharingSites = useMemo(\n () => (sites ?? []).map((site) => ({ id: site.value, name: site.label })),\n [sites],\n )\n const sharingChanged =\n Boolean(sites) &&\n sharing !== null &&\n campaignSharingKey(sharing) !== campaignSharingKey(campaignSharingChoice(campaign))\n /*\n * Why the choice cannot be saved, the same answer the manage route gives\n * from the sites it reads itself. The sites a choice leaves out stay known\n * here even where this list cannot name them, so they aren't taken for sites\n * that are gone. Nothing to say about leaving sites out until they are read.\n */\n const sharingProblem = useMemo(() => {\n if (!sharingChanged || !sharing) return null\n if (sharing.mode === 'allExcept' && !sitesReady) return null\n const leftOut = sharing.mode === 'allExcept' ? sharing.exceptHostIds : []\n return campaignSharingWrite(sharing, [\n ...sharingSites.map((site) => site.id),\n ...leftOut,\n ]).problem\n }, [sharing, sharingChanged, sharingSites, sitesReady])\n\n /*\n * Re-seeded whenever the drawer opens rather than held from the last time.\n * The campaign arrives asynchronously and can change under a closed drawer,\n * so seeding once at mount would open it on a stale name.\n */\n useEffect(() => {\n if (!open) return\n setName(String(campaign?.name ?? ''))\n setStartAt(dayInputValue(campaign?.startAtMs))\n setEndAt(dayInputValue(campaign?.endAtMs))\n setListIds((campaign?.listIds ?? []).map(String))\n setTopicId(String(campaign?.topicId ?? ''))\n setListUnsubscribe(campaignListUnsubscribe(campaign))\n setUtmLabels(campaignUtmLabels(campaign?.utmCampaigns).join(', '))\n setSharing(campaignSharingChoice(campaign))\n }, [open, campaign])\n\n const startAtMs = dayInputMs(startAt)\n const endAtMs = dayInputMs(endAt)\n /*\n * Refused in the form rather than stored and rendered, exactly as the\n * create drawer refuses it: a campaign that ends before it starts is a\n * window no state in `campaignWindowState` describes, so it would draw as\n * \"Ended\" from the day it was made.\n */\n const backwards = startAtMs !== null && endAtMs !== null && endAtMs < startAtMs\n const submittable =\n name.trim().length > 0 &&\n !backwards &&\n !busy &&\n !sharingProblem &&\n !(sharingChanged && sharing?.mode === 'allExcept' && !sitesReady)\n\n return (\n <NavigationDrawerComponent\n open={open}\n anchor=\"right\"\n variant=\"temporary\"\n onClose={onClose}\n AppBarProps={{ color: 'surface' }}\n appBarLeft={\n <>\n <IconButton\n color=\"inherit\"\n edge=\"start\"\n onClick={onClose}\n sx={{ mr: 2 }}\n >\n <MdiIcon path={ICON_VARIANT_CLOSE.path} />\n <SrOnly>close drawer</SrOnly>\n </IconButton>\n <Typography variant=\"h6\" component=\"div\">\n {'Edit campaign'}\n </Typography>\n </>\n }\n appBarRight={\n <Button variant=\"outlined\" color=\"inherit\" onClick={onClose}>\n {'Cancel'}\n </Button>\n }\n >\n <Container gutterY>\n <Stack spacing={2}>\n <TextField\n label=\"Name\"\n value={name}\n onChange={(event) => setName(event.target.value)}\n helperText=\"What you call this campaign in the console\"\n fullWidth\n />\n <TextField\n type=\"date\"\n label=\"Starts\"\n value={startAt}\n onChange={(event) => setStartAt(event.target.value)}\n helperText=\"When the campaign window opens\"\n slotProps={{ inputLabel: { shrink: true } }}\n fullWidth\n />\n <TextField\n type=\"date\"\n label=\"Ends\"\n value={endAt}\n onChange={(event) => setEndAt(event.target.value)}\n helperText=\"Leave empty for an open-ended campaign\"\n slotProps={{ inputLabel: { shrink: true } }}\n fullWidth\n />\n <TextField\n select\n label=\"Lists\"\n value={listIds}\n onChange={(event) =>\n setListIds(\n // A multiple select hands back an array; the typing on the\n // change event does not know that.\n (event.target.value as unknown as string[]).map(String),\n )\n }\n // A campaign with no list is legitimate: its emails can go to\n // leads, to site members, or to a segment.\n helperText=\"The lists this campaign is aimed at\"\n slotProps={{\n select: {\n multiple: true,\n renderValue: (selected: unknown) => (\n <Stack useFlexGap direction=\"row\" spacing={0.5} sx={{ flexWrap: 'wrap' }}>\n {(selected as string[]).map((id) => (\n <Chip\n key={id}\n size=\"small\"\n label={\n lists.find((list) => list.value === id)?.label ?? id\n }\n />\n ))}\n </Stack>\n ),\n },\n }}\n fullWidth\n >\n {lists.map((list) => (\n <MenuItem key={list.value} value={list.value}>\n {list.label}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n select\n label=\"Topic\"\n value={topicId}\n onChange={(event) => setTopicId(event.target.value)}\n helperText=\"The stream its emails open on — each one can change it\"\n fullWidth\n >\n {/*\n An explicit \"no default\" option rather than only the topics.\n A campaign is allowed to carry none — the send resolves the\n org's default when the composer names nothing — and a select\n with no way back to empty makes the first choice permanent.\n */}\n <MenuItem value=\"\">{'No default — each email chooses'}</MenuItem>\n {topics.map((topic) => (\n <MenuItem key={topic.value} value={topic.value}>\n {topic.label}\n </MenuItem>\n ))}\n </TextField>\n {/*\n THE LABELS THAT MEAN THIS CAMPAIGN (AGL-3461). An ad or a social\n post carries `utm_campaign=…`; a label named here credits this\n campaign the way a page filed under it does. Lowercased and\n deduped on save, which is how the lookup matches them.\n */}\n <TextField\n label=\"utm_campaign labels\"\n value={utmLabels}\n onChange={(event) => setUtmLabels(event.target.value)}\n helperText={\n 'Links carrying one of these utm_campaign values credit this ' +\n 'campaign. Separate them with commas. A label two campaigns ' +\n 'both list credits neither.'\n }\n placeholder=\"spring-launch, spring-retargeting\"\n fullWidth\n />\n {/*\n The mail-client unsubscribe button (AGL-3307), the setting a\n sequence carries too with the same label. ON for a campaign,\n because campaigns are bulk mail. Off warns, and the send path\n turns it back on for any email that would make the organization\n a bulk sender — the page says so when it does.\n */}\n <Stack spacing={0}>\n <FormControlLabel\n control={\n <Switch\n checked={listUnsubscribe}\n onChange={(event) => setListUnsubscribe(event.target.checked)}\n />\n }\n label=\"Add a mail-client unsubscribe button\"\n />\n <Typography variant=\"caption\" color=\"text.secondary\">\n Adds the List-Unsubscribe header, so the recipient’s mail app\n shows its own Unsubscribe button. It’s the easiest way out for\n them, and Gmail and Yahoo require it from bulk senders. The\n unsubscribe link in the footer is always there, either way.\n </Typography>\n </Stack>\n {!listUnsubscribe ? (\n <Alert severity=\"warning\">\n {'Without it, Gmail and Yahoo can reject or spam-folder these ' +\n 'emails once your organization sends in bulk, and more ' +\n 'people mark you as spam when their mail app offers no ' +\n 'unsubscribe button. It is turned back on automatically for ' +\n 'any email that would make your organization a bulk sender, ' +\n 'and the campaign page says so when it is.'}\n </Alert>\n ) : null}\n {sites ? (\n <Stack spacing={0.5}>\n <SiteSharingField\n label=\"Shared with\"\n value={sharing}\n onChange={setSharing}\n sites={sharingSites}\n sitesReady={sitesReady}\n problem={sharingProblem}\n />\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'The sites this campaign is offered on.'}\n </Typography>\n </Stack>\n ) : null}\n {backwards ? (\n <Alert severity=\"warning\">\n {'The end date is before the start date.'}\n </Alert>\n ) : null}\n {error ? <Alert severity=\"error\">{error}</Alert> : null}\n <Button\n variant=\"contained\"\n disabled={!submittable}\n onClick={() =>\n onSubmit({\n name: name.trim(),\n startAtMs,\n endAtMs,\n listIds,\n topicId,\n listUnsubscribe,\n utmCampaigns: campaignUtmLabels(utmLabels),\n ...(sharingChanged && sharing ? { sharing } : {}),\n })\n }\n >\n {busy ? 'Saving…' : 'Save campaign'}\n </Button>\n </Stack>\n </Container>\n </NavigationDrawerComponent>\n )\n}\nCampaignEditDrawer.displayName = 'CampaignEditDrawer'\n\nexport default CampaignEditDrawer\n"],"names":["ICON_VARIANT_CLOSE","Container","MdiIcon","SrOnly","NavigationDrawerComponent","SiteSharingField","Alert","Button","Chip","FormControlLabel","IconButton","MenuItem","Stack","Switch","TextField","Typography","useEffect","useMemo","useState","campaignListUnsubscribe","campaignSharingChoice","campaignSharingKey","campaignSharingWrite","campaignUtmLabels","dayInputValue","ms","Number","isFinite","at","Date","isNaN","getTime","toISOString","slice","dayInputMs","value","parsed","parse","CampaignEditDrawer","props","open","onClose","campaign","lists","topics","sites","sitesReady","busy","error","onSubmit","name","setName","startAt","setStartAt","endAt","setEndAt","listIds","setListIds","topicId","setTopicId","listUnsubscribe","setListUnsubscribe","utmLabels","setUtmLabels","sharing","setSharing","sharingSites","map","site","id","label","sharingChanged","Boolean","sharingProblem","mode","leftOut","exceptHostIds","problem","String","startAtMs","endAtMs","utmCampaigns","join","backwards","submittable","trim","length","anchor","variant","AppBarProps","color","appBarLeft","edge","onClick","sx","mr","path","component","appBarRight","gutterY","spacing","onChange","event","target","helperText","fullWidth","type","slotProps","inputLabel","shrink","select","multiple","renderValue","selected","useFlexGap","direction","flexWrap","size","find","list","topic","placeholder","control","checked","severity","disabled","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,kBAAkB,QAAQ,2BAA0B;AAC7D,SAASC,SAAS,EAAEC,OAAO,EAAEC,MAAM,QAAQ,uBAAsB;AACjE,SAASC,yBAAyB,QAAQ,8DAA6D;AACvG,SAASC,gBAAgB,QAAQ,+DAA8D;AAE/F,SACEC,KAAK,EACLC,MAAM,EACNC,IAAI,EACJC,gBAAgB,EAChBC,UAAU,EACVC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACpD,SACEC,uBAAuB,EACvBC,qBAAqB,EACrBC,kBAAkB,EAClBC,oBAAoB,EACpBC,iBAAiB,QACZ,iCAA6B;AAkEpC;;;;;;;CAOC,GACD,SAASC,cAAcC,EAA6B;IAClD,IAAI,OAAOA,OAAO,YAAY,CAACC,OAAOC,QAAQ,CAACF,KAAK,OAAO;IAC3D,MAAMG,KAAK,IAAIC,KAAKJ;IACpB,OAAOC,OAAOI,KAAK,CAACF,GAAGG,OAAO,MAAM,KAAKH,GAAGI,WAAW,GAAGC,KAAK,CAAC,GAAG;AACrE;AAEA,4EAA4E,GAC5E,SAASC,WAAWC,KAAa;IAC/B,IAAI,CAACA,OAAO,OAAO;IACnB,MAAMC,SAASP,KAAKQ,KAAK,CAACF;IAC1B,OAAOT,OAAOC,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;gCACZ+B,SAASJ;;0CAEX,KAAC1D;gCAAWyE,SAAQ;gCAAUE,OAAM;0CACjC;;;yBAGH;oBACHP,0BACC,KAAC7E;wBAAMsH,UAAS;kCACb;yBAED;oBACH5E,sBAAQ,KAAC1C;wBAAMsH,UAAS;kCAAS5E;yBAAiB;kCACnD,KAACzC;wBACCiF,SAAQ;wBACRqC,UAAU,CAACzC;wBACXS,SAAS,IACP5C,SAAS;gCACPC,MAAMA,KAAKmC,IAAI;gCACfN;gCACAC;gCACAxB;gCACAE;gCACAE;gCACAqB,cAAc1D,kBAAkBuC;+BAC5BS,kBAAkBP,UAAU;gCAAEA;4BAAQ,IAAI,CAAC;kCAIlDjB,OAAO,YAAY;;;;;;AAMhC;AACAT,mBAAmBwF,WAAW,GAAG;AAEjC,eAAexF,mBAAkB"}
@@ -0,0 +1,14 @@
1
+ /** The `component` name the create drawer's sharing field asks for. */
2
+ export declare const CAMPAIGN_SHARING_FIELD = "campaign-site-sharing";
3
+ /**
4
+ * Who a new campaign is shared with, in the console's create drawer
5
+ * (AGL-4047): the shared `SiteSharingField`, radios and a visible list of
6
+ * sites, never a dropdown. It holds the choice; what the choice writes, and
7
+ * whether it can be, is `campaignSharingWrite`, asked here to say why before
8
+ * the create, and again by the create itself and by the manage route.
9
+ */
10
+ export declare function CampaignSharingFormField(props: Record<string, unknown>): import("react").JSX.Element;
11
+ export declare namespace CampaignSharingFormField {
12
+ var displayName: string;
13
+ }
14
+ export default CampaignSharingFormField;
@@ -0,0 +1,69 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ 'use client';
17
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
18
+ import { SiteSharingField } from "@aglyn/shared-ui-jsx/components/site-sharing-field.component";
19
+ import { FormFieldGrid } from "@aglyn/shared-ui-jsx-forms/mapper/form-field-grid";
20
+ import { useFieldApi } from "@aglyn/shared-ui-jsx-forms/vendor/data-driven-forms";
21
+ import { Typography } from "@mui/material";
22
+ import { useMemo } from "react";
23
+ import { campaignSharingWrite } from "../model/campaign-container.js";
24
+ /** The `component` name the create drawer's sharing field asks for. */ export const CAMPAIGN_SHARING_FIELD = 'campaign-site-sharing';
25
+ /**
26
+ * Who a new campaign is shared with, in the console's create drawer
27
+ * (AGL-4047): the shared `SiteSharingField`, radios and a visible list of
28
+ * sites, never a dropdown. It holds the choice; what the choice writes, and
29
+ * whether it can be, is `campaignSharingWrite`, asked here to say why before
30
+ * the create, and again by the create itself and by the manage route.
31
+ */ export function CampaignSharingFormField(props) {
32
+ const { input, sites, sitesReady, label, helperText } = useFieldApi(props);
33
+ const value = input.value ? input.value : null;
34
+ const named = useMemo(()=>sites != null ? sites : [], [
35
+ sites
36
+ ]);
37
+ const ready = sitesReady !== false;
38
+ // Nothing to say about leaving sites out until the sites have been read.
39
+ const problem = useMemo(()=>{
40
+ if (!value || value.mode === 'allExcept' && !ready) return null;
41
+ return campaignSharingWrite(value, named.map((site)=>site.id)).problem;
42
+ }, [
43
+ value,
44
+ named,
45
+ ready
46
+ ]);
47
+ return /*#__PURE__*/ _jsxs(FormFieldGrid, {
48
+ children: [
49
+ /*#__PURE__*/ _jsx(SiteSharingField, {
50
+ label: label != null ? label : 'Shared with',
51
+ value: value,
52
+ onChange: input.onChange,
53
+ sites: named,
54
+ sitesReady: ready,
55
+ problem: problem
56
+ }),
57
+ helperText ? /*#__PURE__*/ _jsx(Typography, {
58
+ variant: "caption",
59
+ color: "text.secondary",
60
+ component: "p",
61
+ children: helperText
62
+ }) : null
63
+ ]
64
+ });
65
+ }
66
+ CampaignSharingFormField.displayName = 'CampaignSharingFormField';
67
+ export default CampaignSharingFormField;
68
+
69
+ //# sourceMappingURL=campaign-sharing-form-field.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/campaign-sharing-form-field.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport type { ScopeSharingChoice } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport {\n SiteSharingField,\n type SiteSharingSite,\n} from '@aglyn/shared-ui-jsx/components/site-sharing-field.component'\nimport { FormFieldGrid } from '@aglyn/shared-ui-jsx-forms/mapper/form-field-grid'\nimport { useFieldApi } from '@aglyn/shared-ui-jsx-forms/vendor/data-driven-forms'\nimport { Typography } from '@mui/material'\nimport { useMemo } from 'react'\nimport { campaignSharingWrite } from '../model/campaign-container'\n\n/** The `component` name the create drawer's sharing field asks for. */\nexport const CAMPAIGN_SHARING_FIELD = 'campaign-site-sharing'\n\n/**\n * Who a new campaign is shared with, in the console's create drawer\n * (AGL-4047): the shared `SiteSharingField`, radios and a visible list of\n * sites, never a dropdown. It holds the choice; what the choice writes, and\n * whether it can be, is `campaignSharingWrite`, asked here to say why before\n * the create, and again by the create itself and by the manage route.\n */\nexport function CampaignSharingFormField(props: Record<string, unknown>) {\n const { input, sites, sitesReady, label, helperText } = useFieldApi(props as never) as unknown as {\n input: { value: ScopeSharingChoice | ''; onChange: (next: ScopeSharingChoice) => void }\n sites?: readonly SiteSharingSite[]\n sitesReady?: boolean\n label?: string\n helperText?: string\n }\n const value = input.value ? input.value : null\n const named = useMemo(() => sites ?? [], [sites])\n const ready = sitesReady !== false\n // Nothing to say about leaving sites out until the sites have been read.\n const problem = useMemo(() => {\n if (!value || (value.mode === 'allExcept' && !ready)) return null\n return campaignSharingWrite(\n value,\n named.map((site) => site.id),\n ).problem\n }, [value, named, ready])\n return (\n <FormFieldGrid>\n <SiteSharingField\n label={label ?? 'Shared with'}\n value={value}\n onChange={input.onChange}\n sites={named}\n sitesReady={ready}\n problem={problem}\n />\n {helperText ? (\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"p\">\n {helperText}\n </Typography>\n ) : null}\n </FormFieldGrid>\n )\n}\nCampaignSharingFormField.displayName = 'CampaignSharingFormField'\n\nexport default CampaignSharingFormField\n"],"names":["SiteSharingField","FormFieldGrid","useFieldApi","Typography","useMemo","campaignSharingWrite","CAMPAIGN_SHARING_FIELD","CampaignSharingFormField","props","input","sites","sitesReady","label","helperText","value","named","ready","problem","mode","map","site","id","onChange","variant","color","component","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAGA,SACEA,gBAAgB,QAEX,+DAA8D;AACrE,SAASC,aAAa,QAAQ,oDAAmD;AACjF,SAASC,WAAW,QAAQ,sDAAqD;AACjF,SAASC,UAAU,QAAQ,gBAAe;AAC1C,SAASC,OAAO,QAAQ,QAAO;AAC/B,SAASC,oBAAoB,QAAQ,iCAA6B;AAElE,qEAAqE,GACrE,OAAO,MAAMC,yBAAyB,wBAAuB;AAE7D;;;;;;CAMC,GACD,OAAO,SAASC,yBAAyBC,KAA8B;IACrE,MAAM,EAAEC,KAAK,EAAEC,KAAK,EAAEC,UAAU,EAAEC,KAAK,EAAEC,UAAU,EAAE,GAAGX,YAAYM;IAOpE,MAAMM,QAAQL,MAAMK,KAAK,GAAGL,MAAMK,KAAK,GAAG;IAC1C,MAAMC,QAAQX,QAAQ,IAAMM,gBAAAA,QAAS,EAAE,EAAE;QAACA;KAAM;IAChD,MAAMM,QAAQL,eAAe;IAC7B,yEAAyE;IACzE,MAAMM,UAAUb,QAAQ;QACtB,IAAI,CAACU,SAAUA,MAAMI,IAAI,KAAK,eAAe,CAACF,OAAQ,OAAO;QAC7D,OAAOX,qBACLS,OACAC,MAAMI,GAAG,CAAC,CAACC,OAASA,KAAKC,EAAE,GAC3BJ,OAAO;IACX,GAAG;QAACH;QAAOC;QAAOC;KAAM;IACxB,qBACE,MAACf;;0BACC,KAACD;gBACCY,KAAK,EAAEA,gBAAAA,QAAS;gBAChBE,OAAOA;gBACPQ,UAAUb,MAAMa,QAAQ;gBACxBZ,OAAOK;gBACPJ,YAAYK;gBACZC,SAASA;;YAEVJ,2BACC,KAACV;gBAAWoB,SAAQ;gBAAUC,OAAM;gBAAiBC,WAAU;0BAC5DZ;iBAED;;;AAGV;AACAN,yBAAyBmB,WAAW,GAAG;AAEvC,eAAenB,yBAAwB"}
@@ -42,12 +42,13 @@ import { collection, limit, query, setDoc, where } from "firebase/firestore";
42
42
  import { useCallback, useMemo, useState } from "react";
43
43
  import { useRouter } from "next/navigation";
44
44
  import { useConsoleHostRoute, useFirestore, useFirestoreCollection, useUser } from "@aglyn/tenant-feature-instance";
45
- import { campaignListRows, campaignSiteIds, campaignVisibleTo } from "../model/campaign-container.js";
45
+ import { campaignAllExceptLabel, campaignListRows, campaignSharingWrite, campaignSiteIds, campaignSiteVisibleTo } from "../model/campaign-container.js";
46
46
  import { CreateArtifactDrawer } from "@aglyn/shared-ui-jsx-forms";
47
47
  import { CAMPAIGN_SITE_SEARCH_NOTICE, SINGLE_SENDS_BASE, campaignContainerSearchFields, campaignContainersListQuery, campaignContainersScope, campaignSendsScope, campaignSingleSendsListQuery, campaignSiteSearchClause } from "../model/campaign-list-query.js";
48
48
  import { campaignContainerDoc, campaignContainersCollection, campaignSendsCollection } from "./campaign-queries.js";
49
49
  import { orgSiteName, orgSiteOptions, topicCatalogHostId, useMarketingOrgId, useMarketingOrgMount } from "./marketing-org-mount.js";
50
50
  import { useCampaignManageApi } from "./use-campaign-send-api.js";
51
+ import { CAMPAIGN_SHARING_FIELD, CampaignSharingFormField } from "./campaign-sharing-form-field.js";
51
52
  import { HostCampaignsZone } from "./campaign-list-zones.js";
52
53
  import { useCampaignTopicOptions } from "./use-campaign-topic-options.js";
53
54
  /**
@@ -150,7 +151,7 @@ const NO_CLAUSES = {
150
151
  // so the rule asks it, and the button says so before the save does. Created
151
152
  // here it is placed on this site, so the site's verdict counts. A row's Delete
152
153
  // answers the manage route, which the same hook reads.
153
- const { createBlocked: containersBlocked, deleteBlocked } = useCampaignListAccess(orgId, hostId);
154
+ const { createBlocked: containersBlocked, deleteBlocked, deleteReachRefusal } = useCampaignListAccess(orgId, hostId);
154
155
  // A container is the org's, so deleting one from the org hub names the org.
155
156
  const manageApi = useCampaignManageApi(hostId, orgId);
156
157
  /*==========================================
@@ -354,14 +355,21 @@ const NO_CLAUSES = {
354
355
  return ((_order_get = order.get(a.id)) != null ? _order_get : 0) - ((_order_get1 = order.get(b.id)) != null ? _order_get1 : 0);
355
356
  }).map((row)=>_extends({}, row, {
356
357
  $id: row.id,
357
- sitesLabel: orgMount ? campaignSitesLabel(orgMount, row, byId.get(row.id)) : ''
358
+ sitesLabel: orgMount ? campaignSitesLabel(orgMount, row, byId.get(row.id)) : '',
359
+ /*
360
+ * Why the site's own door would refuse this row's delete past the
361
+ * key: a campaign on other sites too, or shared with all sites except
362
+ * some, asks for access to every site (AGL-4047). Read off the row
363
+ * already loaded, so it costs nothing.
364
+ */ deleteReach: row.legacy ? null : deleteReachRefusal(byId.get(row.id))
358
365
  }));
359
366
  }, [
360
367
  kind,
361
368
  page.rows,
362
369
  firstSends.rows,
363
370
  restSends.rows,
364
- orgMount
371
+ orgMount,
372
+ deleteReachRefusal
365
373
  ]);
366
374
  const pageSorts = useMemo(()=>({
367
375
  sitesLabel: (row)=>row.sitesLabel || null,
@@ -426,7 +434,8 @@ const NO_CLAUSES = {
426
434
  router
427
435
  ]);
428
436
  const handleCreate = useCallback(async (values)=>{
429
- var _values_displayName;
437
+ var _values_displayName, _values_sharing, _ref, _ref1;
438
+ var _placed_fields;
430
439
  if (creating) return;
431
440
  /*
432
441
  * `displayName` is the shared drawer's own field, and every artifact
@@ -449,19 +458,33 @@ const NO_CLAUSES = {
449
458
  */ if (!orgId) {
450
459
  return setCreateError('This workspace is still loading — try again');
451
460
  }
452
- setCreating(true);
453
- setCreateError(null);
454
- const id = createResourceUid();
455
461
  /*
456
462
  * Where it is placed. From a site's hub, that site — the creator is
457
463
  * standing on it, and a campaign that appeared on every sibling site
458
- * would be a decision nobody made. From the org hub, the sites picked,
459
- * and every site when none are.
460
- */ const visibleTo = campaignVisibleTo(hostId ? [
461
- hostId
462
- ] : Array.isArray(values.siteIds) ? values.siteIds.map(String) : null);
464
+ * would be a decision nobody made. From the org hub, who it is shared
465
+ * with, as the sharing field chose (AGL-4047): a choice that cannot be
466
+ * stored is refused with the reason, never cut short — more than thirty
467
+ * chosen sites used to keep the first thirty and say nothing.
468
+ *
469
+ * "All sites except…" is created on the sites it reaches today and then
470
+ * marked by the manage route, the one writer of the marker: the rules
471
+ * refuse it on a client create. Until the route answers it is exactly
472
+ * a campaign on those sites, never on a site that was left out.
473
+ */ const sharing = hostId ? null : (_values_sharing = values.sharing) != null ? _values_sharing : {
474
+ mode: 'all'
475
+ };
476
+ const orgHostIds = ((_ref = orgMount == null ? void 0 : orgMount.hosts) != null ? _ref : []).map((site)=>site.id);
477
+ const placed = sharing ? campaignSharingWrite(sharing, orgHostIds) : null;
478
+ if (sharing && sharing.mode !== 'all' && !(orgMount == null ? void 0 : orgMount.hostsReady)) {
479
+ return setCreateError('This workspace’s sites are still loading — try again');
480
+ }
481
+ if (placed && !placed.fields) return setCreateError(placed.problem);
482
+ const visibleTo = hostId ? campaignSiteVisibleTo(hostId) : (_ref1 = placed == null ? void 0 : (_placed_fields = placed.fields) == null ? void 0 : _placed_fields.visibleTo) != null ? _ref1 : [];
483
+ setCreating(true);
484
+ setCreateError(null);
485
+ const id = createResourceUid();
463
486
  try {
464
- var _ref;
487
+ var _ref2;
465
488
  await setDoc(campaignContainerDoc(firestore, orgId, id), _extends({
466
489
  name
467
490
  }, campaignContainerSearchFields(name), Number.isFinite(startAtMs) && startAtMs !== null ? {
@@ -475,8 +498,26 @@ const NO_CLAUSES = {
475
498
  } : {}, {
476
499
  visibleTo,
477
500
  createdAtMs: Date.now(),
478
- createdBy: String((_ref = user == null ? void 0 : user.uid) != null ? _ref : '')
501
+ createdBy: String((_ref2 = user == null ? void 0 : user.uid) != null ? _ref2 : '')
479
502
  }));
503
+ if ((sharing == null ? void 0 : sharing.mode) === 'allExcept') {
504
+ // The campaign exists either way, so a refusal here is said, never
505
+ // reported as a create that failed.
506
+ const refusal = await manageApi({
507
+ action: 'setSharing',
508
+ campaignId: id,
509
+ choice: sharing
510
+ }).then(({ response, payload })=>{
511
+ var _ref;
512
+ return response.ok ? null : String((_ref = payload == null ? void 0 : payload.error) != null ? _ref : 'the sharing was refused');
513
+ }).catch(()=>'the sharing could not be saved');
514
+ if (refusal) {
515
+ enqueueSnackbar('The campaign was created on the sites it reaches today, but a ' + `new site will not get it: ${refusal}`, {
516
+ variant: 'warning',
517
+ allowDuplicate: true
518
+ });
519
+ }
520
+ }
480
521
  setCreateOpen(false);
481
522
  openCampaign(id);
482
523
  } catch (error) {
@@ -494,8 +535,10 @@ const NO_CLAUSES = {
494
535
  firestore,
495
536
  hostId,
496
537
  orgId,
538
+ orgMount,
497
539
  user,
498
540
  enqueueSnackbar,
541
+ manageApi,
499
542
  openCampaign
500
543
  ]);
501
544
  const campaignHref = useCallback((id)=>hubPath ? `${hubPath}/campaigns/${id}` : null, [
@@ -814,8 +857,8 @@ const NO_CLAUSES = {
814
857
  size: 0.8
815
858
  }),
816
859
  destructive: true,
817
- disabled: row.legacy || deleteBlocked || Boolean(deletingId),
818
- disabledReason: row.legacy ? 'This is a single send, not a campaign. Open it to ' + 'manage the email itself.' : deleteBlocked ? MARKETING_CAMPAIGNS_REFUSAL : 'A campaign is being deleted',
860
+ disabled: row.legacy || deleteBlocked || Boolean(row.deleteReach) || Boolean(deletingId),
861
+ disabledReason: row.legacy ? 'This is a single send, not a campaign. Open it to ' + 'manage the email itself.' : deleteBlocked ? MARKETING_CAMPAIGNS_REFUSAL : row.deleteReach ? String(row.deleteReach) : 'A campaign is being deleted',
819
862
  onClick: ()=>void handleDelete(row)
820
863
  }
821
864
  ]
@@ -995,7 +1038,14 @@ const NO_CLAUSES = {
995
1038
  submitLabel: "Create campaign",
996
1039
  includeDescription: false,
997
1040
  onSubmit: handleCreate,
998
- extraFields: campaignFields(listOptions, topicOptions, orgMount ? orgSiteOptions(orgMount) : null),
1041
+ extraFields: campaignFields(listOptions, topicOptions, orgMount ? {
1042
+ sites: orgSiteOptions(orgMount).map((site)=>({
1043
+ id: site.value,
1044
+ name: site.label
1045
+ })),
1046
+ ready: orgMount.hostsReady
1047
+ } : null),
1048
+ componentMapper: CAMPAIGN_FORM_COMPONENTS,
999
1049
  errorSlot: createError ? /*#__PURE__*/ _jsx(Alert, {
1000
1050
  severity: "error",
1001
1051
  sx: {
@@ -1008,6 +1058,9 @@ const NO_CLAUSES = {
1008
1058
  ]
1009
1059
  });
1010
1060
  }
1061
+ /** The create drawer's one field the shared form library has no component for. */ const CAMPAIGN_FORM_COMPONENTS = {
1062
+ [CAMPAIGN_SHARING_FIELD]: CampaignSharingFormField
1063
+ };
1011
1064
  /**
1012
1065
  * What a campaign collects beyond its name.
1013
1066
  *
@@ -1017,16 +1070,21 @@ const NO_CLAUSES = {
1017
1070
  * day would be a precision the model does not carry.
1018
1071
  */ function campaignFields(lists, topics, /** The org's sites, on the org hub only — a site hub places on itself. */ sites) {
1019
1072
  return [
1020
- ...sites ? [
1073
+ /*
1074
+ * Who it is shared with (AGL-4047): radios and a visible list of sites,
1075
+ * never a dropdown, starting on All sites as the empty selection it
1076
+ * replaces did.
1077
+ */ ...sites ? [
1021
1078
  {
1022
- component: 'select',
1023
- name: 'siteIds',
1024
- label: 'Sites',
1025
- multiple: true,
1026
- initialValue: [],
1027
- helperText: 'The sites this campaign is offered on. Leave empty for every site.',
1028
- disableDefaultOption: true,
1029
- options: sites
1079
+ component: CAMPAIGN_SHARING_FIELD,
1080
+ name: 'sharing',
1081
+ label: 'Shared with',
1082
+ initialValue: {
1083
+ mode: 'all'
1084
+ },
1085
+ helperText: 'The sites this campaign is offered on.',
1086
+ sites: sites.sites,
1087
+ sitesReady: sites.ready
1030
1088
  }
1031
1089
  ] : [],
1032
1090
  {
@@ -1077,6 +1135,12 @@ const NO_CLAUSES = {
1077
1135
  */ function campaignSitesLabel(mount, row, container) {
1078
1136
  var _row_sends_;
1079
1137
  if (row.legacy) return orgSiteName(mount, (_row_sends_ = row.sends[0]) == null ? void 0 : _row_sends_.hostId) || '—';
1138
+ // Shared with all sites except some: the sites it leaves out (AGL-4047).
1139
+ const allExcept = campaignAllExceptLabel(container, Object.fromEntries(orgSiteOptions(mount).map((site)=>[
1140
+ site.value,
1141
+ site.label
1142
+ ])));
1143
+ if (allExcept) return allExcept;
1080
1144
  const ids = campaignSiteIds(container);
1081
1145
  if (ids === null) return 'Every site';
1082
1146
  if (!ids.length) return 'No site';