@opengis/cms 0.0.26 → 0.0.28

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 (90) hide show
  1. package/README.md +98 -98
  2. package/dist/index-W-qQIppj-DunG40EG.js +2452 -0
  3. package/dist/index.html +28 -28
  4. package/dist/index.js +12683 -6702
  5. package/dist/index.umd.cjs +87 -41
  6. package/dist/style.css +1 -0
  7. package/package.json +68 -68
  8. package/plugin.js +76 -76
  9. package/server/app.js +35 -35
  10. package/server/config.js +4 -4
  11. package/server/functions/getDraftKey.js +22 -22
  12. package/server/index.js +22 -22
  13. package/server/migrations/fixes.sql +123 -123
  14. package/server/migrations/site.sql +545 -545
  15. package/server/plugins/adminHook.js +78 -78
  16. package/server/plugins/hook.js +59 -59
  17. package/server/plugins/vite.js +84 -84
  18. package/server/routes/category/controllers/cms.category.delete.js +21 -21
  19. package/server/routes/category/controllers/cms.category.get.js +17 -17
  20. package/server/routes/category/controllers/cms.category.list.js +16 -16
  21. package/server/routes/category/controllers/cms.category.post.js +21 -21
  22. package/server/routes/category/controllers/cms.category.put.js +23 -23
  23. package/server/routes/category/index.mjs +22 -22
  24. package/server/routes/cms/controllers/cmsStat.js +55 -55
  25. package/server/routes/cms/controllers/cmsSuggest.js +57 -57
  26. package/server/routes/cms/controllers/deleteContent.js +114 -114
  27. package/server/routes/cms/controllers/deleteMedia.js +75 -75
  28. package/server/routes/cms/controllers/downloadMedia.js +48 -48
  29. package/server/routes/cms/controllers/getContent.js +110 -110
  30. package/server/routes/cms/controllers/getContentBySlug.js +95 -95
  31. package/server/routes/cms/controllers/getPermissions.js +15 -15
  32. package/server/routes/cms/controllers/insertContent.js +218 -218
  33. package/server/routes/cms/controllers/listMedia.js +93 -93
  34. package/server/routes/cms/controllers/metadataMedia.js +38 -38
  35. package/server/routes/cms/controllers/properties.get.js +53 -53
  36. package/server/routes/cms/controllers/properties.post.js +99 -99
  37. package/server/routes/cms/controllers/searchContent.js +205 -205
  38. package/server/routes/cms/controllers/setPermissions.js +49 -49
  39. package/server/routes/cms/controllers/translate.js +89 -89
  40. package/server/routes/cms/controllers/updateContent.js +238 -238
  41. package/server/routes/cms/controllers/uploadMedia.js +78 -78
  42. package/server/routes/cms/index.mjs +114 -114
  43. package/server/routes/cms/utils/additionalData.js +35 -35
  44. package/server/routes/cms/utils/getCollection.js +81 -81
  45. package/server/routes/cms/utils/getSingle.js +187 -187
  46. package/server/routes/cms/utils/insertContentLocalization.js +86 -86
  47. package/server/routes/cms/utils/requestTranslation.js +85 -85
  48. package/server/routes/cms/utils/updateLocalization.js +47 -47
  49. package/server/routes/cmsSpace/controllers/deleteSpace.js +25 -25
  50. package/server/routes/cmsSpace/controllers/getSpaces.js +27 -27
  51. package/server/routes/cmsSpace/controllers/insertSpace.js +21 -21
  52. package/server/routes/cmsSpace/controllers/updateSpace.js +23 -23
  53. package/server/routes/cmsSpace/index.mjs +20 -20
  54. package/server/routes/contentType/controllers/addContentType.js +162 -162
  55. package/server/routes/contentType/controllers/contentTypeList.js +54 -54
  56. package/server/routes/contentType/controllers/delContentType.js +75 -75
  57. package/server/routes/contentType/controllers/editContentType.js +61 -61
  58. package/server/routes/contentType/controllers/getContentType.js +37 -37
  59. package/server/routes/contentType/index.mjs +35 -35
  60. package/server/routes/contentType/utils/updateContents.js +28 -28
  61. package/server/routes/contentType/utils/updateCustomContentTable.js +55 -55
  62. package/server/routes/feedback/controllers/email.list.js +24 -24
  63. package/server/routes/feedback/controllers/feedback.js +48 -48
  64. package/server/routes/feedback/controllers/feedback.list.js +37 -37
  65. package/server/routes/feedback/controllers/news.subscriptions.js +44 -44
  66. package/server/routes/feedback/index.mjs +71 -71
  67. package/server/routes/logs/controllers/export.user.logs.js +77 -77
  68. package/server/routes/logs/controllers/user.logs.js +44 -44
  69. package/server/routes/logs/index.mjs +9 -9
  70. package/server/routes/menu/controllers/addMenu.js +37 -37
  71. package/server/routes/menu/controllers/delMenu.js +31 -31
  72. package/server/routes/menu/controllers/editMenu.js +41 -41
  73. package/server/routes/menu/controllers/getMenu.js +42 -42
  74. package/server/routes/menu/index.mjs +13 -13
  75. package/server/routes/migration/controllers/collectionToCustom.js +137 -137
  76. package/server/routes/migration/index.mjs +8 -8
  77. package/server/routes/root.mjs +8 -8
  78. package/server/routes/tags/controllers/add.tags.js +24 -24
  79. package/server/routes/tags/controllers/del.tags.js +19 -19
  80. package/server/routes/tags/controllers/edit.tags.js +25 -25
  81. package/server/routes/tags/controllers/get.tags.js +15 -15
  82. package/server/routes/tags/index.mjs +14 -14
  83. package/server/templates/cls/cms.category_type.json +9 -9
  84. package/server/templates/cls/cms.content_review_status.json +9 -9
  85. package/server/templates/cls/cms.content_status.json +9 -9
  86. package/server/templates/cls/cms.content_type.json +9 -9
  87. package/server/templates/cls/cms.lang.json +9 -9
  88. package/server/templates/page/login.html +126 -126
  89. package/server/templates/select/core.user_mentioned.sql +1 -1
  90. package/dist/index-W-qQIppj-DRzFSjU1.js +0 -2452
