@opengis/admin 0.3.114 → 0.3.116

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 (110) hide show
  1. package/README.md +97 -97
  2. package/config.js +4 -4
  3. package/dist/{add-page-BtH22CJN.js → add-page-D0ed-dNM.js} +1 -1
  4. package/dist/{admin-interface-DV1zpOD3.js → admin-interface-C5aCSsqj.js} +2 -2
  5. package/dist/{admin-view-YMPC7Yqw.js → admin-view-X6ZS7IvV.js} +1 -1
  6. package/dist/admin.js +1 -1
  7. package/dist/admin.umd.cjs +51 -51
  8. package/dist/assets/logo.svg +41 -41
  9. package/dist/{card-view-CukPM8Jb.js → card-view-Bs0tW4Ry.js} +1 -1
  10. package/dist/{edit-page-Drth27pw.js → edit-page-BtGxSoh_.js} +1 -1
  11. package/dist/{import-file-C26vi76C.js → import-file-DkbpNIPX.js} +6151 -6195
  12. package/dist/{profile-page-j7QFRFC2.js → profile-page-DmxAaYaO.js} +1 -1
  13. package/dist/style.css +1 -1
  14. package/module/settings/card/admin.accounts.table/index.yml +7 -7
  15. package/module/settings/card/admin.accounts.table/rules.hbs +18 -18
  16. package/module/settings/card/admin.accounts.table/users.hbs +13 -13
  17. package/module/settings/card/admin.routes.table/groups.hbs +11 -11
  18. package/module/settings/card/admin.routes.table/users.hbs +16 -16
  19. package/module/settings/cls/core.actions.json +17 -17
  20. package/module/settings/cls/core.scope.json +13 -13
  21. package/module/settings/cls/properties.site_status.json +13 -13
  22. package/module/settings/cls/properties.widget_status.json +13 -13
  23. package/module/settings/cls/yes_no.json +11 -11
  24. package/module/settings/form/admin.accounts.form.json +13 -13
  25. package/module/settings/form/admin.properties.form.json +15 -15
  26. package/module/settings/form/admin.roles.form.json +21 -21
  27. package/module/settings/form/admin.user_properties.form.json +15 -15
  28. package/module/settings/form/admin.user_roles_card.form.json +13 -13
  29. package/module/settings/interface/admin.properties.json +4 -4
  30. package/module/settings/interface/admin.roles.json +4 -4
  31. package/module/settings/interface/admin.routes.json +4 -4
  32. package/module/settings/interface/admin.users.json +4 -4
  33. package/module/settings/select/core.routes.sql +1 -1
  34. package/module/settings/select/core.user_mentioned.sql +1 -1
  35. package/module/settings/select/core.user_uid.sql +1 -1
  36. package/module/settings/table/admin.properties.table.json +39 -39
  37. package/module/settings/table/admin.user_properties.table.json +34 -34
  38. package/package.json +1 -1
  39. package/server/helpers/core/coalesce.js +7 -7
  40. package/server/helpers/core/select.js +48 -48
  41. package/server/helpers/core/token.js +18 -18
  42. package/server/helpers/list/buttonHelper.js +21 -21
  43. package/server/helpers/list/utils/button.js +5 -5
  44. package/server/helpers/temp/contentList.js +58 -58
  45. package/server/helpers/temp/ifCond.js +101 -101
  46. package/server/helpers/utils/button.js +5 -5
  47. package/server/helpers/utils/mdToHTML.js +17 -17
  48. package/server/plugins/access/index.mjs +6 -6
  49. package/server/plugins/adminHook.js +81 -81
  50. package/server/plugins/cron.js +10 -10
  51. package/server/plugins/docs.js +28 -28
  52. package/server/routes/access/controllers/access.group.js +29 -29
  53. package/server/routes/access/controllers/access.group.post.js +54 -54
  54. package/server/routes/access/index.mjs +11 -11
  55. package/server/routes/access/schema.mjs +67 -67
  56. package/server/routes/calendar/controllers/calendar.data.js +125 -125
  57. package/server/routes/calendar/index.mjs +7 -7
  58. package/server/routes/calendar/schema.js +21 -21
  59. package/server/routes/data/controllers/cardTabData.js +49 -49
  60. package/server/routes/data/controllers/funcs/getFilterSQL/index.js +92 -92
  61. package/server/routes/data/controllers/funcs/getFilterSQL/util/formatValue.js +170 -170
  62. package/server/routes/data/controllers/funcs/getFilterSQL/util/getCustomQuery.js +13 -13
  63. package/server/routes/data/controllers/funcs/getFilterSQL/util/getFilterQuery.js +64 -64
  64. package/server/routes/data/controllers/funcs/getFilterSQL/util/getOptimizedQuery.js +12 -12
  65. package/server/routes/data/controllers/funcs/getFilterSQL/util/getTableSql.js +34 -34
  66. package/server/routes/data/controllers/tableDataId.js +27 -27
  67. package/server/routes/data/controllers/tokenInfo.js +9 -9
  68. package/server/routes/data/controllers/utils/assignTokens.js +30 -30
  69. package/server/routes/data/controllers/utils/conditions.js +20 -20
  70. package/server/routes/data/controllers/utils/getColumns.js +8 -8
  71. package/server/routes/data/index.mjs +20 -20
  72. package/server/routes/data/schema.js +54 -54
  73. package/server/routes/notifications/controllers/readNotifications.js +18 -18
  74. package/server/routes/notifications/controllers/testEmail.js +35 -35
  75. package/server/routes/notifications/controllers/userNotifications.js +53 -53
  76. package/server/routes/notifications/hook/onWidgetSet.js +56 -56
  77. package/server/routes/notifications/index.mjs +26 -26
  78. package/server/routes/notifications/schema.js +16 -16
  79. package/server/routes/properties/schema.js +10 -10
  80. package/server/routes/report/controllers/list.js +23 -23
  81. package/server/routes/report/controllers/tableData.js +6 -0
  82. package/server/routes/report/index.mjs +9 -9
  83. package/server/routes/report/utils/formatValue.js +179 -179
  84. package/server/routes/root.mjs +3 -3
  85. package/server/routes/templates/controllers/getTemplate.js +44 -44
  86. package/server/routes/templates/schema.js +8 -8
  87. package/server/routes/user/controllers/user.cls.id.js +14 -14
  88. package/server/routes/user/controllers/user.cls.js +72 -72
  89. package/server/routes/user/controllers/user.info.js +17 -17
  90. package/server/routes/user/schema.js +14 -14
  91. package/server/routes/util/controllers/code.generator.js +89 -89
  92. package/server/routes/widget/controllers/widget.del.js +80 -80
  93. package/server/routes/widget/controllers/widget.set.js +101 -101
  94. package/server/routes/widget/hook/onWidgetSet.js +12 -12
  95. package/server/routes/widget/index.mjs +20 -20
  96. package/server/routes/widget/schema.js +12 -12
  97. package/server/templates/cls/itree.recrzone_category.json +73 -73
  98. package/server/templates/cls/test.json +9 -9
  99. package/server/templates/form/admin.user_cls.data.form.json +49 -49
  100. package/server/templates/form/admin.user_group_rel.form.json +21 -21
  101. package/server/templates/form/form-user-pass.json +10 -10
  102. package/server/templates/form/form-user_group.json +39 -39
  103. package/server/templates/form/form-users.json +156 -156
  104. package/server/templates/form/user_group_access.form.json +22 -22
  105. package/server/templates/select/account_id.json +2 -2
  106. package/server/templates/table/gis.dataset.table.json +43 -43
  107. package/server/templates/table/management.user_group.table.json +112 -112
  108. package/server/templates/table/management.users.table.json +126 -126
  109. package/server/utils/addNotification.js +21 -21
  110. package/server/utils/sendNotification.js +89 -89
