@unchainedshop/api 3.0.0-rc5 → 3.0.0-rc7

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 (127) hide show
  1. package/lib/api-index.d.ts +1 -1
  2. package/lib/api-index.d.ts.map +1 -1
  3. package/lib/api-index.js +1 -1
  4. package/lib/api-index.js.map +1 -1
  5. package/lib/context.d.ts +0 -1
  6. package/lib/context.d.ts.map +1 -1
  7. package/lib/context.js +4 -19
  8. package/lib/context.js.map +1 -1
  9. package/lib/errors.d.ts +1 -0
  10. package/lib/errors.d.ts.map +1 -1
  11. package/lib/errors.js +1 -0
  12. package/lib/errors.js.map +1 -1
  13. package/lib/express/createBulkImportMiddleware.d.ts +1 -2
  14. package/lib/express/createBulkImportMiddleware.d.ts.map +1 -1
  15. package/lib/express/createBulkImportMiddleware.js.map +1 -1
  16. package/lib/express/createERCMetadataMiddleware.js +1 -1
  17. package/lib/express/createERCMetadataMiddleware.js.map +1 -1
  18. package/lib/express/index.d.ts.map +1 -1
  19. package/lib/express/index.js.map +1 -1
  20. package/lib/fastify/index.d.ts.map +1 -1
  21. package/lib/fastify/index.js.map +1 -1
  22. package/lib/resolvers/mutations/accounts/addWebAuthnCredentials.d.ts.map +1 -1
  23. package/lib/resolvers/mutations/accounts/addWebAuthnCredentials.js +3 -0
  24. package/lib/resolvers/mutations/accounts/addWebAuthnCredentials.js.map +1 -1
  25. package/lib/resolvers/mutations/accounts/createWebAuthnCredentialRequestOptions.js +1 -1
  26. package/lib/resolvers/mutations/accounts/createWebAuthnCredentialRequestOptions.js.map +1 -1
  27. package/lib/resolvers/mutations/accounts/loginWithWebAuthn.d.ts.map +1 -1
  28. package/lib/resolvers/mutations/accounts/loginWithWebAuthn.js +4 -1
  29. package/lib/resolvers/mutations/accounts/loginWithWebAuthn.js.map +1 -1
  30. package/lib/resolvers/mutations/orders/addCartDiscount.d.ts.map +1 -1
  31. package/lib/resolvers/mutations/orders/addCartDiscount.js +8 -3
  32. package/lib/resolvers/mutations/orders/addCartDiscount.js.map +1 -1
  33. package/lib/resolvers/mutations/orders/addCartProduct.d.ts.map +1 -1
  34. package/lib/resolvers/mutations/orders/addCartProduct.js +8 -3
  35. package/lib/resolvers/mutations/orders/addCartProduct.js.map +1 -1
  36. package/lib/resolvers/mutations/orders/addCartQuotation.d.ts.map +1 -1
  37. package/lib/resolvers/mutations/orders/addCartQuotation.js +8 -3
  38. package/lib/resolvers/mutations/orders/addCartQuotation.js.map +1 -1
  39. package/lib/resolvers/mutations/orders/addMultipleCartProducts.d.ts.map +1 -1
  40. package/lib/resolvers/mutations/orders/addMultipleCartProducts.js +8 -3
  41. package/lib/resolvers/mutations/orders/addMultipleCartProducts.js.map +1 -1
  42. package/lib/resolvers/mutations/orders/checkoutCart.d.ts.map +1 -1
  43. package/lib/resolvers/mutations/orders/checkoutCart.js +10 -5
  44. package/lib/resolvers/mutations/orders/checkoutCart.js.map +1 -1
  45. package/lib/resolvers/mutations/orders/emptyCart.d.ts.map +1 -1
  46. package/lib/resolvers/mutations/orders/emptyCart.js +8 -3
  47. package/lib/resolvers/mutations/orders/emptyCart.js.map +1 -1
  48. package/lib/resolvers/mutations/orders/signPaymentProviderForCheckout.js +1 -1
  49. package/lib/resolvers/mutations/orders/signPaymentProviderForCheckout.js.map +1 -1
  50. package/lib/resolvers/mutations/orders/updateCart.d.ts.map +1 -1
  51. package/lib/resolvers/mutations/orders/updateCart.js +8 -3
  52. package/lib/resolvers/mutations/orders/updateCart.js.map +1 -1
  53. package/lib/resolvers/type/filter/loaded-filter-types.d.ts.map +1 -1
  54. package/lib/resolvers/type/filter/loaded-filter-types.js +1 -2
  55. package/lib/resolvers/type/filter/loaded-filter-types.js.map +1 -1
  56. package/lib/resolvers/type/index.d.ts +0 -3
  57. package/lib/resolvers/type/index.d.ts.map +1 -1
  58. package/lib/resolvers/type/product/product-configurable-types.d.ts.map +1 -1
  59. package/lib/resolvers/type/product/product-configurable-types.js +3 -5
  60. package/lib/resolvers/type/product/product-configurable-types.js.map +1 -1
  61. package/lib/resolvers/type/product/product-plan-types.d.ts.map +1 -1
  62. package/lib/resolvers/type/product/product-plan-types.js +3 -5
  63. package/lib/resolvers/type/product/product-plan-types.js.map +1 -1
  64. package/lib/resolvers/type/product/product-simple-types.d.ts +0 -2
  65. package/lib/resolvers/type/product/product-simple-types.d.ts.map +1 -1
  66. package/lib/resolvers/type/product/product-simple-types.js +13 -50
  67. package/lib/resolvers/type/product/product-simple-types.js.map +1 -1
  68. package/lib/resolvers/type/product/product-tokenized-types.d.ts +0 -1
  69. package/lib/resolvers/type/product/product-tokenized-types.d.ts.map +1 -1
  70. package/lib/resolvers/type/product/product-tokenized-types.js +5 -23
  71. package/lib/resolvers/type/product/product-tokenized-types.js.map +1 -1
  72. package/lib/resolvers/type/user-types.d.ts.map +1 -1
  73. package/lib/resolvers/type/user-types.js +2 -2
  74. package/lib/resolvers/type/user-types.js.map +1 -1
  75. package/lib/schema/mutation.js +2 -2
  76. package/package.json +10 -7
  77. package/src/api-index.ts +1 -1
  78. package/src/context.ts +4 -20
  79. package/src/errors.ts +2 -0
  80. package/src/express/createBulkImportMiddleware.ts +1 -2
  81. package/src/express/createERCMetadataMiddleware.ts +1 -1
  82. package/src/express/index.ts +1 -2
  83. package/src/fastify/index.ts +2 -3
  84. package/src/resolvers/mutations/accounts/addWebAuthnCredentials.ts +3 -0
  85. package/src/resolvers/mutations/accounts/createWebAuthnCredentialRequestOptions.ts +1 -1
  86. package/src/resolvers/mutations/accounts/loginWithWebAuthn.ts +4 -1
  87. package/src/resolvers/mutations/orders/addCartDiscount.ts +7 -2
  88. package/src/resolvers/mutations/orders/addCartProduct.ts +8 -2
  89. package/src/resolvers/mutations/orders/addCartQuotation.ts +7 -2
  90. package/src/resolvers/mutations/orders/addMultipleCartProducts.ts +7 -2
  91. package/src/resolvers/mutations/orders/checkoutCart.ts +9 -5
  92. package/src/resolvers/mutations/orders/emptyCart.ts +7 -3
  93. package/src/resolvers/mutations/orders/signPaymentProviderForCheckout.ts +1 -1
  94. package/src/resolvers/mutations/orders/updateCart.ts +7 -3
  95. package/src/resolvers/type/filter/loaded-filter-types.ts +1 -2
  96. package/src/resolvers/type/product/product-configurable-types.ts +3 -10
  97. package/src/resolvers/type/product/product-plan-types.ts +3 -7
  98. package/src/resolvers/type/product/product-simple-types.ts +14 -74
  99. package/src/resolvers/type/product/product-tokenized-types.ts +5 -35
  100. package/src/resolvers/type/user-types.ts +4 -2
  101. package/src/schema/mutation.ts +2 -2
  102. package/tests/api-index.test.ts +4 -4
  103. package/lib/express/passport/access-token-strategy.d.ts +0 -10
  104. package/lib/express/passport/access-token-strategy.d.ts.map +0 -1
  105. package/lib/express/passport/access-token-strategy.js +0 -33
  106. package/lib/express/passport/access-token-strategy.js.map +0 -1
  107. package/lib/express/passport/setup.d.ts +0 -4
  108. package/lib/express/passport/setup.d.ts.map +0 -1
  109. package/lib/express/passport/setup.js +0 -30
  110. package/lib/express/passport/setup.js.map +0 -1
  111. package/lib/resolvers/mutations/products/deleteUserProductReviews.d.ts +0 -5
  112. package/lib/resolvers/mutations/products/deleteUserProductReviews.d.ts.map +0 -1
  113. package/lib/resolvers/mutations/products/deleteUserProductReviews.js +0 -15
  114. package/lib/resolvers/mutations/products/deleteUserProductReviews.js.map +0 -1
  115. package/lib/resolvers/mutations/users/deleteUser.d.ts +0 -6
  116. package/lib/resolvers/mutations/users/deleteUser.d.ts.map +0 -1
  117. package/lib/resolvers/mutations/users/deleteUser.js +0 -15
  118. package/lib/resolvers/mutations/users/deleteUser.js.map +0 -1
  119. package/lib/resolvers/mutations/users/deleteUserProductReviews.d.ts +0 -5
  120. package/lib/resolvers/mutations/users/deleteUserProductReviews.d.ts.map +0 -1
  121. package/lib/resolvers/mutations/users/deleteUserProductReviews.js +0 -15
  122. package/lib/resolvers/mutations/users/deleteUserProductReviews.js.map +0 -1
  123. package/lib/resolvers/mutations/utils/getOrderCart.d.ts +0 -7
  124. package/lib/resolvers/mutations/utils/getOrderCart.d.ts.map +0 -1
  125. package/lib/resolvers/mutations/utils/getOrderCart.js +0 -17
  126. package/lib/resolvers/mutations/utils/getOrderCart.js.map +0 -1
  127. package/src/resolvers/mutations/utils/getOrderCart.ts +0 -20
