@opengis/fastify-table 1.0.90 → 1.0.91

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.
Files changed (53) hide show
  1. package/Changelog.md +4 -0
  2. package/crud/controllers/deleteCrud.js +22 -19
  3. package/crud/controllers/insert.js +58 -54
  4. package/crud/controllers/update.js +61 -59
  5. package/crud/funcs/dataDelete.js +19 -15
  6. package/crud/funcs/dataInsert.js +30 -24
  7. package/crud/funcs/dataUpdate.js +29 -24
  8. package/crud/funcs/getAccess.js +53 -53
  9. package/crud/funcs/getOpt.js +10 -10
  10. package/crud/funcs/setOpt.js +16 -16
  11. package/crud/funcs/utils/logChanges.js +71 -0
  12. package/crud/index.js +36 -36
  13. package/helper.js +28 -28
  14. package/index.js +97 -97
  15. package/notification/controllers/userNotifications.js +19 -19
  16. package/notification/funcs/addNotification.js +8 -8
  17. package/package.json +1 -1
  18. package/pg/pgClients.js +20 -20
  19. package/policy/funcs/checkPolicy.js +83 -83
  20. package/policy/funcs/sqlInjection.js +33 -33
  21. package/policy/index.js +14 -14
  22. package/redis/client.js +8 -8
  23. package/redis/funcs/redisClients.js +2 -2
  24. package/redis/index.js +19 -19
  25. package/server/migrations/0.sql +78 -78
  26. package/server/migrations/log.sql +63 -26
  27. package/server/templates/form/test.dataset.form.json +411 -411
  28. package/server/templates/table/test.dataset.table.json +28 -28
  29. package/server/templates/table/test.gis.map.table.json +44 -44
  30. package/table/controllers/data.js +103 -103
  31. package/table/controllers/suggest.js +79 -79
  32. package/table/controllers/table.js +52 -49
  33. package/table/controllers/utils/gisIRColumn.js +68 -68
  34. package/table/funcs/getFilterSQL/index.js +75 -75
  35. package/table/funcs/getFilterSQL/util/formatValue.js +142 -142
  36. package/table/funcs/getFilterSQL/util/getCustomQuery.js +13 -13
  37. package/table/funcs/getFilterSQL/util/getFilterQuery.js +73 -73
  38. package/table/funcs/getFilterSQL/util/getOptimizedQuery.js +12 -12
  39. package/table/funcs/getFilterSQL/util/getTableSql.js +34 -34
  40. package/table/funcs/metaFormat/getSelectVal.js +20 -20
  41. package/table/funcs/metaFormat/index.js +28 -28
  42. package/test/api/crud.test.js +88 -88
  43. package/test/api/table.test.js +89 -89
  44. package/test/api/widget.test.js +117 -114
  45. package/test/funcs/crud.test.js +122 -76
  46. package/util/controllers/properties.add.js +57 -51
  47. package/util/controllers/status.monitor.js +8 -8
  48. package/widget/controllers/utils/historyFormat.js +76 -76
  49. package/widget/controllers/utils/obj2db.js +13 -13
  50. package/widget/controllers/widget.del.js +44 -44
  51. package/widget/controllers/widget.get.js +98 -96
  52. package/widget/controllers/widget.set.js +76 -70
  53. package/widget/index.js +40 -40
