@saltcorn/history-control 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/diffview.js ADDED
@@ -0,0 +1,149 @@
1
+ const Field = require("@saltcorn/data/models/field");
2
+ const Table = require("@saltcorn/data/models/table");
3
+ const Form = require("@saltcorn/data/models/form");
4
+ const User = require("@saltcorn/data/models/user");
5
+ const View = require("@saltcorn/data/models/view");
6
+ const Workflow = require("@saltcorn/data/models/workflow");
7
+ const HtmlDiff = require("htmldiff-js");
8
+ const {
9
+ text,
10
+ div,
11
+ h3,
12
+ style,
13
+ a,
14
+ script,
15
+ pre,
16
+ domReady,
17
+ p,
18
+ i,
19
+ select,
20
+ option,
21
+ } = require("@saltcorn/markup/tags");
22
+ const { radio_group, checkbox_group } = require("@saltcorn/markup/helpers");
23
+ const moment = require("moment");
24
+
25
+ const get_state_fields = () => [
26
+ {
27
+ name: "id",
28
+ type: "Integer",
29
+ required: true,
30
+ primary_key: true,
31
+ },
32
+ ];
33
+
34
+ const configuration_workflow = (req) =>
35
+ new Workflow({
36
+ steps: [
37
+ {
38
+ name: "Difference Field",
39
+ form: async (context) => {
40
+ const table = await Table.findOne({ id: context.table_id });
41
+ const field_options = table.fields
42
+ .filter((f) => f.type?.name === "String" || f.type?.name === "HTML")
43
+ .map((f) => f.name);
44
+ return new Form({
45
+ fields: [
46
+ {
47
+ name: "diff_field",
48
+ label: "Difference field",
49
+ sublabel: "String or HTML field to show differences for",
50
+ type: "String",
51
+ attributes: {
52
+ options: field_options,
53
+ },
54
+ },
55
+ {
56
+ name: "date_format",
57
+ label: "Date format",
58
+ type: "String",
59
+ sublabel: "moment.js format specifier",
60
+ },
61
+ ],
62
+ });
63
+ },
64
+ },
65
+ ],
66
+ });
67
+
68
+ const run = async (
69
+ table_id,
70
+ viewname,
71
+ { diff_field, date_format },
72
+ state,
73
+ extraArgs
74
+ ) => {
75
+ const table = await Table.findOne({ id: table_id });
76
+
77
+ const cmpMode = state.diffcmp || "Previous";
78
+ //compare to: Current, Previous, No comparison
79
+ const cmpSel = radio_group({
80
+ options: ["Previous", "Latest", "No comparison"],
81
+ name: "diff_cmp_sel",
82
+ value: cmpMode,
83
+ inline: true,
84
+ onChange: `change_cmp_sel(event)`,
85
+ });
86
+ const id = state[table.pk_name];
87
+ if (!id) return `Need id`;
88
+ let hist = await table.get_history(id);
89
+ if (!hist || !hist.length) return "No versions recorded";
90
+ hist = hist.reverse();
91
+ const chosen_version = state.version || hist[0]?._version;
92
+
93
+ const userIds = new Set(hist.map((h) => h._userid));
94
+ const users = await User.find({ id: { in: [...userIds] } });
95
+ const emails = {};
96
+ users.forEach((u) => (emails[u.id] = u.email));
97
+ const row = hist.find((h) => chosen_version == h._version);
98
+ const verSelect = select(
99
+ {
100
+ onChange: "change_diff_version(event)",
101
+ class: "form-select form-control mb-2",
102
+ },
103
+ hist.map((h) =>
104
+ option(
105
+ { value: h._version, selected: chosen_version == h._version },
106
+ date_format ? moment(h._time).format(date_format) : h._time.toString(),
107
+ " - ",
108
+ emails[h._userid]
109
+ )
110
+ )
111
+ );
112
+
113
+ //restore to this version
114
+
115
+ let diff_html;
116
+ if (cmpMode === "No comparison") diff_html = row[diff_field];
117
+ else {
118
+ const cmpTo =
119
+ cmpMode === "Latest"
120
+ ? hist[0]
121
+ : hist.find((h) => chosen_version - 1 == h._version);
122
+ if (!cmpTo || cmpTo._version == row._version) diff_html = row[diff_field];
123
+ else {
124
+ //const field = table.fields.find((f) => f.name === diff_field);
125
+ const oldH = cmpMode === "Latest" ? row[diff_field] : cmpTo[diff_field];
126
+ const newH = cmpMode === "Latest" ? cmpTo[diff_field] : row[diff_field];
127
+ diff_html = HtmlDiff.default.execute(oldH, newH);
128
+ console.log({ oldH, newH, diff_html });
129
+ }
130
+ }
131
+
132
+ return div(
133
+ div({ class: "d-flex" }, p({ class: "me-2" }, "Compare to:"), cmpSel),
134
+ verSelect,
135
+ diff_html,
136
+ script(
137
+ `function change_cmp_sel(e){set_state_field("diffcmp", e.target.value)}
138
+ function change_diff_version(e){set_state_field("version", e.target.value)}`
139
+ )
140
+ );
141
+ };
142
+
143
+ module.exports = {
144
+ name: "History Field Difference",
145
+ display_state_form: false,
146
+ get_state_fields,
147
+ configuration_workflow,
148
+ run,
149
+ };
package/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  const { features } = require("@saltcorn/data/db/state");
2
+ const Table = require("@saltcorn/data/models/table");
2
3
 
