@opengis/fastify-table 1.0.36 → 1.0.37

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 (46) hide show
  1. package/Changelog.md +4 -0
  2. package/crud/controllers/insert.js +29 -29
  3. package/crud/controllers/update.js +31 -31
  4. package/crud/funcs/getOpt.js +10 -10
  5. package/crud/funcs/setOpt.js +16 -16
  6. package/crud/index.js +29 -29
  7. package/helper.js +28 -28
  8. package/notification/controllers/userNotifications.js +19 -19
  9. package/notification/funcs/addNotification.js +8 -8
  10. package/notification/index.js +19 -19
  11. package/package.json +1 -1
  12. package/pg/pgClients.js +20 -20
  13. package/policy/funcs/checkPolicy.js +74 -74
  14. package/policy/funcs/sqlInjection.js +33 -33
  15. package/policy/index.js +14 -14
  16. package/redis/client.js +8 -8
  17. package/redis/funcs/redisClients.js +2 -2
  18. package/redis/index.js +19 -19
  19. package/server/templates/form/test.dataset.form.json +411 -411
  20. package/server/templates/select/test.storage.data.json +2 -2
  21. package/server/templates/table/test.dataset.table.json +24 -24
  22. package/table/controllers/data.js +57 -57
  23. package/table/controllers/form.js +10 -10
  24. package/table/controllers/suggest.js +60 -60
  25. package/table/controllers/utils/getSelect.js +20 -20
  26. package/table/controllers/utils/getSelectMeta.js +66 -66
  27. package/table/controllers/utils/getTemplate.js +28 -28
  28. package/table/funcs/getFilterSQL/index.js +75 -75
  29. package/table/funcs/getFilterSQL/util/formatValue.js +142 -142
  30. package/table/funcs/getFilterSQL/util/getCustomQuery.js +13 -13
  31. package/table/funcs/getFilterSQL/util/getFilterQuery.js +73 -73
  32. package/table/funcs/getFilterSQL/util/getOptimizedQuery.js +12 -12
  33. package/table/funcs/metaFormat/getSelectVal.js +20 -20
  34. package/table/funcs/metaFormat/index.js +26 -26
  35. package/table/index.js +42 -42
  36. package/test/api/crud.test.js +56 -56
  37. package/test/api/crud.xss.test.js +71 -71
  38. package/test/api/notification.test.js +37 -37
  39. package/test/api/table.test.js +57 -57
  40. package/test/funcs/notification.test.js +31 -31
  41. package/widget/controllers/utils/historyFormat.js +76 -76
  42. package/widget/controllers/utils/obj2db.js +13 -13
  43. package/widget/controllers/widget.del.js +44 -41
  44. package/widget/controllers/widget.get.js +86 -77
  45. package/widget/controllers/widget.set.js +70 -64
  46. package/widget/index.js +29 -29
