@opengis/admin 0.1.76 → 0.1.77

Sign up to get free protection for your applications and to get access to all the features.
Files changed (134) hide show
  1. package/README.md +29 -29
  2. package/config.js +4 -4
  3. package/dist/{IconChevronDown-BMnTiJIv.js → IconChevronDown-C7p-qa08.js} +1 -1
  4. package/dist/{add-page-BxK4iJe4.js → add-page-BjxUl0Xb.js} +1 -1
  5. package/dist/{admin-interface-D9vWpTqM.js → admin-interface-hP6bBpCA.js} +4 -4
  6. package/dist/{admin-view-DPtlpZue.js → admin-view-Bg210Kja.js} +3 -3
  7. package/dist/admin.js +1 -1
  8. package/dist/admin.umd.cjs +6 -6
  9. package/dist/assets/logo.svg +41 -41
  10. package/dist/{card-page-KnsaeAPW.js → card-page-DrVSEjOf.js} +2 -2
  11. package/dist/{card-view-BAC53pSQ.js → card-view-CrrcS8Wm.js} +1 -1
  12. package/dist/{edit-page-D2KM1hue.js → edit-page-CJxp0cdD.js} +1 -1
  13. package/dist/{import-file-C3Slz6rJ.js → import-file-L1iBMu59.js} +22 -15
  14. package/dist/style.css +1 -1
  15. package/module/settings/card/admin.roles.table/access.hbs +27 -27
  16. package/module/settings/card/admin.roles.table/general_info.hbs +16 -16
  17. package/module/settings/card/admin.roles.table/index.yml +14 -14
  18. package/module/settings/card/admin.roles.table/users.hbs +27 -27
  19. package/module/settings/card/admin.routes.table/general_info.hbs +40 -40
  20. package/module/settings/card/admin.routes.table/index.yml +8 -8
  21. package/module/settings/card/admin.routes.table/users.hbs +33 -33
  22. package/module/settings/card/admin.users.table/general_info.hbs +25 -25
  23. package/module/settings/card/admin.users.table/index.yml +12 -12
  24. package/module/settings/card/admin.users.table/logs.hbs +30 -30
  25. package/module/settings/card/admin.users.table/user_roles.hbs +24 -24
  26. package/module/settings/cls/core.actions.json +13 -13
  27. package/module/settings/cls/core.scope.json +13 -13
  28. package/module/settings/cls/properties.site_status.json +13 -13
  29. package/module/settings/cls/properties.widget_status.json +13 -13
  30. package/module/settings/cls/users.user_type.json +13 -13
  31. package/module/settings/form/admin.access.form.json +36 -36
  32. package/module/settings/form/admin.custom_column.form.json +71 -71
  33. package/module/settings/form/admin.properties.form.json +15 -15
  34. package/module/settings/form/admin.roles.form.json +19 -19
  35. package/module/settings/form/admin.routes.form.json +25 -25
  36. package/module/settings/form/admin.user_properties.form.json +15 -15
  37. package/module/settings/form/admin.user_roles.form.json +21 -21
  38. package/module/settings/form/admin.users.form.json +153 -153
  39. package/module/settings/form/user.user_roles.form.json +13 -13
  40. package/module/settings/interface/admin.properties.json +4 -4
  41. package/module/settings/interface/admin.roles.json +4 -4
  42. package/module/settings/interface/admin.routes.json +4 -4
  43. package/module/settings/interface/admin.users.json +4 -4
  44. package/module/settings/menu.json +50 -50
  45. package/module/settings/select/core.roles.json +2 -2
  46. package/module/settings/select/core.routes.sql +1 -1
  47. package/module/settings/select/core.user_mentioned.sql +1 -1
  48. package/module/settings/select/core.user_uid.sql +1 -1
  49. package/module/settings/table/admin.access.table.json +83 -83
  50. package/module/settings/table/admin.custom_column.table.json +99 -99
  51. package/module/settings/table/admin.properties.table.json +39 -39
  52. package/module/settings/table/admin.roles.table.json +64 -64
  53. package/module/settings/table/admin.routes.table.json +68 -68
  54. package/module/settings/table/admin.user_properties.table.json +34 -34
  55. package/module/settings/table/admin.user_roles.table.json +72 -72
  56. package/module/settings/table/admin.users.table.json +121 -121
  57. package/package.json +82 -82
  58. package/plugin.js +27 -27
  59. package/server/helpers/controllers/badge.js +11 -11
  60. package/server/helpers/controllers/hb.js +2 -2
  61. package/server/helpers/controllers/map.js +2 -2
  62. package/server/helpers/controllers/mls.js +2 -2
  63. package/server/helpers/controllers/vue.js +2 -2
  64. package/server/helpers/index.mjs +15 -15
  65. package/server/plugins/adminHook.js +93 -93
  66. package/server/plugins/cron.js +10 -10
  67. package/server/plugins/docs.js +28 -28
  68. package/server/plugins/hook.js +214 -214
  69. package/server/plugins/vite.js +71 -71
  70. package/server/routes/calendar/controllers/calendar.data.js +88 -88
  71. package/server/routes/calendar/index.mjs +7 -7
  72. package/server/routes/calendar/schema.js +21 -21
  73. package/server/routes/data/controllers/cardData.js +61 -57
  74. package/server/routes/data/controllers/cardTabData.js +49 -49
  75. package/server/routes/data/controllers/funcs/getFilterSQL/index.js +92 -92
  76. package/server/routes/data/controllers/funcs/getFilterSQL/util/formatValue.js +170 -170
  77. package/server/routes/data/controllers/funcs/getFilterSQL/util/getCustomQuery.js +13 -13
  78. package/server/routes/data/controllers/funcs/getFilterSQL/util/getFilterQuery.js +64 -64
  79. package/server/routes/data/controllers/funcs/getFilterSQL/util/getOptimizedQuery.js +12 -12
  80. package/server/routes/data/controllers/funcs/getFilterSQL/util/getTableSql.js +34 -34
  81. package/server/routes/data/controllers/tableData.js +11 -11
  82. package/server/routes/data/controllers/tableDataId.js +27 -27
  83. package/server/routes/data/controllers/tableFilter.js +63 -63
  84. package/server/routes/data/controllers/utils/assignTokens.js +30 -30
  85. package/server/routes/data/controllers/utils/getColumns.js +8 -8
  86. package/server/routes/data/index.mjs +15 -15
  87. package/server/routes/data/schema.js +54 -54
  88. package/server/routes/menu/controllers/getMenu.js +67 -67
  89. package/server/routes/menu/index.mjs +5 -5
  90. package/server/routes/notifications/controllers/readNotifications.js +27 -27
  91. package/server/routes/notifications/controllers/testEmail.js +35 -35
  92. package/server/routes/notifications/controllers/userNotifications.js +57 -57
  93. package/server/routes/notifications/funcs/addNotification.js +21 -21
  94. package/server/routes/notifications/funcs/sendNotification.js +105 -105
  95. package/server/routes/notifications/hook/onWidgetSet.js +57 -57
  96. package/server/routes/notifications/index.mjs +27 -27
  97. package/server/routes/notifications/schema.js +16 -16
  98. package/server/routes/properties/controllers/admin.properties.get.js +29 -29
  99. package/server/routes/properties/controllers/user.properties.get.js +34 -34
  100. package/server/routes/properties/controllers/user.properties.post.js +30 -30
  101. package/server/routes/properties/funcs/getSettings.js +56 -56
  102. package/server/routes/properties/funcs/setSettings.js +44 -44
  103. package/server/routes/properties/funcs/utils/dataInsert.js +26 -26
  104. package/server/routes/properties/index.mjs +14 -14
  105. package/server/routes/properties/schema.js +10 -10
  106. package/server/routes/root.mjs +3 -3
  107. package/server/routes/templates/controllers/getTemplate.js +22 -22
  108. package/server/routes/templates/index.mjs +14 -14
  109. package/server/routes/templates/scheme.js +8 -8
  110. package/server/routes/user/controllers/user.cls.id.js +14 -14
  111. package/server/routes/user/controllers/user.cls.js +71 -71
  112. package/server/routes/user/controllers/user.cls.post.js +52 -52
  113. package/server/routes/user/controllers/user.info.js +17 -17
  114. package/server/routes/user/schema.js +14 -14
  115. package/server/routes/widget/controllers/utils/historyFormat.js +75 -75
  116. package/server/routes/widget/controllers/utils/obj2db.js +13 -13
  117. package/server/routes/widget/controllers/widget.del.js +41 -41
  118. package/server/routes/widget/controllers/widget.get.js +96 -96
  119. package/server/routes/widget/controllers/widget.set.js +76 -76
  120. package/server/routes/widget/index.mjs +39 -39
  121. package/server/templates/cls/itree.recrzone_category.json +73 -73
  122. package/server/templates/cls/test.json +9 -9
  123. package/server/templates/form/admin.user_cls.data.form.json +49 -49
  124. package/server/templates/form/admin.user_group_rel.form.json +21 -21
  125. package/server/templates/form/cp_building.form.json +32 -32
  126. package/server/templates/form/form-user-pass.json +10 -10
  127. package/server/templates/form/form-user_group.json +39 -39
  128. package/server/templates/form/form-users.json +156 -156
  129. package/server/templates/form/user_group_access.form.json +22 -22
  130. package/server/templates/select/account_id.json +2 -2
  131. package/server/templates/table/gis.dataset.table.json +43 -43
  132. package/server/templates/table/management.user_group.table.json +112 -112
  133. package/server/templates/table/management.users.table.json +126 -126
  134. package/utils.js +26 -26
