@opengis/fastify-table 1.2.12 → 1.2.13

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 (66) hide show
  1. package/README.md +86 -86
  2. package/index.js +79 -79
  3. package/package.json +1 -1
  4. package/server/migrations/0.sql +84 -84
  5. package/server/migrations/cls.sql +39 -39
  6. package/server/migrations/properties.sql +184 -184
  7. package/server/migrations/template.sql +34 -34
  8. package/server/migrations/users.sql +175 -175
  9. package/server/plugins/cron/funcs/addCron.js +130 -130
  10. package/server/plugins/cron/index.js +6 -6
  11. package/server/plugins/crud/funcs/dataDelete.js +24 -24
  12. package/server/plugins/crud/funcs/dataInsert.js +53 -53
  13. package/server/plugins/crud/funcs/dataUpdate.js +65 -65
  14. package/server/plugins/crud/funcs/getOpt.js +13 -13
  15. package/server/plugins/crud/funcs/setOpt.js +21 -21
  16. package/server/plugins/crud/funcs/setToken.js +44 -44
  17. package/server/plugins/crud/funcs/utils/getFolder.js +10 -10
  18. package/server/plugins/crud/funcs/utils/logChanges.js +118 -118
  19. package/server/plugins/crud/index.js +23 -23
  20. package/server/plugins/hook/index.js +8 -8
  21. package/server/plugins/logger/errorStatus.js +19 -19
  22. package/server/plugins/logger/index.js +21 -21
  23. package/server/plugins/migration/exec.migrations.js +37 -37
  24. package/server/plugins/migration/index.js +7 -7
  25. package/server/plugins/pg/pgClients.js +21 -21
  26. package/server/plugins/policy/index.js +12 -12
  27. package/server/plugins/policy/sqlInjection.js +33 -33
  28. package/server/plugins/redis/client.js +8 -8
  29. package/server/plugins/redis/funcs/redisClients.js +3 -3
  30. package/server/plugins/redis/index.js +17 -17
  31. package/server/plugins/table/funcs/addTemplateDir.js +8 -8
  32. package/server/plugins/table/funcs/getFilterSQL/index.js +96 -96
  33. package/server/plugins/table/funcs/getFilterSQL/util/formatValue.js +179 -179
  34. package/server/plugins/table/funcs/getFilterSQL/util/getCustomQuery.js +13 -13
  35. package/server/plugins/table/funcs/getFilterSQL/util/getFilterQuery.js +66 -66
  36. package/server/plugins/table/funcs/getFilterSQL/util/getOptimizedQuery.js +12 -12
  37. package/server/plugins/table/funcs/getFilterSQL/util/getTableSql.js +34 -34
  38. package/server/plugins/table/funcs/getTemplates.js +19 -19
  39. package/server/plugins/table/funcs/gisIRColumn.js +82 -82
  40. package/server/plugins/table/funcs/loadTemplate.js +1 -1
  41. package/server/plugins/table/funcs/loadTemplatePath.js +1 -1
  42. package/server/plugins/table/funcs/metaFormat/getSelectVal.js +50 -50
  43. package/server/plugins/table/funcs/metaFormat/index.js +45 -45
  44. package/server/plugins/table/funcs/userTemplateDir.js +1 -1
  45. package/server/plugins/table/index.js +13 -13
  46. package/server/plugins/util/index.js +7 -7
  47. package/server/routes/cron/index.js +14 -14
  48. package/server/routes/crud/controllers/deleteCrud.js +39 -39
  49. package/server/routes/crud/controllers/table.js +91 -91
  50. package/server/routes/logger/controllers/logger.file.js +92 -92
  51. package/server/routes/logger/controllers/utils/checkUserAccess.js +19 -19
  52. package/server/routes/logger/controllers/utils/getRootDir.js +26 -26
  53. package/server/routes/logger/index.js +17 -17
  54. package/server/routes/properties/controllers/properties.add.js +55 -55
  55. package/server/routes/properties/controllers/properties.get.js +17 -17
  56. package/server/routes/properties/index.js +16 -16
  57. package/server/routes/table/controllers/data.js +172 -169
  58. package/server/routes/table/controllers/filter.js +67 -67
  59. package/server/routes/table/controllers/form.js +42 -42
  60. package/server/routes/table/controllers/search.js +74 -74
  61. package/server/routes/table/controllers/suggest.js +166 -166
  62. package/server/routes/table/index.js +29 -29
  63. package/server/routes/table/schema.js +64 -64
  64. package/server/routes/util/controllers/status.monitor.js +8 -8
  65. package/server/routes/util/index.js +11 -11
  66. package/utils.js +129 -129