@@ -1,26 +1,26 @@
1
- import { addHook } from '@opengis/fastify-table/utils.js';
2
-
3
- // api
4
- import testEmail from './controllers/testEmail.js';
5
- import readNotifications from './controllers/readNotifications.js'; // mark as read
6
- import userNotifications from './controllers/userNotifications.js'; // check all, backend pagination
7
-
8
- // hook
9
- import onWidgetSet from './hook/onWidgetSet.js'; // send notification on comment
10
-
11
- // funcs
12
- // import addNotification from '../notifications/funcs/addNotification.js'; // add to db
13
- // import notification from '../notifications/funcs/sendNotification.js'; // send notification
14
-
15
- import { notificationSchema, emailSchema } from './schema.js';
16
-
17
- export default async function route(fastify) {
18
-
19
- // fastify.decorate('addNotification', addNotification);
20
- // fastify.decorate('notification', notification);
21
-
22
- fastify.get('/test-email', { config: { policy: ['user'] }, schema: emailSchema }, testEmail);
23
- fastify.get('/notification', { config: { policy: ['user'] }, schema: notificationSchema }, userNotifications);
24
- fastify.get('/notification-read/:id?', { config: { policy: ['user'] }, schema: notificationSchema }, readNotifications);
25
- addHook('onWidgetSet', onWidgetSet);
26
- }
1
+ import { addHook } from '@opengis/fastify-table/utils.js';
2
+
3
+ // api
4
+ import testEmail from './controllers/testEmail.js';
5
+ import readNotifications from './controllers/readNotifications.js'; // mark as read
6
+ import userNotifications from './controllers/userNotifications.js'; // check all, backend pagination
7
+
8
+ // hook
9
+ import onWidgetSet from './hook/onWidgetSet.js'; // send notification on comment
10
+
11
+ // funcs
12
+ // import addNotification from '../notifications/funcs/addNotification.js'; // add to db
13
+ // import notification from '../notifications/funcs/sendNotification.js'; // send notification
14
+
15
+ import { notificationSchema, emailSchema } from './schema.js';
16
+
17
+ export default async function route(fastify) {
18
+
19
+ // fastify.decorate('addNotification', addNotification);
20
+ // fastify.decorate('notification', notification);
21
+
22
+ fastify.get('/test-email', { config: { policy: ['user'] }, schema: emailSchema }, testEmail);
23
+ fastify.get('/notification', { config: { policy: ['user'] }, schema: notificationSchema }, userNotifications);
24
+ fastify.get('/notification-read/:id?', { config: { policy: ['user'] }, schema: notificationSchema }, readNotifications);
25
+ addHook('onWidgetSet', onWidgetSet);
26
+ }
@@ -1,17 +1,17 @@
1
- const notificationSchema = {
2
- params: {
3
- id: { type: 'string', pattern: '^([\\d\\w]+)$' },
4
- },
5
- querystring: {
6
- nocache: { type: 'string', pattern: '^(\\d+)$' },
7
- },
8
- };
9
-
10
- const emailSchema = {
11
- quertstring: {
12
- to: { type: 'string', pattern: '^((?!\\.)[\\w\\-_.]*[^.])(@\\w+)(\\.\\w+(\\.\\w+)?[^.\\W])$' },
13
- },
14
- };
15
-
16
- export default null;
1
+ const notificationSchema = {
2
+ params: {
3
+ id: { type: 'string', pattern: '^([\\d\\w]+)$' },
4
+ },
5
+ querystring: {
6
+ nocache: { type: 'string', pattern: '^(\\d+)$' },
7
+ },
8
+ };
9
+
10
+ const emailSchema = {
11
+ quertstring: {
12
+ to: { type: 'string', pattern: '^((?!\\.)[\\w\\-_.]*[^.])(@\\w+)(\\.\\w+(\\.\\w+)?[^.\\W])$' },
13
+ },
14
+ };
15
+
16
+ export default null;
17
17
  export { notificationSchema, emailSchema }
