@opengis/cms 0.0.44 → 0.0.45

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 (99) hide show
  1. package/README.md +98 -98
  2. package/dist/{en-OTy187va.js → en-sWmaB9uu.js} +3 -1
  3. package/dist/index.html +29 -29
  4. package/dist/index.js +4208 -4125
  5. package/dist/index.umd.cjs +70 -65
  6. package/dist/{uk-Dy2psXBp.js → uk-rH4IPxG5.js} +4 -2
  7. package/input-types.json +9 -9
  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 -116
  16. package/package.json +3 -3
  17. package/plugin.js +43 -43
  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/deleteMedia.js +76 -76
  37. package/server/routes/cms/controllers/downloadMedia.js +84 -49
  38. package/server/routes/cms/controllers/getContent.js +110 -110
  39. package/server/routes/cms/controllers/getContentBySlug.js +93 -93
  40. package/server/routes/cms/controllers/getPermissions.js +15 -15
  41. package/server/routes/cms/controllers/insertContent.js +217 -217
  42. package/server/routes/cms/controllers/listMedia.js +108 -94
  43. package/server/routes/cms/controllers/metadataMedia.js +39 -39
  44. package/server/routes/cms/controllers/properties.get.js +53 -53
  45. package/server/routes/cms/controllers/properties.post.js +99 -99
  46. package/server/routes/cms/controllers/searchContent.js +205 -205
  47. package/server/routes/cms/controllers/setPermissions.js +49 -49
  48. package/server/routes/cms/controllers/translate.js +89 -89
  49. package/server/routes/cms/controllers/updateContent.js +238 -238
  50. package/server/routes/cms/controllers/uploadMedia.js +79 -79
  51. package/server/routes/cms/index.mjs +112 -112
  52. package/server/routes/cms/utils/additionalData.js +35 -35
  53. package/server/routes/cms/utils/getCollection.js +82 -82
  54. package/server/routes/cms/utils/getSingle.js +187 -187
  55. package/server/routes/cms/utils/inputTypes.js +5 -5
  56. package/server/routes/cms/utils/insertContentLocalization.js +86 -86
  57. package/server/routes/cms/utils/requestTranslation.js +85 -85
  58. package/server/routes/cms/utils/updateLocalization.js +47 -47
  59. package/server/routes/cmsSpace/controllers/deleteSpace.js +25 -25
  60. package/server/routes/cmsSpace/controllers/getSpaces.js +27 -27
  61. package/server/routes/cmsSpace/controllers/insertSpace.js +21 -21
  62. package/server/routes/cmsSpace/controllers/updateSpace.js +23 -23
  63. package/server/routes/cmsSpace/index.mjs +20 -20
  64. package/server/routes/contentType/controllers/addContentType.js +162 -162
  65. package/server/routes/contentType/controllers/contentTypeList.js +54 -54
  66. package/server/routes/contentType/controllers/delContentType.js +75 -75
  67. package/server/routes/contentType/controllers/editContentType.js +61 -61
  68. package/server/routes/contentType/controllers/getContentType.js +37 -37
  69. package/server/routes/contentType/index.mjs +35 -35
  70. package/server/routes/contentType/utils/updateContents.js +28 -28
  71. package/server/routes/contentType/utils/updateCustomContentTable.js +53 -53
  72. package/server/routes/feedback/controllers/email.list.js +24 -24
  73. package/server/routes/feedback/controllers/feedback.js +48 -48
  74. package/server/routes/feedback/controllers/feedback.list.js +37 -37
  75. package/server/routes/feedback/controllers/news.subscriptions.js +44 -44
  76. package/server/routes/feedback/index.mjs +71 -71
  77. package/server/routes/logs/controllers/export.user.logs.js +77 -77
  78. package/server/routes/logs/controllers/user.logs.js +44 -44
  79. package/server/routes/logs/index.mjs +9 -9
  80. package/server/routes/menu/controllers/addMenu.js +37 -37
  81. package/server/routes/menu/controllers/delMenu.js +31 -31
  82. package/server/routes/menu/controllers/editMenu.js +41 -41
  83. package/server/routes/menu/controllers/getMenu.js +42 -42
  84. package/server/routes/menu/index.mjs +13 -13
  85. package/server/routes/migration/controllers/collectionToCustom.js +137 -137
  86. package/server/routes/migration/index.mjs +8 -8
  87. package/server/routes/root.mjs +8 -8
  88. package/server/routes/tags/controllers/add.tags.js +24 -24
  89. package/server/routes/tags/controllers/del.tags.js +19 -19
  90. package/server/routes/tags/controllers/edit.tags.js +25 -25
  91. package/server/routes/tags/controllers/get.tags.js +15 -15
  92. package/server/routes/tags/index.mjs +14 -14
  93. package/server/templates/cls/cms.category_type.json +9 -9
  94. package/server/templates/cls/cms.content_review_status.json +9 -9
  95. package/server/templates/cls/cms.content_status.json +9 -9
  96. package/server/templates/cls/cms.content_type.json +9 -9
  97. package/server/templates/cls/cms.lang.json +9 -9
  98. package/server/templates/page/login.html +126 -126
  99. package/server/templates/select/core.user_mentioned.sql +1 -1
@@ -1,188 +1,188 @@
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
- };
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
+ };
188
188
  }
@@ -1,6 +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
-
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
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
  }