@aglyn/plugins-workflows 1.0.0-beta.200 → 1.0.0-beta.201
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 +12 -12
- package/src/lib/components/host-actions-card.component.js +2 -1
- package/src/lib/components/host-actions-card.component.js.map +1 -1
- package/src/lib/components/host-workflows-card.component.js +2 -1
- package/src/lib/components/host-workflows-card.component.js.map +1 -1
- package/src/lib/components/site-org-automations-panel.component.js +2 -1
- package/src/lib/components/site-org-automations-panel.component.js.map +1 -1
- package/src/lib/engine/run-event-actions.js +53 -10
- package/src/lib/engine/run-event-actions.js.map +1 -1
- package/src/lib/engine/run-event-workflows.js +4 -0
- package/src/lib/engine/run-event-workflows.js.map +1 -1
- package/src/lib/engine/site-suspension.d.ts +45 -0
- package/src/lib/engine/site-suspension.js +54 -0
- package/src/lib/engine/site-suspension.js.map +1 -0
- package/src/lib/server.js +14 -0
- package/src/lib/server.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/components/host-workflows-card.component.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 {\n type AglynOrgBilling,\n checkEntitlement,\n checkQuota,\n HOST_EVENT_TYPES,\n hostEventLabel,\n hostEventPayloadHint,\n type HostActionStep,\n type HostActionStepType,\n type HostFunction,\n type HostVariable,\n type HostWorkflowStep,\n pluginDocsHelp,\n runWorkflow,\n WORKFLOW_MAX_STEPS,\n} from '@aglyn/aglyn'\n/*\n * The MODULE, not the barrel, for the two PURE helpers — every spec that\n * renders this card mocks `@aglyn/tenant-feature-instance` wholesale to stage\n * its Firestore hooks, and a query builder imported through that barrel\n * disappears under the mock. Neither of these is a hook.\n */\nimport {\n ceilingedWindow,\n collectionCeiling,\n} from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { useConsoleWidgetSlot } from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport type { ConsoleAutomationTarget } from '@aglyn/aglyn/plugin-manager/feature-plugins'\nimport { CardDisplay, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport QuotaReadoutComponent from '@aglyn/shared-ui-jsx/components/quota-readout.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n doc,\n getCountFromServer,\n setDoc,\n updateDoc,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport {\n useDuplicateResource,\n useFirestore,\n useFirestoreCollection,\n useHostResourceApi,\n useUser,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport {\n AutomationStepFields,\n type AutomationStepKind,\n defaultStep,\n} from './automation-step-fields.component'\nimport {\n type AutomationWorkflow,\n isWorkflowActionStep,\n validateWorkflowSteps,\n WORKFLOW_ACTION_STEP_TYPES,\n workflowFunctionCalls,\n type WorkflowStep,\n workflowStepTypeLabel,\n} from '../engine/workflow-steps'\nimport HostRunHistoryCard from './host-run-history-card.component'\nimport {\n EDITOR_OPTION_CEILING,\n useAutomationStepPickers,\n} from './use-automation-step-pickers'\nimport { listConsoleWidgets } from '@aglyn/aglyn'\nimport {\n fetchWhereUsed,\n summarizeDependents,\n type WhereUsedResult,\n} from '@aglyn/aglyn/app-utils/where-used'\nimport { WORKFLOW_USAGE_ZONE } from './workflow-zones'\n\n/**\n * How many workflows the card reads.\n *\n * A CEILING, not a page size — see the query, which explains why this list\n * cannot be paged by the server without making the duplicate-name check lie.\n */\nconst WORKFLOW_CEILING = 100\n\n/** The \"Do\" entry for the step kind a workflow has always had: a call. */\nconst FUNCTION_CALL_KIND = 'functionCall'\n\n/**\n * What a step may be (AGL-3105).\n *\n * The function call comes first because it is what a workflow was before the\n * two engines became one, and is still what a new step is. After it comes\n * every Actions step a SERVER event can run — the client-only interactions\n * are absent, because a workflow runs where there is no page to run them on.\n */\nconst STEP_KINDS: AutomationStepKind[] = [\n { value: FUNCTION_CALL_KIND, label: 'Call a function' },\n ...WORKFLOW_ACTION_STEP_TYPES.map((value) => ({\n value,\n label: workflowStepTypeLabel(value),\n })),\n]\n\nexport interface HostWorkflowsCardProps {\n hostId: string\n /** Resolved entitlement source for quota checks (AGL-395). */\n org?: Partial<AglynOrgBilling>\n}\n\ninterface WorkflowDraft extends AutomationWorkflow {\n id: string | null\n}\n\n/**\n * Workflow builder v1 (AGL-101): pipelines of host-function calls — each\n * step's argument expressions see host variables and previous step results\n * (`step1`, or a custom result name). Runs through the pure `runWorkflow`\n * evaluator; test-run panel included. Plan-gated (`workflows` flag +\n * `workflowsPerHost` cap, AGL-99); site-event triggers are v2.\n */\nexport function HostWorkflowsCard(props: HostWorkflowsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const createHostResource = useHostResourceApi()\n const { enqueueSnackbar } = useSnackbar()\n // Duplicate (AGL-2936): the copy keeps every step and arrives disarmed —\n // its trigger is cleared — so nothing runs twice until somebody arms it.\n const duplicate = useDuplicateResource({\n hostId,\n onDuplicated: (_kind, copy) =>\n enqueueSnackbar(\n `Duplicated as “${copy.name}” — arm its trigger to run it`,\n {\n variant: 'success',\n },\n ),\n })\n const { confirm } = useConfirmationContext()\n const { org } = props\n /**\n * The shell's zone renderer, for what other plugins add to a saved workflow's\n * editor (AGL-2919); `null` outside the console shell.\n */\n const ExtensionZone = useConsoleWidgetSlot()\n\n const {\n data: workflowDocs,\n status: workflowsStatus,\n /**\n * The rows this editor is seeded from are unconfirmed by the server\n * (AGL-1358). Editing destructures a whole stored workflow into `draft`\n * and writes `{...definition}` back, so `merge: true` protects nothing.\n * `trigger` is the field that makes this more than a lost edit: it is\n * `{event, filter}` or `null` for manual-only, and nothing else on this\n * card writes it, so a cached seed can re-arm an automation the author\n * disarmed — or disarm one running on a live site — and revert every\n * step of the pipeline with it.\n */\n fromCache: workflowsFromCache,\n } = useFirestoreCollection<any>(\n /*\n * ORDERED AND CEILINGED, deliberately not paged by the query (AGL-2501) —\n * the same decision as the logic plugin's two cards, for the same reasons.\n *\n * `limit(100)` alone is answered in DOCUMENT-ID order, so the window is a\n * pseudo-random hundred that the `localeCompare` below arranges\n * alphabetically, and nothing said the list was bounded.\n *\n * `collectionCeiling` does not change WHICH hundred — document-id order is\n * what the bare cap already returned. What it changes is that the order is\n * NAMED, so the obvious next edit is caught: ordering on `name` would HIDE\n * every workflow written without one rather than mis-sorting the list, and\n * `/api/hosts/resources` validates no field for presence while\n * `IMPORTABLE_FIELDS.workflows` copies one only if the export carried it.\n *\n * The QUERY is not paged because `nameTaken` below tests the draft against\n * these rows: computed variables look their workflow up BY NAME\n * (AGL-185/AGL-261), so a duplicate silently rebinds a live binding, and a\n * uniqueness check over a ten-row page would let one through.\n */\n () =>\n collectionCeiling(\n collection(firestore, 'hosts', hostId, 'workflows'),\n WORKFLOW_CEILING,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { rows: readWorkflows, truncated: workflowsTruncated } =\n ceilingedWindow<any>(workflowDocs, WORKFLOW_CEILING)\n const [draft, setDraft] = useState<WorkflowDraft | null>(null)\n /**\n * The editor has been opened at least once in this session.\n *\n * A LATCH rather than `draft` itself, because the two reads below key their\n * listeners on it. Tracking the dialog would tear those subscriptions down\n * on Cancel and pay for them again on the next Edit, so a merchant working\n * through ten actions would buy the same two windows ten times — worse than\n * the mount-time read this replaces. Latched, a reader who never edits pays\n * nothing and a reader who edits pays once.\n */\n const [editorOpened, setEditorOpened] = useState(false)\n if (draft && !editorOpened) setEditorOpened(true)\n /*\n * THE EDITOR'S WORKING SET, read when the editor opens.\n *\n * Nothing outside the dialog reads either of these: the table renders a\n * workflow's stored step names, and `runWorkflow` is only reachable from the\n * test-run button inside the dialog. Mounting them unconditionally charges\n * every visitor to this page two windows to fill a select and seed a\n * scratchpad most of them never open.\n *\n * Ceilinged and ordered for the reason the workflows query above gives: a\n * bare `limit` is answered in document-id order, so the `localeCompare` on\n * the options below would arrange a pseudo-random hundred into a convincing\n * alphabet, and a function past the window could not be picked with nothing\n * saying why.\n */\n const { data: functionRead } = useFirestoreCollection<any>(\n () =>\n editorOpened\n ? collectionCeiling(\n collection(firestore, 'hosts', hostId, 'functions'),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, hostId, editorOpened],\n { idField: '$id' },\n )\n // Memoised so the window keeps one identity while the rows do — the option\n // list and the two lookup maps below are all built from it.\n const { rows: functionDocs, truncated: functionsTruncated } = useMemo(\n () => ceilingedWindow<any>(functionRead, EDITOR_OPTION_CEILING),\n [functionRead],\n )\n const { data: variableRead } = useFirestoreCollection<any>(\n () =>\n editorOpened\n ? collectionCeiling(\n collection(firestore, 'hosts', hostId, 'variables'),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, hostId, editorOpened],\n { idField: '$id' },\n )\n const { rows: variableDocs, truncated: variablesTruncated } = useMemo(\n () => ceilingedWindow<any>(variableRead, EDITOR_OPTION_CEILING),\n [variableRead],\n )\n /*\n * What an ACTIONS step can be pointed at, on the same latch (AGL-3105).\n *\n * The hook the Actions builder uses, because a workflow step may be any\n * server-side Actions step and the two editors therefore offer one set of\n * records. Read on the editor's first open, like the two windows above, so\n * a reader who never edits a workflow still pays nothing for them.\n */\n const { pickers: stepPickers, truncated: truncatedPickers } =\n useAutomationStepPickers(hostId, editorOpened)\n // Sorting is safe here in a way it is not on a paged list: these rows are\n // the whole collection below the ceiling, not a slice of one.\n const workflows = useMemo(\n () =>\n readWorkflows\n .filter((workflow: any) => !workflow.deletedAt)\n .sort((a: any, b: any) =>\n String(a.name ?? '').localeCompare(String(b.name ?? '')),\n ),\n [readWorkflows],\n )\n // The page is a SLICE: the rows are already in hand and `nameTaken` needs\n // all of them.\n const [page, setPage] = useState(0)\n const [pageSize, setPageSize] = useState(TABLE_PAGE_SIZE_DEFAULT)\n const visibleWorkflows = useMemo(\n () => workflows.slice(page * pageSize, page * pageSize + pageSize),\n [workflows, page, pageSize],\n )\n /**\n * The workflow HEAD-COUNT is a server aggregate, not the length of the\n * capped listener (AGL-1716, the AGL-1706 shape).\n *\n * The listener is `limit(100)` and `workflows.length` fed\n * `checkQuota(org, 'workflowsPerHost', …)`, whose bands are 0 / 3 / 25 /\n * 100 / 250 / 500. The window TIES Business's 100 and hides Scale's 250\n * and Advanced's 500, so on those plans the gate compared 100 against\n * hundreds and could never refuse — while `api/hosts/resources` counted\n * the collection and did. The card offered headroom that did not exist and\n * then failed the create.\n *\n * UNFILTERED, matching that route's plain `collection('workflows').count()`\n * — its `softDeletes` branch governs only the flat per-host webhook cap, so\n * soft-deleted workflows have always counted server-side while this card\n * excluded them. Only a create moves the number, so that is where it is\n * re-read.\n */\n const [workflowCountEpoch, setWorkflowCountEpoch] = useState(0)\n const [serverWorkflowCount, setServerWorkflowCount] = useState<number | null>(\n null,\n )\n useEffect(() => {\n let active = true\n void getCountFromServer(collection(firestore, 'hosts', hostId, 'workflows'))\n .then((snapshot) => {\n if (active) setServerWorkflowCount(snapshot.data().count)\n })\n .catch(() => {\n // Falls back to the loaded rows — a LOWER bound and the prior\n // behaviour, never 0, which `checkQuota` would answer as \"no usage\"\n // on a site that is over its band.\n })\n return () => {\n active = false\n }\n }, [firestore, hostId, workflowCountEpoch])\n const workflowCount = serverWorkflowCount ?? workflows.length\n // Double-keyed by doc id and name (AGL-261): id references are\n // rename-safe; legacy name references keep resolving.\n const functions = useMemo(() => {\n const map: Record<string, HostFunction> = {}\n for (const definition of functionDocs ?? []) {\n if (definition.deletedAt) continue\n if (definition.$id) map[definition.$id] = definition\n if (definition.name) map[definition.name] = definition\n }\n return map\n }, [functionDocs])\n const functionOptions = useMemo(\n () =>\n (functionDocs ?? [])\n .filter((definition: any) => !definition.deletedAt && definition.name)\n .map((definition: any) => ({\n id: definition.$id as string,\n name: definition.name as string,\n }))\n .sort((a, b) => a.name.localeCompare(b.name)),\n [functionDocs],\n )\n const variables = useMemo(() => {\n const map: Record<string, HostVariable> = {}\n for (const variable of variableDocs ?? []) {\n if (!variable.deletedAt && variable.name) map[variable.name] = variable\n }\n return map\n }, [variableDocs])\n\n // Where-used dialog (AGL-193).\n const [usage, setUsage] = useState<{\n name: string\n result: WhereUsedResult\n } | null>(null)\n const [usageLoading, setUsageLoading] = useState<string | null>(null)\n\n const [testResult, setTestResult] = useState<string | null>(null)\n const [runsFor, setRunsFor] = useState<any | null>(null)\n\n // Case-insensitive uniqueness (AGL-185): workflow names must stay\n // unambiguous for computed-variable lookups keyed by name.\n const nameTaken = Boolean(\n draft &&\n workflows.some(\n (definition: any) =>\n String(definition.name ?? '').toLowerCase() ===\n draft.name.trim().toLowerCase() && definition.$id !== draft.id,\n ),\n )\n\n const patch = useCallback(\n (updater: (previous: WorkflowDraft) => WorkflowDraft) =>\n setDraft((previous) => (previous ? updater(previous) : previous)),\n [],\n )\n\n /** The saved workflow the editor has open, as the `automationEditor` zone names it. */\n const draftId = draft?.id ?? null\n const draftName = draft?.name ?? ''\n const editorTarget = useMemo<ConsoleAutomationTarget | null>(\n () => (draftId ? { type: 'workflow', id: draftId, name: draftName } : null),\n // The name the editor opened with: the zone reads the workflow as it is\n // stored, so a rename being typed does not make it a different one.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [draftId],\n )\n\n const handleAdd = useCallback(() => {\n // Feature + cap gate (AGL-99); dark-launch for plan-less workspaces.\n if (!checkEntitlement(org, 'workflows')) {\n return void enqueueSnackbar(\n 'Workflows require a Starter plan — see Billing to upgrade',\n { variant: 'warning', persist: false },\n )\n }\n // The site's workflows, not this page of them (AGL-1716).\n const quota = checkQuota(org, 'workflowsPerHost', workflowCount)\n if (!quota.allowed) {\n return void enqueueSnackbar(\n `Workflow limit reached (${quota.limit}) — upgrade in Billing`,\n { variant: 'warning', persist: false },\n )\n }\n setTestResult(null)\n setDraft({\n id: null,\n name: '',\n steps: [{ functionName: '', args: [], resultName: '' }],\n returnValue: '',\n trigger: null,\n })\n }, [org, workflowCount, enqueueSnackbar])\n\n /**\n * Every list the ceiling cut, named — the editor's two and the step\n * pickers' six, in one notice for the reason the Actions builder gives:\n * they are one read, and an author told the function list is short learns\n * nothing from being told again about datasets.\n */\n const shortLists = useMemo(\n () =>\n [\n functionsTruncated ? 'functions' : null,\n variablesTruncated ? 'variables' : null,\n ...truncatedPickers,\n ].filter((name): name is string => name !== null),\n [functionsTruncated, variablesTruncated, truncatedPickers],\n )\n\n /**\n * The first thing wrong with the steps, said the way the editors say it.\n *\n * The same check the engine makes of what it is handed: an Actions step is\n * held to the Actions validator, a call has to name a function, and a step\n * only a visitor's browser can run is refused. Said while the author is\n * still in the dialog rather than after a save that stores a step nothing\n * can run.\n */\n const stepProblem = useMemo(\n () => (draft ? validateWorkflowSteps(draft.steps) : null),\n [draft],\n )\n\n const handleTestRun = useCallback(() => {\n if (!draft) return\n /*\n * The FUNCTION CALLS, evaluated. A test run is the pure evaluator, and\n * an Actions step is not something to evaluate — it sends, writes and\n * charges. Running one here would perform it against the live site from\n * a button labelled \"Test run\", so the calls are evaluated, each keeping\n * the result name it holds among all the steps, and the rest is left to\n * the run itself.\n */\n const run = runWorkflow(workflowFunctionCalls(draft), functions, variables)\n setTestResult(\n run.ok === false\n ? `Error: ${run.error}`\n : `Result: ${String(run.value)} (${Object.entries(run.results)\n .map(([key, value]) => `${key}=${value}`)\n .join(', ')})`,\n )\n }, [draft, functions, variables])\n\n const handleSave = useCallback(async () => {\n if (!draft || !draft.name.trim() || nameTaken) return\n // The steps are checked at the door, not after the write: a stored step\n // nothing can run is a run that fails on the site rather than here.\n if (stepProblem) {\n return void enqueueSnackbar(stepProblem, {\n variant: 'warning',\n persist: false,\n })\n }\n const { id: draftId, ...definition } = draft\n const fields = { ...definition, name: draft.name.trim().slice(0, 60) }\n try {\n if (draftId) {\n /**\n * Edit stays client-direct (no quota consumed) — and is refused when\n * its seed was never confirmed by the server (AGL-1358). `fields` is\n * the whole definition spread out of the listener row, `trigger` and\n * `steps` included, so `merge: true` has nothing left to protect.\n *\n * The guard WRAPS the write. An early return is a shape you can keep\n * while losing the protection; here the write is only reachable\n * through the verdict.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'workflow',\n unreadable: workflowsStatus === 'error',\n fromCache: workflowsFromCache,\n },\n async () => {\n await setDoc(\n doc(firestore, 'hosts', hostId, 'workflows', draftId),\n { ...fields, updatedAt: Timestamp.now() },\n { merge: true },\n )\n },\n )\n // Before `setDraft(null)`, so a refusal keeps the dialog open with\n // every step that was built and its test run still on screen.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n } else {\n // New workflow rides the quota-enforcing resources API (AGL-473) —\n // it also re-checks the `workflows` entitlement server-side.\n await createHostResource({ hostId, resource: 'workflow', data: fields })\n // A create moves the count; the one-shot aggregate below does not\n // refresh itself the way the listener refreshes the rows.\n setWorkflowCountEpoch((epoch) => epoch + 1)\n }\n setDraft(null)\n enqueueSnackbar('Workflow saved', { variant: 'success', persist: false })\n } catch (error: any) {\n console.error(error)\n enqueueSnackbar(error?.message ?? 'An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n }, [\n draft,\n nameTaken,\n stepProblem,\n firestore,\n hostId,\n createHostResource,\n enqueueSnackbar,\n workflowsStatus,\n workflowsFromCache,\n ])\n\n const handleShowUsage = useCallback(\n (workflow: any) => async () => {\n setUsageLoading(workflow.$id)\n const result = await fetchWhereUsed(user as any, {\n hostId,\n kind: 'workflow',\n id: workflow.$id,\n name: workflow.name,\n })\n setUsageLoading(null)\n // The rows and their deep links are drawn in a zone; with nothing\n // registered there the answer is still given, in words.\n if (listConsoleWidgets(WORKFLOW_USAGE_ZONE.id).length === 0) {\n enqueueSnackbar(\n result.total\n ? `\"${workflow.name}\" computes ${summarizeDependents(result)}`\n : `\"${workflow.name}\" is not referenced by anything published`,\n { variant: 'info', persist: false },\n )\n return\n }\n setUsage({ name: workflow.name, result })\n },\n [user, hostId, enqueueSnackbar],\n )\n\n const handleDelete = useCallback(\n (workflow: any) => async () => {\n // Dependents warning (AGL-187): computed variables backed by this\n // workflow keep their stored fallback value once it is gone.\n const scan = await fetchWhereUsed(user as any, {\n hostId,\n kind: 'workflow',\n id: workflow.$id,\n name: workflow.name,\n })\n const confirmed = await confirm({\n title: 'Delete this workflow?',\n description: scan.total\n ? `\"${workflow.name}\" computes ${summarizeDependents(scan)} — ` +\n 'those variables will fall back to their stored values.'\n : `\"${workflow.name}\" will no longer be runnable.`,\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await updateDoc(\n doc(firestore, 'hosts', hostId, 'workflows', workflow.$id),\n { deletedAt: Timestamp.now() },\n )\n enqueueSnackbar('Workflow deleted', {\n variant: 'success',\n persist: false,\n })\n },\n [user, confirm, firestore, hostId, enqueueSnackbar],\n )\n\n return (\n <CardDisplay\n header={'Workflows'}\n help={pluginDocsHelp('buildAWorkflow', {\n anchor: '#1-open-the-workflows-page',\n })}\n contentGutterX\n contentGutterY\n >\n {duplicate.dialog}\n <Stack spacing={1}>\n {workflows.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Chain your functions into multi-step pipelines — each step ' +\n 'feeds the next. Site-event triggers are coming next.'}\n </Typography>\n ) : (\n visibleWorkflows.map((workflow: any) => (\n <Stack\n key={workflow.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {workflow.name}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {`${(workflow.steps ?? []).length} step${\n (workflow.steps ?? []).length === 1 ? '' : 's'\n }${\n workflow.trigger?.event\n ? ` · on ${hostEventLabel(workflow.trigger.event)}`\n : ''\n } · ${(workflow.steps ?? [])\n .map((step: any) => step.functionName)\n .join(' → ')}`}\n </Typography>\n </Stack>\n <Button\n size=\"small\"\n disabled={usageLoading === workflow.$id}\n onClick={handleShowUsage(workflow)}\n >\n {usageLoading === workflow.$id ? 'Scanning…' : 'Usage'}\n </Button>\n {/* Run history (wave v6): the event runner logs status +\n duration per run. */}\n <Button size=\"small\" onClick={() => setRunsFor(workflow)}>\n {'Runs'}\n </Button>\n <Button\n size=\"small\"\n onClick={() => {\n setTestResult(null)\n setDraft({\n id: workflow.$id,\n name: workflow.name ?? '',\n steps: workflow.steps ?? [],\n returnValue: workflow.returnValue ?? '',\n trigger: workflow.trigger ?? null,\n })\n }}\n >\n {'Edit'}\n </Button>\n <Button\n size=\"small\"\n onClick={() =>\n duplicate.request('workflow', {\n id: workflow.$id,\n name: workflow.name ?? '',\n })\n }\n >\n {'Duplicate…'}\n </Button>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDelete(workflow)}\n >\n {'Delete'}\n </Button>\n </Stack>\n ))\n )}\n {workflows.length === 0 ? null : (\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={visibleWorkflows.length}\n // The workflows the card HOLDS. Not `workflowCount`, which is the\n // site's total including soft-deleted rows and answers the quota's\n // question rather than the reader's.\n count={workflows.length}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n )}\n {workflowsTruncated ? (\n <Alert severity=\"info\">\n {`Showing ${WORKFLOW_CEILING} workflows, ordered by id. This site ` +\n 'has more — the duplicate-name check below only covers the ' +\n 'ones listed here, so a name may already be taken by one that ' +\n 'is not.'}\n </Alert>\n ) : null}\n <Button\n size=\"small\"\n color=\"primary\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={handleAdd}\n >\n {'Add workflow'}\n </Button>\n {/* The cap, standing rather than only on refusal (AGL-2113).\n `workflowCount` is the server aggregate the gate uses, not\n `workflows.length` — the listener is `limit(100)` and its length\n saturates (AGL-1716). */}\n <QuotaReadoutComponent\n ready={org != null}\n used={workflowCount}\n limit={checkQuota(org, 'workflowsPerHost', workflowCount).limit}\n noun=\"workflow\"\n />\n </Stack>\n\n <Dialog\n open={Boolean(draft)}\n onClose={() => setDraft(null)}\n maxWidth=\"sm\"\n fullWidth\n >\n <DialogTitle>\n {draft?.id ? 'Edit Workflow' : 'Add Workflow'}\n </DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, pt: 1 }}\n >\n {ExtensionZone && editorTarget ? (\n <ExtensionZone\n slot=\"automationEditor\"\n hostId={hostId}\n orgId={org?.$id}\n target={editorTarget}\n />\n ) : null}\n <TextField\n label=\"Name\"\n helperText={\n nameTaken\n ? 'A workflow with this name already exists'\n : 'Used to identify the workflow'\n }\n error={nameTaken}\n value={draft?.name ?? ''}\n onChange={(event) =>\n patch((previous) => ({ ...previous, name: event.target.value }))\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n />\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Steps'}\n </Typography>\n {/*\n The pickers and the test run speak only for what was read. A step\n calling a function past the ceiling still RUNS on the site — this\n editor simply cannot name it, and a test run resolves its\n expression against an incomplete variable set.\n */}\n {shortLists.length > 0 ? (\n <Alert severity=\"info\">\n {`Offering the first ${EDITOR_OPTION_CEILING} ` +\n `${shortLists.join(', ')} on this site, ordered by id. ` +\n 'There are more, so the pickers below are short and a test ' +\n 'run may not resolve every expression.'}\n </Alert>\n ) : null}\n {(draft?.steps ?? []).map((step, index) => {\n const call = isWorkflowActionStep(step)\n ? null\n : (step as HostWorkflowStep)\n const definition = call\n ? (functions[(call as any).functionId ?? ''] ??\n functions[call.functionName])\n : null\n return (\n <AutomationStepFields\n key={index}\n /*\n * The editor speaks the Actions vocabulary. A function call\n * has no Actions type, so it takes none of those fields and\n * renders its own through `fields` instead — which is what\n * keeps this one editor rather than two.\n */\n step={step as HostActionStep}\n index={index}\n kind={call ? FUNCTION_CALL_KIND : (step as HostActionStep).type}\n kinds={STEP_KINDS}\n stepForKind={(value) =>\n (value === FUNCTION_CALL_KIND\n ? { functionName: '', args: [], resultName: '' }\n : defaultStep(\n value as HostActionStepType,\n )) as HostActionStep\n }\n pickers={stepPickers}\n onSteps={(update) =>\n patch((previous) => ({\n ...previous,\n steps: update(\n previous.steps as HostActionStep[],\n ) as WorkflowStep[],\n }))\n }\n fields={\n call ? (\n <Stack\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center', flex: 1, flexWrap: 'wrap' }}\n >\n <TextField\n label=\"Function\"\n // Stored by id (AGL-261); legacy steps carry only the\n // name and resolve through the double-keyed map.\n value={\n (call as any).functionId ??\n (functions[call.functionName] as any)?.$id ??\n ''\n }\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n steps: previous.steps.map((s, index2) =>\n index2 === index\n ? {\n ...s,\n functionId: event.target.value,\n functionName:\n functionOptions.find(\n (option) =>\n option.id === event.target.value,\n )?.name ??\n (s as HostWorkflowStep).functionName,\n }\n : s,\n ),\n }))\n }\n size=\"small\"\n select\n sx={{ minWidth: 160, flex: 1 }}\n >\n {functionOptions.map((option) => (\n <MenuItem key={option.id} value={option.id}>\n {option.name}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n label=\"Result name\"\n placeholder={`step${index + 1}`}\n value={call.resultName ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n steps: previous.steps.map((s, index2) =>\n index2 === index\n ? {\n ...s,\n resultName: event.target.value.replace(\n /[^a-zA-Z0-9_]/g,\n '',\n ),\n }\n : s,\n ),\n }))\n }\n size=\"small\"\n sx={{ width: 140 }}\n />\n {(definition?.parameters ?? []).map(\n (parameter, parameterIndex) => (\n <TextField\n key={parameter.name}\n label={`${parameter.name} expression`}\n placeholder={\n parameterIndex === 0 && index > 0\n ? `step${index}`\n : 'a variable, number, or expression'\n }\n value={call.args?.[parameterIndex] ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n steps: previous.steps.map((s, index2) => {\n if (index2 !== index) return s\n const args = [\n ...((s as HostWorkflowStep).args ?? []),\n ]\n args[parameterIndex] = event.target.value\n return { ...s, args }\n }),\n }))\n }\n size=\"small\"\n sx={{ minWidth: 180, flex: 1 }}\n />\n ),\n )}\n </Stack>\n ) : undefined\n }\n />\n )\n })}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n disabled={(draft?.steps.length ?? 0) >= WORKFLOW_MAX_STEPS}\n onClick={() =>\n patch((previous) => ({\n ...previous,\n steps: [\n ...previous.steps,\n { functionName: '', args: [], resultName: '' },\n ],\n }))\n }\n >\n {'Add step'}\n </Button>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Trigger'}\n </Typography>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Run on event\"\n value={draft?.trigger?.event ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: event.target.value\n ? {\n event: event.target.value as any,\n filter: previous.trigger?.filter ?? '',\n }\n : null,\n }))\n }\n size=\"small\"\n select\n sx={{ minWidth: 180 }}\n >\n <MenuItem value=\"\">{'Manual only'}</MenuItem>\n {HOST_EVENT_TYPES.map((eventType) => (\n <MenuItem key={eventType} value={eventType}>\n {hostEventLabel(eventType)}\n </MenuItem>\n ))}\n </TextField>\n {draft?.trigger ? (\n <TextField\n label=\"Filter (optional)\"\n placeholder={'path == \"/pricing\"'}\n helperText={[\n 'Runs only when this expression is truthy.',\n hostEventPayloadHint(draft?.trigger?.event),\n ]\n .filter(Boolean)\n .join(' ')}\n value={draft?.trigger?.filter ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: previous.trigger\n ? { ...previous.trigger, filter: event.target.value }\n : previous.trigger,\n }))\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n ) : null}\n </Stack>\n <TextField\n label=\"Return value\"\n helperText=\"A step result name; defaults to the last step\"\n value={draft?.returnValue ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n returnValue: event.target.value,\n }))\n }\n size=\"small\"\n />\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Button size=\"small\" color=\"primary\" onClick={handleTestRun}>\n {'Test run'}\n </Button>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Uses current variable values'}\n </Typography>\n </Stack>\n {testResult ? (\n <Alert\n severity={testResult.startsWith('Error') ? 'warning' : 'success'}\n >\n {testResult}\n </Alert>\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!draft?.name.trim() || nameTaken}\n onClick={handleSave}\n >\n {'Done'}\n </Button>\n </DialogActions>\n </Dialog>\n {ExtensionZone ? (\n <ExtensionZone\n slot={WORKFLOW_USAGE_ZONE.id}\n hostId={hostId}\n usage={usage}\n onClose={() => setUsage(null)}\n />\n ) : null}\n <Dialog\n open={Boolean(runsFor)}\n onClose={() => setRunsFor(null)}\n maxWidth=\"sm\"\n fullWidth\n >\n <DialogTitle>{`Runs — ${runsFor?.name ?? ''}`}</DialogTitle>\n <DialogContent>\n {runsFor ? (\n <HostRunHistoryCard\n hostId={hostId}\n orgId={org?.$id}\n targetId={runsFor.$id}\n targetType=\"workflow\"\n targetName={runsFor.name ?? ''}\n header=\"Recent runs\"\n />\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button color=\"inherit\" onClick={() => setRunsFor(null)}>\n {'Close'}\n </Button>\n </DialogActions>\n </Dialog>\n </CardDisplay>\n )\n}\nHostWorkflowsCard.displayName = 'HostWorkflowsCard'\n\nexport default HostWorkflowsCard\n"],"names":["checkEntitlement","checkQuota","HOST_EVENT_TYPES","hostEventLabel","hostEventPayloadHint","pluginDocsHelp","runWorkflow","WORKFLOW_MAX_STEPS","ceilingedWindow","collectionCeiling","useConsoleWidgetSlot","CardDisplay","useConfirmationContext","ListPagination","TABLE_PAGE_SIZE_DEFAULT","QuotaReadoutComponent","useSnackbar","Timestamp","Alert","Button","Dialog","DialogActions","DialogContent","DialogTitle","MenuItem","Stack","TextField","Typography","collection","doc","getCountFromServer","setDoc","updateDoc","useCallback","useEffect","useMemo","useState","useDuplicateResource","useFirestore","useFirestoreCollection","useHostResourceApi","useUser","writeGuardedBySeed","AutomationStepFields","defaultStep","isWorkflowActionStep","validateWorkflowSteps","WORKFLOW_ACTION_STEP_TYPES","workflowFunctionCalls","workflowStepTypeLabel","HostRunHistoryCard","EDITOR_OPTION_CEILING","useAutomationStepPickers","listConsoleWidgets","fetchWhereUsed","summarizeDependents","WORKFLOW_USAGE_ZONE","WORKFLOW_CEILING","FUNCTION_CALL_KIND","STEP_KINDS","value","label","map","HostWorkflowsCard","props","runsFor","draft","hostId","firestore","data","user","createHostResource","enqueueSnackbar","duplicate","onDuplicated","_kind","copy","name","variant","confirm","org","ExtensionZone","workflowDocs","status","workflowsStatus","fromCache","workflowsFromCache","idField","rows","readWorkflows","truncated","workflowsTruncated","setDraft","editorOpened","setEditorOpened","functionRead","functionDocs","functionsTruncated","variableRead","variableDocs","variablesTruncated","pickers","stepPickers","truncatedPickers","workflows","filter","workflow","deletedAt","sort","a","b","String","localeCompare","page","setPage","pageSize","setPageSize","visibleWorkflows","slice","workflowCountEpoch","setWorkflowCountEpoch","serverWorkflowCount","setServerWorkflowCount","active","then","snapshot","count","catch","workflowCount","length","functions","definition","$id","functionOptions","id","variables","variable","usage","setUsage","usageLoading","setUsageLoading","testResult","setTestResult","setRunsFor","nameTaken","Boolean","some","toLowerCase","trim","patch","updater","previous","draftId","draftName","editorTarget","type","handleAdd","persist","quota","allowed","limit","steps","functionName","args","resultName","returnValue","trigger","shortLists","stepProblem","handleTestRun","run","ok","error","Object","entries","results","key","join","handleSave","fields","verdict","subject","unreadable","updatedAt","now","merge","message","resource","epoch","console","allowDuplicate","handleShowUsage","result","kind","total","handleDelete","scan","confirmed","title","description","confirmationText","confirmationButtonProps","color","header","help","anchor","contentGutterX","contentGutterY","dialog","spacing","direction","sx","alignItems","flex","minWidth","noWrap","event","step","size","disabled","onClick","request","rowCount","onPageChange","onPageSizeChange","severity","alignSelf","ready","used","noun","open","onClose","maxWidth","fullWidth","display","flexDirection","gap","pt","slot","orgId","target","helperText","onChange","autoFocus","mt","index","call","functionId","kinds","stepForKind","onSteps","update","flexWrap","s","index2","find","option","select","placeholder","replace","width","parameters","parameter","parameterIndex","undefined","eventType","startsWith","targetId","targetType","targetName","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,SAEEA,gBAAgB,EAChBC,UAAU,EACVC,gBAAgB,EAChBC,cAAc,EACdC,oBAAoB,EAMpBC,cAAc,EACdC,WAAW,EACXC,kBAAkB,QACb,eAAc;AACrB;;;;;CAKC,GACD,SACEC,eAAe,EACfC,iBAAiB,QACZ,+DAA8D;AACrE,SAASC,oBAAoB,QAAQ,qDAAoD;AAEzF,SAASC,WAAW,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC1E,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,uBAAuB,QAAQ,8CAA6C;AACrF,OAAOC,2BAA2B,0DAAyD;AAC3F,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,SAAS,QAAQ,+BAA8B;AACxD,SACEC,KAAK,EACLC,MAAM,EACNC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe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B,UAAU,EAACzJ,yBAAAA,MAAOW,IAAI,CAACuE,IAAI,OAAMJ;gCACjC4E,SAAS1C;0CAER;;;;;;YAINjG,8BACC,KAACA;gBACC6J,MAAMtL,oBAAoB8E,EAAE;gBAC5BnE,QAAQA;gBACRsE,OAAOA;gBACP8F,SAAS,IAAM7F,SAAS;iBAExB;0BACJ,MAACtH;gBACCkN,MAAMrF,QAAQhF;gBACdsK,SAAS,IAAMxF,WAAW;gBAC1ByF,UAAS;gBACTC,SAAS;;kCAET,KAAClN;kCAAa,CAAC,OAAO,WAAE0C,2BAAAA,QAASY,IAAI,oBAAI,IAAI;;kCAC7C,KAACvD;kCACE2C,wBACC,KAACf;4BACCiB,QAAQA;4BACR4K,KAAK,EAAE/J,uBAAAA,IAAKoD,GAAG;4BACfuI,UAAU1M,QAAQmE,GAAG;4BACrBwI,YAAW;4BACXC,UAAU,GAAE5M,gBAAAA,QAAQY,IAAI,YAAZZ,gBAAgB;4BAC5B0I,QAAO;6BAEP;;kCAEN,KAACtL;kCACC,cAAA,KAACF;4BAAOuL,OAAM;4BAAUkB,SAAS,IAAM7E,WAAW;sCAC/C;;;;;;;AAMb;AACAhF,kBAAkB+M,WAAW,GAAG;AAEhC,eAAe/M,kBAAiB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/components/host-workflows-card.component.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 {\n type AglynOrgBilling,\n checkEntitlement,\n checkQuota,\n HOST_EVENT_TYPES,\n hostEventLabel,\n hostEventPayloadHint,\n type HostActionStep,\n type HostActionStepType,\n type HostFunction,\n type HostVariable,\n type HostWorkflowStep,\n pluginDocsHelp,\n runWorkflow,\n WORKFLOW_MAX_STEPS,\n} from '@aglyn/aglyn'\n/*\n * The MODULE, not the barrel, for the two PURE helpers — every spec that\n * renders this card mocks `@aglyn/tenant-feature-instance` wholesale to stage\n * its Firestore hooks, and a query builder imported through that barrel\n * disappears under the mock. Neither of these is a hook.\n */\nimport {\n ceilingedWindow,\n collectionCeiling,\n} from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { useConsoleWidgetSlot } from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport type { ConsoleAutomationTarget } from '@aglyn/aglyn/plugin-manager/feature-plugins'\nimport { CardDisplay, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport QuotaReadoutComponent from '@aglyn/shared-ui-jsx/components/quota-readout.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n doc,\n getCountFromServer,\n setDoc,\n updateDoc,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport {\n useDuplicateResource,\n useFirestore,\n useFirestoreCollection,\n useHostResourceApi,\n useUser,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport {\n AutomationStepFields,\n type AutomationStepKind,\n defaultStep,\n} from './automation-step-fields.component'\nimport {\n type AutomationWorkflow,\n isWorkflowActionStep,\n validateWorkflowSteps,\n WORKFLOW_ACTION_STEP_TYPES,\n workflowFunctionCalls,\n type WorkflowStep,\n workflowStepTypeLabel,\n} from '../engine/workflow-steps'\nimport HostRunHistoryCard from './host-run-history-card.component'\nimport {\n EDITOR_OPTION_CEILING,\n useAutomationStepPickers,\n} from './use-automation-step-pickers'\nimport { listConsoleWidgets } from '@aglyn/aglyn'\nimport {\n fetchWhereUsed,\n summarizeDependents,\n type WhereUsedResult,\n} from '@aglyn/aglyn/app-utils/where-used'\nimport { WORKFLOW_USAGE_ZONE } from './workflow-zones'\n\n/**\n * How many workflows the card reads.\n *\n * A CEILING, not a page size — see the query, which explains why this list\n * cannot be paged by the server without making the duplicate-name check lie.\n */\nconst WORKFLOW_CEILING = 100\n\n/** The \"Do\" entry for the step kind a workflow has always had: a call. */\nconst FUNCTION_CALL_KIND = 'functionCall'\n\n/**\n * What a step may be (AGL-3105).\n *\n * The function call comes first because it is what a workflow was before the\n * two engines became one, and is still what a new step is. After it comes\n * every Actions step a SERVER event can run — the client-only interactions\n * are absent, because a workflow runs where there is no page to run them on.\n */\nconst STEP_KINDS: AutomationStepKind[] = [\n { value: FUNCTION_CALL_KIND, label: 'Call a function' },\n ...WORKFLOW_ACTION_STEP_TYPES.map((value) => ({\n value,\n label: workflowStepTypeLabel(value),\n })),\n]\n\nexport interface HostWorkflowsCardProps {\n hostId: string\n /** Resolved entitlement source for quota checks (AGL-395). */\n org?: Partial<AglynOrgBilling>\n}\n\ninterface WorkflowDraft extends AutomationWorkflow {\n id: string | null\n}\n\n/**\n * Workflow builder v1 (AGL-101): pipelines of host-function calls — each\n * step's argument expressions see host variables and previous step results\n * (`step1`, or a custom result name). Runs through the pure `runWorkflow`\n * evaluator; test-run panel included. Plan-gated (`workflows` flag +\n * `workflowsPerHost` cap, AGL-99); site-event triggers are v2.\n */\nexport function HostWorkflowsCard(props: HostWorkflowsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const createHostResource = useHostResourceApi()\n const { enqueueSnackbar } = useSnackbar()\n // Duplicate (AGL-2936): the copy keeps every step and arrives disarmed —\n // its trigger is cleared — so nothing runs twice until somebody arms it.\n const duplicate = useDuplicateResource({\n hostId,\n onDuplicated: (_kind, copy) =>\n enqueueSnackbar(\n `Duplicated as “${copy.name}” — arm its trigger to run it`,\n {\n variant: 'success',\n },\n ),\n })\n const { confirm } = useConfirmationContext()\n const { org } = props\n /**\n * The shell's zone renderer, for what other plugins add to a saved workflow's\n * editor (AGL-2919); `null` outside the console shell.\n */\n const ExtensionZone = useConsoleWidgetSlot()\n\n const {\n data: workflowDocs,\n status: workflowsStatus,\n /**\n * The rows this editor is seeded from are unconfirmed by the server\n * (AGL-1358). Editing destructures a whole stored workflow into `draft`\n * and writes `{...definition}` back, so `merge: true` protects nothing.\n * `trigger` is the field that makes this more than a lost edit: it is\n * `{event, filter}` or `null` for manual-only, and nothing else on this\n * card writes it, so a cached seed can re-arm an automation the author\n * disarmed — or disarm one running on a live site — and revert every\n * step of the pipeline with it.\n */\n fromCache: workflowsFromCache,\n } = useFirestoreCollection<any>(\n /*\n * ORDERED AND CEILINGED, deliberately not paged by the query (AGL-2501) —\n * the same decision as the logic plugin's two cards, for the same reasons.\n *\n * `limit(100)` alone is answered in DOCUMENT-ID order, so the window is a\n * pseudo-random hundred that the `localeCompare` below arranges\n * alphabetically, and nothing said the list was bounded.\n *\n * `collectionCeiling` does not change WHICH hundred — document-id order is\n * what the bare cap already returned. What it changes is that the order is\n * NAMED, so the obvious next edit is caught: ordering on `name` would HIDE\n * every workflow written without one rather than mis-sorting the list, and\n * `/api/hosts/resources` validates no field for presence while\n * `IMPORTABLE_FIELDS.workflows` copies one only if the export carried it.\n *\n * The QUERY is not paged because `nameTaken` below tests the draft against\n * these rows: computed variables look their workflow up BY NAME\n * (AGL-185/AGL-261), so a duplicate silently rebinds a live binding, and a\n * uniqueness check over a ten-row page would let one through.\n */\n () =>\n collectionCeiling(\n collection(firestore, 'hosts', hostId, 'workflows'),\n WORKFLOW_CEILING,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { rows: readWorkflows, truncated: workflowsTruncated } =\n ceilingedWindow<any>(workflowDocs, WORKFLOW_CEILING)\n const [draft, setDraft] = useState<WorkflowDraft | null>(null)\n /**\n * The editor has been opened at least once in this session.\n *\n * A LATCH rather than `draft` itself, because the two reads below key their\n * listeners on it. Tracking the dialog would tear those subscriptions down\n * on Cancel and pay for them again on the next Edit, so a merchant working\n * through ten actions would buy the same two windows ten times — worse than\n * the mount-time read this replaces. Latched, a reader who never edits pays\n * nothing and a reader who edits pays once.\n */\n const [editorOpened, setEditorOpened] = useState(false)\n if (draft && !editorOpened) setEditorOpened(true)\n /*\n * THE EDITOR'S WORKING SET, read when the editor opens.\n *\n * Nothing outside the dialog reads either of these: the table renders a\n * workflow's stored step names, and `runWorkflow` is only reachable from the\n * test-run button inside the dialog. Mounting them unconditionally charges\n * every visitor to this page two windows to fill a select and seed a\n * scratchpad most of them never open.\n *\n * Ceilinged and ordered for the reason the workflows query above gives: a\n * bare `limit` is answered in document-id order, so the `localeCompare` on\n * the options below would arrange a pseudo-random hundred into a convincing\n * alphabet, and a function past the window could not be picked with nothing\n * saying why.\n */\n const { data: functionRead } = useFirestoreCollection<any>(\n () =>\n editorOpened\n ? collectionCeiling(\n collection(firestore, 'hosts', hostId, 'functions'),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, hostId, editorOpened],\n { idField: '$id' },\n )\n // Memoised so the window keeps one identity while the rows do — the option\n // list and the two lookup maps below are all built from it.\n const { rows: functionDocs, truncated: functionsTruncated } = useMemo(\n () => ceilingedWindow<any>(functionRead, EDITOR_OPTION_CEILING),\n [functionRead],\n )\n const { data: variableRead } = useFirestoreCollection<any>(\n () =>\n editorOpened\n ? collectionCeiling(\n collection(firestore, 'hosts', hostId, 'variables'),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, hostId, editorOpened],\n { idField: '$id' },\n )\n const { rows: variableDocs, truncated: variablesTruncated } = useMemo(\n () => ceilingedWindow<any>(variableRead, EDITOR_OPTION_CEILING),\n [variableRead],\n )\n /*\n * What an ACTIONS step can be pointed at, on the same latch (AGL-3105).\n *\n * The hook the Actions builder uses, because a workflow step may be any\n * server-side Actions step and the two editors therefore offer one set of\n * records. Read on the editor's first open, like the two windows above, so\n * a reader who never edits a workflow still pays nothing for them.\n */\n const { pickers: stepPickers, truncated: truncatedPickers } =\n useAutomationStepPickers(hostId, editorOpened)\n // Sorting is safe here in a way it is not on a paged list: these rows are\n // the whole collection below the ceiling, not a slice of one.\n const workflows = useMemo(\n () =>\n readWorkflows\n .filter((workflow: any) => !workflow.deletedAt)\n .sort((a: any, b: any) =>\n String(a.name ?? '').localeCompare(String(b.name ?? '')),\n ),\n [readWorkflows],\n )\n // The page is a SLICE: the rows are already in hand and `nameTaken` needs\n // all of them.\n const [page, setPage] = useState(0)\n const [pageSize, setPageSize] = useState(TABLE_PAGE_SIZE_DEFAULT)\n const visibleWorkflows = useMemo(\n () => workflows.slice(page * pageSize, page * pageSize + pageSize),\n [workflows, page, pageSize],\n )\n /**\n * The workflow HEAD-COUNT is a server aggregate, not the length of the\n * capped listener (AGL-1716, the AGL-1706 shape).\n *\n * The listener is `limit(100)` and `workflows.length` fed\n * `checkQuota(org, 'workflowsPerHost', …)`, whose bands are 0 / 3 / 25 /\n * 100 / 250 / 500. The window TIES Business's 100 and hides Scale's 250\n * and Advanced's 500, so on those plans the gate compared 100 against\n * hundreds and could never refuse — while `api/hosts/resources` counted\n * the collection and did. The card offered headroom that did not exist and\n * then failed the create.\n *\n * UNFILTERED, matching that route's plain `collection('workflows').count()`\n * — its `softDeletes` branch governs only the flat per-host webhook cap, so\n * soft-deleted workflows have always counted server-side while this card\n * excluded them. Only a create moves the number, so that is where it is\n * re-read.\n */\n const [workflowCountEpoch, setWorkflowCountEpoch] = useState(0)\n const [serverWorkflowCount, setServerWorkflowCount] = useState<number | null>(\n null,\n )\n useEffect(() => {\n let active = true\n void getCountFromServer(collection(firestore, 'hosts', hostId, 'workflows'))\n .then((snapshot) => {\n if (active) setServerWorkflowCount(snapshot.data().count)\n })\n .catch(() => {\n // Falls back to the loaded rows — a LOWER bound and the prior\n // behaviour, never 0, which `checkQuota` would answer as \"no usage\"\n // on a site that is over its band.\n })\n return () => {\n active = false\n }\n }, [firestore, hostId, workflowCountEpoch])\n const workflowCount = serverWorkflowCount ?? workflows.length\n // Double-keyed by doc id and name (AGL-261): id references are\n // rename-safe; legacy name references keep resolving.\n const functions = useMemo(() => {\n const map: Record<string, HostFunction> = {}\n for (const definition of functionDocs ?? []) {\n if (definition.deletedAt) continue\n if (definition.$id) map[definition.$id] = definition\n if (definition.name) map[definition.name] = definition\n }\n return map\n }, [functionDocs])\n const functionOptions = useMemo(\n () =>\n (functionDocs ?? [])\n .filter((definition: any) => !definition.deletedAt && definition.name)\n .map((definition: any) => ({\n id: definition.$id as string,\n name: definition.name as string,\n }))\n .sort((a, b) => a.name.localeCompare(b.name)),\n [functionDocs],\n )\n const variables = useMemo(() => {\n const map: Record<string, HostVariable> = {}\n for (const variable of variableDocs ?? []) {\n if (!variable.deletedAt && variable.name) map[variable.name] = variable\n }\n return map\n }, [variableDocs])\n\n // Where-used dialog (AGL-193).\n const [usage, setUsage] = useState<{\n name: string\n result: WhereUsedResult\n } | null>(null)\n const [usageLoading, setUsageLoading] = useState<string | null>(null)\n\n const [testResult, setTestResult] = useState<string | null>(null)\n const [runsFor, setRunsFor] = useState<any | null>(null)\n\n // Case-insensitive uniqueness (AGL-185): workflow names must stay\n // unambiguous for computed-variable lookups keyed by name.\n const nameTaken = Boolean(\n draft &&\n workflows.some(\n (definition: any) =>\n String(definition.name ?? '').toLowerCase() ===\n draft.name.trim().toLowerCase() && definition.$id !== draft.id,\n ),\n )\n\n const patch = useCallback(\n (updater: (previous: WorkflowDraft) => WorkflowDraft) =>\n setDraft((previous) => (previous ? updater(previous) : previous)),\n [],\n )\n\n /** The saved workflow the editor has open, as the `automationEditor` zone names it. */\n const draftId = draft?.id ?? null\n const draftName = draft?.name ?? ''\n const editorTarget = useMemo<ConsoleAutomationTarget | null>(\n () => (draftId ? { type: 'workflow', id: draftId, name: draftName } : null),\n // The name the editor opened with: the zone reads the workflow as it is\n // stored, so a rename being typed does not make it a different one.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [draftId],\n )\n\n const handleAdd = useCallback(() => {\n // Feature + cap gate (AGL-99); dark-launch for plan-less workspaces.\n if (!checkEntitlement(org, 'workflows')) {\n return void enqueueSnackbar(\n 'Workflows require a Starter plan — see Billing to upgrade',\n { variant: 'warning', persist: false },\n )\n }\n // The site's workflows, not this page of them (AGL-1716).\n const quota = checkQuota(org, 'workflowsPerHost', workflowCount)\n if (!quota.allowed) {\n return void enqueueSnackbar(\n `Workflow limit reached (${quota.limit}) — upgrade in Billing`,\n { variant: 'warning', persist: false },\n )\n }\n setTestResult(null)\n setDraft({\n id: null,\n name: '',\n steps: [{ functionName: '', args: [], resultName: '' }],\n returnValue: '',\n trigger: null,\n })\n }, [org, workflowCount, enqueueSnackbar])\n\n /**\n * Every list the ceiling cut, named — the editor's two and the step\n * pickers' six, in one notice for the reason the Actions builder gives:\n * they are one read, and an author told the function list is short learns\n * nothing from being told again about datasets.\n */\n const shortLists = useMemo(\n () =>\n [\n functionsTruncated ? 'functions' : null,\n variablesTruncated ? 'variables' : null,\n ...truncatedPickers,\n ].filter((name): name is string => name !== null),\n [functionsTruncated, variablesTruncated, truncatedPickers],\n )\n\n /**\n * The first thing wrong with the steps, said the way the editors say it.\n *\n * The same check the engine makes of what it is handed: an Actions step is\n * held to the Actions validator, a call has to name a function, and a step\n * only a visitor's browser can run is refused. Said while the author is\n * still in the dialog rather than after a save that stores a step nothing\n * can run.\n */\n const stepProblem = useMemo(\n () => (draft ? validateWorkflowSteps(draft.steps) : null),\n [draft],\n )\n\n const handleTestRun = useCallback(() => {\n if (!draft) return\n /*\n * The FUNCTION CALLS, evaluated. A test run is the pure evaluator, and\n * an Actions step is not something to evaluate — it sends, writes and\n * charges. Running one here would perform it against the live site from\n * a button labelled \"Test run\", so the calls are evaluated, each keeping\n * the result name it holds among all the steps, and the rest is left to\n * the run itself.\n */\n const run = runWorkflow(workflowFunctionCalls(draft), functions, variables)\n setTestResult(\n run.ok === false\n ? `Error: ${run.error}`\n : `Result: ${String(run.value)} (${Object.entries(run.results)\n .map(([key, value]) => `${key}=${value}`)\n .join(', ')})`,\n )\n }, [draft, functions, variables])\n\n const handleSave = useCallback(async () => {\n if (!draft || !draft.name.trim() || nameTaken) return\n // The steps are checked at the door, not after the write: a stored step\n // nothing can run is a run that fails on the site rather than here.\n if (stepProblem) {\n return void enqueueSnackbar(stepProblem, {\n variant: 'warning',\n persist: false,\n })\n }\n const { id: draftId, ...definition } = draft\n const fields = { ...definition, name: draft.name.trim().slice(0, 60) }\n try {\n if (draftId) {\n /**\n * Edit stays client-direct (no quota consumed) — and is refused when\n * its seed was never confirmed by the server (AGL-1358). `fields` is\n * the whole definition spread out of the listener row, `trigger` and\n * `steps` included, so `merge: true` has nothing left to protect.\n *\n * The guard WRAPS the write. An early return is a shape you can keep\n * while losing the protection; here the write is only reachable\n * through the verdict.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'workflow',\n unreadable: workflowsStatus === 'error',\n fromCache: workflowsFromCache,\n },\n async () => {\n await setDoc(\n doc(firestore, 'hosts', hostId, 'workflows', draftId),\n { ...fields, updatedAt: Timestamp.now() },\n { merge: true },\n )\n },\n )\n // Before `setDraft(null)`, so a refusal keeps the dialog open with\n // every step that was built and its test run still on screen.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n } else {\n // New workflow rides the quota-enforcing resources API (AGL-473) —\n // it also re-checks the `workflows` entitlement server-side.\n await createHostResource({ hostId, resource: 'workflow', data: fields })\n // A create moves the count; the one-shot aggregate below does not\n // refresh itself the way the listener refreshes the rows.\n setWorkflowCountEpoch((epoch) => epoch + 1)\n }\n setDraft(null)\n enqueueSnackbar('Workflow saved', { variant: 'success', persist: false })\n } catch (error: any) {\n console.error(error)\n enqueueSnackbar(error?.message ?? 'An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n }, [\n draft,\n nameTaken,\n stepProblem,\n firestore,\n hostId,\n createHostResource,\n enqueueSnackbar,\n workflowsStatus,\n workflowsFromCache,\n ])\n\n const handleShowUsage = useCallback(\n (workflow: any) => async () => {\n setUsageLoading(workflow.$id)\n const result = await fetchWhereUsed(user as any, {\n hostId,\n kind: 'workflow',\n id: workflow.$id,\n name: workflow.name,\n })\n setUsageLoading(null)\n // The rows and their deep links are drawn in a zone; with nothing\n // registered there the answer is still given, in words.\n if (listConsoleWidgets(WORKFLOW_USAGE_ZONE.id).length === 0) {\n enqueueSnackbar(\n result.total\n ? `\"${workflow.name}\" computes ${summarizeDependents(result)}`\n : `\"${workflow.name}\" is not referenced by anything published`,\n { variant: 'info', persist: false },\n )\n return\n }\n setUsage({ name: workflow.name, result })\n },\n [user, hostId, enqueueSnackbar],\n )\n\n const handleDelete = useCallback(\n (workflow: any) => async () => {\n // Dependents warning (AGL-187): computed variables backed by this\n // workflow keep their stored fallback value once it is gone.\n const scan = await fetchWhereUsed(user as any, {\n hostId,\n kind: 'workflow',\n id: workflow.$id,\n name: workflow.name,\n })\n const confirmed = await confirm({\n title: 'Delete this workflow?',\n description: scan.total\n ? `\"${workflow.name}\" computes ${summarizeDependents(scan)} — ` +\n 'those variables will fall back to their stored values.'\n : `\"${workflow.name}\" will no longer be runnable.`,\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await updateDoc(\n doc(firestore, 'hosts', hostId, 'workflows', workflow.$id),\n { deletedAt: Timestamp.now() },\n )\n enqueueSnackbar('Workflow deleted', {\n variant: 'success',\n persist: false,\n })\n },\n [user, confirm, firestore, hostId, enqueueSnackbar],\n )\n\n return (\n <CardDisplay\n header={'Workflows'}\n help={pluginDocsHelp('buildAWorkflow', {\n anchor: '#1-open-the-workflows-page',\n })}\n contentGutterX\n contentGutterY\n >\n {duplicate.dialog}\n <Stack spacing={1}>\n {workflows.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Chain your functions into multi-step pipelines — each step ' +\n 'feeds the next. Site-event triggers are coming next.'}\n </Typography>\n ) : (\n visibleWorkflows.map((workflow: any) => (\n <Stack\n key={workflow.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {workflow.name}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {`${(workflow.steps ?? []).length} step${\n (workflow.steps ?? []).length === 1 ? '' : 's'\n }${\n workflow.trigger?.event\n ? ` · on ${hostEventLabel(workflow.trigger.event)}`\n : ''\n } · ${(workflow.steps ?? [])\n .map((step: any) => step.functionName)\n .join(' → ')}`}\n </Typography>\n </Stack>\n <Button\n size=\"small\"\n disabled={usageLoading === workflow.$id}\n onClick={handleShowUsage(workflow)}\n >\n {usageLoading === workflow.$id ? 'Scanning…' : 'Usage'}\n </Button>\n {/* Run history (wave v6): the event runner logs status +\n duration per run. */}\n <Button size=\"small\" onClick={() => setRunsFor(workflow)}>\n {'Runs'}\n </Button>\n <Button\n size=\"small\"\n onClick={() => {\n setTestResult(null)\n setDraft({\n id: workflow.$id,\n name: workflow.name ?? '',\n steps: workflow.steps ?? [],\n returnValue: workflow.returnValue ?? '',\n trigger: workflow.trigger ?? null,\n })\n }}\n >\n {'Edit'}\n </Button>\n <Button\n size=\"small\"\n onClick={() =>\n duplicate.request('workflow', {\n id: workflow.$id,\n name: workflow.name ?? '',\n })\n }\n >\n {'Duplicate…'}\n </Button>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDelete(workflow)}\n >\n {'Delete'}\n </Button>\n </Stack>\n ))\n )}\n {workflows.length === 0 ? null : (\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={visibleWorkflows.length}\n // The workflows the card HOLDS. Not `workflowCount`, which is the\n // site's total including soft-deleted rows and answers the quota's\n // question rather than the reader's.\n count={workflows.length}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n )}\n {workflowsTruncated ? (\n <Alert severity=\"info\">\n {`Showing ${WORKFLOW_CEILING} workflows, ordered by id. This site ` +\n 'has more — the duplicate-name check below only covers the ' +\n 'ones listed here, so a name may already be taken by one that ' +\n 'is not.'}\n </Alert>\n ) : null}\n <Button\n size=\"small\"\n color=\"primary\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={handleAdd}\n >\n {'Add workflow'}\n </Button>\n {/* The cap, standing rather than only on refusal (AGL-2113).\n `workflowCount` is the server aggregate the gate uses, not\n `workflows.length` — the listener is `limit(100)` and its length\n saturates (AGL-1716). */}\n <QuotaReadoutComponent\n ready={org != null}\n used={workflowCount}\n limit={checkQuota(org, 'workflowsPerHost', workflowCount).limit}\n noun=\"workflow\"\n />\n </Stack>\n\n <Dialog\n open={Boolean(draft)}\n onClose={() => setDraft(null)}\n maxWidth=\"sm\"\n fullWidth\n >\n <DialogTitle>\n {draft?.id ? 'Edit Workflow' : 'Add Workflow'}\n </DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, pt: 1 }}\n >\n {ExtensionZone && editorTarget ? (\n <ExtensionZone\n slot=\"automationEditor\"\n hostId={hostId}\n orgId={org?.$id}\n target={editorTarget}\n />\n ) : null}\n <TextField\n label=\"Name\"\n helperText={\n nameTaken\n ? 'A workflow with this name already exists'\n : 'Used to identify the workflow'\n }\n error={nameTaken}\n value={draft?.name ?? ''}\n onChange={(event) =>\n patch((previous) => ({ ...previous, name: event.target.value }))\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n />\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Steps'}\n </Typography>\n {/*\n The pickers and the test run speak only for what was read. A step\n calling a function past the ceiling still RUNS on the site — this\n editor simply cannot name it, and a test run resolves its\n expression against an incomplete variable set.\n */}\n {shortLists.length > 0 ? (\n <Alert severity=\"info\">\n {`Offering the first ${EDITOR_OPTION_CEILING} ` +\n `${shortLists.join(', ')} on this site, ordered by id. ` +\n 'There are more, so the pickers below are short and a test ' +\n 'run may not resolve every expression.'}\n </Alert>\n ) : null}\n {(draft?.steps ?? []).map((step, index) => {\n const call = isWorkflowActionStep(step)\n ? null\n : (step as HostWorkflowStep)\n const definition = call\n ? (functions[(call as any).functionId ?? ''] ??\n functions[call.functionName])\n : null\n return (\n <AutomationStepFields\n key={index}\n /*\n * The editor speaks the Actions vocabulary. A function call\n * has no Actions type, so it takes none of those fields and\n * renders its own through `fields` instead — which is what\n * keeps this one editor rather than two.\n */\n step={step as HostActionStep}\n index={index}\n kind={call ? FUNCTION_CALL_KIND : (step as HostActionStep).type}\n kinds={STEP_KINDS}\n stepForKind={(value) =>\n (value === FUNCTION_CALL_KIND\n ? { functionName: '', args: [], resultName: '' }\n : defaultStep(\n value as HostActionStepType,\n )) as HostActionStep\n }\n pickers={stepPickers}\n onSteps={(update) =>\n patch((previous) => ({\n ...previous,\n steps: update(\n previous.steps as HostActionStep[],\n ) as WorkflowStep[],\n }))\n }\n fields={\n call ? (\n <Stack\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center', flex: 1, flexWrap: 'wrap' }}\n >\n <TextField\n label=\"Function\"\n // Stored by id (AGL-261); legacy steps carry only the\n // name and resolve through the double-keyed map.\n value={\n (call as any).functionId ??\n (functions[call.functionName] as any)?.$id ??\n ''\n }\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n steps: previous.steps.map((s, index2) =>\n index2 === index\n ? {\n ...s,\n functionId: event.target.value,\n functionName:\n functionOptions.find(\n (option) =>\n option.id === event.target.value,\n )?.name ??\n (s as HostWorkflowStep).functionName,\n }\n : s,\n ),\n }))\n }\n size=\"small\"\n select\n sx={{ minWidth: 160, flex: 1 }}\n >\n {functionOptions.map((option) => (\n <MenuItem key={option.id} value={option.id}>\n {option.name}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n label=\"Result name\"\n placeholder={`step${index + 1}`}\n value={call.resultName ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n steps: previous.steps.map((s, index2) =>\n index2 === index\n ? {\n ...s,\n resultName: event.target.value.replace(\n /[^a-zA-Z0-9_]/g,\n '',\n ),\n }\n : s,\n ),\n }))\n }\n size=\"small\"\n sx={{ width: 140 }}\n />\n {(definition?.parameters ?? []).map(\n (parameter, parameterIndex) => (\n <TextField\n key={parameter.name}\n label={`${parameter.name} expression`}\n placeholder={\n parameterIndex === 0 && index > 0\n ? `step${index}`\n : 'a variable, number, or expression'\n }\n value={call.args?.[parameterIndex] ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n steps: previous.steps.map((s, index2) => {\n if (index2 !== index) return s\n const args = [\n ...((s as HostWorkflowStep).args ?? []),\n ]\n args[parameterIndex] = event.target.value\n return { ...s, args }\n }),\n }))\n }\n size=\"small\"\n sx={{ minWidth: 180, flex: 1 }}\n />\n ),\n )}\n </Stack>\n ) : undefined\n }\n />\n )\n })}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n disabled={(draft?.steps.length ?? 0) >= WORKFLOW_MAX_STEPS}\n onClick={() =>\n patch((previous) => ({\n ...previous,\n steps: [\n ...previous.steps,\n { functionName: '', args: [], resultName: '' },\n ],\n }))\n }\n >\n {'Add step'}\n </Button>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Trigger'}\n </Typography>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Run on event\"\n value={draft?.trigger?.event ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: event.target.value\n ? {\n event: event.target.value as any,\n filter: previous.trigger?.filter ?? '',\n }\n : null,\n }))\n }\n size=\"small\"\n select\n sx={{ minWidth: 180 }}\n >\n <MenuItem value=\"\">{'Manual only'}</MenuItem>\n {HOST_EVENT_TYPES.map((eventType) => (\n <MenuItem key={eventType} value={eventType}>\n {hostEventLabel(eventType)}\n </MenuItem>\n ))}\n </TextField>\n {draft?.trigger ? (\n <TextField\n label=\"Filter (optional)\"\n placeholder={'path == \"/pricing\"'}\n helperText={[\n 'Runs only when this expression is truthy.',\n hostEventPayloadHint(draft?.trigger?.event),\n ]\n .filter(Boolean)\n .join(' ')}\n value={draft?.trigger?.filter ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: previous.trigger\n ? { ...previous.trigger, filter: event.target.value }\n : previous.trigger,\n }))\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n ) : null}\n </Stack>\n <TextField\n label=\"Return value\"\n helperText=\"A step result name; defaults to the last step\"\n value={draft?.returnValue ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n returnValue: event.target.value,\n }))\n }\n size=\"small\"\n />\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Button size=\"small\" color=\"primary\" onClick={handleTestRun}>\n {'Test run'}\n </Button>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Uses current variable values'}\n </Typography>\n </Stack>\n {testResult ? (\n <Alert\n severity={testResult.startsWith('Error') ? 'warning' : 'success'}\n >\n {testResult}\n </Alert>\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!draft?.name.trim() || nameTaken}\n onClick={handleSave}\n >\n {'Done'}\n </Button>\n </DialogActions>\n </Dialog>\n {ExtensionZone ? (\n <ExtensionZone\n slot={WORKFLOW_USAGE_ZONE.id}\n hostId={hostId}\n usage={usage}\n onClose={() => setUsage(null)}\n />\n ) : null}\n <Dialog\n open={Boolean(runsFor)}\n onClose={() => setRunsFor(null)}\n // md: the history's four columns fit without the table scrolling.\n maxWidth=\"md\"\n fullWidth\n >\n <DialogTitle>{`Runs — ${runsFor?.name ?? ''}`}</DialogTitle>\n <DialogContent>\n {runsFor ? (\n <HostRunHistoryCard\n hostId={hostId}\n orgId={org?.$id}\n targetId={runsFor.$id}\n targetType=\"workflow\"\n targetName={runsFor.name ?? ''}\n header=\"Recent runs\"\n />\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button color=\"inherit\" onClick={() => setRunsFor(null)}>\n {'Close'}\n </Button>\n </DialogActions>\n </Dialog>\n </CardDisplay>\n )\n}\nHostWorkflowsCard.displayName = 'HostWorkflowsCard'\n\nexport default HostWorkflowsCard\n"],"names":["checkEntitlement","checkQuota","HOST_EVENT_TYPES","hostEventLabel","hostEventPayloadHint","pluginDocsHelp","runWorkflow","WORKFLOW_MAX_STEPS","ceilingedWindow","collectionCeiling","useConsoleWidgetSlot","CardDisplay","useConfirmationContext","ListPagination","TABLE_PAGE_SIZE_DEFAULT","QuotaReadoutComponent","useSnackbar","Timestamp","Alert","Button","Dialog","DialogActions","DialogContent","DialogTitle","MenuItem","Stack","TextField","Typography","collection","doc","getCountFromServer","setDoc","updateDoc","useCallback","useEffect","useMemo","useState","useDuplicateResource","useFirestore","useFirestoreCollection","useHostResourceApi","useUser","writeGuardedBySeed","AutomationStepFields","defaultStep","isWorkflowActionStep","validateWorkflowSteps","WORKFLOW_ACTION_STEP_TYPES","workflowFunctionCalls","workflowStepTypeLabel","HostRunHistoryCard","EDITOR_OPTION_CEILING","useAutomationStepPickers","listConsoleWidgets","fetchWhereUsed","summarizeDependents","WORKFLOW_USAGE_ZONE","WORKFLOW_CEILING","FUNCTION_CALL_KIND","STEP_KINDS","value","label","map","HostWorkflowsCard","props","runsFor","draft","hostId","firestore","data","user","createHostResource","enqueueSnackbar","duplicate","onDuplicated","_kind","copy","name","variant","confirm","org","ExtensionZone","workflowDocs","status","workflowsStatus","fromCache","workflowsFromCache","idField","rows","readWorkflows","truncated","workflowsTruncated","setDraft","editorOpened","setEditorOpened","functionRead","functionDocs","functionsTruncated","variableRead","variableDocs","variablesTruncated","pickers","stepPickers","truncatedPickers","workflows","filter","workflow","deletedAt","sort","a","b","String","localeCompare","page","setPage","pageSize","setPageSize","visibleWorkflows","slice","workflowCountEpoch","setWorkflowCountEpoch","serverWorkflowCount","setServerWorkflowCount","active","then","snapshot","count","catch","workflowCount","length","functions","definition","$id","functionOptions","id","variables","variable","usage","setUsage","usageLoading","setUsageLoading","testResult","setTestResult","setRunsFor","nameTaken","Boolean","some","toLowerCase","trim","patch","updater","previous","draftId","draftName","editorTarget","type","handleAdd","persist","quota","allowed","limit","steps","functionName","args","resultName","returnValue","trigger","shortLists","stepProblem","handleTestRun","run","ok","error","Object","entries","results","key","join","handleSave","fields","verdict","subject","unreadable","updatedAt","now","merge","message","resource","epoch","console","allowDuplicate","handleShowUsage","result","kind","total","handleDelete","scan","confirmed","title","description","confirmationText","confirmationButtonProps","color","header","help","anchor","contentGutterX","contentGutterY","dialog","spacing","direction","sx","alignItems","flex","minWidth","noWrap","event","step","size","disabled","onClick","request","rowCount","onPageChange","onPageSizeChange","severity","alignSelf","ready","used","noun","open","onClose","maxWidth","fullWidth","display","flexDirection","gap","pt","slot","orgId","target","helperText","onChange","autoFocus","mt","index","call","functionId","kinds","stepForKind","onSteps","update","flexWrap","s","index2","find","option","select","placeholder","replace","width","parameters","parameter","parameterIndex","undefined","eventType","startsWith","targetId","targetType","targetName","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,SAEEA,gBAAgB,EAChBC,UAAU,EACVC,gBAAgB,EAChBC,cAAc,EACdC,oBAAoB,EAMpBC,cAAc,EACdC,WAAW,EACXC,kBAAkB,QACb,eAAc;AACrB;;;;;CAKC,GACD,SACEC,eAAe,EACfC,iBAAiB,QACZ,+DAA8D;AACrE,SAASC,oBAAoB,QAAQ,qDAAoD;AAEzF,SAASC,WAAW,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC1E,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,uBAAuB,QAAQ,8CAA6C;AACrF,OAAOC,2BAA2B,0DAAyD;AAC3F,SAASC,WAAW,QAAQ,8BAA6B;AACz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AAW6H,UAAU,CAAC,WAAW,YAAY;0CAEtD7H;iCAED;;;kCAEN,MAACxH;;0CACC,KAACF;gCAAOyM,SAAS,IAAMhI,SAAS;0CAAQ;;0CACxC,KAACzE;gCACC2D,SAAQ;gCACR4H,OAAM;gCACNiB,UAAU,EAACzJ,yBAAAA,MAAOW,IAAI,CAACuE,IAAI,OAAMJ;gCACjC4E,SAAS1C;0CAER;;;;;;YAINjG,8BACC,KAACA;gBACC6J,MAAMtL,oBAAoB8E,EAAE;gBAC5BnE,QAAQA;gBACRsE,OAAOA;gBACP8F,SAAS,IAAM7F,SAAS;iBAExB;0BACJ,MAACtH;gBACCkN,MAAMrF,QAAQhF;gBACdsK,SAAS,IAAMxF,WAAW;gBAC1B,kEAAkE;gBAClEyF,UAAS;gBACTC,SAAS;;kCAET,KAAClN;kCAAa,CAAC,OAAO,WAAE0C,2BAAAA,QAASY,IAAI,oBAAI,IAAI;;kCAC7C,KAACvD;kCACE2C,wBACC,KAACf;4BACCiB,QAAQA;4BACR4K,KAAK,EAAE/J,uBAAAA,IAAKoD,GAAG;4BACfuI,UAAU1M,QAAQmE,GAAG;4BACrBwI,YAAW;4BACXC,UAAU,GAAE5M,gBAAAA,QAAQY,IAAI,YAAZZ,gBAAgB;4BAC5B0I,QAAO;6BAEP;;kCAEN,KAACtL;kCACC,cAAA,KAACF;4BAAOuL,OAAM;4BAAUkB,SAAS,IAAM7E,WAAW;sCAC/C;;;;;;;AAMb;AACAhF,kBAAkB+M,WAAW,GAAG;AAEhC,eAAe/M,kBAAiB"}
|
|
@@ -169,7 +169,8 @@ import { useOrgAutomationsApi } from "./use-org-automations-api.js";
|
|
|
169
169
|
/*#__PURE__*/ _jsxs(Dialog, {
|
|
170
170
|
open: Boolean(runsFor),
|
|
171
171
|
onClose: ()=>setRunsFor(null),
|
|
172
|
-
|
|
172
|
+
// md: the history's four columns fit without the table scrolling.
|
|
173
|
+
maxWidth: "md",
|
|
173
174
|
fullWidth: true,
|
|
174
175
|
children: [
|
|
175
176
|
/*#__PURE__*/ _jsx(DialogTitle, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/components/site-org-automations-panel.component.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 {\n HOST_ACTION_STEP_LABELS,\n type HostActionStepType,\n hostEventLabel,\n pluginDocsHelp,\n scopeTokensForHost,\n} from '@aglyn/aglyn'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n useFirestoreCollection,\n useOrgDataScope,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Stack,\n Typography,\n} from '@mui/material'\nimport { collection, limit, query, where } from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport {\n ORG_AUTOMATIONS_COLLECTION,\n ORG_AUTOMATIONS_MAX,\n orgAutomationPausedHostIds,\n type OrgAutomationRow,\n} from '../model/org-automations'\nimport HostRunHistoryCard from './host-run-history-card.component'\nimport { useOrgAutomationsApi } from './use-org-automations-api'\n\n/**\n * THE ORGANIZATION'S AUTOMATIONS THAT RUN ON THIS SITE (AGL-3302), on the\n * site's own Actions section: read-only, with the one control that belongs\n * to the site — pausing an automation here, and resuming it.\n *\n * Read with the site's own scope tokens, so the listener is provable for a\n * collaborator scoped to this site as well as for an org-wide member, and\n * only the live ones placed here come back. Editing is the organization's,\n * on its own hub; a pause is the site's, through `automations/pause`, which\n * admits the site's admins and editors and refuses anyone else with its own\n * words.\n *\n * Renders nothing while there is nothing: a site the organization runs no\n * automation on has no panel to explain.\n */\nexport function SiteOrgAutomationsPanel(props: { hostId: string }) {\n const { hostId } = props\n const firestore = useFirestore()\n const api = useOrgAutomationsApi()\n const { enqueueSnackbar } = useSnackbar()\n const { scope } = useOrgDataScope({ hostId })\n const tokens = useMemo(() => scopeTokensForHost(hostId), [hostId])\n const { data: rows } = useFirestoreCollection<OrgAutomationRow>(\n () =>\n scope\n ? query(\n collection(firestore, scope[0], scope[1], ORG_AUTOMATIONS_COLLECTION),\n where('deletedAt', '==', null),\n where('visibleTo', 'array-contains-any', tokens),\n limit(ORG_AUTOMATIONS_MAX + 1),\n )\n : null,\n [firestore, scope, tokens],\n { idField: '$id' },\n )\n const automations = useMemo(\n () =>\n [...(rows ?? [])].sort((a, b) =>\n String(a.name ?? '').localeCompare(String(b.name ?? '')),\n ),\n [rows],\n )\n const [busy, setBusy] = useState<string | null>(null)\n const [runsFor, setRunsFor] = useState<OrgAutomationRow | null>(null)\n\n const setPaused = useCallback(\n async (row: OrgAutomationRow, paused: boolean) => {\n setBusy(row.$id)\n try {\n await api('pause', { hostId, automationId: row.$id, paused })\n enqueueSnackbar(\n paused\n ? `“${row.name}” is paused on this site`\n : `“${row.name}” runs on this site again`,\n { variant: 'success', persist: false },\n )\n } catch (error) {\n enqueueSnackbar(\n (error as Error)?.message || 'The request could not be completed',\n { variant: 'warning', persist: false },\n )\n } finally {\n setBusy(null)\n }\n },\n [api, hostId, enqueueSnackbar],\n )\n\n if (!automations.length) return null\n return (\n <CardDisplay\n header={'Org automations on this site'}\n help={pluginDocsHelp('orgAutomations', { anchor: '#pause-it-on-one-site' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Your organization runs these on this site beside the site’s own ' +\n 'actions. Each run sends from this site and counts on its action ' +\n 'runs. Pausing one stops it here — and anyone waiting inside it ' +\n 'here — and leaves every other site alone.'}\n </Typography>\n {automations.map((row) => {\n const paused = orgAutomationPausedHostIds(row).includes(hostId)\n const off = row.enabled === false\n return (\n <Stack\n key={row.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {row.name}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {`on ${hostEventLabel(row.trigger?.event)} · ${(row.steps ?? [])\n .map(\n (step) =>\n HOST_ACTION_STEP_LABELS[step.type as HostActionStepType] ??\n step.type,\n )\n .join(' → ')}`}\n </Typography>\n </Stack>\n <Chip\n size=\"small\"\n variant=\"outlined\"\n color={off ? 'default' : paused ? 'warning' : 'success'}\n label={off ? 'Switched off' : paused ? 'Paused here' : 'Runs here'}\n />\n <Button\n size=\"small\"\n disabled={busy === row.$id}\n onClick={() => void setPaused(row, !paused)}\n >\n {paused ? 'Resume here' : 'Pause here'}\n </Button>\n <Button size=\"small\" onClick={() => setRunsFor(row)}>\n {'Runs'}\n </Button>\n </Stack>\n )\n })}\n </Stack>\n <Dialog\n open={Boolean(runsFor)}\n onClose={() => setRunsFor(null)}\n maxWidth=\"sm\"\n fullWidth\n >\n <DialogTitle>{`Runs — ${runsFor?.name ?? ''}`}</DialogTitle>\n <DialogContent>\n {runsFor ? (\n <HostRunHistoryCard\n hostId={hostId}\n targetId={runsFor.$id}\n targetName={runsFor.name ?? ''}\n header=\"Recent runs on this site\"\n />\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button color=\"inherit\" onClick={() => setRunsFor(null)}>\n {'Close'}\n </Button>\n </DialogActions>\n </Dialog>\n </CardDisplay>\n )\n}\nSiteOrgAutomationsPanel.displayName = 'SiteOrgAutomationsPanel'\n\nexport default SiteOrgAutomationsPanel\n"],"names":["HOST_ACTION_STEP_LABELS","hostEventLabel","pluginDocsHelp","scopeTokensForHost","CardDisplay","useSnackbar","useFirestore","useFirestoreCollection","useOrgDataScope","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","Stack","Typography","collection","limit","query","where","useCallback","useMemo","useState","ORG_AUTOMATIONS_COLLECTION","ORG_AUTOMATIONS_MAX","orgAutomationPausedHostIds","HostRunHistoryCard","useOrgAutomationsApi","SiteOrgAutomationsPanel","props","runsFor","hostId","firestore","api","enqueueSnackbar","scope","tokens","data","rows","idField","automations","sort","a","b","String","name","localeCompare","busy","setBusy","setRunsFor","setPaused","row","paused","$id","automationId","variant","persist","error","message","length","header","help","anchor","contentGutterX","contentGutterY","spacing","color","map","includes","off","enabled","direction","sx","alignItems","flex","minWidth","noWrap","trigger","event","steps","step","type","join","size","label","disabled","onClick","open","Boolean","onClose","maxWidth","fullWidth","targetId","targetName","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SACEA,uBAAuB,EAEvBC,cAAc,EACdC,cAAc,EACdC,kBAAkB,QACb,eAAc;AACrB,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,YAAY,EACZC,sBAAsB,EACtBC,eAAe,QACV,iCAAgC;AACvC,SACEC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,KAAK,EACLC,UAAU,QACL,gBAAe;AACtB,SAASC,UAAU,EAAEC,KAAK,EAAEC,KAAK,EAAEC,KAAK,QAAQ,qBAAoB;AACpE,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACtD,SACEC,0BAA0B,EAC1BC,mBAAmB,EACnBC,0BAA0B,QAErB,8BAA0B;AACjC,OAAOC,wBAAwB,uCAAmC;AAClE,SAASC,oBAAoB,QAAQ,+BAA2B;AAEhE;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,wBAAwBC,KAAyB;cA4HvCC;IA3HxB,MAAM,EAAEC,MAAM,EAAE,GA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AAS,YAAY;oCAC9CgC,OAAOf,MAAM,iBAAiBjB,SAAS,gBAAgB;;8CAEzD,KAAC5C;oCACC2E,MAAK;oCACLE,UAAUtC,SAASI,IAAIE,GAAG;oCAC1BiC,SAAS,IAAM,KAAKpC,UAAUC,KAAK,CAACC;8CAEnCA,SAAS,gBAAgB;;8CAE5B,KAAC5C;oCAAO2E,MAAK;oCAAQG,SAAS,IAAMrC,WAAWE;8CAC5C;;;2BAjCEA,IAAIE,GAAG;oBAqClB;;;0BAEF,MAAC3C;gBACC6E,MAAMC,QAAQ1D;gBACd2D,SAAS,IAAMxC,WAAW;gBAC1ByC,UAAS;gBACTC,SAAS;;kCAET,KAAC9E;kCAAa,CAAC,OAAO,UAAEiB,2BAAAA,QAASe,IAAI,mBAAI,IAAI;;kCAC7C,KAACjC;kCACEkB,wBACC,KAACJ;4BACCK,QAAQA;4BACR6D,UAAU9D,QAAQuB,GAAG;4BACrBwC,UAAU,GAAE/D,gBAAAA,QAAQe,IAAI,YAAZf,gBAAgB;4BAC5B8B,QAAO;6BAEP;;kCAEN,KAACjD;kCACC,cAAA,KAACH;4BAAO0D,OAAM;4BAAUoB,SAAS,IAAMrC,WAAW;sCAC/C;;;;;;;AAMb;AACArB,wBAAwBkE,WAAW,GAAG;AAEtC,eAAelE,wBAAuB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/components/site-org-automations-panel.component.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 {\n HOST_ACTION_STEP_LABELS,\n type HostActionStepType,\n hostEventLabel,\n pluginDocsHelp,\n scopeTokensForHost,\n} from '@aglyn/aglyn'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n useFirestoreCollection,\n useOrgDataScope,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Stack,\n Typography,\n} from '@mui/material'\nimport { collection, limit, query, where } from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport {\n ORG_AUTOMATIONS_COLLECTION,\n ORG_AUTOMATIONS_MAX,\n orgAutomationPausedHostIds,\n type OrgAutomationRow,\n} from '../model/org-automations'\nimport HostRunHistoryCard from './host-run-history-card.component'\nimport { useOrgAutomationsApi } from './use-org-automations-api'\n\n/**\n * THE ORGANIZATION'S AUTOMATIONS THAT RUN ON THIS SITE (AGL-3302), on the\n * site's own Actions section: read-only, with the one control that belongs\n * to the site — pausing an automation here, and resuming it.\n *\n * Read with the site's own scope tokens, so the listener is provable for a\n * collaborator scoped to this site as well as for an org-wide member, and\n * only the live ones placed here come back. Editing is the organization's,\n * on its own hub; a pause is the site's, through `automations/pause`, which\n * admits the site's admins and editors and refuses anyone else with its own\n * words.\n *\n * Renders nothing while there is nothing: a site the organization runs no\n * automation on has no panel to explain.\n */\nexport function SiteOrgAutomationsPanel(props: { hostId: string }) {\n const { hostId } = props\n const firestore = useFirestore()\n const api = useOrgAutomationsApi()\n const { enqueueSnackbar } = useSnackbar()\n const { scope } = useOrgDataScope({ hostId })\n const tokens = useMemo(() => scopeTokensForHost(hostId), [hostId])\n const { data: rows } = useFirestoreCollection<OrgAutomationRow>(\n () =>\n scope\n ? query(\n collection(firestore, scope[0], scope[1], ORG_AUTOMATIONS_COLLECTION),\n where('deletedAt', '==', null),\n where('visibleTo', 'array-contains-any', tokens),\n limit(ORG_AUTOMATIONS_MAX + 1),\n )\n : null,\n [firestore, scope, tokens],\n { idField: '$id' },\n )\n const automations = useMemo(\n () =>\n [...(rows ?? [])].sort((a, b) =>\n String(a.name ?? '').localeCompare(String(b.name ?? '')),\n ),\n [rows],\n )\n const [busy, setBusy] = useState<string | null>(null)\n const [runsFor, setRunsFor] = useState<OrgAutomationRow | null>(null)\n\n const setPaused = useCallback(\n async (row: OrgAutomationRow, paused: boolean) => {\n setBusy(row.$id)\n try {\n await api('pause', { hostId, automationId: row.$id, paused })\n enqueueSnackbar(\n paused\n ? `“${row.name}” is paused on this site`\n : `“${row.name}” runs on this site again`,\n { variant: 'success', persist: false },\n )\n } catch (error) {\n enqueueSnackbar(\n (error as Error)?.message || 'The request could not be completed',\n { variant: 'warning', persist: false },\n )\n } finally {\n setBusy(null)\n }\n },\n [api, hostId, enqueueSnackbar],\n )\n\n if (!automations.length) return null\n return (\n <CardDisplay\n header={'Org automations on this site'}\n help={pluginDocsHelp('orgAutomations', { anchor: '#pause-it-on-one-site' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Your organization runs these on this site beside the site’s own ' +\n 'actions. Each run sends from this site and counts on its action ' +\n 'runs. Pausing one stops it here — and anyone waiting inside it ' +\n 'here — and leaves every other site alone.'}\n </Typography>\n {automations.map((row) => {\n const paused = orgAutomationPausedHostIds(row).includes(hostId)\n const off = row.enabled === false\n return (\n <Stack\n key={row.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {row.name}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {`on ${hostEventLabel(row.trigger?.event)} · ${(row.steps ?? [])\n .map(\n (step) =>\n HOST_ACTION_STEP_LABELS[step.type as HostActionStepType] ??\n step.type,\n )\n .join(' → ')}`}\n </Typography>\n </Stack>\n <Chip\n size=\"small\"\n variant=\"outlined\"\n color={off ? 'default' : paused ? 'warning' : 'success'}\n label={off ? 'Switched off' : paused ? 'Paused here' : 'Runs here'}\n />\n <Button\n size=\"small\"\n disabled={busy === row.$id}\n onClick={() => void setPaused(row, !paused)}\n >\n {paused ? 'Resume here' : 'Pause here'}\n </Button>\n <Button size=\"small\" onClick={() => setRunsFor(row)}>\n {'Runs'}\n </Button>\n </Stack>\n )\n })}\n </Stack>\n <Dialog\n open={Boolean(runsFor)}\n onClose={() => setRunsFor(null)}\n // md: the history's four columns fit without the table scrolling.\n maxWidth=\"md\"\n fullWidth\n >\n <DialogTitle>{`Runs — ${runsFor?.name ?? ''}`}</DialogTitle>\n <DialogContent>\n {runsFor ? (\n <HostRunHistoryCard\n hostId={hostId}\n targetId={runsFor.$id}\n targetName={runsFor.name ?? ''}\n header=\"Recent runs on this site\"\n />\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button color=\"inherit\" onClick={() => setRunsFor(null)}>\n {'Close'}\n </Button>\n </DialogActions>\n </Dialog>\n </CardDisplay>\n )\n}\nSiteOrgAutomationsPanel.displayName = 'SiteOrgAutomationsPanel'\n\nexport default SiteOrgAutomationsPanel\n"],"names":["HOST_ACTION_STEP_LABELS","hostEventLabel","pluginDocsHelp","scopeTokensForHost","CardDisplay","useSnackbar","useFirestore","useFirestoreCollection","useOrgDataScope","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","Stack","Typography","collection","limit","query","where","useCallback","useMemo","useState","ORG_AUTOMATIONS_COLLECTION","ORG_AUTOMATIONS_MAX","orgAutomationPausedHostIds","HostRunHistoryCard","useOrgAutomationsApi","SiteOrgAutomationsPanel","props","runsFor","hostId","firestore","api","enqueueSnackbar","scope","tokens","data","rows","idField","automations","sort","a","b","String","name","localeCompare","busy","setBusy","setRunsFor","setPaused","row","paused","$id","automationId","variant","persist","error","message","length","header","help","anchor","contentGutterX","contentGutterY","spacing","color","map","includes","off","enabled","direction","sx","alignItems","flex","minWidth","noWrap","trigger","event","steps","step","type","join","size","label","disabled","onClick","open","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AAEiB,2BAAAA,QAASe,IAAI,mBAAI,IAAI;;kCAC7C,KAACjC;kCACEkB,wBACC,KAACJ;4BACCK,QAAQA;4BACR6D,UAAU9D,QAAQuB,GAAG;4BACrBwC,UAAU,GAAE/D,gBAAAA,QAAQe,IAAI,YAAZf,gBAAgB;4BAC5B8B,QAAO;6BAEP;;kCAEN,KAACjD;kCACC,cAAA,KAACH;4BAAO0D,OAAM;4BAAUoB,SAAS,IAAMrC,WAAW;sCAC/C;;;;;;;AAMb;AACArB,wBAAwBkE,WAAW,GAAG;AAEtC,eAAelE,wBAAuB"}
|
|
@@ -23,9 +23,13 @@ import { visibleToHost } from "@aglyn/aglyn/app-utils/scope-tokens";
|
|
|
23
23
|
// The leaf, not the barrel: this library's specs substitute the barrel
|
|
24
24
|
// wholesale, and the lookup must reach the real index logic under them.
|
|
25
25
|
import { findContactByEmail } from "@aglyn/tenant-data-admin/server/contact-email-index";
|
|
26
|
+
// The leaf again, for the phishing screen's hold (AGL-3356): the control
|
|
27
|
+
// that stops a send must be the real one under a spec that mocks the barrel.
|
|
28
|
+
import { screenOutboundSend } from "@aglyn/tenant-data-admin/server/outbound-send-review";
|
|
26
29
|
import { createHmac } from "crypto";
|
|
27
30
|
import { FieldValue } from "firebase-admin/firestore";
|
|
28
31
|
import { runSummaryFields } from "../model/run-history.js";
|
|
32
|
+
import { eventRunSuspension } from "./site-suspension.js";
|
|
29
33
|
import { advanceFlowEnrollment, claimFlowEnrollment, deferFlowEnrollment, endFlowEnrollment, enrollInFlow, findFlowEnrollmentsAwaiting, sweepDueFlowEnrollments } from "./flow-enrollments.js";
|
|
30
34
|
import { logCrmEmailActivity, prepareCrmEmailActivity, runCrmActionStep } from "./crm-action-steps.js";
|
|
31
35
|
import { resolveDatasetDoc } from "@aglyn/tenant-runtime/resolve-dataset";
|
|
@@ -477,7 +481,7 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
477
481
|
link: `/${hostId}`
|
|
478
482
|
}));
|
|
479
483
|
} else if (step.type === 'sendEmail') {
|
|
480
|
-
var _payload_, _hostPublicOrigin, _step_topicId, _step_subject, _step_body, _env_org;
|
|
484
|
+
var _payload_, _ref4, _hostPublicOrigin, _step_topicId, _step_subject, _step_body, _ref5, _run_orgId, _env_org, _env_org1, _screened_releasedReviewId;
|
|
481
485
|
var _step_toField, _this;
|
|
482
486
|
const to = String((_payload_ = payload[((_step_toField = step.toField) == null ? void 0 : _step_toField.trim()) || 'email']) != null ? _payload_ : '').trim();
|
|
483
487
|
if (!isEmailConfigured()) return failed('email is not configured');
|
|
@@ -488,7 +492,8 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
488
492
|
// than carried on the run env because most action runs send no email
|
|
489
493
|
// at all, and a document read every workflow pays for is a read on
|
|
490
494
|
// the hot path for a link nine runs in ten never need.
|
|
491
|
-
const
|
|
495
|
+
const hostData = (_ref4 = (_this = await hostRef.get().catch(()=>null)) == null ? void 0 : _this.data()) != null ? _ref4 : null;
|
|
496
|
+
const siteBase = (_hostPublicOrigin = hostPublicOrigin(hostData)) != null ? _hostPublicOrigin : '';
|
|
492
497
|
/*
|
|
493
498
|
* MARKETING. The subject and body are merchant-authored and the
|
|
494
499
|
* recipient comes out of the event payload — which, for the collect
|
|
@@ -555,7 +560,40 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
555
560
|
}
|
|
556
561
|
const emailSubject = String((_step_subject = step.subject) != null ? _step_subject : '').slice(0, 200);
|
|
557
562
|
const emailText = String((_step_body = step.body) != null ? _step_body : '').slice(0, 5000);
|
|
558
|
-
|
|
563
|
+
/*
|
|
564
|
+
* THE PHISHING SCREEN, for a workspace in its first fortnight
|
|
565
|
+
* (AGL-3356). The incident's second message was exactly this step: a
|
|
566
|
+
* `contactCreated` workflow mailing "Poshmark Order … has finally
|
|
567
|
+
* sold" with a link to a Poshmark lookalike, once per imported contact.
|
|
568
|
+
*
|
|
569
|
+
* A hold files one review row per (automation, content) in the abuse
|
|
570
|
+
* queue and stops the message. After a wait the step DEFERS, so the
|
|
571
|
+
* enrollment sends the same step once staff release it; an immediate
|
|
572
|
+
* step has no later beat to come back on, so this run records the hold
|
|
573
|
+
* as its failure and the automation sends again from its next event
|
|
574
|
+
* once released. See `outbound-send-review.ts`.
|
|
575
|
+
*/ const screened = await screenOutboundSend({
|
|
576
|
+
kind: run.kind,
|
|
577
|
+
path: run.kind === 'orgAutomation' ? `orgs/${(_ref5 = (_run_orgId = run.orgId) != null ? _run_orgId : env.orgId) != null ? _ref5 : ''}/automations/${run.id}` : `hosts/${hostId}/${run.kind === 'workflow' ? 'workflows' : 'actions'}/${run.id}`,
|
|
578
|
+
hostId,
|
|
579
|
+
orgId: env.orgId,
|
|
580
|
+
org: (_env_org = env.org) != null ? _env_org : null,
|
|
581
|
+
host: hostData,
|
|
582
|
+
subject: emailSubject,
|
|
583
|
+
bodies: [
|
|
584
|
+
emailText
|
|
585
|
+
]
|
|
586
|
+
});
|
|
587
|
+
if (screened.outcome === 'rejected') {
|
|
588
|
+
return failed(`this email was rejected by staff review (${screened.reference})`);
|
|
589
|
+
}
|
|
590
|
+
if (screened.outcome === 'held') {
|
|
591
|
+
if (enrollmentRef) return {
|
|
592
|
+
kind: 'deferred'
|
|
593
|
+
};
|
|
594
|
+
return failed('this email is held for staff review because it may impersonate ' + `another business (${screened.reference})`);
|
|
595
|
+
}
|
|
596
|
+
const consentGroup = consentGroupForHost((_env_org1 = env.org) != null ? _env_org1 : null, hostId);
|
|
559
597
|
/*
|
|
560
598
|
* THE TIMELINE ENTRY (AGL-2615). A message addressed to the contact
|
|
561
599
|
* the event is about is logged on that contact's timeline as an
|
|
@@ -579,7 +617,10 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
579
617
|
tags: emailActivity.tags
|
|
580
618
|
} : {}, {
|
|
581
619
|
audience: 'tenant',
|
|
582
|
-
context: enrollmentRef ? 'flow step' : 'event action'
|
|
620
|
+
context: enrollmentRef ? 'flow step' : 'event action',
|
|
621
|
+
// A step staff released above carries its release to the send
|
|
622
|
+
// seam's screen, which would otherwise hold the same signals again.
|
|
623
|
+
releasedReviewId: screened.outcome === 'send' ? (_screened_releasedReviewId = screened.releasedReviewId) != null ? _screened_releasedReviewId : null : null
|
|
583
624
|
}, enrollmentRef ? {
|
|
584
625
|
priority: 'bulk'
|
|
585
626
|
} : {}, {
|
|
@@ -615,7 +656,7 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
615
656
|
// a frequency ceiling are the controls working, and a merchant
|
|
616
657
|
// reading the run's alerts has a different thing to do about each.
|
|
617
658
|
const refusal = sendFailureReason(result);
|
|
618
|
-
const sendError = refusal ? refusal === 'suppressed' ? 'the recipient is unsubscribed or suppressed' : refusal === 'frequency-capped' ? 'the recipient has already had today’s limit of email ' + 'from this site' : 'email delivery failed' : null;
|
|
659
|
+
const sendError = refusal ? refusal === 'suppressed' ? 'the recipient is unsubscribed or suppressed' : refusal === 'frequency-capped' ? 'the recipient has already had today’s limit of email ' + 'from this site' : refusal === 'held-for-review' ? 'this email is held for staff review because it may ' + 'impersonate another business' : 'email delivery failed' : null;
|
|
619
660
|
// Cost meter (AGL-1438). A workflow notification is transactional:
|
|
620
661
|
// counted, never capped. `sent` is false when Resend refused or the
|
|
621
662
|
// environment is unconfigured, and an email that never left is not a
|
|
@@ -636,7 +677,7 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
636
677
|
}
|
|
637
678
|
if (sendError) return failed(sendError);
|
|
638
679
|
} else if (step.type === 'enrollList') {
|
|
639
|
-
var _payload_email1,
|
|
680
|
+
var _payload_email1, _ref6;
|
|
640
681
|
var _step_listId, _step_listName;
|
|
641
682
|
const orgId = await resolveOrgIdForHost(hostId);
|
|
642
683
|
const email = String((_payload_email1 = payload.email) != null ? _payload_email1 : '').trim().toLowerCase();
|
|
@@ -644,7 +685,7 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
644
685
|
return failed('no email to enroll');
|
|
645
686
|
}
|
|
646
687
|
const listsRef = firebaseAdmin.app().firestore().collection('orgs').doc(orgId).collection('lists');
|
|
647
|
-
const listDoc = ((_step_listId = step.listId) == null ? void 0 : _step_listId.trim()) ? await listsRef.doc(step.listId.trim()).get() : (await listsRef.where('name', '==', (
|
|
688
|
+
const listDoc = ((_step_listId = step.listId) == null ? void 0 : _step_listId.trim()) ? await listsRef.doc(step.listId.trim()).get() : (await listsRef.where('name', '==', (_ref6 = (_step_listName = step.listName) == null ? void 0 : _step_listName.trim()) != null ? _ref6 : '').limit(1).get()).docs[0];
|
|
648
689
|
if (!(listDoc == null ? void 0 : listDoc.exists)) {
|
|
649
690
|
return failed(`unknown list "${step.listName || step.listId}"`);
|
|
650
691
|
}
|
|
@@ -659,7 +700,7 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
659
700
|
source: `${run.kind}:${run.id}`
|
|
660
701
|
});
|
|
661
702
|
} else if (step.type === 'assignCampaign') {
|
|
662
|
-
var _payload_email2, _env_orgId,
|
|
703
|
+
var _payload_email2, _env_orgId, _ref7, _ref8;
|
|
663
704
|
var _step_campaignId, _step_campaignName;
|
|
664
705
|
const email = String((_payload_email2 = payload.email) != null ? _payload_email2 : '').trim().toLowerCase();
|
|
665
706
|
if (!email || !email.includes('@')) {
|
|
@@ -703,8 +744,8 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
703
744
|
if (!campaignOrgId) return failed(`unknown campaign "${campaignLabel}"`);
|
|
704
745
|
const campaignsRef = firebaseAdmin.app().firestore().collection('orgs').doc(campaignOrgId).collection('emailCampaigns');
|
|
705
746
|
const usable = (doc)=>Boolean((doc == null ? void 0 : doc.exists) && !doc.get('deletedAt') && visibleToHost(doc.get('visibleTo'), hostId));
|
|
706
|
-
const namedId = (
|
|
707
|
-
const campaignDoc = namedId ? await campaignsRef.doc(namedId).get() : (await campaignsRef.where('name', '==', (
|
|
747
|
+
const namedId = (_ref7 = (_step_campaignId = step.campaignId) == null ? void 0 : _step_campaignId.trim()) != null ? _ref7 : '';
|
|
748
|
+
const campaignDoc = namedId ? await campaignsRef.doc(namedId).get() : (await campaignsRef.where('name', '==', (_ref8 = (_step_campaignName = step.campaignName) == null ? void 0 : _step_campaignName.trim()) != null ? _ref8 : '').limit(10).get()).docs.find(usable);
|
|
708
749
|
if (!(campaignDoc == null ? void 0 : campaignDoc.exists)) {
|
|
709
750
|
return failed(`unknown campaign "${campaignLabel}"`);
|
|
710
751
|
}
|
|
@@ -1166,6 +1207,8 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
1166
1207
|
// Plan-less orgs resolve as free (AGL-247) — gates always run. Held for
|
|
1167
1208
|
// the rest of the run so the dataset caps below cost no second read.
|
|
1168
1209
|
const owner = await getOrgForHost(hostId);
|
|
1210
|
+
// A suspended site runs nothing (AGL-3356): see `eventRunSuspension`.
|
|
1211
|
+
if (await eventRunSuspension(hostRef, owner == null ? void 0 : owner.org)) return alerts;
|
|
1169
1212
|
{
|
|
1170
1213
|
var _counterSnapshot_get, _ref2;
|
|
1171
1214
|
const org = owner == null ? void 0 : owner.org;
|