pim-import 5.0.1 → 5.0.2

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 (249) hide show
  1. package/dist/algolia/clean.js +0 -1
  2. package/dist/algolia/config.js +0 -1
  3. package/dist/algolia/downloads.js +0 -1
  4. package/dist/algolia/families.js +0 -1
  5. package/dist/algolia/inspirations.js +0 -1
  6. package/dist/algolia/models.js +0 -1
  7. package/dist/algolia/news.js +0 -1
  8. package/dist/algolia/pressRelease.js +0 -1
  9. package/dist/algolia/pressReview.js +0 -1
  10. package/dist/algolia/products.js +0 -1
  11. package/dist/algolia/projects.js +0 -1
  12. package/dist/algolia/stories.js +0 -1
  13. package/dist/algolia/subFamilies.js +0 -1
  14. package/dist/algolia/subModels.js +0 -1
  15. package/dist/browser.js +0 -1
  16. package/dist/downloads/classes/manageEntry.js +0 -1
  17. package/dist/downloads/import.js +0 -1
  18. package/dist/index.js +0 -1
  19. package/dist/libs/contentful-cda.js +0 -1
  20. package/dist/libs/contentful.js +0 -1
  21. package/dist/libs/imgix.js +0 -1
  22. package/dist/libs/logs.js +0 -1
  23. package/dist/libs/netlify.js +0 -1
  24. package/dist/libs/notifications.js +0 -1
  25. package/dist/libs/pdf.js +0 -1
  26. package/dist/libs/s3.js +0 -1
  27. package/dist/libs/sentry.js +0 -1
  28. package/dist/pim/config.js +0 -1
  29. package/dist/pim/endpoints.js +0 -1
  30. package/dist/pim/methods/bulkPublish.js +0 -1
  31. package/dist/pim/methods/catalogs.js +0 -1
  32. package/dist/pim/methods/checkTopicDraftAndPagePublished.js +0 -1
  33. package/dist/pim/methods/designers.js +0 -1
  34. package/dist/pim/methods/dictionary.js +0 -1
  35. package/dist/pim/methods/families.js +0 -1
  36. package/dist/pim/methods/latestProducts.js +0 -1
  37. package/dist/pim/methods/migrateEntryFields.js +0 -1
  38. package/dist/pim/methods/models.js +0 -1
  39. package/dist/pim/methods/pages/catalogs.js +0 -1
  40. package/dist/pim/methods/pages/families.js +0 -1
  41. package/dist/pim/methods/pages/subfamilies.js +0 -1
  42. package/dist/pim/methods/products.js +0 -1
  43. package/dist/pim/methods/subfamilies.js +0 -1
  44. package/dist/pim/methods/submodels.js +0 -1
  45. package/dist/pim/request.js +0 -1
  46. package/dist/resources/AllProducts.js +0 -1
  47. package/dist/resources/Audit.js +0 -1
  48. package/dist/resources/CatalogDetails.js +0 -1
  49. package/dist/resources/CollectionModels.js +0 -1
  50. package/dist/resources/CollectionSubFamilies.js +0 -1
  51. package/dist/resources/CollectionSubModels.js +0 -1
  52. package/dist/resources/DProductSubLine.js +0 -1
  53. package/dist/resources/FamilyDetails.js +0 -1
  54. package/dist/resources/ProductDetails.js +0 -1
  55. package/dist/resources/ProductRelation.js +0 -1
  56. package/dist/resources/cfFields.js +0 -1
  57. package/dist/types.js +0 -1
  58. package/dist/utils.js +0 -1
  59. package/package.json +7 -2
  60. package/.env.example +0 -45
  61. package/.nvmrc +0 -1
  62. package/.vscode/settings.json +0 -21
  63. package/dist/algolia/clean.js.map +0 -1
  64. package/dist/algolia/config.js.map +0 -1
  65. package/dist/algolia/downloads.js.map +0 -1
  66. package/dist/algolia/families.js.map +0 -1
  67. package/dist/algolia/inspirations.js.map +0 -1
  68. package/dist/algolia/models.js.map +0 -1
  69. package/dist/algolia/news.js.map +0 -1
  70. package/dist/algolia/pressRelease.js.map +0 -1
  71. package/dist/algolia/pressReview.js.map +0 -1
  72. package/dist/algolia/products.js.map +0 -1
  73. package/dist/algolia/projects.js.map +0 -1
  74. package/dist/algolia/stories.js.map +0 -1
  75. package/dist/algolia/subFamilies.js.map +0 -1
  76. package/dist/algolia/subModels.js.map +0 -1
  77. package/dist/browser.js.map +0 -1
  78. package/dist/downloads/classes/manageEntry.js.map +0 -1
  79. package/dist/downloads/import.js.map +0 -1
  80. package/dist/index.js.map +0 -1
  81. package/dist/libs/contentful-cda.js.map +0 -1
  82. package/dist/libs/contentful.js.map +0 -1
  83. package/dist/libs/imgix.js.map +0 -1
  84. package/dist/libs/logs.js.map +0 -1
  85. package/dist/libs/netlify.js.map +0 -1
  86. package/dist/libs/notifications.js.map +0 -1
  87. package/dist/libs/pdf.js.map +0 -1
  88. package/dist/libs/s3.js.map +0 -1
  89. package/dist/libs/sentry.js.map +0 -1
  90. package/dist/pim/config.js.map +0 -1
  91. package/dist/pim/endpoints.js.map +0 -1
  92. package/dist/pim/methods/bulkPublish.js.map +0 -1
  93. package/dist/pim/methods/catalogs.js.map +0 -1
  94. package/dist/pim/methods/checkTopicDraftAndPagePublished.js.map +0 -1
  95. package/dist/pim/methods/designers.js.map +0 -1
  96. package/dist/pim/methods/dictionary.js.map +0 -1
  97. package/dist/pim/methods/families.js.map +0 -1
  98. package/dist/pim/methods/latestProducts.js.map +0 -1
  99. package/dist/pim/methods/migrateEntryFields.js.map +0 -1
  100. package/dist/pim/methods/models.js.map +0 -1
  101. package/dist/pim/methods/pages/catalogs.js.map +0 -1
  102. package/dist/pim/methods/pages/families.js.map +0 -1
  103. package/dist/pim/methods/pages/subfamilies.js.map +0 -1
  104. package/dist/pim/methods/products.js.map +0 -1
  105. package/dist/pim/methods/subfamilies.js.map +0 -1
  106. package/dist/pim/methods/submodels.js.map +0 -1
  107. package/dist/pim/request.js.map +0 -1
  108. package/dist/resources/AllProducts.js.map +0 -1
  109. package/dist/resources/Audit.js.map +0 -1
  110. package/dist/resources/CatalogDetails.js.map +0 -1
  111. package/dist/resources/CollectionModels.js.map +0 -1
  112. package/dist/resources/CollectionSubFamilies.js.map +0 -1
  113. package/dist/resources/CollectionSubModels.js.map +0 -1
  114. package/dist/resources/DProductSubLine.js.map +0 -1
  115. package/dist/resources/FamilyDetails.js.map +0 -1
  116. package/dist/resources/ProductDetails.js.map +0 -1
  117. package/dist/resources/ProductRelation.js.map +0 -1
  118. package/dist/resources/cfFields.js.map +0 -1
  119. package/dist/types.js.map +0 -1
  120. package/dist/utils.js.map +0 -1
  121. package/docs/import-data-from-the-dictionary.md +0 -83
  122. package/docs/import-products.md +0 -61
  123. package/docs/import-taxonomies-from-the-catalog.md +0 -60
  124. package/docs/settings.md +0 -47
  125. package/jest.config.js +0 -16
  126. package/local-fn/reindex.js +0 -182
  127. package/src/algolia/clean.ts +0 -164
  128. package/src/algolia/config.ts +0 -390
  129. package/src/algolia/downloads.ts +0 -346
  130. package/src/algolia/families.ts +0 -652
  131. package/src/algolia/inspirations.ts +0 -315
  132. package/src/algolia/models.ts +0 -589
  133. package/src/algolia/news.ts +0 -258
  134. package/src/algolia/pressRelease.ts +0 -255
  135. package/src/algolia/pressReview.ts +0 -247
  136. package/src/algolia/products.ts +0 -731
  137. package/src/algolia/projects.ts +0 -339
  138. package/src/algolia/stories.ts +0 -347
  139. package/src/algolia/subFamilies.ts +0 -709
  140. package/src/algolia/subModels.ts +0 -359
  141. package/src/browser.ts +0 -122
  142. package/src/downloads/classes/manageEntry.ts +0 -99
  143. package/src/downloads/csv/legal.csv +0 -5
  144. package/src/downloads/csv/products.csv +0 -373
  145. package/src/downloads/import.ts +0 -381
  146. package/src/index.ts +0 -140
  147. package/src/libs/contentful-cda.ts +0 -543
  148. package/src/libs/contentful.ts +0 -1453
  149. package/src/libs/imgix.ts +0 -297
  150. package/src/libs/logs.ts +0 -121
  151. package/src/libs/netlify.ts +0 -37
  152. package/src/libs/notifications.ts +0 -104
  153. package/src/libs/pdf.ts +0 -107
  154. package/src/libs/s3.ts +0 -305
  155. package/src/libs/sentry.ts +0 -33
  156. package/src/pim/config.ts +0 -84
  157. package/src/pim/data/productFields.json +0 -1178
  158. package/src/pim/endpoints.ts +0 -364
  159. package/src/pim/methods/bulkPublish.ts +0 -266
  160. package/src/pim/methods/catalogs.ts +0 -586
  161. package/src/pim/methods/checkTopicDraftAndPagePublished.ts +0 -70
  162. package/src/pim/methods/designers.ts +0 -128
  163. package/src/pim/methods/dictionary.ts +0 -611
  164. package/src/pim/methods/families.ts +0 -345
  165. package/src/pim/methods/latestProducts.ts +0 -70
  166. package/src/pim/methods/migrateEntryFields.ts +0 -99
  167. package/src/pim/methods/models.ts +0 -349
  168. package/src/pim/methods/pages/catalogs.ts +0 -28
  169. package/src/pim/methods/pages/families.ts +0 -50
  170. package/src/pim/methods/pages/subfamilies.ts +0 -98
  171. package/src/pim/methods/products.ts +0 -3297
  172. package/src/pim/methods/subfamilies.ts +0 -706
  173. package/src/pim/methods/submodels.ts +0 -262
  174. package/src/pim/request.ts +0 -61
  175. package/src/resources/AllProducts.ts +0 -41
  176. package/src/resources/Audit.ts +0 -24
  177. package/src/resources/CatalogDetails.ts +0 -51
  178. package/src/resources/CollectionModels.ts +0 -42
  179. package/src/resources/CollectionSubFamilies.ts +0 -45
  180. package/src/resources/CollectionSubModels.ts +0 -36
  181. package/src/resources/DProductSubLine.ts +0 -34
  182. package/src/resources/FamilyDetails.ts +0 -31
  183. package/src/resources/ProductDetails.ts +0 -352
  184. package/src/resources/ProductRelation.ts +0 -24
  185. package/src/resources/cfFields.ts +0 -8
  186. package/src/types.ts +0 -268
  187. package/src/utils.ts +0 -553
  188. package/tsconfig.json +0 -93
  189. package/tslint.json +0 -22
  190. package/types/libs/puppeteer.d.ts +0 -17
  191. package/types/pim/methods/checkIp.d.ts +0 -1
  192. /package/{types → dist}/algolia/clean.d.ts +0 -0
  193. /package/{types → dist}/algolia/config.d.ts +0 -0
  194. /package/{types → dist}/algolia/downloads.d.ts +0 -0
  195. /package/{types → dist}/algolia/families.d.ts +0 -0
  196. /package/{types → dist}/algolia/inspirations.d.ts +0 -0
  197. /package/{types → dist}/algolia/models.d.ts +0 -0
  198. /package/{types → dist}/algolia/news.d.ts +0 -0
  199. /package/{types → dist}/algolia/pressRelease.d.ts +0 -0
  200. /package/{types → dist}/algolia/pressReview.d.ts +0 -0
  201. /package/{types → dist}/algolia/products.d.ts +0 -0
  202. /package/{types → dist}/algolia/projects.d.ts +0 -0
  203. /package/{types → dist}/algolia/stories.d.ts +0 -0
  204. /package/{types → dist}/algolia/subFamilies.d.ts +0 -0
  205. /package/{types → dist}/algolia/subModels.d.ts +0 -0
  206. /package/{types → dist}/browser.d.ts +0 -0
  207. /package/{types → dist}/downloads/classes/manageEntry.d.ts +0 -0
  208. /package/{types → dist}/downloads/import.d.ts +0 -0
  209. /package/{types → dist}/index.d.ts +0 -0
  210. /package/{types → dist}/libs/contentful-cda.d.ts +0 -0
  211. /package/{types → dist}/libs/contentful.d.ts +0 -0
  212. /package/{types → dist}/libs/imgix.d.ts +0 -0
  213. /package/{types → dist}/libs/logs.d.ts +0 -0
  214. /package/{types → dist}/libs/netlify.d.ts +0 -0
  215. /package/{types → dist}/libs/notifications.d.ts +0 -0
  216. /package/{types → dist}/libs/pdf.d.ts +0 -0
  217. /package/{types → dist}/libs/s3.d.ts +0 -0
  218. /package/{types → dist}/libs/sentry.d.ts +0 -0
  219. /package/{types → dist}/pim/config.d.ts +0 -0
  220. /package/{types → dist}/pim/endpoints.d.ts +0 -0
  221. /package/{types → dist}/pim/methods/bulkPublish.d.ts +0 -0
  222. /package/{types → dist}/pim/methods/catalogs.d.ts +0 -0
  223. /package/{types → dist}/pim/methods/checkTopicDraftAndPagePublished.d.ts +0 -0
  224. /package/{types → dist}/pim/methods/designers.d.ts +0 -0
  225. /package/{types → dist}/pim/methods/dictionary.d.ts +0 -0
  226. /package/{types → dist}/pim/methods/families.d.ts +0 -0
  227. /package/{types → dist}/pim/methods/latestProducts.d.ts +0 -0
  228. /package/{types → dist}/pim/methods/migrateEntryFields.d.ts +0 -0
  229. /package/{types → dist}/pim/methods/models.d.ts +0 -0
  230. /package/{types → dist}/pim/methods/pages/catalogs.d.ts +0 -0
  231. /package/{types → dist}/pim/methods/pages/families.d.ts +0 -0
  232. /package/{types → dist}/pim/methods/pages/subfamilies.d.ts +0 -0
  233. /package/{types → dist}/pim/methods/products.d.ts +0 -0
  234. /package/{types → dist}/pim/methods/subfamilies.d.ts +0 -0
  235. /package/{types → dist}/pim/methods/submodels.d.ts +0 -0
  236. /package/{types → dist}/pim/request.d.ts +0 -0
  237. /package/{types → dist}/resources/AllProducts.d.ts +0 -0
  238. /package/{types → dist}/resources/Audit.d.ts +0 -0
  239. /package/{types → dist}/resources/CatalogDetails.d.ts +0 -0
  240. /package/{types → dist}/resources/CollectionModels.d.ts +0 -0
  241. /package/{types → dist}/resources/CollectionSubFamilies.d.ts +0 -0
  242. /package/{types → dist}/resources/CollectionSubModels.d.ts +0 -0
  243. /package/{types → dist}/resources/DProductSubLine.d.ts +0 -0
  244. /package/{types → dist}/resources/FamilyDetails.d.ts +0 -0
  245. /package/{types → dist}/resources/ProductDetails.d.ts +0 -0
  246. /package/{types → dist}/resources/ProductRelation.d.ts +0 -0
  247. /package/{types → dist}/resources/cfFields.d.ts +0 -0
  248. /package/{types → dist}/types.d.ts +0 -0
  249. /package/{types → dist}/utils.d.ts +0 -0
