@opengis/cms 0.0.42 → 0.0.44

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 (95) hide show
  1. package/README.md +98 -98
  2. package/dist/{en-CzEziHMG.js → en-OTy187va.js} +1 -0
  3. package/dist/index.html +29 -29
  4. package/dist/index.js +6266 -15660
  5. package/dist/index.umd.cjs +75 -77
  6. package/dist/{uk-TyVZmyOZ.js → uk-Dy2psXBp.js} +1 -0
  7. package/input-types.json +10 -0
  8. package/module/cms/cls/content.status.json +17 -17
  9. package/module/cms/cls/user_type.json +9 -9
  10. package/module/cms/form/admin.users.form.json +77 -77
  11. package/module/cms/select/cms.page_type.sql +1 -1
  12. package/module/cms/select/news_tag_id.sql +11 -11
  13. package/module/cms/table/admin.users.table.json +53 -53
  14. package/module/cms/table/collection.default.table.json +96 -96
  15. package/module/cms/table/single.default.table.json +116 -114
  16. package/package.json +65 -71
  17. package/plugin.js +43 -76
  18. package/server/app.js +35 -35
  19. package/server/config.js +4 -4
  20. package/server/functions/getDraftKey.js +22 -22
  21. package/server/index.js +22 -22
  22. package/server/migrations/fixes.sql +124 -124
  23. package/server/migrations/site.sql +595 -595
  24. package/server/plugins/adminHook.js +78 -78
  25. package/server/plugins/hook.js +59 -59
  26. package/server/plugins/vite.js +75 -75
  27. package/server/routes/category/controllers/cms.category.delete.js +21 -21
  28. package/server/routes/category/controllers/cms.category.get.js +17 -17
  29. package/server/routes/category/controllers/cms.category.list.js +16 -16
  30. package/server/routes/category/controllers/cms.category.post.js +21 -21
  31. package/server/routes/category/controllers/cms.category.put.js +23 -23
  32. package/server/routes/category/index.mjs +22 -22
  33. package/server/routes/cms/controllers/cmsStat.js +55 -55
  34. package/server/routes/cms/controllers/cmsSuggest.js +57 -57
  35. package/server/routes/cms/controllers/deleteContent.js +113 -113
  36. package/server/routes/cms/controllers/getContent.js +110 -110
  37. package/server/routes/cms/controllers/getContentBySlug.js +93 -95
  38. package/server/routes/cms/controllers/getPermissions.js +15 -15
  39. package/server/routes/cms/controllers/insertContent.js +217 -218
  40. package/server/routes/cms/controllers/properties.get.js +53 -53
  41. package/server/routes/cms/controllers/properties.post.js +99 -99
  42. package/server/routes/cms/controllers/searchContent.js +205 -205
  43. package/server/routes/cms/controllers/setPermissions.js +49 -49
  44. package/server/routes/cms/controllers/translate.js +89 -89
  45. package/server/routes/cms/controllers/updateContent.js +238 -240
  46. package/server/routes/cms/index.mjs +112 -114
  47. package/server/routes/cms/utils/additionalData.js +35 -35
  48. package/server/routes/cms/utils/getCollection.js +82 -82
  49. package/server/routes/cms/utils/getSingle.js +187 -189
  50. package/server/routes/cms/utils/inputTypes.js +6 -0
  51. package/server/routes/cms/utils/insertContentLocalization.js +86 -86
  52. package/server/routes/cms/utils/requestTranslation.js +85 -85
  53. package/server/routes/cms/utils/updateLocalization.js +47 -47
  54. package/server/routes/cmsSpace/controllers/deleteSpace.js +25 -25
  55. package/server/routes/cmsSpace/controllers/getSpaces.js +27 -27
  56. package/server/routes/cmsSpace/controllers/insertSpace.js +21 -21
  57. package/server/routes/cmsSpace/controllers/updateSpace.js +23 -23
  58. package/server/routes/cmsSpace/index.mjs +20 -20
  59. package/server/routes/contentType/controllers/addContentType.js +162 -162
  60. package/server/routes/contentType/controllers/contentTypeList.js +54 -54
  61. package/server/routes/contentType/controllers/delContentType.js +75 -75
  62. package/server/routes/contentType/controllers/editContentType.js +61 -61
  63. package/server/routes/contentType/controllers/getContentType.js +37 -37
  64. package/server/routes/contentType/index.mjs +35 -35
  65. package/server/routes/contentType/utils/updateContents.js +28 -28
  66. package/server/routes/contentType/utils/updateCustomContentTable.js +53 -55
  67. package/server/routes/feedback/controllers/email.list.js +24 -24
  68. package/server/routes/feedback/controllers/feedback.js +48 -48
  69. package/server/routes/feedback/controllers/feedback.list.js +37 -37
  70. package/server/routes/feedback/controllers/news.subscriptions.js +44 -44
  71. package/server/routes/feedback/index.mjs +71 -71
  72. package/server/routes/logs/controllers/export.user.logs.js +77 -77
  73. package/server/routes/logs/controllers/user.logs.js +44 -44
  74. package/server/routes/logs/index.mjs +9 -9
  75. package/server/routes/menu/controllers/addMenu.js +37 -37
  76. package/server/routes/menu/controllers/delMenu.js +31 -31
  77. package/server/routes/menu/controllers/editMenu.js +41 -41
  78. package/server/routes/menu/controllers/getMenu.js +42 -42
  79. package/server/routes/menu/index.mjs +13 -13
  80. package/server/routes/migration/controllers/collectionToCustom.js +137 -137
  81. package/server/routes/migration/index.mjs +8 -8
  82. package/server/routes/root.mjs +8 -8
  83. package/server/routes/tags/controllers/add.tags.js +24 -24
  84. package/server/routes/tags/controllers/del.tags.js +19 -19
  85. package/server/routes/tags/controllers/edit.tags.js +25 -25
  86. package/server/routes/tags/controllers/get.tags.js +15 -15
  87. package/server/routes/tags/index.mjs +14 -14
  88. package/server/templates/cls/cms.category_type.json +9 -9
  89. package/server/templates/cls/cms.content_review_status.json +9 -9
  90. package/server/templates/cls/cms.content_status.json +9 -9
  91. package/server/templates/cls/cms.content_type.json +9 -9
  92. package/server/templates/cls/cms.lang.json +9 -9
  93. package/server/templates/page/login.html +126 -126
  94. package/server/templates/select/core.user_mentioned.sql +1 -1
  95. package/dist/index-W-qQIppj-DRzFSjU1.js +0 -2452