@@ -1,188 +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
- order by case when status='archived' then true else false end, published_at desc nulls last
105
- LIMIT ${limit} OFFSET ${id ? 0 : offset}
106
- `;
107
-
108
- if (sql && user?.user_type?.includes?.('admin')) {
109
- return q; // Expose raw SQL for debugging
110
- }
111
-
112
- const { total = 0, filtered = 0 } = await pg.query(`
113
- SELECT COUNT(*)::int as total,
114
- count(*) FILTER(WHERE ${fData.q || "true"})::int as filtered
115
- FROM site.contents
116
- WHERE content_type_id IN (
117
- SELECT content_type_id
118
- FROM site.content_types
119
- WHERE ${localeQuery || '1=1'}
120
- and $1=$1 and $2=$2 and ${contentQuery || 'true'}
121
- )
122
- and ${statusQuery || 'true'}
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
- };
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
+ order by case when status='archived' then true else false end, published_at desc nulls last
105
+ LIMIT ${limit} OFFSET ${id ? 0 : offset}
106
+ `;
107
+
108
+ if (sql && user?.user_type?.includes?.('admin')) {
109
+ return q; // Expose raw SQL for debugging
110
+ }
111
+
112
+ const { total = 0, filtered = 0 } = await pg.query(`
113
+ SELECT COUNT(*)::int as total,
114
+ count(*) FILTER(WHERE ${fData.q || "true"})::int as filtered
115
+ FROM site.contents
116
+ WHERE content_type_id IN (
117
+ SELECT content_type_id
118
+ FROM site.content_types
119
+ WHERE ${localeQuery || '1=1'}
120
+ and $1=$1 and $2=$2 and ${contentQuery || 'true'}
121
+ )
122
+ and ${statusQuery || 'true'}
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
+ };
188
188
  }
@@ -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
  }