@opengis/fastify-table 1.4.63 → 1.4.65

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.
@@ -1,82 +1,82 @@
1
- import getSelect from './getSelect.js';
2
-
3
- import getFilterSQL from './getFilterSQL/index.js';
4
- import getTemplate from './getTemplate.js';
5
- import pgClients from '../../pg/pgClients.js';
6
- import config from '../../../../config.js';
7
- import getSelectVal from './metaFormat/getSelectVal.js';
8
-
9
- export default async function gisIRColumn({
10
- pg = pgClients.client, layer, column, sql, query = '1=1', filter, state, search, custom,
11
- }) {
12
- const time = Date.now();
13
-
14
- const sel = await getSelect(query.cls || column, pg);
15
-
16
- const body = await getTemplate('table', layer);
17
- const fData = await getFilterSQL({
18
- table: layer,
19
- filter,
20
- state,
21
- search,
22
- custom,
23
- });
24
-
25
- const { tlist } = await pg.one(`select array_agg((select nspname from pg_namespace where oid=relnamespace)||'.'||relname) tlist from pg_class
26
- where relkind in ('r','v','m')`);
27
-
28
- const tableName = body?.table || layer;
29
- if (!tlist.includes(tableName)) return { error: `table not found: ${tableName}`, status: 400 };
30
-
31
- // eslint-disable-next-line max-len
32
- const { fields } = await pg.query(`select * from (${fData?.optimizedSQL || `select * from ${tableName}`})q limit 0`);
33
-
34
- const col = fields.find((el) => el.name === column);
35
-
36
- if (!col) return { status: 404, message: 'not found' };
37
- const colField = pg.pgType[col.dataTypeID]?.includes('[]') ? `unnest(${column})` : column;
38
-
39
- const q = `select ${colField} as id, count(*)::int from (
40
- ${fData?.optimizedSQL || `select * from ${tableName} where ${body?.query || 'true'}`}
41
- )t group by ${colField} order by count desc limit 15`;
42
-
43
- if (sql) return q;
44
-
45
- if (!body?.columns?.length) {
46
- const { rows } = await pg.query(q);
47
- if (sel?.arr?.length) {
48
- rows.forEach((el) => {
49
- const data = sel?.find((item) => item.id?.toString() === el.id?.toString());
50
- Object.assign(el, data || {});
51
- });
52
- }
53
- return {
54
- count: rows?.reduce((acc, el) => acc + el.count, 0),
55
- sql: config.local ? q : undefined,
56
- rows,
57
- };
58
- }
59
-
60
- const { rows } = await pg.query(q);
61
- const cls = query.cls || body?.columns?.find((el) => el.name === column)?.data || col.data || col.option;
62
- const select = await getSelectVal({
63
- pg, name: cls, values: rows.map((el) => el.id), ar: 1,
64
- });
65
- rows.forEach((el) => {
66
- if (Array.isArray(select)) {
67
- Object.assign(el, select.find((item) => item.id?.toString() === el.id?.toString()) || {});
68
- }
69
- else if (typeof select?.[el.id] === 'string') {
70
- Object.assign(el, { text: select?.[el.id] });
71
- }
72
- else {
73
- Object.assign(el, select?.[el.id] || {});
74
- }
75
- });
76
- return {
77
- time: Date.now() - time,
78
- count: rows.reduce((acc, el) => acc + el.count, 0),
79
- sql: config.local ? q : undefined,
80
- rows,
81
- };
82
- }
1
+ import getSelect from './getSelect.js';
2
+
3
+ import getFilterSQL from './getFilterSQL/index.js';
4
+ import getTemplate from './getTemplate.js';
5
+ import pgClients from '../../pg/pgClients.js';
6
+ import config from '../../../../config.js';
7
+ import getSelectVal from './metaFormat/getSelectVal.js';
8
+
9
+ export default async function gisIRColumn({
10
+ pg = pgClients.client, layer, column, sql, query = '1=1', filter, state, search, custom,
11
+ }) {
12
+ const time = Date.now();
13
+
14
+ const sel = await getSelect(query.cls || column, pg);
15
+
16
+ const body = await getTemplate('table', layer);
17
+ const fData = await getFilterSQL({
18
+ table: layer,
19
+ filter,
20
+ state,
21
+ search,
22
+ custom,
23
+ });
24
+
25
+ const { tlist } = await pg.one(`select array_agg((select nspname from pg_namespace where oid=relnamespace)||'.'||relname) tlist from pg_class
26
+ where relkind in ('r','v','m')`);
27
+
28
+ const tableName = body?.table || layer;
29
+ if (!tlist.includes(tableName)) return { error: `table not found: ${tableName}`, status: 400 };
30
+
31
+ // eslint-disable-next-line max-len
32
+ const { fields } = await pg.query(`select * from (${fData?.optimizedSQL || `select * from ${tableName}`})q limit 0`);
33
+
34
+ const col = fields.find((el) => el.name === column);
35
+
36
+ if (!col) return { status: 404, message: 'not found' };
37
+ const colField = pg.pgType[col.dataTypeID]?.includes('[]') ? `unnest(${column})` : column;
38
+
39
+ const q = `select ${colField} as id, count(*)::int from (
40
+ ${fData?.optimizedSQL || `select * from ${tableName} where ${body?.query || 'true'}`}
41
+ )t group by ${colField} order by count desc limit 15`;
42
+
43
+ if (sql) return q;
44
+
45
+ if (!body?.columns?.length) {
46
+ const { rows } = await pg.query(q);
47
+ if (sel?.arr?.length) {
48
+ rows.forEach((el) => {
49
+ const data = sel?.find((item) => item.id?.toString() === el.id?.toString());
50
+ Object.assign(el, data || {});
51
+ });
52
+ }
53
+ return {
54
+ count: rows?.reduce((acc, el) => acc + el.count, 0),
55
+ sql: config.local ? q : undefined,
56
+ rows,
57
+ };
58
+ }
59
+
60
+ const { rows } = await pg.query(q);
61
+ const cls = query.cls || body?.columns?.find((el) => el.name === column)?.data || col.data || col.option;
62
+ const select = await getSelectVal({
63
+ pg, name: cls, values: rows.map((el) => el.id), ar: 1,
64
+ });
65
+ rows.forEach((el) => {
66
+ if (Array.isArray(select)) {
67
+ Object.assign(el, select.find((item) => item.id?.toString() === el.id?.toString()) || {});
68
+ }
69
+ else if (typeof select?.[el.id] === 'string') {
70
+ Object.assign(el, { text: select?.[el.id] });
71
+ }
72
+ else {
73
+ Object.assign(el, select?.[el.id] || {});
74
+ }
75
+ });
76
+ return {
77
+ time: Date.now() - time,
78
+ count: rows.reduce((acc, el) => acc + el.count, 0),
79
+ sql: config.local ? q : undefined,
80
+ rows,
81
+ };
82
+ }
@@ -1 +1 @@
1
- export default {};
1
+ export default {};
@@ -1 +1 @@
1
- export default {};
1
+ export default {};
@@ -1 +1 @@
1
- export default [];
1
+ export default [];
@@ -1,42 +1,42 @@
1
- import { applyHook, getTemplate } from '../../../../utils.js';
2
-
3
- const sql = `select property_key as key, property_json as json, property_int as int,
4
- property_text as text from admin.properties where 1=1`;
5
-
6
- async function getSettings({ pg }) {
7
- const { rows = [] } = await pg.query(sql);
8
- const data = rows.reduce((acc, curr) => Object.assign(acc, { [curr.key]: curr.json || curr.int || curr.text }), {});
9
- return data;
10
- }
11
-
12
- export default async function formFunction(req) {
13
- const time = Date.now();
14
-
15
- const { pg, params, user } = req;
16
- const hookData = await applyHook('preForm', { form: params?.form, user });
17
-
18
- if (hookData?.message && hookData?.status) {
19
- return { message: hookData?.message, status: hookData?.status };
20
- }
21
-
22
- const form = await getTemplate('form', hookData?.form || params?.form);
23
- if (!form) { return { status: 404, message: 'not found' }; }
24
-
25
- // replace settings
26
- const arr = JSON.stringify(form).match(/{{settings.([^}]*)}}/g);
27
- if (arr?.length) {
28
- const string = JSON.stringify(form);
29
- const settings = await getSettings({ pg });
30
- const match = arr.reduce((acc, curr) => Object.assign(acc, { [curr]: settings[curr.replace(/^{{settings./g, '').replace(/}}$/, '')] }), {});
31
- const res = Object.keys(match).reduce((s, m) => s.replace(m, match[m]), string);
32
- return { time: Date.now() - time, form: JSON.parse(res) };
33
- }
34
-
35
- const res = { time: Date.now() - time, form };
36
- const res1 = await applyHook('afterForm', {
37
- form: hookData?.form || params?.form,
38
- payload: res,
39
- user,
40
- });
41
- return res1 || { time: Date.now() - time, form };
42
- }
1
+ import { applyHook, getTemplate } from '../../../../utils.js';
2
+
3
+ const sql = `select property_key as key, property_json as json, property_int as int,
4
+ property_text as text from admin.properties where 1=1`;
5
+
6
+ async function getSettings({ pg }) {
7
+ const { rows = [] } = await pg.query(sql);
8
+ const data = rows.reduce((acc, curr) => Object.assign(acc, { [curr.key]: curr.json || curr.int || curr.text }), {});
9
+ return data;
10
+ }
11
+
12
+ export default async function formFunction(req) {
13
+ const time = Date.now();
14
+
15
+ const { pg, params, user } = req;
16
+ const hookData = await applyHook('preForm', { form: params?.form, user });
17
+
18
+ if (hookData?.message && hookData?.status) {
19
+ return { message: hookData?.message, status: hookData?.status };
20
+ }
21
+
22
+ const form = await getTemplate('form', hookData?.form || params?.form);
23
+ if (!form) { return { status: 404, message: 'not found' }; }
24
+
25
+ // replace settings
26
+ const arr = JSON.stringify(form).match(/{{settings.([^}]*)}}/g);
27
+ if (arr?.length) {
28
+ const string = JSON.stringify(form);
29
+ const settings = await getSettings({ pg });
30
+ const match = arr.reduce((acc, curr) => Object.assign(acc, { [curr]: settings[curr.replace(/^{{settings./g, '').replace(/}}$/, '')] }), {});
31
+ const res = Object.keys(match).reduce((s, m) => s.replace(m, match[m]), string);
32
+ return { time: Date.now() - time, form: JSON.parse(res) };
33
+ }
34
+
35
+ const res = { time: Date.now() - time, form };
36
+ const res1 = await applyHook('afterForm', {
37
+ form: hookData?.form || params?.form,
38
+ payload: res,
39
+ user,
40
+ });
41
+ return res1 || { time: Date.now() - time, form };
42
+ }
@@ -1,74 +1,74 @@
1
- import {
2
- getMeta, metaFormat, getTemplates, getTemplate, handlebars,
3
- } from '../../../../utils.js';
4
-
5
- function sequence(tables, data, fn) {
6
- return tables.reduce((promise, table) => promise.then(() => fn({
7
- ...data, tableName: table.replace('.json', ''),
8
- })), Promise.resolve());
9
- }
10
-
11
- async function getData({
12
- pg, tableName, query = {}, maxLimit, res,
13
- }) {
14
- const loadTable = await getTemplate('table', tableName);
15
-
16
- if (!loadTable) { return { message: 'not found', status: 404 }; }
17
-
18
- const {
19
- table, columns, meta,
20
- } = loadTable;
21
-
22
- const { pk } = await getMeta(table);
23
-
24
- const cols = columns.map((el) => el.name || el).join(',');
25
- const [orderColumn, orderDir] = (query.order || loadTable.order || '').split('-');
26
- const order = cols.includes(orderColumn) && orderColumn?.length ? `order by ${orderColumn} ${query.desc || orderDir === 'desc' ? 'desc' : ''}` : '';
27
-
28
- const limit = Math.max(maxLimit - res.rows.length, 0);
29
- // Math.max(query.offset - res.rows.length,0)
30
- const offset = query.page && query.page > 0 ? ` offset ${(query.page - 1) * limit}` : '';
31
-
32
- const search1 = meta?.search && query.key ? `(${meta?.search.concat(meta?.title ? `,${meta?.title}` : '').split(',').map(el => `${el} ilike '%${query.key}%'`).join(' or ')})` : 'false';
33
-
34
- const where = [!pk ? 'false' : 'true', loadTable.query, search1].filter((el) => el);
35
- const q = `select ${[`"${pk}" as id`, meta?.title ? `${meta.title} as title` : ''].filter((el) => el).join(',')} from ${table} t where ${where.join(' and ') || 'true'} ${order} ${offset} limit ${limit}`;
36
- if (query.sql) {
37
- res.sql.push(q);
38
- return null;
39
- }
40
-
41
- const { rows } = await pg.query(q);
42
-
43
- const total = await pg.queryCache(`select count(*) from ${table} t where ${where.join(' and ') || 'true'}`).then((el) => el?.rows[0]?.count) || 0;
44
-
45
- await metaFormat({ rows, table: tableName });
46
- res.total += +total;
47
- rows.forEach((row) => {
48
- const href = meta?.href ? handlebars.compile(meta.href)({ ...row, [pk]: row.id }) : undefined;
49
- res.rows.push({
50
- ...row, register: tableName, register_title: loadTable.ua, href,
51
- });
52
- });
53
- return null;
54
- }
55
-
56
- export default async function search({
57
- pg, funcs, query = {},
58
- }) {
59
- const time = Date.now();
60
-
61
- const tables = query.table ? [query.table] : await getTemplates('table');
62
- const res = { rows: [], sql: [], total: 0 };
63
-
64
- const maxLimit = Math.min(100, query.limit || '16');
65
- await sequence(tables, {
66
- pg, funcs, query, maxLimit, res,
67
- }, getData);
68
-
69
- if (query.sql) return res.sql.join(';\n');
70
-
71
- return {
72
- time: Date.now() - time, total: res.total, count: res.rows.length, rows: res.rows,
73
- };
74
- }
1
+ import {
2
+ getMeta, metaFormat, getTemplates, getTemplate, handlebars,
3
+ } from '../../../../utils.js';
4
+
5
+ function sequence(tables, data, fn) {
6
+ return tables.reduce((promise, table) => promise.then(() => fn({
7
+ ...data, tableName: table.replace('.json', ''),
8
+ })), Promise.resolve());
9
+ }
10
+
11
+ async function getData({
12
+ pg, tableName, query = {}, maxLimit, res,
13
+ }) {
14
+ const loadTable = await getTemplate('table', tableName);
15
+
16
+ if (!loadTable) { return { message: 'not found', status: 404 }; }
17
+
18
+ const {
19
+ table, columns, meta,
20
+ } = loadTable;
21
+
22
+ const { pk } = await getMeta(table);
23
+
24
+ const cols = columns.map((el) => el.name || el).join(',');
25
+ const [orderColumn, orderDir] = (query.order || loadTable.order || '').split('-');
26
+ const order = cols.includes(orderColumn) && orderColumn?.length ? `order by ${orderColumn} ${query.desc || orderDir === 'desc' ? 'desc' : ''}` : '';
27
+
28
+ const limit = Math.max(maxLimit - res.rows.length, 0);
29
+ // Math.max(query.offset - res.rows.length,0)
30
+ const offset = query.page && query.page > 0 ? ` offset ${(query.page - 1) * limit}` : '';
31
+
32
+ const search1 = meta?.search && query.key ? `(${meta?.search.concat(meta?.title ? `,${meta?.title}` : '').split(',').map(el => `${el} ilike '%${query.key}%'`).join(' or ')})` : 'false';
33
+
34
+ const where = [!pk ? 'false' : 'true', loadTable.query, search1].filter((el) => el);
35
+ const q = `select ${[`"${pk}" as id`, meta?.title ? `${meta.title} as title` : ''].filter((el) => el).join(',')} from ${table} t where ${where.join(' and ') || 'true'} ${order} ${offset} limit ${limit}`;
36
+ if (query.sql) {
37
+ res.sql.push(q);
38
+ return null;
39
+ }
40
+
41
+ const { rows } = await pg.query(q);
42
+
43
+ const total = await pg.queryCache(`select count(*) from ${table} t where ${where.join(' and ') || 'true'}`).then((el) => el?.rows[0]?.count) || 0;
44
+
45
+ await metaFormat({ rows, table: tableName });
46
+ res.total += +total;
47
+ rows.forEach((row) => {
48
+ const href = meta?.href ? handlebars.compile(meta.href)({ ...row, [pk]: row.id }) : undefined;
49
+ res.rows.push({
50
+ ...row, register: tableName, register_title: loadTable.ua, href,
51
+ });
52
+ });
53
+ return null;
54
+ }
55
+
56
+ export default async function search({
57
+ pg, funcs, query = {},
58
+ }) {
59
+ const time = Date.now();
60
+
61
+ const tables = query.table ? [query.table] : await getTemplates('table');
62
+ const res = { rows: [], sql: [], total: 0 };
63
+
64
+ const maxLimit = Math.min(100, query.limit || '16');
65
+ await sequence(tables, {
66
+ pg, funcs, query, maxLimit, res,
67
+ }, getData);
68
+
69
+ if (query.sql) return res.sql.join(';\n');
70
+
71
+ return {
72
+ time: Date.now() - time, total: res.total, count: res.rows.length, rows: res.rows,
73
+ };
74
+ }
@@ -72,7 +72,7 @@ export default async function dataAPI(req, reply, called) {
72
72
 
73
73
  if (query.sql === '0') return loadTable;
74
74
 
75
- if (!config.pg) { return reply.status(500).send('empty pg'); }
75
+ if (!pg) { return reply.status(500).send('empty pg'); }
76
76
 
77
77
  const pkey = pg.pk?.[params?.table] || pg.pk?.[params?.table.replace(/"/g, '')];
78
78
 
@@ -182,11 +182,12 @@ export default async function dataAPI(req, reply, called) {
182
182
 
183
183
  const offset = query.page && query.page > 0 && !objectId ? ` offset ${(query.page - 1) * limit}` : '';
184
184
  // id, query, filter
185
- const [orderColumn, orderDir] = (query.order || loadTable?.order || '').split(/[- ]/);
185
+ const [orderColumn, orderDir] = called && query.order ? [query.order] : (query.order || loadTable?.order || '').split(/[- ]/);
186
186
 
187
- const order = query.order && columnList.includes(orderColumn) && orderColumn?.length
188
- ? `order by ${orderColumn} ${query.desc || orderDir === 'desc' ? 'desc' : ''} nulls last`
187
+ const order = query.order && (columnList.includes(orderColumn) && orderColumn?.length || called)
188
+ ? `order by ${orderColumn} ${query.desc || orderDir === 'desc' ? 'desc' : ''} ${!called ? 'nulls last' : ''}`
189
189
  : `order by ${(loadTable?.order || 'true::boolean')} nulls last`;
190
+
190
191
  const search = loadTable?.meta?.search && query.search
191
192
  ? `(${loadTable?.meta?.search?.split(',')?.map(el => `${el} ilike '%${query.search.replace(/%/g, '\\%').replace(/'/g, "''")}%'`).join(' or ')})`
192
193
  : null;
@@ -1,89 +1,89 @@
1
- import config from '../../../../config.js';
2
- import isFileExists from '../../../plugins/file/isFileExists.js';
3
- import logChanges from '../../../plugins/crud/funcs/utils/logChanges.js';
4
- import pgClients from '../../../plugins/pg/pgClients.js';
5
-
6
- const isAdmin = (req) => process.env.NODE_ENV === 'admin'
7
- || config.admin
8
- || req?.hostname?.split?.(':')?.shift?.() === config.adminDomain
9
- || req?.hostname?.startsWith?.('admin');
10
-
11
- async function checkAccess(pg, objectid, id) {
12
- const { uid, filepath } = await pg.query('select uid, file_path as filepath from crm.files where entity_id=$1 and file_id=$2', [objectid, id])
13
- .then(el => el.rows?.[0] || {});
14
- return { uid, exists: filepath ? await isFileExists(filepath) : null };
15
- }
16
-
17
- /**
18
- * Дістає CRM дані для vue хешує ідентифікатори, підтягує селекти
19
- *
20
- * @method DELETE
21
- * @summary CRM дані для обраного віджета.
22
- * @priority 2
23
- * @tag table
24
- * @type api
25
- * @requires setTokenById
26
- * @requires getSelect
27
- * @param {String} id Ідентифікатор для хешування
28
- * @param {Any} sql Використовується для повернення sql запиту
29
- * @param {String} type Тип для хешування даних
30
- * @errors 400, 500
31
- * @returns {Number} status Номер помилки
32
- * @returns {String|Object} error Опис помилки
33
- * @returns {String|Object} message Повідомлення про успішне виконання або об'єкт з параметрами
34
- */
35
-
36
- export default async function widgetDel(req, reply) {
37
- const {
38
- pg = pgClients.client, params = {}, user = {},
39
- } = req;
40
-
41
- if (!user?.uid) {
42
- return reply.status(401).send('access restricted: user not authorized');
43
- }
44
-
45
- const { type, objectid, id } = params;
46
-
47
- if (!objectid) {
48
- return reply.status(400).send('not enough params: id');
49
- }
50
-
51
- // force delete db entry if file not exists
52
- const { exists, uid } = ['file', 'gallery'].includes(type) ? await checkAccess(pg, objectid, id) : {};
53
-
54
- if (exists && !isAdmin(req) && uid && user?.uid !== uid) {
55
- return reply.status(403).send('access restricted: file exists, not an author');
56
- }
57
-
58
- const sqls = {
59
- comment: `delete from crm.communications where entity_id=$1 and ${isAdmin(req) ? '$2=$2' : 'uid=$2'} and communication_id=$3`,
60
- checklist: `delete from crm.checklists where entity_id=$1 and ${isAdmin(req) ? '$2=$2' : 'uid=$2'} and checklist_id=$3`,
61
- file: `update crm.files set file_status=3 where entity_id=$1 and ${!exists || isAdmin(req) ? '$2=$2' : 'uid=$2'} and file_id=$3 returning uploaded_name`,
62
- gallery: `update crm.files set file_status=3 where entity_id=$1 and ${!exists || isAdmin(req) ? '$2=$2' : 'uid=$2'} and file_id=$3 returning uploaded_name`,
63
- };
64
-
65
- const sql = sqls[type];
66
- const table = {
67
- comment: 'crm.communications',
68
- checklist: 'crm.checklists',
69
- file: 'crm.files',
70
- gallery: 'crm.files',
71
- }[type];
72
-
73
- if (!sql) {
74
- return reply.status(400).send('invalid widget type');
75
- }
76
-
77
- const { rows = [] } = await pg.query(sql, [objectid, user.uid, id]);
78
-
79
- await logChanges({
80
- pg,
81
- table,
82
- id,
83
- data: rows[0],
84
- uid: user?.uid,
85
- type: 'DELETE',
86
- });
87
-
88
- return reply.status(200).send({ data: { id }, user: { uid: user.uid, name: user.user_name } });
89
- }
1
+ import config from '../../../../config.js';
2
+ import isFileExists from '../../../plugins/file/isFileExists.js';
3
+ import logChanges from '../../../plugins/crud/funcs/utils/logChanges.js';
4
+ import pgClients from '../../../plugins/pg/pgClients.js';
5
+
6
+ const isAdmin = (req) => process.env.NODE_ENV === 'admin'
7
+ || config.admin
8
+ || req?.hostname?.split?.(':')?.shift?.() === config.adminDomain
9
+ || req?.hostname?.startsWith?.('admin');
10
+
11
+ async function checkAccess(pg, objectid, id) {
12
+ const { uid, filepath } = await pg.query('select uid, file_path as filepath from crm.files where entity_id=$1 and file_id=$2', [objectid, id])
13
+ .then(el => el.rows?.[0] || {});
14
+ return { uid, exists: filepath ? await isFileExists(filepath) : null };
15
+ }
16
+
17
+ /**
18
+ * Дістає CRM дані для vue хешує ідентифікатори, підтягує селекти
19
+ *
20
+ * @method DELETE
21
+ * @summary CRM дані для обраного віджета.
22
+ * @priority 2
23
+ * @tag table
24
+ * @type api
25
+ * @requires setTokenById
26
+ * @requires getSelect
27
+ * @param {String} id Ідентифікатор для хешування
28
+ * @param {Any} sql Використовується для повернення sql запиту
29
+ * @param {String} type Тип для хешування даних
30
+ * @errors 400, 500
31
+ * @returns {Number} status Номер помилки
32
+ * @returns {String|Object} error Опис помилки
33
+ * @returns {String|Object} message Повідомлення про успішне виконання або об'єкт з параметрами
34
+ */
35
+
36
+ export default async function widgetDel(req, reply) {
37
+ const {
38
+ pg = pgClients.client, params = {}, user = {},
39
+ } = req;
40
+
41
+ if (!user?.uid) {
42
+ return reply.status(401).send('access restricted: user not authorized');
43
+ }
44
+
45
+ const { type, objectid, id } = params;
46
+
47
+ if (!objectid) {
48
+ return reply.status(400).send('not enough params: id');
49
+ }
50
+
51
+ // force delete db entry if file not exists
52
+ const { exists, uid } = ['file', 'gallery'].includes(type) ? await checkAccess(pg, objectid, id) : {};
53
+
54
+ if (exists && !isAdmin(req) && uid && user?.uid !== uid) {
55
+ return reply.status(403).send('access restricted: file exists, not an author');
56
+ }
57
+
58
+ const sqls = {
59
+ comment: `delete from crm.communications where entity_id=$1 and ${isAdmin(req) ? '$2=$2' : 'uid=$2'} and communication_id=$3`,
60
+ checklist: `delete from crm.checklists where entity_id=$1 and ${isAdmin(req) ? '$2=$2' : 'uid=$2'} and checklist_id=$3`,
61
+ file: `update crm.files set file_status=3 where entity_id=$1 and ${!exists || isAdmin(req) ? '$2=$2' : 'uid=$2'} and file_id=$3 returning uploaded_name`,
62
+ gallery: `update crm.files set file_status=3 where entity_id=$1 and ${!exists || isAdmin(req) ? '$2=$2' : 'uid=$2'} and file_id=$3 returning uploaded_name`,
63
+ };
64
+
65
+ const sql = sqls[type];
66
+ const table = {
67
+ comment: 'crm.communications',
68
+ checklist: 'crm.checklists',
69
+ file: 'crm.files',
70
+ gallery: 'crm.files',
71
+ }[type];
72
+
73
+ if (!sql) {
74
+ return reply.status(400).send('invalid widget type');
75
+ }
76
+
77
+ const { rows = [] } = await pg.query(sql, [objectid, user.uid, id]);
78
+
79
+ await logChanges({
80
+ pg,
81
+ table,
82
+ id,
83
+ data: rows[0],
84
+ uid: user?.uid,
85
+ type: 'DELETE',
86
+ });
87
+
88
+ return reply.status(200).send({ data: { id }, user: { uid: user.uid, name: user.user_name } });
89
+ }