@unchainedshop/platform 4.0.0-rc.15 → 4.0.0-rc.17

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 (79) hide show
  1. package/lib/bulk-importer/createBulkImporter.d.ts +5 -3
  2. package/lib/bulk-importer/createBulkImporter.d.ts.map +1 -1
  3. package/lib/bulk-importer/createBulkImporter.js.map +1 -1
  4. package/lib/context/withAccessToken.d.ts +4 -0
  5. package/lib/context/withAccessToken.d.ts.map +1 -0
  6. package/lib/context/withAccessToken.js +42 -0
  7. package/lib/context/withAccessToken.js.map +1 -0
  8. package/lib/migrations/createMigrationRunner.d.ts +1 -1
  9. package/lib/migrations/runMigrations.d.ts.map +1 -1
  10. package/lib/migrations/runMigrations.js.map +1 -1
  11. package/lib/platform-index.d.ts +0 -1
  12. package/lib/platform-index.d.ts.map +1 -1
  13. package/lib/platform-index.js +0 -1
  14. package/lib/platform-index.js.map +1 -1
  15. package/lib/setup/setupAccounts.d.ts.map +1 -1
  16. package/lib/setup/setupAccounts.js +3 -8
  17. package/lib/setup/setupAccounts.js.map +1 -1
  18. package/lib/setup/setupCarts.d.ts +8 -0
  19. package/lib/setup/setupCarts.d.ts.map +1 -0
  20. package/lib/setup/setupCarts.js +20 -0
  21. package/lib/setup/setupCarts.js.map +1 -0
  22. package/lib/setup/setupTemplates.d.ts.map +1 -1
  23. package/lib/setup/setupTemplates.js +9 -24
  24. package/lib/setup/setupTemplates.js.map +1 -1
  25. package/lib/setup/setupUploadHandlers.js +1 -1
  26. package/lib/setup/setupUploadHandlers.js.map +1 -1
  27. package/lib/setup/setupWorkqueue.d.ts.map +1 -1
  28. package/lib/setup/setupWorkqueue.js +2 -0
  29. package/lib/setup/setupWorkqueue.js.map +1 -1
  30. package/lib/startPlatform.d.ts +2 -6
  31. package/lib/startPlatform.d.ts.map +1 -1
  32. package/lib/startPlatform.js +3 -5
  33. package/lib/startPlatform.js.map +1 -1
  34. package/lib/templates/order-parser/formatAddress.d.ts +3 -0
  35. package/lib/templates/order-parser/formatAddress.d.ts.map +1 -0
  36. package/lib/templates/order-parser/formatAddress.js +14 -0
  37. package/lib/templates/order-parser/formatAddress.js.map +1 -0
  38. package/lib/templates/order-parser/formatPrice.d.ts +6 -0
  39. package/lib/templates/order-parser/formatPrice.d.ts.map +1 -0
  40. package/lib/templates/order-parser/formatPrice.js +6 -0
  41. package/lib/templates/order-parser/formatPrice.js.map +1 -0
  42. package/lib/templates/order-parser/getOrderPositionsData.d.ts +1 -1
  43. package/lib/templates/order-parser/getOrderSummaryData.d.ts +2 -2
  44. package/lib/templates/order-parser/getOrderSummaryData.d.ts.map +1 -1
  45. package/lib/templates/order-parser/getOrderSummaryData.js +14 -8
  46. package/lib/templates/order-parser/getOrderSummaryData.js.map +1 -1
  47. package/lib/templates/order-parser/index.js.map +1 -1
  48. package/package.json +10 -10
  49. package/src/migrations/runMigrations.ts +6 -1
  50. package/src/platform-index.ts +0 -1
  51. package/src/setup/setupAccounts.ts +3 -8
  52. package/src/setup/setupTemplates.ts +9 -24
  53. package/src/setup/setupUploadHandlers.ts +1 -1
  54. package/src/setup/setupWorkqueue.ts +1 -0
  55. package/src/startPlatform.ts +5 -10
  56. package/src/templates/order-parser/getOrderSummaryData.ts +18 -8
  57. package/src/templates/order-parser/index.ts +1 -1
  58. package/src/bulk-importer/createBulkImporter.ts +0 -134
  59. package/src/bulk-importer/handlers/assortment/create.ts +0 -86
  60. package/src/bulk-importer/handlers/assortment/index.ts +0 -3
  61. package/src/bulk-importer/handlers/assortment/remove.ts +0 -15
  62. package/src/bulk-importer/handlers/assortment/update.ts +0 -88
  63. package/src/bulk-importer/handlers/assortment/upsertAssortmentChildren.ts +0 -49
  64. package/src/bulk-importer/handlers/assortment/upsertAssortmentFilters.ts +0 -42
  65. package/src/bulk-importer/handlers/assortment/upsertAssortmentProducts.ts +0 -50
  66. package/src/bulk-importer/handlers/assortment/upsertMedia.ts +0 -54
  67. package/src/bulk-importer/handlers/filter/create.ts +0 -76
  68. package/src/bulk-importer/handlers/filter/index.ts +0 -3
  69. package/src/bulk-importer/handlers/filter/remove.ts +0 -16
  70. package/src/bulk-importer/handlers/filter/update.ts +0 -67
  71. package/src/bulk-importer/handlers/product/create.ts +0 -69
  72. package/src/bulk-importer/handlers/product/index.ts +0 -3
  73. package/src/bulk-importer/handlers/product/remove.ts +0 -16
  74. package/src/bulk-importer/handlers/product/transformSpecificationToProductStructure.ts +0 -22
  75. package/src/bulk-importer/handlers/product/update.ts +0 -65
  76. package/src/bulk-importer/handlers/product/upsertMedia.ts +0 -60
  77. package/src/bulk-importer/handlers/product/upsertVariations.ts +0 -68
  78. package/src/bulk-importer/handlers/utils/convertTagsToLowerCase.ts +0 -4
  79. package/src/bulk-importer/upsertAsset.ts +0 -41
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unchainedshop/platform",
3
- "version": "4.0.0-rc.15",
3
+ "version": "4.0.0-rc.17",
4
4
  "main": "lib/platform-index.js",
