@opengis/fastify-table 1.4.46 → 1.4.47

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/index.js CHANGED
@@ -42,6 +42,8 @@ import dblistRoutes from './server/routes/dblist/index.mjs';
42
42
  import menuRoutes from './server/routes/menu/index.mjs';
43
43
  import templatesRoutes from './server/routes/templates/index.mjs';
44
44
 
45
+ import widgetRoutes from './server/routes/widget/index.mjs';
46
+
45
47
  // core templates && cls
46
48
  const filename = fileURLToPath(import.meta.url);
47
49
  const cwd = path.dirname(filename);
@@ -110,6 +112,7 @@ async function plugin(fastify, opt) {
110
112
  propertiesRoutes(fastify, opt);
111
113
  tableRoutes(fastify, opt);
112
114
  utilRoutes(fastify, opt);
115
+ widgetRoutes(fastify, opt);
113
116
 
114
117
  menuRoutes(fastify, opt);
115
118
  templatesRoutes(fastify, opt);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengis/fastify-table",
3
- "version": "1.4.46",
3
+ "version": "1.4.47",
4
4
  "type": "module",
5
5
  "description": "core-plugins",
6
6
  "keywords": [
@@ -0,0 +1,55 @@
1
+ import path from 'node:path';
2
+
3
+ import dataUpdate from '../../../plugins/crud/funcs/dataUpdate.js';
4
+ import pgClients from '../../../plugins/pg/pgClients.js';
5
+ import uploadMultiPart from '../../../plugins/file/uploadMultiPart.js';
6
+
7
+ export default async function widgetSet(req, reply) {
8
+ const {
9
+ pg = pgClients.client, headers = {}, user = {}, params = {},
10
+ } = req;
11
+
12
+ if (!params?.id) {
13
+ return reply.status(400).send('not enough params: id');
14
+ }
15
+
16
+ if (!pg.pk?.['crm.files']) {
17
+ return reply.status(404).send('table not found');
18
+ }
19
+
20
+ if (headers['content-type']?.split?.(';')?.shift?.() !== 'multipart/form-data') {
21
+ return reply.status(400).send('invalid payload content type');
22
+ }
23
+
24
+ const file = await uploadMultiPart(req);
25
+ const extName = path.extname(file.filepath).slice(1).toLowerCase();
26
+
27
+ const data = {
28
+ uploaded_name: file?.originalFilename?.toLocaleLowerCase()?.replace(/'/g, '\'\''),
29
+ file_path: file?.relativeFilepath?.replace(/\\/g, '/'),
30
+ ext: extName,
31
+ size: file?.size,
32
+ file_status: 1,
33
+ uid: user?.uid || 1,
34
+ };
35
+
36
+ const result = await dataUpdate({
37
+ pg,
38
+ table: 'crm.files',
39
+ id: params.id,
40
+ data,
41
+ uid: user?.uid,
42
+ });
43
+
44
+ if (!result?.file_id) {
45
+ return reply.status(404).send('file not found');
46
+ }
47
+
48
+ return reply.status(200).send({
49
+ rowCount: 1,
50
+ data: result,
51
+ command: 'UPLOAD',
52
+ id: result?.file_id,
53
+ entity_id: result?.entity_id,
54
+ });
55
+ }
@@ -0,0 +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
+ }
@@ -0,0 +1,137 @@
1
+ import getMeta from '../../../plugins/pg/funcs/getMeta.js';
2
+ import getToken from '../../../plugins/crud/funcs/getToken.js';
3
+ import pgClients from '../../../plugins/pg/pgClients.js';
4
+
5
+ const galleryExtList = ['png', 'svg', 'jpg', 'jpeg', 'gif', 'mp4', 'mov', 'avi'];
6
+ const username = 'coalesce(u.sur_name,\'\')||coalesce(\' \'||u.user_name,\'\') ||coalesce(\' \'||u.father_name,\'\')';
7
+
8
+ /**
9
+ * Дістає CRM для widget
10
+ *
11
+ */
12
+
13
+ export default async function widgetGet({
14
+ pg = pgClients.client, user = {}, params = {}, query = {}, unittest,
15
+ }, reply) {
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 (!objectid) {
23
+ return reply.status(400).send('not enough params: id');
24
+ }
25
+
26
+ const sqls = {
27
+ comment: pg.pk['admin.users']
28
+ ? `select communication_id, entity_id, body, subject, c.cdate, c.uid,
29
+ ${username} as username, u.login, u.avatar
30
+ from crm.communications c
31
+ left join admin.users u on u.uid=c.uid
32
+ where entity_id=$1 order by cdate desc`
33
+ : 'select communication_id, entity_id, body, subject, cdate, uid from crm.communications where entity_id=$1 order by cdate desc',
34
+
35
+ history: `select * from (
36
+ SELECT change_id, entity_id, entity_type, change_type, change_date, a.change_user_id, a.uid, a.cdate, b.json_agg as changes,
37
+ ${username} as username, u.login, u.avatar
38
+ FROM log.table_changes a
39
+ left join admin.users u on a.change_user_id = u.uid
40
+ left join lateral(
41
+ select json_agg(row_to_json(q)) from (
42
+ select change_data_id, entity_key, value_new, value_old from log.table_changes_data
43
+ where change_id=a.change_id
44
+ )q
45
+ )b on 1=1
46
+ where b.json_agg is not null and (entity_id=$1 or entity_id in (
47
+ select communication_id as comments from crm.communications where entity_id=$1
48
+ union all select checklist_id from crm.checklists where entity_id=$1)
49
+ )
50
+
51
+ union all
52
+ select change_id, entity_id, entity_type, change_type, change_date, a.change_user_id, a.uid, a.cdate, b.json_agg as changes,
53
+ ${username} as username, u.login, u.avatar
54
+ FROM log.table_changes a
55
+ left join admin.users u on a.change_user_id = u.uid
56
+ left join lateral(
57
+ select json_agg(o) from (
58
+ select json_object_agg(entity_key, coalesce(value_new, value_old)) as o from log.table_changes_data
59
+ where change_id=a.change_id and entity_key not in ('uid', 'file_status', 'editor_id', 'cdate', 'editor_date', 'entity_id')
60
+ )q
61
+ )b on 1=1
62
+ where a.change_type in ('INSERT', 'DELETE') and a.entity_id in (select file_id from crm.files where entity_id=$1)
63
+ limit 100
64
+
65
+ )q order by cdate desc limit 100`,
66
+
67
+ checklist: pg.pk['admin.users']
68
+ ? `SELECT checklist_id, entity_id, subject, is_done, done_date, c.uid, c.cdate, ${username} as username, u.login, u.avatar
69
+ FROM crm.checklists c
70
+ left join admin.users u on u.uid=c.uid
71
+ where entity_id=$1 order by cdate desc`
72
+ : 'SELECT checklist_id, entity_id, subject, is_done, done_date, uid, cdate FROM crm.checklists where entity_id=$1 order by cdate desc',
73
+
74
+ file: pg.pk['admin.users']
75
+ ? `SELECT file_id, entity_id, entity_type, file_path, uploaded_name, ext, size, c.uid, c.cdate, file_type, c.ismain,
76
+ ${username} as username, u.login, isverified, u.avatar, u.uid as author, file_status
77
+ FROM crm.files c
78
+ left join admin.users u on u.uid=c.uid
79
+ where entity_id=$1 and file_status<>3 order by cdate desc`
80
+ : `SELECT file_id, entity_id, entity_type, file_path, uploaded_name, ext, size, uid, cdate, file_type, ismain,
81
+ isverified, uid as author, file_status FROM crm.files c where entity_id=$1 and file_status<>3 order by cdate desc`,
82
+ gallery: pg.pk['admin.users']
83
+ ? `SELECT file_id, entity_id, entity_type, file_path, uploaded_name, ext, size, c.uid, c.cdate, file_type, c.ismain,
84
+ ${username} as username, u.login, u.avatar, isverified, u.avatar, c.uid as author, file_status
85
+ FROM crm.files c
86
+ left join admin.users u on u.uid=c.uid
87
+ where entity_id=$1 and file_status<>3 and ext = any($2) order by cdate desc`
88
+ : `SELECT file_id, entity_id, entity_type, file_path, uploaded_name, ext, size, c.uid, c.cdate, file_type, ismain,
89
+ 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`,
90
+
91
+ };
92
+
93
+ const q = sqls[params.type];
94
+
95
+ if (!q) {
96
+ return reply.status(400).send('invalid widget type');
97
+ }
98
+
99
+ /* data */
100
+ const time = [Date.now()];
101
+ const { rows = [] } = await pg.query(q, [objectid, params.type === 'gallery' ? galleryExtList : null].filter((el) => el));
102
+ rows.forEach(row => Object.assign(row, { username: row.username?.trim?.() || row.login }));
103
+ time.push(Date.now());
104
+
105
+ /* Object info */
106
+ const { tableName } = pg.pk['log.table_changes'] ? await pg.query(
107
+ 'select entity_type as "tableName" from log.table_changes where entity_id=$1 limit 1',
108
+ [objectid],
109
+ ).then(el => el.rows?.[0] || {}) : {};
110
+
111
+ const { pk, columns = [] } = await getMeta({ pg, table: tableName });
112
+
113
+ const authorIdColumn = columns.find(col => ['uid', 'created_by'].includes(col.name))?.name;
114
+
115
+ if (!pk && params.type === 'history' && !unittest) {
116
+ return reply.status(404).send('log table not found');
117
+ }
118
+
119
+ const q1 = `select ${username} as author, u.login, a.cdate, a.editor_date from ${tableName} a
120
+ left join admin.users u on a.${authorIdColumn}=u.uid where a.${pk}=$1 limit 1`;
121
+
122
+ const data = pg.pk['admin.users'] && pk && tableName ? await pg.query(q, [objectid, params.type === 'gallery' ? galleryExtList : null].filter((el) => el)).then(el => el.rows?.[0] || {}) : {};
123
+
124
+ if (query.debug && user?.user_type === 'admin') {
125
+ return {
126
+ q, type: params.type, q1, id: objectid, data,
127
+ };
128
+ }
129
+
130
+ return reply.status(200).send({
131
+ time: { data: time[1] - time[0] },
132
+ rows,
133
+ user: { uid: user?.uid, name: user?.user_name },
134
+ data: { author: data?.author, cdate: data?.cdate, edate: data?.editor_date },
135
+ objectid: params.objectid,
136
+ });
137
+ }
@@ -0,0 +1,106 @@
1
+ import path from 'node:path';
2
+
3
+ import getMeta from '../../../plugins/pg/funcs/getMeta.js';
4
+ import dataInsert from '../../../plugins/crud/funcs/dataInsert.js';
5
+ import dataUpdate from '../../../plugins/crud/funcs/dataUpdate.js';
6
+ import applyHook from '../../../plugins/hook/funcs/applyHook.js';
7
+ import uploadMultiPart from '../../../plugins/file/uploadMultiPart.js';
8
+
9
+ const tableList = {
10
+ comment: 'crm.communications',
11
+ gallery: 'crm.files',
12
+ file: 'crm.files',
13
+ checklist: 'crm.checklists',
14
+ };
15
+ const pkList = {
16
+ comment: 'communication_id',
17
+ checklist: 'checklist_id',
18
+ file: 'file_id',
19
+ gallery: 'file_id',
20
+ };
21
+
22
+ const galleryExtList = ['png', 'svg', 'jpg', 'jpeg', 'gif', 'mp4', 'mov', 'avi'];
23
+
24
+ export default async function widgetSet(req, reply) {
25
+ const {
26
+ pg, params = {}, session = {}, headers = {}, body = {}, user = {},
27
+ } = req;
28
+ const { type, id, objectid } = params;
29
+
30
+ if (!['comment', 'checklist', 'file', 'gallery'].includes(type)) {
31
+ return reply.status(400).send('param type not valid');
32
+ }
33
+
34
+ if (!objectid) {
35
+ return reply.status(400).send('not enough params: id');
36
+ }
37
+
38
+ const table = tableList[type];
39
+
40
+ // dsadasdad
41
+ if (['gallery', 'file'].includes(type) && headers['content-type']?.split?.(';')?.shift?.() === 'multipart/form-data') {
42
+ const file = await uploadMultiPart(req);
43
+ const extName = path.extname(file.filepath).slice(1).toLowerCase();
44
+
45
+ const data = {
46
+ uploaded_name: file?.originalFilename?.toLocaleLowerCase()?.replace(/'/g, '\'\''),
47
+ file_path: file?.relativeFilepath?.replace(/\\/g, '/'),
48
+ ext: extName,
49
+ size: file?.size,
50
+ file_status: 1,
51
+ uid: user?.uid || 1,
52
+ entity_id: objectid,
53
+ };
54
+
55
+ if (type === 'gallery' && !galleryExtList.includes(extName.toLowerCase())) {
56
+ return reply.status(400).send('invalid file extension');
57
+ }
58
+
59
+ const { rows = [] } = await dataInsert({
60
+ pg, table: 'crm.files', data, uid: user?.uid,
61
+ });
62
+
63
+ if (type === 'gallery') {
64
+ await pg.query(`update crm.files set ismain=true
65
+ where entity_id=$1
66
+ and file_id=$2
67
+ and (select count(*) = 0 from crm.files where entity_id=$1 and ismain)`, [objectid, rows[0]?.file_id]);
68
+ }
69
+
70
+ return {
71
+ rowCount: 1, data: 'ok', command: 'UPLOAD', id: rows[0]?.file_id, entity_id: rows[0]?.entity_id,
72
+ };
73
+ }
74
+ const { pk } = await getMeta({ pg, table });
75
+
76
+ if (!pk) {
77
+ return reply.status(404).send('table not found');
78
+ }
79
+
80
+ const data = { ...body, uid: user?.uid, entity_id: objectid };
81
+
82
+ await applyHook('onWidgetSet', {
83
+ pg,
84
+ link: req.path,
85
+ id,
86
+ objectid,
87
+ session,
88
+ type,
89
+ payload: data,
90
+ });
91
+
92
+ const result = id
93
+ ? await dataUpdate({
94
+ pg, table, data, id, uid: user?.uid,
95
+ })
96
+ : await dataInsert({
97
+ pg, table, data, uid: user?.uid,
98
+ });
99
+
100
+ return reply.status(200).send({
101
+ rowCount: result.rowCount,
102
+ data: 'ok',
103
+ command: result.command,
104
+ id: result.rows?.[0]?.[pkList[type]] || result?.[pkList[type]],
105
+ });
106
+ }
@@ -0,0 +1,13 @@
1
+ import pgClients from '../../../plugins/pg/pgClients.js';
2
+
3
+ export default async function onWidgetSet({
4
+ pg = pgClients.client, id, objectid, type, payload = {},
5
+ }) {
6
+ if (!id || !objectid || type !== 'gallery') {
7
+ return null;
8
+ }
9
+ if (payload?.ismain) {
10
+ await pg.query('update crm.files set ismain=false where entity_id=$1 and file_id<>$2', [objectid, id]);
11
+ }
12
+ return null;
13
+ }
@@ -0,0 +1,38 @@
1
+ import addHook from '../../plugins/hook/funcs/addHook.js';
2
+
3
+ import widgetDel from './controllers/widget.del.js';
4
+ import widgetSet from './controllers/widget.set.js';
5
+ import widgetGet from './controllers/widget.get.js';
6
+ import fileEdit from './controllers/file.edit.js';
7
+
8
+ import onWidgetSet from './hook/onWidgetSet.js';
9
+
10
+ const tableSchema = {
11
+ params: {
12
+ type: 'object',
13
+ properties: {
14
+ // type: { type: 'string', pattern: '^([\\d\\w]+)$' },
15
+ objectid: { type: 'string', pattern: '^([\\d\\w]+)$' },
16
+ id: { type: 'string', pattern: '^([\\d\\w]+)$' },
17
+ },
18
+ },
19
+ querystring: {
20
+ type: 'object',
21
+ properties: {
22
+ debug: { type: 'string', pattern: '^(\\d+)$' },
23
+ },
24
+ },
25
+ };
26
+
27
+ addHook('onWidgetSet', onWidgetSet);
28
+
29
+ const policy = ['site'];
30
+ const params = { config: { policy }, schema: tableSchema };
31
+
32
+ export default async function route(app, config = {}) {
33
+ const { prefix = '/api' } = config;
34
+ app.delete(`${prefix}/widget/:type/:objectid/:id`, params, widgetDel);
35
+ app.post(`${prefix}/widget/:type/:objectid/:id?`, params, widgetSet);
36
+ app.put(`${prefix}/file-edit/:id`, params, fileEdit);
37
+ app.get(`${prefix}/widget/:type/:objectid`, { config: { policy: ['public'] }, schema: tableSchema }, widgetGet);
38
+ }