@opengis/admin 0.2.71 → 0.2.73

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.
@@ -1,4 +1,5 @@
1
1
  import path from 'node:path';
2
+ import { readFileSync } from 'node:fs';
2
3
 
3
4
  import {
4
5
  getTemplatePath, addHook, getToken, getTemplate, config, pgClients,
@@ -6,6 +7,7 @@ import {
6
7
  } from '@opengis/fastify-table/utils.js';
7
8
 
8
9
  import getMenu from '../routes/menu/controllers/getMenu.js';
10
+ import printTemplates from '../routes/print/controllers/printTemplates.js';
9
11
 
10
12
  const { client } = pgClients;
11
13
 
@@ -76,12 +78,24 @@ export default async function plugin(fastify) {
76
78
  }
77
79
  });
78
80
 
81
+ fastify.addHook('onListen', async () => {
82
+ // insert document templates to db (print API)
83
+ const printTemplateList = getTemplatePath('print');
84
+ printTemplateList.filter(el => el[2] === 'json').map((el) => {
85
+ const settings = JSON.parse(readFileSync(el[1]) || '{}');
86
+ printTemplates[el[0]] = settings;
87
+ });
88
+ if (client?.pk?.['admin.templates']) {
89
+ console.log('insert into admin.templates', printTemplateList); // test!
90
+ }
91
+ });
92
+
79
93
  fastify.addHook('onListen', async () => {
80
94
  const clsQuery = [];
81
95
  if (!client?.pk?.['admin.cls']) return;
82
96
 
83
- const selectList = await getTemplatePath('select');
84
- const clsList = (await getTemplatePath('cls'))?.filter((el) => !(selectList?.map((el) => el?.[0]) || []).includes(el[0]));
97
+ const selectList = getTemplatePath('select');
98
+ const clsList = (getTemplatePath('cls'))?.filter((el) => !(selectList?.map((el) => el?.[0]) || []).includes(el[0]));
85
99
  const cls = (selectList || []).concat(clsList || [])
86
100
  ?.map((el) => ({ name: el[0], module: path.basename(path.dirname(path.dirname(el[1]))), type: { 'json': 'cls', 'sql': 'select' }[el[2]] }))
87
101
  if (!cls?.length) return;
@@ -1,15 +1,21 @@
1
- import { handlebars, getMeta, getTemplate } from '@opengis/fastify-table/utils.js';
1
+ import { getMeta, getTemplate, pgClients, handlebarsSync } from '@opengis/fastify-table/utils.js';
2
+
3
+ const isValidDate = (dateStr) => (new Date(dateStr)).toString() !== 'Invalid Date';
2
4
 
3
5
  export default async function calendarData({
4
- pg, params = {}, query = {}, session = {},
6
+ pg = pgClients.client, params = {}, query = {}, session = {},
5
7
  }) {
6
8
  const { name } = params;
7
- const { uid } = session.passport?.user || {};
9
+ const { granularity = 'month' } = query;
10
+ const { user = {} } = session.passport || {};
11
+
8
12
  if (!name) {
9
13
  return { message: 'not enough params: name', status: 400 };
10
14
  }
11
- const { date, sql } = query;
12
-
15
+
16
+ if (query.granularity && !['day', 'month', 'week', 'year'].includes(granularity)) {
17
+ return { message: 'invalid query params: granularity', status: 400 };
18
+ }
13
19
 
14
20
  const body = await getTemplate('calendar', name);
15
21
 
@@ -20,10 +26,8 @@ export default async function calendarData({
20
26
  const {
21
27
  title,
22
28
  table,
23
- query: query1 = '1=1',
24
29
  meta = {},
25
- filter = [],
26
- } = body;
30
+ } = body || {};
27
31
 
28
32
  if (!table) {
29
33
  return { message: 'not enough calendar params: table', status: 404 };
@@ -32,57 +36,91 @@ export default async function calendarData({
32
36
  return { message: `table pkey not found: ${table}`, status: 404 };
33
37
  }
34
38
 
35
- const filterWhere = filter?.length && query.filter?.length
36
- ? filter.filter((el) => (Object.hasOwn(el, 'enabled') ? el?.enabled : true))
39
+ const filterList = (body?.filter || [])
40
+ .concat(body?.filterInline || [])
41
+ .concat(body?.filterCustom || [])
42
+ .concat(body?.filterState || [])
43
+ .concat(body?.filterList || [])
44
+ .concat(body?.filters || [])
45
+ .concat(body?.filter_list || []);
46
+
47
+ const { columns = [] } = await getMeta({ pg, table });
48
+ const columnList = columns?.map((el) => el?.name);
49
+
50
+ const dateColumn = columns?.find((el) => el?.name === (meta?.date || meta?.start))?.name
51
+ || columns?.find((el) => el?.name === 'cdate')?.name;
52
+
53
+ if (query.date && !dateColumn) {
54
+ return { message: 'invalid template params: date column not found', status: 400 };
55
+ }
56
+
57
+ if (query.date && !isValidDate(query.date)) {
58
+ return { message: 'Invalid date: out of range or incorrect format', status: 400 };
59
+ }
60
+
61
+ const filterWhere = filterList?.length && query.filter?.length
62
+ ? filterList
63
+ .filter((el) => (Object.hasOwn(el, 'enabled') ? el?.enabled : true))
37
64
  .map((el) => {
38
65
  const val = query.filter.split(',').find((e) => e?.split('=')?.shift()?.includes(el.column || el.name))?.split('=')?.pop();
39
- if (val) return el.column && val ? `(${[`${el.column}::text='${val.replace(/'/g,"''")}'::text`, el.query].filter((el) => el).join(' and ')})` : el.query;
40
- }).filter((el) => el).join(' and ')
66
+ if (val) return el.column && val ? `(${[`${el.column}::text='${val.replace(/'/g, "''")}'::text`, el.query].filter((el) => el).join(' and ')})` : el.query;
67
+ })
68
+ .filter((el) => el)
69
+ .join(' and ')
41
70
  : undefined;
