@saltcorn/server 1.1.0-beta.13 → 1.1.0-beta.15

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/routes/actions.js CHANGED
@@ -17,6 +17,9 @@ const Trigger = require("@saltcorn/data/models/trigger");
17
17
  const FieldRepeat = require("@saltcorn/data/models/fieldrepeat");
18
18
  const { getTriggerList } = require("./common_lists");
19
19
  const TagEntry = require("@saltcorn/data/models/tag_entry");
20
+ const WorkflowStep = require("@saltcorn/data/models/workflow_step");
21
+ const WorkflowRun = require("@saltcorn/data/models/workflow_run");
22
+ const WorkflowTrace = require("@saltcorn/data/models/workflow_trace");
20
23
  const Tag = require("@saltcorn/data/models/tag");
21
24
  const db = require("@saltcorn/data/db");
22
25
 
@@ -29,7 +32,13 @@ const db = require("@saltcorn/data/db");
29
32
  */
30
33
  const router = new Router();
31
34
  module.exports = router;
32
- const { renderForm, link } = require("@saltcorn/markup");
35
+ const {
36
+ renderForm,
37
+ link,
38
+ mkTable,
39
+ localeDateTime,
40
+ post_delete_btn,
41
+ } = require("@saltcorn/markup");
33
42
  const Form = require("@saltcorn/data/models/form");