5
5
  "types": "lib/platform-index.d.ts",
6
6
  "type": "module",
@@ -35,15 +35,15 @@
35
35
  "npm": ">=10.0.0"
36
36
  },
37
37
  "dependencies": {
38
- "@unchainedshop/api": "^4.0.0-rc.15",
39
- "@unchainedshop/core": "^4.0.0-rc.15",
40
- "@unchainedshop/events": "^4.0.0-rc.15",
41
- "@unchainedshop/file-upload": "^4.0.0-rc.15",
42
- "@unchainedshop/logger": "^4.0.0-rc.15",
43
- "@unchainedshop/mongodb": "^4.0.0-rc.15",
44
- "@unchainedshop/plugins": "^4.0.0-rc.15",
45
- "@unchainedshop/roles": "^4.0.0-rc.15",
46
- "@unchainedshop/utils": "^4.0.0-rc.15",
38
+ "@unchainedshop/api": "^4.0.0-rc.17",
39
+ "@unchainedshop/core": "^4.0.0-rc.17",
40
+ "@unchainedshop/events": "^4.0.0-rc.17",
41
+ "@unchainedshop/file-upload": "^4.0.0-rc.17",
42
+ "@unchainedshop/logger": "^4.0.0-rc.17",
43
+ "@unchainedshop/mongodb": "^4.0.0-rc.17",
44
+ "@unchainedshop/plugins": "^4.0.0-rc.17",
45
+ "@unchainedshop/roles": "^4.0.0-rc.17",
46
+ "@unchainedshop/utils": "^4.0.0-rc.17",
47
47
  "mustache": "^4.2.0",
48
48
  "safe-stable-stringify": "^2.5.0"
49
49
  },