@@ -1,215 +1,215 @@
1
- import path from 'node:path';
2
-
3
- import {
4
- getTemplatePath, addHook, getToken, getTemplate, config, pgClients,
5
- initPG,
6
- } from '@opengis/fastify-table/utils.js';
7
-
8
- import getMenu from '../routes/menu/controllers/getMenu.js';
9
-
10
- const { client } = pgClients;
11
-
12
- export default async function plugin(fastify) {
13
- const user1 = config?.auth?.disable || process.env.NODE_ENV !== 'admin' ? { uid: '1' } : null;
14
- await initPG(client);
15
-
16
- fastify.addHook('onListen', async () => {
17
- const json = await getMenu({ user: { uid: 1 } });
18
- // insert interface list to db (user access management)
19
- if (client?.pk?.['admin.routes'] && json?.length) {
20
- const menuList = json.filter((el) => el?.menu?.length && el?.ua || el?.en || el?.name);
21
- const interfaces = menuList.reduce((acc, curr) => { curr.menu.forEach((el) => acc.push(el.path)); return acc; }, []);
22
- await client.query('update admin.routes set enabled=false where not array[route_id] <@ $1::text[]', [interfaces]);
23
-
24
- const q = `insert into admin.menu(name, ord) values${menuList.map((el, i) => `('${(el?.ua || el?.en || el?.name).replace(/'/g, '’')}', ${i}) `).join(',')
25
- } on conflict (name) do update set ord=excluded.ord, enabled=true returning name, menu_id`;
26
- const { rows = [] } = menuList?.length ? await client.query(q) : {};
27
- await client.query('update admin.menu set enabled=false where not array[menu_id] <@ $1::text[]', [rows.map((el) => el.menu_id)]);
28
-
29
- const menus = rows.reduce((acc, curr) => Object.assign(acc, { [curr.menu_id]: menuList.find((item) => (item?.ua || item?.en || item?.name) === curr.name) }), {});
30
- const values = Object.entries(menus).reduce((acc, curr) => { curr[1]?.menu?.forEach((el) => acc.push({ ...el, menuId: curr[0] })); return acc; }, []);
31
-
32
- await Promise.all(values.filter((el) => el?.table).map(async (el) => {
33
- const loadTable = await getTemplate('table', el.table);
34
- Object.assign(el, {
35
- table1: loadTable?.table || el.table,
36
- actions: loadTable?.actions,
37
- access: loadTable?.access,
38
- });
39
- }));
40
-
41
- const q1 = `insert into admin.routes(route_id, alias, title, menu_id, table_name, actions, access)
42
- values ${values.map((el) => `('${el.path}', '${el.table}', ${(el.title || el.ua) ? `'${el.title || el.ua}'` : 'null'}, '${el.menuId}', '${el.table1}',
43
- ${el.actions?.length ? `'{ ${el.actions} }'::text[]` : 'null'}, ${el.access ? `'${el.access}'` : 'null'})`).join(',')}
44
- on conflict (route_id) do update set menu_id=excluded.menu_id, alias=excluded.alias, title=excluded.title, enabled=true,
45
- table_name=excluded.table_name, actions=excluded.actions, access=excluded.access returning route_id, table_name`;
46
- try {
47
- const { rowCount } = values?.length ? await client.query(q1) : {};
48
- console.log('interface insert ok', /* values, */ rowCount);
49
- } catch (err) {
50
- console.log('interface insert error', values, q1, err);
51
- }
52
- }
53
- });
54
-
55
- fastify.addHook('onListen', async () => {
56
- const clsQuery = [];
57
- if (!client?.pk?.['admin.cls']) return;
58
-
59
- const selectList = await getTemplatePath('select');
60
- const clsList = (await getTemplatePath('cls'))?.filter((el) => !(selectList?.map((el) => el?.[0]) || []).includes(el[0]));
61
- const cls = (selectList || []).concat(clsList || [])
62
- ?.map((el) => ({ name: el[0], module: path.basename(path.dirname(path.dirname(el[1]))), type: { 'json': 'cls', 'sql': 'select' }[el[2]] }))
63
- if (!cls?.length) return;
64
-
65
- const dupes = cls.filter((el, idx, arr) => arr.map((item) => item.name).indexOf(el.name) !== idx);
66
- //console.log('cls insert skip dupes', dupes.map((el) => el.name));
67
-
68
- try {
69
- await Promise.all(cls.filter((el, idx, arr) => arr.map((item) => item.name).indexOf(el.name) === idx).map(async (el) => {
70
- const { name, module, type } = el;
71
- const loadTemplate = await getTemplate(type, name);
72
- // console.log(name, type);
73
- if (type === 'select') {
74
- clsQuery.push(`insert into admin.cls(name,type,data,module) values('${name}','sql','${(loadTemplate?.sql || loadTemplate)?.replace(/'/g, "''")}', '${module?.replace(/'/g, "''")}')`);
75
- } else if (type === 'cls' && loadTemplate?.length) {
76
- clsQuery.push(`insert into admin.cls(name,type, module) values('${name}','json', '${module?.replace(/'/g, "''")}');
77
- insert into admin.cls(code,name,parent,icon)
78
- select value->>'id',value->>'text','${name}',value->>'icon'
79
- from json_array_elements('${JSON.stringify(loadTemplate).replace(/'/g, "''")}'::json)`);
80
- } else {
81
- console.log(name, type, 'empty');
82
- }
83
- }));
84
-
85
- await client.query('truncate admin.cls');
86
- if (clsQuery.filter((el) => el).length) {
87
- await client.query(clsQuery.filter((el) => el).join(';'));
88
- console.log('cls insert ok', clsQuery?.length);
89
- }
90
- } catch (err) {
91
- console.error('cls insert error', err.toString());
92
- }
93
- });
94
-
95
- addHook('afterTable', async ({ table, res = {}, payload: rows = [], user = {} }) => {
96
- const loadTable = await getTemplate('table', table);
97
- const { uid } = user1 || user;
98
- if (!uid || !table || !client?.pk?.[table] || !rows.length || !loadTable?.table) return;
99
-
100
- // admin.custom_column - user column data
101
- const { rows: properties = [] } = await client.query(`select column_id, name, title, format, data from admin.custom_column
102
- where _table and entity=$1 and uid=$2`, [table, uid]);
103
- const extraColumnList = properties.map((row) => ({ id: row.column_id, name: row.name, title: row.title, format: row.format, data: row.data }));
104
- if (!extraColumnList?.length) return;
105
-
106
- if (res?.columns?.length) {
107
- extraColumnList.forEach((col) => res.columns.push(col));
108
- }
109
-
110
- const { rows: extraData = [] } = await client.query(`select object_id, json_object_agg( property_id, coalesce(value_date::text,value_text) ) as extra from crm.extra_data
111
- where property_entity=$1 and property_id=any($2) and object_id=any($3) group by object_id`, [table, extraColumnList?.map((el) => el.id), rows.map((el) => el.id)]);
112
-
113
- if (!extraData?.length) {
114
- // Object.assign(rows?.[0] || {}, { ...extraColumnList.reduce((acc, curr) => Object.assign(acc, { [curr.name]: null }), {}) });
115
- return;
116
- }
117
-
118
- rows.filter((row) => extraData.map((el) => el?.object_id).includes(row.id)).forEach((row) => {
119
- const { extra = {} } = extraData.find((el) => el.object_id === row.id);
120
- Object.assign(row, { ...Object.fromEntries(Object.entries(extra).map((el) => [extraColumnList.find((col) => col.id === el[0]).name, el[1]])) });
121
- });
122
-
123
- // admin.custom_column - metaFormat
124
- await Promise.all(extraColumnList.filter((el) => el?.data).map(async (attr) => {
125
- const values = [...new Set(rows?.map((el) => el[attr.name]).flat())].filter((el) => el);
126
- if (!values.length) return;
127
- const cls = await getSelectVal({ name: attr.data, values });
128
- if (!cls) return;
129
- rows.forEach(el => {
130
- const val = el[attr.name]?.map?.(c => cls[c] || c) || cls[el[attr.name]] || el[attr.name];
131
- if (!val) return;
132
- Object.assign(el, { [val?.color ? `${attr.name}_data` : `${attr.name}_text`]: (val.color ? val : val.text || val) });
133
- });
134
- }));
135
- });
136
-
137
- // extract table from form token for user columns - p.2 - read (refactor to global token)
138
- addHook('preTemplate', async ({ name, type, user = {} }) => {
139
- if (!name || !type) return;
140
- const { uid } = user1 || user;
141
- const tokenData = await getToken({
142
- uid, token: name, mode: 'w', json: 1,
143
- }) // edit?
144
- || await getToken({
145
- uid, token: name, mode: 'a', json: 1,
146
- }) || {}; // add?
147
- return { name: tokenData?.[type] };
148
- });
149
-
150
- addHook('afterTemplate', async ({ name, type, payload: data = {}, user = {} }) => {
151
- const { uid } = user1 || user;
152
- // extract table from form token for user columns - p.1 - assign (refactor to global token)
153
- if (!uid || !data || type !== 'form' || !name) return null;
154
-
155
- const { form, id, table } = await getToken({
156
- uid, token: name, mode: 'w', json: 1,
157
- }) // edit?
158
- || await getToken({
159
- uid, token: name, mode: 'a', json: 1,
160
- }) || {}; // add?
161
-
162
- const { rows: properties = [] } = await client.query(`select name, title, format, data from admin.custom_column
163
- where entity=$1 and uid=$2`, [table || name, uid]);
164
-
165
- await Promise.all(properties.map(async (el) => {
166
- const clsData = el.data ? await getTemplate(['cls', 'select'], el.data) : undefined;
167
- const type = clsData ? 'Select' : ({ date: 'DatePicker' }[el.format] || 'Text');
168
- Object.assign(data?.schema || data || {}, { [el.name]: { type, ua: el.title, data: el.data, options: type === 'Select' && Array.isArray(clsData) && clsData?.length ? clsData : undefined, extra: 1 } });
169
- }));
170
- });
171
-
172
- addHook('afterUpdate', async ({ table, body = {}, payload: res = {}, user = {} }) => {
173
- const { uid } = user1 || user;
174
- if (!uid || !table || !Object.keys(body)?.length) return null;
175
-
176
- const loadTable = await getTemplate('table', table);
177
- if (!client?.pk?.[loadTable?.table || table]) return null;
178
- const pk = client?.pk?.[loadTable?.table || table];
179
- const id = res[pk];
180
-
181
- const { rows: properties = [] } = await client.query(`select column_id, name, title, format, data from admin.custom_column
182
- where entity=$1 and uid=$2`, [table, uid]);
183
-
184
- if (!id || !properties?.length) return null;
185
-
186
- const q = `delete from crm.extra_data where property_entity='${table}' and object_id='${id}';${properties
187
- .filter((el) => Object.keys(body).includes(el.name))
188
- .map((el) => `insert into crm.extra_data(property_id,property_key,property_entity,object_id,${el.format?.toLowerCase() === 'date' ? 'value_date' : 'value_text'})
189
- select '${el.column_id}', '${el.name}', '${table}', '${id}', ${el.format?.toLowerCase() === 'date' ? `'${body[el.name]}'::timestamp without time zone` : `'${body[el.name]}'::text`}`)
190
- .join(';\n') || ''}`;
191
- return client.query(q);
192
- });
193
-
194
- addHook('afterInsert', async ({ table, body = {}, payload: res = {}, user = {} }) => {
195
- const { uid } = user1 || user;
196
- if (!uid || !table || !Object.keys(body)?.length) return null;
197
-
198
- const loadTable = await getTemplate('table', table);
199
- if (!client?.pk?.[loadTable?.table || table]) return null;
200
- const pk = client?.pk?.[loadTable?.table || table];
201
- const id = res.rows?.[0]?.[pk];
202
-
203
- const { rows: properties = [] } = await client.query(`select column_id, name, title, format, data from admin.custom_column
204
- where entity=$1 and uid=$2`, [table, uid]);
205
-
206
- if (!id || !properties?.length) return null;
207
-
208
- const q = properties
209
- .filter((el) => Object.keys(body).includes(el.name))
210
- .map((el) => `insert into crm.extra_data(property_id,property_key,property_entity,object_id,${el.format?.toLowerCase() === 'date' ? 'value_date' : 'value_text'})
211
- select '${el.column_id}', '${el.name}', '${table}', '${id}', ${el.format?.toLowerCase() === 'date' ? `'${body[el.name]}'::timestamp without time zone` : `'${body[el.name]}'::text`}`)
212
- .join(';\n');
213
- return client.query(q);
214
- });
1
+ import path from 'node:path';
2
+
3
+ import {
4
+ getTemplatePath, addHook, getToken, getTemplate, config, pgClients,
5
+ initPG,
6
+ } from '@opengis/fastify-table/utils.js';
7
+
8
+ import getMenu from '../routes/menu/controllers/getMenu.js';
9
+
10
+ const { client } = pgClients;
11
+
12
+ export default async function plugin(fastify) {
13
+ const user1 = config?.auth?.disable || process.env.NODE_ENV !== 'admin' ? { uid: '1' } : null;
14
+ await initPG(client);
15
+
16
+ fastify.addHook('onListen', async () => {
17
+ const json = await getMenu({ user: { uid: 1 } });
18
+ // insert interface list to db (user access management)
19
+ if (client?.pk?.['admin.routes'] && json?.length) {
20
+ const menuList = json.filter((el) => el?.menu?.length && el?.ua || el?.en || el?.name);
21
+ const interfaces = menuList.reduce((acc, curr) => { curr.menu.forEach((el) => acc.push(el.path)); return acc; }, []);
22
+ await client.query('update admin.routes set enabled=false where not array[route_id] <@ $1::text[]', [interfaces]);
23
+
24
+ const q = `insert into admin.menu(name, ord) values${menuList.map((el, i) => `('${(el?.ua || el?.en || el?.name).replace(/'/g, '’')}', ${i}) `).join(',')
25
+ } on conflict (name) do update set ord=excluded.ord, enabled=true returning name, menu_id`;
26
+ const { rows = [] } = menuList?.length ? await client.query(q) : {};
27
+ await client.query('update admin.menu set enabled=false where not array[menu_id] <@ $1::text[]', [rows.map((el) => el.menu_id)]);
28
+
29
+ const menus = rows.reduce((acc, curr) => Object.assign(acc, { [curr.menu_id]: menuList.find((item) => (item?.ua || item?.en || item?.name) === curr.name) }), {});
30
+ const values = Object.entries(menus).reduce((acc, curr) => { curr[1]?.menu?.forEach((el) => acc.push({ ...el, menuId: curr[0] })); return acc; }, []);
31
+
32
+ await Promise.all(values.filter((el) => el?.table).map(async (el) => {
33
+ const loadTable = await getTemplate('table', el.table);
34
+ Object.assign(el, {
35
+ table1: loadTable?.table || el.table,
36
+ actions: loadTable?.actions,
37
+ access: loadTable?.access,
38
+ });
39
+ }));
40
+
41
+ const q1 = `insert into admin.routes(route_id, alias, title, menu_id, table_name, actions, access)
42
+ values ${values.map((el) => `('${el.path}', '${el.table}', ${(el.title || el.ua) ? `'${el.title || el.ua}'` : 'null'}, '${el.menuId}', '${el.table1}',
43
+ ${el.actions?.length ? `'{ ${el.actions} }'::text[]` : 'null'}, ${el.access ? `'${el.access}'` : 'null'})`).join(',')}
44
+ on conflict (route_id) do update set menu_id=excluded.menu_id, alias=excluded.alias, title=excluded.title, enabled=true,
45
+ table_name=excluded.table_name, actions=excluded.actions, access=excluded.access returning route_id, table_name`;
46
+ try {
47
+ const { rowCount } = values?.length ? await client.query(q1) : {};
48
+ console.log('interface insert ok', /* values, */ rowCount);
49
+ } catch (err) {
50
+ console.log('interface insert error', values, q1, err);
51
+ }
52
+ }
53
+ });
54
+
55
+ fastify.addHook('onListen', async () => {
56
+ const clsQuery = [];
57
+ if (!client?.pk?.['admin.cls']) return;
58
+
59
+ const selectList = await getTemplatePath('select');
60
+ const clsList = (await getTemplatePath('cls'))?.filter((el) => !(selectList?.map((el) => el?.[0]) || []).includes(el[0]));
61
+ const cls = (selectList || []).concat(clsList || [])
62
+ ?.map((el) => ({ name: el[0], module: path.basename(path.dirname(path.dirname(el[1]))), type: { 'json': 'cls', 'sql': 'select' }[el[2]] }))
63
+ if (!cls?.length) return;
64
+
65
+ const dupes = cls.filter((el, idx, arr) => arr.map((item) => item.name).indexOf(el.name) !== idx);
66
+ //console.log('cls insert skip dupes', dupes.map((el) => el.name));
67
+
68
+ try {
69
+ await Promise.all(cls.filter((el, idx, arr) => arr.map((item) => item.name).indexOf(el.name) === idx).map(async (el) => {
70
+ const { name, module, type } = el;
71
+ const loadTemplate = await getTemplate(type, name);
72
+ // console.log(name, type);
73
+ if (type === 'select') {
74
+ clsQuery.push(`insert into admin.cls(name,type,data,module) values('${name}','sql','${(loadTemplate?.sql || loadTemplate)?.replace(/'/g, "''")}', '${module?.replace(/'/g, "''")}')`);
75
+ } else if (type === 'cls' && loadTemplate?.length) {
76
+ clsQuery.push(`insert into admin.cls(name,type, module) values('${name}','json', '${module?.replace(/'/g, "''")}');
77
+ insert into admin.cls(code,name,parent,icon)
78
+ select value->>'id',value->>'text','${name}',value->>'icon'
79
+ from json_array_elements('${JSON.stringify(loadTemplate).replace(/'/g, "''")}'::json)`);
80
+ } else {
81
+ console.log(name, type, 'empty');
82
+ }
83
+ }));
84
+
85
+ await client.query('truncate admin.cls');
86
+ if (clsQuery.filter((el) => el).length) {
87
+ await client.query(clsQuery.filter((el) => el).join(';'));
88
+ console.log('cls insert ok', clsQuery?.length);
89
+ }
90
+ } catch (err) {
91
+ console.error('cls insert error', err.toString());
92
+ }
93
+ });
94
+
95
+ addHook('afterTable', async ({ table, res = {}, payload: rows = [], user = {} }) => {
96
+ const loadTable = await getTemplate('table', table);
97
+ const { uid } = user1 || user;
98
+ if (!uid || !table || !client?.pk?.[table] || !rows.length || !loadTable?.table) return;
99
+
100
+ // admin.custom_column - user column data
101
+ const { rows: properties = [] } = await client.query(`select column_id, name, title, format, data from admin.custom_column
102
+ where _table and entity=$1 and uid=$2`, [table, uid]);
103
+ const extraColumnList = properties.map((row) => ({ id: row.column_id, name: row.name, title: row.title, format: row.format, data: row.data }));
104
+ if (!extraColumnList?.length) return;
105
+
106
+ if (res?.columns?.length) {
107
+ extraColumnList.forEach((col) => res.columns.push(col));
108
+ }
109
+
110
+ const { rows: extraData = [] } = await client.query(`select object_id, json_object_agg( property_id, coalesce(value_date::text,value_text) ) as extra from crm.extra_data
111
+ where property_entity=$1 and property_id=any($2) and object_id=any($3) group by object_id`, [table, extraColumnList?.map((el) => el.id), rows.map((el) => el.id)]);
112
+
113
+ if (!extraData?.length) {
114
+ // Object.assign(rows?.[0] || {}, { ...extraColumnList.reduce((acc, curr) => Object.assign(acc, { [curr.name]: null }), {}) });
115
+ return;
116
+ }
117
+
118
+ rows.filter((row) => extraData.map((el) => el?.object_id).includes(row.id)).forEach((row) => {
119
+ const { extra = {} } = extraData.find((el) => el.object_id === row.id);
120
+ Object.assign(row, { ...Object.fromEntries(Object.entries(extra).map((el) => [extraColumnList.find((col) => col.id === el[0]).name, el[1]])) });
121
+ });
122
+
123
+ // admin.custom_column - metaFormat
124
+ await Promise.all(extraColumnList.filter((el) => el?.data).map(async (attr) => {
125
+ const values = [...new Set(rows?.map((el) => el[attr.name]).flat())].filter((el) => el);
126
+ if (!values.length) return;
127
+ const cls = await getSelectVal({ name: attr.data, values });
128
+ if (!cls) return;
129
+ rows.forEach(el => {
130
+ const val = el[attr.name]?.map?.(c => cls[c] || c) || cls[el[attr.name]] || el[attr.name];
131
+ if (!val) return;
132
+ Object.assign(el, { [val?.color ? `${attr.name}_data` : `${attr.name}_text`]: (val.color ? val : val.text || val) });
133
+ });
134
+ }));
135
+ });
136
+
137
+ // extract table from form token for user columns - p.2 - read (refactor to global token)
138
+ addHook('preTemplate', async ({ name, type, user = {} }) => {
139
+ if (!name || !type) return;
140
+ const { uid } = user1 || user;
141
+ const tokenData = await getToken({
142
+ uid, token: name, mode: 'w', json: 1,
143
+ }) // edit?
144
+ || await getToken({
145
+ uid, token: name, mode: 'a', json: 1,
146
+ }) || {}; // add?
147
+ return { name: tokenData?.[type] };
148
+ });
149
+
150
+ addHook('afterTemplate', async ({ name, type, payload: data = {}, user = {} }) => {
151
+ const { uid } = user1 || user;
152
+ // extract table from form token for user columns - p.1 - assign (refactor to global token)
153
+ if (!uid || !data || type !== 'form' || !name) return null;
154
+
155
+ const { form, id, table } = await getToken({
156
+ uid, token: name, mode: 'w', json: 1,
157
+ }) // edit?
158
+ || await getToken({
159
+ uid, token: name, mode: 'a', json: 1,
160
+ }) || {}; // add?
161
+
162
+ const { rows: properties = [] } = await client.query(`select name, title, format, data from admin.custom_column
163
+ where entity=$1 and uid=$2`, [table || name, uid]);
164
+
165
+ await Promise.all(properties.map(async (el) => {
166
+ const clsData = el.data ? await getTemplate(['cls', 'select'], el.data) : undefined;
167
+ const type = clsData ? 'Select' : ({ date: 'DatePicker' }[el.format] || 'Text');
168
+ Object.assign(data?.schema || data || {}, { [el.name]: { type, ua: el.title, data: el.data, options: type === 'Select' && Array.isArray(clsData) && clsData?.length ? clsData : undefined, extra: 1 } });
169
+ }));
170
+ });
171
+
172
+ addHook('afterUpdate', async ({ table, body = {}, payload: res = {}, user = {} }) => {
173
+ const { uid } = user1 || user;
174
+ if (!uid || !table || !Object.keys(body)?.length) return null;
175
+
176
+ const loadTable = await getTemplate('table', table);
177
+ if (!client?.pk?.[loadTable?.table || table]) return null;
178
+ const pk = client?.pk?.[loadTable?.table || table];
179
+ const id = res[pk];
180
+
181
+ const { rows: properties = [] } = await client.query(`select column_id, name, title, format, data from admin.custom_column
182
+ where entity=$1 and uid=$2`, [table, uid]);
183
+
184
+ if (!id || !properties?.length) return null;
185
+
186
+ const q = `delete from crm.extra_data where property_entity='${table}' and object_id='${id}';${properties
187
+ .filter((el) => Object.keys(body).includes(el.name))
188
+ .map((el) => `insert into crm.extra_data(property_id,property_key,property_entity,object_id,${el.format?.toLowerCase() === 'date' ? 'value_date' : 'value_text'})
189
+ select '${el.column_id}', '${el.name}', '${table}', '${id}', ${el.format?.toLowerCase() === 'date' ? `'${body[el.name]}'::timestamp without time zone` : `'${body[el.name]}'::text`}`)
190
+ .join(';\n') || ''}`;
191
+ return client.query(q);
192
+ });
193
+
194
+ addHook('afterInsert', async ({ table, body = {}, payload: res = {}, user = {} }) => {
195
+ const { uid } = user1 || user;
196
+ if (!uid || !table || !Object.keys(body)?.length) return null;
197
+
198
+ const loadTable = await getTemplate('table', table);
199
+ if (!client?.pk?.[loadTable?.table || table]) return null;
200
+ const pk = client?.pk?.[loadTable?.table || table];
201
+ const id = res.rows?.[0]?.[pk];
202
+
203
+ const { rows: properties = [] } = await client.query(`select column_id, name, title, format, data from admin.custom_column
204
+ where entity=$1 and uid=$2`, [table, uid]);
205
+
206
+ if (!id || !properties?.length) return null;
207
+
208
+ const q = properties
209
+ .filter((el) => Object.keys(body).includes(el.name))
210
+ .map((el) => `insert into crm.extra_data(property_id,property_key,property_entity,object_id,${el.format?.toLowerCase() === 'date' ? 'value_date' : 'value_text'})
211
+ select '${el.column_id}', '${el.name}', '${table}', '${id}', ${el.format?.toLowerCase() === 'date' ? `'${body[el.name]}'::timestamp without time zone` : `'${body[el.name]}'::text`}`)
212
+ .join(';\n');
213
+ return client.query(q);
214
+ });
215
215
  }