@@ -1,51 +1,57 @@
1
- import dataInsert from "../../crud/funcs/dataInsert.js";
2
-
3
- const table = 'crm.properties';
4
-
5
- function checkKeyType({ body, key }) {
6
- if (typeof body[key] === 'number' && (!/\D/.test(body[key].toString()) && body[key].toString().length < 10)) {
7
- return { [key]: 'int' };
8
- } else if (typeof body[key] === 'object') {
9
- return { [key]: 'json' };
10
- } else if (Date.parse(body[key], 'yyyy/MM/ddTHH:mm:ss.000Z')) {
11
- return { [key]: 'date' };
12
- }
13
- return { [key]: 'text' };
14
- }
15
-
16
- export default async function addExtraProperties({
17
- pg, params = {}, body = {},
18
- }) {
19
- const { id } = params;
20
- if (!id) {
21
- return { message: 'not enougn params: 1', status: 400 };
22
- }
23
- const extraProperties = Object.keys(body);
24
- if (!extraProperties.length) {
25
- return { message: 'not enougn params: 2', status: 400 };
26
- }
27
-
28
- if (!pg.pk?.[table]) {
29
- return { message: 'table not found: crm.properties', status: 400 };
30
- }
31
-
32
- try {
33
- await pg.query(`delete from crm.properties where object_id=$1`, [id]);
34
- const keyTypeMatch = extraProperties.filter((key) => body[key]).reduce((acc, curr) => Object.assign(acc, checkKeyType({ body, key: curr })), {});
35
- const res = await Promise.all(Object.keys(keyTypeMatch).map(async (key) => {
36
- const propertyType = keyTypeMatch[key];
37
- const { rows = [] } = await dataInsert({
38
- pg, table, data: {
39
- property_type: propertyType,
40
- property_key: key,
41
- object_id: id,
42
- [`property_${propertyType}`]: body[key],
43
- }
44
- });
45
- return { id: rows[0]?.property_id, type: propertyType, value: body[key] };
46
- }));
47
- return { message: { rows: res }, status: 200 };
48
- } catch (err) {
49
- return { error: err.toString(), status: 500 };
50
- }
51
- }
1
+ import dataInsert from '../../crud/funcs/dataInsert.js';
2
+
3
+ const table = 'crm.properties';
4
+
5
+ function checkKeyType({ body, key }) {
6
+ if (typeof body[key] === 'number' && (!/\D/.test(body[key].toString()) && body[key].toString().length < 10)) {
7
+ return { [key]: 'int' };
8
+ } if (typeof body[key] === 'object') {
9
+ return { [key]: 'json' };
10
+ }
11
+ if (Date.parse(body[key], 'yyyy/MM/ddTHH:mm:ss.000Z')) {
12
+ return { [key]: 'date' };
13
+ }
14
+ return { [key]: 'text' };
15
+ }
16
+
17
+ export default async function addExtraProperties({
18
+ pg, funcs, params = {}, body = {}, user = {},
19
+ }) {
20
+ const { id } = params;
21
+ if (!id) {
22
+ return { message: 'not enougn params: 1', status: 400 };
23
+ }
24
+ const extraProperties = Object.keys(body);
25
+ if (!extraProperties.length) {
26
+ return { message: 'not enougn params: 2', status: 400 };
27
+ }
28
+
29
+ if (!pg.pk?.[table]) {
30
+ return { message: 'table not found: crm.properties', status: 400 };
31
+ }
32
+
33
+ try {
34
+ const uid = funcs.config?.auth?.disable ? '1' : user.uid;
35
+ await pg.query('delete from crm.properties where object_id=$1', [id]); // rewrite?
36
+ const keyTypeMatch = extraProperties.filter((key) => body[key]).reduce((acc, curr) => Object.assign(acc, checkKeyType({ body, key: curr })), {});
37
+ const res = await Promise.all(Object.keys(keyTypeMatch).map(async (key) => {
38
+ const propertyType = keyTypeMatch[key];
39
+ const { rows = [] } = await dataInsert({
40
+ pg,
41
+ table,
42
+ data: {
43
+ property_type: propertyType,
44
+ property_key: key,
45
+ object_id: id,
46
+ [`property_${propertyType}`]: body[key],
47
+ },
48
+ uid,
49
+ });
50
+ return { id: rows[0]?.property_id, type: propertyType, value: body[key] };
51
+ }));
52
+ return { message: { rows: res }, status: 200 };
53
+ }
54
+ catch (err) {
55
+ return { error: err.toString(), status: 500 };
56
+ }
57
+ }
@@ -1,8 +1,8 @@
1
- const formatMemoryUsage = (data) => `${Math.round(data / 1024 / 1024 * 100) / 100} MB`;
2
-
3
- export default async function statusMonitor() {
4
- const memoryUsage = process.memoryUsage();
5
- const message = Object.keys(memoryUsage)
6
- .reduce((acc, curr) => Object.assign(acc, { [curr]: formatMemoryUsage(memoryUsage[curr]) }), {});
7
- return { message, status: 200 };
8
- }
1
+ const formatMemoryUsage = (data) => `${Math.round(data / 1024 / 1024 * 100) / 100} MB`;
2
+
3
+ export default async function statusMonitor() {
4
+ const memoryUsage = process.memoryUsage();
5
+ const message = Object.keys(memoryUsage)
6
+ .reduce((acc, curr) => Object.assign(acc, { [curr]: formatMemoryUsage(memoryUsage[curr]) }), {});
7
+ return { message, status: 200 };
8
+ }
@@ -1,76 +1,76 @@
1
- import { readdir } from 'fs/promises';
2
- import { existsSync, readFileSync } from 'fs';
3
-
4
- // import getTemplate from '../../../table/controllers/utils/getTemplate.js';
5
- import getSelect from '../../../table/controllers/utils/getSelect.js';
6
-
7
- const dbData = {};
8
-
9
- // from config??
10
- const allTemplates = { table: {} };
11
-
12
- const historyQ = `select nspname||'.'||relname as table_name, json_agg(json_build_object('name',attname, 'title',coalesce(col_description(attrelid, attnum),attname))) as columns
13
- from pg_attribute a
14
- left join pg_catalog.pg_attrdef d ON (a.attrelid, a.attnum) = (d.adrelid, d.adnum)
15
- JOIN pg_class AS i
16
- ON i.oid = a.attrelid
17
- JOIN pg_namespace AS NS ON i.relnamespace = NS.OID
18
- where a.attnum > 0
19
- and not a.attisdropped
20
- group by nspname||'.'||relname`;
21
-
22
- export default async function historyFormat(rows, table, pg) {
23
- if (!rows?.[0]?.changes) return rows; // old structure
24
- // on startup
25
- if (!allTemplates.table.length) {
26
- const templateDir = './server/templates/table';
27
- const templates = existsSync(templateDir) ? await readdir(templateDir) : [];
28
- templates.forEach((template) => {
29
- const body = JSON.parse(readFileSync(`${templateDir}/${template}`) || '{}');
30
- Object.assign(allTemplates.table, { [template]: body });
31
- });
32
- }
33
-
34
- const progrid = Object.keys(allTemplates.table).find((key) => key.replace('.json', '') === table);
35
- if (!progrid) return rows;
36
- // const body = await getTemplate('table', progrid);
37
- const body = allTemplates.table[progrid];
38
- const tableName = body?.table || table;
39
- if (!tableName) return rows;
40
-
41
- // get DB column description
42
- if (!dbData?.[body.table]?.length) {
43
- const { rows: rows1 } = await pg.query(historyQ);
44
- rows1.forEach((row) => {
45
- dbData[row.table_name] = row.columns;
46
- });
47
- }
48
-
49
- // rewrite!!!
50
- await Promise.all(rows?.map(async (op) => {
51
- op.changes?.map(async (el) => {
52
- const col = body.colModel.filter((col1) => col1.name === el.attr)[0] || dbData[body?.table]?.find((col1) => col1.name === el.attr);
53
- if (el.attr === 'geom') {
54
- el.title = 'Геометрія';
55
- }
56
- el.title = col?.ua || col?.title || el.attr;
57
- if (!col) return;
58
- el.type = col.type;
59
- el.format = col.format;
60
- const select = col.data || col.option || col.select;
61
-
62
- // getSelect not equals to node
63
- if (select && false) {
64
- el.select = select;
65
- const cls = await getSelect(select, {
66
- val: [el.old, el.new],
67
- });
68
-
69
- el.oldf = cls[0] || el.old;
70
- el.newf = cls[1] || el.new;
71
- }
72
- });
73
- }));
74
-
75
- return rows;
76
- }
1
+ import { readdir } from 'fs/promises';
2
+ import { existsSync, readFileSync } from 'fs';
3
+
4
+ // import getTemplate from '../../../table/controllers/utils/getTemplate.js';
5
+ import getSelect from '../../../table/controllers/utils/getSelect.js';
6
+
7
+ const dbData = {};
8
+
9
+ // from config??
10
+ const allTemplates = { table: {} };
11
+
12
+ const historyQ = `select nspname||'.'||relname as table_name, json_agg(json_build_object('name',attname, 'title',coalesce(col_description(attrelid, attnum),attname))) as columns
13
+ from pg_attribute a
14
+ left join pg_catalog.pg_attrdef d ON (a.attrelid, a.attnum) = (d.adrelid, d.adnum)
15
+ JOIN pg_class AS i
16
+ ON i.oid = a.attrelid
17
+ JOIN pg_namespace AS NS ON i.relnamespace = NS.OID
18
+ where a.attnum > 0
19
+ and not a.attisdropped
20
+ group by nspname||'.'||relname`;
21
+
22
+ export default async function historyFormat(rows, table, pg) {
23
+ if (!rows?.[0]?.changes) return rows; // old structure
24
+ // on startup
25
+ if (!allTemplates.table.length) {
26
+ const templateDir = './server/templates/table';
27
+ const templates = existsSync(templateDir) ? await readdir(templateDir) : [];
28
+ templates.forEach((template) => {
29
+ const body = JSON.parse(readFileSync(`${templateDir}/${template}`) || '{}');
30
+ Object.assign(allTemplates.table, { [template]: body });
31
+ });
32
+ }
33
+
34
+ const progrid = Object.keys(allTemplates.table).find((key) => key.replace('.json', '') === table);
35
+ if (!progrid) return rows;
36
+ // const body = await getTemplate('table', progrid);
37
+ const body = allTemplates.table[progrid];
38
+ const tableName = body?.table || table;
39
+ if (!tableName) return rows;
40
+
41
+ // get DB column description
42
+ if (!dbData?.[body.table]?.length) {
43
+ const { rows: rows1 } = await pg.query(historyQ);
44
+ rows1.forEach((row) => {
45
+ dbData[row.table_name] = row.columns;
46
+ });
47
+ }
48
+
49
+ // rewrite!!!
50
+ await Promise.all(rows?.map(async (op) => {
51
+ op.changes?.map(async (el) => {
52
+ const col = body.colModel.filter((col1) => col1.name === el.attr)[0] || dbData[body?.table]?.find((col1) => col1.name === el.attr);
53
+ if (el.attr === 'geom') {
54
+ el.title = 'Геометрія';
55
+ }
56
+ el.title = col?.ua || col?.title || el.attr;
57
+ if (!col) return;
58
+ el.type = col.type;
59
+ el.format = col.format;
60
+ const select = col.data || col.option || col.select;
61
+
62
+ // getSelect not equals to node
63
+ if (select && false) {
64
+ el.select = select;
65
+ const cls = await getSelect(select, {
66
+ val: [el.old, el.new],
67
+ });
68
+
69
+ el.oldf = cls[0] || el.old;
70
+ el.newf = cls[1] || el.new;
71
+ }
72
+ });
73
+ }));
74
+
75
+ return rows;
76
+ }
@@ -1,13 +1,13 @@
1
- export default function obj2db(data, nonexistCol) {
2
- if (
3
- typeof data !== 'object'
4
- || Array.isArray(data)
5
- || !Object.keys(data || {}).length
6
- ) return { error: 'invalid data type' };
7
-
8
- const existColumns = Object.keys(data)?.filter((key) => !nonexistCol.includes(key));
9
- const columns = existColumns?.filter((col) => data[col] || data?.[col] === 0);
10
- const args = columns?.map((col) => data[col]);
11
-
12
- return { columns, args, error: !columns?.length ? 'nothing to process' : undefined };
13
- }
1
+ export default function obj2db(data, nonexistCol) {
2
+ if (
3
+ typeof data !== 'object'
4
+ || Array.isArray(data)
5
+ || !Object.keys(data || {}).length
6
+ ) return { error: 'invalid data type' };
7
+
8
+ const existColumns = Object.keys(data)?.filter((key) => !nonexistCol.includes(key));
9
+ const columns = existColumns?.filter((col) => data[col] || data?.[col] === 0);
10
+ const args = columns?.map((col) => data[col]);
11
+
12
+ return { columns, args, error: !columns?.length ? 'nothing to process' : undefined };
13
+ }
@@ -1,44 +1,44 @@
1
- /**
2
- * Дістає CRM дані для vue хешує ідентифікатори, підтягує селекти
3
- *
4
- * @method DELETE
5
- * @summary CRM дані для обраного віджета.
6
- * @priority 2
7
- * @tag table
8
- * @type api
9
- * @requires setTokenById
10
- * @requires getSelect
11
- * @param {String} id Ідентифікатор для хешування
12
- * @param {Any} sql Використовується для повернення sql запиту
13
- * @param {String} type Тип для хешування даних
14
- * @errors 400, 500
15
- * @returns {Number} status Номер помилки
16
- * @returns {String|Object} error Опис помилки
17
- * @returns {String|Object} message Повідомлення про успішне виконання або об'єкт з параметрами
18
- */
19
-
20
- export default async function widgetDel({
21
- pg, params = {}, session = {},
22
- }) {
23
- const { user = {} } = session.passport || {};
24
- if (!user.uid) return { error: 'access restricted', status: 403 };
25
- const { type, objectid, id } = params;
26
-
27
- if (!objectid) return { error: 'id required', status: 400 };
28
-
29
- const sqls = {
30
- comment: 'delete from crm.communications where entity_id=$1 and uid=$2 and communication_id=$3',
31
- checklist: 'delete from crm.checklists where entity_id=$1 and uid=$2 and checklist_id=$3',
32
- file: 'update crm.files set file_status=3 where entity_id=$1 and uid=$2 and file_id=$3',
33
- gallery: 'update crm.files set file_status=3 where entity_id=$1 and uid=$2 and file_id=$3',
34
- };
35
- const sql = sqls[type];
36
- if (!sql) return { error: 'type not valid', status: 401 };
37
- try {
38
- await pg.query(sql, [objectid, user.uid, id]);
39
- return { data: { id }, user: { uid: user.uid, name: user.user_name } };
40
- }
41
- catch (err) {
42
- return { message: err.toString(), status: 500 };
43
- }
44
- }
1
+ /**
2
+ * Дістає CRM дані для vue хешує ідентифікатори, підтягує селекти
3
+ *
4
+ * @method DELETE
5
+ * @summary CRM дані для обраного віджета.
6
+ * @priority 2
7
+ * @tag table
8
+ * @type api
9
+ * @requires setTokenById
10
+ * @requires getSelect
11
+ * @param {String} id Ідентифікатор для хешування
12
+ * @param {Any} sql Використовується для повернення sql запиту
13
+ * @param {String} type Тип для хешування даних
14
+ * @errors 400, 500
15
+ * @returns {Number} status Номер помилки
16
+ * @returns {String|Object} error Опис помилки
17
+ * @returns {String|Object} message Повідомлення про успішне виконання або об'єкт з параметрами
18
+ */
19
+
20
+ export default async function widgetDel({
21
+ pg, params = {}, session = {},
22
+ }) {
23
+ const { user = {} } = session.passport || {};
24
+ if (!user.uid) return { error: 'access restricted', status: 403 };
25
+ const { type, objectid, id } = params;
26
+
27
+ if (!objectid) return { error: 'id required', status: 400 };
28
+
29
+ const sqls = {
30
+ comment: 'delete from crm.communications where entity_id=$1 and uid=$2 and communication_id=$3',
31
+ checklist: 'delete from crm.checklists where entity_id=$1 and uid=$2 and checklist_id=$3',
32
+ file: 'update crm.files set file_status=3 where entity_id=$1 and uid=$2 and file_id=$3',
33
+ gallery: 'update crm.files set file_status=3 where entity_id=$1 and uid=$2 and file_id=$3',
34
+ };
35
+ const sql = sqls[type];
36
+ if (!sql) return { error: 'type not valid', status: 401 };
37
+ try {
38
+ await pg.query(sql, [objectid, user.uid, id]);
39
+ return { data: { id }, user: { uid: user.uid, name: user.user_name } };
40
+ }
41
+ catch (err) {
42
+ return { message: err.toString(), status: 500 };
43
+ }
44
+ }
@@ -1,96 +1,98 @@
1
- import getToken from '../../crud/funcs/getToken.js';
2
- import getMeta from '../../pg/funcs/getMeta.js';
3
- import historyFormat from './utils/historyFormat.js';
4
-
5
- const galleryExtList = ['png', 'svg', 'jpg', 'jpeg', 'gif', 'mp4', 'mov', 'avi'];
6
-
7
- /**
8
- * Дістає CRM для widget
9
- *
10
- */
11
-
12
- export default async function widgetGet({
13
- pg, session = {}, params = {}, query = {},
14
- }) {
15
- const { user = {} } = session.passport || {};
16
-
17
- const param = user?.uid ? await getToken({
18
- token: params.objectid, mode: 'w', uid: user.uid,
19
- }) : null;
20
-
21
- const objectid = param ? JSON.parse(param)?.id : params.objectid;
22
-
23
- if (!objectid) return { error: 'id required', status: 400 };
24
-
25
- const sqls = {
26
- comment: pg.pk['admin.users']
27
- ? `select communication_id, entity_id, body, subject, c.cdate, c.uid,
28
- coalesce(user_name,' ')||' '||coalesce(sur_name,'') as username, avatar
29
- from crm.communications c left join admin.users u on u.uid=c.uid where entity_id=$1 order by cdate desc`
30
- : 'select communication_id, entity_id, body, subject, cdate, uid from crm.communications where entity_id=$1 order by cdate desc',
31
-
32
- history: `SELECT table_change_id, entity_id, entity_type, change_key, change_date, json_old, json_new, date_old,
33
- date_new, number_old, number_new, bool_old, bool_new, text_old,
34
- text_new, uid, cdate FROM log.table_changes where entity_id=$1 order by cdate desc, change_key limit 100`,
35
-
36
- checklist: pg.pk['admin.users']
37
- ? `SELECT checklist_id, entity_id, subject, is_done, done_date, c.uid, c.cdate, coalesce(user_name,' ')||' '||coalesce(sur_name,'') as username,
38
- avatar FROM crm.checklists c left join admin.users u on u.uid=c.uid where entity_id=$1 order by cdate desc`
39
- : 'SELECT checklist_id, entity_id, subject, is_done, done_date, uid, cdate FROM crm.checklists where entity_id=$1 order by cdate desc',
40
-
41
- file: pg.pk['admin.users']
42
- ? `SELECT file_id, entity_id, entity_type, file_path, uploaded_name, ext, size, c.uid, c.cdate, file_type, c.ismain,
43
- coalesce(user_name,' ')||' '||coalesce(sur_name,'') as username, isverified,
44
- avatar, c.uid as author, file_status FROM crm.files c left join admin.users u on u.uid=c.uid
45
- where entity_id=$1 and file_status<>3 order by cdate desc`
46
- : `SELECT file_id, entity_id, entity_type, file_path, uploaded_name, ext, size, uid, cdate, file_type, ismain,
47
- isverified, uid as author, file_status FROM crm.files c where entity_id=$1 and file_status<>3 order by cdate desc`,
48
- gallery: pg.pk['admin.users']
49
- ? `SELECT file_id, entity_id, entity_type, file_path, uploaded_name, ext, size, c.uid, c.cdate, file_type, c.ismain,
50
- coalesce(user_name,' ')||' '||coalesce(sur_name,'') as username, isverified,
51
- avatar, c.uid as author, file_status FROM crm.files c left join admin.users u on u.uid=c.uid
52
- where entity_id=$1 and file_status<>3 and ext = any($2) order by cdate desc`
53
- : `SELECT file_id, entity_id, entity_type, file_path, uploaded_name, ext, size, c.uid, c.cdate, file_type, ismain,
54
- isverified, uid as author, file_status FROM crm.files c where entity_id=$1 and file_status<>3 and ext = any($2) order by cdate desc`,
55
-
56
- };
57
- const sql = sqls[params.type];
58
- if (!sql) {
59
- return { error: 'param type not valid', status: 400 };
60
- }
61
-
62
- try {
63
- /* data */
64
- const time = [Date.now()];
65
- const { rows } = await pg.query(sql, [objectid, params.type === 'gallery' ? galleryExtList : null].filter((el) => el));
66
- time.push(Date.now());
67
-
68
- /* Object info */
69
- const { tableName } = pg.pk['log.table_changes'] ? await pg.one('select entity_type as "tableName" from log.table_changes where entity_id=$1 limit 1', [objectid]) : {};
70
- const { pk } = await getMeta({ table: tableName });
71
-
72
- const q = tableName && pg.pk['admin.users'] ? `select coalesce(b.user_name,'')||coalesce(' '||b.sur_name,'') as author, a.cdate, a.editor_date from ${tableName} a
73
- left join admin.users b on a.uid=b.uid where a.${pk}=$1 limit 1` : undefined;
74
- const data = pk && q ? await pg.one(q, [objectid]) : {};
75
-
76
- if (query.debug && user?.user_type === 'admin') {
77
- return {
78
- sql, type: params.type, q, id: objectid, data,
79
- };
80
- }
81
-
82
- time.push(Date.now());
83
- return {
84
- time: { data: time[1] - time[0], format: time[2] - time[1] },
85
- rows: params.type === 'history' ? await historyFormat(rows, tableName, pg) : rows,
86
- user: { uid: user?.uid, name: user?.user_name },
87
- data: { author: data?.author, cdate: data?.cdate, edate: data?.editor_date },
88
- objectid: params.objectid,
89
- };
90
- }
91
- catch (err) {
92
- // 'history', 'file', 'checklist'
93
- /* 'document', 'image' - Макс на клиенте */
94
- return { message: err.toString(), status: 500 };
95
- }
96
- }
1
+ import getToken from '../../crud/funcs/getToken.js';
2
+ import getMeta from '../../pg/funcs/getMeta.js';
3
+ import historyFormat from './utils/historyFormat.js';
4
+
5
+ const galleryExtList = ['png', 'svg', 'jpg', 'jpeg', 'gif', 'mp4', 'mov', 'avi'];
6
+
7
+ /**
8
+ * Дістає CRM для widget
9
+ *
10
+ */
11
+
12
+ export default async function widgetGet({
13
+ pg, session = {}, params = {}, query = {},
14
+ }) {
15
+ const { user = {} } = session.passport || {};
16
+
17
+ const param = user?.uid ? await getToken({
18
+ token: params.objectid, mode: 'w', uid: user.uid,
19
+ }) : null;
20
+
21
+ const objectid = param ? JSON.parse(param)?.id : params.objectid;
22
+
23
+ if (!objectid) return { error: 'id required', status: 400 };
24
+
25
+ const sqls = {
26
+ comment: pg.pk['admin.users']
27
+ ? `select communication_id, entity_id, body, subject, c.cdate, c.uid,
28
+ coalesce(user_name,' ')||' '||coalesce(sur_name,'') as username, avatar
29
+ from crm.communications c left join admin.users u on u.uid=c.uid where entity_id=$1 order by cdate desc`
30
+ : 'select communication_id, entity_id, body, subject, cdate, uid from crm.communications where entity_id=$1 order by cdate desc',
31
+
32
+ history: `SELECT b.change_data_id, change_id, entity_id, entity_type, change_type, change_date, uid, cdate, b.entity_key, b.value_new, b.value_old FROM log.table_changes a
33
+ left join lateral(
34
+ select change_data_id, entity_key, value_new, value_old from log.table_changes_data where change_id=a.change_id
35
+ )b on 1=1
36
+ where entity_id=$1 and b.change_data_id is not null order by cdate desc limit 100`,
37
+
38
+ checklist: pg.pk['admin.users']
39
+ ? `SELECT checklist_id, entity_id, subject, is_done, done_date, c.uid, c.cdate, coalesce(user_name,' ')||' '||coalesce(sur_name,'') as username,
40
+ avatar FROM crm.checklists c left join admin.users u on u.uid=c.uid where entity_id=$1 order by cdate desc`
41
+ : 'SELECT checklist_id, entity_id, subject, is_done, done_date, uid, cdate FROM crm.checklists where entity_id=$1 order by cdate desc',
42
+
43
+ file: pg.pk['admin.users']
44
+ ? `SELECT file_id, entity_id, entity_type, file_path, uploaded_name, ext, size, c.uid, c.cdate, file_type, c.ismain,
45
+ coalesce(user_name,' ')||' '||coalesce(sur_name,'') as username, isverified,
46
+ avatar, c.uid as author, file_status FROM crm.files c left join admin.users u on u.uid=c.uid
47
+ where entity_id=$1 and file_status<>3 order by cdate desc`
48
+ : `SELECT file_id, entity_id, entity_type, file_path, uploaded_name, ext, size, uid, cdate, file_type, ismain,
49
+ isverified, uid as author, file_status FROM crm.files c where entity_id=$1 and file_status<>3 order by cdate desc`,
50
+ gallery: pg.pk['admin.users']
51
+ ? `SELECT file_id, entity_id, entity_type, file_path, uploaded_name, ext, size, c.uid, c.cdate, file_type, c.ismain,
52
+ coalesce(user_name,' ')||' '||coalesce(sur_name,'') as username, isverified,
53
+ avatar, c.uid as author, file_status FROM crm.files c left join admin.users u on u.uid=c.uid
54
+ where entity_id=$1 and file_status<>3 and ext = any($2) order by cdate desc`
55
+ : `SELECT file_id, entity_id, entity_type, file_path, uploaded_name, ext, size, c.uid, c.cdate, file_type, ismain,
56
+ isverified, uid as author, file_status FROM crm.files c where entity_id=$1 and file_status<>3 and ext = any($2) order by cdate desc`,
57
+
58
+ };
59
+ const sql = sqls[params.type];
60
+ if (!sql) {
61
+ return { error: 'param type not valid', status: 400 };
62
+ }
63
+
64
+ try {
65
+ /* data */
66
+ const time = [Date.now()];
67
+ const { rows } = await pg.query(sql, [objectid, params.type === 'gallery' ? galleryExtList : null].filter((el) => el));
68
+ time.push(Date.now());
69
+
70
+ /* Object info */
71
+ const { tableName } = pg.pk['log.table_changes'] ? await pg.one('select entity_type as "tableName" from log.table_changes where entity_id=$1 limit 1', [objectid]) : {};
72
+ const { pk } = await getMeta({ table: tableName });
73
+
74
+ const q = tableName && pg.pk['admin.users'] ? `select coalesce(b.user_name,'')||coalesce(' '||b.sur_name,'') as author, a.cdate, a.editor_date from ${tableName} a
75
+ left join admin.users b on a.uid=b.uid where a.${pk}=$1 limit 1` : undefined;
76
+ const data = pk && q ? await pg.one(q, [objectid]) : {};
77
+
78
+ if (query.debug && user?.user_type === 'admin') {
79
+ return {
80
+ sql, type: params.type, q, id: objectid, data,
81
+ };
82
+ }
83
+
84
+ time.push(Date.now());
85
+ return {
86
+ time: { data: time[1] - time[0], format: time[2] - time[1] },
87
+ rows: params.type === 'history' ? await historyFormat(rows, tableName, pg) : rows,
88
+ user: { uid: user?.uid, name: user?.user_name },
89
+ data: { author: data?.author, cdate: data?.cdate, edate: data?.editor_date },
90
+ objectid: params.objectid,
91
+ };
92
+ }
93
+ catch (err) {
94
+ // 'history', 'file', 'checklist'
95
+ /* 'document', 'image' - Макс на клиенте */
96
+ return { message: err.toString(), status: 500 };
97
+ }
98
+ }