@@ -12,7 +12,12 @@ export const runMigrations = async ({
12
12
  logger?: any;
13
13
  unchainedAPI: UnchainedCore;
14
14
  }) => {
15
- const LastMigration = migrationRepository.db.collection('last-migration');
15
+ const LastMigration = migrationRepository.db.collection<{
16
+ _id: string;
17
+ action: string;
18
+ category: string;
19
+ timestamp: Date;
20
+ }>('last-migration');
16
21
 
17
22
  const findCurrentId = async () => {
18
23
  const last = await LastMigration.findOne({ category: 'unchained' }, { sort: { _id: -1 } });
@@ -1,6 +1,5 @@
1
1
  export * from './startPlatform.js';
2
2
  export * from './context/index.js';
3
- export * from './bulk-importer/createBulkImporter.js';
4
3
  export * from './templates/index.js';
5
4
  export * from './migrations/runMigrations.js';
6
5
 
@@ -3,14 +3,9 @@ import { subscribe } from '@unchainedshop/events';
3
3
 
4
4
  export const setupAccounts = (unchainedAPI: UnchainedCore) => {
5
5
  subscribe('USER_ACCOUNT_ACTION', async ({ payload }: { payload: any }) => {
6
- await unchainedAPI.modules.worker.addWork({
7
- type: 'MESSAGE',
8
- retries: 0,
9
- input: {
10
- template: 'ACCOUNT_ACTION',
11
- recipientEmail: payload.address,
12
- ...payload,
13
- },
6
+ await unchainedAPI.services.worker.addMessage('ACCOUNT_ACTION', {
7
+ recipientEmail: payload.address,
8
+ ...payload,
14
9
  });
15
10
  });
16
11
  };
@@ -36,14 +36,9 @@ export const setupTemplates = (unchainedAPI: UnchainedCore) => {
36
36
 
37
37
  if (order.status === OrderStatus.PENDING) {
38
38
  // We only send the "confirmation" when pending, else we let the other events handle it
39
- await unchainedAPI.modules.worker.addWork({
40
- type: 'MESSAGE',
41
- retries: 0,
42
- input: {
43
- locale: locale.baseName,
44
- template: MessageTypes.ORDER_CONFIRMATION,
45
- orderId: order._id,
46
- },
39
+ await unchainedAPI.services.worker.addMessage(MessageTypes.ORDER_CONFIRMATION, {
40
+ locale: locale.baseName,
41
+ orderId: order._id,
47
42
  });
48
43
  }
49
44
  });
@@ -53,14 +48,9 @@ export const setupTemplates = (unchainedAPI: UnchainedCore) => {
53
48
  const user = await unchainedAPI.modules.users.findUserById(order.userId);
54
49
  const locale = unchainedAPI.modules.users.userLocale(user);
55
50
 
56
- await unchainedAPI.modules.worker.addWork({
57
- type: 'MESSAGE',
58
- retries: 0,
59
- input: {
60
- locale: locale.baseName,
61
- template: MessageTypes.ORDER_CONFIRMATION,
62
- orderId: order._id,
63
- },
51
+ await unchainedAPI.services.worker.addMessage(MessageTypes.ORDER_CONFIRMATION, {
52
+ locale: locale.baseName,
53
+ orderId: order._id,
64
54
  });
65
55
  });
66
56
 
@@ -69,14 +59,9 @@ export const setupTemplates = (unchainedAPI: UnchainedCore) => {
69
59
  const user = await unchainedAPI.modules.users.findUserById(order.userId);
70
60
  const locale = unchainedAPI.modules.users.userLocale(user);
71
61
 
72
- await unchainedAPI.modules.worker.addWork({
73
- type: 'MESSAGE',
74
- retries: 0,
75
- input: {
76
- locale: locale.baseName,
77
- template: MessageTypes.ORDER_REJECTION,
78
- orderId: order._id,
79
- },
62
+ await unchainedAPI.services.worker.addMessage(MessageTypes.ORDER_REJECTION, {
63
+ locale: locale.baseName,
64
+ orderId: order._id,
80
65
  });
81
66
  });
82
67
  };
@@ -15,7 +15,7 @@ export const setupUploadHandlers = ({ services, modules }: UnchainedCore) => {
15
15
 
16
16
  FileDirector.registerFileUploadCallback('assortment-media', async (file) => {
17
17
  await modules.assortments.media.create({
18
- assortmentId: file.meta.assortmentId as string,
18
+ assortmentId: file.meta?.assortmentId as string,
19
19
  mediaId: file._id,
20
20
  });
21
21
  });
@@ -75,6 +75,7 @@ export async function setupWorkqueue({
75
75
  await Promise.all(
76
76
  users.map((user) => {
77
77
  const locale = unchainedAPI.modules.users.userLocale(user);
78
+ if (!locale.region) return null;
78
79
  return unchainedAPI.services.orders.nextUserCart({
79
80
  user,
80
81
  countryCode: locale.region,
@@ -3,7 +3,6 @@ import { initCore, UnchainedCoreOptions } from '@unchainedshop/core';
3
3
  import { initDb, mongodb, stopDb } from '@unchainedshop/mongodb';
4
4
  import { defaultLogger } from '@unchainedshop/logger';
5
5
  import { UnchainedCore } from '@unchainedshop/core';
6
- import { BulkImportHandler, createBulkImporterFactory } from './bulk-importer/createBulkImporter.js';
7
6
  import { setupAccounts } from './setup/setupAccounts.js';
8
7
  import { setupUploadHandlers } from './setup/setupUploadHandlers.js';
9
8
  import { setupTemplates, MessageTypes } from './setup/setupTemplates.js';
@@ -14,12 +13,9 @@ import { IRoleOptionConfig } from '@unchainedshop/roles';
14
13
  export { MessageTypes };
15
14
 
16
15
  export type PlatformOptions = {
17
- bulkImporter?: {
18
- handlers?: Record<string, BulkImportHandler>;
19
- };
20
16
  rolesOptions?: IRoleOptionConfig;
21
17
  workQueueOptions?: SetupWorkqueueOptions;
22
- } & Omit<UnchainedCoreOptions, 'bulkImporter' | 'migrationRepository' | 'db'> &
18
+ } & Omit<UnchainedCoreOptions, 'migrationRepository' | 'db'> &
23
19
  Omit<UnchainedServerOptions, 'roles' | 'unchainedAPI'>;
24
20
 
25
21
  const REQUIRED_ENV_VARIABLES = [
@@ -51,8 +47,8 @@ export const startPlatform = async ({
51
47
  modules,
52
48
  services,
53
49
  options,
54
- rolesOptions = {},
55
- bulkImporter: bulkImporterOptions,
50
+ rolesOptions,
51
+ bulkImporter,
56
52
  workQueueOptions,
57
53
  ...arbitraryAPIServerConfiguration
58
54
  }: PlatformOptions): Promise<{
@@ -63,14 +59,13 @@ export const startPlatform = async ({
63
59
  exitOnMissingEnvironmentVariables();
64
60
  existOnInvalidEnvironmentVariables();
65
61
 
66
- const configuredRoles = roles.configureRoles(rolesOptions);
62
+ const configuredRoles = roles.configureRoles(rolesOptions || {});
67
63
 
68
64
  // Configure database
69
65
  const db = await initDb();
70
66
 
71
67
  // Prepare Migrations
72
68
  const migrationRepository = createMigrationRepository(db);
73
- const bulkImporter = createBulkImporterFactory(db, bulkImporterOptions);
74
69
 
75
70
  // Initialise core api using the database
76
71
  const unchainedAPI = await initCore({
@@ -117,7 +112,7 @@ export const startPlatform = async ({
117
112
  await graphqlHandler.dispose();
118
113
  defaultLogger.debug('Stopping DB Connection', { signal });
119
114
  await stopDb();
120
- defaultLogger.info(`Unchained Engine stopped`, { signal, version: packageJson.version });
115
+ defaultLogger.debug(`Unchained Engine exiting`, { signal, version: packageJson.version });
121
116
  process.exit(0);
122
117
  };
123
118
 
@@ -11,12 +11,22 @@ export const getOrderSummaryData = async (
11
11
  ) => {
12
12
  const { modules } = context;
13
13
  const { useNetPrice, format = ch.priceToString } = params || {};
14
- const orderDelivery = await modules.orders.deliveries.findDelivery({
15
- orderDeliveryId: order.deliveryId,
16
- });
17
- const orderPayment = await modules.orders.payments.findOrderPayment({
18
- orderPaymentId: order.paymentId,
19
- });
14
+ const orderDelivery =
15
+ order.deliveryId &&
16
+ (await modules.orders.deliveries.findDelivery({
17
+ orderDeliveryId: order.deliveryId,
18
+ }));
19
+
20
+ if (!orderDelivery) throw new Error('Order delivery not found');
21
+
22
+ const orderPayment =
23
+ order.paymentId &&
24
+ (await modules.orders.payments.findOrderPayment({
25
+ orderPaymentId: order.paymentId,
26
+ }));
27
+
28
+ if (!orderPayment) throw new Error('Order payment not found');
29
+
20
30
  const paymentProvider = await modules.payment.paymentProviders.findProvider({
21
31
  paymentProviderId: orderPayment.paymentProviderId,
22
32
  });
@@ -55,8 +65,8 @@ export const getOrderSummaryData = async (
55
65
 
56
66
  const total = orderPricing.total({ useNetPrice });
57
67
 
58
- const payment = paymentProvider.adapterKey;
59
- const delivery = deliveryProvider.adapterKey;
68
+ const payment = paymentProvider?.adapterKey;
69
+ const delivery = deliveryProvider?.adapterKey;
60
70
 
61
71
  return {
62
72
  rawPrices: {
@@ -42,7 +42,7 @@ export const transformOrderToText = async (
42
42
  return mustache.render(
43
43
  textTemplate,
44
44
  {
45
- orderDate: new Date(order.ordered).toLocaleString(),
45
+ orderDate: new Date(order.ordered!).toLocaleString(),
46
46
  orderNumber: order.orderNumber,
47
47
  summary: await getOrderSummaryData(order, { locale }, context),
48
48
  positions: await getOrderPositionsData(order, { locale }, context),
@@ -1,134 +0,0 @@
1
- import { mongodb } from '@unchainedshop/mongodb';
2
- import { BulkImporter, UnchainedCore } from '@unchainedshop/core';
3
- import * as AssortmentHandlers from './handlers/assortment/index.js';
4
- import * as FilterHandlers from './handlers/filter/index.js';
5
- import * as ProductHandlers from './handlers/product/index.js';
6
- import { createLogger } from '@unchainedshop/logger';
7
-
8
- const logger = createLogger('unchained:bulk-import');
9
-
10
- export interface BulkImportOperationResult {
11
- entity: string;
12
- operation: string;
13
- success: boolean;
14
- }
15
- export type BulkImportOperation = (
16
- payload: any,
17
- options: {
18
- bulk: (collection: string) => typeof mongodb.BulkOperationBase;
19
- createShouldUpsertIfIDExists?: boolean;
20
- updateShouldUpsertIfIDNotExists?: boolean;
21
- skipCacheInvalidation?: boolean;
22
- },
23
- unchainedAPI: UnchainedCore,
24
- ) => Promise<BulkImportOperationResult>;
25
-
26
- export type BulkImportHandler = Record<string, BulkImportOperation>;
27
-
28
- let bulkOperationHandlers: Record<string, BulkImportHandler> = {};
29
-
30
- export const getOperation = (entity: string, operation: string): BulkImportOperation => {
31
- const handlers = bulkOperationHandlers[entity];
32
- if (!handlers) {
33
- throw new Error(`Entity ${entity} unknown`);
34
- }
35
-
36
- const entityOperation = handlers[operation] as BulkImportOperation;
37
-
38
- if (!entityOperation || typeof entityOperation !== 'function') {
39
- throw new Error(`Operation ${operation} for entity ${entity} invalid`);
40
- }
41
-
42
- return entityOperation;
43
- };
44
-
45
- export const createBulkImporterFactory = (db, bulkImporterOptions: any): BulkImporter => {
46
- bulkOperationHandlers = {
47
- ASSORTMENT: AssortmentHandlers,
48
- PRODUCT: ProductHandlers,
49
- FILTER: FilterHandlers,
50
- ...(bulkImporterOptions?.handlers || {}),
51
- };
52
-
53
- const createBulkImporter: BulkImporter['createBulkImporter'] = (options) => {
54
- const bulkOperations = {};
55
- const preparationIssues = [];
56
- const processedOperations = {};
57
- const { createShouldUpsertIfIDExists, skipCacheInvalidation, updateShouldUpsertIfIDNotExists } =
58
- options;
59
-
60
- const bulk = (collectionName: string) => {
61
- const Collection = db.collection(collectionName);
62
- if (!bulkOperations[collectionName])
63
- bulkOperations[collectionName] = Collection.initializeOrderedBulkOp();
64
- return bulkOperations[collectionName];
65
- };
66
-
67
- logger.debug(
68
- `Configure event import with options: createShouldUpsertIfIDExists=${createShouldUpsertIfIDExists} updateShouldUpsertIfIDNotExists=${updateShouldUpsertIfIDNotExists} skipCacheInvalidation=${skipCacheInvalidation}`,
69
- );
70
-
71
- return {
72
- prepare: async (event, unchainedAPI: UnchainedCore) => {
73
- const entity = event.entity.toUpperCase();
74
- const operation = event.operation.toLowerCase();
75
-
76
- const handler = getOperation(entity, operation);
77
-
78
- const payloadId = event.payload?._id || 'global';
79
-
80
- logger.debug(`${operation} ${entity} ${payloadId} [PREPARE]`);
81
-
82
- try {
83
- await handler(event.payload, { bulk, logger, ...options }, unchainedAPI);
84
- if (!processedOperations[entity]) processedOperations[entity] = {};
85
- if (!processedOperations[entity][operation]) processedOperations[entity][operation] = [];
86
- processedOperations[entity][operation].push(payloadId);
87
- logger.debug(`${operation} ${entity} ${payloadId} [SUCCESS]`);
88
- } catch (e) {
89
- logger.debug(`${operation} ${entity} ${payloadId} [FAILED]`, e);
90
- preparationIssues.push({
91
- operation,
92
- entity,
93
- payloadId,
94
- errorCode: e.name,
95
- errorMessage: e.message,
96
- });
97
- } finally {
98
- logger.debug(`${operation} ${entity} ${payloadId} [DONE]`);
99
- }
100
- },
101
- execute: async () => {
102
- logger.debug(`Execute bulk operations for: ${Object.keys(bulkOperations).join(', ')}`);
103
-
104
- const processedBulkOperations = await Promise.allSettled(
105
- Object.values(bulkOperations).map(async (o: any) => o.execute()),
106
- );
107
- const operationResults = {
108
- processedOperations,
109
- processedBulkOperations,
110
- };
111
- if (preparationIssues?.length) {
112
- logger.error(
113
- `${preparationIssues.length} issues occured while preparing events, import finished with errors`,
114
- );
115
- const errors = { preparationIssues };
116
- return [operationResults, errors];
117
- }
118
- logger.debug(`Import finished without errors`);
119
- return [operationResults, null];
120
- },
121
- invalidateCaches: async (unchainedAPI: UnchainedCore) => {
122
- if (skipCacheInvalidation) return;
123
- await unchainedAPI.modules.assortments.invalidateCache({}, { skipUpstreamTraversal: true });
124
- await unchainedAPI.services.filters.invalidateFilterCache();
125
- },
126
- };
127
- };
128
-
129
- return {
130
- createBulkImporter,
131
- };
132
- };
133
-
134
- export { AssortmentHandlers, ProductHandlers, FilterHandlers };
@@ -1,86 +0,0 @@
1
- import { UnchainedCore } from '@unchainedshop/core';
2
- import convertTagsToLowerCase from '../utils/convertTagsToLowerCase.js';
3
- import upsertAssortmentChildren from './upsertAssortmentChildren.js';
4
- import upsertAssortmentFilters from './upsertAssortmentFilters.js';
5
- import upsertAssortmentProducts from './upsertAssortmentProducts.js';
6
- import upsertMedia from './upsertMedia.js';
7
-
8
- export default async function createAssortment(
9
- payload: any,
10
- { logger, createShouldUpsertIfIDExists },
11
- unchainedAPI: UnchainedCore,
12
- ) {
13
- const { modules } = unchainedAPI;
14
- const { media, specification, products, children, filters, _id } = payload;
15
- if (!specification) throw new Error(`Specification is required when creating new assortment ${_id}`);
16
-
17
- if (!specification.content)
18
- throw new Error(`Assortment content is required when creating new assortment${_id}`);
19
-
20
- specification.tags = convertTagsToLowerCase(specification?.tags);
21
-
22
- logger.debug('create assortment object', specification);
23
- try {
24
- await modules.assortments.create({ ...specification, _id });
25
- } catch (e) {
26
- if (!createShouldUpsertIfIDExists) throw e;
27
- logger.debug('entity already exists, falling back to update', specification);
28
- await modules.assortments.update(_id, {
29
- ...specification,
30
- });
31
- }
32
-
33
- if (!(await modules.assortments.assortmentExists({ assortmentId: _id }))) {
34
- throw new Error(`Can't create assortment ${_id}, fields missing?`);
35
- }
36
-
37
- if (specification.content) {
38
- logger.debug('create localized content for assortment', specification.content);
39
- await modules.assortments.texts.updateTexts(
40
- _id,
41
- Object.entries(specification.content).map(([locale, localizedData]: [string, any]) => {
42
- return {
43
- locale,
44
- ...localizedData,
45
- };
46
- }),
47
- );
48
- }
49
-
50
- logger.debug('create assortment products', products);
51
- await upsertAssortmentProducts(
52
- {
53
- products: products || [],
54
- assortmentId: _id,
55
- },
56
- unchainedAPI,
57
- );
58
-
59
- logger.debug('create assortment children', children);
60
- await upsertAssortmentChildren(
61
- {
62
- children: children || [],
63
- assortmentId: _id,
64
- },
65
- unchainedAPI,
66
- );
67
-
68
- logger.debug('create assortment filters', filters);
69
- await upsertAssortmentFilters(
70
- {
71
- filters: filters || [],
72
- assortmentId: _id,
73
- },
74
- unchainedAPI,
75
- );
76
-
77
- logger.debug('create assortment media', media);
78
- await upsertMedia({ media: media || [], assortmentId: _id }, unchainedAPI);
79
-
80
- return {
81
- entity: 'ASSORTMENT',
82
- operation: 'create',
83
- _id,
84
- success: true,
85
- };
86
- }
@@ -1,3 +0,0 @@
1
- export { default as create } from './create.js';
2
- export { default as update } from './update.js';
3
- export { default as remove } from './remove.js';
@@ -1,15 +0,0 @@
1
- import { UnchainedCore } from '@unchainedshop/core';
2
-
3
- export default async function removeAssortment(payload, { logger }, unchainedAPI: UnchainedCore) {
4
- const { modules } = unchainedAPI;
5
- const { _id } = payload;
6
- logger.debug('remove assortment');
7
- await modules.assortments.delete(_id, { skipInvalidation: true });
8
-
9
- return {
10
- entity: 'ASSORTMENT',
11
- operation: 'remove',
12
- _id,
13
- success: true,
14
- };
15
- }
@@ -1,88 +0,0 @@
1
- import { UnchainedCore } from '@unchainedshop/core';
2
- import upsertAssortmentProducts from './upsertAssortmentProducts.js';
3
- import upsertAssortmentChildren from './upsertAssortmentChildren.js';
4
- import upsertAssortmentFilters from './upsertAssortmentFilters.js';
5
- import upsertMedia from './upsertMedia.js';
6
- import convertTagsToLowerCase from '../utils/convertTagsToLowerCase.js';
7
- import createAssortment from './create.js';
8
-
9
- export default async function updateAssortment(
10
- payload: any,
11
- { logger, createShouldUpsertIfIDExists, updateShouldUpsertIfIDNotExists },
12
- unchainedAPI: UnchainedCore,
13
- ) {
14
- const { modules } = unchainedAPI;
15
- const { media, specification, products, children, filters, _id } = payload;
16
-
17
- if (!(await modules.assortments.assortmentExists({ assortmentId: _id }))) {
18
- if (updateShouldUpsertIfIDNotExists) {
19
- return createAssortment(payload, { logger, createShouldUpsertIfIDExists }, unchainedAPI);
20
- }
21
- throw new Error(`Can't update non-existing assortment ${_id}`);
22
- }
23
-
24
- if (specification) {
25
- logger.debug('update assortment object', specification);
26
-
27
- specification.tags = convertTagsToLowerCase(specification?.tags);
28
-
29
- await unchainedAPI.modules.assortments.update(_id, { ...specification });
30
-
31
- if (specification.content) {
32
- logger.debug('replace localized content for assortment', specification.content);
33
- await modules.assortments.texts.updateTexts(
34
- _id,
35
- Object.entries(specification.content).map(([locale, localizedData]: [string, any]) => {
36
- return {
37
- locale,
38
- ...localizedData,
39
- };
40
- }),
41
- );
42
- }
43
- }
44
-
45
- if (products) {
46
- logger.debug('update product products', products);
47
- await upsertAssortmentProducts(
48
- {
49
- products: products || [],
50
- assortmentId: _id,
51
- },
52
- unchainedAPI,
53
- );
54
- }
55
-
56
- if (children) {
57
- logger.debug('update assortment children', children);
58
- await upsertAssortmentChildren(
59
- {
60
- children: children || [],
61
- assortmentId: _id,
62
- },
63
- unchainedAPI,
64
- );
65
- }
66
-
67
- if (filters) {
68
- logger.debug('update assortment filters', filters);
69
- await upsertAssortmentFilters(
70
- {
71
- filters: filters || [],
72
- assortmentId: _id,
73
- },
74
- unchainedAPI,
75
- );
76
- }
77
- if (media) {
78
- logger.debug('update assortment media', media);
79
- await upsertMedia({ media: media || [], assortmentId: _id }, unchainedAPI);
80
- }
81
-
82
- return {
83
- entity: 'ASSORTMENT',
84
- operation: 'update',
85
- _id,
86
- success: true,
87
- };
88
- }
@@ -1,49 +0,0 @@
1
- import { AssortmentLink } from '@unchainedshop/core-assortments';
2
- import { UnchainedCore } from '@unchainedshop/core';
3
- import convertTagsToLowerCase from '../utils/convertTagsToLowerCase.js';
4
-
5
- const upsert = async (assortmentLink: AssortmentLink, { modules }: UnchainedCore) => {
6
- if (
7
- !(await modules.assortments.assortmentExists({
8
- assortmentId: assortmentLink.childAssortmentId,
9
- }))
10
- ) {
11
- throw new Error(`Can't link non-existing assortment ${assortmentLink.childAssortmentId}`);
12
- }
13
- try {
14
- const newAssortmentLink = await modules.assortments.links.create(assortmentLink, {
15
- skipInvalidation: true,
16
- });
17
- return newAssortmentLink;
18
- } catch {
19
- return modules.assortments.links.update(assortmentLink._id, assortmentLink, {
20
- skipInvalidation: true,
21
- });
22
- }
23
- };
24
-
25
- export default async ({ children, assortmentId: parentAssortmentId }, unchainedAPI: UnchainedCore) => {
26
- const { modules } = unchainedAPI;
27
- const assortmentLinkIds = await Promise.all(
28
- children.map(async ({ assortmentId: childAssortmentId, ...childrenRest }) => {
29
- const tags = convertTagsToLowerCase(childrenRest?.tags);
30
- const assortmentLink = await upsert(
31
- {
32
- ...childrenRest,
33
- tags,
34
- parentAssortmentId,
35
- childAssortmentId,
36
- } as AssortmentLink,
37
- unchainedAPI,
38
- );
39
- return assortmentLink._id;
40
- }),
41
- );
42
- await modules.assortments.links.deleteMany(
43
- {
44
- _id: { $nin: assortmentLinkIds },
45
- parentAssortmentId,
46
- },
47
- { skipInvalidation: true },
48
- );
49
- };
@@ -1,42 +0,0 @@
1
- import { AssortmentFilter } from '@unchainedshop/core-assortments';
2
- import { UnchainedCore } from '@unchainedshop/core';
3
- import convertTagsToLowerCase from '../utils/convertTagsToLowerCase.js';
4
-
5
- const upsert = async (assortmentFilter: AssortmentFilter, { modules }: UnchainedCore) => {
6
- if (
7
- !(await modules.filters.filterExists({
8
- filterId: assortmentFilter.filterId,
9
- }))
10
- ) {
11
- throw new Error(`Can't link non-existing filter ${assortmentFilter.filterId}`);
12
- }
13
- try {
14
- const newAssortmentFilter = await modules.assortments.filters.create(assortmentFilter);
15
- return newAssortmentFilter;
16
- } catch {
17
- return modules.assortments.filters.update(assortmentFilter._id, assortmentFilter);
18
- }
19
- };
20
-
21
- export default async ({ filters, assortmentId }, unchainedAPI: UnchainedCore) => {
22
- const { modules } = unchainedAPI;
23
- const assortmentFilterIds = await Promise.all(
24
- filters.map(async (filter: AssortmentFilter) => {
25
- const tags = convertTagsToLowerCase(filter?.tags);
26
- const assortmentFilter = await upsert(
27
- {
28
- ...filter,
29
- tags,
30
- assortmentId,
31
- },
32
- unchainedAPI,
33
- );
34
- return assortmentFilter._id;
35
- }),
36
- );
37
-
38
- await modules.assortments.filters.deleteMany({
39
- _id: { $nin: assortmentFilterIds },
40
- assortmentId,
41
- });
42
- };