@@ -1,71 +1,71 @@
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
- if (!user) return reply.redirect('/login');
31
-
32
- const next = () => new Promise((resolve) => {
33
- viteServer.middlewares(req.raw, reply.raw, () => resolve());
34
- });
35
- await next();
36
- });
37
- fastify.get('*', async () => { });
38
- return;
39
- }
40
-
41
- // From Build
42
- fastify.get('*', async (req, reply) => {
43
- const { user } = req.session?.passport || {};
44
-
45
- if (!user) return reply.redirect('/login');
46
- const stream = fs.createReadStream('dist/index.html');
47
- return reply.type('text/html').send(stream);
48
- });
49
-
50
- const fileSize = {}
51
- async function staticFile(req, reply) {
52
- const assetsDir = 'dist';
53
- const filePath = path.join(root, assetsDir, req.url);
54
- const ext = path.extname(filePath);
55
-
56
- if (!fs.existsSync(filePath)) return { status: 404, message: 'not found' }
57
- fileSize[filePath] = fileSize[filePath] || fs.statSync(filePath).size;
58
- const mime = {
59
- '.js': 'text/javascript', '.css': 'text/css', '.woff2': 'application/font-woff', '.png': 'image/png', '.svg': 'image/svg+xml', '.jpg': 'image/jpg',
60
- }[ext];
61
- reply.headers({ 'Cache-control': 'max-age=3600, public', 'Content-length': fileSize[filePath], 'Content-Encoding': 'identity' });
62
-
63
- const stream = fs.createReadStream(filePath);
64
- return mime ? reply.type(mime).send(stream) : stream;
65
- }
66
-
67
- fastify.get('/assets/*', staticFile);
68
- fastify.get('/public/*', staticFile);
69
- }
70
-
71
- 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
+ if (!user) return reply.redirect('/login');
31
+
32
+ const next = () => new Promise((resolve) => {
33
+ viteServer.middlewares(req.raw, reply.raw, () => resolve());
34
+ });
35
+ await next();
36
+ });
37
+ fastify.get('*', async () => { });
38
+ return;
39
+ }
40
+
41
+ // From Build
42
+ fastify.get('*', async (req, reply) => {
43
+ const { user } = req.session?.passport || {};
44
+
45
+ if (!user) return reply.redirect('/login');
46
+ const stream = fs.createReadStream('dist/index.html');
47
+ return reply.type('text/html').send(stream);
48
+ });
49
+
50
+ const fileSize = {}
51
+ async function staticFile(req, reply) {
52
+ const assetsDir = 'dist';
53
+ const filePath = path.join(root, assetsDir, req.url);
54
+ const ext = path.extname(filePath);
55
+
56
+ if (!fs.existsSync(filePath)) return { status: 404, message: 'not found' }
57
+ fileSize[filePath] = fileSize[filePath] || fs.statSync(filePath).size;
58
+ const mime = {
59
+ '.js': 'text/javascript', '.css': 'text/css', '.woff2': 'application/font-woff', '.png': 'image/png', '.svg': 'image/svg+xml', '.jpg': 'image/jpg',
60
+ }[ext];
61
+ reply.headers({ 'Cache-control': 'max-age=3600, public', 'Content-length': fileSize[filePath], 'Content-Encoding': 'identity' });
62
+
63
+ const stream = fs.createReadStream(filePath);
64
+ return mime ? reply.type(mime).send(stream) : stream;
65
+ }
66
+
67
+ fastify.get('/assets/*', staticFile);
68
+ fastify.get('/public/*', staticFile);
69
+ }
70
+
71
+ export default plugin;