3
4
  // user subscribe action
4
5
  const actions = {
@@ -18,9 +19,47 @@ const actions = {
18
19
  return { reload_page: true };
19
20
  },
20
21
  },
22
+ restore_from_history: {
23
+ requireRow: true,
24
+ run: async ({ table, row, user }) => {
25
+ if (table.provider_name !== "History for database table")
26
+ return {
27
+ error:
28
+ "Only use this action on tables provided by History for database table",
29
+ };
30
+ const real_table = Table.findOne({ name: table.provider_cfg?.table });
31
+ if (!real_table) return { error: "Table not found" };
32
+ if (!real_table.versioned)
33
+ return { error: "History not enabled for table" };
34
+ if (row._deleted) {
35
+ const insRow = {};
36
+ for (const field of real_table.fields) {
37
+ insRow[field.name] = row[field.name];
38
+ }
39
+ await real_table.insertRow(insRow);
40
+ } else {
41
+ const updRow = {};
42
+ for (const field of real_table.fields) {
43
+ if (!field.primary_key) updRow[field.name] = row[field.name];
44
+ }
45
+ await real_table.updateRow(
46
+ updRow,
47
+ row[real_table.pk_name],
48
+ user,
49
+ false,
50
+ undefined,
51
+ row._version
52
+ );
53
+ }
54
+
55
+ return { reload_page: true };
56
+ },
57
+ },
21
58
  };
22
59
 
23
60
  module.exports = {
24
61
  sc_plugin_api_version: 1,
25
62
  actions: features?.table_undo ? actions : undefined,
63
+ table_providers: require("./table-provider.js"),
64
+ viewtemplates: [require("./diffview")],
26
65
  };
