@opengis/admin 0.4.3 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/config.js CHANGED
@@ -1,5 +1,5 @@
1
- import { readFile } from 'fs/promises';
2
- import fs from 'fs';
3
- const config = fs.existsSync('config.json') ? JSON.parse(await readFile('config.json')) : {};
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+
3
+ const config = existsSync('config.json') ? JSON.parse(readFileSync('config.json')) : {};
4
4
 
5
5
  export default config;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengis/admin",
3
- "version": "0.4.3",
3
+ "version": "0.4.4",
4
4
  "description": "This project Softpro Admin",
5
5
  "main": "dist/admin.js",
6
6
  "type": "module",
package/plugin.js CHANGED
@@ -24,8 +24,8 @@ async function plugin(fastify, opts = config) {
24
24
  fastify.register(import('./server/routes/user/index.mjs'), opts);
25
25
  fastify.register(import('./server/routes/widget/index.mjs'), opts);
26
26
  fastify.register(import('./server/routes/access/index.mjs'), opts);
27
- fastify.register(import('./server/routes/report/index.mjs'), opts);
28
- fastify.register(import('./server/routes/print/index.mjs'), opts);
27
+ // fastify.register(import('./server/routes/report/index.mjs'), opts);
28
+ // fastify.register(import('./server/routes/print/index.mjs'), opts);
29
29
  fastify.register(import('./server/routes/util/index.mjs'), opts);
30
30
  }
31
31
  export default fp(plugin)
@@ -6,8 +6,6 @@ import {
6
6
  getTemplatePath, addHook, getToken, getTemplate, config, pgClients, initPG, getRedis, logger, getMenu,
7
7
  } from '@opengis/fastify-table/utils.js';
8
8
 
9
- import printTemplates from '../routes/print/controllers/printTemplates.js';
10
-
11
9
  const { client } = pgClients;
12
10
 
13
11
  const rclient = getRedis();
@@ -84,31 +82,6 @@ export default async function plugin(fastify) {
84
82
  }
85
83
  });
86
84
 