@@ -1,11 +1,11 @@
1
- const propertiesSchema = {
2
- params: {
3
- key: { type: 'string', pattern: '^([\\d\\w._]+)$' },
4
- },
5
- querystring: {
6
- json: { type: 'string', pattern: '^([\\d\\w]+)$' },
7
- },
8
- };
9
-
10
- export default null;
1
+ const propertiesSchema = {
2
+ params: {
3
+ key: { type: 'string', pattern: '^([\\d\\w._]+)$' },
4
+ },
5
+ querystring: {
6
+ json: { type: 'string', pattern: '^([\\d\\w]+)$' },
7
+ },
8
+ };
9
+
10
+ export default null;
11
11
  export { propertiesSchema }
@@ -1,23 +1,23 @@
1
- import path from 'node:path';
2
-
3
- import { getTemplatePath, getTemplate } from '@opengis/fastify-table/utils.js';
4
-
5
- export default async function reportList({
6
- user = {},
7
- }) {
8
- const arr = getTemplatePath('report');
9
-
10
- const rows = await Promise.all(arr.map(async (el) => {
11
- const loadTemplate = await getTemplate('report', el[0]);
12
- const item = Array.isArray(loadTemplate) ? loadTemplate?.find?.(el => el[0].replace(path.extname(el[0]), '') === 'index')[1] : loadTemplate;
13
- return {
14
- name: el[0],
15
- filters: item?.filters || [],
16
- title: item?.title || el[0],
17
- subtitle: item?.subtitle,
18
- category: item?.category,
19
- sql: user.user_type?.includes('admin') ? item?.sql : undefined,
20
- };
21
- }));
22
- return { rows };
23
- }
1
+ import path from 'node:path';
2
+
3
+ import { getTemplatePath, getTemplate } from '@opengis/fastify-table/utils.js';
4
+
5
+ export default async function reportList({
6
+ user = {},
7
+ }) {
8
+ const arr = getTemplatePath('report');
9
+
10
+ const rows = await Promise.all(arr.map(async (el) => {
11
+ const loadTemplate = await getTemplate('report', el[0]);
12
+ const item = Array.isArray(loadTemplate) ? loadTemplate?.find?.(el => el[0].replace(path.extname(el[0]), '') === 'index')[1] : loadTemplate;
13
+ return {
14
+ name: el[0],
15
+ filters: item?.filters || [],
16
+ title: item?.title || el[0],
17
+ subtitle: item?.subtitle,
18
+ category: item?.category,
19
+ sql: user.user_type?.includes('admin') ? item?.sql : undefined,
20
+ };
21
+ }));
22
+ return { rows };
23
+ }
@@ -90,6 +90,9 @@ export default async function tableData(req, reply) {
90
90
  return resp;
91
91
  }
