@opengis/admin 0.4.3 → 0.4.5

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 (30) hide show
  1. package/config.js +3 -3
  2. package/dist/{add-page-fdr6t9-i.js → add-page-DCJ-Yp0v.js} +1 -1
  3. package/dist/{admin-interface-bYzTXuVs.js → admin-interface-BZK7WQza.js} +1 -1
  4. package/dist/{admin-view-3hBO0cXK.js → admin-view-B0_hyDn5.js} +3 -3
  5. package/dist/admin.js +1 -1
  6. package/dist/admin.umd.cjs +72 -72
  7. package/dist/{card-view-Dfgoq-T0.js → card-view-DXKWi1Ty.js} +1 -1
  8. package/dist/{edit-page-pykfh5fh.js → edit-page-DO8gx1TX.js} +1 -1
  9. package/dist/{import-file-DPcs2POV.js → import-file-BlI2DAMT.js} +12172 -12157
  10. package/dist/{profile-page-UeVwkn5K.js → profile-page-9oNOPlYV.js} +1 -1
  11. package/dist/style.css +1 -1
  12. package/module/settings/card/admin.users.table/routes.hbs +1 -1
  13. package/package.json +1 -1
  14. package/plugin.js +2 -2
  15. package/server/plugins/hook.js +0 -27
  16. package/server/routes/print/controllers/cardPrint.js +0 -136
  17. package/server/routes/print/controllers/printTemplate.add.js +0 -37
  18. package/server/routes/print/controllers/printTemplate.delete.js +0 -29
  19. package/server/routes/print/controllers/printTemplate.edit.js +0 -42
  20. package/server/routes/print/controllers/printTemplate.js +0 -67
  21. package/server/routes/print/controllers/printTemplateList.js +0 -20
  22. package/server/routes/print/controllers/printTemplatePreview.js +0 -87
  23. package/server/routes/print/controllers/printTemplates.js +0 -1
  24. package/server/routes/print/index.mjs +0 -20
  25. package/server/routes/report/controllers/list.js +0 -23
  26. package/server/routes/report/controllers/tableData.js +0 -142
  27. package/server/routes/report/controllers/widgetData.js +0 -108
  28. package/server/routes/report/index.mjs +0 -9
  29. package/server/routes/report/utils/formatValue.js +0 -179
  30. package/server/routes/report/utils/getFilterQuery.js +0 -68
@@ -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
- }