@opengis/admin 0.1.53 → 0.1.55

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 (111) hide show
  1. package/README.md +29 -29
  2. package/config.js +4 -4
  3. package/dist/{add-page-DxsI9oTt.js → add-page-CWG_sjY-.js} +1 -1
  4. package/dist/{admin-interface-D1Z9zulm.js → admin-interface-AsFloazv.js} +67 -67
  5. package/dist/{admin-view-DE_wFOGr.js → admin-view-QbbIb27N.js} +2 -2
  6. package/dist/admin.js +1 -1
  7. package/dist/admin.umd.cjs +40 -40
  8. package/dist/{card-page-BEJ2rFfi.js → card-page-DCoKtnma.js} +22 -22
  9. package/dist/{card-view-RRo1C2UV.js → card-view-B-tInKRH.js} +1 -1
  10. package/dist/{edit-page-D4hRn8sR.js → edit-page-BBYenvB9.js} +1 -1
  11. package/dist/{import-file-CL8r9Pju.js → import-file-YqGiZOb_.js} +20 -13
  12. package/dist/style.css +1 -1
  13. package/module/settings/card/admin.roles.table/access.hbs +27 -27
  14. package/module/settings/card/admin.roles.table/general_info.hbs +16 -16
  15. package/module/settings/card/admin.roles.table/index.yml +14 -14
  16. package/module/settings/card/admin.roles.table/users.hbs +27 -27
  17. package/module/settings/card/admin.routes.table/general_info.hbs +40 -40
  18. package/module/settings/card/admin.routes.table/index.yml +8 -8
  19. package/module/settings/card/admin.routes.table/users.hbs +33 -33
  20. package/module/settings/card/admin.users.table/general_info.hbs +25 -25
  21. package/module/settings/card/admin.users.table/index.yml +12 -12
  22. package/module/settings/card/admin.users.table/logs.hbs +30 -30
  23. package/module/settings/card/admin.users.table/user_roles.hbs +24 -24
  24. package/module/settings/cls/core.actions.json +13 -13
  25. package/module/settings/cls/core.scope.json +13 -13
  26. package/module/settings/cls/properties.site_status.json +13 -13
  27. package/module/settings/cls/properties.widget_status.json +13 -13
  28. package/module/settings/cls/users.user_type.json +13 -13
  29. package/module/settings/form/admin.access.form.json +36 -36
  30. package/module/settings/form/admin.custom_column.form.json +71 -71
  31. package/module/settings/form/admin.properties.form.json +15 -15
  32. package/module/settings/form/admin.roles.form.json +19 -19
  33. package/module/settings/form/admin.routes.form.json +25 -25
  34. package/module/settings/form/admin.user_properties.form.json +15 -15
  35. package/module/settings/form/admin.user_roles.form.json +21 -21
  36. package/module/settings/form/admin.users.form.json +150 -150
  37. package/module/settings/form/user.user_roles.form.json +13 -13
  38. package/module/settings/interface/admin.properties.json +4 -4
  39. package/module/settings/interface/admin.roles.json +4 -4
  40. package/module/settings/interface/admin.routes.json +4 -4
  41. package/module/settings/interface/admin.users.json +4 -4
  42. package/module/settings/menu.json +50 -50
  43. package/module/settings/select/core.roles.json +2 -2
  44. package/module/settings/select/core.routes.sql +1 -1
  45. package/module/settings/select/core.user_uid.sql +1 -1
  46. package/module/settings/table/admin.access.table.json +77 -77
  47. package/module/settings/table/admin.custom_column.table.json +94 -94
  48. package/module/settings/table/admin.properties.table.json +33 -33
  49. package/module/settings/table/admin.roles.table.json +58 -58
  50. package/module/settings/table/admin.routes.table.json +67 -67
  51. package/module/settings/table/admin.user_properties.table.json +28 -28
  52. package/module/settings/table/admin.user_roles.table.json +66 -66
  53. package/module/settings/table/admin.users.table.json +119 -119
  54. package/package.json +81 -81
  55. package/plugin.js +162 -162
  56. package/server/helpers/controllers/badge.js +11 -11
  57. package/server/helpers/controllers/hb.js +2 -2
  58. package/server/helpers/controllers/map.js +2 -2
  59. package/server/helpers/controllers/mls.js +2 -2
  60. package/server/helpers/controllers/vue.js +2 -2
  61. package/server/helpers/index.mjs +13 -13
  62. package/server/plugins/docs.js +28 -28
  63. package/server/plugins/hook.js +229 -229
  64. package/server/plugins/vite.js +69 -69
  65. package/server/routes/calendar/controllers/calendar.data.js +89 -0
  66. package/server/routes/calendar/index.mjs +17 -0
  67. package/server/routes/data/controllers/cardData.js +56 -56
  68. package/server/routes/data/controllers/cardTabData.js +49 -49
  69. package/server/routes/data/controllers/funcs/getFilterSQL/index.js +92 -92
  70. package/server/routes/data/controllers/funcs/getFilterSQL/util/formatValue.js +170 -170
  71. package/server/routes/data/controllers/funcs/getFilterSQL/util/getCustomQuery.js +13 -13
  72. package/server/routes/data/controllers/funcs/getFilterSQL/util/getFilterQuery.js +64 -64
  73. package/server/routes/data/controllers/funcs/getFilterSQL/util/getOptimizedQuery.js +12 -12
  74. package/server/routes/data/controllers/funcs/getFilterSQL/util/getTableSql.js +34 -34
  75. package/server/routes/data/controllers/tableData.js +145 -149
  76. package/server/routes/data/controllers/tableDataId.js +27 -27
  77. package/server/routes/data/controllers/tableFilter.js +63 -63
  78. package/server/routes/data/controllers/utils/assignTokens.js +30 -30
  79. package/server/routes/data/controllers/utils/getColumns.js +21 -21
  80. package/server/routes/data/index.mjs +15 -15
  81. package/server/routes/data/schema.js +7 -7
  82. package/server/routes/menu/controllers/getMenu.js +34 -35
  83. package/server/routes/menu/index.mjs +5 -5
  84. package/server/routes/notifications/controllers/readNotifications.js +30 -30
  85. package/server/routes/notifications/controllers/userNotifications.js +64 -64
  86. package/server/routes/notifications/hook/onWidgetSet.js +63 -63
  87. package/server/routes/notifications/index.mjs +40 -40
  88. package/server/routes/properties/controllers/admin.properties.get.js +29 -29
  89. package/server/routes/properties/controllers/user.properties.get.js +34 -34
  90. package/server/routes/properties/controllers/user.properties.post.js +30 -30
  91. package/server/routes/properties/funcs/getSettings.js +56 -56
  92. package/server/routes/properties/funcs/setSettings.js +44 -44
  93. package/server/routes/properties/funcs/utils/dataInsert.js +26 -26
  94. package/server/routes/properties/index.mjs +26 -26
  95. package/server/routes/root.mjs +3 -3
  96. package/server/routes/templates/controllers/getTemplate.js +16 -16
  97. package/server/routes/templates/index.mjs +14 -14
  98. package/server/templates/cls/itree.recrzone_category.json +73 -73
  99. package/server/templates/cls/test.json +9 -9
  100. package/server/templates/form/admin.user_cls.data.form.json +49 -49
  101. package/server/templates/form/admin.user_group_rel.form.json +21 -21
  102. package/server/templates/form/cp_building.form.json +32 -32
  103. package/server/templates/form/form-user-pass.json +10 -10
  104. package/server/templates/form/form-user_group.json +39 -39
  105. package/server/templates/form/form-users.json +156 -156
  106. package/server/templates/form/user_group_access.form.json +22 -22
  107. package/server/templates/select/account_id.json +2 -2
  108. package/server/templates/table/gis.dataset.table.json +43 -43
  109. package/server/templates/table/management.user_group.table.json +112 -112
  110. package/server/templates/table/management.users.table.json +126 -126
  111. package/utils.js +21 -50