92
92
 
93
+ const { total = 0, filtered = 0 } = await pg.queryCache(`select count(*), count(*) filter(where ${where || '1=1'}) as filtered from (${sql.replace(/{{uid}}/g, user?.uid)})q`, { table: loadTemplate.table })
94
+ .then(el => ({ total: el.rows?.[0]?.count, filtered: el.rows?.[0]?.filtered }));
95
+
93
96
  if (kpi?.length) {
94
97
  await Promise.all(kpi.map(async (el) => {
95
98
  if (!el.sql && !el.table) {
@@ -125,6 +128,8 @@ export default async function tableData(req, reply) {
125
128
 
126
129
  return {
127
130
  q: user?.user_type?.includes('admin') ? q : undefined,
131
+ total,
132
+ filtered,
128
133
  kpi,
129
134
  data: rows,
130
135
  title,
@@ -132,5 +137,6 @@ export default async function tableData(req, reply) {
132
137
  category,
133
138
  widgets,
134
139
  columns,
140
+ filters,
135
141
  };
136
142
  }
@@ -1,9 +1,9 @@
1
- import tableData from './controllers/tableData.js';
2
- import widgetData from './controllers/widgetData.js';
3
- import reportList from './controllers/list.js';
4
-
5
- export default async function route(app) {
6
- app.get('/reports', {}, reportList);
7
- app.get('/reports/:name', {}, tableData);
8
- app.get('/reports/:name/:widget', {}, widgetData);
9
- }
1
+ import tableData from './controllers/tableData.js';
2
+ import widgetData from './controllers/widgetData.js';
3
+ import reportList from './controllers/list.js';
4
+
5
+ export default async function route(app) {
6
+ app.get('/reports', {}, reportList);
7
+ app.get('/reports/:name', {}, tableData);
8
+ app.get('/reports/:name/:widget', {}, widgetData);
9
+ }
@@ -1,179 +1,179 @@
1
- const dateTypeList = ['date', 'timestamp', 'timestamp without time zone', 'timestamp with time zone'];
2
- const numberTypeList = ['float8', 'int4', 'int8', 'numeric', 'double precision', 'integer'];
3
- const isValidDate = (dateStr) => {
4
- const [dd, mm, yyyy] = dateStr.split('.');
5
- return new Date(mm + '/' + dd + '/' + yyyy).toString() !== 'Invalid Date';
6
- };
7
-
8
- function dt(y, m, d) {
9
- return new Date(Date.UTC(y, m, d)).toISOString().slice(0, 10);
10
- }
11
- const dp = {
12
- d: new Date().getDate(),
13
- w: new Date().getDate() - (new Date().getDay() || 7) + 1,
14
- m: new Date().getMonth(),
15
- q: (new Date().getMonth() / 4).toFixed() * 3,
16
- y: new Date().getFullYear(),
17
- };
18
-
19
- function formatDateISOString(date) {
20
- if (!date?.includes('.')) return date;
21
- const [day, month, year] = date.split('.');
22
- return `${year}-${month}-${day}`;
23
- }
24
-
25
- function formatValue({
26
- pg, filter = {}, name, value, operator = '=', dataTypeID, uid = 1, optimize,
27
- }) {
28
- const { data, sql, extra } = filter;
29
- const pk = false;
30
-
31
- if (!dataTypeID && !extra) return {};
32
- const fieldType = extra ? pg.pgType?.[{ Date: 1114 }[filter?.type] || 25] : pg.pgType?.[dataTypeID];
33
- if (!name || !value || !fieldType) return {};
34
- const filterType = filter.type?.toLowerCase();
35
-
36
- // current day, week, month, year etc.
37
- if (dateTypeList.includes(fieldType) && !value?.includes('_') && ['cd', 'cw', 'cm', 'cq', 'cy'].includes(value)) {
38
- const query = {
39
- cd: `${name}::date = '${dt(dp.y, dp.m, dp.d)}'::date`,
40
- cw: `${name}::date >= '${dt(dp.y, dp.m, dp.w)}'::date and ${name} <= '${dt(dp.y, dp.m, dp.w + 6)}'::date`,
41
- cm: `${name}::date >= '${dt(dp.y, dp.m, 1)}'::date and ${name} <= '${dt(dp.y, dp.m + 1, 0)}'::date`,
42
- cq: `${name}::date >= '${dt(dp.y, dp.q, 1)}'::date and ${name} <= '${dt(dp.y, dp.q + 3, 0)}'::date`,
43
- cy: `${name}::date >= '${dt(dp.y, 0, 1)}'::date and ${name}::date <= '${dt(dp.y, 11, 31)}'::date`,
44
- }[value];
45
- return { op: '=', query, extra };
46
- }
47
-
48
- // date range
49
- if (dateTypeList.includes(fieldType) && value?.includes('_')) {
50
- const [min, max] = value.split('_');
51
- const query = `${name} >= '${min}'::date and ${name} <= '${max}'::date`;
52
- return { op: 'between', query, extra };
53
- }
54
-
55
- // v3 filter date range, example - "01.01.2024-31.12.2024"
56
- if (dateTypeList.includes(fieldType) && value?.includes('.') && value?.indexOf('-') === 10 && value?.length === 21) {
57
- const [startDate, endDate] = value.split('-');
58
- const min = formatDateISOString(startDate);
59
- const max = formatDateISOString(endDate);
60
-
61
- if (!isValidDate(startDate) || !isValidDate(endDate)) {
62
- return { op: 'between', query: 'false', extra };
63
- }
64
- const query = extra && pk
65
- ? `${pk} in (select object_id from crm.extra_data where property_key='${name}' and value_date::date >= '${min}'::date and value_date::date <= '${max}'::date)`
66
- : `${name}::date >= '${min}'::date and ${name}::date <= '${max}'::date`;
67
- return { op: 'between', query, extra };
68
- }
69
-
70
- // my rows
71
- if (value === 'me' && uid && fieldType === 'text') {
72
- return { op: '=', query: extra ? `uid = '${uid}'` : `${name}::text = '${uid}'`, extra };
73
- }
74
-
75
- const formatType = {
76
- float8: 'numeric',
77
- int4: 'numeric',
78
- int8: 'numeric',
79
- varchar: 'text',
80
- bool: 'boolean',
81
- geometry: 'geom',
82
- }[fieldType] || 'text';
83
-
84
- if (optimize && optimize.name !== optimize.pk) {
85
- const val = filterType === 'text' ? `ilike '%${value}%'` : `= any('{${value}}')`;
86
- return {
87
- op: '~',
88
- query: fieldType?.includes('[]')
89
- ? `${optimize.pk} && (select array_agg(${optimize.pk}) from ${optimize.table} where ${name} ${val} )`
90
- : `${optimize.pk} in (select ${optimize.pk} from ${optimize.table} where ${name} ${val} )`,
91
- extra,
92
- };
93
- }
94
-
95
- if (fieldType?.includes('[]')) {
96
- return { op: 'in', query: `'{${value}}'::text[] && ${name}::text[]`, extra };
97
- }
98
-
99
- // multiple items of 1 param
100
- if (value?.indexOf(',') !== -1) {
101
- const values = value.split(',').filter((el) => el !== 'null');
102
- if (extra && pk) {
103
- const query = value?.indexOf('null') !== -1
104
- ? `${pk} in (select object_id from crm.extra_data where property_key='${name}' and ( value_text is null or value_text in (${values?.map((el) => `'"${el}"'`).join(',')}) ) )`
105
- : `${pk} in (select object_id from crm.extra_data where property_key='${name}' and value_text in (${values?.map((el) => `'"${el}"'`).join(',')}) )`;
106
- return { op: 'in', query, extra };
107
- }
108
- const query = value?.indexOf('null') !== -1
109
- ? `( ${name} is null or ${name}::text in (${values?.map((el) => `'${el}'`).join(',')}) )`
110
- : `${name}::text in (${value.split(',')?.map((el) => `'${el}'`).join(',')})`;
111
- return { op: 'in', query, extra };
112
- }
113
-
114
- // v3 filter number range, example - "100_500"
115
- if (numberTypeList.includes(fieldType) && value?.indexOf('_') !== -1) {
116
- const [min, max] = value.split('_');
117
- const query = (max === 'max' ? `${name} > ${min}` : null) || (min === 'min' ? `${name} <= ${max}` : null) || `${name} between ${min} and ${max}`;
118
- return { op: 'between', query, extra };
119
- }
120
-
121
- // number range
122
- if (numberTypeList.includes(fieldType) && value?.indexOf('-') !== -1) {
123
- const [min, max] = value.split('-');
124
- if (min === 'min' && max === 'max') return {};
125
- const query = (max === 'max' ? `${name} > ${min}` : null) || (min === 'min' ? `${name} < ${max}` : null) || `${name} between ${min} and ${max}`;
126
- return { op: 'between', query, extra };
127
- }
128
-
129
- if (['<', '>'].includes(operator)) {
130
- const query = `${name} ${operator} '${value}'::${formatType}`;
131
- return { op: operator, query, extra };
132
- }
133
-
134
- if (operator === '=' && filterType !== 'text' && !filter?.data) {
135
- const query = {
136
- null: `${name} is null`,
137
- notnull: `${name} is not null`,
138
- }[value] || `${name}::${formatType}='${value}'::${formatType}`;
139
- return { op: '=', query, extra };
140
- }
141
-
142
- if (['~', '='].includes(operator)) {
143
- const operator1 = (filterType === 'text' && (filter?.id || filter?.name) && operator === '=' ? '~' : operator);
144
- const matchNull = { null: 'is null', notnull: 'is not null' }[value];
145
- const match = matchNull || ((operator1 === '=' || filterType === 'autocomplete') ? `='${value}'` : `ilike '%${value}%'`);
146
- if (extra && pk) {
147
- const query = data && sql
148
- ? `${pk} in (select object_id from crm.extra_data where property_key='${name}' and value_text in ( ( with q(id,name) as (${sql}) select id from q where ${filterType === 'autocomplete' ? 'id' : 'name'} ${match})))`
149
- : `${pk} in (select object_id from crm.extra_data where property_key='${name}' and value_text ${match})`;
150
- return { op: 'ilike', query, extra };
151
- }
152
-
153
- const query = filter?.data && filter?.sql
154
- ? `${filter?.name || filter?.id} in ( ( with q(id,name) as (${filter?.sql}) select id from q where ${filterType === 'autocomplete' ? 'id' : 'name'}::text ${match}) )` // filter with cls
155
- : `${name}::text ${match}`; // simple filter
156
- // console.log(query);
157
- return { op: 'ilike', query };
158
- }
159
-
160
- // json
161
- if (name.includes('.')) {
162
- const [col, prop] = name.split('.');
163
- const query = ` ${col}->>'${prop}' in ('${value.join("','")}')`;
164
- return { op: 'in', query, extra };
165
- }
166
-
167
- // geometry
168
- if (['geometry'].includes(fieldType)) {
169
- const bbox = value[0].split('_');
170
-
171
- if (bbox?.length === 4) {
172
- const query = ` ${name} && 'box(${bbox[0]} ${bbox[1]},${bbox[2]} ${bbox[3]})'::box2d `;
173
- return { op: '&&', query, extra };
174
- }
175
- }
176
- return {};
177
- }
178
-
179
- export default formatValue;
1
+ const dateTypeList = ['date', 'timestamp', 'timestamp without time zone', 'timestamp with time zone'];
2
+ const numberTypeList = ['float8', 'int4', 'int8', 'numeric', 'double precision', 'integer'];
3
+ const isValidDate = (dateStr) => {
4
+ const [dd, mm, yyyy] = dateStr.split('.');
5
+ return new Date(mm + '/' + dd + '/' + yyyy).toString() !== 'Invalid Date';
6
+ };
7
+
8
+ function dt(y, m, d) {
9
+ return new Date(Date.UTC(y, m, d)).toISOString().slice(0, 10);
10
+ }
11
+ const dp = {
12
+ d: new Date().getDate(),
13
+ w: new Date().getDate() - (new Date().getDay() || 7) + 1,
14
+ m: new Date().getMonth(),
15
+ q: (new Date().getMonth() / 4).toFixed() * 3,
16
+ y: new Date().getFullYear(),
17
+ };
18
+
19
+ function formatDateISOString(date) {
20
+ if (!date?.includes('.')) return date;
21
+ const [day, month, year] = date.split('.');
22
+ return `${year}-${month}-${day}`;
23
+ }
24
+
25
+ function formatValue({
26
+ pg, filter = {}, name, value, operator = '=', dataTypeID, uid = 1, optimize,
27
+ }) {
28
+ const { data, sql, extra } = filter;
29
+ const pk = false;
30
+
31
+ if (!dataTypeID && !extra) return {};
32
+ const fieldType = extra ? pg.pgType?.[{ Date: 1114 }[filter?.type] || 25] : pg.pgType?.[dataTypeID];
33
+ if (!name || !value || !fieldType) return {};
34
+ const filterType = filter.type?.toLowerCase();
35
+
36
+ // current day, week, month, year etc.
37
+ if (dateTypeList.includes(fieldType) && !value?.includes('_') && ['cd', 'cw', 'cm', 'cq', 'cy'].includes(value)) {
38
+ const query = {
39
+ cd: `${name}::date = '${dt(dp.y, dp.m, dp.d)}'::date`,
40
+ cw: `${name}::date >= '${dt(dp.y, dp.m, dp.w)}'::date and ${name} <= '${dt(dp.y, dp.m, dp.w + 6)}'::date`,
41
+ cm: `${name}::date >= '${dt(dp.y, dp.m, 1)}'::date and ${name} <= '${dt(dp.y, dp.m + 1, 0)}'::date`,
42
+ cq: `${name}::date >= '${dt(dp.y, dp.q, 1)}'::date and ${name} <= '${dt(dp.y, dp.q + 3, 0)}'::date`,
43
+ cy: `${name}::date >= '${dt(dp.y, 0, 1)}'::date and ${name}::date <= '${dt(dp.y, 11, 31)}'::date`,
44
+ }[value];
45
+ return { op: '=', query, extra };
46
+ }
47
+
48
+ // date range
49
+ if (dateTypeList.includes(fieldType) && value?.includes('_')) {
50
+ const [min, max] = value.split('_');
51
+ const query = `${name} >= '${min}'::date and ${name} <= '${max}'::date`;
52
+ return { op: 'between', query, extra };
53
+ }
54
+
55
+ // v3 filter date range, example - "01.01.2024-31.12.2024"
56
+ if (dateTypeList.includes(fieldType) && value?.includes('.') && value?.indexOf('-') === 10 && value?.length === 21) {
57
+ const [startDate, endDate] = value.split('-');
58
+ const min = formatDateISOString(startDate);
59
+ const max = formatDateISOString(endDate);
60
+
61
+ if (!isValidDate(startDate) || !isValidDate(endDate)) {
62
+ return { op: 'between', query: 'false', extra };
63
+ }
64
+ const query = extra && pk
65
+ ? `${pk} in (select object_id from crm.extra_data where property_key='${name}' and value_date::date >= '${min}'::date and value_date::date <= '${max}'::date)`
66
+ : `${name}::date >= '${min}'::date and ${name}::date <= '${max}'::date`;
67
+ return { op: 'between', query, extra };
68
+ }
69
+
70
+ // my rows
71
+ if (value === 'me' && uid && fieldType === 'text') {
72
+ return { op: '=', query: extra ? `uid = '${uid}'` : `${name}::text = '${uid}'`, extra };
73
+ }
74
+
75
+ const formatType = {
76
+ float8: 'numeric',
77
+ int4: 'numeric',
78
+ int8: 'numeric',
79
+ varchar: 'text',
80
+ bool: 'boolean',
81
+ geometry: 'geom',
82
+ }[fieldType] || 'text';
83
+
84
+ if (optimize && optimize.name !== optimize.pk) {
85
+ const val = filterType === 'text' ? `ilike '%${value}%'` : `= any('{${value}}')`;
86
+ return {
87
+ op: '~',
88
+ query: fieldType?.includes('[]')
89
+ ? `${optimize.pk} && (select array_agg(${optimize.pk}) from ${optimize.table} where ${name} ${val} )`
90
+ : `${optimize.pk} in (select ${optimize.pk} from ${optimize.table} where ${name} ${val} )`,
91
+ extra,
92
+ };
93
+ }
94
+
95
+ if (fieldType?.includes('[]')) {
96
+ return { op: 'in', query: `'{${value}}'::text[] && ${name}::text[]`, extra };
97
+ }
98
+
99
+ // multiple items of 1 param
100
+ if (value?.indexOf(',') !== -1) {
101
+ const values = value.split(',').filter((el) => el !== 'null');
102
+ if (extra && pk) {
103
+ const query = value?.indexOf('null') !== -1
104
+ ? `${pk} in (select object_id from crm.extra_data where property_key='${name}' and ( value_text is null or value_text in (${values?.map((el) => `'"${el}"'`).join(',')}) ) )`
105
+ : `${pk} in (select object_id from crm.extra_data where property_key='${name}' and value_text in (${values?.map((el) => `'"${el}"'`).join(',')}) )`;
106
+ return { op: 'in', query, extra };
107
+ }
108
+ const query = value?.indexOf('null') !== -1
109
+ ? `( ${name} is null or ${name}::text in (${values?.map((el) => `'${el}'`).join(',')}) )`
110
+ : `${name}::text in (${value.split(',')?.map((el) => `'${el}'`).join(',')})`;
111
+ return { op: 'in', query, extra };
112
+ }
113
+
114
+ // v3 filter number range, example - "100_500"
115
+ if (numberTypeList.includes(fieldType) && value?.indexOf('_') !== -1) {
116
+ const [min, max] = value.split('_');
117
+ const query = (max === 'max' ? `${name} > ${min}` : null) || (min === 'min' ? `${name} <= ${max}` : null) || `${name} between ${min} and ${max}`;
118
+ return { op: 'between', query, extra };
119
+ }
120
+
121
+ // number range
122
+ if (numberTypeList.includes(fieldType) && value?.indexOf('-') !== -1) {
123
+ const [min, max] = value.split('-');
124
+ if (min === 'min' && max === 'max') return {};
125
+ const query = (max === 'max' ? `${name} > ${min}` : null) || (min === 'min' ? `${name} < ${max}` : null) || `${name} between ${min} and ${max}`;
126
+ return { op: 'between', query, extra };
127
+ }
128
+
129
+ if (['<', '>'].includes(operator)) {
130
+ const query = `${name} ${operator} '${value}'::${formatType}`;
131
+ return { op: operator, query, extra };
132
+ }
133
+
134
+ if (operator === '=' && filterType !== 'text' && !filter?.data) {
135
+ const query = {
136
+ null: `${name} is null`,
137
+ notnull: `${name} is not null`,
138
+ }[value] || `${name}::${formatType}='${value}'::${formatType}`;
139
+ return { op: '=', query, extra };
140
+ }
141
+
142
+ if (['~', '='].includes(operator)) {
143
+ const operator1 = (filterType === 'text' && (filter?.id || filter?.name) && operator === '=' ? '~' : operator);
144
+ const matchNull = { null: 'is null', notnull: 'is not null' }[value];
145
+ const match = matchNull || ((operator1 === '=' || filterType === 'autocomplete') ? `='${value}'` : `ilike '%${value}%'`);
146
+ if (extra && pk) {
147
+ const query = data && sql
148
+ ? `${pk} in (select object_id from crm.extra_data where property_key='${name}' and value_text in ( ( with q(id,name) as (${sql}) select id from q where ${filterType === 'autocomplete' ? 'id' : 'name'} ${match})))`
149
+ : `${pk} in (select object_id from crm.extra_data where property_key='${name}' and value_text ${match})`;
150
+ return { op: 'ilike', query, extra };
151
+ }
152
+
153
+ const query = filter?.data && filter?.sql
154
+ ? `${filter?.name || filter?.id} in ( ( with q(id,name) as (${filter?.sql}) select id from q where ${filterType === 'autocomplete' ? 'id' : 'name'}::text ${match}) )` // filter with cls
155
+ : `${name}::text ${match}`; // simple filter
156
+ // console.log(query);
157
+ return { op: 'ilike', query };
158
+ }
159
+
160
+ // json
161
+ if (name.includes('.')) {
162
+ const [col, prop] = name.split('.');
163
+ const query = ` ${col}->>'${prop}' in ('${value.join("','")}')`;
164
+ return { op: 'in', query, extra };
165
+ }
166
+
167
+ // geometry
168
+ if (['geometry'].includes(fieldType)) {
169
+ const bbox = value[0].split('_');
170
+
171
+ if (bbox?.length === 4) {
172
+ const query = ` ${name} && 'box(${bbox[0]} ${bbox[1]},${bbox[2]} ${bbox[3]})'::box2d `;
173
+ return { op: '&&', query, extra };
174
+ }
175
+ }
176
+ return {};
177
+ }
178
+
179
+ export default formatValue;
@@ -1,3 +1,3 @@
1
- export default async function (fastify, opts) {
2
- fastify.get(`/test`, () => { return { test: true } });
3
- }
1
+ export default async function (fastify, opts) {
2
+ fastify.get(`/test`, () => { return { test: true } });
3
+ }