@opengis/cms 0.0.62 → 0.0.63

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 (124) hide show
  1. package/README.md +131 -131
  2. package/dist/{ArticlesPage-CFjE_cw_.js → ArticlesPage-BjYzvTWM.js} +3 -3
  3. package/dist/{CollectionsBreadcrumb-BCxeRikP.js → CollectionsBreadcrumb-HePNJb-d.js} +1 -1
  4. package/dist/CollectionsBreadcrumb.vue_vue_type_script_setup_true_lang-BJh-tjam.js +53 -0
  5. package/dist/{Dashboard-C1eGscNd.js → Dashboard-CXkg_pk8.js} +132 -132
  6. package/dist/{EditCollectionPage-C4uNmBJf.js → EditCollectionPage-BGZCMcQS.js} +3 -3
  7. package/dist/{MenuAddPage-D-p3gFgm.js → MenuAddPage-QTnwCoGh.js} +1 -1
  8. package/dist/{MenuBody-rN5j4YBu.js → MenuBody-Bi0ONVZf.js} +2 -2
  9. package/dist/{MenuItemPage-BoJw885D.js → MenuItemPage-B7Y9KFyb.js} +3 -3
  10. package/dist/{MenuList-DFEBS0NB.js → MenuList-BLIpeqSd.js} +53 -53
  11. package/dist/{MenuPage-BCZB_S8j.js → MenuPage-3W6jZ15H.js} +1 -1
  12. package/dist/{MenuWrapper-AZ_8s-zd.js → MenuWrapper-OrOv6sOb.js} +1 -1
  13. package/dist/{MonacoEditor-Db-3Jc3E.js → MonacoEditor-ByPT8pnv.js} +1 -1
  14. package/dist/MonacoEditor.vue_vue_type_script_setup_true_lang-C8cip9Ci.js +84 -0
  15. package/dist/{UniversalTable-CzqPG-tY.js → UniversalTable-GBd_pStq.js} +80 -80
  16. package/dist/{UniversalTablePagination-4gL47A7I.js → UniversalTablePagination-Dw2hc0nc.js} +46 -46
  17. package/dist/{contentForm-CcFbUeal.js → contentForm-NmskI6Ye.js} +2 -2
  18. package/dist/index.js +5 -5
  19. package/dist/{vs-builder-monaco-B3Jj0V31.js → vs-builder-monaco-Cw-f19gc.js} +1 -1
  20. package/dist/{vs-builder-preview-DL3RYMp7.js → vs-builder-preview-l5KhqlrF.js} +1 -1
  21. package/dist/{vs-form-reference-list-Dtv8fJJU.js → vs-form-reference-list-hZufPxfE.js} +696 -353
  22. package/input-types.json +9 -9
  23. package/locales/en.json +823 -815
  24. package/locales/uk.json +821 -813
  25. package/module/cms/cls/content.status.json +17 -17
  26. package/module/cms/cls/user_type.json +9 -9
  27. package/module/cms/form/admin.users.form.json +77 -77
  28. package/module/cms/select/cms.page_type.sql +1 -1
  29. package/module/cms/select/news_tag_id.sql +11 -11
  30. package/module/cms/table/admin.users.table.json +53 -53
  31. package/module/cms/table/collection.default.table.json +96 -96
  32. package/module/cms/table/single.default.table.json +116 -116
  33. package/package.json +69 -69
  34. package/plugin.js +43 -43
  35. package/server/app.js +35 -35
  36. package/server/config.js +4 -4
  37. package/server/functions/getContent.js +45 -45
  38. package/server/functions/getDraftKey.js +22 -22
  39. package/server/functions/getSearchData.js +31 -31
  40. package/server/functions/getTags.js +30 -30
  41. package/server/functions/getUser.js +27 -27
  42. package/server/functions/utils/mock.reply.js +55 -55
  43. package/server/index.js +22 -22
  44. package/server/migrations/fixes.sql +132 -132
  45. package/server/migrations/site.sql +596 -596
  46. package/server/plugins/adminHook.js +78 -78
  47. package/server/plugins/hook.js +59 -59
  48. package/server/plugins/vite.js +75 -75
  49. package/server/routes/category/controllers/cms.category.delete.js +21 -21
  50. package/server/routes/category/controllers/cms.category.get.js +17 -17
  51. package/server/routes/category/controllers/cms.category.list.js +16 -16
  52. package/server/routes/category/controllers/cms.category.post.js +21 -21
  53. package/server/routes/category/controllers/cms.category.put.js +23 -23
  54. package/server/routes/category/index.mjs +22 -22
  55. package/server/routes/cms/controllers/cmsStat.js +55 -55
  56. package/server/routes/cms/controllers/cmsSuggest.js +57 -57
  57. package/server/routes/cms/controllers/deleteContent.js +113 -113
  58. package/server/routes/cms/controllers/downloadMedia.js +84 -84
  59. package/server/routes/cms/controllers/getContent.js +113 -113
  60. package/server/routes/cms/controllers/getContentBySlug.js +93 -93
  61. package/server/routes/cms/controllers/getPermissions.js +15 -15
  62. package/server/routes/cms/controllers/insertContent.js +226 -226
  63. package/server/routes/cms/controllers/listMedia.js +155 -155
  64. package/server/routes/cms/controllers/properties.get.js +18 -18
  65. package/server/routes/cms/controllers/properties.post.js +99 -99
  66. package/server/routes/cms/controllers/searchContent.js +214 -214
  67. package/server/routes/cms/controllers/setPermissions.js +49 -49
  68. package/server/routes/cms/controllers/translate.js +89 -89
  69. package/server/routes/cms/controllers/updateContent.js +231 -231
  70. package/server/routes/cms/functions/getSettings.js +48 -48
  71. package/server/routes/cms/index.mjs +112 -112
  72. package/server/routes/cms/utils/additionalData.js +35 -35
  73. package/server/routes/cms/utils/getCollection.js +89 -89
  74. package/server/routes/cms/utils/getSingle.js +188 -188
  75. package/server/routes/cms/utils/inputTypes.js +5 -5
  76. package/server/routes/cms/utils/insertContentLocalization.js +104 -104
  77. package/server/routes/cms/utils/requestTranslation.js +135 -135
  78. package/server/routes/cms/utils/updateLocalization.js +42 -42
  79. package/server/routes/cmsSpace/controllers/deleteSpace.js +26 -26
  80. package/server/routes/cmsSpace/controllers/getSpaces.js +28 -28
  81. package/server/routes/cmsSpace/controllers/insertSpace.js +22 -22
  82. package/server/routes/cmsSpace/controllers/updateSpace.js +24 -24
  83. package/server/routes/cmsSpace/index.mjs +20 -20
  84. package/server/routes/contentType/controllers/addContentType.js +160 -160
  85. package/server/routes/contentType/controllers/contentTypeList.js +47 -47
  86. package/server/routes/contentType/controllers/delContentType.js +75 -75
  87. package/server/routes/contentType/controllers/editContentType.js +70 -70
  88. package/server/routes/contentType/controllers/getContentType.js +57 -57
  89. package/server/routes/contentType/index.mjs +35 -35
  90. package/server/routes/contentType/utils/updateContents.js +44 -44
  91. package/server/routes/contentType/utils/updateCustomContentTable.js +53 -53
  92. package/server/routes/feedback/controllers/email.list.js +24 -24
  93. package/server/routes/feedback/controllers/feedback.js +48 -48
  94. package/server/routes/feedback/controllers/feedback.list.js +37 -37
  95. package/server/routes/feedback/controllers/news.subscriptions.js +44 -44
  96. package/server/routes/feedback/index.mjs +71 -71
  97. package/server/routes/logs/controllers/export.user.logs.js +77 -77
  98. package/server/routes/logs/controllers/user.logs.js +44 -44
  99. package/server/routes/logs/index.mjs +9 -9
  100. package/server/routes/menu/controllers/addMenu.js +37 -37
  101. package/server/routes/menu/controllers/delMenu.js +31 -31
  102. package/server/routes/menu/controllers/editMenu.js +41 -41
  103. package/server/routes/menu/controllers/getMenu.js +24 -24
  104. package/server/routes/menu/functions/getMenu.js +50 -50
  105. package/server/routes/menu/index.mjs +13 -13
  106. package/server/routes/migration/controllers/collectionToCustom.js +137 -137
  107. package/server/routes/migration/index.mjs +8 -8
  108. package/server/routes/root.mjs +8 -8
  109. package/server/routes/tags/controllers/add.tags.js +24 -24
  110. package/server/routes/tags/controllers/del.tags.js +19 -19
  111. package/server/routes/tags/controllers/edit.tags.js +25 -25
  112. package/server/routes/tags/controllers/get.tags.js +15 -15
  113. package/server/routes/tags/index.mjs +14 -14
  114. package/server/templates/cls/cms.category_type.json +9 -9
  115. package/server/templates/cls/cms.content_review_status.json +9 -9
  116. package/server/templates/cls/cms.content_status.json +9 -9
  117. package/server/templates/cls/cms.content_type.json +9 -9
  118. package/server/templates/cls/cms.lang.json +9 -9
  119. package/server/templates/page/login.html +126 -126
  120. package/server/templates/select/core.user_mentioned.sql +1 -1
  121. package/utils.d.ts +52 -52
  122. package/utils.js +8 -8
  123. package/dist/CollectionsBreadcrumb.vue_vue_type_script_setup_true_lang-umRzB5mY.js +0 -53
  124. package/dist/MonacoEditor.vue_vue_type_script_setup_true_lang-B1DrxmQX.js +0 -84