@@ -1,229 +1,229 @@
1
- import fp from 'fastify-plugin';
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
-
5
- import { addHook, getTemplatePath, getTemplate, pgClients } from '@opengis/fastify-table/utils.js';
6
-
7
- import getMenu from '../routes/menu/controllers/getMenu.js';
8
-
9
- import config from '../../config.js';
10
-
11
- // to export the decorators to the outer scope
12
-
13
- async function plugin(fastify) {
14
- fastify.decorate('config', config);
15
-
16
- addHook('afterTemplate', async ({ req, data = {} }) => {
17
- const { uid } = req.session.passport?.user || {};
18
- if (!uid || !data?.schema || req.params?.type !== 'form' || !req.params?.name) return null;
19
- const { pg, params = {} } = req;
20
- const { rows: properties = [] } = await pg.query(`select name, title, format, data from admin.custom_column
21
- where entity=$1 and uid=$2`, [params.name?.replace('.form', '.table'), uid]);
22
- await Promise.all(properties.map(async (el) => {
23
- const clsData = el.data ? await getTemplate(['cls', 'select'], el.data) : undefined;
24
- const type = clsData ? 'Select' : ({ date: 'DatePicker' }[el.format] || 'Text');
25
- debugger;
26
- Object.assign(data.schema || {}, { [el.name]: { type, ua: el.title, data: el.data, options: type === 'Check' ? clsData : undefined, extra: 1 } });
27
- }));
28
- });
29
-
30
- addHook('afterUpdate', async ({ req, res = {} }) => {
31
- const {
32
- pg, session = {}, params = {}, body = {},
33
- } = req;
34
- const { uid } = session.passport?.user || {};
35
- if (!uid) return null;
36
-
37
- const loadTable = await getTemplate('table', params.table);
38
- if (!pg.pk[loadTable?.table || params.table]) return null;
39
- const pk = pg.pk[loadTable?.table || params.table];
40
- const id = res[pk];
41
-
42
- const { rows: properties = [] } = await pg.query(`select column_id, name, title, format, data from admin.custom_column
43
- where entity=$1 and uid=$2`, [params.table, uid]);
44
-
45
- if (!id || !properties?.length) return null;
46
-
47
- const q = `delete from crm.extra_data where property_entity='${params.table}' and object_id='${id}';${properties
48
- .filter((el) => Object.keys(body).includes(el.name))
49
- .map((el) => `insert into crm.extra_data(property_id,property_key,property_entity,object_id,${el.format?.toLowerCase() === 'date' ? 'value_date' : 'value_text'})
50
- select '${el.column_id}', '${el.name}', '${params.table}', '${id}', ${el.format?.toLowerCase() === 'date' ? `'${body[el.name]}'::timestamp without time zone` : `'${body[el.name]}'::text`}`)
51
- .join(';\n') || ''}`;
52
- return pg.query(q);
53
- });
54
-
55
- addHook('afterInsert', async ({ req, res = {} }) => {
56
- const {
57
- pg, session = {}, params = {}, body = {},
58
- } = req;
59
- const { uid } = session.passport?.user || {};
60
- if (!uid) return null;
61
-
62
- const loadTable = await getTemplate('table', params.table);
63
- if (!pg.pk[loadTable?.table || params.table]) return null;
64
- const pk = pg.pk[loadTable?.table || params.table];
65
- const id = res.rows?.[0]?.[pk];
66
-
67
- const { rows: properties = [] } = await pg.query(`select column_id, name, title, format, data from admin.custom_column
68
- where entity=$1 and uid=$2`, [params.table, uid]);
69
-
70
- if (!id || !properties?.length) return null;
71
-
72
- const q = properties
73
- .filter((el) => Object.keys(body).includes(el.name))
74
- .map((el) => `insert into crm.extra_data(property_id,property_key,property_entity,object_id,${el.format?.toLowerCase() === 'date' ? 'value_date' : 'value_text'})
75
- select '${el.column_id}', '${el.name}', '${params.table}', '${id}', ${el.format?.toLowerCase() === 'date' ? `'${body[el.name]}'::timestamp without time zone` : `'${body[el.name]}'::text`}`)
76
- .join(';\n');
77
- return pg.query(q);
78
- });
79
-
80
- fastify.addHook('onListen', async () => {
81
- const { client } = pgClients;
82
- const json = await getMenu();
83
- // insert interface list to db (user access management)
84
- if (client?.pk?.['admin.routes'] && json?.length) {
85
- const menuList = json.filter((el) => el?.menu?.length && el?.ua || el?.en || el?.name);
86
- const interfaces = menuList.reduce((acc, curr) => { curr.menu.forEach((el) => acc.push(el.path)); return acc; }, []);
87
- await client.query('update admin.routes set enabled=false where not array[route_id] <@ $1::text[]', [interfaces]);
88
-
89
- const q = `insert into admin.menu(name, ord) values${menuList.map((el, i) => `('${(el?.ua || el?.en || el?.name).replace(/'/g, '’')}', ${i}) `).join(',')
90
- } on conflict (name) do update set ord=excluded.ord, enabled=true returning name, menu_id`;
91
- const { rows = [] } = await client.query(q);
92
- await client.query('update admin.menu set enabled=false where not array[menu_id] <@ $1::text[]', [rows.map((el) => el.menu_id)]);
93
-
94
- const menus = rows.reduce((acc, curr) => Object.assign(acc, { [curr.menu_id]: menuList.find((item) => (item?.ua || item?.en || item?.name) === curr.name) }), {});
95
- const values = Object.entries(menus).reduce((acc, curr) => { curr[1]?.menu?.forEach((el) => acc.push({ ...el, menuId: curr[0] })); return acc; }, []);
96
-
97
- await Promise.all(values.filter((el) => el?.table).map(async (el) => Object.assign(el, { table: (await getTemplate('table', el.table))?.table || el.table })));
98
-
99
- const q1 = `insert into admin.routes(route_id, alias, title, menu_id, table_name) values ${values.map((el) => `('${el.path}', '${el.path}', '${el.title}', '${el.menuId}', '${el.table}')`).join(',')}
100
- on conflict (route_id) do update set menu_id=excluded.menu_id, title=excluded.title, enabled=true,
101
- table_name=excluded.table_name returning route_id, table_name`;
102
- try {
103
- const { rowCount } = await client.query(q1);
104
- // console.log('interface insert ok', values, rowCount);
105
- } catch (err) {
106
- console.log('interface insert error', values, q1, err);
107
- }
108
- }
109
- });
110
-
111
- fastify.addHook('onListen', async () => {
112
- const { client: pg } = pgClients;
113
- const clsQuery = [];
114
- if (!pg.pk?.['admin.cls']) return;
115
-
116
- const selectList = await getTemplatePath('select');
117
- const clsList = (await getTemplatePath('cls'))?.filter((el) => !(selectList?.map((el) => el?.[0]) || []).includes(el[0]));
118
- const cls = (selectList || []).concat(clsList || [])
119
- ?.map((el) => ({ name: el[0], module: path.basename(path.dirname(path.dirname(el[1]))), type: { 'json': 'cls', 'sql': 'select' }[el[2]] }))
120
- if (!cls?.length) return;
121
-
122
- const dupes = cls.filter((el, idx, arr) => arr.map((item) => item.name).indexOf(el.name) !== idx);
123
- // console.log('cls insert skip dupes', dupes.map((el) => el.name));
124
-
125
- try {
126
- await Promise.all(cls.filter((el, idx, arr) => arr.map((item) => item.name).indexOf(el.name) === idx).map(async (el) => {
127
- const { name, module, type } = el;
128
- const loadTemplate = await getTemplate(type, name);
129
- //console.log(name, type);
130
- if (type === 'select') {
131
- clsQuery.push(`insert into admin.cls(name,type,data,module) values('${name}','sql','${(loadTemplate?.sql || loadTemplate)?.replace(/'/g, "''")}', '${module?.replace(/'/g, "''")}')`);
132
- } else if (type === 'cls' && loadTemplate?.length) {
133
- clsQuery.push(`insert into admin.cls(name,type, module) values('${name}','json', '${module?.replace(/'/g, "''")}');
134
- insert into admin.cls(code,name,parent,icon)
135
- select value->>'id',value->>'text','${name}',value->>'icon'
136
- from json_array_elements('${JSON.stringify(loadTemplate).replace(/'/g, "''")}'::json)`);
137
- } else {
138
- console.log(name, type, 'empty');
139
- }
140
- }));
141
-
142
- await pg.query('truncate admin.cls');
143
- if (clsQuery.filter((el) => el).length) {
144
- await pg.query(clsQuery.filter((el) => el).join(';'));
145
- console.log('cls insert ok', clsQuery?.length);
146
- }
147
- } catch (err) {
148
- console.error('cls insert error', err.toString());
149
- }
150
- });
151
-
152
- // pre Request
153
- fastify.addHook('onRequest', async (req) => {
154
- req.funcs = fastify;
155
- const { user } = req.session?.passport || {};
156
- req.user = user;
157
- });
158
-
159
- // preSerialization
160
- fastify.addHook('preSerialization', async (req, reply, payload) => {
161
- if (req.url.includes('/suggest/') && !req.query.json) {
162
- return payload?.data;
163
- }
164
- if (payload?.redirect) {
165
- return reply.redirect(payload.redirect);
166
- }
167
- if (reply.sent) {
168
- return null;
169
- }
170
-
171
- if (['200', '400', '500', '403', '404'].includes(payload?.status)) {
172
- reply.status(payload.status);
173
- }
174
- /* if (payload.headers) {
175
- reply.headers(payload.headers);
176
- } */
177
- if (payload?.buffer) {
178
- return payload.buffer;
179
- }
180
- if (payload?.file) {
181
- // const buffer = await readFile(payload.file);
182
- // return reply.send(buffer);
183
- const stream = fs.createReadStream(payload.file);
184
- return stream;
185
- // return reply.send(stream);
186
- }
187
-
188
- if (payload?.message) {
189
- return payload.message;
190
- }
191
- return payload;
192
- });
193
-
194
- // preValidation
195
- fastify.addHook('preValidation', async (req) => {
196
- const parseRawBody = ['POST', 'PUT'].includes(req.method) && req.body && typeof req.body === 'string'
197
- && req.body.trim(/\r\n/g).startsWith('{')
198
- && req.body.trim(/\r\n/g).endsWith('}');
199
- if (parseRawBody) {
200
- try {
201
- req.body = JSON.parse(req.body || '{}');
202
- }
203
- catch (err) {
204
- // throw new Error('invalid body');
205
- // return { error: 'invalid body', status: 400 };
206
- }
207
- }
208
- });
209
-
210
- // allow upload file
211
- const kIsMultipart = Symbol.for('[FastifyMultipart.isMultipart]');
212
- fastify.addContentTypeParser('multipart', (request, _, done) => {
213
- request[kIsMultipart] = true;
214
- done(null);
215
- });
216
-
217
- // parse Body
218
- function contentParser(req, body, done) {
219
- const parseBody = decodeURIComponent(body.toString()).split('&').reduce((acc, el) => {
220
- const [key, val] = el.split('=');
221
- return { ...acc, [key]: val };
222
- }, {});
223
- done(null, parseBody);
224
- }
225
-
226
- fastify.addContentTypeParser('application/x-www-form-urlencoded', { parseAs: 'buffer' }, contentParser);
227
- }
228
-
229
- export default fp(plugin);
1
+ import fp from 'fastify-plugin';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ import { addHook, getTemplatePath, getTemplate, pgClients } from '@opengis/fastify-table/utils.js';
6
+
7
+ import getMenu from '../routes/menu/controllers/getMenu.js';
8
+
9
+ import config from '../../config.js';
10
+
11
+ // to export the decorators to the outer scope
12
+
13
+ async function plugin(fastify) {
14
+ fastify.decorate('config', config);
15
+
16
+ addHook('afterTemplate', async ({ req, data = {} }) => {
17
+ const { uid } = req.session.passport?.user || {};
18
+ if (!uid || !data?.schema || req.params?.type !== 'form' || !req.params?.name) return null;
19
+ const { pg, params = {} } = req;
20
+ const { rows: properties = [] } = await pg.query(`select name, title, format, data from admin.custom_column
21
+ where entity=$1 and uid=$2`, [params.name?.replace('.form', '.table'), uid]);
22
+ await Promise.all(properties.map(async (el) => {
23
+ const clsData = el.data ? await getTemplate(['cls', 'select'], el.data) : undefined;
24
+ const type = clsData ? 'Select' : ({ date: 'DatePicker' }[el.format] || 'Text');
25
+ debugger;
26
+ Object.assign(data.schema || {}, { [el.name]: { type, ua: el.title, data: el.data, options: type === 'Check' ? clsData : undefined, extra: 1 } });
27
+ }));
28
+ });
29
+
30
+ addHook('afterUpdate', async ({ req, res = {} }) => {
31
+ const {
32
+ pg, session = {}, params = {}, body = {},
33
+ } = req;
34
+ const { uid } = session.passport?.user || {};
35
+ if (!uid) return null;
36
+
37
+ const loadTable = await getTemplate('table', params.table);
38
+ if (!pg.pk[loadTable?.table || params.table]) return null;
39
+ const pk = pg.pk[loadTable?.table || params.table];
40
+ const id = res[pk];
41
+
42
+ const { rows: properties = [] } = await pg.query(`select column_id, name, title, format, data from admin.custom_column
43
+ where entity=$1 and uid=$2`, [params.table, uid]);
44
+
45
+ if (!id || !properties?.length) return null;
46
+
47
+ const q = `delete from crm.extra_data where property_entity='${params.table}' and object_id='${id}';${properties
48
+ .filter((el) => Object.keys(body).includes(el.name))
49
+ .map((el) => `insert into crm.extra_data(property_id,property_key,property_entity,object_id,${el.format?.toLowerCase() === 'date' ? 'value_date' : 'value_text'})
50
+ select '${el.column_id}', '${el.name}', '${params.table}', '${id}', ${el.format?.toLowerCase() === 'date' ? `'${body[el.name]}'::timestamp without time zone` : `'${body[el.name]}'::text`}`)
51
+ .join(';\n') || ''}`;
52
+ return pg.query(q);
53
+ });
54
+
55
+ addHook('afterInsert', async ({ req, res = {} }) => {
56
+ const {
57
+ pg, session = {}, params = {}, body = {},
58
+ } = req;
59
+ const { uid } = session.passport?.user || {};
60
+ if (!uid) return null;
61
+
62
+ const loadTable = await getTemplate('table', params.table);
63
+ if (!pg.pk[loadTable?.table || params.table]) return null;
64
+ const pk = pg.pk[loadTable?.table || params.table];
65
+ const id = res.rows?.[0]?.[pk];
66
+
67
+ const { rows: properties = [] } = await pg.query(`select column_id, name, title, format, data from admin.custom_column
68
+ where entity=$1 and uid=$2`, [params.table, uid]);
69
+
70
+ if (!id || !properties?.length) return null;
71
+
72
+ const q = properties
73
+ .filter((el) => Object.keys(body).includes(el.name))
74
+ .map((el) => `insert into crm.extra_data(property_id,property_key,property_entity,object_id,${el.format?.toLowerCase() === 'date' ? 'value_date' : 'value_text'})
75
+ select '${el.column_id}', '${el.name}', '${params.table}', '${id}', ${el.format?.toLowerCase() === 'date' ? `'${body[el.name]}'::timestamp without time zone` : `'${body[el.name]}'::text`}`)
76
+ .join(';\n');
77
+ return pg.query(q);
78
+ });
79
+
80
+ fastify.addHook('onListen', async () => {
81
+ const { client } = pgClients;
82
+ const json = await getMenu();
83
+ // insert interface list to db (user access management)
84
+ if (client?.pk?.['admin.routes'] && json?.length) {
85
+ const menuList = json.filter((el) => el?.menu?.length && el?.ua || el?.en || el?.name);
86
+ const interfaces = menuList.reduce((acc, curr) => { curr.menu.forEach((el) => acc.push(el.path)); return acc; }, []);
87
+ await client.query('update admin.routes set enabled=false where not array[route_id] <@ $1::text[]', [interfaces]);
88
+
89
+ const q = `insert into admin.menu(name, ord) values${menuList.map((el, i) => `('${(el?.ua || el?.en || el?.name).replace(/'/g, '’')}', ${i}) `).join(',')
90
+ } on conflict (name) do update set ord=excluded.ord, enabled=true returning name, menu_id`;
91
+ const { rows = [] } = await client.query(q);
92
+ await client.query('update admin.menu set enabled=false where not array[menu_id] <@ $1::text[]', [rows.map((el) => el.menu_id)]);
93
+
94
+ const menus = rows.reduce((acc, curr) => Object.assign(acc, { [curr.menu_id]: menuList.find((item) => (item?.ua || item?.en || item?.name) === curr.name) }), {});
95
+ const values = Object.entries(menus).reduce((acc, curr) => { curr[1]?.menu?.forEach((el) => acc.push({ ...el, menuId: curr[0] })); return acc; }, []);
96
+
97
+ await Promise.all(values.filter((el) => el?.table).map(async (el) => Object.assign(el, { table: (await getTemplate('table', el.table))?.table || el.table })));
98
+
99
+ const q1 = `insert into admin.routes(route_id, alias, title, menu_id, table_name) values ${values.map((el) => `('${el.path}', '${el.path}', '${el.title}', '${el.menuId}', '${el.table}')`).join(',')}
100
+ on conflict (route_id) do update set menu_id=excluded.menu_id, title=excluded.title, enabled=true,
101
+ table_name=excluded.table_name returning route_id, table_name`;
102
+ try {
103
+ const { rowCount } = await client.query(q1);
104
+ // console.log('interface insert ok', values, rowCount);
105
+ } catch (err) {
106
+ console.log('interface insert error', values, q1, err);
107
+ }
108
+ }
109
+ });
110
+
111
+ fastify.addHook('onListen', async () => {
112
+ const { client: pg } = pgClients;
113
+ const clsQuery = [];
114
+ if (!pg.pk?.['admin.cls']) return;
115
+
116
+ const selectList = await getTemplatePath('select');
117
+ const clsList = (await getTemplatePath('cls'))?.filter((el) => !(selectList?.map((el) => el?.[0]) || []).includes(el[0]));
118
+ const cls = (selectList || []).concat(clsList || [])
119
+ ?.map((el) => ({ name: el[0], module: path.basename(path.dirname(path.dirname(el[1]))), type: { 'json': 'cls', 'sql': 'select' }[el[2]] }))
120
+ if (!cls?.length) return;
121
+
122
+ const dupes = cls.filter((el, idx, arr) => arr.map((item) => item.name).indexOf(el.name) !== idx);
123
+ // console.log('cls insert skip dupes', dupes.map((el) => el.name));
124
+
125
+ try {
126
+ await Promise.all(cls.filter((el, idx, arr) => arr.map((item) => item.name).indexOf(el.name) === idx).map(async (el) => {
127
+ const { name, module, type } = el;
128
+ const loadTemplate = await getTemplate(type, name);
129
+ //console.log(name, type);
130
+ if (type === 'select') {
131
+ clsQuery.push(`insert into admin.cls(name,type,data,module) values('${name}','sql','${(loadTemplate?.sql || loadTemplate)?.replace(/'/g, "''")}', '${module?.replace(/'/g, "''")}')`);
132
+ } else if (type === 'cls' && loadTemplate?.length) {
133
+ clsQuery.push(`insert into admin.cls(name,type, module) values('${name}','json', '${module?.replace(/'/g, "''")}');
134
+ insert into admin.cls(code,name,parent,icon)
135
+ select value->>'id',value->>'text','${name}',value->>'icon'
136
+ from json_array_elements('${JSON.stringify(loadTemplate).replace(/'/g, "''")}'::json)`);
137
+ } else {
138
+ console.log(name, type, 'empty');
139
+ }
140
+ }));
141
+
142
+ await pg.query('truncate admin.cls');
143
+ if (clsQuery.filter((el) => el).length) {
144
+ await pg.query(clsQuery.filter((el) => el).join(';'));
145
+ console.log('cls insert ok', clsQuery?.length);
146
+ }
147
+ } catch (err) {
148
+ console.error('cls insert error', err.toString());
149
+ }
150
+ });
151
+
152
+ // pre Request
153
+ fastify.addHook('onRequest', async (req) => {
154
+ req.funcs = fastify;
155
+ const { user } = req.session?.passport || {};
156
+ req.user = user;
157
+ });
158
+
159
+ // preSerialization
160
+ fastify.addHook('preSerialization', async (req, reply, payload) => {
161
+ if (req.url.includes('/suggest/') && !req.query.json) {
162
+ return payload?.data;
163
+ }
164
+ if (payload?.redirect) {
165
+ return reply.redirect(payload.redirect);
166
+ }
167
+ if (reply.sent) {
168
+ return null;
169
+ }
170
+
171
+ if (['200', '400', '500', '403', '404'].includes(payload?.status)) {
172
+ reply.status(payload.status);
173
+ }
174
+ /* if (payload.headers) {
175
+ reply.headers(payload.headers);
176
+ } */
177
+ if (payload?.buffer) {
178
+ return payload.buffer;
179
+ }
180
+ if (payload?.file) {
181
+ // const buffer = await readFile(payload.file);
182
+ // return reply.send(buffer);
183
+ const stream = fs.createReadStream(payload.file);
184
+ return stream;
185
+ // return reply.send(stream);
186
+ }
187
+
188
+ if (payload?.message) {
189
+ return payload.message;
190
+ }
191
+ return payload;
192
+ });
193
+
194
+ // preValidation
195
+ fastify.addHook('preValidation', async (req) => {
196
+ const parseRawBody = ['POST', 'PUT'].includes(req.method) && req.body && typeof req.body === 'string'
197
+ && req.body.trim(/\r\n/g).startsWith('{')
198
+ && req.body.trim(/\r\n/g).endsWith('}');
199
+ if (parseRawBody) {
200
+ try {
201
+ req.body = JSON.parse(req.body || '{}');
202
+ }
203
+ catch (err) {
204
+ // throw new Error('invalid body');
205
+ // return { error: 'invalid body', status: 400 };
206
+ }
207
+ }
208
+ });
209
+
210
+ // allow upload file
211
+ const kIsMultipart = Symbol.for('[FastifyMultipart.isMultipart]');
212
+ fastify.addContentTypeParser('multipart', (request, _, done) => {
213
+ request[kIsMultipart] = true;
214
+ done(null);
215
+ });
216
+
217
+ // parse Body
218
+ function contentParser(req, body, done) {
219
+ const parseBody = decodeURIComponent(body.toString()).split('&').reduce((acc, el) => {
220
+ const [key, val] = el.split('=');
221
+ return { ...acc, [key]: val };
222
+ }, {});
223
+ done(null, parseBody);
224
+ }
225
+
226
+ fastify.addContentTypeParser('application/x-www-form-urlencoded', { parseAs: 'buffer' }, contentParser);
227
+ }
228
+
229
+ export default fp(plugin);
@@ -1,69 +1,69 @@
1
- import fs from 'fs';
2
- import path, { dirname } from 'path';
3
- import { fileURLToPath } from 'url';
4
-
5
- const dir = dirname(fileURLToPath(import.meta.url));
6
- const root = `${dir}/../..`;
7
-
8
- const isProduction = process.env.NODE_ENV === 'production';
9
-
10
- async function plugin(fastify) {
11
- // vite server
12
- if (!isProduction) {
13
- const vite = await import('vite');
14
-
15
- const viteServer = await vite.createServer({
16
- server: {
17
- middlewareMode: true,
18
- },
19
- });
20
- // hot reload
21
- viteServer.watcher.on('all', function (d, t) {
22
- if (!t.includes('module')) return;
23
- console.log(d, t);
24
- viteServer.ws.send({ type: 'full-reload' });
25
- });
26
-
27
- // this is middleware for vite's dev servert
28
- fastify.addHook('onRequest', async (req, reply) => {
29
- const { user } = req.session?.passport || {};
30
- const { disableAuth } = req.funcs?.config || {};
31
- if (!user && !disableAuth) {
32
- // return reply.send('access restricted');
33
- }
34
-
35
- const next = () => new Promise((resolve) => {
36
- viteServer.middlewares(req.raw, reply.raw, () => resolve());
37
- });
38
- await next();
39
- });
40
- fastify.get('*', async () => { });
41
- return;
42
- }
43
-
44
- // From Build
45
- fastify.get('*', async (req, reply) => {
46
- const { user } = req.session?.passport || {};
47
-
48
- // if (!user) return reply.redirect('/login');
49
- const stream = fs.createReadStream('dist/index.html');
50
- return reply.type('text/html').send(stream);
51
- });
52
-
53
- async function staticFile(req, reply) {
54
- const assetsDir = 'dist';
55
- const filePath = path.join(root, assetsDir, req.url);
56
- const ext = path.extname(filePath);
57
- const mime = {
58
- '.js': 'text/javascript', '.css': 'text/css', '.woff2': 'application/font-woff', '.png': 'image/png', '.svg': 'image/svg+xml', '.jpg': 'image/jpg',
59
- }[ext];
60
- reply.headers({ 'Cache-control': 'max-age=3600, public' });
61
- const stream = fs.createReadStream(filePath);
62
- return mime ? reply.type(mime).send(stream) : stream;
63
- }
64
-
65
- fastify.get('/assets/*', staticFile);
66
- fastify.get('/public/*', staticFile);
67
- }
68
-
69
- export default plugin;
1
+ import fs from 'fs';
2
+ import path, { dirname } from 'path';
3
+ import { fileURLToPath } from 'url';
4
+
5
+ const dir = dirname(fileURLToPath(import.meta.url));
6
+ const root = `${dir}/../..`;
7
+
8
+ const isProduction = process.env.NODE_ENV === 'production';
9
+
10
+ async function plugin(fastify) {
11
+ // vite server
12
+ if (!isProduction) {
13
+ const vite = await import('vite');
14
+
15
+ const viteServer = await vite.createServer({
16
+ server: {
17
+ middlewareMode: true,
18
+ },
19
+ });
20
+ // hot reload
21
+ viteServer.watcher.on('all', function (d, t) {
22
+ if (!t.includes('module')) return;
23
+ console.log(d, t);
24
+ viteServer.ws.send({ type: 'full-reload' });
25
+ });
26
+
27
+ // this is middleware for vite's dev servert
28
+ fastify.addHook('onRequest', async (req, reply) => {
29
+ const { user } = req.session?.passport || {};
30
+ const { disableAuth } = req.funcs?.config || {};
31
+ if (!user && !disableAuth) {
32
+ // return reply.send('access restricted');
33
+ }
34
+
35
+ const next = () => new Promise((resolve) => {
36
+ viteServer.middlewares(req.raw, reply.raw, () => resolve());
37
+ });
38
+ await next();
39
+ });
40
+ fastify.get('*', async () => { });
41
+ return;
42
+ }
43
+
44
+ // From Build
45
+ fastify.get('*', async (req, reply) => {
46
+ const { user } = req.session?.passport || {};
47
+
48
+ // if (!user) return reply.redirect('/login');
49
+ const stream = fs.createReadStream('dist/index.html');
50
+ return reply.type('text/html').send(stream);
51
+ });
52
+
53
+ async function staticFile(req, reply) {
54
+ const assetsDir = 'dist';
55
+ const filePath = path.join(root, assetsDir, req.url);
56
+ const ext = path.extname(filePath);
57
+ const mime = {
58
+ '.js': 'text/javascript', '.css': 'text/css', '.woff2': 'application/font-woff', '.png': 'image/png', '.svg': 'image/svg+xml', '.jpg': 'image/jpg',
59
+ }[ext];
60
+ reply.headers({ 'Cache-control': 'max-age=3600, public' });
61
+ const stream = fs.createReadStream(filePath);
62
+ return mime ? reply.type(mime).send(stream) : stream;
63
+ }
64
+
65
+ fastify.get('/assets/*', staticFile);
66
+ fastify.get('/public/*', staticFile);
67
+ }
68
+
69
+ export default plugin;