42
- // console.log(filterWhere);
43
71
 
44
- const queryWhere = await handlebars.compile(query1)({ uid });
45
- const filterDate = date ? `date_trunc('month', "${meta?.date || meta?.start}"::date)='${date}'::date` : undefined;
46
- const where = [queryWhere, filterDate, filterWhere].filter((el) => el).join(' and ');
72
+ const queryWhere = handlebarsSync.compile(body.query || '1=1')({ user, uid: user?.uid });
73
+ const filterDate = query.date ? `date_trunc('${granularity}', "${dateColumn}"::date)='${query.date}'::date` : undefined;
74
+
75
+ const where = [queryWhere, filterDate, filterWhere].filter((el) => el).join(' and ');
76
+
77
+ const filtersByColumn = filterList.filter((el) => (Object.hasOwn(el, 'enabled') ? el?.enabled : true) && el?.column);
47
78
 
48
- const filtersByColumn = filter.filter((el) => (Object.hasOwn(el, 'enabled') ? el?.enabled : true) && el?.column);
49
-
50
79
  const filters = [];
51
80
  if (filtersByColumn?.length) {
52
81
  await Promise.all(filtersByColumn.map(async (el) => {
53
- const { rows: filterData = [] } = await pg.query(`select $1 as id, count(*) from $2
54
- where ${el.query || '1=1'} and ${filterWhere || '1=1'} group by $1`, [el.column, table] );
82
+ const { rows: filterData = [] } = await pg.query(`select ${el.column.replace(/'/g, "''")} as id, count(*) from ${table}
83
+ where ${el.query || '1=1'} and ${filterWhere || '1=1'} group by ${el.column.replace(/'/g, "''")}`);
55
84
  if (!filterData?.length) return;
56
-
57
- // const clsData = await getSelectVal({ pg, name: el.cls, values: filterData.map((el) => el.id) });
58
- const clsData = el.cls ? await getTemplate(['cls', 'select'], el.cls) : undefined;
59
-
60
- if (!el.cls) {
61
- filterData.forEach((el1) => filters.push(el1));
85
+
86
+ const clsData = await getTemplate(['cls', 'select'], el.cls);
87
+
88
+ if (!el.cls || !clsData?.length) {
89
+ filterData.forEach((item) => filters.push(item));
62
90
  return;
63
91
  }
64
92
 
65
- filterData.forEach((el1) => {
66
- const cls = clsData.find((item) => item.id === el1.id.toString());
67
- Object.assign(el1, { title: cls?.text, color: cls?.color });
68
- filters.push(el1);
93
+ filterData.forEach((filter) => {
94
+ const cls = clsData.find((item) => item.id === filter.id.toString());
95
+ Object.assign(filter, { title: cls?.text, color: cls?.color });
96
+ filters.push(filter);
69
97
  });
70
98
  }));
71
99
  }
72
100
 
73
- const tableMeta = await getMeta({ pg, table });
74
- const columnList = tableMeta?.columns?.map((el) => el?.name);
75
- const columns = Object.keys(meta).filter((el) => ['date', 'start','end','title','status'].includes(el) && columnList.includes(meta[el])).map((el) => `"${meta[el]}" as ${el}`);
76
-
77
- if (!columns?.length) {
101
+ const filtersByPreparedQuery = filterList.filter((el) => (Object.hasOwn(el, 'enabled') ? el?.enabled : true) && !el?.column && el?.query);
102
+
103
+ if (filtersByPreparedQuery?.length) {
104
+ await Promise.all(filtersByPreparedQuery.map(async (el) => {
105
+ const { rows = [] } = await pg.query(`select ${el.query} as id, count(*) from ${table}
106
+ where ${filterWhere || '1=1'} group by ${el.query}`);
107
+ rows.forEach((item) => filters.push(item));
108
+ }));
109
+ }
110
+
111
+ const metaColumns = Object.keys(meta)
112
+ .filter((el) => ['date', 'start', 'end', 'title', 'status'].includes(el) && columnList.includes(meta[el]))
113
+ .map((el) => `"${meta[el]}" as ${el}`);
114
+
115
+ if (!metaColumns?.length) {
78
116
  return { message: `calendar param meta is invalid: invalid/empty keys`, status: 404 };
79
117
  }
80
118
 
81
- const q = `select &1 from $2 where $3`;
82
- if (sql) return q;
119
+ const q = `select ${metaColumns.join(',')} from ${table} where ${where}`;
120
+ if (query?.sql && user?.user_type?.includes('admin')) return q;
121
+
122
+ const { rows = [] } = await pg.query(q);
83
123
 
84
- const { rows = [] } = await pg.query(q, [columns.join(','), table, where]);
85
-
86
- return { title, filters, rows };
124
+ return { title, filters, granularity, sql: user?.user_type?.includes('admin') ? q : undefined, rows };
87
125
 
88
126
  }
@@ -3,7 +3,7 @@ const calendarDataSchema = {
3
3
  name: { type: 'string', pattern: '^([\\d\\w._-]+)$' },
4
4
  },
5
5
  querystring: {
6
- date: { type: 'string', pattern: '^([\\d\\s\\/,.:-]+)$' },
6
+ date: { type: 'string', pattern: '^\\d{4}-\\d{2}-\\d{2}$' },
7
7
  sql: { type: 'string', pattern: '^(\\d)$' },
8
8
  },
9
9
 
@@ -1,5 +1,7 @@
1
1
  import path from 'path';
2
2
  import qr from 'qrcode';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { fileURLToPath } from 'url';
3
5
  import { createHash } from 'crypto';
4
6
 
5
7
  import {
@@ -9,6 +11,8 @@ import {
9
11
  import { grpc } from '@opengis/fastify-file/utils.js';
10
12
 
11
13
  const { htmlToPdf } = grpc();
14
+ const filename = fileURLToPath(import.meta.url);
15
+ const dirname = path.dirname(filename);
12
16
 
13
17
  export default async function cardPrint(req, reply) {
14
18
  const { pg = pgClients.client, params = {}, query = {}, user = {} } = req;
@@ -62,7 +66,8 @@ export default async function cardPrint(req, reply) {
62
66
  return { message: 'data not found', status: 404 };
63
67
  }
64
68
 
65
- const pt = await getTemplate('pt', template);
69
+ const pt = await getTemplate('pt', template)
70
+ || await readFile(path.join(dirname, '../../../templates/pt/card-print.pt.hbs'), 'utf8');
66
71
 
67
72
  const url = (req.protocol || 'https') + '://' + req.hostname + req.url;
68
73
  const qrCode = `<img src="${await qr.toDataURL(url, { type: 'png', ec_level: 'M', size: 5, margin: 4 })}" alt="qrcode">`;
@@ -0,0 +1,121 @@
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
+ import printTemplates from './printTemplates.js';
7
+
8
+ const { htmlToPdf } = grpc();
9
+
10
+ export default async function printTemplate(req, reply) {
11
+ const {
12
+ pg = pgClients.client,
13
+ params = {},
14
+ query = {},
15
+ user = {},
16
+ } = req;
17
+
18
+ if (!params?.name) {
19
+ return { message: 'not enough params: name', status: 400 };
20
+ }
21
+
22
+ const printBody = await getTemplate('print', params.name);
23
+
24
+ /* -- params.name === interface -- */
25
+ if (!printBody?.route) {
26
+ const where = user?.user_type?.includes('admin')
27
+ ? '1=1'
28
+ : `coalesce(b.user_uid, d.user_uid)='${user?.uid?.replace(/'/g, "''")}'::text`;
29
+
30
+ const { route_id: routeId, alias } = await pg.query(`select a.route_id, alias
31
+ from admin.routes a
32
+ left join admin.role_access b on
33
+ a.route_id=b.route_id
34
+ left join admin.roles c on
35
+ b.role_id=c.role_id
36
+ and c.enabled
37
+ left join admin.user_roles d on
38
+ c.role_id=d.role_id
39
+ and ( case when
40
+ d.expiration is not null
41
+ then d.expiration > CURRENT_DATE
42
+ else 1=1
43
+ end )
44
+ where $1 in (a.route_id, a.alias, a.table_name) and ${where}`, [params.name])
45
+ .then(el => el.rows?.[0] || {});
46
+
47
+ if (!routeId || !alias) {
48
+ return { message: `access restricted: route (${params.name}/${routeId})`, status: 403 };
49
+ }
50
+
51
+ const rows = Object.keys(printTemplates)
52
+ .filter(key => printTemplates[key]?.route === routeId)
53
+ .map(key => ({ key, title: printTemplates[key]?.title }));
54
+
55
+ return { rows };
56
+ }
57
+
58
+ if (!query.preview && !query?.demo && !params?.id) {
59
+ return { message: 'not enough params: id', status: 400 };
60
+ }
61
+
62
+ /* -- params.name === document template -- */
63
+ const format = query.format || (config.debug ? 'html' : 'pdf');
64
+
65
+ const hash = createHash('md5')
66
+ .update([query?.preview, query?.demo, params?.name, params?.id].join())
67
+ .digest('hex');
68
+
69
+ const headers = format === 'pdf'
70
+ ? { 'Content-Disposition': `inline; filename=${hash}.pdf`, 'Content-Type': 'application/pdf' }
71
+ : { 'Content-Type': 'text/html; charset=utf-8' };
72
+
73
+ const pt = printBody?.hbs || printBody?.html;
74
+
75
+ if (query?.preview) {
76
+ const matches = pt.match(/{{(?!\!)([^}]*)}}/g);
77
+ const preview = `<style> #toggle { background: yellow; } </style>`
78
+ + matches.reduce((acc, curr) => acc.replace(curr, curr.replace(/{{(?!\!)([^}]*)}}/g, `<div id="toggle">${curr.replace(/{/g, '%7B').replace(/}/g, '%7D')}</div>`)), pt);
79
+
80
+ const html = await handlebars.compile(preview)({});
81
+
82
+ if (format == 'html') {
83
+ return reply.headers(headers).send(html.replace(/%7B/g, '{').replace(/%7D/g, '}'));
84
+ }
85
+
86
+ const result = await htmlToPdf({ html: html.replace(/%7B/g, '{').replace(/%7D/g, '}') });
87
+ const buffer = Buffer.from(result.result, 'base64');
88
+ return reply.headers(headers).send(buffer);
89
+ }
90
+
91
+ if (query?.demo || params?.id) {
92
+ const table = await pg.query(`select alias from admin.routes where route_id=$1`, [printBody.route])
93
+ .then(el => el.rows?.[0]?.alias);
94
+
95
+ if (!table) {
96
+ return { message: 'route table not found', status: 404 };
97
+ }
98
+
99
+ const loadTable = await getTemplate('table', table);
100
+ const { optimizedSQL } = await getFilterSQL({ table, pg });
101
+
102
+ const where = query.demo
103
+ ? ' 1=1 limit 1'
104
+ : `${loadTable?.key || pg.pk?.[loadTable?.table || table]}=$1`;
105
+
106
+ const q = `select * from (${optimizedSQL})q where ${loadTable?.query || '1=1'} and ${where}`;
107
+
108
+ const obj = await pg.query(q, [params.id].filter(el => el))
109
+ .then(el => el.rows?.[0] || {});
110
+
111
+ const html = await handlebars.compile(pt)(obj);
112
+
113
+ if (format == 'html') {
114
+ return reply.headers(headers).send(html);
115
+ }
116
+
117
+ const result = await htmlToPdf({ html });
118
+ const buffer = Buffer.from(result.result, 'base64');
119
+ return reply.headers(headers).send(buffer);
120
+ }
121
+ }
@@ -0,0 +1 @@
1
+ export default {}
@@ -1,5 +1,7 @@
1
- import cardPrint from './controllers/cardPrint.js';
2
-
3
- export default async function route(app) {
4
- app.get(`/card-print/:table/:id`, cardPrint);
5
- }
1
+ import cardPrint from './controllers/cardPrint.js';
2
+ import printTemplate from './controllers/printTemplate.js';
3
+
4
+ export default async function route(app) {
5
+ app.get(`/card-print/:table/:id`, cardPrint);
6
+ app.get('/print-template/:name/:id?', printTemplate);
7
+ }