@@ -1,90 +1,90 @@
1
- import { pgClients, eventStream } from "@opengis/fastify-table/utils.js";
2
-
3
- import insertContentLocalization from "../utils/insertContentLocalization.js";
4
-
5
- const getCollectionId = async (id, pg) => pg.query(`select content_type_id as id, table_name as table, columns FROM site.content_types
6
- where $1 in (content_type_id, name)`, [id]).then(el => el.rows?.[0] || {});
7
-
8
- function sequence(arr, data, fn) {
9
- return arr.reduce((promise, id) => promise.then(() => fn({
10
- ...data, id,
11
- })), Promise.resolve());
12
- }
13
-
14
- export async function translateContent({
15
- pg = pgClients.client, query, user,
16
- }, reply) {
17
- if (!query.id) {
18
- return reply.status(400).send({ error: 'not enough query params: id', code: 400 });
19
- }
20
- if (!query.to) {
21
- return reply.status(400).send({ error: 'not enough query params: to', code: 400 });
22
- }
23
-
24
- const { id, collection = 'pages', from = 'uk', to, nocache, skip } = query;
25
- const { id: collectionId, table, columns = [] } = await getCollectionId(collection, pg);
26
-
27
- if (!collectionId) {
28
- return reply.status(404).send({ error: 'collection not found', code: 404 });
29
- }
30
-
31
- const schemaKeys = columns.filter(el => el.name && el.localization).map(el => el.name);
32
-
33
- if (!schemaKeys.length) {
34
- return reply.status(400).send({ error: 'collection does not contain any fields with localization enabled', code: 400 });
35
- }
36
-
37
- const result = await insertContentLocalization({ table, id, from, to, nocache, skip, schemaKeys, user }, pg);
38
-
39
- if (result?.error) {
40
- return reply.status(result.code).send(result);
41
- }
42
-
43
- return result;
44
- }
45
-
46
- export async function translateCollection({
47
- pg = pgClients.client, params, query, user,
48
- }, reply) {
49
- if (!query.to) {
50
- return reply.status(400).send({ error: 'not enough query params: to', code: 400 });
51
- }
52
-
53
- const { id: collectionId, table, columns = [] } = await getCollectionId(params.id, pg);
54
-
55
- if (!collectionId) {
56
- return reply.status(404).send({ error: 'collection not found', code: 404 });
57
- }
58
-
59
- const schemaKeys = columns.filter(el => el.name && el.localization).map(el => el.name);
60
-
61
- if (!schemaKeys.length) {
62
- return reply.status(400).send({ error: 'collection does not contain any fields with localization enabled', code: 400 });
63
- }
64
-
65
- const { from = 'uk', to, nocache, debug } = query;
66
-
67
- const send = eventStream(reply);
68
-
69
- send(`target localization: ${to}`);
70
- send(`skip existing: ${!nocache}`);
71
- send('localization enabled for schema keys: ' + schemaKeys.join(','));
72
-
73
- try {
74
- const ids = !table
75
- ? await pg.query(`select array_agg(content_id) from site.contents where content_type_id=$1`, [collectionId]).then(el => el.rows?.[0]?.array_agg || [])
76
- : await pg.query(`select array_agg(id) from data."${table}"`).then(el => el.rows?.[0]?.array_agg || []);
77
-
78
- const skip = await pg.query('select array_agg(object_id) from site.localization where object_id=any($1::text[]) and split_part(field_key,\':\',2)=$2', [ids, to]).then(el => el.rows?.[0]?.array_agg || []);
79
- const filteredIds = nocache ? ids : ids.filter(id => !skip.includes(id));
80
-
81
- send(`target localization already exists for ${ids.length - filteredIds.length}/${ids.length} rows`);
82
-
83
- await sequence(debug ? filteredIds.slice(0, 1) : filteredIds, { send, pg, from, to, table, nocache: true, skip, schemaKeys, user }, insertContentLocalization);
84
- return send('translation complete', true);
85
- } catch (err) {
86
- return send(err.toString(), true);
87
- }
88
- }
89
-
1
+ import { pgClients, eventStream } from "@opengis/fastify-table/utils.js";
2
+
3
+ import insertContentLocalization from "../utils/insertContentLocalization.js";
4
+
5
+ const getCollectionId = async (id, pg) => pg.query(`select content_type_id as id, table_name as table, columns FROM site.content_types
6
+ where $1 in (content_type_id, name)`, [id]).then(el => el.rows?.[0] || {});
7
+
8
+ function sequence(arr, data, fn) {
9
+ return arr.reduce((promise, id) => promise.then(() => fn({
10
+ ...data, id,
11
+ })), Promise.resolve());
12
+ }
13
+
14
+ export async function translateContent({
15
+ pg = pgClients.client, query, user,
16
+ }, reply) {
17
+ if (!query.id) {
18
+ return reply.status(400).send({ error: 'not enough query params: id', code: 400 });
19
+ }
20
+ if (!query.to) {
21
+ return reply.status(400).send({ error: 'not enough query params: to', code: 400 });
22
+ }
23
+
24
+ const { id, collection = 'pages', from = 'uk', to, nocache, skip } = query;
25
+ const { id: collectionId, table, columns = [] } = await getCollectionId(collection, pg);
26
+
27
+ if (!collectionId) {
28
+ return reply.status(404).send({ error: 'collection not found', code: 404 });
29
+ }
30
+
31
+ const schemaKeys = columns.filter(el => el.name && el.localization).map(el => el.name);
32
+
33
+ if (!schemaKeys.length) {
34
+ return reply.status(400).send({ error: 'collection does not contain any fields with localization enabled', code: 400 });
35
+ }
36
+
37
+ const result = await insertContentLocalization({ table, id, from, to, nocache, skip, schemaKeys, user }, pg);
38
+
39
+ if (result?.error) {
40
+ return reply.status(result.code).send(result);
41
+ }
42
+
43
+ return result;
44
+ }
45
+
46
+ export async function translateCollection({
47
+ pg = pgClients.client, params, query, user,
48
+ }, reply) {
49
+ if (!query.to) {
50
+ return reply.status(400).send({ error: 'not enough query params: to', code: 400 });
51
+ }
52
+
53
+ const { id: collectionId, table, columns = [] } = await getCollectionId(params.id, pg);
54
+
55
+ if (!collectionId) {
56
+ return reply.status(404).send({ error: 'collection not found', code: 404 });
57
+ }
58
+
59
+ const schemaKeys = columns.filter(el => el.name && el.localization).map(el => el.name);
60
+
61
+ if (!schemaKeys.length) {
62
+ return reply.status(400).send({ error: 'collection does not contain any fields with localization enabled', code: 400 });
63
+ }
64
+
65
+ const { from = 'uk', to, nocache, debug } = query;
66
+
67
+ const send = eventStream(reply);
68
+
69
+ send(`target localization: ${to}`);
70
+ send(`skip existing: ${!nocache}`);
71
+ send('localization enabled for schema keys: ' + schemaKeys.join(','));
72
+
73
+ try {
74
+ const ids = !table
75
+ ? await pg.query(`select array_agg(content_id) from site.contents where content_type_id=$1`, [collectionId]).then(el => el.rows?.[0]?.array_agg || [])
76
+ : await pg.query(`select array_agg(id) from data."${table}"`).then(el => el.rows?.[0]?.array_agg || []);
77
+
78
+ const skip = await pg.query('select array_agg(object_id) from site.localization where object_id=any($1::text[]) and split_part(field_key,\':\',2)=$2', [ids, to]).then(el => el.rows?.[0]?.array_agg || []);
79
+ const filteredIds = nocache ? ids : ids.filter(id => !skip.includes(id));
80
+
81
+ send(`target localization already exists for ${ids.length - filteredIds.length}/${ids.length} rows`);
82
+
83
+ await sequence(debug ? filteredIds.slice(0, 1) : filteredIds, { send, pg, from, to, table, nocache: true, skip, schemaKeys, user }, insertContentLocalization);
84
+ return send('translation complete', true);
85
+ } catch (err) {
86
+ return send(err.toString(), true);
87
+ }
88
+ }
89
+
90
90
  export default null;
