@opengis/fastify-table 1.0.47 → 1.0.49

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/Changelog.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # fastify-table
2
2
 
3
+ ## 1.0.49 - 26.06.2024
4
+
5
+ - refactor - npm settings
6
+
7
+ ## 1.0.48 - 26.06.2024
8
+
9
+ - search api no specified table mode support
10
+
3
11
  ## 1.0.47 - 25.06.2024
4
12
 
5
13
  - add extra properties support
@@ -3,7 +3,7 @@ import dataInsert from "../funcs/dataInsert.js";
3
3
  const table = 'crm.properties';
4
4
 
5
5
  function checkKeyType({ body, key }) {
6
- if (typeof body[key] === 'number' && !body[key].toString().includes('.')) {
6
+ if (typeof body[key] === 'number' && (!/\D/.test(body[key].toString()) && body[key].toString().length < 10)) {
7
7
  return { [key]: 'int' };
8
8
  } else if (typeof body[key] === 'object') {
9
9
  return { [key]: 'json' };
package/index.js CHANGED
@@ -13,7 +13,6 @@ import notificationPlugin from './notification/index.js';
13
13
  import widgetPlugin from './widget/index.js';
14
14
  import crudPlugin from './crud/index.js';
15
15
  import policyPlugin from './policy/index.js';
16
- import settingsPlugin from './settings/index.js';
17
16
 
18
17
  import pgClients from './pg/pgClients.js';
19
18
 
@@ -75,7 +74,6 @@ async function plugin(fastify, opt) {
75
74
  crudPlugin(fastify, opt);
76
75
  notificationPlugin(fastify, opt);
77
76
  widgetPlugin(fastify, opt);
78
- settingsPlugin(fastify, opt);
79
77
  }
80
78
  export default fp(plugin);
81
79
  // export { rclient };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengis/fastify-table",
3
- "version": "1.0.47",
3
+ "version": "1.0.49",
4
4
  "type": "module",
5
5
  "description": "core-plugins",
6
6
  "main": "index.js",
@@ -0,0 +1,41 @@
1
+ import getTemplate from './utils/getTemplate.js';
2
+ import getMeta from '../../pg/funcs/getMeta.js';
3
+ import metaFormat from '../funcs/metaFormat/index.js';
4
+
5
+ export default async function card(req) {
6
+ const time = Date.now();
7
+ const {
8
+ pg, params, query = {},
9
+ } = req;
10
+
11
+ const loadTable = await getTemplate('table', params.table);
12
+
13
+ if (!loadTable) { return { status: 404, message: 'not found' }; }
14
+
15
+ const { table, columns, meta, sql, cardSql } = loadTable;
16
+ const { pk, columns: dbColumns = [] } = await getMeta(table);
17
+
18
+ if (!pk) return { message: `table not found: ${table}`, status: 404 };
19
+
20
+ const cols = columns.map((el) => el.name || el).join(',');
21
+ const columnList = dbColumns.map((el) => el.name || el).join(',');
22
+ const sqlTable = sql?.filter?.((el) => !el?.disabled && el?.sql?.replace).map((el, i) => ` left join lateral (${el.sql}) ${el.name || `t${i}`} on 1=1 `)?.join('') || '';
23
+ const cardSqlFiltered = params.id ? cardSql?.filter?.((el) => !el?.disabled && el?.name && el?.sql?.replace) : [];
24
+ const cardSqlTable = cardSqlFiltered.length ? cardSqlFiltered.map((el, i) => ` left join lateral (select json_agg(row_to_json(q)) as ${el.name} from (${el.sql})q) ct${i} on 1=1 `).join('') || '' : '';
25
+
26
+ const where = [`"${pk}" = $1`, loadTable.query].filter((el) => el);
27
+ const cardColumns = cardSqlFiltered.length ? `,${cardSqlFiltered.map((el) => el.name)}` : '';
28
+ const q = `select ${pk ? `"${pk}" as id,` : ''} ${columnList.includes('geom') ? `st_asgeojson(geom)::json as geom,` : ''} ${cols || '*'} ${cardColumns} from ${table} t ${sqlTable} ${cardSqlTable}
29
+ where ${where.join(' and ') || 'true'} limit 1`;
30
+
31
+ if (query.sql === '1') { return q; }
32
+
33
+ const { rows } = await pg.query(q, [params.id]);
34
+
35
+ await metaFormat({ rows, table: params.table });
36
+
37
+ const data = meta.card?.length ? meta.card.reduce((acc, curr) => Object.assign(acc, { [columns.find((col) => col.name === curr)?.ua || '']: rows[0][curr] }), {}) : {};
38
+ return {
39
+ time: Date.now() - time, data,
40
+ };
41
+ }
@@ -1,17 +1,20 @@
1
1
  import getTemplate from './utils/getTemplate.js';
2
2
  import getMeta from '../../pg/funcs/getMeta.js';
3
3
  import metaFormat from '../funcs/metaFormat/index.js';
4
+ import getTemplates from './utils/getTemplates.js';
4
5
 
5
- const maxLimit = 100;
6
+ function sequence(tables, data, fn) {
7
+ return tables.reduce((promise, table) => promise.then(() => fn({
8
+ ...data, tableName: table.replace('.json', ''),
9
+ })), Promise.resolve());
10
+ }
6
11
 
7
- export default async function data({
8
- pg, query = {},
12
+ async function getData({
13
+ pg, tableName, query = {}, maxLimit, res,
9
14
  }) {
10
- const time = Date.now();
15
+ const loadTable = await getTemplate('table', tableName);
11
16
 
12
- const loadTable = await getTemplate('table', query.table);
13
-
14
- if (!loadTable) { return { message: 'not found', status: 404 }; }
17
+ if (!loadTable) { return { message: 'not found', status: 404 }; }
15
18
 
16
19
  const { table, columns, meta } = loadTable;
17
20
  const { pk } = await getMeta(table);
@@ -20,22 +23,46 @@ export default async function data({
20
23
  const [orderColumn, orderDir] = (query.order || loadTable.order || '').split('-');
21
24
  const order = cols.includes(orderColumn) && orderColumn?.length ? `order by ${orderColumn} ${query.desc || orderDir === 'desc' ? 'desc' : ''}` : '';
22
25
 
23
- const limit = Math.min(maxLimit, +(query.limit || 10));
26
+ const limit = Math.max(maxLimit - res.rows.length, 0);
27
+ // Math.max(query.offset - res.rows.length,0)
24
28
  const offset = query.page && query.page > 0 ? ` offset ${(query.page - 1) * limit}` : '';
25
29
 
26
30
  const search = meta?.search && query.key ? `(${meta?.search.concat(meta?.title ? `,${meta?.title}` : '').split(',').map(el => `${el} ilike '%${query.key}%'`).join(' or ')})` : null;
27
31
 
28
32
  const where = [loadTable.query, search].filter((el) => el);
29
33
  const q = `select ${pk ? `"${pk}" as id,` : ''} * from ${table} t where ${where.join(' and ') || 'true'} ${order} ${offset} limit ${limit}`;
30
-
31
- if (query.sql === '1') return q;
34
+ if (query.sql) {
35
+ res.sql.push(q);
36
+ return;
37
+ }
32
38
 
33
39
  const { rows } = await pg.query(q);
34
40
 
35
- const total = await pg.queryCache(`select count(*) from ${table} t where ${where.join(' and ') || 'true'}`).then((el) => el?.rows[0]?.count);
41
+ const total = await pg.queryCache(`select count(*) from ${table} t where ${where.join(' and ') || 'true'}`).then((el) => el?.rows[0]?.count) || 0;
42
+
43
+ await metaFormat({ rows, table: tableName });
44
+ res.total += +total;
45
+ rows.forEach((row) => res.rows.push({ ...row, register: tableName }));
46
+ }
47
+
48
+ export default async function data({
49
+ pg, query = {},
50
+ }) {
51
+ const time = Date.now();
52
+
53
+ try {
54
+ const tables = query.table ? [query.table] : await getTemplates('table');
55
+ const res = { rows: [], sql: [], total: 0 };
56
+
57
+ const maxLimit = Math.min(100, query.limit || '16');
58
+ await sequence(tables, { pg, query, maxLimit, res }, getData);
59
+
60
+ if (query.sql) return res.sql.join(';\n');
36
61
 
37
- await metaFormat({ rows, table: query.table });
38
- return {
39
- time: Date.now() - time, total, count: rows.length, rows,
40
- };
62
+ return {
63
+ time: Date.now() - time, total: res.total, count: res.rows.length, rows: res.rows,
64
+ };
65
+ } catch (err) {
66
+ return { error: err.toString(), status: 500 };
67
+ }
41
68
  }
@@ -0,0 +1,18 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import config from '../../../config.js';
4
+
5
+ const loadTemplate = {};
6
+
7
+ export default async function getTemplateDir(type) {
8
+ if (!type) return null;
9
+
10
+ const cwd = process.cwd();
11
+ const typeDir = path.join(cwd, (config.templateDir || 'server/templates'), type);
12
+
13
+ if (!loadTemplate[type]) {
14
+ const typeList = fs.existsSync(typeDir) ? fs.readdirSync(typeDir) : [];
15
+ loadTemplate[type] = typeList;
16
+ }
17
+ return loadTemplate[type];
18
+ }
package/table/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import suggest from './controllers/suggest.js';
2
2
  import data from './controllers/data.js';
3
+ import card from './controllers/card.js';
3
4
  import search from './controllers/search.js';
4
5
  import filter from './controllers/filter.js';
5
6
  import form from './controllers/form.js';
@@ -34,6 +35,7 @@ async function plugin(fastify, config = {}) {
34
35
 
35
36
  fastify.get(`${prefix}/suggest/:data`, {}, suggest);
36
37
  fastify.get(`${prefix}/data/:table/:id?`, { schema: tableSchema }, data); // vs.crm.data.api с node
38
+ fastify.get(`${prefix}/card/:table/:id`, { schema: tableSchema }, card);
37
39
  fastify.get(`${prefix}/search`, { schema: searchTableSchema }, search);
38
40
  fastify.get(`${prefix}/filter/:table`, {}, filter);
39
41
  fastify.get(`${prefix}/form/:form`, {}, form);
@@ -1,246 +0,0 @@
1
- create schema if not exists admin;
2
-
3
- -- DROP TABLE is exists admin.users;
4
- CREATE TABLE if not exists admin.users();
5
- ALTER TABLE admin.users add column if not exists uid text NOT NULL DEFAULT next_id();
6
- ALTER TABLE admin.users DROP CONSTRAINT if exists admin_user_uid_pkey cascade;
7
-
8
- ALTER TABLE admin.users add column if not exists login text;
9
- ALTER TABLE admin.users add column if not exists password text NOT NULL DEFAULT ''::text;
10
- ALTER TABLE admin.users add column if not exists user_name text;
11
- ALTER TABLE admin.users add column if not exists sur_name text;
12
- ALTER TABLE admin.users add column if not exists father_name text;
13
- ALTER TABLE admin.users add column if not exists email text;
14
- ALTER TABLE admin.users add column if not exists phone text;
15
- ALTER TABLE admin.users add column if not exists avatar text;
16
- ALTER TABLE admin.users add column if not exists enabled boolean;
17
- ALTER TABLE admin.users add column if not exists user_personal_code text;
18
- ALTER TABLE admin.users add column if not exists last_activity_date timestamp without time zone;
19
- ALTER TABLE admin.users add column if not exists user_type text DEFAULT 'regular'::text;
20
- ALTER TABLE admin.users add column if not exists salt text;
21
- ALTER TABLE admin.users add column if not exists cdate timestamp without time zone DEFAULT date_trunc('seconds'::text, now());
22
- ALTER TABLE admin.users add column if not exists editor_id text;
23
- ALTER TABLE admin.users add column if not exists editor_date timestamp without time zone;
24
-
25
- ALTER TABLE admin.users add CONSTRAINT admin_user_uid_pkey PRIMARY KEY (uid);
26
-
27
- COMMENT ON COLUMN admin.users.uid IS 'ID користувача';
28
- COMMENT ON COLUMN admin.users.login IS 'Логін користувача';
29
- COMMENT ON COLUMN admin.users.password IS 'Пароль користувача';
30
- COMMENT ON COLUMN admin.users.user_name IS 'Ім''я користувача';
31
- COMMENT ON COLUMN admin.users.sur_name IS 'Прізвище користувача';
32
- COMMENT ON COLUMN admin.users.father_name IS 'По-батькові користувача';
33
- COMMENT ON COLUMN admin.users.email IS 'Ел. пошта користувача';
34
- COMMENT ON COLUMN admin.users.phone IS 'Номер телефону користувача';
35
- COMMENT ON COLUMN admin.users.avatar IS 'Аватар';
36
- COMMENT ON COLUMN admin.users.enabled IS 'Вкл. / Відкл';
37
- COMMENT ON COLUMN admin.users.last_activity_date IS 'Дата останньої активності';
38
- COMMENT ON COLUMN admin.users.user_type IS 'Тип користувача';
39
- COMMENT ON COLUMN admin.users.salt IS 'Сіль';
40
-
41
- -- drop table if exists admin.user_group;
42
- CREATE TABLE if not exists admin.user_group();
43
- alter table admin.user_group DROP CONSTRAINT if exists admin_user_group_id_pkey cascade;
44
-
45
- ALTER TABLE admin.user_group ADD COLUMN if not exists user_group_id text;
46
- ALTER TABLE admin.user_group ALTER COLUMN user_group_id SET NOT NULL;
47
- ALTER TABLE admin.user_group ALTER COLUMN user_group_id SET DEFAULT next_id();
48
- ALTER TABLE admin.user_group ADD COLUMN if not exists group_name text;
49
- ALTER TABLE admin.user_group ADD COLUMN if not exists enabled boolean;
50
- ALTER TABLE admin.user_group ADD COLUMN if not exists cdate timestamp without time zone;
51
- ALTER TABLE admin.user_group ALTER COLUMN cdate SET DEFAULT date_trunc('seconds'::text, now());
52
- ALTER TABLE admin.user_group ADD COLUMN if not exists uid text;
53
- ALTER TABLE admin.user_group ADD COLUMN if not exists editor_id text;
54
- ALTER TABLE admin.user_group ADD COLUMN if not exists editor_date timestamp without time zone;
55
-
56
- ALTER TABLE admin.user_group
57
- ADD CONSTRAINT admin_user_group_id_pkey PRIMARY KEY(user_group_id);
58
-
59
- COMMENT ON COLUMN admin.user_group.user_group_id IS 'Вкл./Выкл.';
60
- COMMENT ON COLUMN admin.user_group.group_name IS 'Назва групи';
61
- COMMENT ON COLUMN admin.user_group.enabled IS 'Вкл./Відкл.';
62
- COMMENT ON COLUMN admin.user_group.cdate IS 'Дата створення';
63
- COMMENT ON COLUMN admin.user_group.uid IS 'Хто створив';
64
- COMMENT ON COLUMN admin.user_group.editor_id IS 'Останній редагувач';
65
- COMMENT ON COLUMN admin.user_group.editor_date IS 'Дата останнього редагування';
66
-
67
- -- drop table if exists admin.user_access;
68
- CREATE TABLE if not exists admin.user_access();
69
- alter table admin.user_access DROP CONSTRAINT if exists admin_user_access_id_pkey;
70
- alter table admin.user_access DROP CONSTRAINT if exists admin_user_access_user_group_id_fkey;
71
- alter table admin.user_access DROP CONSTRAINT if exists admin_user_access_interface_id_uid_unique;
72
- alter table admin.user_access DROP CONSTRAINT if exists admin_user_access_interface_id_fkey;
73
-
74
- alter table admin.user_access add column if not exists user_access_id text NOT NULL DEFAULT next_id();
75
- alter table admin.user_access add column if not exists interface_id text NOT NULL;
76
- alter table admin.user_access add column if not exists user_group_id text;
77
- alter table admin.user_access add column if not exists user_uid text;
78
- alter table admin.user_access add column if not exists scope text;
79
- alter table admin.user_access add column if not exists actions text[];
80
- ALTER TABLE admin.user_access ADD COLUMN IF NOT EXISTS access_granted text;
81
- ALTER TABLE admin.user_access ADD COLUMN IF NOT EXISTS access_granted_time timestamp without time zone;
82
- alter table admin.user_access add column if not exists cdate timestamp without time zone NOT NULL DEFAULT date_trunc('seconds'::text, now());
83
- alter table admin.user_access add column if not exists uid text;
84
- alter table admin.user_access add column if not exists editor_id text;
85
- alter table admin.user_access add column if not exists editor_date timestamp without time zone;
86
-
87
- alter table admin.user_access
88
- add CONSTRAINT admin_user_access_id_pkey PRIMARY KEY (user_access_id);
89
-
90
- alter table admin.user_access
91
- add CONSTRAINT admin_user_access_user_group_id_fkey FOREIGN KEY (user_group_id) REFERENCES admin.user_group (user_group_id);
92
-
93
- alter table admin.user_access
94
- add CONSTRAINT admin_user_access_interface_id_uid_unique UNIQUE (interface_id, user_uid, user_group_id);
95
- alter table admin.user_access
96
- add constraint admin_user_access_interface_id_fkey FOREIGN KEY (interface_id) REFERENCES admin.interface_list(interface_id);
97
-
98
- COMMENT ON TABLE admin.user_access IS 'Налаштування прав. Відношення груп / окремих користувачів до шаблонів';
99
- COMMENT ON COLUMN admin.user_access.interface_id IS 'ID шаблона';
100
- COMMENT ON COLUMN admin.user_access.user_group_id IS 'ID групи';
101
- COMMENT ON COLUMN admin.user_access.user_uid IS 'ID користувача';
102
- COMMENT ON COLUMN admin.user_access.scope IS 'Обмеження виведення (власні, відповідальний, всі)';
103
- COMMENT ON COLUMN admin.user_access.actions IS 'Доступні дії';
104
- COMMENT ON COLUMN admin.user_access.access_granted IS 'Ідентифікатор користувача який надав доступ';
105
- COMMENT ON COLUMN admin.user_access.access_granted_time IS 'Час коли надали доступ';
106
-
107
- CREATE INDEX if not exists admin_user_access_interface_id_idx
108
- ON admin.user_access USING btree (interface_id COLLATE pg_catalog."default");
109
-
110
- CREATE INDEX if not exists admin_user_access_user_group_id_idx
111
- ON admin.user_access USING btree (user_group_id COLLATE pg_catalog."default");
112
-
113
- -- DROP TABLE if exists admin.user_group_rel;
114
- CREATE TABLE if not exists admin.user_group_rel();
115
- ALTER TABLE admin.user_group_rel DROP CONSTRAINT IF EXISTS admin_user_group_rel_pkey;
116
- ALTER TABLE admin.user_group_rel DROP CONSTRAINT IF EXISTS admin_user_group_rel_user_group_id_fkey;
117
- ALTER TABLE admin.user_group_rel DROP CONSTRAINT IF EXISTS admin_user_group_rel_user_uid_fkey;
118
- ALTER TABLE admin.user_group_rel DROP CONSTRAINT IF EXISTS admin_user_group_rel_user_uid_user_group_id_key;
119
-
120
- ALTER TABLE admin.user_group_rel ADD COLUMN IF NOT EXISTS ugr_id text NOT NULL DEFAULT next_id();
121
- ALTER TABLE admin.user_group_rel ADD COLUMN IF NOT EXISTS user_uid text NOT NULL;
122
- ALTER TABLE admin.user_group_rel ADD COLUMN IF NOT EXISTS user_group_id text NOT NULL;
123
- ALTER TABLE admin.user_group_rel ADD COLUMN IF NOT EXISTS cdate timestamp without time zone DEFAULT date_trunc('seconds'::text, now());
124
- ALTER TABLE admin.user_group_rel ADD COLUMN IF NOT EXISTS uid text;
125
- ALTER TABLE admin.user_group_rel ADD COLUMN IF NOT EXISTS editor_id text;
126
- ALTER TABLE admin.user_group_rel ADD COLUMN IF NOT EXISTS editor_date timestamp without time zone;
127
- ALTER TABLE admin.user_group_rel ADD COLUMN IF NOT EXISTS expiration date;
128
- ALTER TABLE admin.user_group_rel ADD COLUMN IF NOT EXISTS access_granted text;
129
- ALTER TABLE admin.user_group_rel ADD COLUMN IF NOT EXISTS access_granted_time timestamp without time zone;
130
-
131
- ALTER TABLE admin.user_group_rel ADD CONSTRAINT admin_user_group_rel_pkey PRIMARY KEY (ugr_id);
132
- ALTER TABLE admin.user_group_rel ADD CONSTRAINT admin_user_group_rel_user_group_id_fkey FOREIGN KEY (user_group_id) REFERENCES admin.user_group (user_group_id);
133
- ALTER TABLE admin.user_group_rel ADD CONSTRAINT admin_user_group_rel_user_uid_fkey FOREIGN KEY (user_uid) REFERENCES admin.users (uid);
134
- ALTER TABLE admin.user_group_rel ADD CONSTRAINT admin_user_group_rel_user_uid_user_group_id_key UNIQUE (user_uid, user_group_id);
135
-
136
- COMMENT ON TABLE admin.user_group_rel IS 'Відношення користувачів до груп';
137
- COMMENT ON COLUMN admin.user_group_rel.user_uid IS 'ID користувача';
138
- COMMENT ON COLUMN admin.user_group_rel.user_group_id IS 'ID групи';
139
- COMMENT ON COLUMN admin.user_group_rel.uid IS 'Користувач, який створив запис в БД';
140
- COMMENT ON COLUMN admin.user_group_rel.expiration IS 'закінчення терміну дії доступу до групи';
141
- COMMENT ON COLUMN admin.user_group_rel.access_granted IS 'Ідентифікатор користувача який надав доступ';
142
- COMMENT ON COLUMN admin.user_group_rel.access_granted_time IS 'Час коли надали доступ';
143
-
144
- CREATE INDEX IF NOT EXISTS admin_user_group_access_user_uid_idx ON admin.user_group_rel USING btree (user_uid COLLATE pg_catalog."default");
145
-
146
- CREATE INDEX IF NOT EXISTS admin_user_group_rel_cdate_btree_idx ON admin.user_group_rel USING btree (cdate);
147
-
148
- CREATE INDEX IF NOT EXISTS admin_user_group_rel_editor_date_btree_idx ON admin.user_group_rel USING btree (editor_date);
149
-
150
- CREATE INDEX IF NOT EXISTS admin_user_group_rel_user_uid_gin_idx ON admin.user_group_rel USING gin (user_uid COLLATE pg_catalog."default" gin_trgm_ops);
151
-
152
- CREATE INDEX IF NOT EXISTS admin_user_group_user_group_id_idx ON admin.user_group_rel USING btree (user_group_id COLLATE pg_catalog."default");
153
-
154
- -- DROP TABLE if exists admin.menu;
155
- CREATE TABLE if not exists admin.menu();
156
- alter table admin.menu DROP CONSTRAINT if exists admin_menu_id_pkey cascade;
157
- alter table admin.menu DROP CONSTRAINT if exists admin_menu_name_unique;
158
-
159
- alter table admin.menu add column if not exists menu_id text NOT NULL default next_id();
160
- alter table admin.menu add column if not exists name text;
161
- alter table admin.menu add column if not exists ord numeric;
162
- alter table admin.menu add column if not exists enabled boolean NOT NULL DEFAULT true;
163
- alter table admin.menu add column if not exists uid text;
164
- alter table admin.menu add column if not exists editor_id text;
165
- alter table admin.menu add column if not exists editor_date timestamp without time zone;
166
- alter table admin.menu add column if not exists cdate timestamp without time zone DEFAULT now();
167
- alter table admin.menu add CONSTRAINT admin_menu_id_pkey PRIMARY KEY (menu_id);
168
- alter table admin.menu add CONSTRAINT admin_menu_name_unique UNIQUE (name);
169
-
170
- COMMENT ON TABLE admin.menu IS 'Пункти меню';
171
- COMMENT ON COLUMN admin.menu.menu_id IS 'Ідентифікатор пункту меню';
172
- COMMENT ON COLUMN admin.menu.name IS 'Назва пункту меню';
173
- COMMENT ON COLUMN admin.menu.ord IS 'Порядковий номер';
174
- COMMENT ON COLUMN admin.menu.enabled IS 'On / Off';
175
-
176
- -- DROP TABLE if exists admin.interface_list;
177
- CREATE TABLE if not exists admin.interface_list();
178
- alter table admin.interface_list DROP CONSTRAINT if exists admin_interface_id_pkey cascade;
179
-
180
- alter table admin.interface_list add column if not exists interface_id text NOT NULL default next_id();
181
- alter table admin.interface_list add column if not exists alias text NOT NULL;
182
- alter table admin.interface_list add column if not exists title text;
183
- alter table admin.interface_list add column if not exists public boolean;
184
- alter table admin.interface_list add column if not exists menu_id text;
185
- alter table admin.interface_list add column if not exists uid text;
186
- alter table admin.interface_list add column if not exists editor_id text;
187
- alter table admin.interface_list add column if not exists editor_date timestamp without time zone;
188
- alter table admin.interface_list add column if not exists cdate timestamp without time zone DEFAULT now();
189
- alter table admin.interface_list add column if not exists enabled boolean NOT NULL DEFAULT true;
190
- alter table admin.interface_list add CONSTRAINT admin_interface_id_pkey PRIMARY KEY (interface_id);
191
- alter table admin.interface_list add constraint admin_interface_menu_id_fkey FOREIGN KEY (menu_id) REFERENCES admin.menu(menu_id);
192
-
193
- COMMENT ON TABLE admin.interface_list IS 'Список інтерфейсів';
194
- COMMENT ON COLUMN admin.interface_list.interface_id IS 'Ідентифікатор інтерфейса';
195
- COMMENT ON COLUMN admin.interface_list.alias IS 'Назва файлу інтерфейса';
196
- COMMENT ON COLUMN admin.interface_list.title IS 'Назва інтерфейсу українською';
197
- COMMENT ON COLUMN admin.interface_list.public IS 'Ознака чи для всіх показується';
198
- COMMENT ON COLUMN admin.interface_list.enabled IS 'On / Off';
199
- COMMENT ON COLUMN admin.interface_list.menu_id IS 'Пункт меню (для collapse)';
200
-
201
- CREATE EXTENSION if not exists pgcrypto SCHEMA public VERSION "1.3";
202
- CREATE OR REPLACE FUNCTION admin.crypt(text, text) RETURNS text AS '$libdir/pgcrypto', 'pg_crypt' LANGUAGE c IMMUTABLE STRICT COST 1;
203
-
204
- -- DROP FUNCTION admin.insert_update_user_before();
205
- CREATE OR REPLACE FUNCTION admin.insert_update_user_before()
206
- RETURNS trigger AS
207
-
208
- $BODY$
209
- DECLARE
210
-
211
- iterations int;
212
- hash character varying;
213
-
214
- BEGIN
215
-
216
- if(TG_OP='INSERT' or (TG_OP='UPDATE' and new.password<>old.password)) then
217
- if(char_length(new.password) <> 0 and char_length(new.password) < 8) then
218
- --raise exception 'password must be longer than 8 characters';
219
- end if;
220
- new.salt=md5(now()::text);
221
- --raise exception '%','change pass';
222
- if(new.salt ='') then
223
- new.salt=gen_salt('md5');
224
- end if;
225
- iterations = 10;
226
- hash='';
227
-
228
- loop
229
- if iterations=0 then
230
- exit;
231
- end if;
232
- hash = md5(new.password||hash||new.salt);
233
- iterations=iterations-1;
234
- end loop;
235
- new.password=admin.crypt(hash,new.salt);
236
-
237
- end if;
238
- RETURN new;
239
- END
240
- $BODY$
241
-
242
- LANGUAGE plpgsql VOLATILE COST 100;
243
-
244
- DROP TRIGGER if exists insert_update_user_before on admin.users;
245
- CREATE TRIGGER insert_update_user_before BEFORE INSERT OR UPDATE ON admin.users FOR EACH ROW
246
- EXECUTE PROCEDURE admin.insert_update_user_before();
@@ -1,27 +0,0 @@
1
- -- DROP TABLE setting.property;
2
- CREATE TABLE IF NOT EXISTS setting.property();
3
- ALTER TABLE setting.property DROP CONSTRAINT IF EXISTS setting_property_pkey;
4
- ALTER TABLE setting.property ADD COLUMN IF NOT EXISTS property_id text NOT NULL DEFAULT next_id();
5
-
6
- ALTER TABLE setting.property ADD COLUMN IF NOT EXISTS property_entity text;
7
- COMMENT ON COLUMN setting.property.property_entity IS 'Сутність';
8
- ALTER TABLE setting.property ADD COLUMN IF NOT EXISTS property_key text;
9
- COMMENT ON COLUMN setting.property.property_key IS 'Ключ';
10
- ALTER TABLE setting.property ADD COLUMN IF NOT EXISTS property_text text;
11
- COMMENT ON COLUMN setting.property.property_text IS 'Текстове значення налаштування';
12
- ALTER TABLE setting.property ADD COLUMN IF NOT EXISTS property_int integer;
13
- COMMENT ON COLUMN setting.property.property_int IS 'Цілочислове значения';
14
- ALTER TABLE setting.property ADD COLUMN IF NOT EXISTS property_json json;
15
- COMMENT ON COLUMN setting.property.property_json IS 'Значення налаштування';
16
- ALTER TABLE setting.property ADD COLUMN IF NOT EXISTS level text;
17
- COMMENT ON COLUMN setting.property.level IS 'Рівень (user/system)';
18
- ALTER TABLE setting.property ADD COLUMN IF NOT EXISTS object_id text;
19
- COMMENT ON COLUMN setting.property.object_id IS 'ID Об''єкту';
20
-
21
- ALTER TABLE setting.property ADD COLUMN IF NOT EXISTS uid text NOT NULL DEFAULT '1'::text;
22
- ALTER TABLE setting.property ADD COLUMN IF NOT EXISTS editor_id text;
23
- ALTER TABLE setting.property ADD COLUMN IF NOT EXISTS editor_date timestamp without time zone;
24
- ALTER TABLE setting.property ADD COLUMN IF NOT EXISTS cdate timestamp without time zone DEFAULT now();
25
- ALTER TABLE setting.property ADD COLUMN IF NOT EXISTS files json;
26
-
27
- ALTER TABLE setting.property ADD CONSTRAINT setting_property_pkey PRIMARY KEY(property_id);
@@ -1,24 +0,0 @@
1
- export default async function getSettingsAPI({
2
- pg, funcs, params = {},
3
- }) {
4
- const { key } = params;
5
-
6
- if (!pg?.pk?.['setting.property']) {
7
- return { message: 'table not found', status: 404 };
8
- }
9
-
10
- try {
11
- const res = await funcs.getSettings({ pg, key });
12
- if (key) {
13
- if (!res) {
14
- return { message: `settings not found: ${key}`, status: 404 };
15
- }
16
- return { message: res, status: 200 };
17
- }
18
- const { rows } = res || { };
19
- return { message: { total: rows.length || 0, rows }, status: 200 };
20
- }
21
- catch (err) {
22
- return { error: err.toString(), status: 500 };
23
- }
24
- }
@@ -1,14 +0,0 @@
1
- export default async function postSettingsAPI({
2
- pg, funcs, body = {},
3
- }) {
4
- const { key, val } = body;
5
- if (!key || !val) {
6
- return { message: 'not enough params', status: 400 };
7
- }
8
- const res = await funcs.setSettings({
9
- pg, funcs, key, val,
10
- });
11
- if (res?.error) return res;
12
-
13
- return { message: res, status: 200 };
14
- }
@@ -1,12 +0,0 @@
1
- export default async function getSettings({ pg, key }) {
2
- const sql = `select property_id as id, property_entity, property_key, property_text,
3
- property_int, property_json, level, object_id, uid, cdate, editor_id, editor_date from setting.property
4
- where ${key ? 'property_key=$1' : '1=1'}`;
5
-
6
- if (!key) {
7
- const { rows } = await pg.query(sql);
8
- return { rows };
9
- }
10
- const data = await pg.one(sql, [key]);
11
- return data;
12
- }
@@ -1,29 +0,0 @@
1
- const table = 'setting.property';
2
-
3
- function checkValueType(val) {
4
- if (val) {
5
- if (typeof val === 'object') {
6
- return 'property_json';
7
- }
8
- if (typeof val === 'number' || (!/\D/.test(val.toString()) && val.length <= 10)) {
9
- return 'property_int';
10
- }
11
- }
12
- return 'property_text';
13
- }
14
-
15
- export default async function setSettings({
16
- pg, funcs, key, val,
17
- }) {
18
- try {
19
- const columnType = checkValueType(val);
20
- const data = { property_key: key, [columnType]: val };
21
-
22
- await pg.query('delete from setting.property where property_key=$1', [key]);
23
- const { rows } = await funcs.dataInsert({ pg, table, data });
24
- return { key, val, data: rows };
25
- }
26
- catch (err) {
27
- return { error: err.toString(), status: 500 };
28
- }
29
- }
package/settings/index.js DELETED
@@ -1,22 +0,0 @@
1
- import getSettingsAPI from './controllers/settings.get.js';
2
- import postSettingsAPI from './controllers/settings.post.js';
3
- import getSettingsFunc from './funcs/getSettings.js';
4
- import setSettingsFunc from './funcs/setSettings.js';
5
-
6
- async function plugin(fastify, config = { }) {
7
- const prefix = config.prefix || '/api';
8
- fastify.decorate('getSettings', getSettingsFunc);
9
- fastify.decorate('setSettings', setSettingsFunc);
10
- fastify.get(`${prefix}/settings/:key?`, {}, getSettingsAPI);
11
-
12
- fastify.route({
13
- method: 'POST',
14
- path: `${prefix}/settings`,
15
- config: {
16
- policy: ['superadmin'],
17
- },
18
- handler: postSettingsAPI,
19
- });
20
- }
21
-
22
- export default plugin;