34
43
  const {
35
44
  div,
@@ -45,8 +54,13 @@ const {
45
54
  td,
46
55
  h6,
47
56
  pre,
57
+ th,
48
58
  text,
49
59
  i,
60
+ ul,
61
+ li,
62
+ h2,
63
+ h4,
50
64
  } = require("@saltcorn/markup/tags");
51
65
  const Table = require("@saltcorn/data/models/table");
52
66
  const { getActionConfigFields } = require("@saltcorn/data/plugin-helper");
@@ -154,11 +168,15 @@ const triggerForm = async (req, trigger) => {
154
168
  .filter(([k, v]) => v.hasChannel)
155
169
  .map(([k, v]) => k);
156
170
 
157
- const allActions = Trigger.action_options({ notRequireRow: false });
171
+ const allActions = Trigger.action_options({
172
+ notRequireRow: false,
173
+ workflow: true,
174
+ });
158
175
  const table_triggers = ["Insert", "Update", "Delete", "Validate"];
159
176
  const action_options = {};
160
177
  const actionsNotRequiringRow = Trigger.action_options({
161
178
  notRequireRow: true,
179
+ workflow: true,
162
180
  });
163
181
 
164
182
  Trigger.when_options.forEach((t) => {
@@ -326,6 +344,11 @@ router.get(
326
344
  isAdmin,
327
345
  error_catcher(async (req, res) => {
328
346
  const form = await triggerForm(req);
347
+ if (req.query.table) {
348
+ const table = Table.findOne({ name: req.query.table });
349
+ if (table) form.values.table_id = table.id;
350
+ }
351
+
329
352
  send_events_page({
330
353
  res,
331
354
  req,
@@ -467,6 +490,366 @@ router.post(
467
490
  })
468
491
  );
469
492
 
493
+ function genWorkflowDiagram(steps) {
494
+ const stepNames = steps.map((s) => s.name);
495
+ const nodeLines = steps.map(
496
+ (s) => ` ${s.name}["\`**${s.name}**
497
+ ${s.action_name}\`"]:::wfstep${s.id}`
498
+ );
499
+
500
+ nodeLines.unshift(` _Start@{ shape: circle, label: "Start" }`);
501
+ const linkLines = [];
502
+ let step_ix = 0;
503
+ for (const step of steps) {
504
+ if (step.initial_step) linkLines.push(` _Start --> ${step.name}`);
505
+ if (step.action_name === "ForLoop") {
506
+ linkLines.push(
507
+ ` ${step.name} --> ${step.configuration.for_loop_step_name}`
508
+ );
509
+ } else if (stepNames.includes(step.next_step)) {
510
+ linkLines.push(` ${step.name} --> ${step.next_step}`);
511
+ } else if (step.next_step) {
512
+ for (const otherStep of stepNames)
513
+ if (step.next_step.includes(otherStep))
514
+ linkLines.push(` ${step.name} --> ${otherStep}`);
515
+ }
516
+ if (step.action_name === "EndForLoop") {
517
+ // TODO this is not correct. improve.
518
+ let forStep;
519
+ for (let i = step_ix; i >= 0; i -= 1) {
520
+ if (steps[i].action_name === "ForLoop") {
521
+ forStep = steps[i];
522
+ break;
523
+ }
524
+ }
525
+ if (forStep) linkLines.push(` ${step.name} --> ${forStep.name}`);
526
+ }
527
+ step_ix += 1;
528
+ }
529
+ const fc =
530
+ "flowchart TD\n" + nodeLines.join("\n") + "\n" + linkLines.join("\n");
531
+ return fc;
532
+ }
533
+
534
+ const getWorkflowConfig = async (req, id, table, trigger) => {
535
+ let steps = await WorkflowStep.find(
536
+ { trigger_id: trigger.id },
537
+ { orderBy: "id" }
538
+ );
539
+ const initial_step = steps.find((step) => step.initial_step);
540
+ if (initial_step)
541
+ steps = [initial_step, ...steps.filter((s) => !s.initial_step)];
542
+ const trigCfgForm = new Form({
543
+ action: addOnDoneRedirect(`/actions/configure/${id}`, req),
544
+ onChange: "saveAndContinue(this)",
545
+ noSubmitButton: true,
546
+ formStyle: "vert",
547
+ fields: [
548
+ {
549
+ name: "save_traces",
550
+ label: "Save step traces for each run",
551
+ type: "Bool",
552
+ },
553
+ ],
554
+ });
555
+ trigCfgForm.values = trigger.configuration;
556
+ return (
557
+ /*ul(
558
+ steps.map((step) =>
559
+ li(
560
+ a(
561
+ {
562
+ href: `/actions/stepedit/${trigger.id}/${step.id}`,
563
+ },
564
+ step.name
565
+ )
566
+ )
567
+ )
568
+ ) +*/
569
+ pre({ class: "mermaid" }, genWorkflowDiagram(steps)) +
570
+ script(
571
+ { defer: "defer" },
572
+ `function tryAddWFNodes() {
573
+ const ns = $("g.node");
574
+ if(!ns.length) setTimeout(tryAddWFNodes, 200)
575
+ else {
576
+ $("g.node").on("click", (e)=>{
577
+ const $e = $(e.target || e).closest("g.node")
578
+ const cls = $e.attr('class')
579
+ if(!cls || !cls.includes("wfstep")) return;
580
+ const id = cls.split(" ").find(c=>c.startsWith("wfstep")).
581
+ substr(6);
582
+ location.href = '/actions/stepedit/${trigger.id}/'+id;
583
+ //console.log($e.attr('class'), id)
584
+ })
585
+ }
586
+ }
587
+ window.addEventListener('DOMContentLoaded',tryAddWFNodes)`
588
+ ) +
589
+ a(
590
+ {
591
+ href: `/actions/stepedit/${trigger.id}?name=step${steps.length + 1}${
592
+ initial_step ? "" : "&initial_step=true"
593
+ }`,
594
+ class: "btn btn-primary",
595
+ },
596
+ i({ class: "fas fa-plus me-2" }),
597
+ "Add step"
598
+ ) +
599
+ a(
600
+ {
601
+ href: `/actions/runs/?trigger=${trigger.id}`,
602
+ class: "d-block",
603
+ },
604
+ "Show runs »"
605
+ ) +
606
+ renderForm(trigCfgForm, req.csrfToken())
607
+ );
608
+ };
609
+
610
+ const jsIdentifierValidator = (s) => {
611
+ if (!s) return "An identifier is required";
612
+ if (s.includes(" ")) return "Spaces not allowd";
613
+ let badc = "'#:/\\@()[]{}\"!%^&*-+*~<>,.?|"
614
+ .split("")
615
+ .find((c) => s.includes(c));
616
+
617
+ if (badc) return `Character ${badc} not allowed`;
618
+ };
619
+
620
+ const getWorkflowStepForm = async (trigger, req, step_id) => {
621
+ const table = trigger.table_id ? Table.findOne(trigger.table_id) : null;
622
+ let stateActions = getState().actions;
623
+ const stateActionKeys = Object.entries(stateActions)
624
+ .filter(([k, v]) => !v.disableInWorkflow)
625
+ .map(([k, v]) => k);
626
+
627
+ const actionConfigFields = [];
628
+ for (const [name, action] of Object.entries(stateActions)) {
629
+ if (!stateActionKeys.includes(name)) continue;
630
+ try {
631
+ const cfgFields = await getActionConfigFields(action, table, {
632
+ mode: "workflow",
633
+ });
634
+
635
+ for (const field of cfgFields) {
636
+ const cfgFld = {
637
+ ...field,
638
+ showIf: {
639
+ wf_action_name: name,
640
+ ...(field.showIf || {}),
641
+ },
642
+ };
643
+ if (cfgFld.input_type === "code") cfgFld.input_type = "textarea";
644
+ actionConfigFields.push(cfgFld);
645
+ }
646
+ } catch {}
647
+ }
648
+ const actionsNotRequiringRow = Trigger.action_options({
649
+ notRequireRow: true,
650
+ noMultiStep: true,
651
+ builtInLabel: "Workflow Actions",
652
+ builtIns: [
653
+ "SetContext",
654
+ "TableQuery",
655
+ "Output",
656
+ "WaitUntil",
657
+ "UserForm",
658
+ "WaitNextTick",
659
+ ],
660
+ forWorkflow: true,
661
+ });
662
+
663
+ actionConfigFields.push({
664
+ label: "Form header",
665
+ name: "form_header",
666
+ type: "String",
667
+ showIf: { wf_action_name: "UserForm" },
668
+ });
669
+ actionConfigFields.push({
670
+ label: "User ID",
671
+ name: "user_id_expression",
672
+ type: "String",
673
+ sublabel: "Optional. If blank assigned to user starting the workflow",
674
+ showIf: { wf_action_name: "UserForm" },
675
+ });
676
+ actionConfigFields.push({
677
+ label: "Resume at",
678
+ name: "resume_at",
679
+ sublabel:
680
+ "JavaScript expression for the time to resume. <code>moment</code> is in scope.",
681
+ type: "String",
682
+ showIf: { wf_action_name: "WaitUntil" },
683
+ });
684
+ actionConfigFields.push({
685
+ label: "Context values",
686
+ name: "ctx_values",
687
+ sublabel:
688
+ "JavaScript object expression for the variables to set. Example <code>{x: 5, y:y+1}</code> will set x to 5 and increment existing context variable y",
689
+ type: "String",
690
+ fieldview: "textarea",
691
+ class: "validate-expression",
692
+ default: "{}",
693
+ showIf: { wf_action_name: "SetContext" },
694
+ });
695
+ actionConfigFields.push({
696
+ label: "Output text",
697
+ name: "output_text",
698
+ sublabel:
699
+ "Message shown to the user. Can contain HTML tags and use interpolations {{ }} to access the context",
700
+ type: "String",
701
+ fieldview: "textarea",
702
+ showIf: { wf_action_name: "Output" },
703
+ });
704
+ actionConfigFields.push({
705
+ label: "Table",
706
+ name: "query_table",
707
+ type: "String",
708
+ required: true,
709
+ attributes: { options: (await Table.find()).map((t) => t.name) },
710
+ showIf: { wf_action_name: "TableQuery" },
711
+ });
712
+ actionConfigFields.push({
713
+ label: "Query",
714
+ name: "query_object",
715
+ sublabel: "Where object, example <code>{manager: 1}</code>",
716
+ type: "String",
717
+ required: true,
718
+ class: "validate-expression",
719
+ default: "{}",
720
+ showIf: { wf_action_name: "TableQuery" },
721
+ });
722
+ actionConfigFields.push({
723
+ label: "Variable",
724
+ name: "query_variable",
725
+ sublabel: "Context variable to write to query results to",
726
+ type: "String",
727
+ required: true,
728
+ validator: jsIdentifierValidator,
729
+ showIf: { wf_action_name: "TableQuery" },
730
+ });
731
+ actionConfigFields.push(
732
+ new FieldRepeat({
733
+ name: "user_form_questions",
734
+ showIf: { wf_action_name: "UserForm" },
735
+ fields: [
736
+ {
737
+ label: "Label",
738
+ name: "label",
739
+ type: "String",
740
+ sublabel:
741
+ "The text that will shown to the user above the input elements",
742
+ },
743
+ {
744
+ label: "Variable name",
745
+ name: "var_name",
746
+ type: "String",
747
+ sublabel:
748
+ "The answer will be set in the context with this variable name",
749
+ validator: jsIdentifierValidator,
750
+ },
751
+ {
752
+ label: "Input Type",
753
+ name: "qtype",
754
+ type: "String",
755
+ required: true,
756
+ attributes: {
757
+ options: [
758
+ "Yes/No",
759
+ "Checkbox",
760
+ "Free text",
761
+ "Multiple choice",
762
+ //"Multiple checks",
763
+ "Integer",
764
+ "Float",
765
+ //"File upload",
766
+ ],
767
+ },
768
+ },
769
+ {
770
+ label: "Options",
771
+ name: "options",
772
+ type: "String",
773
+ sublabel: "Comma separated list of multiple choice options",
774
+ showIf: { qtype: ["Multiple choice", "Multiple checks"] },
775
+ },
776
+ ],
777
+ })
778
+ );
779
+
780
+ const form = new Form({
781
+ action: addOnDoneRedirect(`/actions/stepedit/${trigger.id}`, req),
782
+ onChange: "saveAndContinueIfValid(this)",
783
+ submitLabel: req.__("Done"),
784
+ additionalButtons: step_id
785
+ ? [
786
+ {
787
+ label: req.__("Delete"),
788
+ class: "btn btn-outline-danger",
789
+ onclick: `ajax_post('/actions/delete-step/${+step_id}')`,
790
+ afterSave: true,
791
+ },
792
+ ]
793
+ : undefined,
794
+ fields: [
795
+ {
796
+ name: "wf_step_name",
797
+ label: req.__("Step name"),
798
+ type: "String",
799
+ required: true,
800
+ sublabel: "An identifier by which this step can be referred to.",
801
+ validator: jsIdentifierValidator,
802
+ },
803
+ {
804
+ name: "wf_initial_step",
805
+ label: req.__("Initial step"),
806
+ sublabel: "Is this the first step in the workflow?",
807
+ type: "Bool",
808
+ },
809
+ {
810
+ name: "wf_only_if",
811
+ label: req.__("Only if..."),
812
+ sublabel:
813
+ "Optional JavaScript expression based on the run context. If given, the chosen action will only be executed if evaluates to true",
814
+ type: "String",
815
+ },
816
+ {
817
+ name: "wf_next_step",
818
+ label: req.__("Next step"),
819
+ type: "String",
820
+ class: "validate-expression",
821
+ sublabel:
822
+ "Name of next step. Can be a JavaScript expression based on the run context. Blank if final step",
823
+ },
824
+ {
825
+ name: "wf_action_name",
826
+ label: req.__("Action"),
827
+ type: "String",
828
+ required: true,
829
+ attributes: {
830
+ options: actionsNotRequiringRow,
831
+ },
832
+ },
833
+ ...actionConfigFields,
834
+ ],
835
+ });
836
+ form.hidden("wf_step_id");
837
+ if (step_id) {
838
+ const step = await WorkflowStep.findOne({ id: step_id });
839
+ if (!step) throw new Error("Step not found");
840
+ form.values = {
841
+ wf_step_id: step.id,
842
+ wf_step_name: step.name,
843
+ wf_initial_step: step.initial_step,
844
+ wf_only_if: step.only_if,
845
+ wf_action_name: step.action_name,
846
+ wf_next_step: step.next_step,
847
+ ...step.configuration,
848
+ };
849
+ }
850
+ return form;
851
+ };
852
+
470
853
  const getMultiStepForm = async (req, id, table) => {
471
854
  let stateActions = getState().actions;
472
855
  const stateActionKeys = Object.entries(stateActions)
@@ -579,7 +962,35 @@ router.get(
579
962
  { href: `/actions/testrun/${id}`, class: "ms-2" },
580
963
  req.__("Test run") + "&nbsp;&raquo;"
581
964
  );
582
- if (trigger.action === "Multi-step action") {
965
+ if (trigger.action === "Workflow") {
966
+ const wfCfg = await getWorkflowConfig(req, id, table, trigger);
967
+ send_events_page({
968
+ res,
969
+ req,
970
+ active_sub: "Triggers",
971
+ sub2_page: "Configure",
972
+ page_title: req.__(`%s configuration`, trigger.name),
973
+ headers: [
974
+ {
975
+ script: `/static_assets/${db.connectObj.version_tag}/mermaid.min.js`,
976
+ },
977
+ {
978
+ headerTag: `<script type="module">mermaid.initialize({securityLevel: 'loose'${
979
+ getState().getLightDarkMode(req.user) === "dark"
980
+ ? ",theme: 'dark',"
981
+ : ""
982
+ }});</script>`,
983
+ },
984
+ ],
985
+ contents: {
986
+ type: "card",
987
+ titleAjaxIndicator: true,
988
+ title: req.__("Configure trigger %s", trigger.name),
989
+ subtitle,
990
+ contents: wfCfg,
991
+ },
992
+ });
993
+ } else if (trigger.action === "Multi-step action") {
583
994
  const form = await getMultiStepForm(req, id, table);
584
995
  form.values = trigger.configuration;
585
996
  send_events_page({
@@ -725,6 +1136,11 @@ router.post(
725
1136
  let form;
726
1137
  if (trigger.action === "Multi-step action") {
727
1138
  form = await getMultiStepForm(req, id, table);
1139
+ } else if (trigger.action === "Workflow") {
1140
+ form = new Form({
1141
+ action: `/actions/configure/${id}`,
1142
+ fields: [{ name: "save_traces", label: "Save traces", type: "Bool" }],
1143
+ });
728
1144
  } else {
729
1145
  const cfgFields = await getActionConfigFields(action, table, {
730
1146
  mode: "trigger",
@@ -830,6 +1246,7 @@ router.get(
830
1246
  table,
831
1247
  row,
832
1248
  req,
1249
+ interactive: true,
833
1250
  ...(row || {}),
834
1251
  Table,
835
1252
  user: req.user,
@@ -848,7 +1265,13 @@ router.get(
848
1265
  ? script(domReady(`common_done(${JSON.stringify(runres)})`))
849
1266
  : ""
850
1267
  );
851
- res.redirect(`/actions/`);
1268
+ if (trigger.action === "Workflow")
1269
+ res.redirect(
1270
+ runres?.__wf_run_id
1271
+ ? `/actions/run/${runres?.__wf_run_id}`
1272
+ : `/actions/runs/?trigger=${trigger.id}`
1273
+ );
1274
+ else res.redirect(`/actions/`);
852
1275
  } else {
853
1276
  send_events_page({
854
1277
  res,
@@ -909,3 +1332,513 @@ router.post(
909
1332
  res.redirect(`/actions`);
910
1333
  })
911
1334
  );
1335
+
1336
+ /**
1337
+ * @name post/clone/:id
1338
+ * @function
1339
+ * @memberof module:routes/actions~actionsRouter
1340
+ * @function
1341
+ */
1342
+ router.get(
1343
+ "/stepedit/:trigger_id/:step_id?",
1344
+ isAdmin,
1345
+ error_catcher(async (req, res) => {
1346
+ const { trigger_id, step_id } = req.params;
1347
+ const { initial_step, name } = req.query;
1348
+ const trigger = await Trigger.findOne({ id: trigger_id });
1349
+ const form = await getWorkflowStepForm(trigger, req, step_id);
1350
+
1351
+ if (initial_step) form.values.wf_initial_step = true;
1352
+ if (name) form.values.wf_step_name = name;
1353
+ send_events_page({
1354
+ res,
1355
+ req,
1356
+ active_sub: "Triggers",
1357
+ sub2_page: "Configure",
1358
+ page_title: req.__(`%s configuration`, trigger.name),
1359
+ contents: {
1360
+ type: "card",
1361
+ titleAjaxIndicator: true,
1362
+ title: req.__(
1363
+ "Configure trigger %s",
1364
+ a({ href: `/actions/configure/${trigger.id}` }, trigger.name)
1365
+ ),
1366
+ contents: renderForm(form, req.csrfToken()),
1367
+ },
1368
+ });
1369
+ })
1370
+ );
1371
+
1372
+ router.post(
1373
+ "/stepedit/:trigger_id",
1374
+ isAdmin,
1375
+ error_catcher(async (req, res) => {
1376
+ const { trigger_id } = req.params;
1377
+ const trigger = await Trigger.findOne({ id: trigger_id });
1378
+ const form = await getWorkflowStepForm(trigger, req);
1379
+ form.validate(req.body);
1380
+ if (form.hasErrors) {
1381
+ if (req.xhr) {
1382
+ res.json({ error: form.errorSummary });
1383
+ } else
1384
+ send_events_page({
1385
+ res,
1386
+ req,
1387
+ active_sub: "Triggers",
1388
+ sub2_page: "Configure",
1389
+ page_title: req.__(`%s configuration`, trigger.name),
1390
+ contents: {
1391
+ type: "card",
1392
+ titleAjaxIndicator: true,
1393
+ title: req.__(
1394
+ "Configure trigger %s",
1395
+ a({ href: `/actions/configure/${trigger.id}` }, trigger.name)
1396
+ ),
1397
+ contents: renderForm(form, req.csrfToken()),
1398
+ },
1399
+ });
1400
+ return;
1401
+ }
1402
+ const {
1403
+ wf_step_name,
1404
+ wf_action_name,
1405
+ wf_next_step,
1406
+ wf_initial_step,
1407
+ wf_only_if,
1408
+ wf_step_id,
1409
+ ...configuration
1410
+ } = form.values;
1411
+ Object.entries(configuration).forEach(([k, v]) => {
1412
+ if (v === null) delete configuration[k];
1413
+ });
1414
+ const step = {
1415
+ name: wf_step_name,
1416
+ action_name: wf_action_name,
1417
+ next_step: wf_next_step,
1418
+ only_if: wf_only_if,
1419
+ initial_step: wf_initial_step,
1420
+ trigger_id,
1421
+ configuration,
1422
+ };
1423
+ try {
1424
+ if (wf_step_id && wf_step_id !== "undefined") {
1425
+ const wfStep = new WorkflowStep({ id: wf_step_id, ...step });
1426
+
1427
+ await wfStep.update(step);
1428
+ if (req.xhr) res.json({ success: "ok" });
1429
+ else {
1430
+ req.flash("success", req.__("Step saved"));
1431
+ res.redirect(`/actions/configure/${step.trigger_id}`);
1432
+ }
1433
+ } else {
1434
+ //insert
1435
+
1436
+ const id = await WorkflowStep.create(step);
1437
+ if (req.xhr)
1438
+ res.json({ success: "ok", set_fields: { wf_step_id: id } });
1439
+ else {
1440
+ req.flash("success", req.__("Step saved"));
1441
+ res.redirect(`/actions/configure/${step.trigger_id}`);
1442
+ }
1443
+ }
1444
+ } catch (e) {
1445
+ const emsg =
1446
+ e.message ===
1447
+ 'duplicate key value violates unique constraint "workflow_steps_name_uniq"'
1448
+ ? `A step with the name ${wf_step_name} already exists`
1449
+ : e.message;
1450
+ if (req.xhr) res.json({ error: emsg });
1451
+ else {
1452
+ req.flash("error", emsg);
1453
+ res.redirect(`/actions/configure/${step.trigger_id}`);
1454
+ }
1455
+ }
1456
+ })
1457
+ );
1458
+
1459
+ router.post(
1460
+ "/delete-step/:step_id",
1461
+ isAdmin,
1462
+ error_catcher(async (req, res) => {
1463
+ const { step_id } = req.params;
1464
+ const step = await WorkflowStep.findOne({ id: step_id });
1465
+ await step.delete();
1466
+ res.json({ goto: `/actions/configure/${step.trigger_id}` });
1467
+ })
1468
+ );
1469
+
1470
+ router.get(
1471
+ "/runs",
1472
+ isAdmin,
1473
+ error_catcher(async (req, res) => {
1474
+ const trNames = {};
1475
+ const { _page, trigger } = req.query;
1476
+ for (const trig of await Trigger.find({ action: "Workflow" }))
1477
+ trNames[trig.id] = trig.name;
1478
+ const q = {};
1479
+ const selOpts = { orderBy: "started_at", orderDesc: true, limit: 20 };
1480
+ if (_page) selOpts.offset = 20 * (parseInt(_page) - 1);
1481
+ if (trigger) q.trigger_id = trigger;
1482
+ const runs = await WorkflowRun.find(q, selOpts);
1483
+ const count = await WorkflowRun.count(q);
1484
+
1485
+ const wfTable = mkTable(
1486
+ [
1487
+ { label: "Trigger", key: (run) => trNames[run.trigger_id] },
1488
+ { label: "Started", key: (run) => localeDateTime(run.started_at) },
1489
+ { label: "Status", key: "status" },
1490
+ {
1491
+ label: "",
1492
+ key: (run) => {
1493
+ switch (run.status) {
1494
+ case "Running":
1495
+ return run.current_step;
1496
+ case "Error":
1497
+ return run.error;
1498
+ case "Waiting":
1499
+ if (run.wait_info?.form || run.wait_info.output)
1500
+ return a(
1501
+ { href: `/actions/fill-workflow-form/${run.id}` },
1502
+ run.wait_info.output ? "Show " : "Fill ",
1503
+ run.current_step
1504
+ );
1505
+ return run.current_step;
1506
+ default:
1507
+ return "";
1508
+ }
1509
+ },
1510
+ },
1511
+ ],
1512
+ runs,
1513
+ {
1514
+ onRowSelect: (row) => `location.href='/actions/run/${row.id}'`,
1515
+ pagination: {
1516
+ current_page: parseInt(_page) || 1,
1517
+ pages: Math.ceil(count / 20),
1518
+ get_page_link: (n) => `gopage(${n}, 20)`,
1519
+ },
1520
+ }
1521
+ );
1522
+ send_events_page({
1523
+ res,
1524
+ req,
1525
+ active_sub: "Workflow runs",
1526
+ page_title: req.__(`Workflow runs`),
1527
+ contents: {
1528
+ type: "card",
1529
+ titleAjaxIndicator: true,
1530
+ title: req.__("Workflow runs"),
1531
+ contents: wfTable,
1532
+ },
1533
+ });
1534
+ })
1535
+ );
1536
+
1537
+ router.get(
1538
+ "/run/:id",
1539
+ isAdmin,
1540
+ error_catcher(async (req, res) => {
1541
+ const { id } = req.params;
1542
+
1543
+ const run = await WorkflowRun.findOne({ id });
1544
+ const trigger = await Trigger.findOne({ id: run.trigger_id });
1545
+ const traces = await WorkflowTrace.find(
1546
+ { run_id: run.id },
1547
+ { orderBy: "id" }
1548
+ );
1549
+ const traces_accordion_items = div(
1550
+ { class: "accordion" },
1551
+ traces.map((trace, ix) =>
1552
+ div(
1553
+ { class: "accordion-item" },
1554
+
1555
+ h2(
1556
+ { class: "accordion-header", id: `trhead${ix}` },
1557
+ button(
1558
+ {
1559
+ class: ["accordion-button", "collapsed"],
1560
+ type: "button",
1561
+
1562
+ "data-bs-toggle": "collapse",
1563
+ "data-bs-target": `#trtab${ix}`,
1564
+ "aria-expanded": "false",
1565
+ "aria-controls": `trtab${ix}`,
1566
+ },
1567
+ `${ix + 1}: ${trace.step_name_run}`
1568
+ )
1569
+ ),
1570
+ div(
1571
+ {
1572
+ class: ["accordion-collapse", "collapse"],
1573
+ id: `trtab${ix}`,
1574
+ "aria-labelledby": `trhead${ix}`,
1575
+ },
1576
+ div(
1577
+ { class: ["accordion-body"] },
1578
+ table(
1579
+ { class: "table table-condensed w-unset" },
1580
+ tbody(
1581
+ tr(
1582
+ th("Started at"),
1583
+ td(localeDateTime(trace.step_started_at))
1584
+ ),
1585
+ tr(th("Elapsed"), td(trace.elapsed, "s")),
1586
+ tr(th("Run by user"), td(trace.user_id)),
1587
+ tr(th("Status"), td(trace.status)),
1588
+ trace.status === "Waiting"
1589
+ ? tr(th("Waiting for"), td(JSON.stringify(trace.wait_info)))
1590
+ : null,
1591
+ tr(
1592
+ th("Context"),
1593
+ td(pre(text(JSON.stringify(trace.context, null, 2))))
1594
+ )
1595
+ )
1596
+ )
1597
+ )
1598
+ )
1599
+ )
1600
+ )
1601
+ );
1602
+
1603
+ send_events_page({
1604
+ res,
1605
+ req,
1606
+ active_sub: "Workflow runs",
1607
+ page_title: req.__(`Workflow runs`),
1608
+ sub2_page: trigger.name,
1609
+ contents: {
1610
+ above: [
1611
+ {
1612
+ type: "card",
1613
+ titleAjaxIndicator: true,
1614
+ title: req.__("Workflow run"),
1615
+ contents:
1616
+ table(
1617
+ { class: "table table-condensed w-unset" },
1618
+ tbody(
1619
+ tr(th("Run ID"), td(run.id)),
1620
+ tr(
1621
+ th("Trigger"),
1622
+ td(
1623
+ a(
1624
+ { href: `/actions/configure/${trigger.id}` },
1625
+ trigger.name
1626
+ )
1627
+ )
1628
+ ),
1629
+ tr(th("Started at"), td(localeDateTime(run.started_at))),
1630
+ tr(th("Started by user"), td(run.started_by)),
1631
+ tr(th("Status"), td(run.status)),
1632
+ run.status === "Waiting"
1633
+ ? tr(th("Waiting for"), td(JSON.stringify(run.wait_info)))
1634
+ : null,
1635
+ run.status === "Error"
1636
+ ? tr(th("Error message"), td(run.error))
1637
+ : null,
1638
+ tr(
1639
+ th("Context"),
1640
+ td(pre(text(JSON.stringify(run.context, null, 2))))
1641
+ )
1642
+ )
1643
+ ) + post_delete_btn("/actions/delete-run/" + run.id, req),
1644
+ },
1645
+ ...(traces.length
1646
+ ? [
1647
+ {
1648
+ type: "card",
1649
+ title: req.__("Step traces"),
1650
+ contents: traces_accordion_items,
1651
+ },
1652
+ ]
1653
+ : []),
1654
+ ],
1655
+ },
1656
+ });
1657
+ })
1658
+ );
1659
+
1660
+ router.post(
1661
+ "/delete-run/:id",
1662
+ isAdmin,
1663
+ error_catcher(async (req, res) => {
1664
+ const { id } = req.params;
1665
+
1666
+ const run = await WorkflowRun.findOne({ id });
1667
+ await run.delete();
1668
+ res.redirect("/actions/runs");
1669
+ })
1670
+ );
1671
+
1672
+ const getWorkflowStepUserForm = async (run, trigger, step, user) => {
1673
+ const qTypeToField = (q) => {
1674
+ switch (q.qtype) {
1675
+ case "Yes/No":
1676
+ return {
1677
+ type: "String",
1678
+ attributes: { options: "Yes,No" },
1679
+ fieldview: "radio_group",
1680
+ };
1681
+ case "Checkbox":
1682
+ return { type: "Bool" };
1683
+ case "Free text":
1684
+ return { type: "String" };
1685
+ case "Multiple choice":
1686
+ return {
1687
+ type: "String",
1688
+ attributes: { options: q.options },
1689
+ fieldview: "radio_group",
1690
+ };
1691
+ case "Integer":
1692
+ return { type: "Integer" };
1693
+ case "Float":
1694
+ return { type: "Float" };
1695
+ default:
1696
+ return {};
1697
+ }
1698
+ };
1699
+
1700
+ const form = new Form({
1701
+ action: `/actions/fill-workflow-form/${run.id}`,
1702
+ blurb: run.wait_info.output || step.configuration?.form_header || "",
1703
+ formStyle: run.wait_info.output ? "vert" : undefined,
1704
+ fields: (step.configuration.user_form_questions || []).map((q) => ({
1705
+ label: q.label,
1706
+ name: q.var_name,
1707
+ ...qTypeToField(q),
1708
+ })),
1709
+ });
1710
+ return form;
1711
+ };
1712
+
1713
+ router.get(
1714
+ "/fill-workflow-form/:id",
1715
+ error_catcher(async (req, res) => {
1716
+ const { id } = req.params;
1717
+
1718
+ const run = await WorkflowRun.findOne({ id });
1719
+
1720
+ if (!run.user_allowed_to_fill_form(req.user)) {
1721
+ if (req.xhr) res.json({ error: "Not authorized" });
1722
+ else {
1723
+ req.flash("danger", req.__("Not authorized"));
1724
+ res.redirect("/");
1725
+ }
1726
+ return;
1727
+ }
1728
+
1729
+ const trigger = await Trigger.findOne({ id: run.trigger_id });
1730
+ const step = await WorkflowStep.findOne({
1731
+ trigger_id: trigger.id,
1732
+ name: run.current_step,
1733
+ });
1734
+
1735
+ const form = await getWorkflowStepUserForm(run, trigger, step, req.user);
1736
+ if (req.xhr) form.xhrSubmit = true;
1737
+ const title = run.wait_info.output ? "Workflow output" : "Fill form";
1738
+ res.sendWrap(title, renderForm(form, req.csrfToken()));
1739
+ })
1740
+ );
1741
+
1742
+ router.post(
1743
+ "/fill-workflow-form/:id",
1744
+ error_catcher(async (req, res) => {
1745
+ const { id } = req.params;
1746
+
1747
+ const run = await WorkflowRun.findOne({ id });
1748
+ if (!run.user_allowed_to_fill_form(req.user)) {
1749
+ if (req.xhr) res.json({ error: "Not authorized" });
1750
+ else {
1751
+ req.flash("danger", req.__("Not authorized"));
1752
+ res.redirect("/");
1753
+ }
1754
+ return;
1755
+ }
1756
+
1757
+ const trigger = await Trigger.findOne({ id: run.trigger_id });
1758
+ const step = await WorkflowStep.findOne({
1759
+ trigger_id: trigger.id,
1760
+ name: run.current_step,
1761
+ });
1762
+
1763
+ const form = await getWorkflowStepUserForm(run, trigger, step, req.user);
1764
+ form.validate(req.body);
1765
+ if (form.hasErrors) {
1766
+ const title = "Fill form";
1767
+ res.sendWrap(title, renderForm(form, req.csrfToken()));
1768
+ } else {
1769
+ await run.provide_form_input(form.values);
1770
+ await run.run({
1771
+ user: req.user,
1772
+ trace: trigger.configuration?.save_traces,
1773
+ });
1774
+ if (req.xhr) {
1775
+ const retDirs = await run.popReturnDirectives();
1776
+ res.json({ success: "ok", ...retDirs });
1777
+ } else {
1778
+ if (run.context.goto) res.redirect(run.context.goto);
1779
+ else res.redirect("/");
1780
+ }
1781
+ }
1782
+ })
1783
+ );
1784
+
1785
+ router.post(
1786
+ "/resume-workflow/:id",
1787
+ error_catcher(async (req, res) => {
1788
+ const { id } = req.params;
1789
+
1790
+ const run = await WorkflowRun.findOne({ id });
1791
+ //TODO session if not logged in
1792
+ if (run.started_by !== req.user?.id) {
1793
+ if (req.xhr) res.json({ error: "Not authorized" });
1794
+ else {
1795
+ req.flash("danger", req.__("Not authorized"));
1796
+ res.redirect("/");
1797
+ }
1798
+ return;
1799
+ }
1800
+ const trigger = await Trigger.findOne({ id: run.trigger_id });
1801
+ const runResult = await run.run({
1802
+ user: req.user,
1803
+ interactive: true,
1804
+ trace: trigger.configuration?.save_traces,
1805
+ });
1806
+ if (req.xhr) {
1807
+ if (
1808
+ runResult &&
1809
+ typeof runResult === "object" &&
1810
+ Object.keys(runResult).length
1811
+ ) {
1812
+ res.json({ success: "ok", ...runResult });
1813
+ return;
1814
+ }
1815
+ const retDirs = await run.popReturnDirectives();
1816
+ res.json({ success: "ok", ...retDirs });
1817
+ } else {
1818
+ if (run.context.goto) res.redirect(run.context.goto);
1819
+ else res.redirect("/");
1820
+ }
1821
+ })
1822
+ );
1823
+
1824
+ /*
1825
+
1826
+ WORKFLOWS TODO
1827
+
1828
+ delete is not always working?
1829
+ help file to explain steps, and context
1830
+
1831
+ action explainer
1832
+ workflow actions: ForLoop, EndForLoop, ReadFile, WriteFile, APIResponse
1833
+
1834
+ interactive workflows for not logged in
1835
+ correctly suggest new step name
1836
+ show end node in diagram
1837
+
1838
+ Error handlers
1839
+
1840
+ show unconnected steps
1841
+ why is code not initialising
1842
+ drag and drop edges
1843
+
1844
+ */