@@ -1,55 +1,55 @@
1
- import { dataInsert } from '../../../../utils.js';
2
-
3
- const table = 'crm.properties';
4
-
5
- function checkKeyType({ body, key }) {
6
- if (typeof body[key] === 'number' && (!/\D/.test(body[key].toString()) && body[key].toString().length < 10)) {
7
- return { [key]: 'int' };
8
- } if (typeof body[key] === 'object') {
9
- return { [key]: 'json' };
10
- }
11
- if (Date.parse(body[key], 'yyyy/MM/ddTHH:mm:ss.000Z')) {
12
- return { [key]: 'date' };
13
- }
14
- return { [key]: 'text' };
15
- }
16
-
17
- export default async function addExtraProperties({
18
- pg, params = {}, body = {}, user = {},
19
- }) {
20
- const { id } = params;
21
- const { uid } = user;
22
- if (!uid) {
23
- return { message: 'access restricted: uid', status: 403 };
24
- }
25
- if (!id) {
26
- return { message: 'not enougn params: 1', status: 400 };
27
- }
28
- const extraProperties = Object.keys(body);
29
- if (!extraProperties.length) {
30
- return { message: 'not enougn params: 2', status: 400 };
31
- }
32
-
33
- if (!pg.pk?.[table]) {
34
- return { message: 'table not found: crm.properties', status: 400 };
35
- }
36
-
37
- await pg.query('delete from crm.properties where object_id=$1', [id]); // rewrite?
38
- const keyTypeMatch = extraProperties.filter((key) => body[key]).reduce((acc, curr) => Object.assign(acc, checkKeyType({ body, key: curr })), {});
39
- const res = await Promise.all(Object.keys(keyTypeMatch).map(async (key) => {
40
- const propertyType = keyTypeMatch[key];
41
- const { rows = [] } = await dataInsert({
42
- pg,
43
- table,
44
- data: {
45
- property_type: propertyType,
46
- property_key: key,
47
- object_id: id,
48
- [`property_${propertyType}`]: body[key],
49
- },
50
- uid,
51
- });
52
- return { id: rows[0]?.property_id, type: propertyType, value: body[key] };
53
- }));
54
- return { message: { rows: res }, status: 200 };
55
- }
1
+ import { dataInsert } from '../../../../utils.js';
2
+
3
+ const table = 'crm.properties';
4
+
5
+ function checkKeyType({ body, key }) {
6
+ if (typeof body[key] === 'number' && (!/\D/.test(body[key].toString()) && body[key].toString().length < 10)) {
7
+ return { [key]: 'int' };
8
+ } if (typeof body[key] === 'object') {
9
+ return { [key]: 'json' };
10
+ }
11
+ if (Date.parse(body[key], 'yyyy/MM/ddTHH:mm:ss.000Z')) {
12
+ return { [key]: 'date' };
13
+ }
14
+ return { [key]: 'text' };
15
+ }
16
+
17
+ export default async function addExtraProperties({
18
+ pg, params = {}, body = {}, user = {},
19
+ }) {
20
+ const { id } = params;
21
+ const { uid } = user;
22
+ if (!uid) {
23
+ return { message: 'access restricted: uid', status: 403 };
24
+ }
25
+ if (!id) {
26
+ return { message: 'not enougn params: 1', status: 400 };
27
+ }
28
+ const extraProperties = Object.keys(body);
29
+ if (!extraProperties.length) {
30
+ return { message: 'not enougn params: 2', status: 400 };
31
+ }
32
+
33
+ if (!pg.pk?.[table]) {
34
+ return { message: 'table not found: crm.properties', status: 400 };
35
+ }
36
+
37
+ await pg.query('delete from crm.properties where object_id=$1', [id]); // rewrite?
38
+ const keyTypeMatch = extraProperties.filter((key) => body[key]).reduce((acc, curr) => Object.assign(acc, checkKeyType({ body, key: curr })), {});
39
+ const res = await Promise.all(Object.keys(keyTypeMatch).map(async (key) => {
40
+ const propertyType = keyTypeMatch[key];
41
+ const { rows = [] } = await dataInsert({
42
+ pg,
43
+ table,
44
+ data: {
45
+ property_type: propertyType,
46
+ property_key: key,
47
+ object_id: id,
48
+ [`property_${propertyType}`]: body[key],
49
+ },
50
+ uid,
51
+ });
52
+ return { id: rows[0]?.property_id, type: propertyType, value: body[key] };
53
+ }));
54
+ return { message: { rows: res }, status: 200 };
55
+ }
@@ -1,17 +1,17 @@
1
- export default async function getExtraProperties({
2
- pg, params = {},
3
- }) {
4
- const { id } = params;
5
- if (!id) {
6
- return { message: 'not enougn params', status: 400 };
7
- }
8
-
9
- const { rows = [] } = pg.pk?.['crm.properties']
10
- ? await pg.query(`select property_key, property_type, property_text, property_int,
11
- property_json, property_date from crm.properties where property_key is not null and object_id=$1`, [id])
12
- : {};
13
- if (!rows.length) return {};
14
-
15
- const data = rows.reduce((acc, curr) => Object.assign(acc, { [curr.property_key]: curr[`property_${curr.property_type}`] }), {});
16
- return { message: data, status: 200 };
17
- }
1
+ export default async function getExtraProperties({
2
+ pg, params = {},
3
+ }) {
4
+ const { id } = params;
5
+ if (!id) {
6
+ return { message: 'not enougn params', status: 400 };
7
+ }
8
+
9
+ const { rows = [] } = pg.pk?.['crm.properties']
10
+ ? await pg.query(`select property_key, property_type, property_text, property_int,
11
+ property_json, property_date from crm.properties where property_key is not null and object_id=$1`, [id])
12
+ : {};
13
+ if (!rows.length) return {};
14
+
15
+ const data = rows.reduce((acc, curr) => Object.assign(acc, { [curr.property_key]: curr[`property_${curr.property_type}`] }), {});
16
+ return { message: data, status: 200 };
17
+ }
@@ -1,16 +1,16 @@
1
- import getExtraProperties from './controllers/properties.get.js';
2
- import addExtraProperties from './controllers/properties.add.js';
3
-
4
- const propertiesSchema = {
5
- params: {
6
- id: { type: 'string', pattern: '^([\\d\\w]+)$' },
7
- },
8
- };
9
-
10
- async function plugin(fastify, config = {}) {
11
- const prefix = config.prefix || '/api';
12
- fastify.get(`${prefix}/properties/:id`, { schema: propertiesSchema }, getExtraProperties);
13
- fastify.post(`${prefix}/properties/:id`, { schema: propertiesSchema }, addExtraProperties);
14
- }
15
-
16
- export default plugin;
1
+ import getExtraProperties from './controllers/properties.get.js';
2
+ import addExtraProperties from './controllers/properties.add.js';
3
+
4
+ const propertiesSchema = {
5
+ params: {
6
+ id: { type: 'string', pattern: '^([\\d\\w]+)$' },
7
+ },
8
+ };
9
+
10
+ async function plugin(fastify, config = {}) {
11
+ const prefix = config.prefix || '/api';
12
+ fastify.get(`${prefix}/properties/:id`, { schema: propertiesSchema }, getExtraProperties);
13
+ fastify.post(`${prefix}/properties/:id`, { schema: propertiesSchema }, addExtraProperties);
14
+ }
15
+
16
+ export default plugin;
@@ -1,169 +1,172 @@
1
- import {
2
- config, getTemplate, getFilterSQL, getMeta, metaFormat, getAccess, setToken, gisIRColumn, applyHook, handlebars, getSelect,
3
- } from '../../../../utils.js';
4
-
5
- const maxLimit = 100;
6
- export default async function dataAPI(req) {
7
- const {
8
- pg, params, query = {}, user = {},
9
- } = req;
10
-
11
- const time = Date.now();
12
-
13
- const { uid } = user;
14
-
15
- const hookData = await applyHook('preData', {
16
- table: params?.table, id: params?.id, user,
17
- });
18
- if (hookData?.message && hookData?.status) {
19
- return { message: hookData?.message, status: hookData?.status };
20
- }
21
-
22
- const loadTable = await getTemplate('table', hookData?.table || params.table);
23
- if (!loadTable) { return { message: 'template not found', status: 404 }; }
24
-
25
- const id = hookData?.id || params?.id;
26
- const { actions = [], query: accessQuery } = await getAccess({ table: hookData?.table || params.table, id, user }) || {};
27
-
28
- if (!actions.includes('view') && !config?.local) {
29
- return { message: 'access restricted', status: 403 };
30
- }
31
-
32
- const {
33
- table, columns = [], sql, cardSql, filters, form, meta, sqlColumns, public: ispublic,
34
- } = loadTable;
35
-
36
- const tableMeta = await getMeta(table);
37
- if (tableMeta?.view) {
38
- if (!loadTable?.key) return { message: `key not found: ${table}`, status: 404 };
39
- Object.assign(tableMeta, { pk: loadTable?.key });
40
- }
41
- const { pk, columns: dbColumns = [] } = tableMeta || {};
42
-
43
- if (!pk) return { message: `table not found: ${table}`, status: 404 };
44
-
45
- const cols = columns.filter((el) => el.name !== 'geom').map((el) => el.name || el).join(',');
46
- const metaCols = Object.keys(loadTable?.meta?.cls || {}).filter((el) => !cols.includes(el)).length
47
- ? `,${Object.keys(loadTable?.meta?.cls || {})?.filter((el) => !cols.includes(el)).join(',')}`
48
- : '';
49
- const columnList = dbColumns.map((el) => el.name || el).join(',');
50
- const sqlTable = sql?.filter?.((el) => !el?.disabled && el?.sql?.replace).map((el, i) => ` left join lateral (${el.sql.replace('{{uid}}', uid)}) ${el.name || `t${i}`} on 1=1 `)?.join('') || '';
51
- const cardSqlFiltered = hookData?.id || params.id ? (cardSql?.filter?.((el) => !el?.disabled && el?.name && el?.sql?.replace) || []) : [];
52
- const cardSqlTable = cardSqlFiltered.length ? cardSqlFiltered.map((el, i) => ` left join lateral (${el.sql.replace('{{uid}}', uid)}) ct${i} on 1=1 `).join('\n') || '' : '';
53
-
54
- if (params.id && columnList.includes(params.id)) {
55
- return gisIRColumn({
56
- pg,
57
- layer: params.table,
58
- column: params.id,
59
- sql: query.sql,
60
- filter: query.filter,
61
- search: query.search,
62
- state: query.state,
63
- custom: query.custom,
64
- });
65
- }
66
-
67
- const checkFilter = [query.filter, query.search, query.state, query.custom].filter((el) => el).length;
68
- const fData = checkFilter ? await getFilterSQL({
69
- table: params.table,
70
- filter: query.filter,
71
- search: query.search,
72
- state: query.state,
73
- custom: query.custom,
74
- json: 1,
75
- }) : {};
76
-
77
- const keyQuery = query.key && loadTable.key && !(hookData?.id || params.id) ? `${loadTable.key}=$1` : null;
78
-
79
- const limit = Math.min(maxLimit, +(query.limit || 20));
80
-
81
- const offset = query.page && query.page > 0 ? ` offset ${(query.page - 1) * limit}` : '';
82
- // id, query, filter
83
- const [orderColumn, orderDir] = (query.order || loadTable.order || '').split(/[- ]/);
84
-
85
- const order = columnList.includes(orderColumn) && orderColumn?.length ? `order by ${orderColumn} ${query.desc || orderDir === 'desc' ? 'desc' : ''}` : '';
86
- const search = loadTable.meta?.search && query.search
87
- ? `(${loadTable.meta?.search.split(',').map(el => `${el} ilike '%${query.search.replace(/%/g, '\\%').replace(/'/g, "''")}%'`).join(' or ')})`
88
- : null;
89
- const queryBbox = query?.bbox ? query.bbox.replace(/ /g, ',').split(',')?.map((el) => el - 0) : [];
90
- const queryPolyline = meta?.bbox && query?.polyline ? `ST_Contains(ST_MakePolygon(ST_LineFromEncodedPolyline('${query?.polyline}')),${meta.bbox})` : undefined;
91
- const bbox = meta?.bbox && queryBbox.filter((el) => !Number.isNaN(el))?.length === 4 ? `${meta.bbox} && 'box(${queryBbox[0]} ${queryBbox[1]},${queryBbox[2]} ${queryBbox[3]})'::box2d ` : undefined;
92
-
93
- const interfaceQuery = params?.query ? await handlebars.compile(params?.query)({ user, uid }) : undefined;
94
- const where = [(hookData?.id || params.id ? ` "${pk}" = $1` : null), keyQuery, loadTable.query, fData.q, search, accessQuery || '1=1', bbox, queryPolyline, interfaceQuery].filter((el) => el).filter((el) => (user?.user_type === 'superadmin' ? !el.includes('{{uid}}') : true));
95
-
96
- // const cardColumns = cardSqlFiltered.length ? `,${cardSqlFiltered.map((el) => el.name)}` : '';
97
- const q = `select ${pk ? `"${pk}" as id,` : ''}
98
- ${params.id || query.key ? '*' : sqlColumns || cols || '*'}
99
- ${metaCols}
100
-
101
- ${dbColumns.find((el) => el.name === 'geom' && pg.pgType[el.dataTypeID] === 'geometry') ? ',st_asgeojson(geom)::json as geom' : ''}
102
- from (select * from ${table} where ${sqlTable ? 'true' : (where.join(' and ') || 'true')} ${order}) t
103
- ${sqlTable}
104
- ${cardSqlTable}
105
- where ${where.join(' and ') || 'true'}
106
- ${order} ${offset} limit ${limit}`
107
- .replace(/{{uid}}/g, uid);
108
-
109
- // if (user?.user_type === 'superadmin') console.log(q);
110
-
111
- if (query.sql === '1') { return q; }
112
-
113
- const { rows } = await pg.query(q, (hookData?.id || params.id ? [hookData?.id || params.id] : null) || (query.key && loadTable.key ? [query.key] : []));
114
-
115
- const filterWhere = [fData.q, search, bbox, queryPolyline, interfaceQuery, loadTable.query].filter((el) => el);
116
-
117
- const aggColumns = columns.filter((el) => el.agg).reduce((acc, curr) => Object.assign(acc, { [curr.name]: curr.agg }), {});
118
- const aggregates = dbColumns.map((el) => ({ name: el.name, type: pg.pgType[el.dataTypeID] })).filter((el) => ['numeric', 'double precision'].includes(el.type) && aggColumns[el.name]);
119
- const qCount = `select
120
- count(*)::int as total,
121
- count(*) FILTER(WHERE ${filterWhere.join(' and ') || 'true'})::int as filtered
122
- ${aggregates.length ? `,${aggregates.map((el) => `${aggColumns[el.name]}(${el.name}) FILTER(WHERE ${filterWhere.join(' and ') || 'true'}) as ${el.name}`).join(',')}` : ''}
123
- from ${table} t ${sqlTable}
124
- where ${[loadTable.query, accessQuery].filter(el => el).join(' and ') || 'true'} `
125
- .replace(/{{uid}}/g, uid);
126
-
127
- if (query.sql === '2') { return qCount; }
128
-
129
- const counts = keyQuery || hookData?.id || params.id
130
- ? { total: rows.length, filtered: rows.length }
131
- : await pg.queryCache(qCount, { table: loadTable.table, time: 5 }).then(el => el?.rows[0] || {});
132
-
133
- const { total, filtered } = counts;
134
- const agg = Object.keys(counts).filter(el => !['total', 'filtered'].includes(el)).reduce((acc, el) => ({ ...acc, [el]: counts[el] }), {});
135
-
136
- await metaFormat({ rows, table: hookData?.table || params.table });
137
-
138
- const status = [];
139
- if (loadTable.meta?.status) {
140
- const statusColumn = loadTable.meta?.cls?.[loadTable.meta?.status]
141
- ? { name: loadTable.meta?.status, data: loadTable.meta?.cls?.[loadTable.meta?.status] }
142
- : loadTable.columns.find(col => col.name === loadTable.meta?.status) || {};
143
-
144
- const statusCls = statusColumn.data || statusColumn.option;
145
- const statusClsData = statusCls ? await getSelect(statusCls, pg) : {};
146
- statusClsData?.arr
147
- ?.forEach(el => status.push({ ...el, count: rows.filter(row => el.id === row[statusColumn.name]).length }));
148
- }
149
-
150
- const res = {
151
- time: Date.now() - time, public: ispublic, card: loadTable.card, actions, total, filtered, count: rows.length, pk, form, agg, status, rows, meta, columns, filters,
152
- };
153
-
154
- // console.log({ add: loadTable.table, form: loadTable.form });
155
- if (uid && actions.includes('add')) {
156
- const addTokens = setToken({
157
- ids: [JSON.stringify({ table: hookData?.table || params.table, form: loadTable.form })],
158
- uid,
159
- array: 1,
160
- });
161
- Object.assign(res, { addToken: addTokens[0] });
162
- }
163
-
164
- const result = await applyHook('afterData', {
165
- table: loadTable.table, payload: res, user,
166
- });
167
-
168
- return result || res;
169
- }
1
+ import {
2
+ config, getTemplate, getFilterSQL, getMeta, metaFormat, getAccess, setToken, gisIRColumn, applyHook, handlebars, getSelect,
3
+ } from '../../../../utils.js';
4
+
5
+ const maxLimit = 100;
6
+ export default async function dataAPI(req) {
7
+ const {
8
+ pg, params, query = {}, user = {},
9
+ } = req;
10
+
11
+ const time = Date.now();
12
+
13
+ const { uid } = user;
14
+
15
+ const hookData = await applyHook('preData', {
16
+ table: params?.table, id: params?.id, user,
17
+ });
18
+ if (hookData?.message && hookData?.status) {
19
+ return { message: hookData?.message, status: hookData?.status };
20
+ }
21
+
22
+ const loadTable = await getTemplate('table', hookData?.table || params.table);
23
+ if (!loadTable) { return { message: 'template not found', status: 404 }; }
24
+
25
+ const id = hookData?.id || params?.id;
26
+ const { actions = [], query: accessQuery } = await getAccess({ table: hookData?.table || params.table, id, user }) || {};
27
+
28
+ if (!actions.includes('view') && !config?.local) {
29
+ return { message: 'access restricted', status: 403 };
30
+ }
31
+
32
+ const {
33
+ table, columns = [], sql, cardSql, filters, form, meta, sqlColumns, public: ispublic,
34
+ } = loadTable;
35
+
36
+ const tableMeta = await getMeta(table);
37
+ if (tableMeta?.view) {
38
+ if (!loadTable?.key) return { message: `key not found: ${table}`, status: 404 };
39
+ Object.assign(tableMeta, { pk: loadTable?.key });
40
+ }
41
+ const { pk, columns: dbColumns = [] } = tableMeta || {};
42
+
43
+ if (!pk) return { message: `table not found: ${table}`, status: 404 };
44
+
45
+ const columnList = dbColumns.map((el) => el.name || el).join(',');
46
+ const sqlTable = sql?.filter?.((el) => !el?.disabled && el?.sql?.replace && (!el.sql.includes('{{uid}}') || uid)).map((el, i) => ` left join lateral (${el.sql.replace('{{uid}}', uid)}) ${el.name || `t${i}`} on 1=1 `)?.join('') || '';
47
+ const cardSqlFiltered = hookData?.id || params.id ? (cardSql?.filter?.((el) => !el?.disabled && el?.name && el?.sql?.replace) || []) : [];
48
+ const cardSqlTable = cardSqlFiltered.length ? cardSqlFiltered.map((el, i) => ` left join lateral (${el.sql.replace('{{uid}}', uid)}) ct${i} on 1=1 `).join('\n') || '' : '';
49
+
50
+ const { fields } = await pg.queryCache(`select * from ${table} t ${sqlTable} ${cardSqlTable} limit 0`);
51
+ const dbColumnsTable = fields.map(el => el.name);
52
+ const cols = columns.filter((el) => el.name !== 'geom' && dbColumnsTable.includes(el.name)).map((el) => el.name || el).join(',');
53
+ const metaCols = Object.keys(loadTable?.meta?.cls || {}).filter((el) => !cols.includes(el)).length
54
+ ? `,${Object.keys(loadTable?.meta?.cls || {})?.filter((el) => !cols.includes(el)).join(',')}`
55
+ : '';
56
+
57
+ if (params.id && columnList.includes(params.id)) {
58
+ return gisIRColumn({
59
+ pg,
60
+ layer: params.table,
61
+ column: params.id,
62
+ sql: query.sql,
63
+ filter: query.filter,
64
+ search: query.search,
65
+ state: query.state,
66
+ custom: query.custom,
67
+ });
68
+ }
69
+
70
+ const checkFilter = [query.filter, query.search, query.state, query.custom].filter((el) => el).length;
71
+ const fData = checkFilter ? await getFilterSQL({
72
+ table: params.table,
73
+ filter: query.filter,
74
+ search: query.search,
75
+ state: query.state,
76
+ custom: query.custom,
77
+ json: 1,
78
+ }) : {};
79
+
80
+ const keyQuery = query.key && loadTable.key && !(hookData?.id || params.id) ? `${loadTable.key}=$1` : null;
81
+
82
+ const limit = Math.min(maxLimit, +(query.limit || 20));
83
+
84
+ const offset = query.page && query.page > 0 ? ` offset ${(query.page - 1) * limit}` : '';
85
+ // id, query, filter
86
+ const [orderColumn, orderDir] = (query.order || loadTable.order || '').split(/[- ]/);
87
+
88
+ const order = columnList.includes(orderColumn) && orderColumn?.length ? `order by ${orderColumn} ${query.desc || orderDir === 'desc' ? 'desc' : ''}` : '';
89
+ const search = loadTable.meta?.search && query.search
90
+ ? `(${loadTable.meta?.search.split(',').map(el => `${el} ilike '%${query.search.replace(/%/g, '\\%').replace(/'/g, "''")}%'`).join(' or ')})`
91
+ : null;
92
+ const queryBbox = query?.bbox ? query.bbox.replace(/ /g, ',').split(',')?.map((el) => el - 0) : [];
93
+ const queryPolyline = meta?.bbox && query?.polyline ? `ST_Contains(ST_MakePolygon(ST_LineFromEncodedPolyline('${query?.polyline}')),${meta.bbox})` : undefined;
94
+ const bbox = meta?.bbox && queryBbox.filter((el) => !Number.isNaN(el))?.length === 4 ? `${meta.bbox} && 'box(${queryBbox[0]} ${queryBbox[1]},${queryBbox[2]} ${queryBbox[3]})'::box2d ` : undefined;
95
+
96
+ const interfaceQuery = params?.query ? await handlebars.compile(params?.query)({ user, uid }) : undefined;
97
+ const where = [(hookData?.id || params.id ? ` "${pk}" = $1` : null), keyQuery, loadTable.query, fData.q, search, accessQuery || '1=1', bbox, queryPolyline, interfaceQuery].filter((el) => el).filter((el) => (user?.user_type === 'superadmin' ? !el.includes('{{uid}}') : true));
98
+
99
+ // const cardColumns = cardSqlFiltered.length ? `,${cardSqlFiltered.map((el) => el.name)}` : '';
100
+ const q = `select ${pk ? `"${pk}" as id,` : ''}
101
+ ${params.id || query.key ? '*' : sqlColumns || cols || '*'}
102
+ ${metaCols}
103
+
104
+ ${dbColumns.find((el) => el.name === 'geom' && pg.pgType[el.dataTypeID] === 'geometry') ? ',st_asgeojson(geom)::json as geom' : ''}
105
+ from (select * from ${table} where ${sqlTable ? 'true' : (where.join(' and ') || 'true')} ${order}) t
106
+ ${sqlTable}
107
+ ${params.id ? cardSqlTable : ''}
108
+ where ${where.join(' and ') || 'true'}
109
+ ${order} ${offset} limit ${limit}`
110
+ .replace(/{{uid}}/g, uid);
111
+
112
+ // if (user?.user_type === 'superadmin') console.log(q);
113
+
114
+ if (query.sql === '1') { return q; }
115
+
116
+ const { rows } = await pg.query(q, (hookData?.id || params.id ? [hookData?.id || params.id] : null) || (query.key && loadTable.key ? [query.key] : []));
117
+
118
+ const filterWhere = [fData.q, search, bbox, queryPolyline, interfaceQuery, loadTable.query].filter((el) => el);
119
+
120
+ const aggColumns = columns.filter((el) => el.agg).reduce((acc, curr) => Object.assign(acc, { [curr.name]: curr.agg }), {});
121
+ const aggregates = dbColumns.map((el) => ({ name: el.name, type: pg.pgType[el.dataTypeID] })).filter((el) => ['numeric', 'double precision'].includes(el.type) && aggColumns[el.name]);
122
+ const qCount = `select
123
+ count(*)::int as total,
124
+ count(*) FILTER(WHERE ${filterWhere.join(' and ') || 'true'})::int as filtered
125
+ ${aggregates.length ? `,${aggregates.map((el) => `${aggColumns[el.name]}(${el.name}) FILTER(WHERE ${filterWhere.join(' and ') || 'true'}) as ${el.name}`).join(',')}` : ''}
126
+ from ${table} t ${sqlTable}
127
+ where ${[loadTable.query, accessQuery].filter(el => el).join(' and ') || 'true'} `
128
+ .replace(/{{uid}}/g, uid);
129
+
130
+ if (query.sql === '2') { return qCount; }
131
+
132
+ const counts = keyQuery || hookData?.id || params.id
133
+ ? { total: rows.length, filtered: rows.length }
134
+ : await pg.queryCache(qCount, { table: loadTable.table, time: 5 }).then(el => el?.rows[0] || {});
135
+
136
+ const { total, filtered } = counts;
137
+ const agg = Object.keys(counts).filter(el => !['total', 'filtered'].includes(el)).reduce((acc, el) => ({ ...acc, [el]: counts[el] }), {});
138
+
139
+ await metaFormat({ rows, table: hookData?.table || params.table });
140
+
141
+ const status = [];
142
+ if (loadTable.meta?.status) {
143
+ const statusColumn = loadTable.meta?.cls?.[loadTable.meta?.status]
144
+ ? { name: loadTable.meta?.status, data: loadTable.meta?.cls?.[loadTable.meta?.status] }
145
+ : loadTable.columns.find(col => col.name === loadTable.meta?.status) || {};
146
+
147
+ const statusCls = statusColumn.data || statusColumn.option;
148
+ const statusClsData = statusCls ? await getSelect(statusCls, pg) : {};
149
+ statusClsData?.arr
150
+ ?.forEach(el => status.push({ ...el, count: rows.filter(row => el.id === row[statusColumn.name]).length }));
151
+ }
152
+
153
+ const res = {
154
+ time: Date.now() - time, public: ispublic, card: loadTable.card, actions, total, filtered, count: rows.length, pk, form, agg, status, rows, meta, columns, filters,
155
+ };
156
+
157
+ // console.log({ add: loadTable.table, form: loadTable.form });
158
+ if (uid && actions.includes('add')) {
159
+ const addTokens = setToken({
160
+ ids: [JSON.stringify({ table: hookData?.table || params.table, form: loadTable.form })],
161
+ uid,
162
+ array: 1,
163
+ });
164
+ Object.assign(res, { addToken: addTokens[0] });
165
+ }
166
+
167
+ const result = await applyHook('afterData', {
168
+ table: loadTable.table, payload: res, user,
169
+ });
170
+
171
+ return result || res;
172
+ }