87
- fastify.addHook('onListen', async () => {
88
- return; // temporary moved to product/rent
89
- // insert document templates to db (print API)
90
- const printTemplateList = getTemplatePath('print');
91
- printTemplateList.filter(el => el[2] === 'json').map((el) => {
92
- const settings = JSON.parse(readFileSync(el[1]) || '{}');
93
- const htmlPath = printTemplateList.find(item => item[0] === el[0] && ['hbs', 'html'].includes(item[2]))?.[1];
94
- const html = htmlPath ? readFileSync(htmlPath, 'utf-8') : null;
95
- Object.assign(settings, { html });
96
- printTemplates[el[0]] = settings;
97
- });
98
- if (client?.pk?.['admin.templates']) {
99
- const arr = Object.keys(printTemplates || {}).map(el => ({ name: el, ...printTemplates?.[el] || {} })).filter(el => el.name && el.route && el.html);
100
-
101
- const { rowsCount = 0 } = await pgClients.client.query(`delete from admin.templates where not (name=any($1::text[])) and type = 'demo'`, [arr.map(el => el.name)]);
102
- console.log('delete deprecated templates', 'ok', rowsCount);
103
- const { rowsCount: empty = 0 } = await pgClients.client.query('delete from admin.templates where body is null');
104
- console.log('delete empty templates', 'ok', empty);
105
-
106
- const q = arr.map(el => `insert into admin.templates(name, route_id, title, type, body) values ('${el.name.replace(/'/g, "''")}', '${el.route.replace(/'/g, "''")}', '${(el.title || el.name).replace(/'/g, "''")}', 'demo', '${(el.html || '').replace(/'/g, "''")}') on conflict(name, type) do update set route_id=excluded.route_id, title=excluded.title`).join(';');
107
- const res = await pgClients.client.query(q);
108
- console.log('insert print templates', 'ok', (Array.isArray(res) ? res : [res]).length);
109
- }
110
- });
111
-
112
85
  fastify.addHook('onListen', async () => {
113
86
  const clsQuery = [];
114
87
  if (!client?.pk?.['admin.cls']) return;
@@ -1,136 +0,0 @@
1
- import path from 'path';
2
- import qr from 'qrcode';
3
- import { readFile } from 'node:fs/promises';
4
- import { fileURLToPath } from 'url';
5
- import { createHash } from 'crypto';
6
-
7
- import {
8
- config, getTemplate, pgClients, handlebars, getFilterSQL, logger, metaFormat, getMeta,
9
- } from '@opengis/fastify-table/utils.js';
10
- import { grpc } from '@opengis/fastify-file/utils.js';
11
-
12
- const { htmlToPdf } = grpc();
13
- const filename = fileURLToPath(import.meta.url);
14
- const dirname = path.dirname(filename);
15
-
16
- // printMap
17
- const host = 'https://data.gki.com.ua';
18
- const width = 850;
19
- const height = 400;
20
- const geomBuffer = 0.001;
21
- const layers = '';
22
- const basemap = 'voyager';
23
-
24
- export default async function cardPrint(req, reply) {
25
- const { pg = pgClients.client, params = {}, query = {}, user = {} } = req;
26
- const { table, id } = params;
27
-
28
- const { template = 'card-print.pt', tab } = query;
29
- const format = query.format || (config.debug ? 'html' : 'pdf');
30
-
31
- const hash = createHash('md5').update([table, id, template, tab].join()).digest('hex');
32
-
33
- // const rootDir = getFolder(req, 'local');
34
- // const filepath = path.join(rootDir, '/files/tmp/print/', `${hash}.pdf`);
35
-
36
- const headers = {
37
- 'Content-Disposition': `inline; filename=${hash}.pdf`,
38
- 'Content-Type': 'application/pdf',
39
- };
40
-
41
- if (!user?.uid) {
42
- return { message: 'access restricted', status: 401 };
43
- }
44
-
45
- if (!table || !id) {
46
- return { message: 'not enougn params: table, id', status: 400 };
47
- }
48
-
49
- const body = await getTemplate('table', table);
50
- const { geom } = await getMeta({ pg, table: body?.table });
51
-
52
- if (!body?.table) {
53
- return { message: 'table nof found', status: 404 };
54
- }
55
-
56
- if (!body.key && !pg.pk?.[body.table]) {
57
- return { message: 'pkey not found', status: 404 };
58
- }
59
-
60
- const where = `${body.query || '1=1'} and ${body.key || pg.pk?.[body.table]}=$1`;
61
-
62
- const { optimizedSQL = `select * from ${body.table} where ${body.query || '1=1'} and ` } = await getFilterSQL({
63
- pg,
64
- table,
65
- query: where,
66
- })
67
- const { rows = [] } = await pg.query(`select * ${geom ? `, st_asgeojson(${geom})::json as geom` : ''} from (${optimizedSQL})q where ${where}`, [id]);
68
-
69
- // metaFormat + descriptionList => bugs
70
- // const cls = body?.columns?.filter(el => el.data)?.reduce((acc, curr) => Object.assign(acc, { [curr.name]: curr.data }), {});
71
- // await metaFormat({ rows, cls, sufix: false });
72
-
73
- const data = rows?.[0];
74
- if (!data) {
75
- return { message: 'data not found', status: 404 };
76
- }
77
-
78
- Object.assign(data, { id: data[body.key || pg.pk?.[body.table]] });
79
-
80
- const mapUrl = `${host}/api-user/print-map?basemap=${basemap}&layers=${layers || ''}&geojson=${JSON.stringify(data['geom'])}&base64=1&height=${height}&width=${width}&buffer=${geomBuffer}&nocache=1`;
81
- const resp = data['geom'] ? await fetch(mapUrl) : null;
82
- const printMap = data['geom'] ? await resp.text() : '';
83
-
84
- const pt = await getTemplate('pt', template)
85
- || await readFile(path.join(dirname, '../../../templates/pt/card-print.pt.hbs'), 'utf8');
86
-
87
- const trimPort = ['80', '443'].find(el => req.hostname.endsWith(el));
88
- const url = (req.protocol || 'https') + '://' + req.hostname.replace(trimPort, '') + req.url.replace(req.routeOptions.url.split(':')[0], '/card/');
89
- const qrCode = `<img src="${await qr.toDataURL(url, { type: 'png', ec_level: 'M', size: 5, margin: 4 })}" alt="qrcode">`;
90
-
91
- const cardTemplates = await getTemplate('card', table);
92
- const index = cardTemplates?.find(el => el[0] === 'index.yml')?.[1];
93
- const cardHbsTabs = cardTemplates.filter(el => el[0].endsWith('hbs'));
94
-
95
- const orderedTabs = index?.panels
96
- ?.flatMap(panel => panel.items?.map(item => {
97
- const body = cardHbsTabs.find(el => el[0] === `${item.name}.hbs`)?.[1];
98
- return { ...item, body };
99
- }))
100
- .filter(el => el.name && el.body)
101
- .filter(el => query.tab ? el.name === query.tab.toString() : true);
102
-
103
- const tabData = await Promise.all(orderedTabs.map(async (el) => {
104
- const html = await handlebars.compile(el.body.replace(/\{\{\{button[^\}]*\}\}\}/g, ''))(data);
105
- return { name: el.name, title: el.title, html };
106
- }));
107
-
108
- const title = data?.[body.meta.title || ''];
109
-
110
- const columnTitles = body?.columns?.reduce((acc, curr) => Object.assign(acc, { [curr.name]: curr.title || curr.ua }), {});
111
- const obj = {
112
- title,
113
- table_title: body.ua || body.title,
114
- printMap,
115
- rows: tabData,
116
- data: Object.keys(data).filter(el => columnTitles[el]).reduce((acc, curr) => Object.assign(acc, { [columnTitles[curr] || curr]: data[curr] }), {}),
117
- rawData: data,
118
- url,
119
- qr: qrCode,
120
- };
121
-
122
- const html = await handlebars.compile(pt || 'template not found')(obj);
123
-
124
- if (format == 'html') {
125
- return reply.headers({ 'Content-Type': 'text/html; charset=utf-8' }).send(html);
126
- }
127
-
128
- const result = await htmlToPdf({ html });
129
- const buffer = Buffer.from(result.result, 'base64');
130
-
131
- // await mkdir(path.dirname(filepath), { recursive: true });
132
- // await writeFile(filepath, buffer);
133
-
134
- logger.file('cardPrint', { table, id, format, uid: user?.uid });
135
- return reply.headers(headers).send(buffer);
136
- }
@@ -1,37 +0,0 @@
1
- import { pgClients, dataInsert } from '@opengis/fastify-table/utils.js';
2
-
3
- export default async function printTemplateAdd({
4
- pg = pgClients.client, body = {}, user = {},
5
- }) {
6
- if (!user?.uid) {
7
- return { message: 'access restricted', status: 403 };
8
- }
9
-
10
- const { name, title, route, html } = body;
11
-
12
- if (!name) {
13
- return { message: 'not enough body params: name', status: 400 };
14
- }
15
-
16
- if (!html) {
17
- return { message: 'not enough body params: html', status: 400 };
18
- }
19
-
20
- const id = await pg.query(`select template_id as id from admin.templates where $1 in (template_id, name)`, [name])
21
- .then(el => el.rows?.[0]?.id);
22
-
23
- if (id) {
24
- return { message: 'access restricted: template exists', status: 403 };
25
- }
26
-
27
- const res = await dataInsert({
28
- pg,
29
- table: 'admin.templates',
30
- data: { name, title, route_id: route, body: html, type: 'user' },
31
- uid: user?.uid,
32
- })
33
-
34
- const data = res.rows?.[0];
35
-
36
- return { id: data?.template_id, data };
37
- }
@@ -1,29 +0,0 @@
1
- import { pgClients, dataDelete } from '@opengis/fastify-table/utils.js';
2
-
3
- export default async function printTemplateDelete({
4
- pg = pgClients.client, params = {}, user = {},
5
- }) {
6
- if (!user?.uid) {
7
- return { message: 'access restricted', status: 403 };
8
- }
9
-
10
- const { id, type } = await pg.query(`select template_id as id, type from admin.templates where enabled and $1 in (template_id, name)`, [params.id])
11
- .then(el => el.rows?.[0] || {});
12
-
13
- if (!id) {
14
- return { message: 'template not found', status: 404 };
15
- }
16
-
17
- if (type === 'demo') {
18
- return { message: 'access restricted: demo', status: 403 };
19
- }
20
-
21
- const res = await dataDelete({
22
- pg,
23
- table: 'admin.templates',
24
- id,
25
- uid: user?.uid,
26
- });
27
-
28
- return { id: res?.template_id, data: res };
29
- }
@@ -1,42 +0,0 @@
1
- import { pgClients, dataInsert } from '@opengis/fastify-table/utils.js';
2
-
3
- export default async function printTemplateEdit({
4
- pg = pgClients.client, params = {}, body = {}, user = {},
5
- }) {
6
- if (!user?.uid) {
7
- return { message: 'access restricted', status: 403 };
8
- }
9
-
10
- if (!params?.id) {
11
- return { message: 'not enough params: id', status: 400 };
12
- }
13
-
14
- const { html, route, title } = body;
15
-
16
- if (!html) {
17
- return { message: 'not enough body params: html', status: 400 };
18
- }
19
-
20
- const { id, name } = await pg.query(`select template_id as id, name from admin.templates where $1 in (template_id, name)`, [params.id])
21
- .then(el => el.rows?.[0] || {});
22
-
23
- if (!id) {
24
- return { message: 'template not found', status: 404 };
25
- }
26
-
27
- await pg.query(`delete from admin.templates where $1 in (template_id, name)`, [id]);
28
-
29
- const data = { name, body: html, type: 'user' };
30
- if (title) Object.assign(data, { title });
31
- if (route) Object.assign(data, { route_id: route });
32
-
33
- const res = await dataInsert({
34
- pg,
35
- table: 'admin.templates',
36
- id,
37
- data,
38
- uid: user?.uid,
39
- });
40
-
41
- return { id: res.rows?.[0]?.template_id, data: res.rows?.[0] };
42
- }
@@ -1,67 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
-
3
- import { config, getFilterSQL, getTemplate, handlebars, pgClients } from '@opengis/fastify-table/utils.js';
4
- import { grpc } from '@opengis/fastify-file/utils.js';
5
-
6
- const { htmlToPdf } = grpc();
7
-
8
- export default async function printTemplate(req, reply) {
9
- const {
10
- pg = pgClients.client,
11
- params = {},
12
- query = {},
13
- } = req;
14
-
15
- if (!params?.name) {
16
- return { message: 'not enough params: name', status: 400 };
17
- }
18
-
19
- if (!params?.id) {
20
- return { message: 'not enough params: id', status: 400 };
21
- }
22
-
23
- const { id, route, body = '' } = await pg.query(`select template_id as id, body, route_id as route from admin.templates where $1 in (template_id,name)`, [params.name])
24
- .then(el => el.rows?.[0] || {});
25
-
26
- if (!id) {
27
- return reply.status(404).send('template not found');
28
- }
29
-
30
- /* -- params.name === document template -- */
31
- const format = query.format || (config.debug ? 'html' : 'pdf');
32
-
33
- const hash = createHash('md5')
34
- .update([params?.name, params?.id].join())
35
- .digest('hex');
36
-
37
- const headers = format === 'pdf'
38
- ? { 'Content-Disposition': `inline; filename=${hash}.pdf`, 'Content-Type': 'application/pdf' }
39
- : { 'Content-Type': 'text/html; charset=utf-8' };
40
-
41
- const table = await pg.query(`select alias from admin.routes where route_id=$1`, [route])
42
- .then(el => el.rows?.[0]?.alias);
43
-
44
- if (!table) {
45
- return { message: 'route table not found', status: 404 };
46
- }
47
-
48
- const loadTable = await getTemplate('table', table);
49
- const { optimizedSQL } = await getFilterSQL({ table, pg });
50
-
51
- const where = `${loadTable?.key || pg.pk?.[loadTable?.table || table]}=any($1::text[])`;
52
-
53
- const q = `select * from (${optimizedSQL})q where ${loadTable?.query || '1=1'} and ${where}`;
54
-
55
- const { rows = [] } = await pg.query(q, [params.id.split(',')]);
56
-
57
- const htmls = await Promise.all(rows.map(async (row) => handlebars.compile(body)(row)));
58
- const html = htmls.join('<p style="page-break-after: always;">&nbsp;</p>');
59
-
60
- if (format == 'html') {
61
- return reply.headers(headers).send(html);
62
- }
63
-
64
- const result = await htmlToPdf({ html });
65
- const buffer = Buffer.from(result.result, 'base64');
66
- return reply.headers(headers).send(buffer);
67
- }
@@ -1,20 +0,0 @@
1
- import { pgClients } from "@opengis/fastify-table/utils.js";
2
-
3
- const maxLimit = 100;
4
-
5
- export default async function printTemplateList({
6
- pg = pgClients.client, query = {},
7
- }) {
8
- const { page = 1 } = query;
9
-
10
- const limit = Math.min(maxLimit, +(query.limit || 20));
11
-
12
- const offset = page && page > 0 ? (page - 1) * limit : '0';
13
-
14
- const q = `select template_id as id, name, title, route_id as route, type from admin.templates
15
- where enabled limit ${limit} offset ${offset}`;
16
-
17
- const { rows = [] } = pg.pk?.['admin.templates'] ? await pg.query(q) : {};
18
-
19
- return { page, limit, rows };
20
- }
@@ -1,87 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
-
3
- import { config, getFilterSQL, getTemplate, handlebars, pgClients, getMeta } from '@opengis/fastify-table/utils.js';
4
- import { grpc } from '@opengis/fastify-file/utils.js';
5
-
6
- const { htmlToPdf } = grpc();
7
-
8
- export default async function printTemplate(req, reply) {
9
- const {
10
- pg = pgClients.client,
11
- params = {},
12
- query = {},
13
- } = req;
14
-
15
- if (!params?.name) {
16
- return reply.status(404).send('not enough params: name');
17
- }
18
-
19
- const { id, name, title, body = '', route } = await pg.query(`select template_id as id, name, title, body, route_id as route from admin.templates where $1 in (template_id,name)`, [params.name])
20
- .then(el => el.rows?.[0] || {});
21
-
22
- if (!id) {
23
- return reply.status(404).send('template not found');
24
- }
25
-
26
- /* -- params.name === document template -- */
27
- const format = query.format || (config.debug ? 'html' : 'pdf');
28
-
29
- const hash = createHash('md5')
30
- .update([query?.preview, query?.demo, params?.name].join())
31
- .digest('hex');
32
-
33
- const headers = format === 'pdf'
34
- ? { 'Content-Disposition': `inline; filename=${hash}.pdf`, 'Content-Type': 'application/pdf' }
35
- : { 'Content-Type': 'text/html; charset=utf-8' };
36
-
37
- if (query?.preview) {
38
- const matches = body?.match?.(/{{(?!\!)([^}]*)}}/g) || [];
39
- const preview = `<style> #toggle { background: yellow; } </style>`
40
- + matches.reduce((acc, curr) => acc.replace(curr, curr.replace(/{{(?!\!)([^}]*)}}/g, `<div id="toggle">${curr.replace(/{/g, '%7B').replace(/}/g, '%7D')}</div>`)), body);
41
-
42
- const html = await handlebars.compile(preview)({});
43
-
44
- if (format == 'html') {
45
- return reply.headers(headers).send(html.replace(/%7B/g, '{').replace(/%7D/g, '}'));
46
- }
47
-
48
- const result = await htmlToPdf({ html: html.replace(/%7B/g, '{').replace(/%7D/g, '}') });
49
- const buffer = Buffer.from(result.result, 'base64');
50
- return reply.headers(headers).send(buffer);
51
- }
52
-
53
- const { alias, table } = await pg.query(`select alias, table_name as table from admin.routes where route_id=$1`, [route])
54
- .then(el => el.rows?.[0] || {});
55
-
56
- if (!alias || !table) {
57
- return reply.status(404).send('route table not found');
58
- }
59
-
60
- if (query?.demo) {
61
- const loadTable = await getTemplate('table', alias);
62
- const { optimizedSQL } = await getFilterSQL({ pg, table: alias });
63
-
64
- if (!optimizedSQL) {
65
- return reply.status(400).send('empty query');
66
- }
67
-
68
- const q = `select * from (${optimizedSQL})q where ${loadTable?.query || '1=1'} limit 1`;
69
-
70
- const obj = await pg.query(q).then(el => el.rows?.[0] || {});
71
-
72
- const html = await handlebars.compile(body)(obj);
73
-
74
- if (format == 'html') {
75
- return reply.headers(headers).send(html);
76
- }
77
-
78
- const result = await htmlToPdf({ html });
79
- const buffer = Buffer.from(result.result, 'base64');
80
- return reply.headers(headers).send(buffer);
81
- }
82
-
83
- const meta = await getMeta({ pg, table });
84
- const columns = meta.columns?.map(el => ({ name: el.name, title: el.title, type: pg.pgType[el.dataTypeID] || 'text' }));
85
- // for body edit
86
- return { name, title, html: body, route, alias, table, columns };
87
- }
@@ -1 +0,0 @@
1
- export default {}
@@ -1,20 +0,0 @@
1
- import cardPrint from './controllers/cardPrint.js';
2
- import printTemplateAdd from './controllers/printTemplate.add.js';
3
- import printTemplateEdit from './controllers/printTemplate.edit.js';
4
- import printTemplateDelete from './controllers/printTemplate.delete.js';
5
- import printTemplate from './controllers/printTemplate.js';
6
- import printTemplatePreview from './controllers/printTemplatePreview.js';
7
- import printTemplateList from './controllers/printTemplateList.js';
8
-
9
- const policy = ['user'];
10
-
11
- // temporary moved to product/rent
12
- export default async function route(app) {
13
- // app.get(`/card-print/:table/:id`, { config: { policy } }, cardPrint);
14
- // app.get('/print-template/:name/:id', { config: { policy } }, printTemplate);
15
- // app.get('/print-template/:name', { config: { policy } }, printTemplatePreview);
16
- // app.get('/print-template', { config: { policy } }, printTemplateList);
17
- // app.post('/print-template', { config: { policy } }, printTemplateAdd);
18
- // app.put('/print-template/:id', { config: { policy } }, printTemplateEdit);
19
- // app.delete('/print-template/:id', { config: { policy } }, printTemplateDelete);
20
- }
@@ -1,23 +0,0 @@
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,142 +0,0 @@
1
- import path from 'node:path';
2
-
3
- import { pgClients, getTemplate, metaFormat } from '@opengis/fastify-table/utils.js';
4
-
5
- import getFilterQuery from '../utils/getFilterQuery.js';
6
- import { downloadFile, getExport, getMimeType } from '@opengis/fastify-file/utils.js';
7
-
8
- const maxLimit = 100;
9
-
10
- const matches = {
11
- 16: 'yes/no', // boolean
12
- 701: 'number', // double precision
13
- 1082: 'date', // date
14
- 1184: 'date', // timestamp w/ time zone
15
- 1114: 'date', // timestamp w/o time zone
16
- 1700: 'number', // numeric
17
- };
18
-
19
- export default async function tableData(req, reply) {
20
- const {
21
- pg = pgClients.client, params = {}, query = {}, user = {}, host, unittest,
22
- } = req;
23
-
24
- if (!params?.name) {
25
- return { message: 'not enough params: name', status: 400 };
26
- }
27
-
28
- const body = await getTemplate('report', params.name);
29
- const loadTemplate = Array.isArray(body) ? body?.find?.(el => el[0].replace(path.extname(el[0]), '') === 'index')?.[1] : body;
30
-
31
- if (!loadTemplate?.sql && !loadTemplate?.table) {
32
- return reply.status(404).send(`report not found: ${params.name}`);
33
- }
34
-
35
- if (loadTemplate?.table && !pg.pk?.[loadTemplate.table]) {
36
- return reply.status(404).send(`table not found: ${loadTemplate.table}`);
37
- }
38
-
39
- if (Array.isArray(body)) {
40
- loadTemplate.widgets = [];
41
- body.filter(el => el[0].replace(path.extname(el[0]), '') !== 'index').forEach((el) => {
42
- loadTemplate.widgets.push(el[1]);
43
- });
44
- }
45
-
46
- const { title, subtitle, category, widgets = [], kpi, sql = `select * from ${loadTemplate.table} where ${loadTemplate.query || 'true'}`, meta, filters } = loadTemplate;
47
- const { date, columns: metaColumns } = meta || {};
48
-
49
- const granularity = query.granularity && date && false ? `date_trunc('${query.granularity}',${date})::date::text` : null;
50
- const groupby = [meta?.groupby, granularity].filter(el => el).join(',');
51
- const [orderby, ord] = (query.order || loadTemplate.orderby || '').replace(/ /, '-').split('-');
52
-
53
- const period = query.period && date ? `${date}=${query.period}` : null;
54
- const filter = [query.filter, period].filter(el => el).join(';');
55
-
56
- const limit = Math.min(maxLimit, +(query.limit || 20));
57
- const offset = query.page && query.page > 0 ? (query.page - 1) * limit : 0;
58
-
59
- const { fields = [] } = await pg.query(`select * from (${sql.replace(/{{uid}}/g, user?.uid)})q limit 0`);
60
-
61
- const where = getFilterQuery({ pg, filter, fields, filterList: filters, searchColumns: meta.search, search: query.search });
62
-
63
- const orderbyColumnExists = fields?.find?.(el => el.name === orderby);
64
- const q = `select ${metaColumns || '*'} from (${sql.replace(/{{uid}}/g, user?.uid)})q where ${where || '1=1'} ${groupby ? `group by ${groupby}` : ''} ${orderby && orderbyColumnExists ? `order by ${orderby} ${['asc', 'desc'].includes(ord) ? ord : 'desc'} nulls last` : ''} limit ${limit} offset ${offset}`;
65
-
66
- if (query.sql && user?.user_type?.includes('admin')) {
67
- return q;
68
- }
69
-
70
- if (query.export) {
71
- const resp = await getExport({
72
- pg,
73
- host,
74
- unittest,
75
- nocache: query.nocache,
76
- tableSql: `select ${metaColumns || '*'} from (${sql.replace(/{{uid}}/g, user?.uid)})q where ${where || '1=1'}`,
77
- sourceName: title || 'report',
78
- columns: fields.map(({ name }) => ({ name, title: meta?.titles?.[name] || name })),
79
- cls: meta?.cls,
80
- format: ['xlsx', 'csv'].find(el => (req.query.format || 'xlsx') === el) || 'xlsx',
81
- formatAnswer: 'filepath',
82
- }, reply);
83
- if (resp?.filePath) {
84
- const buffer = await downloadFile(resp.filePath, { buffer: true });
85
- const headers = {};
86
- headers['Content-Type'] = `attachment; filename=${getMimeType(resp.filePath)}`;
87
- headers['Content-Disposition'] = `attachment; filename=${path.basename(resp.filePath)}`;
88
- return reply.status(200).headers(headers).send(buffer);
89
- }
90
- return resp;
91
- }
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
-
96
- if (kpi?.length) {
97
- await Promise.all(kpi.map(async (el) => {
98
- if (!el.sql && !el.table) {
99
- Object.assign(el, { error: 'empty sql / table' });
100
- return;
101
- }
102
-
103
- const sqlq = el.sql || `select ${el.agg || 'count(*)'} as value from ${el.table} where ${el.query || 'true'}`;
104
- const { rows = [], fields = [] } = await pg.query(sqlq.replace(/{{uid}}/g, user?.uid)).catch(err => {
105
- Object.assign(el, { error: err.toString() });
106
- }) || {};
107
- Object.assign(el, { count: rows?.[0]?.[fields[0].name] || 0, sql: user?.user_type === 'admin' ? sqlq.replace(/{{uid}}/g, user?.uid) : undefined });
108
- }));
109
- }
110
-
111
- widgets?.forEach?.((el) => Object.assign(el, {
112
- agg: user?.user_type === 'admin' ? el.agg : undefined,
113
- sql: user?.user_type === 'admin' ? el.sql : undefined
114
- }));
115
-
116
- const { rows = [] } = await pg.query(q).catch(err => {
117
- return reply.status(500).send('query error: ' + err.toString());
118
- });
119
-
120
- await metaFormat({ rows, cls: meta?.cls, sufix: false }, pg);
121
-
122
- const columns = fields.map(el => ({
123
- name: el.name,
124
- title: meta?.titles?.[el.name] || el.name,
125
- format: meta?.cls?.[el.name] ? 'select' : (matches[el.dataTypeID] || 'text'),
126
- data: meta?.cls?.[el.name],
127
- }));
128
-
129
- return {
130
- q: user?.user_type?.includes('admin') ? q : undefined,
131
- total,
132
- filtered,
133
- kpi,
134
- data: rows,
135
- title,
136
- subtitle,
137
- category,
138
- widgets,
139
- columns,
140
- filters,
141
- };
142
- }
@@ -1,108 +0,0 @@
1
- import path from 'node:path';
2
-
3
- import { pgClients, getTemplate, metaFormat } from '@opengis/fastify-table/utils.js';
4
-
5
- const maxLimit = 100;
6
-
7
- const matches = {
8
- 16: 'yes/no', // boolean
9
- 701: 'number', // double precision
10
- 1082: 'date', // date
11
- 1184: 'date', // timestamp w/ time zone
12
- 1114: 'date', // timestamp w/o time zone
13
- 1700: 'number', // numeric
14
- };
15
-
16
- function normalizeData(widget, limit = maxLimit, offset = 0) {
17
- const groupby = typeof widget.groupby === 'string'
18
- ? { name: widget.groupby }
19
- : (widget.groupby?.[0] || widget.groupby);
20
-
21
- const agg = groupby.name
22
- ? `${widget.granularity ? `date_trunc('${widget.granularity}', ${groupby.name})` : `${groupby.name}`}`
23
- : 'count(*)';
24
-
25
- const xCol = widget.granularity
26
- ? `date_trunc('${widget.granularity}', ${groupby.name})`
27
- : groupby.name;
28
-
29
- const sql = `select * from ${widget.table} where ${widget.query || 'true'} limit ${limit} offset ${offset}`;
30
-
31
- const q = `select ${agg} as ${groupby.name}, ${widget.agg} as metric from (${sql}) t
32
- ${groupby.name ? `group by ${xCol}` : ''}
33
- ${widget.orderby || xCol ? `order by ${widget.orderby || xCol}` : ''}`;
34
-
35
- return { groupby, agg, xCol, q };
36
- }
37
-
38
- export default async function widgetData({
39
- pg = pgClients.client, params = {}, query = {}, user = {},
40
- }, reply) {
41
- if (!params?.name) {
42
- return { message: 'not enough params: name', status: 400 };
43
- }
44
-
45
- if (!params?.widget) {
46
- return reply.status(400).send('not enough params: widget');
47
- }
48
-
49
- const body = await getTemplate('report', params.name);
50
- const loadTemplate = Array.isArray(body) ? body?.find?.(el => el[0].replace(path.extname(el[0]), '') === 'index')?.[1] : body;
51
-
52
- if (!loadTemplate) {
53
- return reply.status(404).send(`report not found: ${params.name}`);
54
- }
55
-
56
- if (Array.isArray(body)) {
57
- loadTemplate.widgets = [];
58
- body.filter(el => el[0].replace(path.extname(el[0]), '') !== 'index').forEach((el) => {
59
- loadTemplate.widgets.push(el[1]);
60
- });
61
- }
62
-
63
- const { widgets = [] } = loadTemplate;
64
-
65
- const widget = widgets.find(el => el.name === params.widget);
66
-
67
- if (!widget) {
68
- return reply.status(404).send(`widget not found: ${params.widget}`);
69
- }
70
-
71
- if (!widget.table || !pg.pk?.[widget.table]) {
72
- return reply.status(404).send(`widget table not found: ${widget.table}`);
73
- }
74
-
75
- const { cls = {}, titles = {} } = widget.meta || {};
76
-
77
- const limit = Math.min(query.limit || maxLimit, maxLimit);
78
- const offset = query.page && query.page > 0 ? (query.page - 1) * limit : 0;
79
-
80
- const { groupby, q } = normalizeData(widget, limit, offset);
81
-
82
- if (groupby.cls) {
83
- Object.assign(cls, { [groupby.name]: groupby.cls });
84
- }
85
-
86
- if (query.sql) return q;
87
-
88
- const { rows = [], fields = [] } = await pg.query(q).catch(err => {
89
- Object.assign(widget, { error: err.toString() });
90
- }) || {};
91
- await metaFormat({ rows, cls, sufix: false }, pg);
92
-
93
- const columns = fields.map(el => ({
94
- name: el.name,
95
- title: titles?.[el.name] || el.name,
96
- format: cls?.[el.name] ? 'select' : (matches[el.dataTypeID] || 'text'),
97
- data: cls?.[el.name],
98
- }));
99
-
100
- Object.assign(widget, {
101
- source: rows,
102
- columns,
103
- agg: user?.user_type === 'admin' ? widget.agg : undefined,
104
- sql: user?.user_type === 'admin' ? q : undefined,
105
- });
106
-
107
- return widget;
108
- }
@@ -1,9 +0,0 @@
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 +0,0 @@
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,68 +0,0 @@
1
- /* eslint-disable no-continue */
2
-
3
- import { pgClients } from '@opengis/fastify-table/utils.js';
4
-
5
- import formatValue from './formatValue.js';
6
-
7
- export default function getFilterQuery({ pg = pgClients.client, filter: filterStr, fields, filterList, searchColumns, search }) {
8
- if (!filterStr && !search) return null;
9
-
10
- const mainOperators = ['=', '~', '>', '<'];
11
-
12
- const filterQueryArray = decodeURIComponent(filterStr?.replace(/%/g, '%25').replace(/%/g, '\\%')?.replace(/(^,)|(,$)/g, '')).replace(/'/g, '').split(/[;|]/);
13
-
14
- const resultList = [];
15
- const searchwith = searchColumns || fields?.filter?.((el) => pg.pgType?.[el.dataTypeID] === 'text')?.map?.((el) => el.name)?.join?.(',');
16
-
17
- const sval = `ilike '%${decodeURIComponent(search?.replace(/%/g, '%25')).replace(/'/g, "''").replace(/%/g, '\\%')}%'`;
18
- const searchQuery = search && searchwith ? ` (${searchwith.split(',')?.map((name) => `${name} ${sval}`).join(' or ')} )` : '';
19
-
20
- for (let i = 0; i < filterQueryArray.length; i += 1) {
21
- const item = filterQueryArray[i];
22
- const operator = mainOperators?.find((el) => item.indexOf(el) !== -1) || '=';
23
- const [name] = item.split(operator);
24
-
25
- // skip already added filter
26
- if (resultList.find((el) => el.name === name)) {
27
- continue;
28
- }
29
-
30
- // filter
31
- const filter = filterList?.find((el) => [el.id, el.name].includes(name)) || { type: 'text' };
32
-
33
- // find all value
34
- const value = filterQueryArray.filter((el) => el.startsWith(name)).map((el) => el.substring(name.length + 1)).join(',');
35
-
36
- if (filter?.query) {
37
- resultList.push({
38
- name, value, query: filter?.query, operator: '=', filterType: filter.type, type: 'text',
39
- });
40
- continue;
41
- }
42
-
43
- // find field and skip not exists
44
- const { dataTypeID } = fields?.find((el) => el.name === name) || {};
45
-
46
- // format query
47
- const {
48
- op, query, filterType, fieldType,
49
- } = formatValue({
50
- pg,
51
- filter,
52
- name,
53
- value,
54
- operator,
55
- dataTypeID,
56
- }) || {};
57
- if (!query) continue;
58
-
59
- resultList.push({
60
- name, value, query, operator: op, filterType, type: fieldType,
61
- });
62
- }
63
-
64
- const where = [searchQuery].concat(resultList?.map?.(el => el.query) || []).filter(el => el).join(' and ');
65
-
66
- return where;
67
- }
68
-