@@ -1,31 +1,31 @@
1
- import { test } from 'node:test';
2
- import assert from 'node:assert';
3
-
4
- import build from '../../helper.js';
5
- import config from '../config.js';
6
-
7
- import addNotification from '../../notification/funcs/addNotification.js';
8
-
9
- import pgClients from '../../pg/pgClients.js';
10
-
11
- test('notification funcs', async (t) => {
12
- await build(t);
13
- const pg = pgClients.client;
14
- let resp;
15
- await t.test('addNotification', async () => {
16
- resp = await addNotification({
17
- pg,
18
-
19
- title: 'test title',
20
- body: 'test body',
21
- link: 'http://link',
22
- notificationType: 'mention',
23
- uid: config.testUser?.uid || '1',
24
- });
25
- assert.ok(resp.id);
26
- });
27
- await t.test('clean up after test, before pool is closed', async () => {
28
- await pg.query('delete from crm.notification where notification_id=$1', [resp.id]);
29
- console.log(resp.id, 'deleted');
30
- });
31
- });
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert';
3
+
4
+ import build from '../../helper.js';
5
+ import config from '../config.js';
6
+
7
+ import addNotification from '../../notification/funcs/addNotification.js';
8
+
9
+ import pgClients from '../../pg/pgClients.js';
10
+
11
+ test('notification funcs', async (t) => {
12
+ await build(t);
13
+ const pg = pgClients.client;
14
+ let resp;
15
+ await t.test('addNotification', async () => {
16
+ resp = await addNotification({
17
+ pg,
18
+
19
+ title: 'test title',
20
+ body: 'test body',
21
+ link: 'http://link',
22
+ notificationType: 'mention',
23
+ uid: config.testUser?.uid || '1',
24
+ });
25
+ assert.ok(resp.id);
26
+ });
27
+ await t.test('clean up after test, before pool is closed', async () => {
28
+ await pg.query('delete from crm.notification where notification_id=$1', [resp.id]);
29
+ console.log(resp.id, 'deleted');
30
+ });
31
+ });
@@ -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,41 +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
- if (!['comment', 'checklist', 'file'].includes(type)) return { error: 'type not valid', status: 401 };
27
- if (!objectid) return { error: 'id required', status: 400 };
28
-
29
- const sql = {
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
- };
34
- try {
35
- await pg.query(sql[type], [objectid, user.uid, id]);
36
- return { data: { id }, user: { uid: user.uid, name: user.user_name } };
37
- }
38
- catch (err) {
39
- return { message: err.toString(), status: 500 };
40
- }
41
- }
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,77 +1,86 @@
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
- /**
6
- * Дістає CRM для widget
7
- *
8
- */
9
-
10
- export default async function widgetGet({
11
- pg, session = {}, params = {}, query = {},
12
- }) {
13
- const { user = {} } = session.passport || {};
14
- console.log('test');
15
-
16
- const param = user?.uid ? await getToken({
17
- token: params.objectid, mode: 'w', uid: user.uid,
18
- }) : null;
19
-
20
- const objectid = param ? JSON.parse(param)?.id : params.objectid;
21
-
22
- if (!['comment', 'history', 'file', 'checklist'].includes(params.type)) return { error: 'param type not valid', status: 400 };
23
- if (!objectid) return { error: 'id required', status: 400 };
24
-
25
- const sql = {
26
- comment: `select communication_id, entity_id, body, subject, c.cdate, c.uid,
27
- coalesce(user_name,' ')||' '||coalesce(sur_name,'') as username, avatar
28
- from crm.communications c left join admin.users u on u.uid=c.uid where entity_id=$1 order by cdate desc`,
29
-
30
- history: `SELECT table_change_id, entity_id, entity_type, change_key, change_date, json_old, json_new, date_old,
31
- date_new, number_old, number_new, bool_old, bool_new, text_old,
32
- text_new, uid, cdate FROM log.table_changes where entity_id=$1 order by cdate desc, change_key limit 100`,
33
-
34
- checklist: `SELECT checklist_id, entity_id, subject, is_done, done_date, c.uid, c.cdate, coalesce(user_name,' ')||' '||coalesce(sur_name,'') as username,
35
- avatar FROM crm.checklists c left join admin.users u on u.uid=c.uid where entity_id=$1 order by cdate desc`,
36
-
37
- file: `SELECT file_id, entity_id, entity_type, file_path, uploaded_name, ext, size, c.uid, c.cdate, file_type, c.ismain,
38
- coalesce(user_name,' ')||' '||coalesce(sur_name,'') as username, isverified,
39
- avatar, c.uid as author, file_status FROM crm.files c left join admin.users u on u.uid=c.uid
40
- where entity_id=$1 and file_status<>3 order by cdate desc`,
41
-
42
- };
43
- try {
44
- /* data */
45
- const time = [Date.now()];
46
- const { rows } = await pg.query(sql[params.type], [objectid]);
47
- time.push(Date.now());
48
-
49
- /* Object info */
50
- const { tableName } = await pg.one('select entity_type as "tableName" from log.table_changes where entity_id=$1 limit 1', [objectid]);
51
- const { pk } = await getMeta({ table: tableName });
52
-
53
- const q = `select coalesce(b.user_name,'')||coalesce(' '||b.sur_name,'') as author, a.cdate, a.editor_date from ${tableName} a
54
- left join admin.users b on a.uid=b.uid where a.${pk}=$1 limit 1`;
55
- const data = pk ? await pg.one(q, [objectid]) : {};
56
-
57
- if (query.debug && user?.user_type === 'admin') {
58
- return {
59
- sql, type: params.type, q, id: objectid, data,
60
- };
61
- }
62
-
63
- time.push(Date.now());
64
- return {
65
- time: { data: time[1] - time[0], format: time[2] - time[1] },
66
- rows: params.type === 'history' ? await historyFormat(rows, tableName, pg) : rows,
67
- user: { uid: user?.uid, name: user?.user_name },
68
- data: { author: data?.author, cdate: data?.cdate, edate: data?.editor_date },
69
- objectid: params.objectid,
70
- };
71
- }
72
- catch (err) {
73
- // 'history', 'file', 'checklist'
74
- /* 'document', 'image' - Макс на клиенте */
75
- return { message: err.toString(), status: 500 };
76
- }
77
- }
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: `select communication_id, entity_id, body, subject, c.cdate, c.uid,
27
+ coalesce(user_name,' ')||' '||coalesce(sur_name,'') as username, avatar
28
+ from crm.communications c left join admin.users u on u.uid=c.uid where entity_id=$1 order by cdate desc`,
29
+
30
+ history: `SELECT table_change_id, entity_id, entity_type, change_key, change_date, json_old, json_new, date_old,
31
+ date_new, number_old, number_new, bool_old, bool_new, text_old,
32
+ text_new, uid, cdate FROM log.table_changes where entity_id=$1 order by cdate desc, change_key limit 100`,
33
+
34
+ checklist: `SELECT checklist_id, entity_id, subject, is_done, done_date, c.uid, c.cdate, coalesce(user_name,' ')||' '||coalesce(sur_name,'') as username,
35
+ avatar FROM crm.checklists c left join admin.users u on u.uid=c.uid where entity_id=$1 order by cdate desc`,
36
+
37
+ file: `SELECT file_id, entity_id, entity_type, file_path, uploaded_name, ext, size, c.uid, c.cdate, file_type, c.ismain,
38
+ coalesce(user_name,' ')||' '||coalesce(sur_name,'') as username, isverified,
39
+ avatar, c.uid as author, file_status FROM crm.files c left join admin.users u on u.uid=c.uid
40
+ where entity_id=$1 and file_status<>3 order by cdate desc`,
41
+ gallery: `SELECT file_id, entity_id, entity_type, file_path, uploaded_name, ext, size, c.uid, c.cdate, file_type, c.ismain,
42
+ coalesce(user_name,' ')||' '||coalesce(sur_name,'') as username, isverified,
43
+ avatar, c.uid as author, file_status FROM crm.files c left join admin.users u on u.uid=c.uid
44
+ where entity_id=$1 and file_status<>3 and ext = any($2) order by cdate desc`,
45
+
46
+ };
47
+ const sql = sqls[params.type];
48
+ if (!sql) {
49
+ return { error: 'param type not valid', status: 400 };
50
+ }
51
+
52
+ try {
53
+ /* data */
54
+ const time = [Date.now()];
55
+ const { rows } = await pg.query(sql, [objectid, params.type === 'gallery' ? galleryExtList : null].filter((el) => el));
56
+ time.push(Date.now());
57
+
58
+ /* Object info */
59
+ const { tableName } = await pg.one('select entity_type as "tableName" from log.table_changes where entity_id=$1 limit 1', [objectid]);
60
+ const { pk } = await getMeta({ table: tableName });
61
+
62
+ const q = `select coalesce(b.user_name,'')||coalesce(' '||b.sur_name,'') as author, a.cdate, a.editor_date from ${tableName} a
63
+ left join admin.users b on a.uid=b.uid where a.${pk}=$1 limit 1`;
64
+ const data = pk ? await pg.one(q, [objectid]) : {};
65
+
66
+ if (query.debug && user?.user_type === 'admin') {
67
+ return {
68
+ sql, type: params.type, q, id: objectid, data,
69
+ };
70
+ }
71
+
72
+ time.push(Date.now());
73
+ return {
74
+ time: { data: time[1] - time[0], format: time[2] - time[1] },
75
+ rows: params.type === 'history' ? await historyFormat(rows, tableName, pg) : rows,
76
+ user: { uid: user?.uid, name: user?.user_name },
77
+ data: { author: data?.author, cdate: data?.cdate, edate: data?.editor_date },
78
+ objectid: params.objectid,
79
+ };
80
+ }
81
+ catch (err) {
82
+ // 'history', 'file', 'checklist'
83
+ /* 'document', 'image' - Макс на клиенте */
84
+ return { message: err.toString(), status: 500 };
85
+ }
86
+ }
@@ -1,64 +1,70 @@
1
- import path from 'path';
2
-
3
- import getMeta from '../../pg/funcs/getMeta.js';
4
- import dataInsert from '../../crud/funcs/dataInsert.js';
5
- import dataUpdate from '../../crud/funcs/dataUpdate.js';
6
-
7
- const tableList = {
8
- comment: 'crm.communications',
9
- checklist: 'crm.checklists',
10
- };
11
- const pkList = {
12
- comment: 'communication_id',
13
- checklist: 'checklist_id',
14
- };
15
-
16
- export default async function widgetSet(req) {
17
- const {
18
- pg, params = {}, session = {}, body = {}, funcs, log,
19
- } = req;
20
- const { user = {} } = session.passport || {};
21
- const { type, id, objectid } = params;
22
- if (!['comment', 'checklist', 'file'].includes(type)) return { error: 'param type not valid', status: 400 };
23
- if (!objectid) return { error: 'id required', status: 400 };
24
-
25
- const table = tableList[type];
26
-
27
- try {
28
- if (type === 'file') {
29
- const file = await funcs.uploadMultiPart(req);
30
- const extName = path.extname(file.filepath).slice(1).toLowerCase();
31
-
32
- const data = {
33
- uploaded_name: file?.originalFilename?.toLocaleLowerCase()?.replace(/'/g, '\'\''),
34
- file_path: file?.relativeFilepath?.replace(/\\/g, '/'),
35
- ext: extName,
36
- size: file?.size,
37
- file_status: 1,
38
- uid: user?.uid || 1,
39
- entity_id: objectid,
40
- };
41
-
42
- const { rows = [] } = await dataInsert({ table: 'crm.files', data });
43
- return {
44
- rowCount: 1, data: 'ok', command: 'UPLOAD', id: rows[0]?.file_id, entity_id: rows[0]?.entity_id,
45
- };
46
- }
47
- const { pk } = await getMeta({ pg, table });
48
- if (!pk) return { message: 'table not found', status: 404 };
49
-
50
- const data = { ...body, uid: user?.uid, entity_id: objectid };
51
-
52
- const result = id
53
- ? await dataUpdate({ table, data, id })
54
- : await dataInsert({ table, data });
55
-
56
- return {
57
- rowCount: result.rowCount, data: 'ok', command: result.command, id: result.rows?.[0]?.[pkList[type]] || result?.[pkList[type]],
58
- };
59
- }
60
- catch (err) {
61
- log.error('widget/upload', { error: err.toString(), params });
62
- return { error: err.toString(), status: 500 };
63
- }
64
- }
1
+ import path from 'path';
2
+
3
+ import getMeta from '../../pg/funcs/getMeta.js';
4
+ import dataInsert from '../../crud/funcs/dataInsert.js';
5
+ import dataUpdate from '../../crud/funcs/dataUpdate.js';
6
+
7
+ const tableList = {
8
+ comment: 'crm.communications',
9
+ checklist: 'crm.checklists',
10
+ };
11
+ const pkList = {
12
+ comment: 'communication_id',
13
+ checklist: 'checklist_id',
14
+ };
15
+
16
+ const galleryExtList = ['png', 'svg', 'jpg', 'jpeg', 'gif', 'mp4', 'mov', 'avi'];
17
+
18
+ export default async function widgetSet(req) {
19
+ const {
20
+ pg, params = {}, session = {}, body = {}, funcs, log,
21
+ } = req;
22
+ const { user = {} } = session.passport || {};
23
+ const { type, id, objectid } = params;
24
+ if (!['comment', 'checklist', 'file', 'gallery'].includes(type)) return { error: 'param type not valid', status: 400 };
25
+ if (!objectid) return { error: 'id required', status: 400 };
26
+
27
+ const table = tableList[type];
28
+
29
+ try {
30
+ if (['gallery', 'file'].includes(type)) {
31
+ const file = await funcs.uploadMultiPart(req);
32
+ const extName = path.extname(file.filepath).slice(1).toLowerCase();
33
+
34
+ const data = {
35
+ uploaded_name: file?.originalFilename?.toLocaleLowerCase()?.replace(/'/g, '\'\''),
36
+ file_path: file?.relativeFilepath?.replace(/\\/g, '/'),
37
+ ext: extName,
38
+ size: file?.size,
39
+ file_status: 1,
40
+ uid: user?.uid || 1,
41
+ entity_id: objectid,
42
+ };
43
+
44
+ if (type === 'gallery' && !galleryExtList.includes(extName.toLowerCase())) {
45
+ return { message: 'invalid file extension', status: 400 };
46
+ }
47
+
48
+ const { rows = [] } = await dataInsert({ table: 'crm.files', data });
49
+ return {
50
+ rowCount: 1, data: 'ok', command: 'UPLOAD', id: rows[0]?.file_id, entity_id: rows[0]?.entity_id,
51
+ };
52
+ }
53
+ const { pk } = await getMeta({ pg, table });
54
+ if (!pk) return { message: 'table not found', status: 404 };
55
+
56
+ const data = { ...body, uid: user?.uid, entity_id: objectid };
57
+
58
+ const result = id
59
+ ? await dataUpdate({ table, data, id })
60
+ : await dataInsert({ table, data });
61
+
62
+ return {
63
+ rowCount: result.rowCount, data: 'ok', command: result.command, id: result.rows?.[0]?.[pkList[type]] || result?.[pkList[type]],
64
+ };
65
+ }
66
+ catch (err) {
67
+ log.error('widget/upload', { error: err.toString(), params });
68
+ return { error: err.toString(), status: 500 };
69
+ }
70
+ }