package/src/api-index.ts CHANGED
@@ -10,8 +10,8 @@ import { UnchainedCore } from '@unchainedshop/core';
10
10
  export * from './context.js';
11
11
  export * from './locale-context.js';
12
12
  export * from './loaders/index.js';
13
+ export * from './errors.js';
13
14
  export * as acl from './acl.js';
14
- export * as errors from './errors.js';
15
15
  export * as roles from './roles/index.js';
16
16
  export { createContextResolver, getCurrentContextResolver, setCurrentContextResolver };
17
17
 
package/src/context.ts CHANGED
@@ -1,5 +1,3 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
1
  import { UnchainedCore } from '@unchainedshop/core';
4
2
  import instantiateLoaders, { UnchainedLoaders } from './loaders/index.js';
5
3
  import { getLocaleContext, UnchainedLocaleContext } from './locale-context.js';
@@ -58,24 +56,10 @@ export type UnchainedContextResolver = (
58
56
  },
59
57
  ) => Promise<Context>;
60
58
 
61
- export const loadJSON = (filename) => {
62
- try {
63
- const base = typeof __filename !== 'undefined' && __filename;
64
- if (!base)
65
- return {
66
- version: process.env.npm_package_version,
67
- };
68
- const absolutePath = path.resolve(path.dirname(base), filename);
69
- const data = JSON.parse(fs.readFileSync(absolutePath, 'utf-8'));
70
- return data;
71
- } catch {
72
- return null;
73
- }
74
- };
75
-
76
- const packageJson = loadJSON('../package.json');
77
-
78
- const { UNCHAINED_API_VERSION = packageJson?.version || '2.x' } = process.env;
59
+ const { default: packageJson } = await import(`${import.meta.dirname}/../package.json`, {
60
+ with: { type: 'json' },
61
+ });
62
+ const { UNCHAINED_API_VERSION = packageJson?.version || '3.x' } = process.env;
79
63
 