@@ -1,1453 +0,0 @@
1
- import dotenv from "dotenv";
2
- import { createClient } from "contentful-management";
3
- import type {
4
- Entry,
5
- CreateEntryProps,
6
- EntryProps,
7
- } from "contentful-management/dist/typings/entities/entry";
8
- import type { QueryOptions } from "contentful-management/dist/typings/common-types";
9
- import { log } from "./logs";
10
- dotenv.config();
11
-
12
- import {
13
- Environment,
14
- Locale,
15
- CreateAssetProps,
16
- } from "contentful-management/types";
17
-
18
- import {
19
- ContentfulLocale,
20
- AvailableCatalogs,
21
- CfSys,
22
- TopicDetailsResponse,
23
- AssetPropFields,
24
- OtherFilters,
25
- WrapperImageFields,
26
- } from "../types";
27
- import {
28
- sleep,
29
- doChunk,
30
- secondBetweenTwoDate,
31
- getPimTranslations,
32
- keysToLowerCase,
33
- getAllTranslations,
34
- } from "../utils";
35
- import { getSubFamilyRelatedDetails } from "../pim/methods/subfamilies";
36
- import { removeProductObject } from "../algolia/products";
37
- import { getFileFromS3 } from "../libs/s3";
38
-
39
- export type Config = {
40
- accessToken: string;
41
- spaceId: string;
42
- environmentId: string;
43
- };
44
-
45
- export let config: Config = {} as any;
46
- export let environment: Environment;
47
- export let defaultEnvironmentLocale: Locale;
48
- export let defaultEnvironmentLocaleCode: string;
49
-
50
- export const cfLocales: ContentfulLocale[] = [
51
- "en",
52
- "en-US",
53
- "it",
54
- "es",
55
- "de",
56
- "fr",
57
- ];
58
-
59
- /**
60
- * Check configurations
61
- *
62
- * @param skipInit
63
- * @returns
64
- */
65
- export const checkConfig = (skipInit: boolean = false): boolean => {
66
- if (!skipInit) {
67
- init();
68
- }
69
- const message: string =
70
- 'You must call "init" before using any Contentful method';
71
- if (!config.accessToken) {
72
- throw new Error("accessToken not found. " + message);
73
- } else if (!config.environmentId) {
74
- throw new Error("environmentId not found. " + message);
75
- } else if (!config.spaceId) {
76
- throw new Error("spaceId not found. " + message);
77
- }
78
-
79
- return true;
80
- };
81
-
82
- /**
83
- * Init settings
84
- *
85
- * @param opts
86
- */
87
- export const init = (opts?: Config): void => {
88
- if (!opts) {
89
- opts = {
90
- accessToken: process.env.FPI_CTF_CMA_ACCESS_TOKEN!,
91
- spaceId: process.env.FPI_CTF_SPACE_ID!,
92
- environmentId: process.env.FPI_CTF_ENVIRONMENT!,
93
- };
94
- }
95
- config = { ...opts };
96
-
97
- checkConfig(true);
98
- };
99
-
100
- /**
101
- * Get configurations
102
- *
103
- * @returns
104
- */
105
- export const getConfig = (): Config => {
106
- return config;
107
- };
108
-
109
- /**
110
- * Get environment
111
- *
112
- * @returns
113
- */
114
- export const getEnvironment = async (): Promise<Environment> => {
115
- checkConfig();
116
-
117
- if (environment) {
118
- return new Promise((resolve) => resolve(environment));
119
- }
120
-
121
- const client = createClient({
122
- accessToken: config.accessToken,
123
- });
124
-
125
- const space = await client.getSpace(config.spaceId);
126
- if (!space) {
127
- throw new Error("Space not found");
128
- }
129
-
130
- const env = await space.getEnvironment(config.environmentId);
131
- if (!env) {
132
- throw new Error("Environment not found");
133
- }
134
-
135
- environment = env;
136
-
137
- return new Promise((resolve) => resolve(environment));
138
- };
139
-
140
- /**
141
- * Get environment default locale
142
- *
143
- * @returns
144
- */
145
- export const getEnvironmentDefaultLocale = async (): Promise<Locale> => {
146
- checkConfig();
147
-
148
- if (defaultEnvironmentLocale) {
149
- return new Promise((resolve) => resolve(defaultEnvironmentLocale));
150
- }
151
-
152
- const env = await getEnvironment();
153
- const environmentLocales = await env.getLocales();
154
- if (!environmentLocales) {
155
- throw new Error("Environment locales not found");
156
- }
157
-
158
- const findDefaultEnvironmentLocale: Locale | undefined =
159
- environmentLocales.items.find((locale) => locale.default);
160
-
161
- if (findDefaultEnvironmentLocale) {
162
- defaultEnvironmentLocale = findDefaultEnvironmentLocale;
163
- } else {
164
- throw new Error("Default environment locales not found");
165
- }
166
-
167
- return new Promise((resolve) => resolve(defaultEnvironmentLocale));
168
- };
169
-
170
- export const getClient = async () => {
171
- return await getEnvironment();
172
- };
173
-
174
- /**
175
- * Get environment default locale code
176
- *
177
- * @returns
178
- */
179
- export const getEnvironmentDefaultLocaleCode = async (): Promise<string> => {
180
- checkConfig();
181
-
182
- if (defaultEnvironmentLocaleCode) {
183
- return new Promise((resolve) => resolve(defaultEnvironmentLocaleCode));
184
- }
185
-
186
- const defEnvironmentLocale = await getEnvironmentDefaultLocale();
187
- defaultEnvironmentLocaleCode = defEnvironmentLocale.code;
188
- return new Promise((resolve) => resolve(defaultEnvironmentLocaleCode));
189
- };
190
-
191
- /**
192
- * Upload file
193
- *
194
- * @param asset
195
- * @returns
196
- */
197
- export const uploadFile = async (asset: CreateAssetProps): Promise<any> => {
198
- const env = await getEnvironment();
199
- const assetRes = await env.createAsset(asset);
200
- return assetRes.processForAllLocales();
201
- };
202
-
203
- /**
204
- * Create entry wuth id
205
- *
206
- * @param contentTypeId
207
- * @param id
208
- * @param data
209
- * @param publish
210
- * @returns
211
- */
212
- export const createEntryWithId = async (
213
- contentTypeId: string,
214
- id: string,
215
- data: CreateEntryProps,
216
- publish: boolean = false
217
- ) => {
218
- const env = await getEnvironment();
219
- const entry = await env.createEntryWithId(contentTypeId, id, data);
220
-
221
- if (publish) {
222
- try {
223
- return await entry.publish();
224
- } catch (err: any) {
225
- log(`Cannot publish entry.`);
226
- log(err);
227
- }
228
- }
229
-
230
- return entry;
231
- };
232
-
233
- /**
234
- * Update entry
235
- *
236
- * @param itemEntry
237
- * @param data
238
- * @param publish
239
- * @returns
240
- */
241
- export const updateEntry = async (
242
- itemEntry: Entry,
243
- data: CreateEntryProps,
244
- publish: boolean = false
245
- ) => {
246
- for (const [key, value] of Object.entries(data.fields)) {
247
- itemEntry.fields[key] = value;
248
- }
249
-
250
- let entry = itemEntry;
251
- try {
252
- entry = await itemEntry.update();
253
- } catch (err: any) {
254
- log(`Cannot update entry.`);
255
- log(err);
256
- }
257
-
258
- if (publish) {
259
- try {
260
- return await entry.publish();
261
- } catch (err: any) {
262
- log(`Cannot publish entry.`);
263
- log(err);
264
- }
265
- } else if (entry.isPublished()) {
266
- return await entry.unpublish();
267
- } else if (entry.isArchived()) {
268
- return await entry.unarchive();
269
- }
270
-
271
- return entry;
272
- };
273
-
274
- /**
275
- * Get entry by code
276
- *
277
- * @param {string} code
278
- * @param {string} contentTypeId
279
- * @param {string} select Example: "sys,fields.code". Default all
280
- * @returns
281
- */
282
- export const getEntryByCode = async (
283
- code: string,
284
- contentTypeId: string,
285
- select?: string
286
- ): Promise<Entry> => {
287
- const env = await getEnvironment();
288
- const defEnvLocaleCode = await getEnvironmentDefaultLocaleCode();
289
-
290
- const opts = {
291
- content_type: contentTypeId,
292
- "fields.code": code,
293
- limit: 1,
294
- locale: defEnvLocaleCode,
295
- select,
296
- };
297
- const entries = await env.getEntries(opts);
298
- return entries.items[0];
299
- };
300
-
301
- /**
302
- * Get all entries by code
303
- *
304
- * @param {string} codes
305
- * @param {string} contentTypeId
306
- * @param {string} select Example: "sys,fields.code". Default all
307
- * @param {string} filter Default "fields.code"
308
- * @param {array} otherFilters Example: [{ key: "fields.catalogs.sys.id[in]", value: 'ARCHITECTURAL' }]
309
- * @returns
310
- */
311
- export const getAllEntriesByCodes = async (
312
- codes: string[],
313
- contentTypeId: string,
314
- select?: string,
315
- filter: string = "fields.code",
316
- otherFilters?: OtherFilters[]
317
- ): Promise<Entry[]> => {
318
- if (!codes.length) {
319
- return [];
320
- }
321
-
322
- log(
323
- `getAllEntriesByCodes codes: ${codes.length} contentTypeId: ${contentTypeId}`
324
- );
325
-
326
- const env = await getEnvironment();
327
- const defEnvLocaleCode = await getEnvironmentDefaultLocaleCode();
328
- let allItems: Entry[] = [];
329
- let othersPagesToFetch = false;
330
- let skip = 0;
331
- const limit = 20;
332
- const chunkLimit = 20;
333
- const filterKey = `${filter}[in]`;
334
-
335
- let codesChunks: any[] = [];
336
- if (codes.length > chunkLimit) {
337
- codesChunks = doChunk(codes, chunkLimit);
338
- } else {
339
- codesChunks.push(codes);
340
- }
341
-
342
- let count = 0;
343
- for (const codesChunk of codesChunks) {
344
- if (codesChunk.length) {
345
- do {
346
- const opts: any = {
347
- content_type: contentTypeId,
348
- limit,
349
- skip,
350
- locale: defEnvLocaleCode,
351
- select,
352
- };
353
- opts[filterKey] = codesChunk.join(",");
354
- if (otherFilters?.length) {
355
- for (const otherFilter of otherFilters) {
356
- opts[otherFilter.key] = otherFilter.value;
357
- }
358
- }
359
- const { items, total } = await env.getEntries(opts);
360
-
361
- allItems = [...allItems, ...(items || [])];
362
-
363
- if (total && allItems.length < total) {
364
- othersPagesToFetch = true;
365
- skip += limit;
366
-
367
- if (++count % 7 === 0) {
368
- await sleep(200);
369
- }
370
- } else {
371
- othersPagesToFetch = false;
372
- }
373
- } while (othersPagesToFetch);
374
- }
375
- }
376
-
377
- return allItems;
378
- };
379
-
380
- /**
381
- * Get all entries
382
- *
383
- * @param {string} contentType
384
- * @param {string} select
385
- * @param {string} filterKey Ex: `fields.catalog[in]`
386
- * @param {string} filterValue Ex: `ARCHITECTURAL`
387
- * @param {number} limit Default: 50
388
- * @returns
389
- */
390
- export const getAllEntries = async (
391
- contentType: string,
392
- select?: string,
393
- filterKey?: string,
394
- filterValue?: string,
395
- limit: number = 50
396
- ): Promise<Entry[]> => {
397
- // log(
398
- // `getAllEntries contentType: ${contentType} select: ${select} filterKey: ${filterKey} filterValue: ${filterValue}`,
399
- // "INFO"
400
- // );
401
-
402
- const env = await getEnvironment();
403
- const defEnvLocaleCode = await getEnvironmentDefaultLocaleCode();
404
- let allItems: Entry[] = [];
405
- let othersPagesToFetch = false;
406
- let skip = 0;
407
-
408
- let count = 0;
409
- do {
410
- const opts: any = {
411
- content_type: contentType,
412
- limit,
413
- skip,
414
- locale: defEnvLocaleCode,
415
- select,
416
- };
417
- if (filterKey) {
418
- opts[filterKey] = filterValue;
419
- }
420
- const { items, total } = await env.getEntries(opts);
421
-
422
- allItems = [...allItems, ...(items || [])];
423
-
424
- if (total && allItems.length < total) {
425
- othersPagesToFetch = true;
426
- skip += limit;
427
-
428
- if (++count % 7 === 0) {
429
- await sleep(200);
430
- }
431
- } else {
432
- othersPagesToFetch = false;
433
- }
434
- } while (othersPagesToFetch);
435
-
436
- return allItems;
437
- };
438
-
439
- /**
440
- * Get entry by id
441
- *
442
- * @param entryID
443
- * @param contentTypeId
444
- * @param select
445
- * @returns
446
- */
447
- export const getEntryByID = async (
448
- entryID: string,
449
- contentTypeId: string,
450
- select?: string,
451
- locale?: string
452
- ): Promise<Entry> => {
453
- const env = await getEnvironment();
454
- const defEnvLocaleCode = await getEnvironmentDefaultLocaleCode();
455
-
456
- const opts = {
457
- content_type: contentTypeId,
458
- "sys.id": entryID,
459
- limit: 1,
460
- locale: locale ?? defEnvLocaleCode,
461
- select,
462
- };
463
-
464
- const entries = await env.getEntries(opts);
465
-
466
- return entries.items[0];
467
- };
468
-
469
- /**
470
- * Init base entries
471
- * @returns
472
- */
473
- export const initBaseEntries = async (): Promise<boolean> => {
474
- const defaultEnvCode = await getEnvironmentDefaultLocaleCode();
475
- // topicSite - corporate
476
- log(`Check topicSite - corporate`);
477
- let siteCorporateEntry: Entry = await getEntryByID(
478
- "SITE_CORPORATE",
479
- "topicSite"
480
- );
481
- if (!siteCorporateEntry) {
482
- log(`topicSite - corporate not exists, await...`);
483
- const siteCorporateEntryData: CreateEntryProps = {
484
- fields: {
485
- title: {},
486
- code: {},
487
- },
488
- };
489
- siteCorporateEntryData.fields.title[defaultEnvCode] = "Corporate";
490
- siteCorporateEntryData.fields.code[defaultEnvCode] = "corporate";
491
- siteCorporateEntry = await createEntryWithId(
492
- "topicSite",
493
- "SITE_CORPORATE",
494
- siteCorporateEntryData
495
- );
496
- siteCorporateEntry = await siteCorporateEntry.publish();
497
- log(`topicSite - corporate created with id: ${siteCorporateEntry.sys.id}`);
498
- } else {
499
- log(
500
- `topicSite - corporate already exists with id: ${siteCorporateEntry.sys.id}`
501
- );
502
- }
503
- // topicSite - professional
504
- log(`Check topicSite - professional`);
505
- let siteProfessionalEntry: Entry = await getEntryByID(
506
- "SITE_PROFESSIONAL",
507
- "topicSite"
508
- );
509
- if (!siteProfessionalEntry) {
510
- log(`topicSite - professional not exists, await...`);
511
- const siteProfessionalEntryData: CreateEntryProps = {
512
- fields: {
513
- title: {},
514
- code: {},
515
- },
516
- };
517
- siteProfessionalEntryData.fields.title[defaultEnvCode] = "Professional";
518
- siteProfessionalEntryData.fields.code[defaultEnvCode] = "professional";
519
- siteProfessionalEntry = await createEntryWithId(
520
- "topicSite",
521
- "SITE_PROFESSIONAL",
522
- siteProfessionalEntryData
523
- );
524
- siteProfessionalEntry = await siteProfessionalEntry.publish();
525
- log(
526
- `topicSite - professional created with id: ${siteProfessionalEntry.sys.id}`
527
- );
528
- } else {
529
- log(
530
- `topicSite - professional already exists with id: ${siteProfessionalEntry.sys.id}`
531
- );
532
- }
533
-
534
- // topicRegion - global
535
- log(`Check topicRegion - global`);
536
- let regionGlobalEntry: Entry = await getEntryByID(
537
- "REGION_GLOBAL",
538
- "topicRegion"
539
- );
540
- if (!regionGlobalEntry) {
541
- log(`topicRegion - global not exists, await...`);
542
- const regionGlobalEntryData: CreateEntryProps = {
543
- fields: {
544
- region: {},
545
- defaultLocale: {},
546
- locales: {},
547
- },
548
- };
549
- regionGlobalEntryData.fields.region[defaultEnvCode] = "global";
550
- regionGlobalEntryData.fields.defaultLocale[defaultEnvCode] = "en";
551
- regionGlobalEntryData.fields.locales[defaultEnvCode] = [
552
- "en-US",
553
- "en",
554
- "it",
555
- "de",
556
- "fr",
557
- "es",
558
- ];
559
- regionGlobalEntry = await createEntryWithId(
560
- "topicRegion",
561
- "REGION_GLOBAL",
562
- regionGlobalEntryData
563
- );
564
- regionGlobalEntry = await regionGlobalEntry.publish();
565
- log(`topicRegion - global created with id: ${regionGlobalEntry.sys.id}`);
566
- } else {
567
- log(
568
- `topicRegion - global already exists with id: ${regionGlobalEntry.sys.id}`
569
- );
570
- }
571
- // topicRegion - us
572
- log(`Check topicRegion - us`);
573
- let regionUsEntry: Entry = await getEntryByID("REGION_US", "topicRegion");
574
- if (!regionUsEntry) {
575
- log(`topicRegion - us not exists, await...`);
576
- const regionUsEntryData: CreateEntryProps = {
577
- fields: {
578
- region: {},
579
- defaultLocale: {},
580
- locales: {},
581
- },
582
- };
583
- regionUsEntryData.fields.region[defaultEnvCode] = "us";
584
- regionUsEntryData.fields.defaultLocale[defaultEnvCode] = "en-US";
585
- regionUsEntryData.fields.locales[defaultEnvCode] = ["en-US"];
586
- regionUsEntry = await createEntryWithId(
587
- "topicRegion",
588
- "REGION_US",
589
- regionUsEntryData
590
- );
591
- regionUsEntry = await regionUsEntry.publish();
592
- log(`topicRegion - us created with id: ${regionUsEntry.sys.id}`);
593
- } else {
594
- log(`topicRegion - us already exists with id: ${regionUsEntry.sys.id}`);
595
- }
596
-
597
- return true;
598
- };
599
-
600
- /**
601
- * Get default professional page content data
602
- *
603
- * @param pageContentEntry
604
- * @param pageContentData
605
- * @returns
606
- */
607
- export const getDefaultProfessionalPageContentData = async (
608
- pageContentEntry: Entry,
609
- pageContentData: CreateEntryProps
610
- ) => {
611
- // Regions
612
- const regionEntry: Entry = await getEntryByID("REGION_GLOBAL", "topicRegion");
613
- if (!regionEntry) {
614
- throw new Error(
615
- `topicRegion with id "REGION_GLOBAL" not exists. Run initBaseEntries() function before.`
616
- );
617
- }
618
- if (
619
- !pageContentEntry ||
620
- typeof pageContentEntry.fields?.regions === "undefined" ||
621
- !pageContentEntry.fields?.regions[defaultEnvironmentLocaleCode]?.find(
622
- (item: CfSys) => item.sys.id === regionEntry.sys.id
623
- )
624
- ) {
625
- if (
626
- !pageContentEntry ||
627
- typeof pageContentEntry.fields?.regions === "undefined"
628
- ) {
629
- pageContentData.fields.regions = {};
630
- pageContentData.fields.regions[defaultEnvironmentLocaleCode] = [];
631
- }
632
-
633
- pageContentData.fields.regions[defaultEnvironmentLocaleCode].push({
634
- sys: {
635
- type: "Link",
636
- linkType: "Entry",
637
- id: regionEntry.sys.id,
638
- },
639
- });
640
- }
641
-
642
- // Sites
643
- const siteEntry: Entry = await getEntryByID("SITE_PROFESSIONAL", "topicSite");
644
- if (!siteEntry) {
645
- throw new Error(
646
- `topicSite with id "SITE_PROFESSIONAL" not exists. Run initBaseEntries() function before.`
647
- );
648
- }
649
- if (
650
- !pageContentEntry ||
651
- typeof pageContentEntry.fields?.sites === "undefined" ||
652
- !pageContentEntry.fields?.sites[defaultEnvironmentLocaleCode]?.find(
653
- (item: CfSys) => item.sys.id === siteEntry.sys.id
654
- )
655
- ) {
656
- if (
657
- !pageContentEntry ||
658
- typeof pageContentEntry.fields?.sites === "undefined"
659
- ) {
660
- pageContentData.fields.sites = {};
661
- pageContentData.fields.sites[defaultEnvironmentLocaleCode] = [];
662
- }
663
-
664
- pageContentData.fields.sites[defaultEnvironmentLocaleCode].push({
665
- sys: {
666
- type: "Link",
667
- linkType: "Entry",
668
- id: siteEntry.sys.id,
669
- },
670
- });
671
- }
672
-
673
- return pageContentData;
674
- };
675
-
676
- /**
677
- * Delete all entries
678
- *
679
- * @param contentType
680
- * @param catalogCode
681
- * @returns
682
- */
683
- export const deleteAllEntries = async (
684
- contentType: string,
685
- catalogCode?: AvailableCatalogs
686
- ) => {
687
- log(`Delete all entries of contentType: ${contentType}`, "INFO");
688
- init();
689
-
690
- const env = await getEnvironment();
691
- const defEnvLocaleCode = await getEnvironmentDefaultLocaleCode();
692
-
693
- let opts = {};
694
- if (catalogCode) {
695
- opts = {
696
- content_type: contentType,
697
- "fields.catalog.sys.id": catalogCode,
698
- limit: 100,
699
- locale: defEnvLocaleCode,
700
- include: 0,
701
- select: "sys",
702
- };
703
- } else {
704
- opts = {
705
- content_type: contentType,
706
- limit: 100,
707
- locale: defEnvLocaleCode,
708
- include: 0,
709
- select: "sys",
710
- };
711
- }
712
-
713
- let total = 0;
714
- let deleted = 0;
715
-
716
- do {
717
- try {
718
- const entries = await env.getEntries(opts);
719
- total = total === 0 ? entries.total : total;
720
- if (total) {
721
- for (const entry of entries.items) {
722
- if (entry.isPublished()) {
723
- log(`Unpublish entry ${entry.sys.id}`);
724
- const unpublishedEntry = await entry.unpublish();
725
- await unpublishedEntry.delete();
726
- } else {
727
- log(`Delete entry ${entry.sys.id}`);
728
- await entry.delete();
729
- }
730
- deleted++;
731
- // await sleep(100);
732
- }
733
- log(`deleted ${deleted} entries of ${total}`);
734
- } else {
735
- log(`No entries found`);
736
- }
737
- } catch (err: any) {
738
- log(err, "ERROR");
739
- }
740
- // await sleep(200);
741
- } while (Number(deleted) < Number(total));
742
-
743
- return {
744
- deleted,
745
- total,
746
- };
747
- };
748
-
749
- /**
750
- * Delete all pages
751
- *
752
- * @param types
753
- * @returns
754
- */
755
- export const deleteAllPages = async (types: string[]) => {
756
- log(`Delete all pages of types: ${types.join(",")}`, "INFO");
757
- const env = await getEnvironment();
758
-
759
- const opts = {
760
- content_type: "page",
761
- "fields.type[in]": types.join(","),
762
- limit: 100,
763
- include: 0,
764
- select: "sys",
765
- };
766
-
767
- let total = 0;
768
- let deleted = 0;
769
-
770
- do {
771
- try {
772
- const entries = await env.getEntries(opts);
773
- total = total === 0 ? entries.total : total;
774
-
775
- if (total) {
776
- for (const entry of entries.items) {
777
- const pageContentEntry = await env.getEntries({
778
- content_type: "pageContent",
779
- "sys.id": `${entry.sys.id}_CONTENT`,
780
- limit: 1,
781
- include: 0,
782
- select: "sys",
783
- });
784
-
785
- if (pageContentEntry.items.length) {
786
- log(`Delete page content ${pageContentEntry.items[0].sys.id}`);
787
- await pageContentEntry.items[0].delete();
788
- }
789
-
790
- log(`Delete page ${entry.sys.id}`);
791
- await entry.delete();
792
- deleted++;
793
- // await sleep(100);
794
- }
795
- log(`deleted ${deleted} pages of ${total}`);
796
- } else {
797
- log(`No pages found`);
798
- }
799
- } catch (err: any) {
800
- log(err, "ERROR");
801
- }
802
- // await sleep(200);
803
- } while (Number(deleted) < Number(total));
804
-
805
- return {
806
- deleted,
807
- total,
808
- };
809
- };
810
-
811
- /**
812
- * Delete pages
813
- *
814
- * @param types
815
- * @param limit
816
- * @returns
817
- */
818
- export const deletePages = async (types: string[], limit: number = 100) => {
819
- log(`Delete ${limit} pages of types: ${types.join(",")}`, "INFO");
820
- const env = await getEnvironment();
821
-
822
- const opts = {
823
- content_type: "page",
824
- "fields.type[in]": types.join(","),
825
- limit,
826
- include: 0,
827
- select: "sys",
828
- };
829
-
830
- let total = 0;
831
- let deleted = 0;
832
-
833
- const entries = await env.getEntries(opts);
834
- total = total === 0 ? entries.total : total;
835
-
836
- if (total) {
837
- for (const entry of entries.items) {
838
- log(`Delete page ${entry.sys.id}`);
839
- await entry.delete();
840
- deleted++;
841
- // await sleep(100);
842
- }
843
- log(`deleted ${deleted} pages of ${total}`);
844
- } else {
845
- log(`No pages found`);
846
- }
847
-
848
- return {
849
- deleted,
850
- total,
851
- };
852
- };
853
-
854
- /**
855
- * Delete Entries
856
- *
857
- * @param contentType
858
- * @param catalogCode
859
- * @param limit
860
- * @returns
861
- */
862
- export const deleteEntries = async (
863
- contentType: string,
864
- catalogCode?: AvailableCatalogs,
865
- limit: number = 100
866
- ) => {
867
- const timeStart = new Date();
868
- log(`Delete ${limit} entries of contentType: ${contentType}`, "INFO");
869
- init();
870
-
871
- const env = await getEnvironment();
872
- const defEnvLocaleCode = await getEnvironmentDefaultLocaleCode();
873
-
874
- let opts = {};
875
- if (catalogCode) {
876
- opts = {
877
- content_type: contentType,
878
- "fields.catalog.sys.id": catalogCode,
879
- limit,
880
- locale: defEnvLocaleCode,
881
- include: 0,
882
- select: "sys",
883
- };
884
- } else {
885
- opts = {
886
- content_type: contentType,
887
- limit,
888
- locale: defEnvLocaleCode,
889
- include: 0,
890
- select: "sys",
891
- };
892
- }
893
-
894
- let total = 0;
895
- let deleted = 0;
896
-
897
- const entries = await env.getEntries(opts);
898
- total = total === 0 ? entries.total : total;
899
- if (total) {
900
- for (const entry of entries.items) {
901
- if (entry.isPublished()) {
902
- log(`Unpublish entry ${entry.sys.id}`);
903
- const unpublishedEntry = await entry.unpublish();
904
- log(`Delete entry ${entry.sys.id}`);
905
- await unpublishedEntry.delete();
906
- } else {
907
- log(`Delete entry ${entry.sys.id}`);
908
- await entry.delete();
909
- }
910
- deleted++;
911
- // await sleep(100);
912
- }
913
- log(`deleted ${deleted} entries of ${total}`);
914
- } else {
915
- log(`No entries found`);
916
- }
917
- const timeEnd = new Date();
918
- const seconds = secondBetweenTwoDate(timeStart, timeEnd);
919
- log(`Request time: ${seconds} seconds`);
920
-
921
- return {
922
- deleted,
923
- total,
924
- };
925
- };
926
-
927
- /**
928
- * Add entry to relation field
929
- *
930
- * @example
931
- * // Add catalog to catalogs relation field of the familyEntry (has many references)
932
- * familyEntry.fields = await addToRelationFields(familyEntry.fields,"catalogs",catalogEntry.sys.id,true);
933
- *
934
- * @param {object} entry
935
- * @param {string} fieldKey
936
- * @param {string} entrySysIdValue
937
- * @param {boolean} manyReferences Has many references? Default: false
938
- * @param {boolean} resetOldValues You want to delete the pre-existing values? Default: false
939
- * @param {string} linkType The Contenful relation link type. Accept Asset or Entry. Default: Entry
940
- *
941
- * @returns entry.fields
942
- */
943
- export const addToRelationFields = async (
944
- entry: Entry | any,
945
- fieldKey: string,
946
- entrySysIdValue: string,
947
- manyReferences: boolean = false,
948
- resetOldValues: boolean = false,
949
- linkType: "Asset" | "Entry" = "Entry"
950
- ): Promise<Entry> => {
951
- const defEnvLocaleCode = await getEnvironmentDefaultLocaleCode();
952
-
953
- // Reset old values
954
- if (resetOldValues && entry.fields?.[fieldKey]?.[defEnvLocaleCode]) {
955
- if (manyReferences) {
956
- entry.fields[fieldKey][defEnvLocaleCode] = [];
957
- } else {
958
- entry.fields[fieldKey][defEnvLocaleCode] = {};
959
- }
960
- }
961
-
962
- // Set field if not exists
963
- if (!entry.fields?.[fieldKey]?.[defaultEnvironmentLocaleCode]) {
964
- entry.fields[fieldKey] = {};
965
- if (manyReferences) {
966
- entry.fields[fieldKey][defEnvLocaleCode] = [];
967
- } else {
968
- entry.fields[fieldKey][defEnvLocaleCode] = {};
969
- }
970
- }
971
-
972
- // chek if the value already exists
973
- let alreadyValueEsists = false;
974
- if (manyReferences) {
975
- alreadyValueEsists = entry.fields[fieldKey][defEnvLocaleCode].find(
976
- (item: CfSys) => item.sys.id === entrySysIdValue
977
- );
978
- } else {
979
- alreadyValueEsists =
980
- entry.fields[fieldKey][defEnvLocaleCode]?.sys?.id === entrySysIdValue;
981
- }
982
-
983
- // Add entry to relation field
984
- if (!alreadyValueEsists) {
985
- if (manyReferences) {
986
- entry.fields[fieldKey][defEnvLocaleCode].push({
987
- sys: {
988
- type: "Link",
989
- linkType,
990
- id: entrySysIdValue,
991
- },
992
- });
993
- } else {
994
- entry.fields[fieldKey][defEnvLocaleCode] = {
995
- sys: { type: "Link", linkType, id: entrySysIdValue },
996
- };
997
- }
998
- }
999
-
1000
- return entry.fields;
1001
- };
1002
-
1003
- /**
1004
- * Remove item from relation
1005
- *
1006
- * @param {object} entry The product entry
1007
- * @param {string} fieldKey The field of relation
1008
- * @param {string} entrySysIdValue The code of entry to remove
1009
- * @param {boolean} manyReferences Has many references? Default: false
1010
- */
1011
- export const removeFromRelationFields = async (
1012
- entry: Entry | any,
1013
- fieldKey: string,
1014
- entrySysIdValue: string,
1015
- manyReferences: boolean = false
1016
- ) => {
1017
- const defEnvLocaleCode = await getEnvironmentDefaultLocaleCode();
1018
- // Set field if not exists
1019
- if (!entry.fields?.[fieldKey]?.[defEnvLocaleCode]) {
1020
- log(
1021
- `The ${fieldKey} relations field of the ${entry.sys.id} entry is empty`,
1022
- "WARN"
1023
- );
1024
- return entry.fields;
1025
- }
1026
-
1027
- // check if the value already exists
1028
- let alreadyValueEsists = false;
1029
- if (manyReferences) {
1030
- alreadyValueEsists = entry.fields[fieldKey][defEnvLocaleCode].find(
1031
- (item: CfSys) => item.sys.id === entrySysIdValue
1032
- );
1033
- if (alreadyValueEsists) {
1034
- entry.fields[fieldKey][defEnvLocaleCode] = entry.fields[fieldKey][
1035
- defEnvLocaleCode
1036
- ].filter((item: CfSys) => item.sys.id !== entrySysIdValue);
1037
- }
1038
- } else {
1039
- alreadyValueEsists =
1040
- entry.fields[fieldKey][defEnvLocaleCode]?.sys?.id === entrySysIdValue;
1041
-
1042
- if (alreadyValueEsists) {
1043
- entry.fields[fieldKey] = {};
1044
- }
1045
- }
1046
-
1047
- if (!alreadyValueEsists) {
1048
- log(
1049
- `${entrySysIdValue} not found into ${fieldKey} relation field values`,
1050
- "WARN"
1051
- );
1052
- }
1053
-
1054
- return entry.fields;
1055
- };
1056
-
1057
- /**
1058
- * Remove item from object field
1059
- *
1060
- * @param {object} entry The product entry
1061
- * @param {string} fieldKey The field of relation
1062
- * @param {string|array} entrySysIdValues The code of entry to remove
1063
- */
1064
- export const removeFromFieldObject = async (
1065
- entry: Entry | any,
1066
- fieldKey: string,
1067
- entrySysIdValues: string | string[]
1068
- ) => {
1069
- const defEnvLocaleCode = await getEnvironmentDefaultLocaleCode();
1070
- // Set field if not exists
1071
- if (!entry.fields?.[fieldKey]?.[defEnvLocaleCode]) {
1072
- log(
1073
- `The ${fieldKey} object field of the ${entry.sys.id} entry is empty`,
1074
- "WARN"
1075
- );
1076
- return entry.fields;
1077
- }
1078
-
1079
- entrySysIdValues = Array.isArray(entrySysIdValues)
1080
- ? entrySysIdValues
1081
- : [entrySysIdValues];
1082
-
1083
- for (const entrySysIdValue of entrySysIdValues) {
1084
- // check if the value already exists
1085
- let alreadyValueEsists = entry.fields[fieldKey][defEnvLocaleCode].find(
1086
- (item: any) => item.entryId === entrySysIdValue
1087
- );
1088
-
1089
- if (alreadyValueEsists) {
1090
- entry.fields[fieldKey][defEnvLocaleCode] = entry.fields[fieldKey][
1091
- defEnvLocaleCode
1092
- ].filter((item: any) => item.entryId !== entrySysIdValue);
1093
- } else {
1094
- log(`No ${fieldKey} ${entrySysIdValue} found to ${entry.sys.id}`);
1095
- }
1096
- }
1097
-
1098
- return entry.fields;
1099
- };
1100
-
1101
- export const addFieldValue = async (
1102
- entry: Entry | any,
1103
- fieldKey: string,
1104
- fieldValue: any,
1105
- manyReferences: boolean = false,
1106
- locale?: string
1107
- ) => {
1108
- const defEnvLocaleCode = locale ?? (await getEnvironmentDefaultLocaleCode());
1109
-
1110
- // Set field if not exists
1111
- if (!entry.fields?.[fieldKey]?.[defaultEnvironmentLocaleCode]) {
1112
- entry.fields[fieldKey] = {};
1113
- if (manyReferences) {
1114
- entry.fields[fieldKey][defEnvLocaleCode] = [];
1115
- } else {
1116
- entry.fields[fieldKey][defEnvLocaleCode] = {};
1117
- }
1118
- }
1119
-
1120
- entry.fields[fieldKey][defEnvLocaleCode] = fieldValue;
1121
-
1122
- return entry.fields;
1123
- };
1124
-
1125
- /**
1126
- * Get topic details
1127
- *
1128
- * @example const catalogs = await getTopicDetails(topicFamily,"catalogs", "topicCatalog");
1129
- * @returns {
1130
- * names: {
1131
- * de: 'Architectural Lighting',
1132
- * 'en-US': 'Architectural Lighting',
1133
- * ...
1134
- * },
1135
- * code: { 'en': 'ARCHITECTURAL' },
1136
- * slugs: {
1137
- * de: 'architectural lighting',
1138
- * 'en-US': 'architectural lighting'
1139
- * ...
1140
- * }
1141
- * }
1142
- *
1143
- * @param topicEntry
1144
- * @param fieldKey
1145
- * @param contentType
1146
- * @param showRelatedEntities Default false
1147
- * @param isCatalogEntry Default true
1148
- * @param skipPageSlugs Default false
1149
- * @returns
1150
- */
1151
- export const getTopicDetails = async (
1152
- topicEntry: Entry,
1153
- fieldKey: string,
1154
- contentType: string,
1155
- showRelatedEntities: boolean = false,
1156
- isCatalogEntry: boolean = true,
1157
- skipPageSlugs: boolean = false
1158
- ): Promise<TopicDetailsResponse[]> => {
1159
- const defEnvLocaleCode = await getEnvironmentDefaultLocaleCode();
1160
- const isHasToManyField = Array.isArray(
1161
- topicEntry?.fields?.[fieldKey]?.[defEnvLocaleCode]
1162
- );
1163
-
1164
- const items: TopicDetailsResponse[] = [];
1165
- let entryIds = [];
1166
- if (isHasToManyField) {
1167
- entryIds = topicEntry?.fields?.[fieldKey]?.[defEnvLocaleCode].map(
1168
- (item: CfSys) => item.sys.id
1169
- );
1170
- } else {
1171
- entryIds = [topicEntry?.fields?.[fieldKey]?.[defEnvLocaleCode]?.sys?.id];
1172
- }
1173
-
1174
- if (entryIds) {
1175
- let select = isCatalogEntry
1176
- ? "sys,fields.name,fields.code"
1177
- : "sys,fields.name";
1178
- if (contentType === "topicSubFamily" && showRelatedEntities) {
1179
- select += ",fields.catalog,fields.category,fields.parentFamily";
1180
- }
1181
-
1182
- const entries = await getAllEntries(
1183
- contentType,
1184
- select,
1185
- "sys.id[in]",
1186
- entryIds.join(",")
1187
- );
1188
-
1189
- if (entries) {
1190
- for (const entry of entries) {
1191
- const data: TopicDetailsResponse = {
1192
- names: await getAllTranslations(entry?.fields?.name || {}),
1193
- code: entry?.fields?.code?.[defEnvLocaleCode],
1194
- };
1195
- if (!skipPageSlugs) {
1196
- let entryPage: any = {};
1197
- if (isCatalogEntry) {
1198
- const entryPageId = `${entry.sys.id}_PAGE`;
1199
- entryPage = await getEntryByID(entryPageId, "page", "fields.slug");
1200
- } else {
1201
- entryPage = await getTopicPage(entry.sys.id);
1202
- }
1203
- data.slugs = await getAllTranslations(entryPage?.fields?.slug || {});
1204
- }
1205
-
1206
- if (contentType === "topicSubFamily" && showRelatedEntities) {
1207
- data.details = await getSubFamilyRelatedDetails(entry);
1208
- }
1209
-
1210
- items.push(data);
1211
- }
1212
- }
1213
- } else {
1214
- log(
1215
- `No ${fieldKey} found in the ${contentType} ${topicEntry.sys.id}`,
1216
- "WARN"
1217
- );
1218
- }
1219
-
1220
- return items;
1221
- };
1222
-
1223
- /**
1224
- * Get asset details
1225
- *
1226
- * @param assetId
1227
- * @returns
1228
- *
1229
- * // TODO: modificare quanto verrà integrato imagix
1230
- */
1231
- export const getAssetDetails = async (
1232
- assetId: string
1233
- ): Promise<AssetPropFields> => {
1234
- const env = await getEnvironment();
1235
- const thumbnailEntry = await env.getAsset(assetId);
1236
- return thumbnailEntry?.fields
1237
- ? keysToLowerCase(thumbnailEntry.fields, true)
1238
- : {};
1239
- };
1240
-
1241
- /**
1242
- * Get entry image details
1243
- *
1244
- * @example
1245
- * await getEntryImageDetails(topicSubModule, 'thumbnail');
1246
- *
1247
- * @param entry The Contentful entry
1248
- * @param fieldKey The image field key of the entry
1249
- * @returns
1250
- *
1251
- * // TODO: modificare quanto verrà integrato imagix
1252
- */
1253
- export const getEntryImageDetails = async (entry: Entry, fieldKey: string) => {
1254
- const defEnvLocaleCode = await getEnvironmentDefaultLocaleCode();
1255
- const assetId =
1256
- entry?.fields?.[fieldKey]?.[defaultEnvironmentLocaleCode]?.sys?.id;
1257
- if (assetId) {
1258
- const assetEntry = await getAssetDetails(assetId);
1259
- return assetEntry?.file?.[defEnvLocaleCode.toLowerCase()]?.url || "";
1260
- }
1261
-
1262
- return "";
1263
- };
1264
-
1265
- export const getDictionaryJson = async () => {
1266
- const data = await getFileFromS3(`dictionary.json`);
1267
- if (!data) {
1268
- throw new Error("Dictionary JSON file not found on S3.");
1269
- }
1270
-
1271
- return data;
1272
- };
1273
-
1274
- export const getDictionaryValue = async (
1275
- fieldKey: string,
1276
- fieldValue: string,
1277
- fieldParent: string = "",
1278
- dictionaryJsonFile: any = {}
1279
- ) => {
1280
- const dictionaryJson = Object.entries(dictionaryJsonFile)
1281
- ? dictionaryJsonFile
1282
- : await getDictionaryJson();
1283
- let field = null;
1284
-
1285
- if (fieldParent && dictionaryJson?.[fieldParent]?.[fieldKey]) {
1286
- field = dictionaryJson[fieldParent][fieldKey];
1287
- } else if (dictionaryJson?.[fieldKey]) {
1288
- field = dictionaryJson[fieldKey];
1289
- }
1290
-
1291
- if (field) {
1292
- if (Array.isArray(field)) {
1293
- return getPimTranslations(
1294
- field.find((item: any) => item.code === fieldValue)
1295
- );
1296
- } else if (typeof field === "object" && field?.code) {
1297
- return getPimTranslations(field);
1298
- } else {
1299
- return field;
1300
- }
1301
- } else {
1302
- log(
1303
- `No field found with fieldKey: ${fieldKey} fieldValue: ${fieldValue} fieldParent: ${fieldParent}`
1304
- );
1305
- }
1306
- };
1307
-
1308
- /**
1309
- *
1310
- * @example
1311
- * const lampCategoriesLocalizedValue = await getDictionaryLocaleValue(locale, "lampCategories", productFileds.electrical.lampCategories.code, "electrical");
1312
- *
1313
- * @param locale
1314
- * @param fieldKey
1315
- * @param fieldValue
1316
- * @param fieldParent
1317
- * @param dictionaryJsonFile
1318
- * @returns
1319
- */
1320
- export const getDictionaryLocaleValue = async (
1321
- locale: string,
1322
- fieldKey: string,
1323
- fieldValue: string,
1324
- fieldParent: string = "",
1325
- dictionaryJsonFile: any = {}
1326
- ) => {
1327
- const defEnvLocaleCode = await getEnvironmentDefaultLocaleCode();
1328
- const values = await getDictionaryValue(
1329
- fieldKey,
1330
- fieldValue,
1331
- fieldParent,
1332
- dictionaryJsonFile
1333
- );
1334
- if (typeof values === "object") {
1335
- return values?.[locale] || values?.[defEnvLocaleCode];
1336
- } else {
1337
- return values;
1338
- }
1339
- };
1340
-
1341
- export const getTopicPage = async (
1342
- topicId: string,
1343
- select: string = "sys,fields"
1344
- ) => {
1345
- const env = await getEnvironment();
1346
-
1347
- const { items } = await env.getEntries({
1348
- links_to_entry: topicId,
1349
- content_type: "page",
1350
- include: 2,
1351
- locale: "*",
1352
- select,
1353
- limit: 1,
1354
- });
1355
-
1356
- return items?.[0];
1357
- };
1358
-
1359
- /**
1360
- * Create wrapperImgix if not exists or get it if already exists
1361
- *
1362
- * @param id The wrapperImgix ID
1363
- * @param data See WrapperImageFields
1364
- * @returns
1365
- */
1366
- export const createWrapperImgix = async (
1367
- id: string,
1368
- data: WrapperImageFields
1369
- ) => {
1370
- let wrapperImgix = await getEntryByID(id, "wrapperImgix");
1371
- if (wrapperImgix) {
1372
- log(`wrapperImgix with id ${id} already exists`);
1373
- return wrapperImgix;
1374
- }
1375
-
1376
- log(`wrapperImgix with id ${id} not found, create it...`);
1377
-
1378
- const defaultEnvCode = await getEnvironmentDefaultLocaleCode();
1379
- const entryData: any = {
1380
- fields: {},
1381
- };
1382
- for (const [key, value] of Object.entries(data)) {
1383
- const fieldValue: any = value;
1384
- if (!entryData.fields?.[key]) {
1385
- entryData.fields[key] = {};
1386
- }
1387
-
1388
- if (
1389
- fieldValue?.hasOwnProperty(defaultEnvCode) ||
1390
- fieldValue?.[defaultEnvCode] === null
1391
- ) {
1392
- fieldValue[defaultEnvCode] =
1393
- fieldValue[defaultEnvCode] === null ? "" : fieldValue[defaultEnvCode];
1394
- entryData.fields[key] = fieldValue;
1395
- } else {
1396
- entryData.fields[key][defaultEnvCode] = fieldValue;
1397
- }
1398
- }
1399
-
1400
- wrapperImgix = await createEntryWithId("wrapperImgix", id, entryData, true);
1401
-
1402
- return wrapperImgix;
1403
- };
1404
-
1405
- /**
1406
- * Archive Entry
1407
- *
1408
- * @param entry
1409
- * @param isProduct
1410
- * @returns
1411
- */
1412
- export const archiveEntry = async (
1413
- entry: Entry,
1414
- isProduct: boolean = false
1415
- ) => {
1416
- if (!entry.isArchived()) {
1417
- if (entry.isPublished()) {
1418
- log(`Unpublish entry ${entry.sys.id}`);
1419
- entry = await entry.unpublish();
1420
- }
1421
-
1422
- log(`Archive entry ${entry.sys.id}`);
1423
- entry = await entry.archive();
1424
- } else {
1425
- log(`Entry ${entry.sys.id} is already archived`);
1426
- }
1427
-
1428
- if (isProduct) {
1429
- const defEnvLocaleCode = await getEnvironmentDefaultLocaleCode();
1430
- const recordObjectId = entry.fields.code[defEnvLocaleCode];
1431
- if (recordObjectId) {
1432
- await removeProductObject(recordObjectId);
1433
- } else {
1434
- log(`recordObjectId not found`, "WARN");
1435
- }
1436
- }
1437
-
1438
- return entry;
1439
- };
1440
-
1441
- export const getEntries = async (
1442
- opts: QueryOptions
1443
- ): Promise<
1444
- import("contentful-management/dist/typings/common-types").Collection<
1445
- import("contentful-management/dist/typings/entities/entry").Entry,
1446
- EntryProps<Record<string, any>>
1447
- >
1448
- > => {
1449
- const env = await getEnvironment();
1450
- const result = await env.getEntries(opts);
1451
-
1452
- return result;
1453
- };