package/package.json CHANGED
@@ -1,11 +1,13 @@
1
1
  {
2
2
  "name": "@saltcorn/history-control",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "Allow users to interact with row history",
5
5
  "main": "index.js",
6
6
  "dependencies": {
7
7
  "@saltcorn/data": "^0.8.7",
8
- "@saltcorn/markup": "^0.8.7"
8
+ "@saltcorn/markup": "^0.8.7",
9
+ "htmldiff-js": "1.0.5",
10
+ "moment": "^2.29.4"
9
11
  },
10
12
  "author": "Tom Nielsen",
11
13
  "license": "MIT",
@@ -0,0 +1,130 @@
1
+ const db = require("@saltcorn/data/db");
2
+ const { eval_expression } = require("@saltcorn/data/models/expression");
3
+ const Workflow = require("@saltcorn/data/models/workflow");
4
+ const Form = require("@saltcorn/data/models/form");
5
+ const FieldRepeat = require("@saltcorn/data/models/fieldrepeat");
6
+ const Field = require("@saltcorn/data/models/field");
7
+ const Table = require("@saltcorn/data/models/table");
8
+ const { getState } = require("@saltcorn/data/db/state");
9
+ const { mkTable } = require("@saltcorn/markup");
10
+ const { pre, code } = require("@saltcorn/markup/tags");
11
+
12
+ const configuration_workflow = (req) =>
13
+ new Workflow({
14
+ steps: [
15
+ {
16
+ name: "query",
17
+ form: async () => {
18
+ const tables = await Table.find({ versioned: true });
19
+ return new Form({
20
+ fields: [
21
+ {
22
+ name: "table",
23
+ label: "Table",
24
+ type: "String",
25
+ required: true,
26
+ attributes: {
27
+ options: tables.map((t) => t.name),
28
+ },
29
+ sublabel: "Select a versioned table",
30
+ },
31
+ ],
32
+ });
33
+ },
34
+ },
35
+ ],
36
+ });
37
+ const runQuery = async (cfg, where, opts) => {
38
+ const table = Table.findOne({ name: cfg.table });
39
+ const wheres = [];
40
+ let phIndex = 1;
41
+ const phValues = [];
42
+
43
+ const schemaPrefix = db.getTenantSchemaPrefix();
44
+
45
+ for (const k of Object.keys(where)) {
46
+ if (k === "_is_latest" && where[k]) {
47
+ wheres.push(
48
+ `h._version = (select max(ih._version) from ${schemaPrefix}"${db.sqlsanitize(
49
+ table.name
50
+ )}__history" ih where ih.id = h.id)`
51
+ );
52
+ continue;
53
+ }
54
+ if (k === "_deleted") {
55
+ if (where[k])
56
+ wheres.push(
57
+ `not exists(select id from ${schemaPrefix}"${db.sqlsanitize(
58
+ table.name
59
+ )}" t where t.id = h.id)`
60
+ );
61
+ else
62
+ wheres.push(
63
+ `exists(select id from ${schemaPrefix}"${db.sqlsanitize(
64
+ table.name
65
+ )}" t where t.id = h.id)`
66
+ );
67
+ continue;
68
+ }
69
+ const f = table.getField(k);
70
+ if (f) {
71
+ wheres.push(
72
+ where[k]?.ilike ? `"${k}" ILIKE $${phIndex}` : `"${k}" = $${phIndex}`
73
+ );
74
+ phValues.push(where[k]?.ilike ? where[k]?.ilike : where[k]);
75
+ phIndex += 1;
76
+ }
77
+ }
78
+
79
+ const sql = `select
80
+ _version || '_'|| id as _version_id,
81
+ _version = (select max(ih._version) from ${schemaPrefix}"${db.sqlsanitize(
82
+ table.name
83
+ )}__history" ih where ih.id = h.id) as _is_latest,
84
+ not exists(select id from ${schemaPrefix}"${db.sqlsanitize(
85
+ table.name
86
+ )}" t where t.id = h.id) as _deleted,
87
+ * from ${schemaPrefix}"${db.sqlsanitize(table.name)}__history" h ${
88
+ wheres.length ? ` where ${wheres.join(" AND")}` : ""
89
+ }`;
90
+
91
+ return await db.query(sql, phValues);
92
+ };
93
+ module.exports = {
94
+ "History for database table": {
95
+ configuration_workflow,
96
+ fields: (cfg) => {
97
+ if (!cfg?.table) return [];
98
+
99
+ const table = Table.findOne({ name: cfg.table });
100
+ return [
101
+ { name: "_version_id", type: "String", primary_key: true },
102
+ ...table.fields.map((f) => {
103
+ f.primary_key = false;
104
+ f.validator = undefined;
105
+ if (f.is_fkey) f.type = "Integer";
106
+ else f.type = f.type?.name || f.type;
107
+ return f;
108
+ }),
109
+ { name: "_version", label: "Version", type: "Integer" },
110
+ { name: "_is_latest", label: "Is latest", type: "Bool" },
111
+ { name: "_deleted", label: "Deleted", type: "Bool" },
112
+ { name: "_time", label: "Time", type: "Date" },
113
+ { name: "_userid", label: "User ID", type: "Integer" },
114
+ {
115
+ name: "_restore_of_version",
116
+ label: "Restore of version",
117
+ type: "Integer",
118
+ },
119
+ ];
120
+ },
121
+ get_table: (cfg) => {
122
+ return {
123
+ getRows: async (where, opts) => {
124
+ const qres = await runQuery(cfg, where, opts);
125
+ return qres.rows;
126
+ },
127
+ };
128
+ },
129
+ },
130
+ };