80
64
  export const createContextResolver =
81
65
  (
package/src/errors.ts CHANGED
@@ -79,6 +79,8 @@ export const UserWebAuthnCredentialsNotFoundError = createError(
79
79
  'User WebAuth Credentials not found',
80
80
  );
81
81
 
82
+ export const WebAuthnDisabledError = createError('WebAuthnDisabledError', 'WebAuthn disabled');
83
+
82
84
  export const UserWeb3AddressNotFoundError = createError(
83
85
  'UserWeb3AddressNotFoundError',
84
86
  'Web3 Account not found for User',
@@ -1,7 +1,6 @@
1
1
  import { createLogger } from '@unchainedshop/logger';
2
2
  import { checkAction } from '../acl.js';
3
3
  import { actions } from '../roles/index.js';
4
- import { IncomingMessage } from 'http';
5
4
  import { Context } from '../context.js';
6
5
 
7
6
  const logger = createLogger('unchained:bulk-import');
@@ -19,7 +18,7 @@ const methodWrongHandler = (res) => () => {
19
18
  };
20
19
 
21
20
  export default async function bulkImportMiddleware(
22
- req: IncomingMessage & { query?: any; unchainedContext: Context },
21
+ req: Request & { query?: any; unchainedContext: Context },
23
22
  res,
24
23
  ) {
25
24
  try {
@@ -1,4 +1,4 @@
1
- import path from 'path';
1
+ import path from 'node:path';
2
2
  import { createLogger } from '@unchainedshop/logger';
3
3
  import { Context } from '../context.js';
4
4
  import { Request, RequestHandler } from 'express';
@@ -11,9 +11,8 @@ import { UnchainedCore } from '@unchainedshop/core';
11
11
  import { emit } from '@unchainedshop/events';
12
12
  import { API_EVENTS } from '../events.js';
13
13
  import { User } from '@unchainedshop/core-users';
14
- import { IncomingMessage } from 'http';
15
14
 
16
- const resolveUserRemoteAddress = (req: IncomingMessage) => {
15
+ const resolveUserRemoteAddress = (req: e.Request) => {
17
16
  const remoteAddress =
18
17
  (req.headers['x-real-ip'] as string) ||
19
18
  (req.headers['x-forwarded-for'] as string) ||
@@ -8,12 +8,11 @@ import { UnchainedCore } from '@unchainedshop/core';
8
8
  import { emit } from '@unchainedshop/events';
9
9
  import { API_EVENTS } from '../events.js';
10
10
  import { User } from '@unchainedshop/core-users';
11
- import { IncomingMessage } from 'http';
12
11
  import fastifySession from '@fastify/session';
13
12
  import fastifyCookie from '@fastify/cookie';
14
- import { FastifyInstance } from 'fastify';
13
+ import { FastifyInstance, FastifyRequest } from 'fastify';
15
14
 
16
- const resolveUserRemoteAddress = (req: IncomingMessage) => {
15
+ const resolveUserRemoteAddress = (req: FastifyRequest) => {
17
16
  const remoteAddress =
18
17
  (req.headers['x-real-ip'] as string) ||
19
18
  (req.headers['x-forwarded-for'] as string) ||
@@ -1,5 +1,6 @@
1
1
  import { log } from '@unchainedshop/logger';
2
2
  import { Context } from '../../../context.js';
3
+ import { WebAuthnDisabledError } from '../../../errors.js';
3
4
 
4
5
  export default async function addWebAuthnCredentials(
5
6
  root: never,
@@ -15,6 +16,8 @@ export default async function addWebAuthnCredentials(
15
16
  credentials,
16
17
  );
17
18
 
19
+ if (!webAuthnService) throw new WebAuthnDisabledError();
20
+
18
21
  return modules.users.updateUser(
19
22
  { _id: userId },
20
23
  {
@@ -16,7 +16,7 @@ export default async function createWebAuthnCredentialRequestOptions(
16
16
  extensionOptions,
17
17
  );
18
18
 
19
- if (username) {
19
+ if (username && options) {
20
20
  const user = await modules.users.findUserByUsername(username);
21
21
  options.allowCredentials = user?.services?.webAuthn?.map(({ id, type }) => ({
22
22
  id,
@@ -1,5 +1,6 @@
1
1
  import { log } from '@unchainedshop/logger';
2
2
  import { Context } from '../../../context.js';
3
+ import { WebAuthnDisabledError } from '../../../errors.js';
3
4
 
4
5
  export default async function loginWithWebAuthn(
5
6
  root: never,
@@ -16,12 +17,14 @@ export default async function loginWithWebAuthn(
16
17
  let user = await context.modules.users.findUserByUsername(username);
17
18
  if (!user) throw new Error('User not found');
18
19
 
19
- await context.modules.users.webAuthn.verifyCredentialRequest(
20
+ const verification = await context.modules.users.webAuthn.verifyCredentialRequest(
20
21
  user.services?.webAuthn,
21
22
  user.username,
22
23
  params.webAuthnPublicKeyCredentials,
23
24
  );
24
25
 
26
+ if (!verification) throw new WebAuthnDisabledError();
27
+
25
28
  user = await context.modules.users.updateHeartbeat(user._id, {
26
29
  remoteAddress: context.remoteAddress,
27
30
  remotePort: context.remotePort,
@@ -1,10 +1,10 @@
1
1
  import { Context } from '../../../context.js';
2
2
  import { log } from '@unchainedshop/logger';
3
- import { getOrderCart } from '../utils/getOrderCart.js';
4
3
  import {
5
4
  OrderWrongStatusError,
6
5
  OrderDiscountCodeAlreadyPresentError,
7
6
  OrderDiscountCodeNotValidError,
7
+ OrderNotFoundError,
8
8
  } from '../../../errors.js';
9
9
 
10
10
  export default async function addCartDiscount(
@@ -16,7 +16,12 @@ export default async function addCartDiscount(
16
16
 
17
17
  log(`mutation addCartDiscount ${code} ${orderId}`, { userId, orderId });
18
18
 
19
- const order = await getOrderCart({ orderId, user }, context);
19
+ const order = await services.orders.findOrInitCart({
20
+ orderId,
21
+ user,
22
+ countryCode: context.countryContext,
23
+ });
24
+ if (!order) throw new OrderNotFoundError({ orderId });
20
25
 
21
26
  if (!modules.orders.isCart(order)) throw new OrderWrongStatusError({ status: order.status });
22
27
 
@@ -5,8 +5,8 @@ import {
5
5
  OrderQuantityTooLowError,
6
6
  InvalidIdError,
7
7
  OrderWrongStatusError,
8
+ OrderNotFoundError,
8
9
  } from '../../../errors.js';
9
- import { getOrderCart } from '../utils/getOrderCart.js';
10
10
  import { ordersSettings } from '@unchainedshop/core-orders';
11
11
 
12
12
  export default async function addCartProduct(
@@ -29,7 +29,13 @@ export default async function addCartProduct(
29
29
  const originalProduct = await modules.products.findProduct({ productId: originalProductId });
30
30
  if (!originalProduct) throw new ProductNotFoundError({ productId: originalProductId });
31
31
 
32
- const order = await getOrderCart({ orderId, user }, context);
32
+ const order = await services.orders.findOrInitCart({
33
+ orderId,
34
+ user,
35
+ countryCode: context.countryContext,
36
+ });
37
+ if (!order) throw new OrderNotFoundError({ orderId });
38
+
33
39
  if (!modules.orders.isCart(order)) throw new OrderWrongStatusError({ status: order.status });
34
40
 
35
41
  const product = await modules.products.resolveOrderableProduct(originalProduct, { configuration });
@@ -8,8 +8,8 @@ import {
8
8
  InvalidIdError,
9
9
  OrderWrongStatusError,
10
10
  ProductNotFoundError,
11
+ OrderNotFoundError,
11
12
  } from '../../../errors.js';
12
- import { getOrderCart } from '../utils/getOrderCart.js';
13
13
  import { QuotationDirector } from '@unchainedshop/core';
14
14
 
15
15
  export default async function addCartQuotation(
@@ -43,7 +43,12 @@ export default async function addCartQuotation(
43
43
  throw new QuotationWrongStatusError({ status: quotation.status });
44
44
  }
45
45
 
46
- const order = await getOrderCart({ orderId, user }, context);
46
+ const order = await services.orders.findOrInitCart({
47
+ orderId,
48
+ user,
49
+ countryCode: context.countryContext,
50
+ });
51
+ if (!order) throw new OrderNotFoundError({ orderId });
47
52
  if (!modules.orders.isCart(order)) throw new OrderWrongStatusError({ status: order.status });
48
53
 
49
54
  if (
@@ -4,8 +4,8 @@ import {
4
4
  ProductNotFoundError,
5
5
  OrderQuantityTooLowError,
6
6
  OrderWrongStatusError,
7
+ OrderNotFoundError,
7
8
  } from '../../../errors.js';
8
- import { getOrderCart } from '../utils/getOrderCart.js';
9
9
  import { ordersSettings } from '@unchainedshop/core-orders';
10
10
 
11
11
  export default async function addMultipleCartProducts(
@@ -41,7 +41,12 @@ export default async function addMultipleCartProducts(
41
41
  }),
42
42
  );
43
43
 
44
- const order = await getOrderCart({ orderId, user }, context);
44
+ const order = await services.orders.findOrInitCart({
45
+ orderId,
46
+ user,
47
+ countryCode: context.countryContext,
48
+ });
49
+ if (!order) throw new OrderNotFoundError({ orderId });
45
50
  if (!modules.orders.isCart(order)) throw new OrderWrongStatusError({ status: order.status });
46
51
 
47
52
  // Reduce is used to wait for each product to be added before processing the next (sequential processing)
@@ -1,6 +1,5 @@
1
1
  import { Context } from '../../../context.js';
2
- import { OrderCheckoutError } from '../../../errors.js';
3
- import { getOrderCart } from '../utils/getOrderCart.js';
2
+ import { OrderCheckoutError, OrderNotFoundError } from '../../../errors.js';
4
3
  import { createLogger, log } from '@unchainedshop/logger';
5
4
 
6
5
  const logger = createLogger('unchained:api');
@@ -20,11 +19,16 @@ export default async function checkoutCart(
20
19
  log('mutation checkoutCart', { orderId: forceOrderId, userId });
21
20
 
22
21
  // Do not check for order status here! The checkout method will act accordingly
23
- let order = await getOrderCart({ orderId: forceOrderId, user }, context);
22
+ const order = await services.orders.findOrInitCart({
23
+ orderId: forceOrderId,
24
+ user,
25
+ countryCode: context.countryContext,
26
+ });
27
+ if (!order) throw new OrderNotFoundError({ orderId: forceOrderId });
24
28
 
25
29
  try {
26
- order = await services.orders.checkoutOrder(order._id, transactionContext);
27
- return order;
30
+ const checkedOutOrder = await services.orders.checkoutOrder(order._id, transactionContext);
31
+ return checkedOutOrder;
28
32
  } catch (error) {
29
33
  logger.error(error.message, { userId, orderId: order._id });
30
34
  throw new OrderCheckoutError({
@@ -1,7 +1,6 @@
1
1
  import { log } from '@unchainedshop/logger';
2
2
  import { Context } from '../../../context.js';
3
- import { getOrderCart } from '../utils/getOrderCart.js';
4
- import { OrderWrongStatusError } from '../../../errors.js';
3
+ import { OrderNotFoundError, OrderWrongStatusError } from '../../../errors.js';
5
4
 
6
5
  export default async function emptyCart(
7
6
  root: never,
@@ -12,7 +11,12 @@ export default async function emptyCart(
12
11
 
13
12
  log('mutation emptyCart', { userId, orderId });
14
13
 
15
- const order = await getOrderCart({ orderId, user }, context);
14
+ const order = await services.orders.findOrInitCart({
15
+ orderId,
16
+ user,
17
+ countryCode: context.countryContext,
18
+ });
19
+ if (!order) throw new OrderNotFoundError({ orderId });
16
20
  if (!modules.orders.isCart(order)) throw new OrderWrongStatusError({ status: order.status });
17
21
 
18
22
  if (!order) return null;
@@ -32,7 +32,7 @@ export default async function signPaymentProviderForCheckout(
32
32
  if (!orderPayment) throw new OrderPaymentNotFoundError({ orderPaymentId });
33
33
  } else {
34
34
  const order = await modules.orders.cart({
35
- countryContext: context.countryContext || context.user.lastLogin?.countryCode,
35
+ countryCode: context.countryContext,
36
36
  userId,
37
37
  });
38
38
  if (!order) throw new UserNoCartError({ userId });
@@ -1,7 +1,6 @@
1
1
  import { log } from '@unchainedshop/logger';
2
2
  import { Context } from '../../../context.js';
3
- import { getOrderCart } from '../utils/getOrderCart.js';
4
- import { OrderWrongStatusError } from '../../../errors.js';
3
+ import { OrderNotFoundError, OrderWrongStatusError } from '../../../errors.js';
5
4
  import { Address, Contact } from '@unchainedshop/mongodb';
6
5
 
7
6
  interface UpdateCartParams {
@@ -20,7 +19,12 @@ export default async function updateCart(root: never, params: UpdateCartParams,
20
19
 
21
20
  log('mutation updateCart', { userId });
22
21
 
23
- let order = await getOrderCart({ orderId, user }, context);
22
+ let order = await services.orders.findOrInitCart({
23
+ orderId,
24
+ user,
25
+ countryCode: context.countryContext,
26
+ });
27
+ if (!order) throw new OrderNotFoundError({ orderId });
24
28
  if (!modules.orders.isCart(order)) throw new OrderWrongStatusError({ status: order.status });
25
29
 
26
30
  if (meta) {
@@ -1,7 +1,6 @@
1
1
  import { Context } from '../../../context.js';
2
2
  import { Filter, SearchQuery } from '@unchainedshop/core-filters';
3
3
  import { FilterDirector } from '@unchainedshop/core';
4
- import { intersectSet } from '@unchainedshop/utils';
5
4
 
6
5
  type LoadedFilterData = {
7
6
  forceLiveCollection: boolean;
@@ -26,7 +25,7 @@ export const LoadedFilter = {
26
25
  ) => {
27
26
  const filterActions = await FilterDirector.actions({ searchQuery }, context);
28
27
  return filterActions.aggregateProductIds({
29
- productIds: Array.from(intersectSet(filteredByOtherFiltersSet, filteredByThisFilterSet)),
28
+ productIds: Array.from(filteredByOtherFiltersSet.intersection(filteredByThisFilterSet)),
30
29
  }).length;
31
30
  },
32
31
  productsCount: async (
@@ -8,7 +8,6 @@ import {
8
8
  import { Context } from '../../../context.js';
9
9
  import { Product } from './product-types.js';
10
10
  import { sha256 } from '@unchainedshop/utils';
11
- import { ProductPricingDirector } from '@unchainedshop/core';
12
11
 
13
12
  export const ConfigurableProduct = {
14
13
  ...Product,
@@ -105,7 +104,7 @@ export const ConfigurableProduct = {
105
104
  },
106
105
  requestContext: Context,
107
106
  ): Promise<ProductPriceRange> {
108
- const { countryContext, modules } = requestContext;
107
+ const { countryContext, modules, services } = requestContext;
109
108
  const currency = forcedCurrencyCode || requestContext.currencyContext;
110
109
 
111
110
  const products = await modules.products.proxyProducts(product, vectors, {
@@ -123,14 +122,8 @@ export const ConfigurableProduct = {
123
122
  quantity,
124
123
  };
125
124
 
126
- const calculated = await ProductPricingDirector.rebuildCalculation(
127
- pricingContext,
128
- requestContext,
129
- );
130
-
131
- if (!calculated || !calculated.length) return null;
132
-
133
- const pricing = ProductPricingDirector.calculationSheet(pricingContext, calculated);
125
+ const pricing = await services.products.simulateProductPricing(pricingContext);
126
+ if (!pricing) return null;
134
127
  const unitPrice = pricing.unitPrice({ useNetPrice });
135
128
 
136
129
  return {
@@ -5,7 +5,6 @@ import {
5
5
  } from '@unchainedshop/core-products';
6
6
  import { Context } from '../../../context.js';
7
7
  import { Product } from './product-types.js';
8
- import { ProductPricingDirector } from '@unchainedshop/core';
9
8
  import { sha256 } from '@unchainedshop/utils';
10
9
 
11
10
  export const PlanProduct = {
@@ -40,7 +39,7 @@ export const PlanProduct = {
40
39
  },
41
40
  requestContext: Context,
42
41
  ): Promise<ProductPrice> {
43
- const { countryContext, user } = requestContext;
42
+ const { countryContext, user, services } = requestContext;
44
43
  const currency = forcedCurrencyCode || requestContext.currencyContext;
45
44
 
46
45
  const pricingContext = {
@@ -52,11 +51,8 @@ export const PlanProduct = {
52
51
  configuration,
53
52
  };
54
53
 
55
- const calculated = await ProductPricingDirector.rebuildCalculation(pricingContext, requestContext);
56
-
57
- if (!calculated || !calculated.length) return null;
58
-
59
- const pricing = ProductPricingDirector.calculationSheet(pricingContext, calculated);
54
+ const pricing = await services.products.simulateProductPricing(pricingContext);
55
+ if (!pricing) return null;
60
56
  const unitPrice = pricing.unitPrice({ useNetPrice });
61
57
 
62
58
  return {
@@ -15,54 +15,23 @@ export const SimpleProduct = {
15
15
  requestContext: Context,
16
16
  ): Promise<
17
17
  Array<{
18
- _id: string;
19
18
  deliveryProvider?: DeliveryProvider;
20
19
  warehousingProvider?: WarehousingProvider;
21
20
  shipping?: Date;
22
21
  earliestDelivery?: Date;
23
22
  }>
24
23
  > {
25
- const { deliveryProviderType, referenceDate, quantity } = params;
26
- const { modules, services } = requestContext;
27
-
28
- const deliveryProviders = await modules.delivery.findProviders({
29
- type: deliveryProviderType,
30
- });
31
-
32
- return deliveryProviders.reduce(async (oldResult, deliveryProvider) => {
33
- const result = await oldResult;
34
-
35
- const warehousingProviders = await services.orders.supportedWarehousingProviders({
36
- product: obj,
37
- deliveryProvider,
38
- });
39
-
40
- const mappedWarehousingProviders = await Promise.all(
41
- warehousingProviders.map(async (warehousingProvider) => {
42
- const warehousingContext: WarehousingContext = {
43
- deliveryProvider,
44
- product: obj,
45
- quantity,
46
- referenceDate,
47
- };
24
+ const { referenceDate, quantity } = params;
25
+ const { services, modules } = requestContext;
48
26
 
49
- const director = await WarehousingDirector.actions(
50
- warehousingProvider,
51
- warehousingContext,
52
- requestContext,
53
- );
54
- const dispatch = await director.estimatedDispatch();
27
+ const deliveryProviders = await modules.delivery.findProviders({});
55
28
 
56
- return {
57
- warehousingProvider,
58
- ...warehousingContext,
59
- ...dispatch,
60
- };
61
- }),
62
- );
63
-
64
- return result.concat(result, mappedWarehousingProviders);
65
- }, Promise.resolve([]));
29
+ return services.products.simulateProductDispatching({
30
+ deliveryProviders,
31
+ product: obj,
32
+ quantity,
33
+ referenceDate,
34
+ });
66
35
  },
67
36
 
68
37
  async simulatedStocks(
@@ -74,7 +43,6 @@ export const SimpleProduct = {
74
43
  requestContext: Context,
75
44
  ): Promise<
76
45
  Array<{
77
- _id: string;
78
46
  deliveryProvider?: DeliveryProvider;
79
47
  warehousingProvider?: WarehousingProvider;
80
48
  quantity?: number;
@@ -87,39 +55,11 @@ export const SimpleProduct = {
87
55
  type: deliveryProviderType,
88
56
  });
89
57
 
90
- return deliveryProviders.reduce(async (oldResult, deliveryProvider) => {
91
- const result = await oldResult;
92
-
93
- const warehousingProviders = await services.orders.supportedWarehousingProviders({
94
- product: obj,
95
- deliveryProvider,
96
- });
97
-
98
- const mappedWarehousingProviders = await Promise.all(
99
- warehousingProviders.map(async (warehousingProvider) => {
100
- const warehousingContext: WarehousingContext = {
101
- deliveryProvider,
102
- product: obj,
103
- referenceDate,
104
- };
105
-
106
- const director = await WarehousingDirector.actions(
107
- warehousingProvider,
108
- warehousingContext,
109
- requestContext,
110
- );
111
- const stock = await director.estimatedStock();
112
-
113
- return {
114
- warehousingProvider,
115
- ...warehousingContext,
116
- ...stock,
117
- };
118
- }),
119
- );
120
-
121
- return result.concat(result, mappedWarehousingProviders);
122
- }, Promise.resolve([]));
58
+ return services.products.simulateProductInventory({
59
+ deliveryProviders,
60
+ product: obj,
61
+ referenceDate,
62
+ });
123
63
  },
124
64
 
125
65
  baseUnit({ warehousing }): string {
@@ -1,4 +1,3 @@
1
- import { WarehousingContext, WarehousingDirector } from '@unchainedshop/core';
2
1
  import {
3
2
  Product,
4
3
  ProductContractConfiguration,
@@ -40,7 +39,6 @@ export const TokenizedProduct = {
40
39
  requestContext: Context,
41
40
  ): Promise<
42
41
  Array<{
43
- _id: string;
44
42
  deliveryProvider?: DeliveryProvider;
45
43
  warehousingProvider?: WarehousingProvider;
46
44
  quantity?: number;
@@ -51,39 +49,11 @@ export const TokenizedProduct = {
51
49
 
52
50
  const deliveryProviders = await modules.delivery.findProviders({});
53
51
 
54
- return deliveryProviders.reduce(async (oldResult, deliveryProvider) => {
55
- const result = await oldResult;
56
-
57
- const warehousingProviders = await services.orders.supportedWarehousingProviders({
58
- product: obj,
59
- deliveryProvider,
60
- });
61
-
62
- const mappedWarehousingProviders = await Promise.all(
63
- warehousingProviders.map(async (warehousingProvider) => {
64
- const warehousingContext: WarehousingContext = {
65
- deliveryProvider,
66
- product: obj,
67
- referenceDate,
68
- };
69
-
70
- const director = await WarehousingDirector.actions(
71
- warehousingProvider,
72
- warehousingContext,
73
- requestContext,
74
- );
75
- const stock = await director.estimatedStock();
76
-
77
- return {
78
- warehousingProvider,
79
- ...warehousingContext,
80
- ...stock,
81
- };
82
- }),
83
- );
84
-
85
- return result.concat(result, mappedWarehousingProviders);
86
- }, Promise.resolve([]));
52
+ return services.products.simulateProductInventory({
53
+ deliveryProviders,
54
+ product: obj,
55
+ referenceDate,
56
+ });
87
57
  },
88
58
 
89
59
  async tokens(product: Product, params: never, requestContext: Context) {
@@ -114,7 +114,9 @@ const {
114
114
  } = actions as Record<string, string>;
115
115
 
116
116
  const getPrimaryEmail = (user: UserType) => {
117
- return (user.emails || []).sort((left, right) => Number(right.verified) - Number(left.verified))?.[0];
117
+ return (user.emails || []).toSorted(
118
+ (left, right) => Number(right.verified) - Number(left.verified),
119
+ )?.[0];
118
120
  };
119
121
 
120
122
  export const User: UserHelperTypes = {
@@ -174,7 +176,7 @@ export const User: UserHelperTypes = {
174
176
  const { modules, countryContext } = context;
175
177
  await checkAction(context, viewUserOrders, [user, params]);
176
178
  return modules.orders.cart({
177
- countryContext: countryContext || user.lastLogin?.countryCode,
179
+ countryCode: countryContext,
178
180
  orderNumber: params.orderNumber,
179
181
  userId: user._id,
180
182
  });
@@ -75,7 +75,7 @@ export default [
75
75
  """
76
76
  Create WebAuthn PublicKeyCredentialCreationOptions to use for Registering a new WebAuthn Device
77
77
  """
78
- createWebAuthnCredentialCreationOptions(username: String!, extensionOptions: JSON): JSON!
78
+ createWebAuthnCredentialCreationOptions(username: String!, extensionOptions: JSON): JSON
79
79
 
80
80
  """
81
81
  Register WebAuthn Credentials for current user
@@ -90,7 +90,7 @@ export default [
90
90
  """
91
91
  Create WebAuthn PublicKeyCredentialRequestrOptions to use for WebAuthn Login Flow
92
92
  """
93
- createWebAuthnCredentialRequestOptions(username: String, extensionOptions: JSON): JSON!
93
+ createWebAuthnCredentialRequestOptions(username: String, extensionOptions: JSON): JSON
94
94
 
95
95
  """
96
96
  Creates an alternative cart. If you use this feature, you should use explicit orderId's when using the
@@ -1,8 +1,8 @@
1
1
  // Import the function to be tested.
2
- import { admin } from '../lib/roles/admin.js';
3
- import { actions } from '../lib/roles/index.js';
4
- import { checkAction, ensureActionExists, ensureIsFunction } from '../lib/acl.js';
5
- import { NoPermissionError, PermissionSystemError } from '../lib/errors.js';
2
+ import { admin } from '../src/roles/admin.js';
3
+ import { actions } from '../src/roles/index.js';
4
+ import { checkAction, ensureActionExists, ensureIsFunction } from '../src/acl.js';
5
+ import { NoPermissionError, PermissionSystemError } from '../src/errors.js';
6
6
  import { Roles } from '@unchainedshop/roles';
7
7
 
8
8
  describe('API', () => {