@@ -1,190 +1,188 @@
1
- import path from 'node:path';
2
- import { existsSync, readFileSync } from 'node:fs';
3
-
4
- import { pgClients, metaFormat, getFilterSQL, getFilter, getMeta } from '@opengis/fastify-table/utils.js';
5
-
6
- const inputTypes = existsSync('input-types.json') ? JSON.parse(readFileSync('input-types.json') || '{}') : {};
7
-
8
- import additionalData from "./additionalData.js";
9
-
10
- export default async function getSingle({
11
- contentId: contentId1, id: id1, limit: queryLimit, maxLimit, search, filter, locale, statusQuery, user, sql, page, defaultColumns = [], fields, defaultFields = [], defaultFilters = [],
12
- }, pg = pgClients.client) {
13
- const id = id1 || (contentId1 === 'pages' ? undefined : contentId1) || '';
14
- const contentId = id1 ? contentId1 : "pages";
15
-
16
- // defaultColumns.push({
17
- // "name": "content_type_id",
18
- // "label": "Тип сторінки",
19
- // "type": "select",
20
- // "data": "cms.page_type"
21
- // });
22
-
23
- const customColumns = await pg.query(`
24
- SELECT columns FROM site.content_types WHERE content_type_id in (select content_type_id from site.contents where content_id=$1) limit 1
25
- `, [id1 || contentId]).then(el => el.rows?.[0]?.columns || []);
26
-
27
- const contentQuery = contentId === 'pages' || !id
28
- ? `(type = 'single' or content_type_id = 'pages')`
29
- : 'content_type_id=(select content_type_id from site.contents where content_id=$2)';
30
-
31
- const columns = defaultColumns.concat(customColumns.filter(col => defaultColumns.findIndex(el => el.name === col.name) === -1));
32
-
33
- columns.filter(el => el.default).forEach(col => {
34
- const { name, localization } = customColumns.find(item => item.name === col.name) || {};
35
- if (name) {
36
- Object.assign(col, { localization });
37
- }
38
- });
39
-
40
- const limit = Math.min(maxLimit, +(queryLimit || 20));
41
- const offset = page && page > 0 && !id ? (page - 1) * limit : 0;
42
-
43
- const fData = filter
44
- ? await getFilterSQL({
45
- pg,
46
- table: 'site.contents',
47
- filter,
48
- search,
49
- filterList: defaultFilters,
50
- query: `
51
- content_type_id IN (
52
- SELECT content_type_id
53
- FROM site.content_types
54
- WHERE ${contentQuery || 'true'}
55
- )
56
- `,
57
- })
58
- : {
59
- optimizedSQL: 'SELECT * FROM site.contents WHERE true',
60
- };
61
-
62
- const localeQuery = locale && locale !== 'uk' && pg.pk?.['site.contents'] ? `${pg.pk?.['site.contents']} in ( select object_id from site.localization where REVERSE( split_part( REVERSE(field_key), ':', 1) ) = '${locale.replace(/'/g, "''")}' )` : undefined;
63
-
64
- const columnList = await getMeta({
65
- pg,
66
- table: 'site.contents',
67
- }).then(el => el.columns?.map?.(col => col.name) || []);
68
- const existingFields = fields && contentId === 'pages' || !id ? defaultFields.concat((fields || '').split(',')).filter(colName => columnList.includes(colName)).concat(['content_id AS id']).join(',') : '';
69
- const extraKeys = fields ? fields.split(',').filter(key => !defaultFields.includes(key)) : [];
70
- const cols = existingFields.length ? existingFields.concat(extraKeys?.length ? `,"extraKeys"` : []) : `content_id AS id,
71
- content_id,
72
- created_by,
73
- title,
74
- slug,
75
- meta,
76
- published_by,
77
- published_at,
78
- status,
79
- content_type_id,
80
- /* content_type_id AS type, */
81
- main_image
82
- ${contentId === 'pages' || !id ? `,"extraKeys"` : ''}`;
83
-
84
- const q = `
85
- SELECT ${cols} FROM (${fData.optimizedSQL}) a
86
- ${extraKeys || id ? `LEFT JOIN LATERAL (
87
- SELECT json_agg(row_to_json(q)) AS "extraKeys"
88
- FROM (
89
- SELECT field_key, field_type, field_value, field_value_object
90
- FROM site.content_data
91
- WHERE content_id = a.content_id
92
- ) q
93
- ) b ON true` : ''}
94
-
95
- LEFT JOIN LATERAL (
96
- SELECT type FROM site.content_types WHERE content_type_id=a.content_type_id LIMIT 1
97
- )c ON true
98
-
99
- WHERE $1=$1 and $2=$2
100
- and ${statusQuery || 'true'}
101
- and ${localeQuery || '1=1'}
102
- and ${contentQuery || 'true'}
103
- and ${id ? `$2 in (slug, content_id)` : 'true'}
104
- and content_id<>'pages'
105
- order by case when status='archived' then true else false end, published_at desc nulls last
106
- LIMIT ${limit} OFFSET ${id ? 0 : offset}
107
- `;
108
-
109
- if (sql && user?.user_type?.includes?.('admin')) {
110
- return q; // Expose raw SQL for debugging
111
- }
112
-
113
- const { total = 0, filtered = 0 } = await pg.query(`
114
- SELECT COUNT(*)::int as total,
115
- count(*) FILTER(WHERE ${fData.q || "true"})::int as filtered
116
- FROM site.contents
117
- WHERE content_type_id IN (
118
- SELECT content_type_id
119
- FROM site.content_types
120
- WHERE ${localeQuery || '1=1'}
121
- and $1=$1 and $2=$2 and ${contentQuery || 'true'}
122
- )
123
- and ${statusQuery || 'true'}
124
- and content_id<>'pages'
125
- `, [contentId, id]).then(el => el.rows?.[0] || {});
126
-
127
- const { rows = [] } = await pg.query(q, [contentId, id || '']);
128
-
129
- const locales = await pg.query(`select array_agg(distinct REVERSE(split_part(REVERSE(field_key), ':', 1))) from site.localization
130
- where object_id in (select content_id from site.contents
131
- where content_type_id IN (
132
- SELECT content_type_id FROM site.content_types where $1=$1 and $2=$2 and ${contentQuery || 'true'}
133
- )
134
- and ${statusQuery || 'true'}
135
- )`, [contentId, id]
136
- ).then(el => el.rows?.[0]?.array_agg || []);
137
-
138
- // Flatten extra fields into main object
139
- const rows1 = rows.map(row => ({
140
- ...row,
141
- ...Object.fromEntries(
142
- row.extraKeys?.filter(k => extraKeys?.length ? extraKeys.includes(k.field_key) : true)?.map(k =>
143
- [k.field_key, inputTypes[k.field_type] === 'json' || k.field_key === 'meta'
144
- ? k.field_value_object
145
- : k.field_value]
146
- ) || []
147
- ),
148
- extraKeys: undefined,
149
- }));
150
-
151
- // Apply localization and tags etc.
152
- await additionalData(pg, rows1, locale, contentId === 'pages' || !id ? [existingFields, extraKeys].filter(Boolean).join(',') : null);
153
-
154
- // Apply metadata formatting
155
- await metaFormat({
156
- rows: rows1,
157
- cls: {
158
- created_by: 'core.user_mentioned',
159
- // content_type_id: 'cms.type_id',
160
- // type: 'cms.type_id',
161
- },
162
- sufix: false,
163
- }, pg);
164
-
165
- const { list: filters = [] } = await getFilter({
166
- pg, table: 'single.default.table', user, filter: `content_type_id in (select content_type_id from site.content_types where type='single' or content_type_id='pages')`
167
- }) || {};
168
-
169
- const finalColumns = !id
170
- ? columns?.map?.(col => Object.assign(col, { type: col.name === 'published_at' ? 'date' : col.type }))?.filter?.(el => !el.hidden)
171
- : columns?.filter?.(el => !el.hidden);
172
-
173
- rows1.filter(row => row.single_sections?.length).forEach(row => {
174
- row.single_sections.filter(section => section.documents?.length).forEach(section => {
175
- section.documents.filter(doc => doc.file).forEach(doc => Object.assign(doc, { file_name: path.basename(doc.file) }));
176
- });
177
- });
178
-
179
- return {
180
- locales,
181
- type: 'single',
182
- total,
183
- filtered,
184
- count: rows1.length,
185
- pk: 'id',
186
- rows: rows1,
187
- columns: finalColumns,
188
- filters,
189
- };
1
+ import path from 'node:path';
2
+
3
+ import { pgClients, metaFormat, getFilterSQL, getFilter, getMeta } from '@opengis/fastify-table/utils.js';
4
+
5
+ import inputTypes from '../utils/inputTypes.js';
6
+ import additionalData from "./additionalData.js";
7
+
8
+ export default async function getSingle({
9
+ contentId: contentId1, id: id1, limit: queryLimit, maxLimit, search, filter, locale, statusQuery, user, sql, page, defaultColumns = [], fields, defaultFields = [], defaultFilters = [],
10
+ }, pg = pgClients.client) {
11
+ const id = id1 || (contentId1 === 'pages' ? undefined : contentId1) || '';
12
+ const contentId = id1 ? contentId1 : "pages";
13
+
14
+ // defaultColumns.push({
15
+ // "name": "content_type_id",
16
+ // "label": "Тип сторінки",
17
+ // "type": "select",
18
+ // "data": "cms.page_type"
19
+ // });
20
+
21
+ const customColumns = await pg.query(`
22
+ SELECT columns FROM site.content_types WHERE content_type_id in (select content_type_id from site.contents where content_id=$1) limit 1
23
+ `, [id1 || contentId]).then(el => el.rows?.[0]?.columns || []);
24
+
25
+ const contentQuery = contentId === 'pages' || !id
26
+ ? `(type = 'single' or content_type_id = 'pages')`
27
+ : 'content_type_id=(select content_type_id from site.contents where content_id=$2)';
28
+
29
+ const columns = defaultColumns.concat(customColumns.filter(col => defaultColumns.findIndex(el => el.name === col.name) === -1));
30
+
31
+ columns.filter(el => el.default).forEach(col => {
32
+ const { name, localization } = customColumns.find(item => item.name === col.name) || {};
33
+ if (name) {
34
+ Object.assign(col, { localization });
35
+ }
36
+ });
37
+
38
+ const limit = Math.min(maxLimit, +(queryLimit || 20));
39
+ const offset = page && page > 0 && !id ? (page - 1) * limit : 0;
40
+
41
+ const fData = filter
42
+ ? await getFilterSQL({
43
+ pg,
44
+ table: 'site.contents',
45
+ filter,
46
+ search,
47
+ filterList: defaultFilters,
48
+ query: `
49
+ content_type_id IN (
50
+ SELECT content_type_id
51
+ FROM site.content_types
52
+ WHERE ${contentQuery || 'true'}
53
+ )
54
+ `,
55
+ })
56
+ : {
57
+ optimizedSQL: 'SELECT * FROM site.contents WHERE true',
58
+ };
59
+
60
+ const localeQuery = locale && locale !== 'uk' && pg.pk?.['site.contents'] ? `${pg.pk?.['site.contents']} in ( select object_id from site.localization where REVERSE( split_part( REVERSE(field_key), ':', 1) ) = '${locale.replace(/'/g, "''")}' )` : undefined;
61
+
62
+ const columnList = await getMeta({
63
+ pg,
64
+ table: 'site.contents',
65
+ }).then(el => el.columns?.map?.(col => col.name) || []);
66
+ const existingFields = fields && contentId === 'pages' || !id ? defaultFields.concat((fields || '').split(',')).filter(colName => columnList.includes(colName)).concat(['content_id AS id']).join(',') : '';
67
+ const extraKeys = fields ? fields.split(',').filter(key => !defaultFields.includes(key)) : [];
68
+ const cols = existingFields.length ? existingFields.concat(extraKeys?.length ? `,"extraKeys"` : []) : `content_id AS id,
69
+ content_id,
70
+ created_by,
71
+ title,
72
+ slug,
73
+ meta,
74
+ published_by,
75
+ published_at,
76
+ status,
77
+ content_type_id,
78
+ /* content_type_id AS type, */
79
+ main_image
80
+ ${contentId === 'pages' || !id ? `,"extraKeys"` : ''}`;
81
+
82
+ const q = `
83
+ SELECT ${cols} FROM (${fData.optimizedSQL}) a
84
+ ${extraKeys || id ? `LEFT JOIN LATERAL (
85
+ SELECT json_agg(row_to_json(q)) AS "extraKeys"
86
+ FROM (
87
+ SELECT field_key, field_type, field_value, field_value_object
88
+ FROM site.content_data
89
+ WHERE content_id = a.content_id
90
+ ) q
91
+ ) b ON true` : ''}
92
+
93
+ LEFT JOIN LATERAL (
94
+ SELECT type FROM site.content_types WHERE content_type_id=a.content_type_id LIMIT 1
95
+ )c ON true
96
+
97
+ WHERE $1=$1 and $2=$2
98
+ and ${statusQuery || 'true'}
99
+ and ${localeQuery || '1=1'}
100
+ and ${contentQuery || 'true'}
101
+ and ${id ? `$2 in (slug, content_id)` : 'true'}
102
+ and content_id<>'pages'
103
+ order by case when status='archived' then true else false end, published_at desc nulls last
104
+ LIMIT ${limit} OFFSET ${id ? 0 : offset}
105
+ `;
106
+
107
+ if (sql && user?.user_type?.includes?.('admin')) {
108
+ return q; // Expose raw SQL for debugging
109
+ }
110
+
111
+ const { total = 0, filtered = 0 } = await pg.query(`
112
+ SELECT COUNT(*)::int as total,
113
+ count(*) FILTER(WHERE ${fData.q || "true"})::int as filtered
114
+ FROM site.contents
115
+ WHERE content_type_id IN (
116
+ SELECT content_type_id
117
+ FROM site.content_types
118
+ WHERE ${localeQuery || '1=1'}
119
+ and $1=$1 and $2=$2 and ${contentQuery || 'true'}
120
+ )
121
+ and ${statusQuery || 'true'}
122
+ and content_id<>'pages'
123
+ `, [contentId, id]).then(el => el.rows?.[0] || {});
124
+
125
+ const { rows = [] } = await pg.query(q, [contentId, id || '']);
126
+
127
+ const locales = await pg.query(`select array_agg(distinct REVERSE(split_part(REVERSE(field_key), ':', 1))) from site.localization
128
+ where object_id in (select content_id from site.contents
129
+ where content_type_id IN (
130
+ SELECT content_type_id FROM site.content_types where $1=$1 and $2=$2 and ${contentQuery || 'true'}
131
+ )
132
+ and ${statusQuery || 'true'}
133
+ )`, [contentId, id]
134
+ ).then(el => el.rows?.[0]?.array_agg || []);
135
+
136
+ // Flatten extra fields into main object
137
+ const rows1 = rows.map(row => ({
138
+ ...row,
139
+ ...Object.fromEntries(
140
+ row.extraKeys?.filter(k => extraKeys?.length ? extraKeys.includes(k.field_key) : true)?.map(k =>
141
+ [k.field_key, inputTypes[k.field_type] === 'json' || k.field_key === 'meta'
142
+ ? k.field_value_object
143
+ : k.field_value]
144
+ ) || []
145
+ ),
146
+ extraKeys: undefined,
147
+ }));
148
+
149
+ // Apply localization and tags etc.
150
+ await additionalData(pg, rows1, locale, contentId === 'pages' || !id ? [existingFields, extraKeys].filter(Boolean).join(',') : null);
151
+
152
+ // Apply metadata formatting
153
+ await metaFormat({
154
+ rows: rows1,
155
+ cls: {
156
+ created_by: 'core.user_mentioned',
157
+ // content_type_id: 'cms.type_id',
158
+ // type: 'cms.type_id',
159
+ },
160
+ sufix: false,
161
+ }, pg);
162
+
163
+ const { list: filters = [] } = await getFilter({
164
+ pg, table: 'single.default.table', user, filter: `content_type_id in (select content_type_id from site.content_types where type='single' or content_type_id='pages')`
165
+ }) || {};
166
+
167
+ const finalColumns = !id
168
+ ? columns?.map?.(col => Object.assign(col, { type: col.name === 'published_at' ? 'date' : col.type }))?.filter?.(el => !el.hidden)
169
+ : columns?.filter?.(el => !el.hidden);
170
+
171
+ rows1.filter(row => row.single_sections?.length).forEach(row => {
172
+ row.single_sections.filter(section => section.documents?.length).forEach(section => {
173
+ section.documents.filter(doc => doc.file).forEach(doc => Object.assign(doc, { file_name: path.basename(doc.file) }));
174
+ });
175
+ });
176
+
177
+ return {
178
+ locales,
179
+ type: 'single',
180
+ total,
181
+ filtered,
182
+ count: rows1.length,
183
+ pk: 'id',
184
+ rows: rows1,
185
+ columns: finalColumns,
186
+ filters,
187
+ };
190
188
  }
@@ -0,0 +1,6 @@
1
+ import path from 'node:path';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+
4
+ const inputTypes = ['input-types.json', path.join('node_modules/@opengis/cms', 'input-types.json')].filter(filepath => existsSync(filepath)).reduce((acc, curr) => ({ ...acc, ...JSON.parse(readFileSync(curr) || '{}') }), {});
5
+
6
+ export default inputTypes
@@ -1,87 +1,87 @@
1
- import { dataInsert, pgClients } from "@opengis/fastify-table/utils.js";
2
-
3
- import requestTranslation from "./requestTranslation.js";
4
-
5
- export default async function insertContentLocalization({ send = () => { }, table, id, from, to, nocache, schemaKeys, user }, pg = pgClients.client) {
6
- if (!to) {
7
- const resp = { error: 'not enough query params: to', code: 400 };
8
- send(resp.error + ': ' + id);
9
- return resp;
10
- }
11
-
12
- const row = await pg.query(`select * ${table ? '' : ',content_id as id'} from ${table ? `data."${table}"` : 'site.contents'} where $1 in (id,slug)`, [id]).then(el => el.rows?.[0]);
13
-
14
- if (!row) {
15
- const resp = { error: 'content not found', code: 404 };
16
- send(resp.error + ': ' + id);
17
- return resp;
18
- }
19
-
20
- const localizationExists = await pg.query('select 1 from site.localization where object_id=$1 and field_key is not null and split_part(field_key,\':\',2)=$2', [row.id, to])
21
- .then(el => el.rowCount);
22
-
23
- if (localizationExists && !nocache) {
24
- const resp = { error: 'target localization already exists', code: 400 };
25
- send(resp.error + ': ' + id);
26
- return resp;
27
- }
28
-
29
- const localization = await pg.query('select json_object_agg(split_part(field_key,\':\',2),field_value) from site.localization where object_id=$1 and field_key is not null and split_part(field_key,\':\',2)=$2', [row.id, from])
30
- .then(el => el.rows?.[0]?.json_object_agg || {});
31
-
32
- if (!row) {
33
- const resp = { error: 'content not found', code: 404 };
34
- send(resp.error + ': ' + id);
35
- return resp;
36
- }
37
-
38
- const obj = { ...row, ...localization };
39
-
40
- const entries = Object.entries(obj).filter(([key, value]) => value && schemaKeys.includes(key) && (typeof value === 'string' || (Array.isArray(value) && value?.[0] && typeof value?.[0] === 'object' && Object.keys(value).length)));
41
- const skipped = schemaKeys.filter(key => !entries.map(([el]) => el).includes(key));
42
-
43
- const { result, error, code = 200 } = await requestTranslation(entries, from, to);
44
-
45
- if (error && code) {
46
- send(error + ': ' + id);
47
- return { error, code };
48
- }
49
-
50
- const arr = Object.keys(result).reduce((acc, curr) => {
51
- acc.push({
52
- field_key: curr,
53
- field_value: result[curr],
54
- object_id: id,
55
- });
56
- return acc;
57
- }, []);
58
-
59
- const client = await pg.connect();
60
-
61
- try {
62
- await client.query('begin');
63
-
64
- if (nocache) {
65
- const deleted = await client.query('delete from site.localization where object_id=$1 and split_part(field_key,\':\',2)=$2', [id, to]).then(el => el.rowCount || 0);
66
- send(`deleted existing localizations: ${deleted}, ${id}`);
67
- console.log('deleted existing localizations: ', deleted, id);
68
- }
69
-
70
- await Promise.all(arr.map(async row => dataInsert({
71
- pg: client,
72
- table: 'site.localization',
73
- data: row,
74
- uid: user?.uid,
75
- })));
76
- await client.query('commit');
77
-
78
- send(`translation success: ${table}/${id}`);
79
- return { table, id: row.id, keys: schemaKeys, skipped, to };
80
- } catch (err) {
81
- await client.query('rollback');
82
- send(`translation error: ${err.toString()} (${id})`);
83
- return { error: err.toString(), code: 500 };
84
- } finally {
85
- client.release();
86
- }
1
+ import { dataInsert, pgClients } from "@opengis/fastify-table/utils.js";
2
+
3
+ import requestTranslation from "./requestTranslation.js";
4
+
5
+ export default async function insertContentLocalization({ send = () => { }, table, id, from, to, nocache, schemaKeys, user }, pg = pgClients.client) {
6
+ if (!to) {
7
+ const resp = { error: 'not enough query params: to', code: 400 };
8
+ send(resp.error + ': ' + id);
9
+ return resp;
10
+ }
11
+
12
+ const row = await pg.query(`select * ${table ? '' : ',content_id as id'} from ${table ? `data."${table}"` : 'site.contents'} where $1 in (id,slug)`, [id]).then(el => el.rows?.[0]);
13
+
14
+ if (!row) {
15
+ const resp = { error: 'content not found', code: 404 };
16
+ send(resp.error + ': ' + id);
17
+ return resp;
18
+ }
19
+
20
+ const localizationExists = await pg.query('select 1 from site.localization where object_id=$1 and field_key is not null and split_part(field_key,\':\',2)=$2', [row.id, to])
21
+ .then(el => el.rowCount);
22
+
23
+ if (localizationExists && !nocache) {
24
+ const resp = { error: 'target localization already exists', code: 400 };
25
+ send(resp.error + ': ' + id);
26
+ return resp;
27
+ }
28
+
29
+ const localization = await pg.query('select json_object_agg(split_part(field_key,\':\',2),field_value) from site.localization where object_id=$1 and field_key is not null and split_part(field_key,\':\',2)=$2', [row.id, from])
30
+ .then(el => el.rows?.[0]?.json_object_agg || {});
31
+
32
+ if (!row) {
33
+ const resp = { error: 'content not found', code: 404 };
34
+ send(resp.error + ': ' + id);
35
+ return resp;
36
+ }
37
+
38
+ const obj = { ...row, ...localization };
39
+
40
+ const entries = Object.entries(obj).filter(([key, value]) => value && schemaKeys.includes(key) && (typeof value === 'string' || (Array.isArray(value) && value?.[0] && typeof value?.[0] === 'object' && Object.keys(value).length)));
41
+ const skipped = schemaKeys.filter(key => !entries.map(([el]) => el).includes(key));
42
+
43
+ const { result, error, code = 200 } = await requestTranslation(entries, from, to);
44
+
45
+ if (error && code) {
46
+ send(error + ': ' + id);
47
+ return { error, code };
48
+ }
49
+
50
+ const arr = Object.keys(result).reduce((acc, curr) => {
51
+ acc.push({
52
+ field_key: curr,
53
+ field_value: result[curr],
54
+ object_id: id,
55
+ });
56
+ return acc;
57
+ }, []);
58
+
59
+ const client = await pg.connect();
60
+
61
+ try {
62
+ await client.query('begin');
63
+
64
+ if (nocache) {
65
+ const deleted = await client.query('delete from site.localization where object_id=$1 and split_part(field_key,\':\',2)=$2', [id, to]).then(el => el.rowCount || 0);
66
+ send(`deleted existing localizations: ${deleted}, ${id}`);
67
+ console.log('deleted existing localizations: ', deleted, id);
68
+ }
69
+
70
+ await Promise.all(arr.map(async row => dataInsert({
71
+ pg: client,
72
+ table: 'site.localization',
73
+ data: row,
74
+ uid: user?.uid,
75
+ })));
76
+ await client.query('commit');
77
+
78
+ send(`translation success: ${table}/${id}`);
79
+ return { table, id: row.id, keys: schemaKeys, skipped, to };
80
+ } catch (err) {
81
+ await client.query('rollback');
82
+ send(`translation error: ${err.toString()} (${id})`);
83
+ return { error: err.toString(), code: 500 };
84
+ } finally {
85
+ client.release();
86
+ }
87
87
  }