@aglyn/plugins-workflows 1.0.0-beta.232 → 1.0.0-beta.234
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-run-history-card.component.js +31 -7
- package/src/lib/components/host-run-history-card.component.js.map +1 -1
- package/src/lib/components/host-webhooks-card.component.js +2 -2
- package/src/lib/components/host-webhooks-card.component.js.map +1 -1
- package/src/lib/components/host-workflows-card.component.js +1 -1
- package/src/lib/components/host-workflows-card.component.js.map +1 -1
- package/src/lib/components/staff-automations-card.component.js +38 -3
- package/src/lib/components/staff-automations-card.component.js.map +1 -1
- package/src/lib/engine/run-event-actions.js +4 -0
- package/src/lib/engine/run-event-actions.js.map +1 -1
- package/src/lib/model/run-history.js +37 -2
- package/src/lib/model/run-history.js.map +1 -1
- package/src/lib/model/webhook-text.d.ts +17 -0
- package/src/lib/model/webhook-text.js +78 -0
- package/src/lib/model/webhook-text.js.map +1 -0
- package/src/lib/model/webhooks.d.ts +9 -0
- package/src/lib/model/webhooks.js +18 -0
- package/src/lib/model/webhooks.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 HostFunction,\n type HostVariable,\n pluginDocsHelp,\n triggerFilterProblem,\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 { 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 {\n AUTOMATION_EDITOR_ZONE,\n HOST_AUTOMATIONS_ZONE,\n openActionHref,\n WORKFLOW_USAGE_ZONE,\n type AutomationTarget,\n} from './workflow-zones'\nimport {\n type HostWorkflowStep,\n runWorkflow,\n WORKFLOW_MAX_STEPS,\n} from '../model/workflows'\nimport {\n type HostActionStep,\n type HostActionStepType,\n stepRunsAfterWait,\n} from '../model/host-actions'\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 * The Actions section's address (AGL-3603). A widget in the\n * `hostAutomations` zone drafts an ACTION, which lives there; opening it\n * goes to that section with the action named. Absent, the zone's\n * `openAction` answers `false` and the widget says where the draft went.\n */\n actionsHref?: string\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 const { actionsHref } = props\n /*\n * For the `hostAutomations` zone (AGL-3603): what a widget drafts is an\n * action, listed on the Actions section rather than this card, so opening\n * it goes there and asks that section's editor to open it.\n */\n const openAction = useCallback(\n (actionId: string) => {\n if (!actionsHref) return false\n window.location.assign(openActionHref(actionsHref, actionId))\n return true\n },\n [actionsHref],\n )\n const automationsZone = ExtensionZone ? (\n <ExtensionZone\n slot={HOST_AUTOMATIONS_ZONE.id}\n hostId={hostId}\n orgId={org?.$id}\n openAction={openAction}\n />\n ) : null\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<AutomationTarget | 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 () =>\n draft\n ? // A filter the evaluator can never run saves fine and never fires\n // (AGL-3458), so it is refused with the steps.\n (triggerFilterProblem(draft.trigger?.filter, { remedy: 'action' }) ?? validateWorkflowSteps(draft.steps))\n : 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 // Other ways to start an automation (AGL-3603), in the header while\n // the list has rows and in the empty state while it has none.\n actions={workflows.length === 0 ? undefined : automationsZone}\n contentGutterX\n contentGutterY\n >\n {duplicate.dialog}\n <Stack spacing={1}>\n {workflows.length === 0 ? (\n <Stack spacing={1} sx={{ alignItems: 'flex-start' }}>\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 {automationsZone}\n </Stack>\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={AUTOMATION_EDITOR_ZONE.id}\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 // A workflow with no trigger runs from another automation, so\n // its email step is a reply only on its own event.\n replyContext={{\n event: draft?.trigger?.event,\n afterWait: stepRunsAfterWait(draft?.steps as HostActionStep[], index),\n }}\n fields={\n call ? (\n <Stack\n useFlexGap\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=\"subscribe\"\n // The evaluator is arithmetic and has no comparison (AGL-3458):\n // `path == \"/pricing\"` throws on every event and never runs.\n error={Boolean(triggerFilterProblem(draft?.trigger?.filter, { remedy: 'action' }))}\n helperText={\n triggerFilterProblem(draft?.trigger?.filter, { remedy: 'action' }) ??\n [\n 'Runs only when this expression is truthy — a field name, or arithmetic. It cannot compare values.',\n hostEventPayloadHint(draft?.trigger?.event),\n ]\n .filter(Boolean)\n .join(' ')\n }\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","triggerFilterProblem","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","AUTOMATION_EDITOR_ZONE","HOST_AUTOMATIONS_ZONE","openActionHref","WORKFLOW_USAGE_ZONE","runWorkflow","WORKFLOW_MAX_STEPS","stepRunsAfterWait","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","actionsHref","openAction","actionId","window","location","assign","automationsZone","slot","id","orgId","$id","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","functionOptions","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","remedy","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","actions","undefined","contentGutterX","contentGutterY","dialog","spacing","sx","alignItems","direction","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","target","helperText","onChange","autoFocus","mt","index","call","functionId","kinds","stepForKind","onSteps","update","replyContext","afterWait","useFlexGap","flexWrap","s","index2","find","option","select","placeholder","replace","width","parameters","parameter","parameterIndex","eventType","startsWith","targetId","targetType","targetName","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,SAEEA,gBAAgB,EAChBC,UAAU,EACVC,gBAAgB,EAChBC,cAAc,EACdC,oBAAoB,EAGpBC,cAAc,EACdC,oBAAoB,QACf,eAAc;AACrB;;;;;CAKC,GACD,SACEC,eAAe,EACfC,iBAAiB,QACZ,+DAA8D;AACrE,SAASC,oBAAoB,QAAQ,qDAAoD;AACzF,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,SAC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,SAAQ;wCAAUsI,OAAM;kDACjC;;;;4BAGJ9D,2BACC,KAAC1I;gCACCiO,UAAUvF,WAAWgI,UAAU,CAAC,WAAW,YAAY;0CAEtDhI;iCAED;;;kCAEN,MAACvI;;0CACC,KAACF;gCAAO2N,SAAS,IAAMjI,SAAS;0CAAQ;;0CACxC,KAAC1F;gCACCiE,SAAQ;gCACRsI,OAAM;gCACNmB,UAAU,EAACrK,yBAAAA,MAAOW,IAAI,CAACgF,IAAI,OAAMJ;gCACjC+E,SAAS5C;0CAER;;;;;;YAIN3G,8BACC,KAACA;gBACCQ,MAAMpC,oBAAoBqC,EAAE;gBAC5BvB,QAAQA;gBACR+E,OAAOA;gBACPiG,SAAS,IAAMhG,SAAS;iBAExB;0BACJ,MAACrI;gBACCoO,MAAMxF,QAAQzF;gBACdkL,SAAS,IAAM3F,WAAW;gBAC1B,kEAAkE;gBAClE4F,UAAS;gBACTC,SAAS;;kCAET,KAACpO;kCAAa,CAAC,OAAO,WAAEgD,2BAAAA,QAASY,IAAI,oBAAI,IAAI;;kCAC7C,KAAC7D;kCACEiD,wBACC,KAACrB;4BACCuB,QAAQA;4BACRwB,KAAK,EAAEX,uBAAAA,IAAKY,GAAG;4BACf2L,UAAUtN,QAAQ2B,GAAG;4BACrB4L,YAAW;4BACXC,UAAU,GAAExN,gBAAAA,QAAQY,IAAI,YAAZZ,gBAAgB;4BAC5BoJ,QAAO;6BAEP;;kCAEN,KAACtM;kCACC,cAAA,KAACF;4BAAOuM,OAAM;4BAAUoB,SAAS,IAAMhF,WAAW;sCAC/C;;;;;;;AAMb;AACAzF,kBAAkB2N,WAAW,GAAG;AAEhC,eAAe3N,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 HostFunction,\n type HostVariable,\n pluginDocsHelp,\n triggerFilterProblem,\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 { 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 {\n AUTOMATION_EDITOR_ZONE,\n HOST_AUTOMATIONS_ZONE,\n openActionHref,\n WORKFLOW_USAGE_ZONE,\n type AutomationTarget,\n} from './workflow-zones'\nimport {\n type HostWorkflowStep,\n runWorkflow,\n WORKFLOW_MAX_STEPS,\n} from '../model/workflows'\nimport {\n type HostActionStep,\n type HostActionStepType,\n stepRunsAfterWait,\n} from '../model/host-actions'\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 * The Actions section's address (AGL-3603). A widget in the\n * `hostAutomations` zone drafts an ACTION, which lives there; opening it\n * goes to that section with the action named. Absent, the zone's\n * `openAction` answers `false` and the widget says where the draft went.\n */\n actionsHref?: string\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 const { actionsHref } = props\n /*\n * For the `hostAutomations` zone (AGL-3603): what a widget drafts is an\n * action, listed on the Actions section rather than this card, so opening\n * it goes there and asks that section's editor to open it.\n */\n const openAction = useCallback(\n (actionId: string) => {\n if (!actionsHref) return false\n window.location.assign(openActionHref(actionsHref, actionId))\n return true\n },\n [actionsHref],\n )\n const automationsZone = ExtensionZone ? (\n <ExtensionZone\n slot={HOST_AUTOMATIONS_ZONE.id}\n hostId={hostId}\n orgId={org?.$id}\n openAction={openAction}\n />\n ) : null\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<AutomationTarget | 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 () =>\n draft\n ? // A filter the evaluator can never run saves fine and never fires\n // (AGL-3458), so it is refused with the steps.\n (triggerFilterProblem(draft.trigger?.filter, { remedy: 'action' }) ?? validateWorkflowSteps(draft.steps))\n : 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 // Other ways to start an automation (AGL-3603), in the header while\n // the list has rows and in the empty state while it has none.\n actions={workflows.length === 0 ? undefined : automationsZone}\n contentGutterX\n contentGutterY\n >\n {duplicate.dialog}\n <Stack spacing={1}>\n {workflows.length === 0 ? (\n <Stack spacing={1} sx={{ alignItems: 'flex-start' }}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Run steps in order when something happens on your site — a ' +\n 'form submission, a booking, a new member — or chain your ' +\n 'functions, each step feeding the next.'}\n </Typography>\n {automationsZone}\n </Stack>\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={AUTOMATION_EDITOR_ZONE.id}\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 // A workflow with no trigger runs from another automation, so\n // its email step is a reply only on its own event.\n replyContext={{\n event: draft?.trigger?.event,\n afterWait: stepRunsAfterWait(draft?.steps as HostActionStep[], index),\n }}\n fields={\n call ? (\n <Stack\n useFlexGap\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=\"subscribe\"\n // The evaluator is arithmetic and has no comparison (AGL-3458):\n // `path == \"/pricing\"` throws on every event and never runs.\n error={Boolean(triggerFilterProblem(draft?.trigger?.filter, { remedy: 'action' }))}\n helperText={\n triggerFilterProblem(draft?.trigger?.filter, { remedy: 'action' }) ??\n [\n 'Runs only when this expression is truthy — a field name, or arithmetic. It cannot compare values.',\n hostEventPayloadHint(draft?.trigger?.event),\n ]\n .filter(Boolean)\n .join(' ')\n }\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","triggerFilterProblem","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","AUTOMATION_EDITOR_ZONE","HOST_AUTOMATIONS_ZONE","openActionHref","WORKFLOW_USAGE_ZONE","runWorkflow","WORKFLOW_MAX_STEPS","stepRunsAfterWait","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","actionsHref","openAction","actionId","window","location","assign","automationsZone","slot","id","orgId","$id","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","functionOptions","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","remedy","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","actions","undefined","contentGutterX","contentGutterY","dialog","spacing","sx","alignItems","direction","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","target","helperText","onChange","autoFocus","mt","index","call","functionId","kinds","stepForKind","onSteps","update","replyContext","afterWait","useFlexGap","flexWrap","s","index2","find","option","select","placeholder","replace","width","parameters","parameter","parameterIndex","eventType","startsWith","targetId","targetType","targetName","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,SAEEA,gBAAgB,EAChBC,UAAU,EACVC,gBAAgB,EAChBC,cAAc,EACdC,oBAAoB,EAGpBC,cAAc,EACdC,oBAAoB,QACf,eA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M;kCACC,cAAA,KAACF;4BAAOuM,OAAM;4BAAUoB,SAAS,IAAMhF,WAAW;sCAC/C;;;;;;;AAMb;AACAzF,kBAAkB2N,WAAW,GAAG;AAEhC,eAAe3N,kBAAiB"}
|
|
@@ -19,8 +19,10 @@ import { pluginDocsHelp } from "@aglyn/aglyn/app-utils/docs-help";
|
|
|
19
19
|
import { mdiEyeOutline } from "@aglyn/shared-data-mdi";
|
|
20
20
|
import { CardDisplay } from "@aglyn/shared-ui-jsx";
|
|
21
21
|
import { ListPagination } from "@aglyn/shared-ui-jsx/components/list-pagination.component";
|
|
22
|
+
import ListQueryNotices from "@aglyn/shared-ui-jsx/components/list-query-notices.component";
|
|
22
23
|
import { ListRowActions, ListTable, listActionsColumn } from "@aglyn/shared-ui-jsx/components/list-table.component";
|
|
23
24
|
import { TABLE_ROW_HEIGHT } from "@aglyn/shared-ui-jsx/const/table-pagination";
|
|
25
|
+
import { useListColumnSort } from "@aglyn/shared-ui-jsx/hooks/use-list-column-sort";
|
|
24
26
|
import { useFirestore, usePagedCollection } from "@aglyn/tenant-feature-instance";
|
|
25
27
|
import { Box, Button, Chip, Dialog, DialogActions, DialogContent, DialogTitle, Stack, Typography } from "@mui/material";
|
|
26
28
|
import { collection, documentId, limit, orderBy, query, where } from "firebase/firestore";
|
|
@@ -99,7 +101,30 @@ const whenOf = (value)=>typeof (value == null ? void 0 : value.toDate) === 'func
|
|
|
99
101
|
]
|
|
100
102
|
});
|
|
101
103
|
}
|
|
102
|
-
/** One paged, read-only table of automations. */ function
|
|
104
|
+
/** One paged, read-only table of automations. */ const millisOf = (value)=>typeof (value == null ? void 0 : value.toMillis) === 'function' ? value.toMillis() : null;
|
|
105
|
+
/*
|
|
106
|
+
* EVERY HEADER SORTS, OVER THE PAGE (AGL-3680). These read-only staff tables
|
|
107
|
+
* walk each collection by document id. Their name falls back across fields
|
|
108
|
+
* that differ by collection (`name`, `displayName`, the id), their status is
|
|
109
|
+
* drawn from the trigger and the pause lists, and `updatedAt` is not stamped
|
|
110
|
+
* by every writer (an imported automation carries none) — so no stored field
|
|
111
|
+
* orders all three, and each header sorts the page on screen and says so.
|
|
112
|
+
*/ const AUTOMATION_PAGE_SORTS = {
|
|
113
|
+
name: (row)=>nameOf(row),
|
|
114
|
+
status: (row)=>{
|
|
115
|
+
var _ref;
|
|
116
|
+
var _row_trigger;
|
|
117
|
+
return String((_ref = (_row_trigger = row['trigger']) == null ? void 0 : _row_trigger.event) != null ? _ref : 'manual');
|
|
118
|
+
},
|
|
119
|
+
updatedAt: (row)=>millisOf(row['updatedAt'])
|
|
120
|
+
};
|
|
121
|
+
const AUTOMATION_PAGE_SORT_HEADERS = {
|
|
122
|
+
name: 'Automation',
|
|
123
|
+
status: 'Status',
|
|
124
|
+
updatedAt: 'Updated'
|
|
125
|
+
};
|
|
126
|
+
const NO_QUERY_SORTS = [];
|
|
127
|
+
function AutomationTable(props) {
|
|
103
128
|
const { title, buildQuery, deps, hostId, emptyLabel, onOpen } = props;
|
|
104
129
|
const firestore = useFirestore();
|
|
105
130
|
const paged = usePagedCollection((pageLimit)=>buildQuery(firestore, pageLimit), [
|
|
@@ -114,6 +139,12 @@ const whenOf = (value)=>typeof (value == null ? void 0 : value.toDate) === 'func
|
|
|
114
139
|
])), [
|
|
115
140
|
paged.rows
|
|
116
141
|
]);
|
|
142
|
+
const columnSort = useListColumnSort({
|
|
143
|
+
sorts: NO_QUERY_SORTS,
|
|
144
|
+
rows: paged.rows,
|
|
145
|
+
pageSorts: AUTOMATION_PAGE_SORTS,
|
|
146
|
+
headers: AUTOMATION_PAGE_SORT_HEADERS
|
|
147
|
+
});
|
|
117
148
|
const columns = useMemo(()=>[
|
|
118
149
|
{
|
|
119
150
|
field: 'name',
|
|
@@ -207,11 +238,15 @@ const whenOf = (value)=>typeof (value == null ? void 0 : value.toDate) === 'func
|
|
|
207
238
|
variant: "subtitle2",
|
|
208
239
|
children: title
|
|
209
240
|
}),
|
|
241
|
+
/*#__PURE__*/ _jsx(ListQueryNotices, {
|
|
242
|
+
refused: [],
|
|
243
|
+
notices: columnSort.notices
|
|
244
|
+
}),
|
|
210
245
|
/*#__PURE__*/ _jsx(ListTable, {
|
|
211
|
-
rows:
|
|
246
|
+
rows: columnSort.rows,
|
|
212
247
|
columns: columns,
|
|
213
248
|
loading: paged.status === 'loading',
|
|
214
|
-
|
|
249
|
+
columnSort: columnSort,
|
|
215
250
|
noRowsLabel: emptyLabel,
|
|
216
251
|
onOpen: (id)=>{
|
|
217
252
|
const row = byId.get(String(id));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/components/staff-automations-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 { pluginDocsHelp } from '@aglyn/aglyn/app-utils/docs-help'\nimport { mdiEyeOutline } from '@aglyn/shared-data-mdi'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { TABLE_ROW_HEIGHT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { useFirestore, usePagedCollection } from '@aglyn/tenant-feature-instance'\nimport {\n Box,\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Stack,\n Typography,\n} from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport {\n collection,\n documentId,\n type Firestore,\n limit,\n orderBy,\n query,\n type Query,\n where,\n} from 'firebase/firestore'\nimport { useMemo, useState } from 'react'\n\n/*\n * AUTOMATIONS, AS STAFF SEE THEM (AGL-3379).\n *\n * The staff site and organization pages are about a customer the staffer is\n * not a member of, so nothing here edits, runs or pauses: each table is a\n * paged walk of one collection in document-id order, and a row opens a\n * read-only view of the trigger and the steps. The rules admit staff reads on\n * every site and organization subcollection.\n */\n\ntype AutomationRow = { $id: string } & Record<string, any>\n\nconst nameOf = (row: AutomationRow): string => String(row['name'] || row['displayName'] || row.$id)\n\nconst whenOf = (value: any): string =>\n typeof value?.toDate === 'function' ? value.toDate().toLocaleString() : '—'\n\n/** The trigger and the steps of one automation, read-only. */\nfunction StepsDialog(props: { row: AutomationRow | null; onClose: () => void }) {\n const { row, onClose } = props\n const steps: unknown[] = Array.isArray(row?.['steps']) ? row['steps'] : []\n return (\n <Dialog open={Boolean(row)} onClose={onClose} maxWidth=\"md\" fullWidth>\n <DialogTitle>{row ? nameOf(row) : ''}</DialogTitle>\n <DialogContent>\n <Stack spacing={2}>\n <Box>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Trigger'}\n </Typography>\n <Typography variant=\"body2\">\n {row?.['trigger']?.event ?? 'Manual — runs only when called'}\n </Typography>\n {row?.['trigger']?.filter ? (\n <Typography variant=\"caption\" sx={{ fontFamily: 'monospace' }}>\n {`when ${row['trigger'].filter}`}\n </Typography>\n ) : null}\n </Box>\n <Box>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {`Steps (${steps.length})`}\n </Typography>\n <Box\n component=\"pre\"\n sx={{\n m: 0,\n p: 1.5,\n borderRadius: 1,\n bgcolor: 'action.hover',\n fontSize: 12,\n overflow: 'auto',\n maxHeight: 420,\n }}\n >\n {JSON.stringify(steps, null, 2)}\n </Box>\n </Box>\n </Stack>\n </DialogContent>\n <DialogActions>\n <Button onClick={onClose}>{'Close'}</Button>\n </DialogActions>\n </Dialog>\n )\n}\n\n/** One paged, read-only table of automations. */\nfunction AutomationTable(props: {\n title: string\n buildQuery: (firestore: Firestore, pageLimit: number) => Query | null\n deps: readonly unknown[]\n /** The site the table is read for, to mark what it has paused. */\n hostId?: string\n emptyLabel: string\n onOpen: (row: AutomationRow) => void\n}) {\n const { title, buildQuery, deps, hostId, emptyLabel, onOpen } = props\n const firestore = useFirestore()\n const paged = usePagedCollection<AutomationRow>(\n (pageLimit) => buildQuery(firestore, pageLimit),\n [firestore, ...deps],\n { idField: '$id' },\n )\n const byId = useMemo(() => new Map(paged.rows.map((row) => [row.$id, row])), [paged.rows])\n const columns: GridColDef[] = useMemo(\n () => [\n {\n field: 'name',\n headerName: 'Automation',\n flex: 1.4,\n minWidth: 200,\n valueGetter: (_value, row: AutomationRow) => nameOf(row),\n },\n {\n field: 'status',\n headerName: 'Status',\n flex: 1.2,\n minWidth: 200,\n valueGetter: (_value, row: AutomationRow) => String(row['trigger']?.event ?? 'manual'),\n renderCell: ({ row }: { row: AutomationRow }) => {\n const paused: string[] = Array.isArray(row['pausedHostIds']) ? row['pausedHostIds'] : []\n return (\n <Stack\n direction=\"row\"\n spacing={0.5}\n useFlexGap\n sx={{ alignItems: 'center', height: '100%', flexWrap: 'wrap' }}\n >\n <Chip size=\"small\" variant=\"outlined\" label={row['trigger']?.event ?? 'manual'} />\n {row['enabled'] === false ? (\n <Chip size=\"small\" color=\"warning\" label=\"off\" />\n ) : (\n <Chip size=\"small\" color=\"success\" label=\"on\" />\n )}\n {hostId && paused.includes(hostId) ? (\n <Chip size=\"small\" color=\"warning\" label=\"paused here\" />\n ) : !hostId && paused.length ? (\n <Chip size=\"small\" color=\"warning\" label={`paused on ${paused.length}`} />\n ) : null}\n {row['deletedAt'] ? <Chip size=\"small\" color=\"error\" label=\"deleted\" /> : null}\n </Stack>\n )\n },\n },\n {\n field: 'updatedAt',\n headerName: 'Updated',\n flex: 0.9,\n minWidth: 160,\n valueGetter: (_value, row: AutomationRow) => whenOf(row['updatedAt']),\n },\n listActionsColumn(\n (row: AutomationRow) => (\n <ListRowActions\n label={nameOf(row)}\n quick={{ icon: mdiEyeOutline.path, label: 'View steps', onClick: () => onOpen(row) }}\n items={[]}\n />\n ),\n { width: 110 },\n ),\n ],\n [hostId, onOpen],\n )\n return (\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{title}</Typography>\n <ListTable\n rows={paged.rows}\n columns={columns}\n loading={paged.status === 'loading'}\n disableColumnSorting\n noRowsLabel={emptyLabel}\n onOpen={(id) => {\n const row = byId.get(String(id))\n if (row) onOpen(row)\n }}\n hideFooter\n rowHeight={TABLE_ROW_HEIGHT}\n />\n <ListPagination\n page={paged.page}\n pageSize={paged.pageSize}\n rowCount={paged.rows.length}\n hasMore={paged.hasMore}\n onPageChange={paged.setPage}\n onPageSizeChange={paged.setPageSize}\n />\n </Stack>\n )\n}\n\nconst inIdOrder = (source: Query, pageLimit: number) =>\n query(source, orderBy(documentId()), limit(pageLimit))\n\n/**\n * The staff site page's automations (`staffSite` zone): the site's own\n * automations, the organization automations that run on it, and its\n * workflows.\n */\nexport function StaffSiteAutomationsCard(props: { hostId: string; orgId?: string }) {\n const { hostId, orgId } = props\n const [open, setOpen] = useState<AutomationRow | null>(null)\n return (\n <>\n <CardDisplay\n header={'Automations'}\n help={pluginDocsHelp('staffConsole', {\n anchor: '#staff-automations',\n excerpt:\n \"The site's automations, the organization automations that run on it, and its workflows — read-only, each opening its trigger and steps.\",\n })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={3}>\n <AutomationTable\n title=\"Site automations\"\n buildQuery={(firestore, pageLimit) =>\n hostId ? inIdOrder(collection(firestore, 'hosts', hostId, 'actions'), pageLimit) : null\n }\n deps={[hostId]}\n hostId={hostId}\n emptyLabel=\"No automations on this site\"\n onOpen={setOpen}\n />\n <AutomationTable\n title=\"Organization automations that run here\"\n buildQuery={(firestore, pageLimit) =>\n orgId && hostId\n ? inIdOrder(\n query(\n collection(firestore, 'orgs', orgId, 'automations'),\n where('visibleTo', 'array-contains-any', ['org', `host:${hostId}`]),\n ),\n pageLimit,\n )\n : null\n }\n deps={[orgId, hostId]}\n hostId={hostId}\n emptyLabel=\"No organization automation runs on this site\"\n onOpen={setOpen}\n />\n <AutomationTable\n title=\"Workflows\"\n buildQuery={(firestore, pageLimit) =>\n hostId ? inIdOrder(collection(firestore, 'hosts', hostId, 'workflows'), pageLimit) : null\n }\n deps={[hostId]}\n emptyLabel=\"No workflows on this site\"\n onOpen={setOpen}\n />\n </Stack>\n </CardDisplay>\n <StepsDialog row={open} onClose={() => setOpen(null)} />\n </>\n )\n}\n\n/** The staff organization page's automations (`adminOrgDetail` zone). */\nexport function StaffOrgAutomationsCard(props: { orgId: string }) {\n const { orgId } = props\n const [open, setOpen] = useState<AutomationRow | null>(null)\n return (\n <>\n <CardDisplay\n header={'Organization automations'}\n help={pluginDocsHelp('staffConsole', {\n anchor: '#staff-automations',\n excerpt:\n \"The organization's automations, whether each is on and where it is paused — read-only, each opening its trigger and steps.\",\n })}\n contentGutterX\n contentGutterY\n >\n <AutomationTable\n title=\"Automations\"\n buildQuery={(firestore, pageLimit) =>\n orgId ? inIdOrder(collection(firestore, 'orgs', orgId, 'automations'), pageLimit) : null\n }\n deps={[orgId]}\n emptyLabel=\"This organization has no automations\"\n onOpen={setOpen}\n />\n </CardDisplay>\n <StepsDialog row={open} onClose={() => setOpen(null)} />\n </>\n )\n}\n"],"names":["pluginDocsHelp","mdiEyeOutline","CardDisplay","ListPagination","ListRowActions","ListTable","listActionsColumn","TABLE_ROW_HEIGHT","useFirestore","usePagedCollection","Box","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","Stack","Typography","collection","documentId","limit","orderBy","query","where","useMemo","useState","nameOf","row","String","$id","whenOf","value","toDate","toLocaleString","StepsDialog","props","onClose","steps","Array","isArray","open","Boolean","maxWidth","fullWidth","spacing","variant","color","event","filter","sx","fontFamily","length","component","m","p","borderRadius","bgcolor","fontSize","overflow","maxHeight","JSON","stringify","onClick","AutomationTable","title","buildQuery","deps","hostId","emptyLabel","onOpen","firestore","paged","pageLimit","idField","byId","Map","rows","map","columns","field","headerName","flex","minWidth","valueGetter","_value","renderCell","paused","direction","useFlexGap","alignItems","height","flexWrap","size","label","includes","quick","icon","path","items","width","loading","status","disableColumnSorting","noRowsLabel","id","get","hideFooter","rowHeight","page","pageSize","rowCount","hasMore","onPageChange","setPage","onPageSizeChange","setPageSize","inIdOrder","source","StaffSiteAutomationsCard","orgId","setOpen","header","help","anchor","excerpt","contentGutterX","contentGutterY","StaffOrgAutomationsCard"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,cAAc,QAAQ,mCAAkC;AACjE,SAASC,aAAa,QAAQ,yBAAwB;AACtD,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SACEC,cAAc,EACdC,SAAS,EACTC,iBAAiB,QACZ,uDAAsD;AAC7D,SAASC,gBAAgB,QAAQ,8CAA6C;AAC9E,SAASC,YAAY,EAAEC,kBAAkB,QAAQ,iCAAgC;AACjF,SACEC,GAAG,EACHC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,KAAK,EACLC,UAAU,QACL,gBAAe;AAEtB,SACEC,UAAU,EACVC,UAAU,EAEVC,KAAK,EACLC,OAAO,EACPC,KAAK,EAELC,KAAK,QACA,qBAAoB;AAC3B,SAASC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AAczC,MAAMC,SAAS,CAACC,MAA+BC,OAAOD,GAAG,CAAC,OAAO,IAAIA,GAAG,CAAC,cAAc,IAAIA,IAAIE,GAAG;AAElG,MAAMC,SAAS,CAACC,QACd,QAAOA,yBAAAA,MAAOC,MAAM,MAAK,aAAaD,MAAMC,MAAM,GAAGC,cAAc,KAAK;AAE1E,4DAA4D,GAC5D,SAASC,YAAYC,KAAyD;;QAa/DR,cAEFA;IAdX,MAAM,EAAEA,GAAG,EAAES,OAAO,EAAE,GAAGD;IACzB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C9D,MAAM,EAAEoF,KAAK,EAAE,GAAGpF;IAClB,MAAM,CAACK,MAAMgF,QAAQ,GAAG/F,SAA+B;IACvD,qBACE;;0BACE,KAACxB;gBACCwH,QAAQ;gBACRC,MAAM3H,eAAe,gBAAgB;oBACnC4H,QAAQ;oBACRC,SACE;gBACJ;gBACAC,cAAc;gBACdC,cAAc;0BAEd,cAAA,KAAC/D;oBACCC,OAAM;oBACNC,YAAY,CAACK,WAAWE,YACtB+C,QAAQH,UAAUlG,WAAWoD,WAAW,QAAQiD,OAAO,gBAAgB/C,aAAa;oBAEtFN,MAAM;wBAACqD;qBAAM;oBACbnD,YAAW;oBACXC,QAAQmD;;;0BAGZ,KAACtF;gBAAYP,KAAKa;gBAAMJ,SAAS,IAAMoF,QAAQ;;;;AAGrD"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/components/staff-automations-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 { pluginDocsHelp } from '@aglyn/aglyn/app-utils/docs-help'\nimport { mdiEyeOutline } from '@aglyn/shared-data-mdi'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport ListQueryNotices from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\nimport {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { TABLE_ROW_HEIGHT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { useListColumnSort } from '@aglyn/shared-ui-jsx/hooks/use-list-column-sort'\nimport { useFirestore, usePagedCollection } from '@aglyn/tenant-feature-instance'\nimport {\n Box,\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Stack,\n Typography,\n} from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport {\n collection,\n documentId,\n type Firestore,\n limit,\n orderBy,\n query,\n type Query,\n where,\n} from 'firebase/firestore'\nimport { useMemo, useState } from 'react'\n\n/*\n * AUTOMATIONS, AS STAFF SEE THEM (AGL-3379).\n *\n * The staff site and organization pages are about a customer the staffer is\n * not a member of, so nothing here edits, runs or pauses: each table is a\n * paged walk of one collection in document-id order, and a row opens a\n * read-only view of the trigger and the steps. The rules admit staff reads on\n * every site and organization subcollection.\n */\n\ntype AutomationRow = { $id: string } & Record<string, any>\n\nconst nameOf = (row: AutomationRow): string => String(row['name'] || row['displayName'] || row.$id)\n\nconst whenOf = (value: any): string =>\n typeof value?.toDate === 'function' ? value.toDate().toLocaleString() : '—'\n\n/** The trigger and the steps of one automation, read-only. */\nfunction StepsDialog(props: { row: AutomationRow | null; onClose: () => void }) {\n const { row, onClose } = props\n const steps: unknown[] = Array.isArray(row?.['steps']) ? row['steps'] : []\n return (\n <Dialog open={Boolean(row)} onClose={onClose} maxWidth=\"md\" fullWidth>\n <DialogTitle>{row ? nameOf(row) : ''}</DialogTitle>\n <DialogContent>\n <Stack spacing={2}>\n <Box>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Trigger'}\n </Typography>\n <Typography variant=\"body2\">\n {row?.['trigger']?.event ?? 'Manual — runs only when called'}\n </Typography>\n {row?.['trigger']?.filter ? (\n <Typography variant=\"caption\" sx={{ fontFamily: 'monospace' }}>\n {`when ${row['trigger'].filter}`}\n </Typography>\n ) : null}\n </Box>\n <Box>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {`Steps (${steps.length})`}\n </Typography>\n <Box\n component=\"pre\"\n sx={{\n m: 0,\n p: 1.5,\n borderRadius: 1,\n bgcolor: 'action.hover',\n fontSize: 12,\n overflow: 'auto',\n maxHeight: 420,\n }}\n >\n {JSON.stringify(steps, null, 2)}\n </Box>\n </Box>\n </Stack>\n </DialogContent>\n <DialogActions>\n <Button onClick={onClose}>{'Close'}</Button>\n </DialogActions>\n </Dialog>\n )\n}\n\n/** One paged, read-only table of automations. */\nconst millisOf = (value: any): number | null =>\n typeof value?.toMillis === 'function' ? value.toMillis() : null\n\n/*\n * EVERY HEADER SORTS, OVER THE PAGE (AGL-3680). These read-only staff tables\n * walk each collection by document id. Their name falls back across fields\n * that differ by collection (`name`, `displayName`, the id), their status is\n * drawn from the trigger and the pause lists, and `updatedAt` is not stamped\n * by every writer (an imported automation carries none) — so no stored field\n * orders all three, and each header sorts the page on screen and says so.\n */\nconst AUTOMATION_PAGE_SORTS = {\n name: (row: AutomationRow) => nameOf(row),\n status: (row: AutomationRow) => String(row['trigger']?.event ?? 'manual'),\n updatedAt: (row: AutomationRow) => millisOf(row['updatedAt']),\n}\nconst AUTOMATION_PAGE_SORT_HEADERS = { name: 'Automation', status: 'Status', updatedAt: 'Updated' }\nconst NO_QUERY_SORTS = [] as const\n\nfunction AutomationTable(props: {\n title: string\n buildQuery: (firestore: Firestore, pageLimit: number) => Query | null\n deps: readonly unknown[]\n /** The site the table is read for, to mark what it has paused. */\n hostId?: string\n emptyLabel: string\n onOpen: (row: AutomationRow) => void\n}) {\n const { title, buildQuery, deps, hostId, emptyLabel, onOpen } = props\n const firestore = useFirestore()\n const paged = usePagedCollection<AutomationRow>(\n (pageLimit) => buildQuery(firestore, pageLimit),\n [firestore, ...deps],\n { idField: '$id' },\n )\n const byId = useMemo(() => new Map(paged.rows.map((row) => [row.$id, row])), [paged.rows])\n const columnSort = useListColumnSort<AutomationRow>({\n sorts: NO_QUERY_SORTS,\n rows: paged.rows,\n pageSorts: AUTOMATION_PAGE_SORTS,\n headers: AUTOMATION_PAGE_SORT_HEADERS,\n })\n const columns: GridColDef[] = useMemo(\n () => [\n {\n field: 'name',\n headerName: 'Automation',\n flex: 1.4,\n minWidth: 200,\n valueGetter: (_value, row: AutomationRow) => nameOf(row),\n },\n {\n field: 'status',\n headerName: 'Status',\n flex: 1.2,\n minWidth: 200,\n valueGetter: (_value, row: AutomationRow) => String(row['trigger']?.event ?? 'manual'),\n renderCell: ({ row }: { row: AutomationRow }) => {\n const paused: string[] = Array.isArray(row['pausedHostIds']) ? row['pausedHostIds'] : []\n return (\n <Stack\n direction=\"row\"\n spacing={0.5}\n useFlexGap\n sx={{ alignItems: 'center', height: '100%', flexWrap: 'wrap' }}\n >\n <Chip size=\"small\" variant=\"outlined\" label={row['trigger']?.event ?? 'manual'} />\n {row['enabled'] === false ? (\n <Chip size=\"small\" color=\"warning\" label=\"off\" />\n ) : (\n <Chip size=\"small\" color=\"success\" label=\"on\" />\n )}\n {hostId && paused.includes(hostId) ? (\n <Chip size=\"small\" color=\"warning\" label=\"paused here\" />\n ) : !hostId && paused.length ? (\n <Chip size=\"small\" color=\"warning\" label={`paused on ${paused.length}`} />\n ) : null}\n {row['deletedAt'] ? <Chip size=\"small\" color=\"error\" label=\"deleted\" /> : null}\n </Stack>\n )\n },\n },\n {\n field: 'updatedAt',\n headerName: 'Updated',\n flex: 0.9,\n minWidth: 160,\n valueGetter: (_value, row: AutomationRow) => whenOf(row['updatedAt']),\n },\n listActionsColumn(\n (row: AutomationRow) => (\n <ListRowActions\n label={nameOf(row)}\n quick={{ icon: mdiEyeOutline.path, label: 'View steps', onClick: () => onOpen(row) }}\n items={[]}\n />\n ),\n { width: 110 },\n ),\n ],\n [hostId, onOpen],\n )\n return (\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{title}</Typography>\n <ListQueryNotices refused={[]} notices={columnSort.notices} />\n <ListTable\n rows={columnSort.rows}\n columns={columns}\n loading={paged.status === 'loading'}\n columnSort={columnSort}\n noRowsLabel={emptyLabel}\n onOpen={(id) => {\n const row = byId.get(String(id))\n if (row) onOpen(row)\n }}\n hideFooter\n rowHeight={TABLE_ROW_HEIGHT}\n />\n <ListPagination\n page={paged.page}\n pageSize={paged.pageSize}\n rowCount={paged.rows.length}\n hasMore={paged.hasMore}\n onPageChange={paged.setPage}\n onPageSizeChange={paged.setPageSize}\n />\n </Stack>\n )\n}\n\nconst inIdOrder = (source: Query, pageLimit: number) =>\n query(source, orderBy(documentId()), limit(pageLimit))\n\n/**\n * The staff site page's automations (`staffSite` zone): the site's own\n * automations, the organization automations that run on it, and its\n * workflows.\n */\nexport function StaffSiteAutomationsCard(props: { hostId: string; orgId?: string }) {\n const { hostId, orgId } = props\n const [open, setOpen] = useState<AutomationRow | null>(null)\n return (\n <>\n <CardDisplay\n header={'Automations'}\n help={pluginDocsHelp('staffConsole', {\n anchor: '#staff-automations',\n excerpt:\n \"The site's automations, the organization automations that run on it, and its workflows — read-only, each opening its trigger and steps.\",\n })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={3}>\n <AutomationTable\n title=\"Site automations\"\n buildQuery={(firestore, pageLimit) =>\n hostId ? inIdOrder(collection(firestore, 'hosts', hostId, 'actions'), pageLimit) : null\n }\n deps={[hostId]}\n hostId={hostId}\n emptyLabel=\"No automations on this site\"\n onOpen={setOpen}\n />\n <AutomationTable\n title=\"Organization automations that run here\"\n buildQuery={(firestore, pageLimit) =>\n orgId && hostId\n ? inIdOrder(\n query(\n collection(firestore, 'orgs', orgId, 'automations'),\n where('visibleTo', 'array-contains-any', ['org', `host:${hostId}`]),\n ),\n pageLimit,\n )\n : null\n }\n deps={[orgId, hostId]}\n hostId={hostId}\n emptyLabel=\"No organization automation runs on this site\"\n onOpen={setOpen}\n />\n <AutomationTable\n title=\"Workflows\"\n buildQuery={(firestore, pageLimit) =>\n hostId ? inIdOrder(collection(firestore, 'hosts', hostId, 'workflows'), pageLimit) : null\n }\n deps={[hostId]}\n emptyLabel=\"No workflows on this site\"\n onOpen={setOpen}\n />\n </Stack>\n </CardDisplay>\n <StepsDialog row={open} onClose={() => setOpen(null)} />\n </>\n )\n}\n\n/** The staff organization page's automations (`adminOrgDetail` zone). */\nexport function StaffOrgAutomationsCard(props: { orgId: string }) {\n const { orgId } = props\n const [open, setOpen] = useState<AutomationRow | null>(null)\n return (\n <>\n <CardDisplay\n header={'Organization automations'}\n help={pluginDocsHelp('staffConsole', {\n anchor: '#staff-automations',\n excerpt:\n \"The organization's automations, whether each is on and where it is paused — read-only, each opening its trigger and steps.\",\n })}\n contentGutterX\n contentGutterY\n >\n <AutomationTable\n title=\"Automations\"\n buildQuery={(firestore, pageLimit) =>\n orgId ? inIdOrder(collection(firestore, 'orgs', orgId, 'automations'), pageLimit) : null\n }\n deps={[orgId]}\n emptyLabel=\"This organization has no automations\"\n onOpen={setOpen}\n />\n </CardDisplay>\n <StepsDialog row={open} onClose={() => setOpen(null)} />\n </>\n )\n}\n"],"names":["pluginDocsHelp","mdiEyeOutline","CardDisplay","ListPagination","ListQueryNotices","ListRowActions","ListTable","listActionsColumn","TABLE_ROW_HEIGHT","useListColumnSort","useFirestore","usePagedCollection","Box","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","Stack","Typography","collection","documentId","limit","orderBy","query","where","useMemo","useState","nameOf","row","String","$id","whenOf","value","toDate","toLocaleString","StepsDialog","props","onClose","steps","Array","isArray","open","Boolean","maxWidth","fullWidth","spacing","variant","color","event","filter","sx","fontFamily","length","component","m","p","borderRadius","bgcolor","fontSize","overflow","maxHeight","JSON","stringify","onClick","millisOf","toMillis","AUTOMATION_PAGE_SORTS","name","status","updatedAt","AUTOMATION_PAGE_SORT_HEADERS","NO_QUERY_SORTS","AutomationTable","title","buildQuery","deps","hostId","emptyLabel","onOpen","firestore","paged","pageLimit","idField","byId","Map","rows","map","columnSort","sorts","pageSorts","headers","columns","field","headerName","flex","minWidth","valueGetter","_value","renderCell","paused","direction","useFlexGap","alignItems","height","flexWrap","size","label","includes","quick","icon","path","items","width","refused","notices","loading","noRowsLabel","id","get","hideFooter","rowHeight","page","pageSize","rowCount","hasMore","onPageChange","setPage","onPageSizeChange","setPageSize","inIdOrder","source","StaffSiteAutomationsCard","orgId","setOpen","header","help","anchor","excerpt","contentGutterX","contentGutterY","StaffOrgAutomationsCard"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,cAAc,QAAQ,mCAAkC;AACjE,SAASC,aAAa,QAAQ,yBAAwB;AACtD,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,OAAOC,sBAAsB,+DAA8D;AAC3F,SACEC,cAAc,EACdC,SAAS,EACTC,iBAAiB,QACZ,uDAAsD;AAC7D,SAASC,gBAAgB,QAAQ,8CAA6C;AAC9E,SAASC,iBAAiB,QAAQ,kDAAiD;AACnF,SAASC,YAAY,EAAEC,kBAAkB,QAAQ,iCAAgC;AACjF,SACEC,GAAG,EACHC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,KAAK,EACLC,UAAU,QACL,gBAAe;AAEtB,SACEC,UAAU,EACVC,UAAU,EAEVC,KAAK,EACLC,OAAO,EACPC,KAAK,EAELC,KAAK,QACA,qBAAoB;AAC3B,SAASC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AAczC,MAAMC,SAAS,CAACC,MAA+BC,OAAOD,GAAG,CAAC,OAAO,IAAIA,GAAG,CAAC,cAAc,IAAIA,IAAIE,GAAG;AAElG,MAAMC,SAAS,CAACC,QACd,QAAOA,yBAAAA,MAAOC,MAAM,MAAK,aAAaD,MAAMC,MAAM,GAAGC,cAAc,KAAK;AAE1E,4DAA4D,GAC5D,SAASC,YAAYC,KAAyD;;QAa/DR,cAEFA;IAdX,MAAM,EAAEA,GAAG,EAAES,OAAO,EAAE,GAAGD;IACzB,MAAME,QAAmBC,MAAMC,OAAO,CAACZ,uBAAAA,GAAK,CAAC,QAAQ,IAAIA,GAAG,CAAC,QAAQ,GAAG,EAAE;IAC1E,qBACE,MA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WAAW4D,WAAW,QAAQqD,OAAO,gBACrC5G,MAAM,aAAa,sBAAsB;oCAAC;oCAAO,CAAC,KAAK,EAAEoD,QAAQ;iCAAC,IAEpEK,aAEF;4BAENN,MAAM;gCAACyD;gCAAOxD;6BAAO;4BACrBA,QAAQA;4BACRC,YAAW;4BACXC,QAAQuD;;sCAEV,KAAC7D;4BACCC,OAAM;4BACNC,YAAY,CAACK,WAAWE,YACtBL,SAASqD,UAAU9G,WAAW4D,WAAW,SAASH,QAAQ,cAAcK,aAAa;4BAEvFN,MAAM;gCAACC;6BAAO;4BACdC,YAAW;4BACXC,QAAQuD;;;;;0BAId,KAAClG;gBAAYP,KAAKa;gBAAMJ,SAAS,IAAMgG,QAAQ;;;;AAGrD;AAEA,uEAAuE,GACvE,OAAO,SAASO,wBAAwBxG,KAAwB;IAC9D,MAAM,EAAEgG,KAAK,EAAE,GAAGhG;IAClB,MAAM,CAACK,MAAM4F,QAAQ,GAAG3G,SAA+B;IACvD,qBACE;;0BACE,KAAC1B;gBACCsI,QAAQ;gBACRC,MAAMzI,eAAe,gBAAgB;oBACnC0I,QAAQ;oBACRC,SACE;gBACJ;gBACAC,cAAc;gBACdC,cAAc;0BAEd,cAAA,KAACnE;oBACCC,OAAM;oBACNC,YAAY,CAACK,WAAWE,YACtBmD,QAAQH,UAAU9G,WAAW4D,WAAW,QAAQqD,OAAO,gBAAgBnD,aAAa;oBAEtFN,MAAM;wBAACyD;qBAAM;oBACbvD,YAAW;oBACXC,QAAQuD;;;0BAGZ,KAAClG;gBAAYP,KAAKa;gBAAMJ,SAAS,IAAMgG,QAAQ;;;;AAGrD"}
|
|
@@ -32,6 +32,7 @@ import { renderSiteTextEmail } from "@aglyn/tenant-data-admin/server/host-email-
|
|
|
32
32
|
import { createHmac } from "crypto";
|
|
33
33
|
import { FieldValue } from "firebase-admin/firestore";
|
|
34
34
|
import { runSummaryFields } from "../model/run-history.js";
|
|
35
|
+
import { webhookSummaryText } from "../model/webhook-text.js";
|
|
35
36
|
import { ACTION_MAX_EVENT_DEPTH, runWorkflow, WORKFLOW_MAX_STEPS } from "../model/workflows.js";
|
|
36
37
|
import { describeStepOutcome } from "../model/step-outcomes.js";
|
|
37
38
|
import { eventRunSuspension } from "./site-suspension.js";
|
|
@@ -299,9 +300,12 @@ export function makeWorkflowContextLoader(hostRef) {
|
|
|
299
300
|
if (!hook || hookDoc.get('deletedAt') || hook.enabled === false || hook.direction !== 'outbound' || !hook.url) {
|
|
300
301
|
return failed(`unknown webhook "${step.webhookName || step.webhookId}"`);
|
|
301
302
|
}
|
|
303
|
+
// `text` is what a Slack, Google Chat or Teams incoming webhook posts
|
|
304
|
+
// (AGL-3684); without it Slack refuses the body with `400 no_text`.
|
|
302
305
|
const body = JSON.stringify({
|
|
303
306
|
event,
|
|
304
307
|
payload,
|
|
308
|
+
text: webhookSummaryText(event, payload),
|
|
305
309
|
sentAt: new Date().toISOString()
|
|
306
310
|
});
|
|
307
311
|
const signature = hook.secret ? createHmac('sha256', hook.secret).update(body).digest('hex') : '';
|