@@ -1,232 +1,232 @@
1
- import { config, pgClients, dataUpdate, dataInsert, getTemplate, checkSQL, logger } from '@opengis/fastify-table/utils.js';
2
-
3
- import inputTypes from '../utils/inputTypes.js';
4
-
5
- import updateLocalization from '../utils/updateLocalization.js';
6
-
7
- const defaultColumns = [
8
- 'content_id',
9
- 'space_id',
10
- 'content_type_id',
11
- 'created_at',
12
- 'updated_at',
13
- 'published_at',
14
- 'revision',
15
- 'locale',
16
- 'status',
17
- 'slug',
18
- 'title',
19
- 'created_by',
20
- 'published_by',
21
- 'updated_by',
22
- 'meta',
23
- ];
24
-
25
- export default async function updateContent(req, reply) {
26
- const {
27
- pg = pgClients.client,
28
- params = {},
29
- user = {},
30
- body = {},
31
- headers = {},
32
- } = req;
33
-
34
- const { type, id } = params;
35
-
36
- if (!type) {
37
- return reply.status(400).send({ error: 'not enough params: type', code: 400 });
38
- }
39
-
40
- if (!id) {
41
- return reply.status(400).send({ error: 'not enough params: id', code: 400 });
42
- }
43
-
44
- if (!Object.keys(body || {}).length) {
45
- return reply.status(400).send({ error: 'empty body', code: 400 });
46
- }
47
-
48
- // order priority - custom columns -> default for pages
49
- const { ctid, ctname, dbtable, columns: contentColumns = [] } = await pg.query('select content_type_id as ctid, name as ctname, table_name as dbtable, columns from site.content_types where content_type_id in (select content_type_id from site.contents where content_id=$1) or content_type_id=$2 order by content_type_id = \'pages\'', [id, type]).then(el => el.rows?.[0] || {});
50
-
51
- const arr = pg ? await pg.query(`select array_agg(relname)::text[] from pg_class a
52
- left join pg_namespace b on a.relnamespace=b.oid
53
- where a.relam=2 and b.nspname='data'`).then(el => el.rows?.[0]?.array_agg || []) : [];
54
-
55
- if (!arr.length && type !== 'pages') {
56
- return reply.status(400).send({ error: 'empty schema: data', code: 400 });
57
- }
58
-
59
- const table = arr.find(el => el === params.type);
60
-
61
- const loadTable = type === 'pages' ? await getTemplate('table', 'single.default.table') : {};
62
- const columns = type === 'pages'
63
- ? (loadTable?.columns || []).concat((contentColumns || []).filter(col => loadTable?.columns.findIndex(el => el.name === col.name) === -1))
64
- : contentColumns;
65
-
66
- // const xss = checkXSS({ body });
67
- const sql = checkSQL({ body });
68
-
69
- if (/*xss.error ||*/ sql.error && false) {
70
- logger.file(`injection/${/*xss.error ? 'xss' : */'sql'}/cms`, {
71
- table,
72
- ...params,
73
- uid: user?.uid,
74
- ...(/*xss.error ? xss : */sql),
75
- });
76
- return reply
77
- .status(409)
78
- .send(
79
- `Дані містять заборонені ${/*xss.error ? 'xss' : */'sql'} символи. Приберіть їх та спробуйте ще раз`
80
- );
81
- }
82
-
83
- // site.content_data, includes singletone
84
- if (((!table && !dbtable) || ['single', 'pages'].includes(type)) && ctid) {
85
- const cid = await pg.query(
86
- 'select content_id from site.contents where content_type_id=$1 limit 1',
87
- [ctid],
88
- ).then(el => el.rows?.[0]?.content_id);
89
-
90
- const ctid1 = body.content_type_id || ctid;
91
-
92
- if (!cid) {
93
- return reply.status(404).send({ error: 'contents not found', code: 404 });
94
- }
95
-
96
- const columnList = columns?.map?.(el => el.name) || [];
97
- const types = columns?.reduce?.((acc, curr) => ({ ...acc, [curr.name]: curr.type || 'text' }), {}) || {};
98
- const keys = Object.keys(body || {}).filter(key => columnList.includes(key) && !defaultColumns.includes(key));
99
-
100
-
101
- if (!Object.keys(body || {}).length) {
102
- return reply.status(400).send({ error: 'invalid payload', code: 400 });
103
- }
104
-
105
- const blocks = await pg.query(`select json_object_agg(field_key,field_value) from site.content_data where content_id=$1 and field_type='reference'`, [id])
106
- .then(el => el.rows?.[0]?.json_object_agg || {});
107
-
108
- const emptyBlock = Object.keys(body).find(key => blocks[key] && (!body[key] || typeof body[key] !== 'object' || Object.keys(body[key] || {}) === 0));
109
-
110
- if (emptyBlock) {
111
- return reply.status(400).send({ error: 'access restricted: empty/invalid block ' + emptyBlock, code: 400 });
112
- }
113
-
114
- const client = await pg.connect();
115
-
116
- try {
117
- await client.query('begin');
118
-
119
- const res = {};
120
-
121
- const res1 = await dataUpdate({
122
- pg: client,
123
- table: 'site.contents',
124
- id,
125
- data: { ...body, content_type_id: ctid1 },
126
- uid: user?.uid,
127
- });
128
- Object.assign(res, res1);
129
-
130
- const objectId = (ctname === 'pages' || ['single', 'pages'].includes(type)) && id ? id : cid;
131
- await client.query(`delete from site.content_data where object_id=$1`, [objectId]);
132
- await Promise.all(keys.map(async key => dataInsert({
133
- pg: client,
134
- table: 'site.content_data',
135
- data: {
136
- field_key: key,
137
- content_id: objectId,
138
- object_id: objectId,
139
- field_type: types[key] || 'text',
140
- field_value: inputTypes[types[key] || ''] === 'json' || key === 'meta' ? undefined : body[key],
141
- field_value_object: inputTypes[types[key] || ''] === 'json' || key === 'meta' ? body[key] : undefined,
142
- },
143
- uid: user?.uid,
144
- })));
145
-
146
- // if pages allow localization, update localization
147
- const localeRes = await updateLocalization(client, id, body, type === 'pages' ? type : ctid1, user?.uid);
148
-
149
- if (Object.hasOwn(body, 'tag_list')) {
150
- await client.query('delete from site.tag_data where data_id=$1', [id]);
151
- if (body.tag_list?.length) {
152
- await Promise.all(body.tag_list.map(async tag => dataInsert({
153
- pg: client,
154
- table: 'site.tag_data',
155
- data: {
156
- tag_id: tag,
157
- data_id: id,
158
- },
159
- uid: user?.uid,
160
- })));
161
- Object.assign(res, { tag_list: body.tag_list });
162
- }
163
- }
164
-
165
- await client.query('commit');
166
-
167
- return {
168
- id, ...res || {}, ...(keys || []).reduce((acc, curr) => ({ ...acc, [curr]: body[curr] }), {}), ...(localeRes || {})
169
- };
170
- } catch (err) {
171
- await client.query('rollback');
172
- return reply.status(500).send({ error: err.toString(), code: 500 });
173
- } finally {
174
- client.release();
175
- }
176
- }
177
-
178
- if (!table && !dbtable) {
179
- return reply.status(400).send({ error: 'invalid params: type', code: 400 });
180
- }
181
-
182
- const client = await pg.connect();
183
-
184
- try {
185
- await client.query('begin');
186
-
187
- const result = await dataUpdate({
188
- pg: client,
189
- id,
190
- table: 'data.' + `"${(table || dbtable)}"`,
191
- data: body,
192
- referer: headers?.referer,
193
- uid: user?.uid,
194
- }).catch(err => {
195
- if (err.message?.includes?.('unique constraint')) {
196
- throw new Error('Порушенні унікальності: ' + err.message?.match?.(/([^"]+)/g)?.[1]);
197
- }
198
- throw err;
199
- });
200
-
201
- await updateLocalization(client, result?.id, body, ctid, user?.uid);
202
-
203
- if (Object.hasOwn(body, 'tag_list')) {
204
- await client.query('delete from site.tag_data where data_id=$1', [id]);
205
- if (body.tag_list?.length) {
206
- await Promise.all(body.tag_list.map(async tag => dataInsert({
207
- pg: client,
208
- table: 'site.tag_data',
209
- data: {
210
- tag_id: tag?.id,
211
- data_id: id,
212
- },
213
- uid: user?.uid,
214
- })));
215
- Object.assign(result, { tag_list: body.tag_list });
216
- }
217
- }
218
-
219
- await client.query('commit');
220
-
221
- if (!result?.id) {
222
- return reply.status(404).send({ error: 'content not found', code: 404 });
223
- }
224
-
225
- return reply.status(200).send(result);
226
- } catch (err) {
227
- await client.query('rollback');
228
- return reply.status(500).send({ error: err.toString(), code: 500 });
229
- } finally {
230
- client.release();
231
- }
1
+ import { config, pgClients, dataUpdate, dataInsert, getTemplate, checkSQL, logger } from '@opengis/fastify-table/utils.js';
2
+
3
+ import inputTypes from '../utils/inputTypes.js';
4
+
5
+ import updateLocalization from '../utils/updateLocalization.js';
6
+
7
+ const defaultColumns = [
8
+ 'content_id',
9
+ 'space_id',
10
+ 'content_type_id',
11
+ 'created_at',
12
+ 'updated_at',
13
+ 'published_at',
14
+ 'revision',
15
+ 'locale',
16
+ 'status',
17
+ 'slug',
18
+ 'title',
19
+ 'created_by',
20
+ 'published_by',
21
+ 'updated_by',
22
+ 'meta',
23
+ ];
24
+
25
+ export default async function updateContent(req, reply) {
26
+ const {
27
+ pg = pgClients.client,
28
+ params = {},
29
+ user = {},
30
+ body = {},
31
+ headers = {},
32
+ } = req;
33
+
34
+ const { type, id } = params;
35
+
36
+ if (!type) {
37
+ return reply.status(400).send({ error: 'not enough params: type', code: 400 });
38
+ }
39
+
40
+ if (!id) {
41
+ return reply.status(400).send({ error: 'not enough params: id', code: 400 });
42
+ }
43
+
44
+ if (!Object.keys(body || {}).length) {
45
+ return reply.status(400).send({ error: 'empty body', code: 400 });
46
+ }
47
+
48
+ // order priority - custom columns -> default for pages
49
+ const { ctid, ctname, dbtable, columns: contentColumns = [] } = await pg.query('select content_type_id as ctid, name as ctname, table_name as dbtable, columns from site.content_types where content_type_id in (select content_type_id from site.contents where content_id=$1) or content_type_id=$2 order by content_type_id = \'pages\'', [id, type]).then(el => el.rows?.[0] || {});
50
+
51
+ const arr = pg ? await pg.query(`select array_agg(relname)::text[] from pg_class a
52
+ left join pg_namespace b on a.relnamespace=b.oid
53
+ where a.relam=2 and b.nspname='data'`).then(el => el.rows?.[0]?.array_agg || []) : [];
54
+
55
+ if (!arr.length && type !== 'pages') {
56
+ return reply.status(400).send({ error: 'empty schema: data', code: 400 });
57
+ }
58
+
59
+ const table = arr.find(el => el === params.type);
60
+
61
+ const loadTable = type === 'pages' ? await getTemplate('table', 'single.default.table') : {};
62
+ const columns = type === 'pages'
63
+ ? (loadTable?.columns || []).concat((contentColumns || []).filter(col => loadTable?.columns.findIndex(el => el.name === col.name) === -1))
64
+ : contentColumns;
65
+
66
+ // const xss = checkXSS({ body });
67
+ const sql = checkSQL({ body });
68
+
69
+ if (/*xss.error ||*/ sql.error && false) {
70
+ logger.file(`injection/${/*xss.error ? 'xss' : */'sql'}/cms`, {
71
+ table,
72
+ ...params,
73
+ uid: user?.uid,
74
+ ...(/*xss.error ? xss : */sql),
75
+ });
76
+ return reply
77
+ .status(409)
78
+ .send(
79
+ `Дані містять заборонені ${/*xss.error ? 'xss' : */'sql'} символи. Приберіть їх та спробуйте ще раз`
80
+ );
81
+ }
82
+
83
+ // site.content_data, includes singletone
84
+ if (((!table && !dbtable) || ['single', 'pages'].includes(type)) && ctid) {
85
+ const cid = await pg.query(
86
+ 'select content_id from site.contents where content_type_id=$1 limit 1',
87
+ [ctid],
88
+ ).then(el => el.rows?.[0]?.content_id);
89
+
90
+ const ctid1 = body.content_type_id || ctid;
91
+
92
+ if (!cid) {
93
+ return reply.status(404).send({ error: 'contents not found', code: 404 });
94
+ }
95
+
96
+ const columnList = columns?.map?.(el => el.name) || [];
97
+ const types = columns?.reduce?.((acc, curr) => ({ ...acc, [curr.name]: curr.type || 'text' }), {}) || {};
98
+ const keys = Object.keys(body || {}).filter(key => columnList.includes(key) && !defaultColumns.includes(key));
99
+
100
+
101
+ if (!Object.keys(body || {}).length) {
102
+ return reply.status(400).send({ error: 'invalid payload', code: 400 });
103
+ }
104
+
105
+ const blocks = await pg.query(`select json_object_agg(field_key,field_value) from site.content_data where content_id=$1 and field_type='reference'`, [id])
106
+ .then(el => el.rows?.[0]?.json_object_agg || {});
107
+
108
+ const emptyBlock = Object.keys(body).find(key => blocks[key] && (!body[key] || typeof body[key] !== 'object' || Object.keys(body[key] || {}) === 0));
109
+
110
+ if (emptyBlock) {
111
+ return reply.status(400).send({ error: 'access restricted: empty/invalid block ' + emptyBlock, code: 400 });
112
+ }
113
+
114
+ const client = await pg.connect();
115
+
116
+ try {
117
+ await client.query('begin');
118
+
119
+ const res = {};
120
+
121
+ const res1 = await dataUpdate({
122
+ pg: client,
123
+ table: 'site.contents',
124
+ id,
125
+ data: { ...body, content_type_id: ctid1 },
126
+ uid: user?.uid,
127
+ });
128
+ Object.assign(res, res1);
129
+
130
+ const objectId = (ctname === 'pages' || ['single', 'pages'].includes(type)) && id ? id : cid;
131
+ await client.query(`delete from site.content_data where object_id=$1`, [objectId]);
132
+ await Promise.all(keys.map(async key => dataInsert({
133
+ pg: client,
134
+ table: 'site.content_data',
135
+ data: {
136
+ field_key: key,
137
+ content_id: objectId,
138
+ object_id: objectId,
139
+ field_type: types[key] || 'text',
140
+ field_value: inputTypes[types[key] || ''] === 'json' || key === 'meta' ? undefined : body[key],
141
+ field_value_object: inputTypes[types[key] || ''] === 'json' || key === 'meta' ? body[key] : undefined,
142
+ },
143
+ uid: user?.uid,
144
+ })));
145
+
146
+ // if pages allow localization, update localization
147
+ const localeRes = await updateLocalization(client, id, body, type === 'pages' ? type : ctid1, user?.uid);
148
+
149
+ if (Object.hasOwn(body, 'tag_list')) {
150
+ await client.query('delete from site.tag_data where data_id=$1', [id]);
151
+ if (body.tag_list?.length) {
152
+ await Promise.all(body.tag_list.map(async tag => dataInsert({
153
+ pg: client,
154
+ table: 'site.tag_data',
155
+ data: {
156
+ tag_id: tag,
157
+ data_id: id,
158
+ },
159
+ uid: user?.uid,
160
+ })));
161
+ Object.assign(res, { tag_list: body.tag_list });
162
+ }
163
+ }
164
+
165
+ await client.query('commit');
166
+
167
+ return {
168
+ id, ...res || {}, ...(keys || []).reduce((acc, curr) => ({ ...acc, [curr]: body[curr] }), {}), ...(localeRes || {})
169
+ };
170
+ } catch (err) {
171
+ await client.query('rollback');
172
+ return reply.status(500).send({ error: err.toString(), code: 500 });
173
+ } finally {
174
+ client.release();
175
+ }
176
+ }
177
+
178
+ if (!table && !dbtable) {
179
+ return reply.status(400).send({ error: 'invalid params: type', code: 400 });
180
+ }
181
+
182
+ const client = await pg.connect();
183
+
184
+ try {
185
+ await client.query('begin');
186
+
187
+ const result = await dataUpdate({
188
+ pg: client,
189
+ id,
190
+ table: 'data.' + `"${(table || dbtable)}"`,
191
+ data: body,
192
+ referer: headers?.referer,
193
+ uid: user?.uid,
194
+ }).catch(err => {
195
+ if (err.message?.includes?.('unique constraint')) {
196
+ throw new Error('Порушенні унікальності: ' + err.message?.match?.(/([^"]+)/g)?.[1]);
197
+ }
198
+ throw err;
199
+ });
200
+
201
+ await updateLocalization(client, result?.id, body, ctid, user?.uid);
202
+
203
+ if (Object.hasOwn(body, 'tag_list')) {
204
+ await client.query('delete from site.tag_data where data_id=$1', [id]);
205
+ if (body.tag_list?.length) {
206
+ await Promise.all(body.tag_list.map(async tag => dataInsert({
207
+ pg: client,
208
+ table: 'site.tag_data',
209
+ data: {
210
+ tag_id: tag?.id,
211
+ data_id: id,
212
+ },
213
+ uid: user?.uid,
214
+ })));
215
+ Object.assign(result, { tag_list: body.tag_list });
216
+ }
217
+ }
218
+
219
+ await client.query('commit');
220
+
221
+ if (!result?.id) {
222
+ return reply.status(404).send({ error: 'content not found', code: 404 });
223
+ }
224
+
225
+ return reply.status(200).send(result);
226
+ } catch (err) {
227
+ await client.query('rollback');
228
+ return reply.status(500).send({ error: err.toString(), code: 500 });
229
+ } finally {
230
+ client.release();
231
+ }
232
232
  }