{"version":3,"file":"index.mjs","names":["uuidv4","uuidv4","parseBasicAuth","store","Decimal","Decimal","uuidv4","uuidv4","uuidv4","uuidv4","storeReference","uuidv4","uuidv4","uuidv4","uuidv4","isSearchAndExpression","isSearchOrExpression","isSearchNotExpression","isSearchFilterExpression","isSearchRangeExpression","isSearchExactExpression","isSearchExistsExpression","isSearchFullTextExpression","isSearchFullTextPrefixExpression","isSearchPrefixExpression","isSearchWildCardExpression","uuidv4"],"sources":["../src/constants.ts","../src/lib/proxy.ts","../src/lib/password.ts","../src/oauth/helpers.ts","../src/oauth/store.ts","../src/oauth/server.ts","../src/projectAPI.ts","../src/schemas/generated/common.ts","../src/schemas/generated/product-tailoring.ts","../src/repositories/errors.ts","../src/repositories/helpers.ts","../src/repositories/abstract.ts","../src/repositories/product-tailoring.ts","../src/repositories/approval-flow.ts","../src/repositories/approval-rule.ts","../src/schemas/generated/business-unit.ts","../src/repositories/business-unit.ts","../src/lib/tax.ts","../src/schemas/generated/cart.ts","../src/shipping.ts","../src/repositories/cart/helpers.ts","../src/repositories/cart/actions.ts","../src/repositories/cart/index.ts","../src/orderSearch.ts","../src/schemas/generated/order-from-cart.ts","../src/repositories/product/helpers.ts","../src/repositories/order/actions.ts","../src/repositories/order/index.ts","../src/schemas/generated/quote.ts","../src/repositories/quote/actions.ts","../src/repositories/quote/index.ts","../src/schemas/generated/quote-request.ts","../src/repositories/quote-request/actions.ts","../src/repositories/quote-request/index.ts","../src/schemas/generated/shopping-list.ts","../src/repositories/shopping-list/actions.ts","../src/repositories/shopping-list/index.ts","../src/repositories/as-associate.ts","../src/schemas/generated/associate-role.ts","../src/repositories/associate-role.ts","../src/schemas/generated/attribute-group.ts","../src/repositories/attribute-group.ts","../src/schemas/generated/cart-discount.ts","../src/repositories/cart-discount/actions.ts","../src/repositories/cart-discount/index.ts","../src/schemas/generated/category.ts","../src/repositories/category/actions.ts","../src/repositories/category/index.ts","../src/schemas/generated/channel.ts","../src/repositories/channel.ts","../src/schemas/generated/custom-object.ts","../src/repositories/custom-object.ts","../src/schemas/generated/customer.ts","../src/repositories/customer/actions.ts","../src/repositories/customer/index.ts","../src/schemas/generated/customer-group.ts","../src/repositories/customer-group.ts","../src/schemas/generated/discount-code.ts","../src/repositories/discount-code/actions.ts","../src/repositories/discount-code/index.ts","../src/schemas/generated/discount-group.ts","../src/repositories/discount-group/actions.ts","../src/repositories/discount-group/index.ts","../src/schemas/generated/extension.ts","../src/lib/masking.ts","../src/repositories/extension.ts","../src/schemas/generated/inventory-entry.ts","../src/repositories/inventory-entry/actions.ts","../src/repositories/inventory-entry/index.ts","../src/repositories/my-customer.ts","../src/repositories/my-order.ts","../src/schemas/generated/order-edit.ts","../src/repositories/order-edit.ts","../src/schemas/generated/payment.ts","../src/repositories/payment/helpers.ts","../src/repositories/payment/actions.ts","../src/repositories/payment/index.ts","../src/lib/review-statistics.ts","../src/lib/projectionSearchFilter.ts","../src/lib/productSearchFilter.ts","../src/lib/searchQueryTypeChecker.ts","../src/priceSelector.ts","../src/product-search.ts","../src/schemas/generated/product.ts","../src/repositories/product/actions.ts","../src/repositories/product/index.ts","../src/schemas/generated/product-discount.ts","../src/repositories/product-discount.ts","../src/product-projection-search.ts","../src/repositories/product-projection.ts","../src/schemas/generated/product-selection.ts","../src/repositories/product-selection.ts","../src/schemas/generated/product-type.ts","../src/repositories/product-type.ts","../src/repositories/project.ts","../src/schemas/generated/staged-quote.ts","../src/repositories/quote-staged/actions.ts","../src/repositories/quote-staged/index.ts","../src/schemas/generated/recurrence-policy.ts","../src/repositories/recurrence-policy/actions.ts","../src/repositories/recurrence-policy/index.ts","../src/schemas/generated/recurring-order.ts","../src/repositories/recurring-order/actions.ts","../src/repositories/recurring-order/index.ts","../src/schemas/generated/review.ts","../src/repositories/review.ts","../src/schemas/generated/shipping-method.ts","../src/repositories/shipping-method/helpers.ts","../src/repositories/shipping-method/actions.ts","../src/repositories/shipping-method/index.ts","../src/schemas/generated/standalone-price.ts","../src/repositories/standalone-price.ts","../src/schemas/generated/state.ts","../src/repositories/state.ts","../src/schemas/generated/store.ts","../src/repositories/store.ts","../src/schemas/generated/subscription.ts","../src/repositories/subscription.ts","../src/schemas/generated/tax-category.ts","../src/repositories/tax-category/helpers.ts","../src/repositories/tax-category/actions.ts","../src/repositories/tax-category/index.ts","../src/schemas/generated/type.ts","../src/repositories/type/actions.ts","../src/repositories/type/index.ts","../src/schemas/generated/zone.ts","../src/repositories/zone.ts","../src/repositories/index.ts","../src/schemas/update-request.ts","../src/validate.ts","../src/services/abstract.ts","../src/services/approval-flow.ts","../src/services/approval-rule.ts","../src/services/as-associate-approval-flow.ts","../src/services/as-associate-approval-rule.ts","../src/services/as-associate-business-unit.ts","../src/services/as-associate-cart.ts","../src/services/as-associate-order.ts","../src/services/as-associate-quote.ts","../src/services/as-associate-quote-request.ts","../src/services/as-associate-shopping-list.ts","../src/services/as-associate.ts","../src/services/associate-roles.ts","../src/services/attribute-group.ts","../src/services/business-units.ts","../src/services/cart.ts","../src/services/cart-discount.ts","../src/services/category.ts","../src/services/channel.ts","../src/services/custom-object.ts","../src/services/customer.ts","../src/services/customer-group.ts","../src/services/discount-code.ts","../src/services/discount-group.ts","../src/services/extension.ts","../src/services/inventory-entry.ts","../src/services/my-business-unit.ts","../src/services/my-cart.ts","../src/services/my-customer.ts","../src/schemas/generated/my-order-from-quote.ts","../src/services/my-order.ts","../src/services/my-payment.ts","../src/services/my-shopping-list.ts","../src/schemas/generated/order-from-quote.ts","../src/services/order.ts","../src/services/payment.ts","../src/services/product.ts","../src/services/product-discount.ts","../src/services/product-projection.ts","../src/services/product-selection.ts","../src/services/product-type.ts","../src/services/quote.ts","../src/services/quote-request.ts","../src/services/quote-staged.ts","../src/services/recurrence-policy.ts","../src/services/recurring-order.ts","../src/services/reviews.ts","../src/services/shipping-method.ts","../src/services/shopping-list.ts","../src/services/standalone-price.ts","../src/services/state.ts","../src/services/store.ts","../src/services/subscription.ts","../src/services/tax-category.ts","../src/services/type.ts","../src/services/zone.ts","../src/services/index.ts","../src/services/project.ts","../src/storage/storage-map.ts","../src/storage/in-memory.ts","../src/ctMock.ts"],"sourcesContent":["export const DEFAULT_API_HOSTNAME = \"https://api.*.commercetools.com\";\nexport const DEFAULT_AUTH_HOSTNAME = \"https://auth.*.commercetools.com\";\n","export const copyHeaders = (headers: Headers) => {\n\tconst validHeaders = [\"accept\", \"host\", \"authorization\", \"content-type\"];\n\tconst result: Record<string, string> = {};\n\n\tfor (const [key, value] of headers.entries()) {\n\t\tif (validHeaders.includes(key.toLowerCase())) {\n\t\t\tresult[key] = value;\n\t\t}\n\t}\n\n\treturn result;\n};\n","import type { Customer } from \"@commercetools/platform-sdk\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nconst PWRESET_SECRET = \"pwreset\";\nconst EMAIL_VERIFY_SECRET = \"emailverifysecret\";\n\nexport const validatePassword = (\n\tclearPassword: string,\n\thashedPassword: string,\n) => hashPassword(clearPassword) === hashedPassword;\n\nexport const hashPassword = (clearPassword: string) =>\n\tBuffer.from(clearPassword).toString(\"base64\");\n\nexport const createPasswordResetToken = (customer: Customer, expiresAt: Date) =>\n\tBuffer.from(\n\t\t`${customer.id}:${PWRESET_SECRET}:${expiresAt.getTime()}`,\n\t).toString(\"base64\");\n\nexport const createEmailVerifyToken = (customer: Customer) =>\n\tBuffer.from(`${customer.id}:${EMAIL_VERIFY_SECRET}:${uuidv4()}`).toString(\n\t\t\"base64\",\n\t);\n\nexport const validatePasswordResetToken = (token: string) => {\n\tconst items = Buffer.from(token, \"base64\").toString(\"utf-8\").split(\":\");\n\tconst [customerId, secret, time] = items;\n\n\tif (secret !== PWRESET_SECRET) {\n\t\treturn undefined;\n\t}\n\n\t// Check if the token is expired\n\tif (Number.parseInt(time, 10) < Date.now()) {\n\t\treturn undefined;\n\t}\n\n\treturn customerId;\n};\n\nexport const validateEmailVerifyToken = (token: string) => {\n\tconst items = Buffer.from(token, \"base64\").toString(\"utf-8\").split(\":\");\n\tconst [customerId, secret] = items;\n\tif (secret !== EMAIL_VERIFY_SECRET) {\n\t\treturn undefined;\n\t}\n\n\treturn customerId;\n};\n","import type { FastifyRequest } from \"fastify\";\n\nexport const getBearerToken = (request: FastifyRequest): string | undefined => {\n\tconst authHeader = request.headers.authorization;\n\tconst normalizedAuthHeader = Array.isArray(authHeader)\n\t\t? authHeader[0]\n\t\t: authHeader;\n\tconst match = normalizedAuthHeader?.match(/^Bearer\\s(?<token>[^\\s]+)$/);\n\tif (match) {\n\t\treturn match.groups?.token;\n\t}\n\treturn undefined;\n};\n","import { randomBytes } from \"node:crypto\";\nimport { v4 as uuidv4 } from \"uuid\";\n\ntype Token = {\n\taccess_token: string;\n\ttoken_type: \"Bearer\";\n\texpires_in: number;\n\tscope: string;\n\trefresh_token?: string;\n};\n\nexport class OAuth2Store {\n\ttokens: Token[] = [];\n\tprivate tokenClientMap: Map<string, string> = new Map();\n\n\tvalidate = true;\n\n\tconstructor(validate = true) {\n\t\tthis.validate = validate;\n\t}\n\n\taddToken(token: Token, clientId?: string) {\n\t\tthis.tokens.push(token);\n\t\tif (clientId) {\n\t\t\tthis.tokenClientMap.set(token.access_token, clientId);\n\t\t}\n\t}\n\n\tgetClientIdForToken(accessToken: string): string | undefined {\n\t\treturn this.tokenClientMap.get(accessToken);\n\t}\n\n\tgetClientToken(clientId: string, clientSecret: string, scope?: string) {\n\t\tconst token: Token = {\n\t\t\taccess_token: randomBytes(16).toString(\"base64\"),\n\t\t\ttoken_type: \"Bearer\",\n\t\t\texpires_in: 172800,\n\t\t\tscope: scope || \"todo\",\n\t\t\trefresh_token: `my-project-${randomBytes(16).toString(\"base64\")}`,\n\t\t};\n\t\tthis.addToken(token, clientId);\n\t\treturn token;\n\t}\n\n\tgetAnonymousToken(\n\t\tprojectKey: string,\n\t\tanonymousId: string | undefined,\n\t\tscope: string,\n\t\tclientId?: string,\n\t) {\n\t\tif (!anonymousId) {\n\t\t\tanonymousId = uuidv4();\n\t\t}\n\t\tconst token: Token = {\n\t\t\taccess_token: randomBytes(16).toString(\"base64\"),\n\t\t\ttoken_type: \"Bearer\",\n\t\t\texpires_in: 172800,\n\t\t\tscope: scope\n\t\t\t\t? `${scope} anonymous_id:${anonymousId}`\n\t\t\t\t: `anonymous_id:${anonymousId}`,\n\t\t\trefresh_token: `${projectKey}:${randomBytes(16).toString(\"base64\")}`,\n\t\t};\n\t\tthis.addToken(token, clientId);\n\t\treturn token;\n\t}\n\n\tgetCustomerToken(\n\t\tprojectKey: string,\n\t\tcustomerId: string,\n\t\tscope: string,\n\t\tclientId?: string,\n\t) {\n\t\tconst token: Token = {\n\t\t\taccess_token: randomBytes(16).toString(\"base64\"),\n\t\t\ttoken_type: \"Bearer\",\n\t\t\texpires_in: 172800,\n\t\t\tscope: scope\n\t\t\t\t? `${scope} customer_id:${customerId}`\n\t\t\t\t: `customer_id:${customerId}`,\n\t\t\trefresh_token: `${projectKey}:${randomBytes(16).toString(\"base64\")}`,\n\t\t};\n\t\tthis.addToken(token, clientId);\n\t\treturn token;\n\t}\n\n\trefreshToken(clientId: string, clientSecret: string, refreshToken: string) {\n\t\tconst existing = this.tokens.find((t) => t.refresh_token === refreshToken);\n\t\tif (!existing) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst token: Token = {\n\t\t\t...existing,\n\t\t\taccess_token: randomBytes(16).toString(\"base64\"),\n\t\t};\n\t\tthis.addToken(token, clientId);\n\n\t\t// We don't want to return the refresh_token again\n\t\treturn {\n\t\t\taccess_token: token.access_token,\n\t\t\ttoken_type: token.token_type,\n\t\t\texpires_in: token.expires_in,\n\t\t\tscope: token.scope,\n\t\t};\n\t}\n\n\tvalidateToken(token: string) {\n\t\tif (!this.validate) return true;\n\n\t\tconst foundToken = this.tokens.find((t) => t.access_token === token);\n\t\tif (foundToken) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n}\n","import type { InvalidTokenError } from \"@commercetools/platform-sdk\";\nimport { parse as parseBasicAuth } from \"basic-auth\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport type { AuthError, InvalidRequestError } from \"#src/exceptions.ts\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { hashPassword } from \"../lib/password.ts\";\nimport type { CustomerRepository } from \"../repositories/customer/index.ts\";\nimport type { InvalidClientError, UnsupportedGrantType } from \"./errors.ts\";\nimport { getBearerToken } from \"./helpers.ts\";\nimport { OAuth2Store } from \"./store.ts\";\n\ndeclare module \"fastify\" {\n\tinterface FastifyRequest {\n\t\tcredentials?: {\n\t\t\tclientId: string;\n\t\t\tclientSecret: string;\n\t\t};\n\t}\n}\n\nexport type Token = {\n\taccess_token: string;\n\ttoken_type: \"Bearer\";\n\texpires_in: number;\n\tscope: string;\n\trefresh_token?: string;\n};\n\nexport class OAuth2Server {\n\tstore: OAuth2Store;\n\n\tprivate customerRepository: CustomerRepository;\n\tprivate options: { enabled: boolean; validate: boolean };\n\n\tconstructor(options: { enabled: boolean; validate: boolean }) {\n\t\tthis.options = options;\n\t\tthis.store = new OAuth2Store(options.validate);\n\t}\n\n\tsetCustomerRepository(repository: CustomerRepository) {\n\t\tthis.customerRepository = repository;\n\t}\n\n\tcreatePlugin() {\n\t\treturn async (instance: FastifyInstance) => {\n\t\t\tawait instance.register(import(\"@fastify/formbody\"));\n\t\t\tinstance.decorateRequest(\"credentials\", undefined);\n\t\t\tinstance.addHook(\"preHandler\", this.validateClientCredentials.bind(this));\n\t\t\tinstance.post(\"/token\", this.tokenHandler.bind(this));\n\t\t\tinstance.post(\n\t\t\t\t\"/:projectKey/customers/token\",\n\t\t\t\tthis.customerTokenHandler.bind(this),\n\t\t\t);\n\t\t\tinstance.post(\n\t\t\t\t\"/:projectKey/in-store/key=:storeKey/customers/token\",\n\t\t\t\tthis.inStoreCustomerTokenHandler.bind(this),\n\t\t\t);\n\t\t\tinstance.post(\n\t\t\t\t\"/:projectKey/anonymous/token\",\n\t\t\t\tthis.anonymousTokenHandler.bind(this),\n\t\t\t);\n\t\t};\n\t}\n\n\tcreateMiddleware() {\n\t\tif (!this.options.validate) {\n\t\t\treturn async (request: FastifyRequest, reply: FastifyReply) => {\n\t\t\t\t// When validation is disabled, still populate credentials\n\t\t\t\t// so createdBy/lastModifiedBy can be set on resources\n\t\t\t\tconst token = getBearerToken(request);\n\t\t\t\tconst clientId = token\n\t\t\t\t\t? this.store.getClientIdForToken(token)\n\t\t\t\t\t: undefined;\n\t\t\t\trequest.credentials = {\n\t\t\t\t\tclientId: clientId ?? \"\",\n\t\t\t\t\tclientSecret: \"\",\n\t\t\t\t};\n\t\t\t};\n\t\t}\n\n\t\treturn async (request: FastifyRequest, reply: FastifyReply) => {\n\t\t\tconst token = getBearerToken(request);\n\t\t\tif (!token) {\n\t\t\t\tthrow new CommercetoolsError<InvalidTokenError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"invalid_token\",\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\"This endpoint requires an access token. You can get one from the authorization server.\",\n\t\t\t\t\t},\n\t\t\t\t\t401,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (!token || !this.store.validateToken(token)) {\n\t\t\t\tthrow new CommercetoolsError<InvalidTokenError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"invalid_token\",\n\t\t\t\t\t\tmessage: \"invalid_token\",\n\t\t\t\t\t},\n\t\t\t\t\t401,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Populate credentials so createdBy/lastModifiedBy can be set\n\t\t\tconst clientId = this.store.getClientIdForToken(token);\n\t\t\trequest.credentials = {\n\t\t\t\tclientId: clientId ?? \"\",\n\t\t\t\tclientSecret: \"\",\n\t\t\t};\n\t\t};\n\t}\n\n\tasync validateClientCredentials(\n\t\trequest: FastifyRequest,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst authHeader = request.headers.authorization;\n\t\tif (!authHeader) {\n\t\t\tthrow new CommercetoolsError<InvalidClientError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid_client\",\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t\"Please provide valid client credentials using HTTP Basic Authentication.\",\n\t\t\t\t},\n\t\t\t\t401,\n\t\t\t);\n\t\t}\n\t\tconst credentials = parseBasicAuth(authHeader);\n\t\tif (!credentials) {\n\t\t\tthrow new CommercetoolsError<InvalidClientError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid_client\",\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t\"Please provide valid client credentials using HTTP Basic Authentication.\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\trequest.credentials = {\n\t\t\tclientId: credentials.name,\n\t\t\tclientSecret: credentials.pass,\n\t\t};\n\t}\n\n\tasync tokenHandler(\n\t\trequest: FastifyRequest<{\n\t\t\tQuerystring: Record<string, any>;\n\t\t\tBody: Record<string, any>;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tif (!request.credentials) {\n\t\t\tthrow new CommercetoolsError<InvalidClientError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid_client\",\n\t\t\t\t\tmessage: \"Client credentials are missing.\",\n\t\t\t\t},\n\t\t\t\t401,\n\t\t\t);\n\t\t}\n\n\t\tconst query = request.query;\n\t\tconst body = request.body;\n\t\tconst grantType = query.grant_type || body?.grant_type;\n\t\tif (!grantType) {\n\t\t\tthrow new CommercetoolsError<InvalidRequestError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid_request\",\n\t\t\t\t\tmessage: \"Missing required parameter: grant_type.\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\tif (grantType === \"client_credentials\") {\n\t\t\tconst token = this.store.getClientToken(\n\t\t\t\trequest.credentials.clientId,\n\t\t\t\trequest.credentials.clientSecret,\n\t\t\t\tquery.scope?.toString(),\n\t\t\t);\n\t\t\treturn reply.status(200).send(token);\n\t\t}\n\t\tif (grantType === \"refresh_token\") {\n\t\t\tconst refreshToken =\n\t\t\t\tquery.refresh_token?.toString() || body?.refresh_token;\n\t\t\tif (!refreshToken) {\n\t\t\t\tthrow new CommercetoolsError<InvalidRequestError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"invalid_request\",\n\t\t\t\t\t\tmessage: \"Missing required parameter: refresh_token.\",\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst token = this.store.refreshToken(\n\t\t\t\trequest.credentials.clientId,\n\t\t\t\trequest.credentials.clientSecret,\n\t\t\t\trefreshToken,\n\t\t\t);\n\t\t\tif (!token) {\n\t\t\t\tthrow new CommercetoolsError<AuthError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tstatusCode: 400,\n\t\t\t\t\t\tmessage: \"The refresh token was not found. It may have expired.\",\n\t\t\t\t\t\terror: \"invalid_grant\",\n\t\t\t\t\t\terror_description:\n\t\t\t\t\t\t\t\"The refresh token was not found. It may have expired.\",\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn reply.status(200).send(token);\n\t\t}\n\t\tthrow new CommercetoolsError<UnsupportedGrantType>(\n\t\t\t{\n\t\t\t\tcode: \"unsupported_grant_type\",\n\t\t\t\tmessage: `Invalid parameter: grant_type: Invalid grant type: ${grantType}`,\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\tasync customerTokenHandler(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tQuerystring: Record<string, any>;\n\t\t\tBody: Record<string, any>;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst params = request.params;\n\t\tconst query = request.query;\n\t\tconst body = request.body;\n\t\tconst projectKey = params.projectKey;\n\t\tconst grantType = query.grant_type || body?.grant_type;\n\t\tif (!grantType) {\n\t\t\tthrow new CommercetoolsError<InvalidRequestError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid_request\",\n\t\t\t\t\tmessage: \"Missing required parameter: grant_type.\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\tif (grantType === \"password\") {\n\t\t\tconst username = query.username || body?.username;\n\t\t\tconst password = hashPassword(query.password || body.password);\n\t\t\tconst scope = query.scope?.toString() || body?.scope?.toString();\n\n\t\t\tconst result = await this.customerRepository.query(\n\t\t\t\t{ projectKey: params.projectKey },\n\t\t\t\t{\n\t\t\t\t\twhere: [`email = \"${username}\"`, `password = \"${password}\"`],\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tif (result.count === 0) {\n\t\t\t\tthrow new CommercetoolsError<any>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"invalid_customer_account_credentials\",\n\t\t\t\t\t\tmessage: \"Customer account with the given credentials not found.\",\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst customer = result.results[0];\n\t\t\tconst token = this.store.getCustomerToken(\n\t\t\t\tprojectKey,\n\t\t\t\tcustomer.id,\n\t\t\t\tscope,\n\t\t\t\trequest.credentials?.clientId,\n\t\t\t);\n\t\t\treturn reply.status(200).send(token);\n\t\t}\n\t}\n\n\tasync inStoreCustomerTokenHandler(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tQuerystring: Record<string, any>;\n\t\t\tBody: Record<string, any>;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst params = request.params;\n\t\tconst query = request.query;\n\t\tconst body = request.body;\n\t\tconst projectKey = params.projectKey;\n\t\tconst storeKey = params.storeKey;\n\t\tconst grantType = query.grant_type || body.grant_type;\n\t\tif (!grantType) {\n\t\t\tthrow new CommercetoolsError<InvalidRequestError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid_request\",\n\t\t\t\t\tmessage: \"Missing required parameter: grant_type.\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\tif (grantType === \"password\") {\n\t\t\tconst username = query.username || body.username;\n\t\t\tconst password = hashPassword(query.password || body.password);\n\t\t\tconst scope = query.scope?.toString() || body.scope?.toString();\n\n\t\t\tconst result = await this.customerRepository.query(\n\t\t\t\t{ projectKey, storeKey },\n\t\t\t\t{\n\t\t\t\t\twhere: [`email = \"${username}\"`, `password = \"${password}\"`],\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tif (result.count === 0) {\n\t\t\t\tthrow new CommercetoolsError<any>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"invalid_customer_account_credentials\",\n\t\t\t\t\t\tmessage: \"Customer account with the given credentials not found.\",\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst customer = result.results[0];\n\t\t\tconst token = this.store.getCustomerToken(\n\t\t\t\tprojectKey,\n\t\t\t\tcustomer.id,\n\t\t\t\tscope,\n\t\t\t\trequest.credentials?.clientId,\n\t\t\t);\n\t\t\treturn reply.status(200).send(token);\n\t\t}\n\t}\n\n\tasync anonymousTokenHandler(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tQuerystring: Record<string, any>;\n\t\t\tBody: Record<string, any>;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst params = request.params;\n\t\tconst query = request.query;\n\t\tconst body = request.body;\n\t\tconst projectKey = params.projectKey;\n\t\tconst grantType = query.grant_type || body.grant_type;\n\t\tif (!grantType) {\n\t\t\tthrow new CommercetoolsError<InvalidRequestError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid_request\",\n\t\t\t\t\tmessage: \"Missing required parameter: grant_type.\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\tif (grantType === \"client_credentials\") {\n\t\t\tconst scope = query.scope?.toString() || body?.scope?.toString();\n\n\t\t\tconst anonymous_id = undefined;\n\n\t\t\tconst token = this.store.getAnonymousToken(\n\t\t\t\tprojectKey,\n\t\t\t\tanonymous_id,\n\t\t\t\tscope,\n\t\t\t\trequest.credentials?.clientId,\n\t\t\t);\n\t\t\treturn reply.status(200).send(token);\n\t\t}\n\t}\n}\n","import type { Config } from \"./config.ts\";\nimport { getBaseResourceProperties } from \"./helpers.ts\";\nimport type { GetParams } from \"./repositories/abstract.ts\";\nimport type { RepositoryMap } from \"./repositories/index.ts\";\nimport type { AbstractStorage } from \"./storage/index.ts\";\nimport type { ResourceMap, ResourceType } from \"./types.ts\";\n\nexport class ProjectAPI {\n\tprivate projectKey: string;\n\n\tprivate _storage: AbstractStorage;\n\n\tprivate _repositories: RepositoryMap;\n\n\treadonly config: Config;\n\n\tconstructor(projectKey: string, repositories: RepositoryMap, config: Config) {\n\t\tthis.projectKey = projectKey;\n\t\tthis.config = config;\n\t\tthis._storage = config.storage;\n\t\tthis._repositories = repositories;\n\t}\n\n\tasync unsafeAdd<T extends keyof RepositoryMap & keyof ResourceMap>(\n\t\ttypeId: T,\n\t\tresource: ResourceMap[T],\n\t) {\n\t\tconst repository = this._repositories[typeId];\n\t\tif (repository) {\n\t\t\tawait this._storage.add(this.projectKey, typeId, {\n\t\t\t\t...getBaseResourceProperties(),\n\t\t\t\t...resource,\n\t\t\t});\n\t\t} else {\n\t\t\tthrow new Error(`Service for ${typeId} not implemented yet`);\n\t\t}\n\t}\n\n\tasync get<RT extends ResourceType>(\n\t\ttypeId: RT,\n\t\tid: string,\n\t\tparams?: GetParams,\n\t): Promise<ResourceMap[RT]> {\n\t\tconst result = await this._storage.get(this.projectKey, typeId, id, params);\n\t\treturn result as ResourceMap[RT];\n\t}\n\n\t// TODO: Not sure if we want to expose this...\n\tgetRepository<RT extends keyof RepositoryMap>(typeId: RT): RepositoryMap[RT] {\n\t\tconst repository = this._repositories[typeId];\n\t\tif (repository !== undefined) {\n\t\t\treturn repository as RepositoryMap[RT];\n\t\t}\n\t\tthrow new Error(\"No such repository\");\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\n\nexport const PermissionSchema = z.enum([\n\t\"AddChildUnits\",\n\t\"UpdateAssociates\",\n\t\"UpdateBusinessUnitDetails\",\n\t\"UpdateParentUnit\",\n\t\"ViewMyCarts\",\n\t\"ViewOthersCarts\",\n\t\"UpdateMyCarts\",\n\t\"UpdateOthersCarts\",\n\t\"CreateMyCarts\",\n\t\"CreateOthersCarts\",\n\t\"DeleteMyCarts\",\n\t\"DeleteOthersCarts\",\n\t\"ViewMyOrders\",\n\t\"ViewOthersOrders\",\n\t\"UpdateMyOrders\",\n\t\"UpdateOthersOrders\",\n\t\"CreateMyOrdersFromMyCarts\",\n\t\"CreateMyOrdersFromMyQuotes\",\n\t\"CreateOrdersFromOthersCarts\",\n\t\"CreateOrdersFromOthersQuotes\",\n\t\"ViewMyQuotes\",\n\t\"ViewOthersQuotes\",\n\t\"AcceptMyQuotes\",\n\t\"AcceptOthersQuotes\",\n\t\"DeclineMyQuotes\",\n\t\"DeclineOthersQuotes\",\n\t\"RenegotiateMyQuotes\",\n\t\"RenegotiateOthersQuotes\",\n\t\"ReassignMyQuotes\",\n\t\"ReassignOthersQuotes\",\n\t\"ViewMyQuoteRequests\",\n\t\"ViewOthersQuoteRequests\",\n\t\"UpdateMyQuoteRequests\",\n\t\"UpdateOthersQuoteRequests\",\n\t\"CreateMyQuoteRequestsFromMyCarts\",\n\t\"CreateQuoteRequestsFromOthersCarts\",\n\t\"CreateApprovalRules\",\n\t\"UpdateApprovalRules\",\n\t\"UpdateApprovalFlows\",\n\t\"ViewMyShoppingLists\",\n\t\"ViewOthersShoppingLists\",\n\t\"UpdateMyShoppingLists\",\n\t\"UpdateOthersShoppingLists\",\n\t\"CreateMyShoppingLists\",\n\t\"CreateOthersShoppingLists\",\n\t\"DeleteMyShoppingLists\",\n\t\"DeleteOthersShoppingLists\",\n]);\n\nexport const ReferenceTypeIdSchema = z.enum([\n\t\"approval-flow\",\n\t\"approval-rule\",\n\t\"associate-role\",\n\t\"attribute-group\",\n\t\"business-unit\",\n\t\"cart\",\n\t\"cart-discount\",\n\t\"category\",\n\t\"channel\",\n\t\"customer\",\n\t\"customer-email-token\",\n\t\"customer-group\",\n\t\"customer-password-token\",\n\t\"direct-discount\",\n\t\"discount-code\",\n\t\"discount-group\",\n\t\"extension\",\n\t\"inventory-entry\",\n\t\"key-value-document\",\n\t\"order\",\n\t\"order-edit\",\n\t\"payment-method\",\n\t\"payment\",\n\t\"product\",\n\t\"product-discount\",\n\t\"product-price\",\n\t\"product-selection\",\n\t\"product-tailoring\",\n\t\"product-type\",\n\t\"quote\",\n\t\"quote-request\",\n\t\"recurrence-policy\",\n\t\"recurring-order\",\n\t\"reservation\",\n\t\"review\",\n\t\"shipping-method\",\n\t\"shopping-list\",\n\t\"staged-quote\",\n\t\"standalone-price\",\n\t\"state\",\n\t\"store\",\n\t\"subscription\",\n\t\"tax-category\",\n\t\"type\",\n\t\"variant\",\n\t\"zone\",\n]);\n\nexport const BusinessUnitStatusSchema = z.enum([\"Active\", \"Inactive\"]);\n\nexport const BusinessUnitStoreModeSchema = z.enum([\"Explicit\", \"FromParent\"]);\n\nexport const BusinessUnitTypeSchema = z.enum([\"Company\", \"Division\"]);\n\nexport const BusinessUnitAssociateModeSchema = z.enum([\n\t\"Explicit\",\n\t\"ExplicitAndFromParent\",\n]);\n\nexport const AssociateRoleInheritanceModeSchema = z.enum([\n\t\"Enabled\",\n\t\"Disabled\",\n]);\n\nexport const AssociateRoleDeprecatedSchema = z.enum([\"Admin\", \"Buyer\"]);\n\nexport const BusinessUnitApprovalRuleModeSchema = z.enum([\n\t\"Explicit\",\n\t\"ExplicitAndFromParent\",\n]);\n\nexport const InventoryModeSchema = z.enum([\n\t\"None\",\n\t\"TrackOnly\",\n\t\"ReserveOnOrder\",\n\t\"ReserveOnCart\",\n]);\n\nexport const PriceSelectionModeSchema = z.enum([\"Fixed\", \"Dynamic\"]);\n\nexport const CustomLineItemPriceModeSchema = z.enum([\"Standard\", \"External\"]);\n\nexport const TaxModeSchema = z.enum([\n\t\"Platform\",\n\t\"External\",\n\t\"ExternalAmount\",\n\t\"Disabled\",\n]);\n\nexport const RoundingModeSchema = z.enum([\"HalfEven\", \"HalfUp\", \"HalfDown\"]);\n\nexport const TaxCalculationModeSchema = z.enum([\n\t\"LineItemLevel\",\n\t\"UnitPriceLevel\",\n]);\n\nexport const ShippingModeSchema = z.enum([\"Single\", \"Multiple\"]);\n\nexport const ShippingRateTierTypeSchema = z.enum([\n\t\"CartValue\",\n\t\"CartClassification\",\n\t\"CartScore\",\n]);\n\nexport const CartOriginSchema = z.enum([\n\t\"Customer\",\n\t\"Merchant\",\n\t\"Quote\",\n\t\"RecurringOrder\",\n]);\n\nexport const DiscountApplicationModeSchema = z.enum([\n\t\"ProportionateDistribution\",\n\t\"EvenDistribution\",\n\t\"IndividualApplication\",\n]);\n\nexport const MoneyTypeSchema = z.enum([\"centPrecision\", \"highPrecision\"]);\n\nexport const StackingModeSchema = z.enum([\"Stacking\", \"StopAfterThisDiscount\"]);\n\nexport const ChannelRoleEnumSchema = z.enum([\n\t\"InventorySupply\",\n\t\"ProductDistribution\",\n\t\"OrderExport\",\n\t\"OrderImport\",\n\t\"Primary\",\n]);\n\nexport const AuthenticationModeSchema = z.enum([\"Password\", \"ExternalAuth\"]);\n\nexport const ExtensionResourceTypeIdSchema = z.enum([\n\t\"cart\",\n\t\"order\",\n\t\"payment\",\n\t\"payment-method\",\n\t\"customer\",\n\t\"customer-group\",\n\t\"quote-request\",\n\t\"staged-quote\",\n\t\"quote\",\n\t\"business-unit\",\n\t\"shopping-list\",\n]);\n\nexport const ExtensionActionSchema = z.enum([\"Create\", \"Update\"]);\n\nexport const PaymentStateSchema = z.enum([\n\t\"BalanceDue\",\n\t\"Failed\",\n\t\"Pending\",\n\t\"CreditOwed\",\n\t\"Paid\",\n]);\n\nexport const ShipmentStateSchema = z.enum([\n\t\"Shipped\",\n\t\"Delivered\",\n\t\"Ready\",\n\t\"Pending\",\n\t\"Delayed\",\n\t\"Partial\",\n\t\"Backorder\",\n\t\"Canceled\",\n]);\n\nexport const OrderStateSchema = z.enum([\n\t\"Open\",\n\t\"Confirmed\",\n\t\"Complete\",\n\t\"Cancelled\",\n]);\n\nexport const TransactionTypeSchema = z.enum([\n\t\"Authorization\",\n\t\"CancelAuthorization\",\n\t\"Charge\",\n\t\"Refund\",\n\t\"Chargeback\",\n]);\n\nexport const TransactionStateSchema = z.enum([\n\t\"Initial\",\n\t\"Pending\",\n\t\"Success\",\n\t\"Failure\",\n]);\n\nexport const ProductPriceModeEnumSchema = z.enum([\"Embedded\", \"Standalone\"]);\n\nexport const ProductSelectionTypeEnumSchema = z.enum([\n\t\"individual\",\n\t\"individualExclusion\",\n]);\n\nexport const ProductSelectionModeSchema = z.enum([\n\t\"Individual\",\n\t\"IndividualExclusion\",\n]);\n\nexport const AttributeLevelEnumSchema = z.enum([\"Product\", \"Variant\"]);\n\nexport const AttributeConstraintEnumSchema = z.enum([\n\t\"None\",\n\t\"Unique\",\n\t\"CombinationUnique\",\n\t\"SameForAll\",\n]);\n\nexport const TextInputHintSchema = z.enum([\"SingleLine\", \"MultiLine\"]);\n\nexport const IntervalUnitSchema = z.enum([\"Days\", \"Weeks\", \"Months\"]);\n\nexport const StateTypeEnumSchema = z.enum([\n\t\"OrderState\",\n\t\"RecurringOrderState\",\n\t\"LineItemState\",\n\t\"ProductState\",\n\t\"ReviewState\",\n\t\"PaymentState\",\n\t\"QuoteRequestState\",\n\t\"StagedQuoteState\",\n\t\"QuoteState\",\n]);\n\nexport const StateRoleEnumSchema = z.enum([\n\t\"ReviewIncludedInStatistics\",\n\t\"Return\",\n]);\n\nexport const MessageSubscriptionResourceTypeIdSchema = z.enum([\n\t\"approval-flow\",\n\t\"approval-rule\",\n\t\"associate-role\",\n\t\"business-unit\",\n\t\"category\",\n\t\"customer\",\n\t\"customer-email-token\",\n\t\"customer-group\",\n\t\"customer-password-token\",\n\t\"inventory-entry\",\n\t\"order\",\n\t\"payment\",\n\t\"product\",\n\t\"product-selection\",\n\t\"product-tailoring\",\n\t\"quote\",\n\t\"quote-request\",\n\t\"review\",\n\t\"shopping-list\",\n\t\"staged-quote\",\n\t\"standalone-price\",\n\t\"store\",\n]);\n\nexport const ChangeSubscriptionResourceTypeIdSchema = z.enum([\n\t\"approval-flow\",\n\t\"approval-rule\",\n\t\"associate-role\",\n\t\"attribute-group\",\n\t\"business-unit\",\n\t\"cart\",\n\t\"cart-discount\",\n\t\"category\",\n\t\"channel\",\n\t\"customer\",\n\t\"customer-email-token\",\n\t\"customer-group\",\n\t\"customer-password-token\",\n\t\"discount-code\",\n\t\"discount-group\",\n\t\"extension\",\n\t\"inventory-entry\",\n\t\"key-value-document\",\n\t\"order\",\n\t\"order-edit\",\n\t\"payment\",\n\t\"product\",\n\t\"product-discount\",\n\t\"product-selection\",\n\t\"product-tailoring\",\n\t\"product-type\",\n\t\"quote\",\n\t\"quote-request\",\n\t\"recurrence-policy\",\n\t\"recurring-order\",\n\t\"review\",\n\t\"shipping-method\",\n\t\"shopping-list\",\n\t\"staged-quote\",\n\t\"standalone-price\",\n\t\"state\",\n\t\"store\",\n\t\"subscription\",\n\t\"tax-category\",\n\t\"type\",\n\t\"zone\",\n]);\n\nexport const EventSubscriptionResourceTypeIdSchema = z.enum([\n\t\"checkout\",\n\t\"import-api\",\n]);\n\nexport const EventTypeSchema = z.enum([\n\t\"CheckoutOrderCreationFailed\",\n\t\"CheckoutPaymentAuthorizationCancelled\",\n\t\"CheckoutPaymentAuthorizationFailed\",\n\t\"CheckoutPaymentAuthorized\",\n\t\"CheckoutPaymentCancelAuthorizationFailed\",\n\t\"CheckoutPaymentCharged\",\n\t\"CheckoutPaymentChargeFailed\",\n\t\"CheckoutPaymentRefunded\",\n\t\"CheckoutPaymentRefundFailed\",\n\t\"ImportContainerCreated\",\n\t\"ImportContainerDeleted\",\n\t\"ImportOperationRejected\",\n\t\"ImportUnresolved\",\n\t\"ImportValidationFailed\",\n\t\"ImportWaitForMasterVariant\",\n]);\n\nexport const ResourceTypeIdSchema = z.enum([\n\t\"address\",\n\t\"asset\",\n\t\"approval-flow\",\n\t\"approval-rule\",\n\t\"associate-role\",\n\t\"business-unit\",\n\t\"cart-discount\",\n\t\"category\",\n\t\"channel\",\n\t\"customer\",\n\t\"customer-group\",\n\t\"custom-line-item\",\n\t\"discount-code\",\n\t\"inventory-entry\",\n\t\"line-item\",\n\t\"order\",\n\t\"order-edit\",\n\t\"order-delivery\",\n\t\"order-parcel\",\n\t\"order-return-item\",\n\t\"payment\",\n\t\"payment-interface-interaction\",\n\t\"payment-method\",\n\t\"payment-method-info\",\n\t\"product-price\",\n\t\"product-selection\",\n\t\"product-tailoring\",\n\t\"quote\",\n\t\"reservation\",\n\t\"review\",\n\t\"recurring-order\",\n\t\"shipping\",\n\t\"shipping-method\",\n\t\"shopping-list\",\n\t\"shopping-list-text-line-item\",\n\t\"standalone-price\",\n\t\"store\",\n\t\"transaction\",\n]);\n\nexport const TypeTextInputHintSchema = z.enum([\"SingleLine\", \"MultiLine\"]);\n\nexport const CountryCodeSchema = z.string();\n\nexport const CurrencyCodeSchema = z.string();\n\nexport const LocaleSchema = z.string();\n\nexport const TypeResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const FieldContainerSchema = z.record(z.string(), z.unknown());\n\nexport const CustomFieldsDraftSchema = z.object({\n\ttype: TypeResourceIdentifierSchema,\n\tfields: FieldContainerSchema.nullish(),\n});\n\nexport const LocalizedStringSchema = z.record(z.string(), z.string());\n\nexport const AttributeReferenceSchema = z.object({\n\tkey: z.string(),\n});\n\nexport const StoreResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const AssociateRoleResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const AssociateRoleAssignmentDraftSchema = z.object({\n\tassociateRole: AssociateRoleResourceIdentifierSchema,\n\tinheritance: AssociateRoleInheritanceModeSchema.nullish(),\n});\n\nexport const CustomerResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const AssociateDraftSchema = z.object({\n\tassociateRoleAssignments: z.array(AssociateRoleAssignmentDraftSchema),\n\troles: z.array(AssociateRoleDeprecatedSchema).nullish(),\n\tcustomer: CustomerResourceIdentifierSchema,\n});\n\nexport const BaseAddressSchema = z.object({\n\tid: z.string().nullish(),\n\tkey: z.string().nullish(),\n\tcountry: CountryCodeSchema,\n\ttitle: z.string().nullish(),\n\tsalutation: z.string().nullish(),\n\tfirstName: z.string().nullish(),\n\tlastName: z.string().nullish(),\n\tstreetName: z.string().nullish(),\n\tstreetNumber: z.string().nullish(),\n\tadditionalStreetInfo: z.string().nullish(),\n\tpostalCode: z.string().nullish(),\n\tcity: z.string().nullish(),\n\tregion: z.string().nullish(),\n\tstate: z.string().nullish(),\n\tcompany: z.string().nullish(),\n\tdepartment: z.string().nullish(),\n\tbuilding: z.string().nullish(),\n\tapartment: z.string().nullish(),\n\tpOBox: z.string().nullish(),\n\tphone: z.string().nullish(),\n\tmobile: z.string().nullish(),\n\temail: z.string().nullish(),\n\tfax: z.string().nullish(),\n\tadditionalAddressInfo: z.string().nullish(),\n\texternalId: z.string().nullish(),\n});\n\nexport const CustomerGroupResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const CustomerGroupAssignmentDraftSchema = z.object({\n\tcustomerGroup: CustomerGroupResourceIdentifierSchema,\n});\n\nexport const CompanyDraftSchema = z.object({\n\tkey: z.string(),\n\tstatus: BusinessUnitStatusSchema.nullish(),\n\tstores: z.array(StoreResourceIdentifierSchema).nullish(),\n\tstoreMode: BusinessUnitStoreModeSchema.nullish(),\n\tunitType: z.literal(\"Company\"),\n\tname: z.string(),\n\tcontactEmail: z.string().nullish(),\n\tassociateMode: BusinessUnitAssociateModeSchema.nullish(),\n\tassociates: z.array(AssociateDraftSchema).nullish(),\n\tapprovalRuleMode: BusinessUnitApprovalRuleModeSchema.nullish(),\n\taddresses: z.array(BaseAddressSchema).nullish(),\n\tshippingAddresses: z.array(z.number().int()).nullish(),\n\tdefaultShippingAddress: z.number().int().nullish(),\n\tbillingAddresses: z.array(z.number().int()).nullish(),\n\tdefaultBillingAddress: z.number().int().nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\tcustomerGroupAssignments: z\n\t\t.array(CustomerGroupAssignmentDraftSchema)\n\t\t.nullish(),\n});\n\nexport const BusinessUnitResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const DivisionDraftSchema = z.object({\n\tkey: z.string(),\n\tstatus: BusinessUnitStatusSchema.nullish(),\n\tstores: z.array(StoreResourceIdentifierSchema).nullish(),\n\tstoreMode: BusinessUnitStoreModeSchema.nullish(),\n\tunitType: z.literal(\"Division\"),\n\tname: z.string(),\n\tcontactEmail: z.string().nullish(),\n\tassociateMode: BusinessUnitAssociateModeSchema.nullish(),\n\tassociates: z.array(AssociateDraftSchema).nullish(),\n\tapprovalRuleMode: BusinessUnitApprovalRuleModeSchema.nullish(),\n\taddresses: z.array(BaseAddressSchema).nullish(),\n\tshippingAddresses: z.array(z.number().int()).nullish(),\n\tdefaultShippingAddress: z.number().int().nullish(),\n\tbillingAddresses: z.array(z.number().int()).nullish(),\n\tdefaultBillingAddress: z.number().int().nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\tcustomerGroupAssignments: z\n\t\t.array(CustomerGroupAssignmentDraftSchema)\n\t\t.nullish(),\n\tparentUnit: BusinessUnitResourceIdentifierSchema,\n});\n\nexport const ChannelResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const MoneySchema = z.object({\n\tcentAmount: z.number().int(),\n\tcurrencyCode: CurrencyCodeSchema,\n});\n\nexport const ExternalLineItemTotalPriceSchema = z.object({\n\tprice: MoneySchema,\n\ttotalPrice: MoneySchema,\n});\n\nexport const SubRateSchema = z.object({\n\tname: z.string(),\n\tamount: z.number(),\n});\n\nexport const ExternalTaxRateDraftSchema = z.object({\n\tname: z.string(),\n\tamount: z.number().nullish(),\n\tincludedInPrice: z.boolean().nullish(),\n\tcountry: CountryCodeSchema,\n\tstate: z.string().nullish(),\n\tsubRates: z.array(SubRateSchema).nullish(),\n});\n\nexport const MethodExternalTaxRateDraftSchema = z.object({\n\tshippingMethodKey: z.string(),\n\ttaxRate: ExternalTaxRateDraftSchema.nullish(),\n});\n\nexport const ItemShippingTargetSchema = z.object({\n\taddressKey: z.string(),\n\tquantity: z.number().int(),\n\tshippingMethodKey: z.string().nullish(),\n});\n\nexport const ItemShippingDetailsDraftSchema = z.object({\n\ttargets: z.array(ItemShippingTargetSchema),\n});\n\nexport const RecurrencePolicyResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const LineItemRecurrenceInfoDraftSchema = z.object({\n\trecurrencePolicy: RecurrencePolicyResourceIdentifierSchema,\n\tpriceSelectionMode: PriceSelectionModeSchema,\n});\n\nexport const LineItemDraftSchema = z.object({\n\tkey: z.string().nullish(),\n\tproductId: z.string().nullish(),\n\tvariantId: z.number().int().nullish(),\n\tsku: z.string().nullish(),\n\tquantity: z.number().int().nullish(),\n\taddedAt: z.string().nullish(),\n\tdistributionChannel: ChannelResourceIdentifierSchema.nullish(),\n\tsupplyChannel: ChannelResourceIdentifierSchema.nullish(),\n\texternalPrice: MoneySchema.nullish(),\n\texternalTotalPrice: ExternalLineItemTotalPriceSchema.nullish(),\n\texternalTaxRate: ExternalTaxRateDraftSchema.nullish(),\n\tperMethodExternalTaxRate: z.array(MethodExternalTaxRateDraftSchema).nullish(),\n\tinventoryMode: InventoryModeSchema.nullish(),\n\tshippingDetails: ItemShippingDetailsDraftSchema.nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\trecurrenceInfo: LineItemRecurrenceInfoDraftSchema.nullish(),\n});\n\nexport const TaxCategoryResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const CustomLineItemRecurrenceInfoDraftSchema = z.object({\n\trecurrencePolicy: RecurrencePolicyResourceIdentifierSchema,\n});\n\nexport const CustomLineItemDraftSchema = z.object({\n\tname: LocalizedStringSchema,\n\tkey: z.string().nullish(),\n\tquantity: z.number().int().nullish(),\n\tmoney: MoneySchema,\n\tslug: z.string(),\n\ttaxCategory: TaxCategoryResourceIdentifierSchema.nullish(),\n\texternalTaxRate: ExternalTaxRateDraftSchema.nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\tshippingDetails: ItemShippingDetailsDraftSchema.nullish(),\n\tpriceMode: CustomLineItemPriceModeSchema.nullish(),\n\trecurrenceInfo: CustomLineItemRecurrenceInfoDraftSchema.nullish(),\n});\n\nexport const ShippingMethodResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const ClassificationShippingRateInputDraftSchema = z.object({\n\ttype: z.literal(\"Classification\"),\n\tkey: z.string(),\n});\n\nexport const ScoreShippingRateInputDraftSchema = z.object({\n\ttype: z.literal(\"Score\"),\n\tscore: z.number().int(),\n});\n\nexport const ShippingRateInputDraftSchema = z.discriminatedUnion(\"type\", [\n\tClassificationShippingRateInputDraftSchema,\n\tScoreShippingRateInputDraftSchema,\n]);\n\nexport const CartClassificationTierSchema = z.object({\n\ttype: z.literal(\"CartClassification\"),\n\tvalue: z.string(),\n\tprice: MoneySchema,\n\tisMatching: z.boolean().nullish(),\n});\n\nexport const PriceFunctionSchema = z.object({\n\tcurrencyCode: CurrencyCodeSchema,\n\tfunction: z.string(),\n});\n\nexport const CartScoreTierSchema = z.object({\n\ttype: z.literal(\"CartScore\"),\n\tscore: z.number().int(),\n\tprice: MoneySchema.nullish(),\n\tpriceFunction: PriceFunctionSchema.nullish(),\n\tisMatching: z.boolean().nullish(),\n});\n\nexport const CartValueTierSchema = z.object({\n\ttype: z.literal(\"CartValue\"),\n\tminimumCentAmount: z.number().int(),\n\tprice: MoneySchema,\n\tisMatching: z.boolean().nullish(),\n});\n\nexport const ShippingRatePriceTierSchema = z.discriminatedUnion(\"type\", [\n\tCartClassificationTierSchema,\n\tCartScoreTierSchema,\n\tCartValueTierSchema,\n]);\n\nexport const ShippingRateDraftSchema = z.object({\n\tprice: MoneySchema,\n\tfreeAbove: MoneySchema.nullish(),\n\ttiers: z.array(ShippingRatePriceTierSchema).nullish(),\n});\n\nexport const DeliveryItemSchema = z.object({\n\tid: z.string(),\n\tquantity: z.number().int(),\n});\n\nexport const ParcelMeasurementsSchema = z.object({\n\theightInMillimeter: z.number().int().nullish(),\n\tlengthInMillimeter: z.number().int().nullish(),\n\twidthInMillimeter: z.number().int().nullish(),\n\tweightInGram: z.number().int().nullish(),\n});\n\nexport const TrackingDataSchema = z.object({\n\ttrackingId: z.string().nullish(),\n\tcarrier: z.string().nullish(),\n\tprovider: z.string().nullish(),\n\tproviderTransaction: z.string().nullish(),\n\tisReturn: z.boolean().nullish(),\n});\n\nexport const ParcelDraftSchema = z.object({\n\tkey: z.string().nullish(),\n\tmeasurements: ParcelMeasurementsSchema.nullish(),\n\ttrackingData: TrackingDataSchema.nullish(),\n\titems: z.array(DeliveryItemSchema).nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n});\n\nexport const AddressDraftSchema = z.object({\n\tid: z.string().nullish(),\n\tkey: z.string().nullish(),\n\tcountry: CountryCodeSchema,\n\ttitle: z.string().nullish(),\n\tsalutation: z.string().nullish(),\n\tfirstName: z.string().nullish(),\n\tlastName: z.string().nullish(),\n\tstreetName: z.string().nullish(),\n\tstreetNumber: z.string().nullish(),\n\tadditionalStreetInfo: z.string().nullish(),\n\tpostalCode: z.string().nullish(),\n\tcity: z.string().nullish(),\n\tregion: z.string().nullish(),\n\tstate: z.string().nullish(),\n\tcompany: z.string().nullish(),\n\tdepartment: z.string().nullish(),\n\tbuilding: z.string().nullish(),\n\tapartment: z.string().nullish(),\n\tpOBox: z.string().nullish(),\n\tphone: z.string().nullish(),\n\tmobile: z.string().nullish(),\n\temail: z.string().nullish(),\n\tfax: z.string().nullish(),\n\tadditionalAddressInfo: z.string().nullish(),\n\texternalId: z.string().nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n});\n\nexport const DeliveryDraftSchema = z.object({\n\tkey: z.string().nullish(),\n\titems: z.array(DeliveryItemSchema).nullish(),\n\tparcels: z.array(ParcelDraftSchema).nullish(),\n\taddress: AddressDraftSchema.nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n});\n\nexport const CustomShippingDraftSchema = z.object({\n\tkey: z.string(),\n\tshippingMethodName: z.string(),\n\tshippingAddress: BaseAddressSchema.nullish(),\n\tshippingRate: ShippingRateDraftSchema,\n\tshippingRateInput: ShippingRateInputDraftSchema.nullish(),\n\ttaxCategory: TaxCategoryResourceIdentifierSchema.nullish(),\n\texternalTaxRate: ExternalTaxRateDraftSchema.nullish(),\n\tdeliveries: z.array(DeliveryDraftSchema).nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n});\n\nexport const ShippingMethodReferenceSchema = z.object({\n\ttypeId: ReferenceTypeIdSchema,\n\tid: z.string(),\n});\n\nexport const ShippingDraftSchema = z.object({\n\tkey: z.string(),\n\tshippingMethod: ShippingMethodReferenceSchema.nullish(),\n\tshippingAddress: BaseAddressSchema,\n\tshippingRateInput: ShippingRateInputDraftSchema.nullish(),\n\texternalTaxRate: ExternalTaxRateDraftSchema.nullish(),\n\tdeliveries: z.array(DeliveryDraftSchema).nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n});\n\nexport const CartDiscountValueAbsoluteDraftSchema = z.object({\n\ttype: z.literal(\"absolute\"),\n\tmoney: z.array(MoneySchema),\n\tapplicationMode: DiscountApplicationModeSchema.nullish(),\n});\n\nexport const TypedMoneyDraftSchema = z.object({\n\tcentAmount: z.number().int(),\n\tcurrencyCode: CurrencyCodeSchema,\n\ttype: MoneyTypeSchema,\n\tfractionDigits: z.number().int().nullish(),\n});\n\nexport const CartDiscountValueFixedDraftSchema = z.object({\n\ttype: z.literal(\"fixed\"),\n\tmoney: z.array(TypedMoneyDraftSchema),\n\tapplicationMode: DiscountApplicationModeSchema.nullish(),\n});\n\nexport const ProductResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const CartDiscountValueGiftLineItemDraftSchema = z.object({\n\ttype: z.literal(\"giftLineItem\"),\n\tproduct: ProductResourceIdentifierSchema,\n\tvariantId: z.number().int(),\n\tsupplyChannel: ChannelResourceIdentifierSchema.nullish(),\n\tdistributionChannel: ChannelResourceIdentifierSchema.nullish(),\n});\n\nexport const CartDiscountValueRelativeDraftSchema = z.object({\n\ttype: z.literal(\"relative\"),\n\tpermyriad: z.number().int(),\n\tapplicationMode: DiscountApplicationModeSchema.nullish(),\n});\n\nexport const CartDiscountValueDraftSchema = z.discriminatedUnion(\"type\", [\n\tCartDiscountValueAbsoluteDraftSchema,\n\tCartDiscountValueFixedDraftSchema,\n\tCartDiscountValueGiftLineItemDraftSchema,\n\tCartDiscountValueRelativeDraftSchema,\n]);\n\nexport const CartDiscountTargetSchema = z.object({\n\ttype: z.string(),\n});\n\nexport const DiscountGroupResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const AnyOrderDraftSchema = z.object({\n\ttype: z.literal(\"AnyOrder\"),\n});\n\nexport const ApplicableRecurrencePoliciesDraftSchema = z.object({\n\ttype: z.literal(\"ApplicableRecurrencePolicies\"),\n\trecurrencePolicies: z.array(RecurrencePolicyResourceIdentifierSchema),\n});\n\nexport const NonRecurringOrdersOnlyDraftSchema = z.object({\n\ttype: z.literal(\"NonRecurringOrdersOnly\"),\n});\n\nexport const RecurringOrdersOnlyDraftSchema = z.object({\n\ttype: z.literal(\"RecurringOrdersOnly\"),\n});\n\nexport const RecurringOrderScopeDraftSchema = z.discriminatedUnion(\"type\", [\n\tAnyOrderDraftSchema,\n\tApplicableRecurrencePoliciesDraftSchema,\n\tNonRecurringOrdersOnlyDraftSchema,\n\tRecurringOrdersOnlyDraftSchema,\n]);\n\nexport const CategoryResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const AssetDimensionsSchema = z.object({\n\tw: z.number().int(),\n\th: z.number().int(),\n});\n\nexport const AssetSourceSchema = z.object({\n\turi: z.string(),\n\tkey: z.string().nullish(),\n\tdimensions: AssetDimensionsSchema.nullish(),\n\tcontentType: z.string().nullish(),\n});\n\nexport const AssetDraftSchema = z.object({\n\tsources: z.array(AssetSourceSchema),\n\tname: LocalizedStringSchema,\n\tdescription: LocalizedStringSchema.nullish(),\n\ttags: z.array(z.string()).nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\tkey: z.string().nullish(),\n});\n\nexport const GeoJsonPointSchema = z.object({\n\ttype: z.literal(\"Point\"),\n\tcoordinates: z.array(z.number()),\n});\n\nexport const GeoJsonSchema = z.object({\n\ttype: z.string(),\n\tcoordinates: z.array(z.number()),\n});\n\nexport const CartResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const CartDiscountResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const AWSLambdaDestinationSchema = z.object({\n\ttype: z.literal(\"AWSLambda\"),\n\tarn: z.string(),\n\taccessKey: z.string(),\n\taccessSecret: z.string(),\n});\n\nexport const GoogleCloudFunctionDestinationSchema = z.object({\n\ttype: z.literal(\"GoogleCloudFunction\"),\n\turl: z.string(),\n});\n\nexport const AuthorizationHeaderAuthenticationSchema = z.object({\n\ttype: z.literal(\"AuthorizationHeader\"),\n\theaderValue: z.string(),\n});\n\nexport const AzureFunctionsAuthenticationSchema = z.object({\n\ttype: z.literal(\"AzureFunctions\"),\n\tkey: z.string(),\n});\n\nexport const HttpDestinationAuthenticationSchema = z.discriminatedUnion(\n\t\"type\",\n\t[AuthorizationHeaderAuthenticationSchema, AzureFunctionsAuthenticationSchema],\n);\n\nexport const HttpDestinationSchema = z.object({\n\ttype: z.literal(\"HTTP\"),\n\turl: z.string(),\n\tauthentication: HttpDestinationAuthenticationSchema.nullish(),\n});\n\nexport const ExtensionDestinationSchema = z.discriminatedUnion(\"type\", [\n\tAWSLambdaDestinationSchema,\n\tGoogleCloudFunctionDestinationSchema,\n\tHttpDestinationSchema,\n]);\n\nexport const ExtensionTriggerSchema = z.object({\n\tresourceTypeId: ExtensionResourceTypeIdSchema,\n\tactions: z.array(ExtensionActionSchema),\n\tcondition: z.string().nullish(),\n});\n\nexport const ExtensionResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const ExtensionAdditionalContextDraftSchema = z.object({\n\tincludeOldResource: z.boolean().nullish(),\n});\n\nexport const InventoryEntryStockLevelsSchema = z.object({\n\treorderPoint: z.number().int().nullish(),\n\tsafetyStock: z.number().int().nullish(),\n});\n\nexport const OrderReferenceSchema = z.object({\n\ttypeId: ReferenceTypeIdSchema,\n\tid: z.string(),\n});\n\nexport const StagedOrderUpdateActionSchema = z.object({\n\taction: z.string(),\n});\n\nexport const StateResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const QuoteResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const PaymentMethodTokenSchema = z.object({\n\tvalue: z.string(),\n});\n\nexport const PaymentMethodInfoDraftSchema = z.object({\n\tpaymentInterface: z.string().nullish(),\n\tmethod: z.string().nullish(),\n\tname: LocalizedStringSchema.nullish(),\n\ttoken: PaymentMethodTokenSchema.nullish(),\n\tinterfaceAccount: z.string().nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n});\n\nexport const PaymentStatusDraftSchema = z.object({\n\tinterfaceCode: z.string().nullish(),\n\tinterfaceText: z.string().nullish(),\n\tstate: StateResourceIdentifierSchema.nullish(),\n});\n\nexport const TransactionDraftSchema = z.object({\n\ttimestamp: z.string().nullish(),\n\ttype: TransactionTypeSchema,\n\tamount: MoneySchema,\n\tinteractionId: z.string().nullish(),\n\tstate: TransactionStateSchema.nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\tinterfaceId: z.string().nullish(),\n});\n\nexport const ProductTypeResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const CategoryOrderHintsSchema = z.record(z.string(), z.string());\n\nexport const ProductDiscountReferenceSchema = z.object({\n\ttypeId: ReferenceTypeIdSchema,\n\tid: z.string(),\n});\n\nexport const DiscountedPriceDraftSchema = z.object({\n\tvalue: MoneySchema,\n\tdiscount: ProductDiscountReferenceSchema,\n});\n\nexport const PriceTierDraftSchema = z.object({\n\tminimumQuantity: z.number().int(),\n\tvalue: MoneySchema,\n});\n\nexport const PriceDraftSchema = z.object({\n\tkey: z.string().nullish(),\n\tvalue: MoneySchema,\n\tcountry: CountryCodeSchema.nullish(),\n\tcustomerGroup: CustomerGroupResourceIdentifierSchema.nullish(),\n\tchannel: ChannelResourceIdentifierSchema.nullish(),\n\tvalidFrom: z.string().nullish(),\n\tvalidUntil: z.string().nullish(),\n\tdiscounted: DiscountedPriceDraftSchema.nullish(),\n\ttiers: z.array(PriceTierDraftSchema).nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\trecurrencePolicy: RecurrencePolicyResourceIdentifierSchema.nullish(),\n});\n\nexport const AttributeSchema = z.object({\n\tname: z.string(),\n\tvalue: z.unknown(),\n});\n\nexport const ImageDimensionsSchema = z.object({\n\tw: z.number().int(),\n\th: z.number().int(),\n});\n\nexport const ImageSchema = z.object({\n\turl: z.string(),\n\tdimensions: ImageDimensionsSchema,\n\tlabel: z.string().nullish(),\n});\n\nexport const ProductVariantDraftSchema = z.object({\n\tsku: z.string().nullish(),\n\tkey: z.string().nullish(),\n\tprices: z.array(PriceDraftSchema).nullish(),\n\tattributes: z.array(AttributeSchema).nullish(),\n\timages: z.array(ImageSchema).nullish(),\n\tassets: z.array(AssetDraftSchema).nullish(),\n});\n\nexport const SearchKeywordsSchema = z.record(z.string(), z.string());\n\nexport const ProductDiscountValueAbsoluteDraftSchema = z.object({\n\ttype: z.literal(\"absolute\"),\n\tmoney: z.array(MoneySchema),\n});\n\nexport const ProductDiscountValueExternalDraftSchema = z.object({\n\ttype: z.literal(\"external\"),\n});\n\nexport const ProductDiscountValueRelativeDraftSchema = z.object({\n\ttype: z.literal(\"relative\"),\n\tpermyriad: z.number().int(),\n});\n\nexport const ProductDiscountValueDraftSchema = z.discriminatedUnion(\"type\", [\n\tProductDiscountValueAbsoluteDraftSchema,\n\tProductDiscountValueExternalDraftSchema,\n\tProductDiscountValueRelativeDraftSchema,\n]);\n\nexport const TypeReferenceSchema = z.object({\n\ttypeId: ReferenceTypeIdSchema,\n\tid: z.string(),\n});\n\nexport const CustomFieldsSchema = z.object({\n\ttype: TypeReferenceSchema,\n\tfields: FieldContainerSchema,\n});\n\nexport const AssetSchema = z.object({\n\tid: z.string(),\n\tsources: z.array(AssetSourceSchema),\n\tname: LocalizedStringSchema,\n\tdescription: LocalizedStringSchema.nullish(),\n\ttags: z.array(z.string()).nullish(),\n\tcustom: CustomFieldsSchema.nullish(),\n\tkey: z.string().nullish(),\n});\n\nexport const ProductTailoringAttributeSchema = z.object({\n\tname: z.string(),\n\tvalue: z.unknown(),\n});\n\nexport const ProductVariantTailoringDraftSchema = z.object({\n\tid: z.number().int().nullish(),\n\tsku: z.string().nullish(),\n\timages: z.array(ImageSchema).nullish(),\n\tassets: z.array(AssetSchema).nullish(),\n\tattributes: z.array(ProductTailoringAttributeSchema).nullish(),\n});\n\nexport const AttributeTypeSchema = z.object({\n\tname: z.string(),\n});\n\nexport const AttributeDefinitionDraftSchema = z.object({\n\ttype: AttributeTypeSchema,\n\tname: z.string(),\n\tlabel: LocalizedStringSchema,\n\tisRequired: z.boolean(),\n\tlevel: AttributeLevelEnumSchema.nullish(),\n\tattributeConstraint: AttributeConstraintEnumSchema.nullish(),\n\tinputTip: LocalizedStringSchema.nullish(),\n\tinputHint: TextInputHintSchema.nullish(),\n\tisSearchable: z.boolean().nullish(),\n});\n\nexport const StagedQuoteResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const StateReferenceSchema = z.object({\n\ttypeId: ReferenceTypeIdSchema,\n\tid: z.string(),\n});\n\nexport const DayOfMonthScheduleDraftSchema = z.object({\n\ttype: z.literal(\"dayOfMonth\"),\n\tday: z.number().int(),\n});\n\nexport const StandardScheduleDraftSchema = z.object({\n\ttype: z.literal(\"standard\"),\n\tvalue: z.number().int(),\n\tintervalUnit: IntervalUnitSchema,\n});\n\nexport const RecurrencePolicyScheduleDraftSchema = z.discriminatedUnion(\n\t\"type\",\n\t[DayOfMonthScheduleDraftSchema, StandardScheduleDraftSchema],\n);\n\nexport const ZoneResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const ZoneRateDraftSchema = z.object({\n\tzone: ZoneResourceIdentifierSchema,\n\tshippingRates: z.array(ShippingRateDraftSchema),\n});\n\nexport const ShoppingListLineItemDraftSchema = z.object({\n\tkey: z.string().nullish(),\n\tproductId: z.string().nullish(),\n\tvariantId: z.number().int().nullish(),\n\tsku: z.string().nullish(),\n\taddedAt: z.string().nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\tquantity: z.number().int().nullish(),\n});\n\nexport const TextLineItemDraftSchema = z.object({\n\tkey: z.string().nullish(),\n\taddedAt: z.string().nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\tdescription: LocalizedStringSchema.nullish(),\n\tname: LocalizedStringSchema,\n\tquantity: z.number().int().nullish(),\n});\n\nexport const StagedPriceDraftSchema = z.object({\n\tvalue: TypedMoneyDraftSchema,\n});\n\nexport const QuoteRequestResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const StoreCountrySchema = z.object({\n\tcode: CountryCodeSchema,\n});\n\nexport const ProductSelectionResourceIdentifierSchema = z\n\t.object({\n\t\ttypeId: ReferenceTypeIdSchema,\n\t\tid: z.string().nullish(),\n\t\tkey: z.string().nullish(),\n\t})\n\t.refine((data) => data.id !== undefined || data.key !== undefined, {\n\t\tmessage: \"Either 'id' or 'key' must be provided\",\n\t});\n\nexport const ProductSelectionSettingDraftSchema = z.object({\n\tproductSelection: ProductSelectionResourceIdentifierSchema,\n\tactive: z.boolean().nullish(),\n});\n\nexport const StorefrontSchema = z.object({\n\tcheckoutUrlTemplate: z.string().nullish(),\n\torderUrlTemplate: z.string().nullish(),\n\ttermsOfServiceUrl: z.string().nullish(),\n\tprivacyPolicyUrl: z.string().nullish(),\n\trefundPolicyUrl: z.string().nullish(),\n\tshippingPolicyUrl: z.string().nullish(),\n\tcookiePolicyUrl: z.string().nullish(),\n\timprintUrl: z.string().nullish(),\n\tfaqUrl: z.string().nullish(),\n\tcontactUrl: z.string().nullish(),\n});\n\nexport const DestinationSchema = z.object({\n\ttype: z.string(),\n});\n\nexport const MessageSubscriptionSchema = z.object({\n\tresourceTypeId: MessageSubscriptionResourceTypeIdSchema,\n\ttypes: z.array(z.string()).nullish(),\n});\n\nexport const ChangeSubscriptionSchema = z.object({\n\tresourceTypeId: ChangeSubscriptionResourceTypeIdSchema,\n});\n\nexport const EventSubscriptionSchema = z.object({\n\tresourceTypeId: EventSubscriptionResourceTypeIdSchema,\n\ttypes: z.array(EventTypeSchema).nullish(),\n});\n\nexport const CloudEventsFormatSchema = z.object({\n\ttype: z.literal(\"CloudEvents\"),\n\tcloudEventsVersion: z.string(),\n});\n\nexport const PlatformFormatSchema = z.object({\n\ttype: z.literal(\"Platform\"),\n});\n\nexport const DeliveryFormatSchema = z.discriminatedUnion(\"type\", [\n\tCloudEventsFormatSchema,\n\tPlatformFormatSchema,\n]);\n\nexport const TaxRateDraftSchema = z.object({\n\tname: z.string(),\n\tamount: z.number().nullish(),\n\tincludedInPrice: z.boolean(),\n\tcountry: CountryCodeSchema,\n\tstate: z.string().nullish(),\n\tsubRates: z.array(SubRateSchema).nullish(),\n\tkey: z.string().nullish(),\n});\n\nexport const FieldTypeSchema = z.object({\n\tname: z.string(),\n});\n\nexport const FieldDefinitionSchema = z.object({\n\ttype: FieldTypeSchema,\n\tname: z.string(),\n\tlabel: LocalizedStringSchema,\n\trequired: z.boolean(),\n\tinputHint: TypeTextInputHintSchema.nullish(),\n});\n\nexport const LocationSchema = z.object({\n\tcountry: CountryCodeSchema,\n\tstate: z.string().nullish(),\n});\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tLocalizedStringSchema,\n\tProductResourceIdentifierSchema,\n\tProductTailoringAttributeSchema,\n\tProductVariantTailoringDraftSchema,\n\tStoreResourceIdentifierSchema,\n} from \"./common.ts\";\n\nexport const ProductTailoringDraftSchema = z.object({\n\tkey: z.string().nullish(),\n\tstore: StoreResourceIdentifierSchema,\n\tproduct: ProductResourceIdentifierSchema,\n\tname: LocalizedStringSchema.nullish(),\n\tdescription: LocalizedStringSchema.nullish(),\n\tmetaTitle: LocalizedStringSchema.nullish(),\n\tmetaDescription: LocalizedStringSchema.nullish(),\n\tmetaKeywords: LocalizedStringSchema.nullish(),\n\tslug: LocalizedStringSchema.nullish(),\n\tpublish: z.boolean().nullish(),\n\tvariants: z.array(ProductVariantTailoringDraftSchema).nullish(),\n\tattributes: z.array(ProductTailoringAttributeSchema).nullish(),\n});\n","import type { ConcurrentModificationError } from \"@commercetools/platform-sdk\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\n\nexport const checkConcurrentModification = (\n\tcurrentVersion: number,\n\texpectedVersion: number,\n\tidentifier: string,\n) => {\n\tif (currentVersion === expectedVersion) return;\n\tthrow new CommercetoolsError<ConcurrentModificationError>(\n\t\t{\n\t\t\tmessage: `Object ${identifier} has a different version than expected. Expected: ${expectedVersion} - Actual: ${currentVersion}.`,\n\t\t\tcurrentVersion: currentVersion,\n\t\t\tcode: \"ConcurrentModification\",\n\t\t},\n\t\t409,\n\t);\n};\n","import type {\n\t_Money,\n\tAddress,\n\tAssociate,\n\tAssociateDraft,\n\tAssociateRoleAssignment,\n\tAssociateRoleAssignmentDraft,\n\tAssociateRoleKeyReference,\n\tAssociateRoleReference,\n\tAssociateRoleResourceIdentifier,\n\tBaseAddress,\n\tBusinessUnitKeyReference,\n\tBusinessUnitResourceIdentifier,\n\tCentPrecisionMoney,\n\tCustomFields,\n\tCustomFieldsDraft,\n\tHighPrecisionMoney,\n\tHighPrecisionMoneyDraft,\n\tInvalidInputError,\n\tInvalidJsonInputError,\n\tReference,\n\tReferencedResourceNotFoundError,\n\tResourceIdentifier,\n\tRoundingMode,\n\tStore,\n\tStoreKeyReference,\n\tStoreReference,\n\tStoreResourceIdentifier,\n\tType,\n\tTypedMoney,\n} from \"@commercetools/platform-sdk\";\nimport { Decimal } from \"decimal.js/decimal\";\nimport type { FastifyRequest } from \"fastify\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport type { AbstractStorage } from \"../storage/index.ts\";\nimport type { RepositoryContext } from \"./abstract.ts\";\n\nexport const createAddress = (\n\tbase: BaseAddress | undefined,\n\tprojectKey: string,\n\tstorage: AbstractStorage,\n): Address | undefined => {\n\tif (!base) return undefined;\n\n\tif (!base?.country) {\n\t\tthrow new CommercetoolsError<InvalidJsonInputError>(\n\t\t\t{\n\t\t\t\tcode: \"InvalidJsonInput\",\n\t\t\t\tmessage: \"Country is required\",\n\t\t\t\tdetailedErrorMessage: \"Country is required\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\t// Generate a random 8-character alphanumeric string\n\t// which is what addresses use instead of uuid\n\tconst generateRandomId = (): string =>\n\t\tMath.random().toString(36).substring(2, 10).padEnd(8, \"0\");\n\treturn {\n\t\t...base,\n\t\tid: base.id ?? generateRandomId(),\n\t};\n};\n\nexport const createCustomFields = async (\n\tdraft: CustomFieldsDraft | undefined,\n\tprojectKey: string,\n\tstorage: AbstractStorage,\n): Promise<CustomFields | undefined> => {\n\tif (!draft) return undefined;\n\tif (!draft.type) return undefined;\n\tif (!draft.type.typeId) return undefined;\n\tconst typeResource = (await storage.getByResourceIdentifier(\n\t\tprojectKey,\n\t\tdraft.type,\n\t)) as Type;\n\n\tif (!typeResource) {\n\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>(\n\t\t\t{\n\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\ttypeId: draft.type.typeId,\n\t\t\t\tmessage: `No type '${draft.type.typeId}' with id=${draft.type.id} or key=${draft.type.key}`,\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\treturn {\n\t\ttype: {\n\t\t\ttypeId: draft.type.typeId,\n\t\t\tid: typeResource.id,\n\t\t},\n\t\tfields: draft.fields ?? {},\n\t};\n};\n\n/**\n * Rounds a decimal to the nearest whole number using the specified\n * (Commercetools) rounding mode.\n *\n * @see https://docs.commercetools.com/api/projects/carts#roundingmode\n */\nexport const roundDecimal = (decimal: Decimal, roundingMode: RoundingMode) => {\n\tswitch (roundingMode) {\n\t\tcase \"HalfEven\":\n\t\t\treturn decimal.toDecimalPlaces(0, Decimal.ROUND_HALF_EVEN);\n\t\tcase \"HalfUp\":\n\t\t\treturn decimal.toDecimalPlaces(0, Decimal.ROUND_HALF_UP);\n\t\tcase \"HalfDown\":\n\t\t\treturn decimal.toDecimalPlaces(0, Decimal.ROUND_HALF_DOWN);\n\t\tdefault:\n\t\t\tthrow new CommercetoolsError<InvalidInputError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidInput\",\n\t\t\t\t\tmessage: `Unknown rounding mode: ${roundingMode}`,\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t}\n};\n\nexport const getCurrencyFractionDigits = (currencyCode: string): number => {\n\t// Taken from https://docs.adyen.com/development-resources/currency-codes\n\tswitch (currencyCode.toUpperCase()) {\n\t\tcase \"BHD\":\n\t\tcase \"IQD\":\n\t\tcase \"JOD\":\n\t\tcase \"KWD\":\n\t\tcase \"LYD\":\n\t\tcase \"OMR\":\n\t\tcase \"TND\":\n\t\t\treturn 3;\n\t\tcase \"CVE\":\n\t\tcase \"DJF\":\n\t\tcase \"GNF\":\n\t\tcase \"IDR\":\n\t\tcase \"JPY\":\n\t\tcase \"KMF\":\n\t\tcase \"KRW\":\n\t\tcase \"PYG\":\n\t\tcase \"RWF\":\n\t\tcase \"UGX\":\n\t\tcase \"VND\":\n\t\tcase \"VUV\":\n\t\tcase \"XAF\":\n\t\tcase \"XOF\":\n\t\tcase \"XPF\":\n\t\t\treturn 0;\n\t\tdefault:\n\t\t\treturn 2;\n\t}\n};\n\nexport const calculateCentAmountFromPreciseAmount = (\n\tpreciseAmount: number,\n\tfractionDigits: number,\n\tcurrencyCode: string,\n\troundingMode: RoundingMode = \"HalfEven\",\n): number => {\n\tconst centFractionDigits = getCurrencyFractionDigits(currencyCode);\n\tconst diff = fractionDigits - centFractionDigits;\n\tconst scale = new Decimal(10).pow(Math.abs(diff));\n\tconst decimal =\n\t\tdiff >= 0\n\t\t\t? new Decimal(preciseAmount).div(scale)\n\t\t\t: new Decimal(preciseAmount).mul(scale);\n\n\treturn roundDecimal(decimal, roundingMode).toNumber();\n};\n\nexport const createCentPrecisionMoney = (value: _Money): CentPrecisionMoney => {\n\tconst fractionDigits = getCurrencyFractionDigits(value.currencyCode);\n\tconst preciseValue = value as HighPrecisionMoney & HighPrecisionMoneyDraft;\n\tlet centAmount: number;\n\n\tcentAmount = value.centAmount ?? 0;\n\n\tif (\n\t\tpreciseValue.preciseAmount !== undefined &&\n\t\tpreciseValue.fractionDigits !== undefined\n\t) {\n\t\tcentAmount = calculateCentAmountFromPreciseAmount(\n\t\t\tpreciseValue.preciseAmount,\n\t\t\tpreciseValue.fractionDigits,\n\t\t\tvalue.currencyCode,\n\t\t\t\"HalfEven\",\n\t\t);\n\t}\n\n\treturn {\n\t\ttype: \"centPrecision\",\n\t\tcentAmount,\n\t\tcurrencyCode: value.currencyCode,\n\t\tfractionDigits,\n\t};\n};\n\nexport const createHighPrecisionMoney = (\n\tvalue: HighPrecisionMoney | HighPrecisionMoneyDraft,\n): HighPrecisionMoney => {\n\tif (value.preciseAmount === undefined) {\n\t\tthrow new CommercetoolsError<InvalidJsonInputError>(\n\t\t\t{\n\t\t\t\tcode: \"InvalidJsonInput\",\n\t\t\t\tmessage: \"HighPrecisionMoney requires preciseAmount\",\n\t\t\t\tdetailedErrorMessage: \"HighPrecisionMoney requires preciseAmount\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\tif (value.fractionDigits === undefined) {\n\t\tthrow new CommercetoolsError<InvalidJsonInputError>(\n\t\t\t{\n\t\t\t\tcode: \"InvalidJsonInput\",\n\t\t\t\tmessage: \"HighPrecisionMoney requires fractionDigits\",\n\t\t\t\tdetailedErrorMessage: \"HighPrecisionMoney requires fractionDigits\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\tconst centAmount =\n\t\tvalue.centAmount ??\n\t\tcalculateCentAmountFromPreciseAmount(\n\t\t\tvalue.preciseAmount,\n\t\t\tvalue.fractionDigits,\n\t\t\tvalue.currencyCode,\n\t\t\t\"HalfEven\",\n\t\t);\n\n\treturn {\n\t\ttype: \"highPrecision\",\n\t\tcentAmount,\n\t\tcurrencyCode: value.currencyCode,\n\t\tfractionDigits: value.fractionDigits,\n\t\tpreciseAmount: value.preciseAmount,\n\t};\n};\n\nexport const createTypedMoney = (value: _Money): TypedMoney => {\n\tconst preciseValue = value as HighPrecisionMoney & HighPrecisionMoneyDraft;\n\tif (\n\t\t(\"type\" in value && value.type === \"highPrecision\") ||\n\t\tpreciseValue.preciseAmount !== undefined\n\t) {\n\t\treturn createHighPrecisionMoney(\n\t\t\tvalue as HighPrecisionMoney | HighPrecisionMoneyDraft,\n\t\t);\n\t}\n\n\treturn createCentPrecisionMoney(value);\n};\n\nexport const calculateMoneyTotalCentAmount = (\n\tmoney: _Money,\n\tquantity: number,\n\troundingMode: RoundingMode = \"HalfEven\",\n): number => {\n\tconst preciseValue = money as HighPrecisionMoney & HighPrecisionMoneyDraft;\n\n\tif (\n\t\tpreciseValue.preciseAmount === undefined ||\n\t\tpreciseValue.fractionDigits === undefined\n\t) {\n\t\treturn (money.centAmount ?? 0) * quantity;\n\t}\n\n\tconst totalPrecise = new Decimal(preciseValue.preciseAmount).mul(quantity);\n\treturn calculateCentAmountFromPreciseAmount(\n\t\ttotalPrecise.toNumber(),\n\t\tpreciseValue.fractionDigits,\n\t\tmoney.currencyCode,\n\t\troundingMode,\n\t);\n};\n\nexport const resolveStoreReference = async (\n\tref: StoreResourceIdentifier | undefined,\n\tprojectKey: string,\n\tstorage: AbstractStorage,\n): Promise<StoreKeyReference | undefined> => {\n\tif (!ref) return undefined;\n\tconst resource = await storage.getByResourceIdentifier(projectKey, ref);\n\tif (!resource) {\n\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>(\n\t\t\t{\n\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\ttypeId: \"store\",\n\t\t\t\tmessage: \"The referenced object of type 'store' was not found.\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\tconst store = resource as Store;\n\treturn {\n\t\ttypeId: \"store\",\n\t\tkey: store.key,\n\t};\n};\n\nexport const getReferenceFromResourceIdentifier = async <T extends Reference>(\n\tresourceIdentifier: ResourceIdentifier,\n\tprojectKey: string,\n\tstorage: AbstractStorage,\n): Promise<T> => {\n\tif (!resourceIdentifier.id && !resourceIdentifier.key) {\n\t\tthrow new CommercetoolsError<InvalidJsonInputError>(\n\t\t\t{\n\t\t\t\tcode: \"InvalidJsonInput\",\n\t\t\t\tmessage: `${resourceIdentifier.typeId}: ResourceIdentifier requires an 'id' xor a 'key'`,\n\t\t\t\tdetailedErrorMessage: `ResourceIdentifier requires an 'id' xor a 'key'`,\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\tconst resource = await storage.getByResourceIdentifier(\n\t\tprojectKey,\n\t\tresourceIdentifier,\n\t);\n\tif (!resource) {\n\t\tconst errIdentifier = resourceIdentifier.key\n\t\t\t? `key '${resourceIdentifier.key}'`\n\t\t\t: `identifier '${resourceIdentifier.id}'`;\n\n\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>(\n\t\t\t{\n\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\ttypeId: resourceIdentifier.typeId,\n\t\t\t\tmessage: `The referenced object of type '${resourceIdentifier.typeId}' with '${errIdentifier}' was not found. It either doesn't exist, or it can't be accessed from this endpoint (e.g., if the endpoint filters by store or customer account).`,\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\treturn {\n\t\ttypeId: resourceIdentifier.typeId,\n\t\tid: resource?.id,\n\t} as unknown as T;\n};\n\nexport const getStoreKeyReference = async (\n\tid: StoreResourceIdentifier,\n\tprojectKey: string,\n\tstorage: AbstractStorage,\n): Promise<StoreKeyReference> => {\n\tif (id.key) {\n\t\treturn {\n\t\t\ttypeId: \"store\",\n\t\t\tkey: id.key,\n\t\t};\n\t}\n\tconst value = await getReferenceFromResourceIdentifier<StoreReference>(\n\t\tid,\n\t\tprojectKey,\n\t\tstorage,\n\t);\n\n\tif (!value.obj?.key) {\n\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>(\n\t\t\t{\n\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\ttypeId: \"store\",\n\t\t\t\tmessage: \"The referenced object of type 'store' was not found.\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\treturn {\n\t\ttypeId: \"store\",\n\t\tkey: value.obj?.key,\n\t};\n};\n\nexport const getRepositoryContext = (\n\trequest: FastifyRequest<{ Params: Record<string, string> }>,\n): RepositoryContext => ({\n\tprojectKey: request.params.projectKey,\n\tstoreKey: request.params.storeKey,\n\tclientId: request.credentials?.clientId,\n\tassociateId: request.params.associateId,\n\tbusinessUnitKey: request.params.businessUnitKey,\n});\n\nexport const createAssociate = async (\n\ta: AssociateDraft,\n\tprojectKey: string,\n\tstorage: AbstractStorage,\n): Promise<Associate | undefined> => {\n\tif (!a) return undefined;\n\n\tif (!a.associateRoleAssignments) {\n\t\tthrow new CommercetoolsError<InvalidJsonInputError>(\n\t\t\t{\n\t\t\t\tcode: \"InvalidJsonInput\",\n\t\t\t\tmessage: \"AssociateRoleAssignments is required\",\n\t\t\t\tdetailedErrorMessage: \"AssociateRoleAssignments is required\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\tconst associateRoleAssignments = await Promise.all(\n\t\ta.associateRoleAssignments.map(\n\t\t\tasync (\n\t\t\t\ta: AssociateRoleAssignmentDraft,\n\t\t\t): Promise<AssociateRoleAssignment> => ({\n\t\t\t\tassociateRole: await getAssociateRoleKeyReference(\n\t\t\t\t\ta.associateRole,\n\t\t\t\t\tprojectKey,\n\t\t\t\t\tstorage,\n\t\t\t\t),\n\t\t\t\tinheritance: a.inheritance as string,\n\t\t\t}),\n\t\t),\n\t);\n\n\treturn {\n\t\tcustomer: await getReferenceFromResourceIdentifier(\n\t\t\ta.customer,\n\t\t\tprojectKey,\n\t\t\tstorage,\n\t\t),\n\t\tassociateRoleAssignments,\n\t};\n};\n\nexport const getAssociateRoleKeyReference = async (\n\tid: AssociateRoleResourceIdentifier,\n\tprojectKey: string,\n\tstorage: AbstractStorage,\n): Promise<AssociateRoleKeyReference> => {\n\tif (id.key) {\n\t\treturn {\n\t\t\ttypeId: \"associate-role\",\n\t\t\tkey: id.key,\n\t\t};\n\t}\n\n\tconst value =\n\t\tawait getReferenceFromResourceIdentifier<AssociateRoleReference>(\n\t\t\tid,\n\t\t\tprojectKey,\n\t\t\tstorage,\n\t\t);\n\n\tif (!value.obj?.key) {\n\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>(\n\t\t\t{\n\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\ttypeId: \"associate-role\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"The referenced object of type 'associate-role' was not found.\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\treturn {\n\t\ttypeId: \"associate-role\",\n\t\tkey: value.obj?.key,\n\t};\n};\n\nexport const getBusinessUnitKeyReference = async (\n\tid: BusinessUnitResourceIdentifier,\n\tprojectKey: string,\n\tstorage: AbstractStorage,\n): Promise<BusinessUnitKeyReference> => {\n\tif (id.key) {\n\t\treturn {\n\t\t\ttypeId: \"business-unit\",\n\t\t\tkey: id.key,\n\t\t};\n\t}\n\n\tconst resource = await storage.getByResourceIdentifier<\"business-unit\">(\n\t\tprojectKey,\n\t\tid,\n\t);\n\n\tif (!resource?.key) {\n\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>(\n\t\t\t{\n\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\ttypeId: \"business-unit\",\n\t\t\t\tmessage: \"The referenced object of type 'business-unit' was not found.\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\treturn {\n\t\ttypeId: \"business-unit\",\n\t\tkey: resource.key,\n\t};\n};\n","import { isDeepStrictEqual } from \"node:util\";\nimport type {\n\tBaseResource,\n\tCustomFields,\n\tFieldContainer,\n\tInvalidInputError,\n\tInvalidOperationError,\n\tProject,\n\tQueryParam,\n\tResourceNotFoundError,\n\tTypeResourceIdentifier,\n\tUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type { z } from \"zod\";\nimport type { Config } from \"#src/config.ts\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { cloneObject } from \"../helpers.ts\";\nimport type { AbstractStorage } from \"../storage/index.ts\";\nimport type {\n\tResourceMap,\n\tResourceType,\n\tShallowWritable,\n\tWritable,\n} from \"./../types.ts\";\nimport { checkConcurrentModification } from \"./errors.ts\";\nimport { createCustomFields } from \"./helpers.ts\";\n\nexport type QueryParams = {\n\texpand?: string[];\n\twhere?: string[];\n\toffset?: number;\n\tlimit?: number;\n\n\t// Predicate var values. Should always start with `var.`\n\t[key: string]: QueryParam;\n};\n\nexport type GetParams = {\n\texpand?: string[];\n};\n\nexport type RepositoryContext = {\n\tprojectKey: string;\n\tstoreKey?: string;\n\tclientId?: string;\n\tassociateId?: string;\n\tbusinessUnitKey?: string;\n};\n\nexport abstract class AbstractRepository<R extends BaseResource | Project> {\n\tprotected _storage: AbstractStorage;\n\n\tprotected config: Config;\n\n\tprotected actions: AbstractUpdateHandler | undefined;\n\n\tconstructor(config: Config) {\n\t\tthis.config = config;\n\t\tthis._storage = config.storage;\n\t}\n\n\tasync saveNew({ projectKey }: RepositoryContext, resource: R): Promise<R> {\n\t\tthrow new Error(\"Not implemented\");\n\t}\n\n\tasync saveUpdate(\n\t\t{ projectKey }: RepositoryContext,\n\t\tversion: number,\n\t\tresource: R,\n\t): Promise<R> {\n\t\tthrow new Error(\"Not implemented\");\n\t}\n\n\tasync postProcessResource(\n\t\tcontext: RepositoryContext,\n\t\tresource: any,\n\t): Promise<any> {\n\t\tthrow new Error(\"Not implemented\");\n\t}\n\n\tasync processUpdateActions(\n\t\tcontext: RepositoryContext,\n\t\tresource: R,\n\t\tversion: number,\n\t\tactions: UpdateAction[],\n\t): Promise<R> {\n\t\tif (!this.actions) {\n\t\t\tthrow new Error(\"No actions defined\");\n\t\t}\n\n\t\tconst updatedResource = await this.actions.apply(\n\t\t\tcontext,\n\t\t\tresource,\n\t\t\tversion,\n\t\t\tactions,\n\t\t);\n\n\t\t// If all actions succeeded we write the new version\n\t\t// to the storage.\n\t\tif (resource.version !== updatedResource.version) {\n\t\t\tawait this.saveUpdate(context, version, updatedResource);\n\t\t}\n\n\t\tconst result = await this.postProcessResource(context, updatedResource);\n\t\tif (!result) {\n\t\t\tthrow new Error(\"invalid post process action\");\n\t\t}\n\t\treturn result;\n\t}\n}\n\nexport abstract class AbstractResourceRepository<\n\tT extends ResourceType,\n> extends AbstractRepository<ResourceMap[T]> {\n\tprotected _typeId: T;\n\n\t/**\n\t * Optional Zod schema for validating creation drafts.\n\t * When set and strict mode is enabled, the service layer will\n\t * validate incoming request bodies against this schema before\n\t * passing them to create().\n\t */\n\tdraftSchema?: z.ZodType;\n\n\tconstructor(typeId: T, config: Config) {\n\t\tsuper(config);\n\t\tthis._typeId = typeId;\n\t}\n\n\t/**\n\t * Whether strict validation is enabled.\n\t */\n\tget strict(): boolean {\n\t\treturn this.config.strict;\n\t}\n\n\tabstract create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: any,\n\t): Promise<ResourceMap[T]>;\n\n\tprotected getTypeId(): T {\n\t\treturn this._typeId;\n\t}\n\n\t/**\n\t * Apply expand clauses to a resource without re-fetching from storage.\n\t */\n\tasync expand(\n\t\tcontext: RepositoryContext,\n\t\tresource: ResourceMap[T],\n\t\texpand: string[] | undefined,\n\t): Promise<ResourceMap[T]> {\n\t\tif (!expand || expand.length === 0) {\n\t\t\treturn resource;\n\t\t}\n\t\treturn this._storage.expand(context.projectKey, resource, expand);\n\t}\n\n\tasync delete(\n\t\tcontext: RepositoryContext,\n\t\tid: string,\n\t\tparams: GetParams = {},\n\t): Promise<ResourceMap[T] | null> {\n\t\tconst resource = await this._storage.delete(\n\t\t\tcontext.projectKey,\n\t\t\tthis.getTypeId(),\n\t\t\tid,\n\t\t\tparams,\n\t\t);\n\t\treturn resource\n\t\t\t? await this.postProcessResource(context, resource, params)\n\t\t\t: null;\n\t}\n\n\tasync get(\n\t\tcontext: RepositoryContext,\n\t\tid: string,\n\t\tparams: GetParams = {},\n\t): Promise<ResourceMap[T] | null> {\n\t\tconst resource = await this._storage.get(\n\t\t\tcontext.projectKey,\n\t\t\tthis.getTypeId(),\n\t\t\tid,\n\t\t\tparams,\n\t\t);\n\t\treturn resource\n\t\t\t? await this.postProcessResource(context, resource, params)\n\t\t\t: null;\n\t}\n\n\tasync getByKey(\n\t\tcontext: RepositoryContext,\n\t\tkey: string,\n\t\tparams: GetParams = {},\n\t): Promise<ResourceMap[T] | null> {\n\t\tconst resource = await this._storage.getByKey(\n\t\t\tcontext.projectKey,\n\t\t\tthis.getTypeId(),\n\t\t\tkey,\n\t\t\tparams,\n\t\t);\n\t\treturn resource\n\t\t\t? await this.postProcessResource(context, resource, params)\n\t\t\t: null;\n\t}\n\n\tasync postProcessResource(\n\t\tcontext: RepositoryContext,\n\t\tresource: ResourceMap[T],\n\t\tparams?: GetParams,\n\t): Promise<ResourceMap[T]> {\n\t\treturn resource;\n\t}\n\n\tasync query(context: RepositoryContext, params: QueryParams = {}) {\n\t\tconst result = await this._storage.query(\n\t\t\tcontext.projectKey,\n\t\t\tthis.getTypeId(),\n\t\t\t{\n\t\t\t\t...params,\n\t\t\t},\n\t\t);\n\n\t\tconst data = await Promise.all(\n\t\t\tresult.results.map((r) =>\n\t\t\t\tthis.postProcessResource(context, r as ResourceMap[T], {\n\t\t\t\t\texpand: params.expand,\n\t\t\t\t}),\n\t\t\t),\n\t\t);\n\t\treturn {\n\t\t\t...result,\n\t\t\tresults: data,\n\t\t};\n\t}\n\n\tasync saveNew(\n\t\tcontext: RepositoryContext,\n\t\tresource: ShallowWritable<ResourceMap[T]>,\n\t): Promise<ResourceMap[T]> {\n\t\tresource.version = 1;\n\t\treturn await this._storage.add(\n\t\t\tcontext.projectKey,\n\t\t\tthis.getTypeId(),\n\t\t\tresource as any,\n\t\t);\n\t}\n\n\tasync saveUpdate(\n\t\tcontext: RepositoryContext,\n\t\tversion: number,\n\t\tresource: ShallowWritable<ResourceMap[T]>,\n\t): Promise<ResourceMap[T]> {\n\t\t// Check if the resource still exists.\n\t\tconst current = await this._storage.get(\n\t\t\tcontext.projectKey,\n\t\t\tthis.getTypeId(),\n\t\t\tresource.id,\n\t\t);\n\t\tif (!current) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\t\tmessage: \"Resource not found while updating\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\tcheckConcurrentModification(current.version, version, resource.id);\n\n\t\tif (current.version === resource.version) {\n\t\t\tthrow new Error(\"Internal error: no changes to save\");\n\t\t}\n\t\tresource.lastModifiedAt = new Date().toISOString();\n\t\t(resource as any).lastModifiedBy = {\n\t\t\tclientId: context.clientId ?? \"\",\n\t\t\tisPlatformClient: false,\n\t\t};\n\n\t\tawait this._storage.add(\n\t\t\tcontext.projectKey,\n\t\t\tthis.getTypeId(),\n\t\t\tresource as any,\n\t\t);\n\n\t\treturn resource as ResourceMap[T];\n\t}\n}\n\ntype UpdateActionHandlerMethod<A, T> = (\n\tcontext: RepositoryContext,\n\tresource: Writable<A>,\n\taction: T,\n) => void | Promise<void>;\n\nexport type UpdateHandlerInterface<\n\tA extends BaseResource | Project,\n\tT extends UpdateAction,\n> = {\n\t[P in T as P[\"action\"]]: UpdateActionHandlerMethod<A, P>;\n};\n\nexport class AbstractUpdateHandler {\n\t_storage: AbstractStorage;\n\tconstructor(_storage: AbstractStorage) {\n\t\tif (!_storage) {\n\t\t\tthrow new Error(\"No storage provided\");\n\t\t}\n\t\tthis._storage = _storage;\n\t}\n\n\t/**\n\t * Shared implementation for setCustomField update actions.\n\t *\n\t * Throws InvalidOperation if the resource has no custom type set.\n\t * When `value` is `null`, the field is removed; otherwise it is set.\n\t */\n\tprotected _setCustomFieldValues(\n\t\tresource: { custom?: CustomFields },\n\t\t{ name, value }: { name: string; value?: unknown },\n\t): void {\n\t\tif (!resource.custom) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: \"Resource has no custom type\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tif (value === null) {\n\t\t\tif (!(name in resource.custom.fields)) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: `Cannot remove custom field ${name} because it does not exist.`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tdelete resource.custom.fields[name];\n\t\t} else {\n\t\t\tresource.custom.fields[name] = value;\n\t\t}\n\t}\n\n\t/**\n\t * Shared implementation for setCustomType update actions.\n\t *\n\t * When `type` is provided, resolves the type reference and sets the\n\t * custom fields on the resource. When `type` is not provided, removes\n\t * the custom fields entirely.\n\t */\n\tprotected async _setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: { custom?: CustomFields },\n\t\t{\n\t\t\ttype,\n\t\t\tfields,\n\t\t}: { type?: TypeResourceIdentifier; fields?: FieldContainer },\n\t): Promise<void> {\n\t\tif (type) {\n\t\t\tresource.custom = await createCustomFields(\n\t\t\t\t{ type, fields },\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t);\n\t\t} else {\n\t\t\tresource.custom = undefined;\n\t\t}\n\t}\n\n\t/**\n\t * Hook to reject an action based on the state the resource is in at the\n\t * point the action is applied, rather than the state it started in.\n\t */\n\tprotected beforeAction(\n\t\tresource: BaseResource | Project,\n\t\taction: UpdateAction,\n\t): void {}\n\n\tasync apply<R extends BaseResource | Project>(\n\t\tcontext: RepositoryContext,\n\t\tresource: R,\n\t\tversion: number,\n\t\tactions: UpdateAction[],\n\t): Promise<R> {\n\t\t// We need a separate working copy because the caller (processUpdateActions)\n\t\t// compares resource.version with updatedResource.version to detect changes.\n\t\t// The resource parameter is already a clone from storage, but we still need\n\t\t// two distinct references.\n\t\tconst updatedResource = cloneObject(resource) as ShallowWritable<R>;\n\t\tconst identifier = (resource as BaseResource).id\n\t\t\t? (resource as BaseResource).id\n\t\t\t: (resource as Project).key;\n\n\t\tfor (const action of actions) {\n\t\t\t// Validate if this action exists\n\t\t\t// @ts-expect-error\n\t\t\tif (this[action.action] === undefined) {\n\t\t\t\tthrow new CommercetoolsError<InvalidInputError>({\n\t\t\t\t\tcode: \"InvalidInput\",\n\t\t\t\t\tmessage: `Invalid action ${action.action}`,\n\t\t\t\t\terrors: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcode: \"InvalidInput\",\n\t\t\t\t\t\t\tmessage: `Invalid action ${action.action}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tthis.beforeAction(\n\t\t\t\tupdatedResource as unknown as BaseResource | Project,\n\t\t\t\taction,\n\t\t\t);\n\n\t\t\t// @ts-expect-error\n\t\t\tconst updateFunc = this[action.action].bind(this);\n\n\t\t\tif (!updateFunc) {\n\t\t\t\tthrow new CommercetoolsError<InvalidInputError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidInput\",\n\t\t\t\t\t\tmessage: `No mock implemented for update action ${action.action}`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Snapshot the current state before applying the action so we can\n\t\t\t// detect whether it actually changed anything.\n\t\t\tconst beforeUpdate = cloneObject(updatedResource);\n\t\t\tawait updateFunc(context, updatedResource, action);\n\n\t\t\t// Check if the object is updated. We need to increase the version of\n\t\t\t// an object per action which does an actual modification.\n\t\t\t// This isn't the most performant method to do this (the update action\n\t\t\t// should return a flag) but for now the easiest.\n\t\t\tif (!isDeepStrictEqual(beforeUpdate, updatedResource)) {\n\t\t\t\t// We only check the version when there is an actual modification to\n\t\t\t\t// be stored.\n\t\t\t\tcheckConcurrentModification(resource.version, version, identifier);\n\n\t\t\t\tupdatedResource.version += 1;\n\t\t\t}\n\t\t}\n\t\treturn updatedResource;\n\t}\n}\n","import type {\n\tInvalidOperationError,\n\tProductTailoring,\n\tProductTailoringUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { ProductTailoringDraftSchema } from \"#src/schemas/generated/product-tailoring.ts\";\nimport type { RepositoryContext, UpdateHandlerInterface } from \"./abstract.ts\";\nimport {\n\tAbstractResourceRepository,\n\tAbstractUpdateHandler,\n} from \"./abstract.ts\";\n\nexport class ProductTailoringRepository extends AbstractResourceRepository<\"product-tailoring\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"product-tailoring\", config);\n\t\tthis.actions = new ProductTailoringUpdateHandler(this._storage);\n\t\tthis.draftSchema = ProductTailoringDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: any,\n\t): Promise<ProductTailoring> {\n\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t{\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"Create method for product-tailoring not implemented.\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n}\n\nclass ProductTailoringUpdateHandler\n\textends AbstractUpdateHandler\n\timplements\n\t\tPartial<\n\t\t\tUpdateHandlerInterface<ProductTailoring, ProductTailoringUpdateAction>\n\t\t>\n{\n\tsetSlug() {\n\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t{\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"SetSlug method for product-tailoring not implemented.\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n}\n","import type {\n\tApprovalFlow,\n\tApprovalFlowApproveAction,\n\tApprovalFlowRejectAction,\n\tApprovalFlowSetCustomFieldAction,\n\tApprovalFlowSetCustomTypeAction,\n\tApprovalFlowUpdateAction,\n\tBusinessUnitKeyReference,\n\tOrderReference,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { getBaseResourceProperties } from \"../helpers.ts\";\nimport type { Writable } from \"../types.ts\";\nimport type { UpdateHandlerInterface } from \"./abstract.ts\";\nimport {\n\tAbstractResourceRepository,\n\tAbstractUpdateHandler,\n\ttype RepositoryContext,\n} from \"./abstract.ts\";\n\n/**\n * Test-only draft for seeding ApprovalFlows. In commercetools, ApprovalFlows\n * are generated automatically when an Order matches an active ApprovalRule;\n * this draft exists so test fixtures can create them via the mock.\n */\nexport type ApprovalFlowDraft = {\n\torder: OrderReference;\n\tbusinessUnit: BusinessUnitKeyReference;\n\tstatus?: ApprovalFlow[\"status\"];\n\trules?: ApprovalFlow[\"rules\"];\n\tapprovals?: ApprovalFlow[\"approvals\"];\n\teligibleApprovers?: ApprovalFlow[\"eligibleApprovers\"];\n\tpendingApprovers?: ApprovalFlow[\"pendingApprovers\"];\n\tcurrentTierPendingApprovers?: ApprovalFlow[\"currentTierPendingApprovers\"];\n};\n\nexport class ApprovalFlowRepository extends AbstractResourceRepository<\"approval-flow\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"approval-flow\", config);\n\t\tthis.actions = new ApprovalFlowUpdateHandler(this._storage);\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: ApprovalFlowDraft,\n\t): Promise<ApprovalFlow> {\n\t\tconst resource: ApprovalFlow = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\torder: draft.order,\n\t\t\tbusinessUnit: draft.businessUnit,\n\t\t\trules: draft.rules ?? [],\n\t\t\tstatus: draft.status ?? \"Pending\",\n\t\t\tapprovals: draft.approvals ?? [],\n\t\t\teligibleApprovers: draft.eligibleApprovers ?? [],\n\t\t\tpendingApprovers: draft.pendingApprovers ?? [],\n\t\t\tcurrentTierPendingApprovers: draft.currentTierPendingApprovers ?? [],\n\t\t};\n\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n\nclass ApprovalFlowUpdateHandler\n\textends AbstractUpdateHandler\n\timplements\n\t\tPartial<UpdateHandlerInterface<ApprovalFlow, ApprovalFlowUpdateAction>>\n{\n\tapprove(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ApprovalFlow>,\n\t\t_action: ApprovalFlowApproveAction,\n\t) {\n\t\tresource.status = \"Approved\";\n\t}\n\n\treject(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ApprovalFlow>,\n\t\t{ reason }: ApprovalFlowRejectAction,\n\t) {\n\t\tresource.status = \"Rejected\";\n\t\tresource.rejection = {\n\t\t\trejecter: {\n\t\t\t\tcustomer: { typeId: \"customer\", id: context.associateId ?? \"\" },\n\t\t\t\tassociateRoleAssignments: [],\n\t\t\t},\n\t\t\trejectedAt: new Date().toISOString(),\n\t\t\treason,\n\t\t};\n\t}\n\n\tsetCustomField(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ApprovalFlow>,\n\t\t{ name, value }: ApprovalFlowSetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ApprovalFlow>,\n\t\t{ type, fields }: ApprovalFlowSetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n}\n","import type {\n\tApprovalRule,\n\tApprovalRuleDraft,\n\tApprovalRuleSetApproversAction,\n\tApprovalRuleSetCustomFieldAction,\n\tApprovalRuleSetCustomTypeAction,\n\tApprovalRuleSetDescriptionAction,\n\tApprovalRuleSetKeyAction,\n\tApprovalRuleSetNameAction,\n\tApprovalRuleSetPredicateAction,\n\tApprovalRuleSetRequestersAction,\n\tApprovalRuleSetStatusAction,\n\tApprovalRuleUpdateAction,\n\tApproverConjunctionDraft,\n\tApproverHierarchy,\n\tApproverHierarchyDraft,\n\tRuleRequester,\n\tRuleRequesterDraft,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { getBaseResourceProperties } from \"../helpers.ts\";\nimport type { AbstractStorage } from \"../storage/index.ts\";\nimport type { Writable } from \"../types.ts\";\nimport type { UpdateHandlerInterface } from \"./abstract.ts\";\nimport {\n\tAbstractResourceRepository,\n\tAbstractUpdateHandler,\n\ttype RepositoryContext,\n} from \"./abstract.ts\";\nimport {\n\tcreateCustomFields,\n\tgetAssociateRoleKeyReference,\n\tgetBusinessUnitKeyReference,\n} from \"./helpers.ts\";\n\nconst resolveApproverHierarchy = async (\n\tdraft: ApproverHierarchyDraft,\n\tprojectKey: string,\n\tstorage: AbstractStorage,\n): Promise<ApproverHierarchy> => ({\n\ttiers: await Promise.all(\n\t\tdraft.tiers.map(async (tier: ApproverConjunctionDraft) => ({\n\t\t\tand: await Promise.all(\n\t\t\t\ttier.and.map(async (disjunction) => ({\n\t\t\t\t\tor: await Promise.all(\n\t\t\t\t\t\tdisjunction.or.map(async (approver) => ({\n\t\t\t\t\t\t\tassociateRole: await getAssociateRoleKeyReference(\n\t\t\t\t\t\t\t\tapprover.associateRole,\n\t\t\t\t\t\t\t\tprojectKey,\n\t\t\t\t\t\t\t\tstorage,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t})),\n\t\t\t\t\t),\n\t\t\t\t})),\n\t\t\t),\n\t\t})),\n\t),\n});\n\nconst resolveRequesters = async (\n\tdrafts: RuleRequesterDraft[],\n\tprojectKey: string,\n\tstorage: AbstractStorage,\n): Promise<RuleRequester[]> =>\n\tPromise.all(\n\t\tdrafts.map(async (requester) => ({\n\t\t\tassociateRole: await getAssociateRoleKeyReference(\n\t\t\t\trequester.associateRole,\n\t\t\t\tprojectKey,\n\t\t\t\tstorage,\n\t\t\t),\n\t\t})),\n\t);\n\nexport class ApprovalRuleRepository extends AbstractResourceRepository<\"approval-rule\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"approval-rule\", config);\n\t\tthis.actions = new ApprovalRuleUpdateHandler(this._storage);\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: ApprovalRuleDraft & {\n\t\t\tbusinessUnit?: { typeId: \"business-unit\"; key: string };\n\t\t},\n\t): Promise<ApprovalRule> {\n\t\tconst businessUnitKey =\n\t\t\t(draft as any).businessUnit?.key ?? context.businessUnitKey;\n\t\tif (!businessUnitKey) {\n\t\t\tthrow new Error(\n\t\t\t\t\"ApprovalRule requires a businessUnit. Provide it either via the request path (as-associate route) or in the draft for direct creation.\",\n\t\t\t);\n\t\t}\n\n\t\tconst businessUnit = await getBusinessUnitKeyReference(\n\t\t\t{ typeId: \"business-unit\", key: businessUnitKey },\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage,\n\t\t);\n\n\t\tconst resource: ApprovalRule = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tkey: draft.key,\n\t\t\tname: draft.name,\n\t\t\tdescription: draft.description,\n\t\t\tstatus: draft.status,\n\t\t\tpredicate: draft.predicate,\n\t\t\tapprovers: await resolveApproverHierarchy(\n\t\t\t\tdraft.approvers,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t\trequesters: await resolveRequesters(\n\t\t\t\tdraft.requesters,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t\tbusinessUnit,\n\t\t\tcustom: await createCustomFields(\n\t\t\t\t(draft as any).custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t};\n\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n\nclass ApprovalRuleUpdateHandler\n\textends AbstractUpdateHandler\n\timplements\n\t\tPartial<UpdateHandlerInterface<ApprovalRule, ApprovalRuleUpdateAction>>\n{\n\tasync setApprovers(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ApprovalRule>,\n\t\t{ approvers }: ApprovalRuleSetApproversAction,\n\t) {\n\t\tresource.approvers = await resolveApproverHierarchy(\n\t\t\tapprovers,\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage,\n\t\t);\n\t}\n\n\tsetCustomField(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ApprovalRule>,\n\t\t{ name, value }: ApprovalRuleSetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ApprovalRule>,\n\t\t{ type, fields }: ApprovalRuleSetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n\n\tsetDescription(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ApprovalRule>,\n\t\t{ description }: ApprovalRuleSetDescriptionAction,\n\t) {\n\t\tresource.description = description;\n\t}\n\n\tsetKey(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ApprovalRule>,\n\t\t{ key }: ApprovalRuleSetKeyAction,\n\t) {\n\t\tresource.key = key;\n\t}\n\n\tsetName(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ApprovalRule>,\n\t\t{ name }: ApprovalRuleSetNameAction,\n\t) {\n\t\tresource.name = name;\n\t}\n\n\tsetPredicate(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ApprovalRule>,\n\t\t{ predicate }: ApprovalRuleSetPredicateAction,\n\t) {\n\t\tresource.predicate = predicate;\n\t}\n\n\tasync setRequesters(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ApprovalRule>,\n\t\t{ requesters }: ApprovalRuleSetRequestersAction,\n\t) {\n\t\tresource.requesters = await resolveRequesters(\n\t\t\trequesters,\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage,\n\t\t);\n\t}\n\n\tsetStatus(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ApprovalRule>,\n\t\t{ status }: ApprovalRuleSetStatusAction,\n\t) {\n\t\tresource.status = status;\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport { CompanyDraftSchema, DivisionDraftSchema } from \"./common.ts\";\n\nexport const BusinessUnitDraftSchema = z.discriminatedUnion(\"unitType\", [\n\tCompanyDraftSchema,\n\tDivisionDraftSchema,\n]);\n","import assert from \"node:assert\";\nimport type {\n\tAddress,\n\tAssociate,\n\tBusinessUnit,\n\tBusinessUnitAddAddressAction,\n\tBusinessUnitAddAssociateAction,\n\tBusinessUnitAddBillingAddressIdAction,\n\tBusinessUnitAddShippingAddressIdAction,\n\tBusinessUnitAddStoreAction,\n\tBusinessUnitChangeAddressAction,\n\tBusinessUnitChangeApprovalRuleModeAction,\n\tBusinessUnitChangeAssociateAction,\n\tBusinessUnitChangeAssociateModeAction,\n\tBusinessUnitChangeNameAction,\n\tBusinessUnitChangeParentUnitAction,\n\tBusinessUnitChangeStatusAction,\n\tBusinessUnitDraft,\n\tBusinessUnitKeyReference,\n\tBusinessUnitRemoveAddressAction,\n\tBusinessUnitRemoveAssociateAction,\n\tBusinessUnitRemoveBillingAddressIdAction,\n\tBusinessUnitRemoveShippingAddressIdAction,\n\tBusinessUnitSetAddressCustomFieldAction,\n\tBusinessUnitSetAddressCustomTypeAction,\n\tBusinessUnitSetAssociatesAction,\n\tBusinessUnitSetContactEmailAction,\n\tBusinessUnitSetCustomFieldAction,\n\tBusinessUnitSetCustomTypeAction,\n\tBusinessUnitSetDefaultBillingAddressAction,\n\tBusinessUnitSetDefaultShippingAddressAction,\n\tBusinessUnitSetStoreModeAction,\n\tBusinessUnitUpdateAction,\n\tCompany,\n\tCompanyDraft,\n\tDivision,\n\tDivisionDraft,\n\tInvalidJsonInputError,\n\tInvalidOperationError,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { BusinessUnitDraftSchema } from \"#src/schemas/generated/business-unit.ts\";\nimport { generateRandomString, getBaseResourceProperties } from \"../helpers.ts\";\nimport type { Writable } from \"../types.ts\";\nimport type { UpdateHandlerInterface } from \"./abstract.ts\";\nimport {\n\tAbstractResourceRepository,\n\tAbstractUpdateHandler,\n\ttype RepositoryContext,\n} from \"./abstract.ts\";\nimport {\n\tcreateAddress,\n\tcreateAssociate,\n\tcreateCustomFields,\n\tgetBusinessUnitKeyReference,\n\tgetStoreKeyReference,\n} from \"./helpers.ts\";\n\nexport class BusinessUnitRepository extends AbstractResourceRepository<\"business-unit\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"business-unit\", config);\n\t\tthis.actions = new BusinessUnitUpdateHandler(this._storage);\n\t\tthis.draftSchema = BusinessUnitDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: BusinessUnitDraft,\n\t): Promise<BusinessUnit> {\n\t\tconst addresses =\n\t\t\tdraft.addresses?.map((address) => ({\n\t\t\t\t...address,\n\t\t\t\tid: generateRandomString(5),\n\t\t\t})) ?? [];\n\n\t\tconst defaultBillingAddressId =\n\t\t\taddresses.length > 0 && draft.defaultBillingAddress !== undefined\n\t\t\t\t? addresses[draft.defaultBillingAddress].id\n\t\t\t\t: undefined;\n\t\tconst defaultShippingAddressId =\n\t\t\taddresses.length > 0 && draft.defaultShippingAddress !== undefined\n\t\t\t\t? addresses[draft.defaultShippingAddress].id\n\t\t\t\t: undefined;\n\n\t\tconst shippingAddressIds = draft.shippingAddresses?.map(\n\t\t\t(i) => addresses[i].id,\n\t\t);\n\t\tconst billingAddressIds = draft.billingAddresses?.map(\n\t\t\t(i) => addresses[i].id,\n\t\t);\n\n\t\tconst stores = draft.stores\n\t\t\t? await Promise.all(\n\t\t\t\t\tdraft.stores.map((s) =>\n\t\t\t\t\t\tgetStoreKeyReference(s, context.projectKey, this._storage),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t: undefined;\n\n\t\tconst associates = draft.associates\n\t\t\t? await Promise.all(\n\t\t\t\t\tdraft.associates.map((a) =>\n\t\t\t\t\t\tcreateAssociate(a, context.projectKey, this._storage),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t: [];\n\n\t\tconst resource = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tkey: draft.key,\n\t\t\tstatus: draft.status,\n\t\t\tstores,\n\t\t\tstoreMode: draft.storeMode,\n\t\t\tname: draft.name,\n\t\t\tcontactEmail: draft.contactEmail,\n\t\t\taddresses: addresses,\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t\tshippingAddressIds: shippingAddressIds,\n\t\t\tbillingAddressIds: billingAddressIds,\n\t\t\tdefaultShippingAddressId: defaultShippingAddressId,\n\t\t\tdefaultBillingAddressId: defaultBillingAddressId,\n\t\t\tassociateMode: draft.associateMode,\n\t\t\tapprovalRuleMode: draft.approvalRuleMode,\n\t\t\tassociates,\n\t\t};\n\n\t\tif (this._isDivisionDraft(draft)) {\n\t\t\tconst parentUnit = await getBusinessUnitKeyReference(\n\t\t\t\tdraft.parentUnit,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t);\n\t\t\t// Look up the parent to determine the topLevelUnit\n\t\t\tconst parent = (await this._storage.getByResourceIdentifier(\n\t\t\t\tcontext.projectKey,\n\t\t\t\tparentUnit,\n\t\t\t)) as BusinessUnit | undefined;\n\t\t\tconst topLevelUnit: BusinessUnitKeyReference = parent?.topLevelUnit ?? {\n\t\t\t\ttypeId: \"business-unit\",\n\t\t\t\tkey: parentUnit.key!,\n\t\t\t};\n\t\t\tconst division = {\n\t\t\t\t...resource,\n\t\t\t\tunitType: \"Division\" as const,\n\t\t\t\tparentUnit,\n\t\t\t\ttopLevelUnit,\n\t\t\t} as Division;\n\n\t\t\tawait this.saveNew(context, division);\n\t\t\treturn division;\n\t\t}\n\t\tif (this._isCompanyDraft(draft)) {\n\t\t\tconst company = {\n\t\t\t\t...resource,\n\t\t\t\tunitType: \"Company\" as const,\n\t\t\t\ttopLevelUnit: {\n\t\t\t\t\ttypeId: \"business-unit\" as const,\n\t\t\t\t\tkey: draft.key,\n\t\t\t\t},\n\t\t\t} as Company;\n\n\t\t\tawait this.saveNew(context, company);\n\t\t\treturn company;\n\t\t}\n\n\t\tthrow new CommercetoolsError<InvalidJsonInputError>(\n\t\t\t{\n\t\t\t\tcode: \"InvalidJsonInput\",\n\t\t\t\tmessage: \"Invalid business unit type\",\n\t\t\t\tdetailedErrorMessage: \"Invalid business unit type\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\tprivate _isCompanyDraft(draft: BusinessUnitDraft): draft is CompanyDraft {\n\t\treturn draft.unitType === \"Company\";\n\t}\n\n\tprivate _isDivisionDraft(draft: BusinessUnitDraft): draft is DivisionDraft {\n\t\treturn draft.unitType === \"Division\";\n\t}\n}\n\nclass BusinessUnitUpdateHandler\n\textends AbstractUpdateHandler\n\timplements\n\t\tPartial<UpdateHandlerInterface<BusinessUnit, BusinessUnitUpdateAction>>\n{\n\tasync addAddress(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ address }: BusinessUnitAddAddressAction,\n\t) {\n\t\tconst newAddress = createAddress(\n\t\t\taddress,\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage,\n\t\t);\n\t\tif (newAddress) {\n\t\t\tresource.addresses.push(newAddress);\n\t\t}\n\t}\n\n\tasync addAssociate(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ associate }: BusinessUnitAddAssociateAction,\n\t) {\n\t\tconst newAssociate = await createAssociate(\n\t\t\tassociate,\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage,\n\t\t);\n\t\tif (newAssociate) {\n\t\t\tresource.associates.push(newAssociate);\n\t\t}\n\t}\n\n\tasync addStore(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ store }: BusinessUnitAddStoreAction,\n\t) {\n\t\tconst newStore = await getStoreKeyReference(\n\t\t\tstore,\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage,\n\t\t);\n\t\tif (newStore) {\n\t\t\tif (!resource.stores) {\n\t\t\t\tresource.stores = [];\n\t\t\t}\n\n\t\t\tresource.stores.push(newStore);\n\t\t}\n\t}\n\n\tchangeAddress(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ addressId, addressKey, address }: BusinessUnitChangeAddressAction,\n\t) {\n\t\tconst current = this._findAddress(resource, addressId, addressKey, true);\n\t\tassert(current?.id); // always true since we set required to true\n\n\t\tconst oldAddressIndex = resource.addresses.findIndex(\n\t\t\t(a) => a.id === current.id,\n\t\t);\n\n\t\tconst newAddress = createAddress(\n\t\t\t{ ...address, id: current.id },\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage,\n\t\t);\n\n\t\tif (newAddress) {\n\t\t\tresource.addresses[oldAddressIndex] = newAddress;\n\t\t}\n\t}\n\n\tchangeApprovalRuleMode(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ approvalRuleMode }: BusinessUnitChangeApprovalRuleModeAction,\n\t) {\n\t\tresource.approvalRuleMode = approvalRuleMode;\n\t}\n\n\tchangeAssociateMode(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ associateMode }: BusinessUnitChangeAssociateModeAction,\n\t) {\n\t\tresource.associateMode = associateMode;\n\t}\n\n\tchangeName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ name }: BusinessUnitChangeNameAction,\n\t) {\n\t\tresource.name = name;\n\t}\n\n\tasync changeParentUnit(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ parentUnit }: BusinessUnitChangeParentUnitAction,\n\t) {\n\t\tresource.parentUnit = await getBusinessUnitKeyReference(\n\t\t\tparentUnit,\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage,\n\t\t);\n\t}\n\n\tchangeStatus(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ status }: BusinessUnitChangeStatusAction,\n\t) {\n\t\tresource.status = status;\n\t}\n\n\tasync setAssociates(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ associates }: BusinessUnitSetAssociatesAction,\n\t) {\n\t\tconst newAssociates = (\n\t\t\tawait Promise.all(\n\t\t\t\tassociates.map((a) =>\n\t\t\t\t\tcreateAssociate(a, context.projectKey, this._storage),\n\t\t\t\t),\n\t\t\t)\n\t\t).filter((a): a is Writable<Associate> => a !== undefined);\n\t\tresource.associates = newAssociates || undefined;\n\t}\n\n\tremoveAssociate(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ customer }: BusinessUnitRemoveAssociateAction,\n\t) {\n\t\tresource.associates = resource.associates.filter(\n\t\t\t(associate) => associate.customer.id !== customer.id,\n\t\t);\n\t}\n\n\tasync changeAssociate(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ associate }: BusinessUnitChangeAssociateAction,\n\t) {\n\t\tconst existingAssociateIndex = resource.associates.findIndex(\n\t\t\t(a) => a.customer.id === associate.customer.id,\n\t\t);\n\t\tif (existingAssociateIndex === -1) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: `Associate with customer id ${associate.customer.id} not found`,\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\tconst newAssociate = await createAssociate(\n\t\t\tassociate,\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage,\n\t\t);\n\t\tif (newAssociate) {\n\t\t\tresource.associates[existingAssociateIndex] = newAssociate;\n\t\t}\n\t}\n\n\tsetContactEmail(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ contactEmail }: BusinessUnitSetContactEmailAction,\n\t) {\n\t\tresource.contactEmail = contactEmail;\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ type, fields }: BusinessUnitSetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n\n\tsetStoreMode(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ storeMode }: BusinessUnitSetStoreModeAction,\n\t) {\n\t\tresource.storeMode = storeMode;\n\t}\n\n\tsetDefaultShippingAddress(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ addressId, addressKey }: BusinessUnitSetDefaultShippingAddressAction,\n\t) {\n\t\tconst address = this._findAddress(resource, addressId, addressKey, true);\n\t\tassert(address?.id); // always true since we set required to true\n\n\t\tresource.defaultShippingAddressId = address.id;\n\t\tif (resource.shippingAddressIds === undefined) {\n\t\t\tresource.shippingAddressIds = [];\n\t\t}\n\t\tif (!resource.shippingAddressIds.includes(address.id)) {\n\t\t\tresource.shippingAddressIds.push(address.id);\n\t\t}\n\t}\n\n\taddShippingAddressId(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ addressId, addressKey }: BusinessUnitAddShippingAddressIdAction,\n\t) {\n\t\tconst address = this._findAddress(resource, addressId, addressKey, true);\n\t\tassert(address?.id); // always true since we set required to true\n\n\t\tif (resource.shippingAddressIds === undefined) {\n\t\t\tresource.shippingAddressIds = [];\n\t\t}\n\n\t\tif (!resource.shippingAddressIds.includes(address.id)) {\n\t\t\tresource.shippingAddressIds.push(address.id);\n\t\t}\n\t}\n\n\tremoveShippingAddressId(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ addressId, addressKey }: BusinessUnitRemoveShippingAddressIdAction,\n\t) {\n\t\tconst address = this._findAddress(resource, addressId, addressKey, true);\n\t\tassert(address?.id); // always true since we set required to true\n\t\tresource.shippingAddressIds = resource.shippingAddressIds?.filter(\n\t\t\t(id) => id !== address.id,\n\t\t);\n\t\tif (resource.defaultShippingAddressId === address.id) {\n\t\t\tresource.defaultShippingAddressId = undefined;\n\t\t}\n\t}\n\n\taddBillingAddressId(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ addressId, addressKey }: BusinessUnitAddBillingAddressIdAction,\n\t) {\n\t\tconst address = this._findAddress(resource, addressId, addressKey, true);\n\t\tassert(address?.id); // always true since we set required to true\n\n\t\tif (resource.billingAddressIds === undefined) {\n\t\t\tresource.billingAddressIds = [];\n\t\t}\n\n\t\tif (!resource.billingAddressIds.includes(address.id)) {\n\t\t\tresource.billingAddressIds.push(address.id);\n\t\t}\n\t}\n\n\tremoveBillingAddressId(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ addressId, addressKey }: BusinessUnitRemoveBillingAddressIdAction,\n\t) {\n\t\tconst address = this._findAddress(resource, addressId, addressKey, true);\n\t\tassert(address?.id); // always true since we set required to true\n\t\tresource.billingAddressIds = resource.billingAddressIds?.filter(\n\t\t\t(id) => id !== address.id,\n\t\t);\n\t\tif (resource.defaultBillingAddressId === address.id) {\n\t\t\tresource.defaultBillingAddressId = undefined;\n\t\t}\n\t}\n\n\tsetDefaultBillingAddress(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ addressId, addressKey }: BusinessUnitSetDefaultBillingAddressAction,\n\t) {\n\t\tconst address = this._findAddress(resource, addressId, addressKey, true);\n\t\tassert(address?.id); // always true since we set required to true\n\n\t\tresource.defaultBillingAddressId = address.id;\n\t\tif (resource.billingAddressIds === undefined) {\n\t\t\tresource.billingAddressIds = [];\n\t\t}\n\t\tif (!resource.billingAddressIds.includes(address.id)) {\n\t\t\tresource.billingAddressIds.push(address.id);\n\t\t}\n\t}\n\n\tsetCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ name, value }: BusinessUnitSetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tsetAddressCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ addressId, name, value }: BusinessUnitSetAddressCustomFieldAction,\n\t) {\n\t\tconst address = resource.addresses.find((addr) => addr.id === addressId);\n\t\tif (!address) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: `Address with id ${addressId} not found`,\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tif (!address.custom) {\n\t\t\t// If the address doesn't have custom fields, we need to initialize them\n\t\t\t// This might require a type to be set first, but we'll just create minimal structure\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t\"Address has no custom type set. Use setAddressCustomType first.\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\taddress.custom.fields[name] = value;\n\t}\n\n\tasync setAddressCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ addressId, type, fields }: BusinessUnitSetAddressCustomTypeAction,\n\t) {\n\t\tconst address = resource.addresses.find((addr) => addr.id === addressId);\n\t\tif (!address) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: `Address with id ${addressId} not found`,\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\tif (!type) {\n\t\t\taddress.custom = undefined;\n\t\t} else {\n\t\t\taddress.custom = await createCustomFields(\n\t\t\t\t{ type, fields },\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t);\n\t\t}\n\t}\n\n\tremoveAddress(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<BusinessUnit>,\n\t\t{ addressId, addressKey }: BusinessUnitRemoveAddressAction,\n\t) {\n\t\tconst address = this._findAddress(resource, addressId, addressKey, true);\n\t\tassert(address?.id); // always true since we set required to true\n\t\tresource.addresses = resource.addresses.filter((a) => a.id !== address.id);\n\n\t\tif (resource.shippingAddressIds) {\n\t\t\tresource.shippingAddressIds = resource.shippingAddressIds.filter(\n\t\t\t\t(id) => id !== address.id,\n\t\t\t);\n\t\t}\n\t\tif (resource.billingAddressIds) {\n\t\t\tresource.billingAddressIds = resource.billingAddressIds.filter(\n\t\t\t\t(id) => id !== address.id,\n\t\t\t);\n\t\t}\n\n\t\tif (resource.defaultShippingAddressId === address.id) {\n\t\t\tresource.defaultShippingAddressId = undefined;\n\t\t}\n\t\tif (resource.defaultBillingAddressId === address.id) {\n\t\t\tresource.defaultBillingAddressId = undefined;\n\t\t}\n\t}\n\n\tprivate _findAddress(\n\t\tresource: Writable<BusinessUnit>,\n\t\taddressId: string | undefined,\n\t\taddressKey: string | undefined,\n\t\trequired = false,\n\t): Address | undefined {\n\t\tif (addressKey) {\n\t\t\tconst address = resource.addresses.find((a) => a.key === addressKey);\n\t\t\tif (!address) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: `Business Unit does not contain an address with the key ${addressKey}.`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn address;\n\t\t}\n\n\t\tif (addressId) {\n\t\t\tconst address = resource.addresses.find((a) => a.id === addressId);\n\t\t\tif (!address) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: `Business Unit does not contain an address with the id ${addressId}.`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn address;\n\t\t}\n\n\t\tif (required) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: \"One of address 'addressId' or 'addressKey' is required.\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t}\n}\n","import type {\n\tCart,\n\tExternalTaxAmountDraft,\n\tExternalTaxRateDraft,\n\tRoundingMode,\n\tTaxCategory,\n\tTaxedItemPrice,\n\tTaxedPrice,\n\tTaxPortion,\n\tTaxRate,\n} from \"@commercetools/platform-sdk\";\nimport { Decimal } from \"decimal.js\";\nimport {\n\tcreateCentPrecisionMoney,\n\troundDecimal,\n} from \"#src/repositories/helpers.ts\";\n\nconst roundCents = (value: number, mode: RoundingMode = \"HalfEven\"): number =>\n\troundDecimal(new Decimal(value), mode).toNumber();\n\nexport const buildTaxedPriceFromExternalAmount = (\n\tdraft: ExternalTaxAmountDraft,\n\troundingMode: RoundingMode = \"HalfEven\",\n): TaxedItemPrice => {\n\tconst taxRate = taxRateFromExternalDraft(draft.taxRate);\n\tconst totalGross = createCentPrecisionMoney(draft.totalGross);\n\tconst currencyCode = totalGross.currencyCode;\n\tconst toMoney = (centAmount: number) =>\n\t\tcreateCentPrecisionMoney({ currencyCode, centAmount });\n\n\tconst grossAmount = totalGross.centAmount;\n\t// totalGross is authoritative in ExternalAmount mode, so net is always\n\t// gross / (1 + rate) regardless of taxRate.includedInPrice. The flag is kept\n\t// on the stored taxRate for callers that read it back.\n\tconst taxAmount =\n\t\ttaxRate.amount > 0\n\t\t\t? roundCents(\n\t\t\t\t\tnew Decimal(grossAmount)\n\t\t\t\t\t\t.mul(taxRate.amount)\n\t\t\t\t\t\t.div(1 + taxRate.amount)\n\t\t\t\t\t\t.toNumber(),\n\t\t\t\t\troundingMode,\n\t\t\t\t)\n\t\t\t: 0;\n\tconst netAmount = grossAmount - taxAmount;\n\n\treturn {\n\t\ttotalNet: toMoney(netAmount),\n\t\ttotalGross,\n\t\ttotalTax: taxAmount > 0 ? toMoney(taxAmount) : undefined,\n\t\ttaxPortions:\n\t\t\ttaxAmount > 0\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trate: taxRate.amount,\n\t\t\t\t\t\t\tname: taxRate.name,\n\t\t\t\t\t\t\tamount: toMoney(taxAmount),\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: [],\n\t};\n};\n\nexport const taxRateFromExternalDraft = (\n\tdraft: ExternalTaxRateDraft,\n): TaxRate => {\n\tconst amount =\n\t\tdraft.amount ??\n\t\tdraft.subRates?.reduce((acc, subRate) => acc + subRate.amount, 0) ??\n\t\t0;\n\treturn {\n\t\tname: draft.name,\n\t\tamount,\n\t\tincludedInPrice: draft.includedInPrice ?? false,\n\t\tcountry: draft.country,\n\t\tstate: draft.state,\n\t\tsubRates: draft.subRates,\n\t};\n};\n\ntype TaxableResource = Pick<\n\tCart,\n\t\"lineItems\" | \"customLineItems\" | \"shippingInfo\" | \"totalPrice\"\n>;\n\nexport const calculateTaxTotals = (\n\tresource: TaxableResource,\n): {\n\ttaxedPrice?: TaxedPrice;\n\ttaxedShippingPrice?: TaxedItemPrice;\n} => {\n\tconst taxedItemPrices: TaxedItemPrice[] = [];\n\n\tresource.lineItems.forEach((item) => {\n\t\tif (item.taxedPrice) {\n\t\t\ttaxedItemPrices.push(item.taxedPrice);\n\t\t}\n\t});\n\n\tresource.customLineItems.forEach((item) => {\n\t\tif (item.taxedPrice) {\n\t\t\ttaxedItemPrices.push(item.taxedPrice);\n\t\t}\n\t});\n\n\tlet taxedShippingPrice: TaxedItemPrice | undefined;\n\tif (resource.shippingInfo?.taxedPrice) {\n\t\ttaxedShippingPrice = resource.shippingInfo.taxedPrice;\n\t\ttaxedItemPrices.push(resource.shippingInfo.taxedPrice);\n\t}\n\n\tif (!taxedItemPrices.length) {\n\t\treturn {\n\t\t\ttaxedPrice: undefined,\n\t\t\ttaxedShippingPrice,\n\t\t};\n\t}\n\n\tconst currencyCode = resource.totalPrice.currencyCode;\n\tconst toMoney = (centAmount: number) =>\n\t\tcreateCentPrecisionMoney({\n\t\t\tcurrencyCode,\n\t\t\tcentAmount,\n\t\t});\n\n\tlet totalNet = 0;\n\tlet totalGross = 0;\n\tlet totalTax = 0;\n\n\tconst taxPortionsByRate = new Map<\n\t\tstring,\n\t\t{ rate: number; name?: string; centAmount: number }\n\t>();\n\n\ttaxedItemPrices.forEach((price) => {\n\t\ttotalNet += price.totalNet.centAmount;\n\t\ttotalGross += price.totalGross.centAmount;\n\t\tconst priceTax = price.totalTax\n\t\t\t? price.totalTax.centAmount\n\t\t\t: price.totalGross.centAmount - price.totalNet.centAmount;\n\t\ttotalTax += Math.max(priceTax, 0);\n\n\t\tprice.taxPortions?.forEach((portion) => {\n\t\t\tconst key = `${portion.rate}-${portion.name ?? \"\"}`;\n\t\t\tconst existing = taxPortionsByRate.get(key) ?? {\n\t\t\t\trate: portion.rate,\n\t\t\t\tname: portion.name,\n\t\t\t\tcentAmount: 0,\n\t\t\t};\n\t\t\texisting.centAmount += portion.amount.centAmount;\n\t\t\ttaxPortionsByRate.set(key, existing);\n\t\t});\n\t});\n\n\tconst taxPortions: TaxPortion[] = Array.from(taxPortionsByRate.values()).map(\n\t\t(portion) => ({\n\t\t\trate: portion.rate,\n\t\t\tname: portion.name,\n\t\t\tamount: toMoney(portion.centAmount),\n\t\t}),\n\t);\n\n\treturn {\n\t\ttaxedPrice: {\n\t\t\ttotalNet: toMoney(totalNet),\n\t\t\ttotalGross: toMoney(totalGross),\n\t\t\ttaxPortions,\n\t\t\ttotalTax: totalTax > 0 ? toMoney(totalTax) : undefined,\n\t\t},\n\t\ttaxedShippingPrice,\n\t};\n};\n\nexport const calculateTaxedPriceFromRate = (\n\tamount: number,\n\tcurrencyCode: string,\n\ttaxRate?: TaxRate,\n\troundingMode: RoundingMode = \"HalfEven\",\n): TaxedItemPrice | undefined => {\n\tif (!taxRate) {\n\t\treturn undefined;\n\t}\n\n\tconst toMoney = (centAmount: number) =>\n\t\tcreateCentPrecisionMoney({\n\t\t\ttype: \"centPrecision\",\n\t\t\tcurrencyCode,\n\t\t\tcentAmount,\n\t\t});\n\n\tlet netAmount: number;\n\tlet grossAmount: number;\n\tlet taxAmount: number;\n\n\tif (taxRate.includedInPrice) {\n\t\tgrossAmount = amount;\n\t\ttaxAmount = roundCents(\n\t\t\tnew Decimal(grossAmount)\n\t\t\t\t.mul(taxRate.amount)\n\t\t\t\t.div(1 + taxRate.amount)\n\t\t\t\t.toNumber(),\n\t\t\troundingMode,\n\t\t);\n\t\tnetAmount = grossAmount - taxAmount;\n\t} else {\n\t\tnetAmount = amount;\n\t\ttaxAmount = roundCents(\n\t\t\tnew Decimal(netAmount).mul(taxRate.amount).toNumber(),\n\t\t\troundingMode,\n\t\t);\n\t\tgrossAmount = netAmount + taxAmount;\n\t}\n\n\treturn {\n\t\ttotalNet: toMoney(netAmount),\n\t\ttotalGross: toMoney(grossAmount),\n\t\ttotalTax: taxAmount > 0 ? toMoney(taxAmount) : undefined,\n\t\ttaxPortions:\n\t\t\ttaxAmount > 0\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trate: taxRate.amount,\n\t\t\t\t\t\t\tname: taxRate.name,\n\t\t\t\t\t\t\tamount: toMoney(taxAmount),\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: [],\n\t};\n};\n\nexport const calculateTaxedPrice = (\n\tamount: number,\n\ttaxCategory: TaxCategory | undefined,\n\tcurrency: string,\n\tcountry: string | undefined,\n\troundingMode: RoundingMode = \"HalfEven\",\n): TaxedPrice | undefined => {\n\tif (!taxCategory?.rates.length) {\n\t\treturn undefined;\n\t}\n\n\tconst taxRate =\n\t\ttaxCategory.rates.find(\n\t\t\t(rate) => !rate.country || rate.country === country,\n\t\t) || taxCategory.rates[0];\n\n\tconst taxedItemPrice = calculateTaxedPriceFromRate(\n\t\tamount,\n\t\tcurrency,\n\t\ttaxRate,\n\t\troundingMode,\n\t);\n\tif (!taxedItemPrice) {\n\t\treturn undefined;\n\t}\n\n\treturn {\n\t\ttotalNet: taxedItemPrice.totalNet,\n\t\ttotalGross: taxedItemPrice.totalGross,\n\t\ttaxPortions: taxedItemPrice.taxPortions,\n\t\ttotalTax: taxedItemPrice.totalTax,\n\t};\n};\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tBaseAddressSchema,\n\tBusinessUnitResourceIdentifierSchema,\n\tCartOriginSchema,\n\tCountryCodeSchema,\n\tCurrencyCodeSchema,\n\tCustomerGroupResourceIdentifierSchema,\n\tCustomFieldsDraftSchema,\n\tCustomLineItemDraftSchema,\n\tCustomShippingDraftSchema,\n\tExternalTaxRateDraftSchema,\n\tInventoryModeSchema,\n\tLineItemDraftSchema,\n\tLocaleSchema,\n\tRoundingModeSchema,\n\tShippingDraftSchema,\n\tShippingMethodResourceIdentifierSchema,\n\tShippingModeSchema,\n\tShippingRateInputDraftSchema,\n\tStoreResourceIdentifierSchema,\n\tTaxCalculationModeSchema,\n\tTaxModeSchema,\n} from \"./common.ts\";\n\nexport const CartDraftSchema = z.object({\n\tcurrency: CurrencyCodeSchema,\n\tkey: z.string().nullish(),\n\tcustomerId: z.string().nullish(),\n\tcustomerEmail: z.string().nullish(),\n\tcustomerGroup: CustomerGroupResourceIdentifierSchema.nullish(),\n\tanonymousId: z.string().nullish(),\n\tbusinessUnit: BusinessUnitResourceIdentifierSchema.nullish(),\n\tstore: StoreResourceIdentifierSchema.nullish(),\n\tlineItems: z.array(LineItemDraftSchema).nullish(),\n\tcustomLineItems: z.array(CustomLineItemDraftSchema).nullish(),\n\ttaxMode: TaxModeSchema.nullish(),\n\texternalTaxRateForShippingMethod: ExternalTaxRateDraftSchema.nullish(),\n\tpriceRoundingMode: RoundingModeSchema.nullish(),\n\ttaxRoundingMode: RoundingModeSchema.nullish(),\n\ttaxCalculationMode: TaxCalculationModeSchema.nullish(),\n\tinventoryMode: InventoryModeSchema.nullish(),\n\tbillingAddress: BaseAddressSchema.nullish(),\n\tshippingAddress: BaseAddressSchema.nullish(),\n\tshippingMethod: ShippingMethodResourceIdentifierSchema.nullish(),\n\tshippingRateInput: ShippingRateInputDraftSchema.nullish(),\n\tshippingMode: ShippingModeSchema.nullish(),\n\tcustomShipping: z.array(CustomShippingDraftSchema).nullish(),\n\tshipping: z.array(ShippingDraftSchema).nullish(),\n\titemShippingAddresses: z.array(BaseAddressSchema).nullish(),\n\tdiscountCodes: z.array(z.string()).nullish(),\n\tcountry: CountryCodeSchema.nullish(),\n\tlocale: LocaleSchema.nullish(),\n\torigin: CartOriginSchema.nullish(),\n\tdeleteDaysAfterLastModification: z.number().int().nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\tpurchaseOrderNumber: z.string().nullish(),\n});\n","import type {\n\tCart,\n\tCartValueTier,\n\tCentPrecisionMoney,\n\tExternalTaxRateDraft,\n\tInvalidOperationError,\n\tMissingTaxRateForCountryError,\n\tShippingInfo,\n\tShippingMethod,\n\tShippingRate,\n\tShippingRatePriceTier,\n\tTaxedItemPrice,\n\tTaxPortion,\n\tTaxRate,\n} from \"@commercetools/platform-sdk\";\nimport { Decimal } from \"decimal.js\";\nimport { CommercetoolsError } from \"./exceptions.ts\";\nimport { taxRateFromExternalDraft } from \"./lib/tax.ts\";\nimport type { GetParams, RepositoryContext } from \"./repositories/abstract.ts\";\nimport {\n\tcreateCentPrecisionMoney,\n\troundDecimal,\n} from \"./repositories/helpers.ts\";\nimport type { AbstractStorage } from \"./storage/abstract.ts\";\n\nexport const markMatchingShippingRate = (\n\tcart: Cart,\n\tshippingRate: ShippingRate,\n): ShippingRate => {\n\tconst isMatching =\n\t\tshippingRate.price.currencyCode === cart.totalPrice.currencyCode;\n\treturn {\n\t\t...shippingRate,\n\t\ttiers: markMatchingShippingRatePriceTiers(cart, shippingRate.tiers),\n\t\tisMatching: isMatching,\n\t};\n};\n\nexport const markMatchingShippingRatePriceTiers = (\n\tcart: Cart,\n\ttiers: ShippingRatePriceTier[],\n): ShippingRatePriceTier[] => {\n\tif (tiers.length === 0) {\n\t\treturn [];\n\t}\n\n\tif (new Set(tiers.map((tier) => tier.type)).size > 1) {\n\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t{\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"Can't handle multiple types of tiers\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\tconst tierType = tiers[0].type;\n\tswitch (tierType) {\n\t\tcase \"CartValue\":\n\t\t\treturn markMatchingCartValueTiers(cart, tiers as CartValueTier[]);\n\t\t// case 'CartClassification':\n\t\t// \treturn markMatchingCartClassificationTiers(cart, tiers)\n\t\t// case 'CartScore':\n\t\t// \treturn markMatchingCartScoreTiers(cart, tiers)\n\t\tdefault:\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: `Unsupported tier type: ${tierType}`,\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t}\n};\n\nconst markMatchingCartValueTiers = (\n\tcart: Cart,\n\ttiers: readonly CartValueTier[],\n): ShippingRatePriceTier[] => {\n\t// Sort tiers from high to low since we only want to match the highest tier\n\tconst sortedTiers = [...tiers].sort(\n\t\t(a, b) => b.minimumCentAmount - a.minimumCentAmount,\n\t);\n\n\t// Find the first tier that matches the cart and set the flag. We push\n\t// the results into a map so that we can output the tiers in the same order as\n\t// we received them.\n\tconst result: Record<number, ShippingRatePriceTier> = {};\n\tlet hasMatchingTier = false;\n\tfor (const tier of sortedTiers) {\n\t\tconst isMatching =\n\t\t\t!hasMatchingTier &&\n\t\t\tcart.totalPrice.currencyCode === tier.price.currencyCode &&\n\t\t\tcart.totalPrice.centAmount >= tier.minimumCentAmount;\n\n\t\tif (isMatching) hasMatchingTier = true;\n\t\tresult[tier.minimumCentAmount] = {\n\t\t\t...tier,\n\t\t\tisMatching: isMatching,\n\t\t};\n\t}\n\n\treturn tiers.map((tier) => result[tier.minimumCentAmount]);\n};\n\n/*\n * Retrieves all the ShippingMethods that can ship to the shipping address of\n * the given Cart. Each ShippingMethod contains exactly one ShippingRate with\n * the flag isMatching set to true. This ShippingRate is used when the\n * ShippingMethod is added to the Cart.\n */\nexport const getShippingMethodsMatchingCart = async (\n\tcontext: RepositoryContext,\n\tstorage: AbstractStorage,\n\tcart: Cart,\n\tparams: GetParams = {},\n) => {\n\tif (!cart.shippingAddress?.country) {\n\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\tcode: \"InvalidOperation\",\n\t\t\tmessage: `The cart with ID '${cart.id}' does not have a shipping address set.`,\n\t\t});\n\t}\n\n\t// Get all shipping methods that have a zone that matches the shipping address\n\tconst zones = await storage.query<\"zone\">(context.projectKey, \"zone\", {\n\t\twhere: [`locations(country=\"${cart.shippingAddress.country}\")`],\n\t\tlimit: 100,\n\t});\n\tconst zoneIds = zones.results.map((zone) => zone.id);\n\tconst shippingMethods = await storage.query<\"shipping-method\">(\n\t\tcontext.projectKey,\n\t\t\"shipping-method\",\n\t\t{\n\t\t\twhere: [\n\t\t\t\t\"zoneRates(zone(id in (:zoneIds)))\",\n\t\t\t\t`zoneRates(shippingRates(price(currencyCode=\"${cart.totalPrice.currencyCode}\")))`,\n\t\t\t],\n\t\t\t\"var.zoneIds\": zoneIds,\n\t\t\texpand: params.expand,\n\t\t},\n\t);\n\n\t// Make sure that each shipping method has exactly one shipping rate and\n\t// that the shipping rate is marked as matching\n\tconst results = shippingMethods.results\n\t\t.map((shippingMethod) => {\n\t\t\t// Iterate through the zoneRates, process the shipping rates and filter\n\t\t\t// out all zoneRates which have no matching shipping rates left\n\t\t\tconst rates = shippingMethod.zoneRates\n\t\t\t\t.map((zoneRate) => ({\n\t\t\t\t\tzone: zoneRate.zone,\n\n\t\t\t\t\t// Iterate through the shippingRates and mark the matching ones\n\t\t\t\t\t// then we filter out the non-matching ones\n\t\t\t\t\tshippingRates: zoneRate.shippingRates\n\t\t\t\t\t\t.map((rate) => markMatchingShippingRate(cart, rate))\n\t\t\t\t\t\t.filter((rate) => rate.isMatching),\n\t\t\t\t}))\n\t\t\t\t.filter((zoneRate) => zoneRate.shippingRates.length > 0);\n\n\t\t\treturn {\n\t\t\t\t...shippingMethod,\n\t\t\t\tzoneRates: rates,\n\t\t\t};\n\t\t})\n\t\t.filter((shippingMethod) => shippingMethod.zoneRates.length > 0);\n\n\treturn {\n\t\t...shippingMethods,\n\t\tresults: results,\n\t};\n};\n\n/**\n * Interface for cart-like objects that can be used for shipping calculations\n */\ninterface ShippingCalculationSource {\n\tid: string;\n\ttotalPrice: CentPrecisionMoney;\n\tshippingAddress?: {\n\t\tcountry: string;\n\t\t[key: string]: any;\n\t};\n\ttaxRoundingMode?: string;\n}\n\n/**\n * Creates shipping info from a shipping method, handling all tax calculations and pricing logic.\n */\nexport const createShippingInfoFromMethod = async (\n\tcontext: RepositoryContext,\n\tstorage: AbstractStorage,\n\tresource: ShippingCalculationSource,\n\tmethod: ShippingMethod,\n\texternalTaxRate?: ExternalTaxRateDraft,\n): Promise<Omit<ShippingInfo, \"deliveries\">> => {\n\tconst country = resource.shippingAddress!.country;\n\n\t// There should only be one zone rate matching the address, since\n\t// Locations cannot be assigned to more than one zone.\n\t// See https://docs.commercetools.com/api/projects/zones#location\n\tconst zoneRate = method.zoneRates.find((rate) =>\n\t\trate.zone.obj?.locations.some((loc) => loc.country === country),\n\t);\n\n\tif (!zoneRate) {\n\t\t// This shouldn't happen because getShippingMethodsMatchingCart already\n\t\t// filtered out shipping methods without any zones matching the address\n\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t{\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"Zone rate not found\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\t// Shipping rates are defined by currency, and getShippingMethodsMatchingCart\n\t// also matches on currency, so there should only be one in the array.\n\t// See https://docs.commercetools.com/api/projects/shippingMethods#zonerate\n\tconst shippingRate = zoneRate.shippingRates[0];\n\tif (!shippingRate) {\n\t\t// This shouldn't happen because getShippingMethodsMatchingCart already\n\t\t// filtered out shipping methods without any matching rates\n\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t{\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"Shipping rate not found\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\tlet taxRate: TaxRate | undefined;\n\tif (externalTaxRate) {\n\t\ttaxRate = taxRateFromExternalDraft(externalTaxRate);\n\t} else {\n\t\tconst taxCategory = await storage.getByResourceIdentifier<\"tax-category\">(\n\t\t\tcontext.projectKey,\n\t\t\tmethod.taxCategory,\n\t\t);\n\n\t\t// TODO: match state in addition to country\n\t\ttaxRate = taxCategory.rates.find((rate) => rate.country === country);\n\n\t\tif (!taxRate) {\n\t\t\tthrow new CommercetoolsError<MissingTaxRateForCountryError>({\n\t\t\t\tcode: \"MissingTaxRateForCountry\",\n\t\t\t\tmessage: `Tax category '${taxCategory.id}' is missing a tax rate for country '${country}'.`,\n\t\t\t\ttaxCategoryId: taxCategory.id,\n\t\t\t});\n\t\t}\n\t}\n\n\tconst shippingRateTier = shippingRate.tiers.find((tier) => tier.isMatching);\n\tif (shippingRateTier && shippingRateTier.type !== \"CartValue\") {\n\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t{\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"Non-CartValue shipping rate tier is not supported\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\tlet shippingPrice = shippingRateTier\n\t\t? createCentPrecisionMoney(shippingRateTier.price)\n\t\t: shippingRate.price;\n\n\t// Handle freeAbove: if total is above the freeAbove threshold, shipping is free\n\tif (\n\t\tshippingRate.freeAbove &&\n\t\tshippingRate.freeAbove.currencyCode === resource.totalPrice.currencyCode &&\n\t\tresource.totalPrice.centAmount >= shippingRate.freeAbove.centAmount\n\t) {\n\t\tshippingPrice = {\n\t\t\t...shippingPrice,\n\t\t\tcentAmount: 0,\n\t\t};\n\t}\n\n\t// Calculate tax amounts\n\tconst totalGross: CentPrecisionMoney = taxRate.includedInPrice\n\t\t? shippingPrice\n\t\t: {\n\t\t\t\t...shippingPrice,\n\t\t\t\tcentAmount: roundDecimal(\n\t\t\t\t\tnew Decimal(shippingPrice.centAmount).mul(1 + taxRate.amount),\n\t\t\t\t\tresource.taxRoundingMode || \"HalfEven\",\n\t\t\t\t).toNumber(),\n\t\t\t};\n\n\tconst totalNet: CentPrecisionMoney = taxRate.includedInPrice\n\t\t? {\n\t\t\t\t...shippingPrice,\n\t\t\t\tcentAmount: roundDecimal(\n\t\t\t\t\tnew Decimal(shippingPrice.centAmount).div(1 + taxRate.amount),\n\t\t\t\t\tresource.taxRoundingMode || \"HalfEven\",\n\t\t\t\t).toNumber(),\n\t\t\t}\n\t\t: shippingPrice;\n\n\tconst taxPortions: TaxPortion[] = [\n\t\t{\n\t\t\tname: taxRate.name,\n\t\t\trate: taxRate.amount,\n\t\t\tamount: {\n\t\t\t\t...shippingPrice,\n\t\t\t\tcentAmount: totalGross.centAmount - totalNet.centAmount,\n\t\t\t},\n\t\t},\n\t];\n\n\tconst totalTax: CentPrecisionMoney = {\n\t\t...shippingPrice,\n\t\tcentAmount: taxPortions.reduce(\n\t\t\t(acc, portion) => acc + portion.amount.centAmount,\n\t\t\t0,\n\t\t),\n\t};\n\n\tconst taxedPrice: TaxedItemPrice = {\n\t\ttotalNet,\n\t\ttotalGross,\n\t\ttaxPortions,\n\t\ttotalTax,\n\t};\n\n\treturn {\n\t\tshippingMethod: {\n\t\t\ttypeId: \"shipping-method\" as const,\n\t\t\tid: method.id,\n\t\t},\n\t\tshippingMethodName: method.name,\n\t\tprice: shippingPrice,\n\t\tshippingRate,\n\t\ttaxedPrice,\n\t\ttaxRate,\n\t\ttaxCategory: method.taxCategory,\n\t\tshippingMethodState: \"MatchesCart\",\n\t};\n};\n","import type {\n\tCart,\n\tCustomLineItem,\n\tCustomLineItemDraft,\n\tDiscountCodeInfo,\n\tDiscountCodeNonApplicableError,\n\tLineItem,\n\tPrice,\n\tRoundingMode,\n\tTaxCategory,\n\tTaxCategoryReference,\n\tTaxedItemPrice,\n\tTaxRate,\n} from \"@commercetools/platform-sdk\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport {\n\tcalculateTaxedPrice,\n\tcalculateTaxedPriceFromRate,\n\ttaxRateFromExternalDraft,\n} from \"#src/lib/tax.ts\";\nimport type { AbstractStorage } from \"#src/storage/abstract.ts\";\nimport {\n\tcalculateMoneyTotalCentAmount,\n\tcreateCentPrecisionMoney,\n\tcreateCustomFields,\n\tcreateTypedMoney,\n\tgetReferenceFromResourceIdentifier,\n} from \"../helpers.ts\";\n\nexport const selectPrice = ({\n\tprices,\n\tcurrency,\n\tcountry,\n}: {\n\tprices: Price[] | undefined;\n\tcurrency: string;\n\tcountry: string | undefined;\n}): Price | undefined => {\n\tif (!prices) {\n\t\treturn undefined;\n\t}\n\n\t// Quick-and-dirty way of selecting price based on the given currency and country.\n\t// Can be improved later to give more priority to exact matches over\n\t// 'all country' matches, and include customer groups in the mix as well\n\treturn prices.find((price) => {\n\t\tconst countryMatch = !price.country || price.country === country;\n\t\tconst currencyMatch = price.value.currencyCode === currency;\n\t\treturn countryMatch && currencyMatch;\n\t});\n};\n\nexport const calculateLineItemTotalPrice = (lineItem: LineItem): number => {\n\tif (!lineItem.price?.value) {\n\t\treturn 0;\n\t}\n\n\treturn calculateMoneyTotalCentAmount(lineItem.price.value, lineItem.quantity);\n};\n\nexport const computeItemTaxedPrice = (\n\titem: Pick<LineItem | CustomLineItem, \"taxRate\" | \"totalPrice\">,\n\troundingMode: RoundingMode = \"HalfEven\",\n): TaxedItemPrice | undefined => {\n\tif (!item.taxRate) return undefined;\n\treturn calculateTaxedPriceFromRate(\n\t\titem.totalPrice.centAmount,\n\t\titem.totalPrice.currencyCode,\n\t\titem.taxRate,\n\t\troundingMode,\n\t);\n};\n\nexport const calculateCartTotalPrice = (cart: Cart): number => {\n\tconst lineItemsTotal = cart.lineItems.reduce(\n\t\t(cur, item) => cur + item.totalPrice.centAmount,\n\t\t0,\n\t);\n\tconst customLineItemsTotal = cart.customLineItems.reduce(\n\t\t(cur, item) => cur + item.totalPrice.centAmount,\n\t\t0,\n\t);\n\treturn lineItemsTotal + customLineItemsTotal;\n};\n\nexport const createCustomLineItemFromDraft = async (\n\tprojectKey: string,\n\tdraft: CustomLineItemDraft,\n\tstorage: AbstractStorage,\n\tcountry?: string,\n\ttaxMode: Cart[\"taxMode\"] = \"Platform\",\n\troundingMode: RoundingMode = \"HalfEven\",\n): Promise<CustomLineItem> => {\n\tconst quantity = draft.quantity ?? 1;\n\n\tconst isTaxExternal = taxMode === \"External\";\n\n\tconst taxCategoryRef =\n\t\t!isTaxExternal && draft.taxCategory\n\t\t\t? await getReferenceFromResourceIdentifier<TaxCategoryReference>(\n\t\t\t\t\tdraft.taxCategory,\n\t\t\t\t\tprojectKey,\n\t\t\t\t\tstorage,\n\t\t\t\t)\n\t\t\t: undefined;\n\n\tlet taxCategory: TaxCategory | undefined;\n\tif (taxCategoryRef) {\n\t\ttry {\n\t\t\tconst result = await storage.get(\n\t\t\t\tprojectKey,\n\t\t\t\t\"tax-category\",\n\t\t\t\ttaxCategoryRef.id,\n\t\t\t\t{},\n\t\t\t);\n\t\t\ttaxCategory = result || undefined;\n\t\t} catch (_error) {\n\t\t\t// Tax category not found, continue without tax calculation\n\t\t}\n\t}\n\n\tconst totalPrice = createCentPrecisionMoney({\n\t\tcurrencyCode: draft.money.currencyCode,\n\t\tcentAmount: calculateMoneyTotalCentAmount(draft.money, quantity),\n\t});\n\n\tconst resolveTax = (): {\n\t\ttaxRate?: TaxRate;\n\t\ttaxedPrice?: TaxedItemPrice;\n\t} => {\n\t\tif (isTaxExternal) {\n\t\t\tif (!draft.externalTaxRate) return {};\n\t\t\tconst taxRate = taxRateFromExternalDraft(draft.externalTaxRate);\n\t\t\treturn {\n\t\t\t\ttaxRate,\n\t\t\t\ttaxedPrice: calculateTaxedPriceFromRate(\n\t\t\t\t\ttotalPrice.centAmount,\n\t\t\t\t\ttotalPrice.currencyCode,\n\t\t\t\t\ttaxRate,\n\t\t\t\t\troundingMode,\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\t\tif (!taxCategory) return {};\n\t\treturn {\n\t\t\ttaxRate: taxCategory.rates.find(\n\t\t\t\t(rate) => !rate.country || rate.country === country,\n\t\t\t),\n\t\t\ttaxedPrice: calculateTaxedPrice(\n\t\t\t\ttotalPrice.centAmount,\n\t\t\t\ttaxCategory,\n\t\t\t\ttotalPrice.currencyCode,\n\t\t\t\tcountry,\n\t\t\t\troundingMode,\n\t\t\t),\n\t\t};\n\t};\n\tconst { taxRate, taxedPrice } = resolveTax();\n\n\treturn {\n\t\tid: uuidv4(),\n\t\tkey: draft.key,\n\t\tname: draft.name,\n\t\tmoney: createTypedMoney(draft.money),\n\t\tslug: draft.slug,\n\t\tquantity: draft.quantity ?? 1,\n\t\tstate: [],\n\t\ttaxCategory: taxCategoryRef,\n\t\ttaxRate,\n\t\ttaxedPrice,\n\t\tcustom: await createCustomFields(draft.custom, projectKey, storage),\n\t\tdiscountedPricePerQuantity: [],\n\t\tperMethodTaxRate: [],\n\t\tpriceMode: draft.priceMode ?? \"Standard\",\n\t\ttotalPrice,\n\t\ttaxedPricePortions: [],\n\t};\n};\n\nexport const createDiscountCodeInfoFromCode = async (\n\tprojectKey: string,\n\tstorage: AbstractStorage,\n\tcode: string,\n): Promise<DiscountCodeInfo> => {\n\tconst discountCodes = await storage.query(projectKey, \"discount-code\", {\n\t\twhere: `code=\"${code}\"`,\n\t});\n\t// Does not validate anything besides existence of the DiscountCode object\n\tif (discountCodes.count === 0) {\n\t\tthrow new CommercetoolsError<DiscountCodeNonApplicableError>({\n\t\t\tcode: \"DiscountCodeNonApplicable\",\n\t\t\tmessage: `The discount code '${code}' was not found.`,\n\t\t\treason: \"DoesNotExist\",\n\t\t\tdiscountCode: code,\n\t\t});\n\t}\n\treturn {\n\t\tdiscountCode: {\n\t\t\ttypeId: \"discount-code\",\n\t\t\tid: discountCodes.results[0].id,\n\t\t},\n\t\tstate: \"MatchesCart\",\n\t};\n};\n","import type {\n\tAddress,\n\tAddressDraft,\n\tBaseResource,\n\tCart,\n\tCartAddCustomLineItemAction,\n\tCartAddItemShippingAddressAction,\n\tCartAddLineItemAction,\n\tCartAddPaymentAction,\n\tCartChangeCustomLineItemMoneyAction,\n\tCartChangeCustomLineItemQuantityAction,\n\tCartChangeLineItemQuantityAction,\n\tCartChangeTaxRoundingModeAction,\n\tCartFreezeCartAction,\n\tCartRemoveCustomLineItemAction,\n\tCartRemoveDiscountCodeAction,\n\tCartRemoveLineItemAction,\n\tCartRemovePaymentAction,\n\tCartRemoveShippingMethodAction,\n\tCartSetAnonymousIdAction,\n\tCartSetBillingAddressAction,\n\tCartSetBillingAddressCustomTypeAction,\n\tCartSetCartTotalTaxAction,\n\tCartSetCountryAction,\n\tCartSetCustomerEmailAction,\n\tCartSetCustomerIdAction,\n\tCartSetCustomFieldAction,\n\tCartSetCustomLineItemTaxAmountAction,\n\tCartSetCustomLineItemTaxRateAction,\n\tCartSetCustomShippingMethodAction,\n\tCartSetCustomTypeAction,\n\tCartSetDirectDiscountsAction,\n\tCartSetLineItemCustomFieldAction,\n\tCartSetLineItemCustomTypeAction,\n\tCartSetLineItemPriceAction,\n\tCartSetLineItemShippingDetailsAction,\n\tCartSetLineItemTaxAmountAction,\n\tCartSetLineItemTaxRateAction,\n\tCartSetLocaleAction,\n\tCartSetPurchaseOrderNumberAction,\n\tCartSetShippingAddressAction,\n\tCartSetShippingAddressCustomFieldAction,\n\tCartSetShippingAddressCustomTypeAction,\n\tCartSetShippingMethodAction,\n\tCartSetShippingMethodTaxAmountAction,\n\tCartSetShippingMethodTaxRateAction,\n\tCartUnfreezeCartAction,\n\tCartUpdateAction,\n\tCustomFields,\n\tGeneralError,\n\tInvalidOperationError,\n\tItemShippingDetails,\n\tLineItem,\n\tProduct,\n\tProductVariant,\n\tProject,\n\tReferencedResourceNotFoundError,\n\tTaxRate,\n\tUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type {\n\tCartAddDiscountCodeAction,\n\tCustomLineItem,\n\tDirectDiscount,\n} from \"@commercetools/platform-sdk/dist/declarations/src/generated/models/cart\";\nimport type { ShippingMethodResourceIdentifier } from \"@commercetools/platform-sdk/dist/declarations/src/generated/models/shipping-method\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport {\n\tbuildTaxedPriceFromExternalAmount,\n\tcalculateTaxedPriceFromRate,\n\tcalculateTaxTotals,\n\ttaxRateFromExternalDraft,\n} from \"#src/lib/tax.ts\";\nimport type { Writable } from \"#src/types.ts\";\nimport type { UpdateHandlerInterface } from \"../abstract.ts\";\nimport { AbstractUpdateHandler, type RepositoryContext } from \"../abstract.ts\";\nimport {\n\tcalculateMoneyTotalCentAmount,\n\tcreateAddress,\n\tcreateCentPrecisionMoney,\n\tcreateCustomFields,\n\tcreateTypedMoney,\n} from \"../helpers.ts\";\nimport {\n\tcalculateCartTotalPrice,\n\tcalculateLineItemTotalPrice,\n\tcomputeItemTaxedPrice,\n\tcreateCustomLineItemFromDraft,\n\tcreateDiscountCodeInfoFromCode,\n\tselectPrice,\n} from \"./helpers.ts\";\nimport type { CartRepository } from \"./index.ts\";\n\n/**\n * Freezing a cart locks in its prices, so the actions that would change what\n * the cart costs are rejected while it is frozen.\n * See https://docs.commercetools.com/api/projects/carts#freeze-cart\n */\nconst PRICE_CHANGING_ACTIONS = new Set([\n\t\"addCustomLineItem\",\n\t\"addDiscountCode\",\n\t\"addLineItem\",\n\t\"changeCustomLineItemMoney\",\n\t\"changeCustomLineItemQuantity\",\n\t\"changeLineItemQuantity\",\n\t\"changeTaxRoundingMode\",\n\t\"recalculate\",\n\t\"removeCustomLineItem\",\n\t\"removeDiscountCode\",\n\t\"removeLineItem\",\n\t\"removeShippingMethod\",\n\t\"setCartTotalTax\",\n\t\"setCountry\",\n\t\"setCustomLineItemTaxAmount\",\n\t\"setCustomLineItemTaxRate\",\n\t\"setCustomShippingMethod\",\n\t\"setDirectDiscounts\",\n\t\"setLineItemPrice\",\n\t\"setLineItemTaxAmount\",\n\t\"setLineItemTaxRate\",\n\t\"setShippingMethod\",\n\t\"setShippingMethodTaxAmount\",\n\t\"setShippingMethodTaxRate\",\n]);\n\nexport class CartUpdateHandler\n\textends AbstractUpdateHandler\n\timplements Partial<UpdateHandlerInterface<Cart, CartUpdateAction>>\n{\n\tprivate repository: CartRepository;\n\n\tconstructor(storage: any, repository: CartRepository) {\n\t\tsuper(storage);\n\t\tthis.repository = repository;\n\t}\n\n\tasync apply<R extends BaseResource | Project>(\n\t\tcontext: RepositoryContext,\n\t\tresource: R,\n\t\tversion: number,\n\t\tactions: UpdateAction[],\n\t): Promise<R> {\n\t\tconst updated = await super.apply(context, resource, version, actions);\n\t\tif (updated.version !== resource.version) {\n\t\t\tconst cart = updated as unknown as Writable<Cart>;\n\t\t\tif (cart.taxMode === \"ExternalAmount\") {\n\t\t\t\t// Cart total tax is set explicitly via setCartTotalTax — never\n\t\t\t\t// aggregate from line items. Shipping subtotal is just a mirror of\n\t\t\t\t// shippingInfo.taxedPrice and should still be kept in sync.\n\t\t\t\tcart.taxedShippingPrice = cart.shippingInfo?.taxedPrice;\n\t\t\t} else {\n\t\t\t\tconst { taxedPrice, taxedShippingPrice } = calculateTaxTotals(cart);\n\t\t\t\tcart.taxedPrice = taxedPrice;\n\t\t\t\tcart.taxedShippingPrice = taxedShippingPrice;\n\t\t\t}\n\t\t}\n\t\treturn updated;\n\t}\n\n\tprotected beforeAction(\n\t\tresource: BaseResource | Project,\n\t\taction: UpdateAction,\n\t) {\n\t\tconst cart = resource as unknown as Cart;\n\t\tif (\n\t\t\tcart.cartState === \"Frozen\" &&\n\t\t\tPRICE_CHANGING_ACTIONS.has(action.action)\n\t\t) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: `The cart with ID '${cart.id}' is frozen and cannot be modified by the action '${action.action}'.`,\n\t\t\t});\n\t\t}\n\t}\n\n\tfreezeCart(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t_action: CartFreezeCartAction,\n\t) {\n\t\tif (resource.cartState !== \"Active\") {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: `The cart with ID '${resource.id}' cannot be frozen because it is in state '${resource.cartState}'.`,\n\t\t\t});\n\t\t}\n\t\tresource.cartState = \"Frozen\";\n\t}\n\n\tunfreezeCart(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t_action: CartUnfreezeCartAction,\n\t) {\n\t\tif (resource.cartState !== \"Frozen\") {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: `The cart with ID '${resource.id}' cannot be unfrozen because it is in state '${resource.cartState}'.`,\n\t\t\t});\n\t\t}\n\t\tresource.cartState = \"Active\";\n\t}\n\n\taddItemShippingAddress(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ action, address }: CartAddItemShippingAddressAction,\n\t) {\n\t\tconst newAddress = createAddress(\n\t\t\taddress,\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage,\n\t\t);\n\t\tif (newAddress) {\n\t\t\tresource.itemShippingAddresses.push(newAddress);\n\t\t}\n\t}\n\n\tasync addLineItem(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{\n\t\t\tproductId,\n\t\t\tvariantId,\n\t\t\tsku,\n\t\t\tcustom,\n\t\t\tquantity = 1,\n\t\t\taddedAt,\n\t\t\tkey,\n\t\t\texternalTaxRate,\n\t\t}: CartAddLineItemAction,\n\t) {\n\t\tlet product: Product | null = null;\n\n\t\tif (productId && variantId) {\n\t\t\t// Fetch product and variant by ID\n\t\t\tproduct = await this._storage.get(\n\t\t\t\tcontext.projectKey,\n\t\t\t\t\"product\",\n\t\t\t\tproductId,\n\t\t\t\t{},\n\t\t\t);\n\t\t} else if (sku) {\n\t\t\t// Fetch product and variant by SKU\n\t\t\tconst items = await this._storage.query(context.projectKey, \"product\", {\n\t\t\t\twhere: [\n\t\t\t\t\t`masterData(current(masterVariant(sku=\"${sku}\"))) or masterData(current(variants(sku=\"${sku}\")))`,\n\t\t\t\t],\n\t\t\t});\n\n\t\t\tif (items.count === 1) {\n\t\t\t\tproduct = items.results[0];\n\t\t\t}\n\t\t}\n\n\t\tif (!product) {\n\t\t\t// Check if product is found\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: \"General\",\n\t\t\t\tmessage: sku\n\t\t\t\t\t? `A product containing a variant with SKU '${sku}' not found.`\n\t\t\t\t\t: `A product with ID '${productId}' not found.`,\n\t\t\t});\n\t\t}\n\n\t\t// Find matching variant\n\t\tconst variant: ProductVariant | undefined = [\n\t\t\tproduct.masterData.current.masterVariant,\n\t\t\t...product.masterData.current.variants,\n\t\t].find((x) => {\n\t\t\tif (sku) return x.sku === sku;\n\t\t\tif (variantId) return x.id === variantId;\n\t\t\treturn false;\n\t\t});\n\n\t\tif (!variant) {\n\t\t\t// Check if variant is found\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: \"General\",\n\t\t\t\tmessage: sku\n\t\t\t\t\t? `A variant with SKU '${sku}' for product '${product.id}' not found.`\n\t\t\t\t\t: `A variant with ID '${variantId}' for product '${product.id}' not found.`,\n\t\t\t});\n\t\t}\n\n\t\tconst alreadyAdded = resource.lineItems.some(\n\t\t\t(x) => x.productId === product?.id && x.variant.id === variant?.id,\n\t\t);\n\t\tif (alreadyAdded) {\n\t\t\t// increase quantity and update total price\n\t\t\tresource.lineItems.forEach((x) => {\n\t\t\t\tif (x.productId === product?.id && x.variant.id === variant?.id) {\n\t\t\t\t\tx.quantity += quantity;\n\t\t\t\t\tx.totalPrice.centAmount = calculateLineItemTotalPrice(x);\n\t\t\t\t\tx.taxedPrice = computeItemTaxedPrice(x, resource.taxRoundingMode);\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\t// add line item\n\t\t\tif (!variant.prices?.length) {\n\t\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\t\tcode: \"General\",\n\t\t\t\t\tmessage: `A product with ID '${productId}' doesn't have any prices.`,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst currency = resource.totalPrice.currencyCode;\n\n\t\t\tconst price = selectPrice({\n\t\t\t\tprices: variant.prices,\n\t\t\t\tcurrency,\n\t\t\t\tcountry: resource.country,\n\t\t\t});\n\t\t\tif (!price) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: `No valid price found for ${productId} for country ${resource.country} and currency ${currency}`,\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst totalPrice = createCentPrecisionMoney({\n\t\t\t\tcurrencyCode: price.value.currencyCode,\n\t\t\t\tcentAmount: calculateMoneyTotalCentAmount(price.value, quantity),\n\t\t\t});\n\t\t\tconst taxRate =\n\t\t\t\tresource.taxMode === \"External\" && externalTaxRate\n\t\t\t\t\t? taxRateFromExternalDraft(externalTaxRate)\n\t\t\t\t\t: undefined;\n\t\t\tconst taxedPrice = taxRate\n\t\t\t\t? calculateTaxedPriceFromRate(\n\t\t\t\t\t\ttotalPrice.centAmount,\n\t\t\t\t\t\ttotalPrice.currencyCode,\n\t\t\t\t\t\ttaxRate,\n\t\t\t\t\t\tresource.taxRoundingMode,\n\t\t\t\t\t)\n\t\t\t\t: undefined;\n\t\t\tresource.lineItems.push({\n\t\t\t\tid: uuidv4(),\n\t\t\t\tkey,\n\t\t\t\taddedAt: addedAt ? addedAt : new Date().toISOString(),\n\t\t\t\tproductId: product.id,\n\t\t\t\tproductKey: product.key,\n\t\t\t\tproductSlug: product.masterData.current.slug,\n\t\t\t\tproductType: product.productType,\n\t\t\t\tname: product.masterData.current.name,\n\t\t\t\tvariant,\n\t\t\t\tprice: price,\n\t\t\t\ttaxRate,\n\t\t\t\ttaxedPrice,\n\t\t\t\ttaxedPricePortions: [],\n\t\t\t\tperMethodTaxRate: [],\n\t\t\t\ttotalPrice,\n\t\t\t\tquantity,\n\t\t\t\tdiscountedPricePerQuantity: [],\n\t\t\t\tlineItemMode: \"Standard\",\n\t\t\t\tpriceMode: \"Platform\",\n\t\t\t\tstate: [],\n\t\t\t\tcustom: await createCustomFields(\n\t\t\t\t\tcustom,\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tthis._storage,\n\t\t\t\t),\n\t\t\t});\n\t\t}\n\n\t\t// Update cart total price\n\t\tresource.totalPrice.centAmount = calculateCartTotalPrice(resource);\n\t}\n\n\tasync addPayment(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ payment }: CartAddPaymentAction,\n\t) {\n\t\tconst resolvedPayment = await this._storage.getByResourceIdentifier(\n\t\t\tcontext.projectKey,\n\t\t\tpayment,\n\t\t);\n\t\tif (!resolvedPayment) {\n\t\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>({\n\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\tmessage: `Payment ${payment.id} not found`,\n\t\t\t\ttypeId: \"payment\",\n\t\t\t});\n\t\t}\n\n\t\tif (!resource.paymentInfo) {\n\t\t\tresource.paymentInfo = {\n\t\t\t\tpayments: [],\n\t\t\t};\n\t\t}\n\n\t\tresource.paymentInfo.payments.push({\n\t\t\ttypeId: \"payment\",\n\t\t\tid: resolvedPayment.id,\n\t\t});\n\t}\n\n\tasync removePayment(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ payment }: CartRemovePaymentAction,\n\t) {\n\t\tconst resolvedPayment = await this._storage.getByResourceIdentifier(\n\t\t\tcontext.projectKey,\n\t\t\tpayment,\n\t\t);\n\t\tif (!resolvedPayment) {\n\t\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>({\n\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\tmessage: `Payment ${payment.id} not found`,\n\t\t\t\ttypeId: \"payment\",\n\t\t\t});\n\t\t}\n\n\t\tif (!resource.paymentInfo) {\n\t\t\treturn;\n\t\t}\n\n\t\tresource.paymentInfo.payments = resource.paymentInfo.payments.filter(\n\t\t\t(reference) => reference.id !== resolvedPayment.id,\n\t\t);\n\n\t\tif (resource.paymentInfo.payments.length === 0) {\n\t\t\tresource.paymentInfo = undefined;\n\t\t}\n\t}\n\n\tchangeLineItemQuantity(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ lineItemId, lineItemKey, quantity }: CartChangeLineItemQuantityAction,\n\t) {\n\t\tlet lineItem: Writable<LineItem> | undefined;\n\n\t\tif (lineItemId) {\n\t\t\tlineItem = resource.lineItems.find((x) => x.id === lineItemId);\n\t\t\tif (!lineItem) {\n\t\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\t\tcode: \"General\",\n\t\t\t\t\tmessage: `A line item with ID '${lineItemId}' not found.`,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (lineItemKey) {\n\t\t\tlineItem = resource.lineItems.find((x) => x.id === lineItemId);\n\t\t\tif (!lineItem) {\n\t\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\t\tcode: \"General\",\n\t\t\t\t\tmessage: `A line item with Key '${lineItemKey}' not found.`,\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: \"General\",\n\t\t\t\tmessage: \"Either lineItemid or lineItemKey needs to be provided.\",\n\t\t\t});\n\t\t}\n\n\t\tif (quantity === 0) {\n\t\t\t// delete line item\n\t\t\tresource.lineItems = resource.lineItems.filter(\n\t\t\t\t(x) => x.id !== lineItemId,\n\t\t\t);\n\t\t} else {\n\t\t\tresource.lineItems.forEach((x) => {\n\t\t\t\tif (x.id === lineItemId && quantity) {\n\t\t\t\t\tx.quantity = quantity;\n\t\t\t\t\tx.totalPrice.centAmount = calculateLineItemTotalPrice(x);\n\t\t\t\t\tx.taxedPrice = computeItemTaxedPrice(x, resource.taxRoundingMode);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\t// Update cart total price\n\t\tresource.totalPrice.centAmount = calculateCartTotalPrice(resource);\n\t}\n\n\tchangeTaxRoundingMode(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ taxRoundingMode }: CartChangeTaxRoundingModeAction,\n\t) {\n\t\tresource.taxRoundingMode = taxRoundingMode;\n\t}\n\n\trecalculate() {\n\t\t// Dummy action when triggering a recalculation of the cart\n\t\t//\n\t\t// From commercetools documentation:\n\t\t// This update action does not set any Cart field in particular,\n\t\t// but it triggers several Cart updates to bring prices and discounts to the latest state.\n\t\t// Those can become stale over time when no Cart updates have been performed for a while\n\t\t// and prices on related Products have changed in the meanwhile.\n\t}\n\n\tasync addDiscountCode(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ code }: CartAddDiscountCodeAction,\n\t) {\n\t\tconst info = await createDiscountCodeInfoFromCode(\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage,\n\t\t\tcode,\n\t\t);\n\t\tif (\n\t\t\t!resource.discountCodes\n\t\t\t\t.map((dc) => dc.discountCode.id)\n\t\t\t\t.includes(info.discountCode.id)\n\t\t) {\n\t\t\tresource.discountCodes.push(info);\n\t\t}\n\t}\n\n\tremoveDiscountCode(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ discountCode }: CartRemoveDiscountCodeAction,\n\t) {\n\t\tresource.discountCodes = resource.discountCodes.filter(\n\t\t\t(code) => code.discountCode.id !== discountCode.id,\n\t\t);\n\t}\n\n\tremoveLineItem(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ lineItemId, quantity }: CartRemoveLineItemAction,\n\t) {\n\t\tconst lineItem = resource.lineItems.find((x) => x.id === lineItemId);\n\t\tif (!lineItem) {\n\t\t\t// Check if product is found\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: \"General\",\n\t\t\t\tmessage: `A line item with ID '${lineItemId}' not found.`,\n\t\t\t});\n\t\t}\n\n\t\tconst shouldDelete = !quantity || quantity >= lineItem.quantity;\n\t\tif (shouldDelete) {\n\t\t\t// delete line item\n\t\t\tresource.lineItems = resource.lineItems.filter(\n\t\t\t\t(x) => x.id !== lineItemId,\n\t\t\t);\n\t\t} else {\n\t\t\t// decrease quantity and update total price\n\t\t\tresource.lineItems.forEach((x) => {\n\t\t\t\tif (x.id === lineItemId && quantity) {\n\t\t\t\t\tx.quantity -= quantity;\n\t\t\t\t\tx.totalPrice.centAmount = calculateLineItemTotalPrice(x);\n\t\t\t\t\tx.taxedPrice = computeItemTaxedPrice(x, resource.taxRoundingMode);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\t// Update cart total price\n\t\tresource.totalPrice.centAmount = calculateCartTotalPrice(resource);\n\t}\n\n\tasync addCustomLineItem(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{\n\t\t\tmoney,\n\t\t\tname,\n\t\t\tslug,\n\t\t\tquantity = 1,\n\t\t\ttaxCategory,\n\t\t\texternalTaxRate,\n\t\t\tcustom,\n\t\t\tpriceMode = \"Standard\",\n\t\t\tkey,\n\t\t}: CartAddCustomLineItemAction,\n\t) {\n\t\tconst customLineItem = await createCustomLineItemFromDraft(\n\t\t\tcontext.projectKey,\n\t\t\t{\n\t\t\t\tmoney,\n\t\t\t\tname,\n\t\t\t\tslug,\n\t\t\t\tquantity,\n\t\t\t\ttaxCategory,\n\t\t\t\texternalTaxRate,\n\t\t\t\tcustom,\n\t\t\t\tpriceMode,\n\t\t\t\tkey,\n\t\t\t},\n\t\t\tthis._storage,\n\t\t\tresource.shippingAddress?.country ?? resource.country,\n\t\t\tresource.taxMode,\n\t\t\tresource.taxRoundingMode,\n\t\t);\n\n\t\tresource.customLineItems.push(customLineItem);\n\t\tresource.totalPrice.centAmount = calculateCartTotalPrice(resource);\n\t}\n\n\tremoveCustomLineItem(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ customLineItemId, customLineItemKey }: CartRemoveCustomLineItemAction,\n\t) {\n\t\tlet customLineItem;\n\n\t\tif (!customLineItemId && !customLineItemKey) {\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: \"General\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"Either customLineItemId or customLineItemKey needs to be provided.\",\n\t\t\t});\n\t\t}\n\n\t\tif (customLineItemId) {\n\t\t\tcustomLineItem = resource.customLineItems.find(\n\t\t\t\t(x) => x.id === customLineItemId,\n\t\t\t);\n\t\t\tif (!customLineItem) {\n\t\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\t\tcode: \"General\",\n\t\t\t\t\tmessage: `A custom line item with ID '${customLineItemId}' not found.`,\n\t\t\t\t});\n\t\t\t}\n\t\t\tresource.customLineItems = resource.customLineItems.filter(\n\t\t\t\t(x) => x.id !== customLineItemId,\n\t\t\t);\n\t\t}\n\n\t\tif (customLineItemKey) {\n\t\t\tcustomLineItem = resource.customLineItems.find(\n\t\t\t\t(x) => x.key === customLineItemKey,\n\t\t\t);\n\t\t\tif (!customLineItem) {\n\t\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\t\tcode: \"General\",\n\t\t\t\t\tmessage: `A custom line item with key '${customLineItemKey}' not found.`,\n\t\t\t\t});\n\t\t\t}\n\t\t\tresource.customLineItems = resource.customLineItems.filter(\n\t\t\t\t(x) => x.key !== customLineItemKey,\n\t\t\t);\n\t\t}\n\n\t\tresource.totalPrice.centAmount = calculateCartTotalPrice(resource);\n\t}\n\n\tchangeCustomLineItemQuantity(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{\n\t\t\tcustomLineItemId,\n\t\t\tcustomLineItemKey,\n\t\t\tquantity,\n\t\t}: CartChangeCustomLineItemQuantityAction,\n\t) {\n\t\tlet customLineItem;\n\n\t\tif (!customLineItemId && !customLineItemKey) {\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: \"General\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"Either customLineItemId or customLineItemKey needs to be provided.\",\n\t\t\t});\n\t\t}\n\n\t\tconst setQuantity = (\n\t\t\tcustomLineItem: Writable<CustomLineItem> | undefined,\n\t\t) => {\n\t\t\tif (!customLineItem) {\n\t\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\t\tcode: \"General\",\n\t\t\t\t\tmessage: `A custom line item with ${customLineItemId ? `ID '${customLineItemId}'` : `key '${customLineItemKey}'`} not found.`,\n\t\t\t\t});\n\t\t\t}\n\t\t\tcustomLineItem.quantity = quantity;\n\t\t\tcustomLineItem.totalPrice = createCentPrecisionMoney({\n\t\t\t\tcurrencyCode: customLineItem.money.currencyCode,\n\t\t\t\tcentAmount: calculateMoneyTotalCentAmount(\n\t\t\t\t\tcustomLineItem.money,\n\t\t\t\t\tquantity,\n\t\t\t\t),\n\t\t\t});\n\t\t\tcustomLineItem.taxedPrice = computeItemTaxedPrice(\n\t\t\t\tcustomLineItem,\n\t\t\t\tresource.taxRoundingMode,\n\t\t\t);\n\t\t};\n\n\t\tif (customLineItemId) {\n\t\t\tcustomLineItem = resource.customLineItems.find(\n\t\t\t\t(x) => x.id === customLineItemId,\n\t\t\t);\n\t\t\tsetQuantity(customLineItem);\n\t\t}\n\n\t\tif (customLineItemKey) {\n\t\t\tcustomLineItem = resource.customLineItems.find(\n\t\t\t\t(x) => x.key === customLineItemKey,\n\t\t\t);\n\t\t\tsetQuantity(customLineItem);\n\t\t}\n\n\t\t// Update cart total price\n\t\tresource.totalPrice.centAmount = calculateCartTotalPrice(resource);\n\t}\n\n\tchangeCustomLineItemMoney(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{\n\t\t\tcustomLineItemId,\n\t\t\tcustomLineItemKey,\n\t\t\tmoney,\n\t\t}: CartChangeCustomLineItemMoneyAction,\n\t) {\n\t\tlet customLineItem;\n\n\t\tconst setMoney = (customLineItem: Writable<CustomLineItem> | undefined) => {\n\t\t\tif (!customLineItem) {\n\t\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\t\tcode: \"General\",\n\t\t\t\t\tmessage: `A custom line item with ${customLineItemId ? `ID '${customLineItemId}'` : `key '${customLineItemKey}'`} not found.`,\n\t\t\t\t});\n\t\t\t}\n\t\t\tcustomLineItem.money = createTypedMoney(money);\n\t\t\tcustomLineItem.totalPrice = createCentPrecisionMoney({\n\t\t\t\tcurrencyCode: money.currencyCode,\n\t\t\t\tcentAmount: calculateMoneyTotalCentAmount(\n\t\t\t\t\tmoney,\n\t\t\t\t\tcustomLineItem.quantity,\n\t\t\t\t),\n\t\t\t});\n\t\t\tcustomLineItem.taxedPrice = computeItemTaxedPrice(\n\t\t\t\tcustomLineItem,\n\t\t\t\tresource.taxRoundingMode,\n\t\t\t);\n\t\t};\n\n\t\tif (customLineItemId) {\n\t\t\tcustomLineItem = resource.customLineItems.find(\n\t\t\t\t(x) => x.id === customLineItemId,\n\t\t\t);\n\t\t\tsetMoney(customLineItem);\n\t\t}\n\n\t\tif (customLineItemKey) {\n\t\t\tcustomLineItem = resource.customLineItems.find(\n\t\t\t\t(x) => x.key === customLineItemKey,\n\t\t\t);\n\t\t\tsetMoney(customLineItem);\n\t\t}\n\n\t\t// Update cart total price\n\t\tresource.totalPrice.centAmount = calculateCartTotalPrice(resource);\n\t}\n\n\tsetAnonymousId(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ anonymousId }: CartSetAnonymousIdAction,\n\t) {\n\t\tresource.anonymousId = anonymousId;\n\t\tresource.customerId = undefined;\n\t}\n\n\tsetBillingAddress(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ address }: CartSetBillingAddressAction,\n\t) {\n\t\tresource.billingAddress = createAddress(\n\t\t\taddress,\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage,\n\t\t);\n\t}\n\n\tasync setBillingAddressCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\tcustom: CartSetBillingAddressCustomTypeAction,\n\t) {\n\t\tif (!resource.billingAddress) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"Resource has no billing address\",\n\t\t\t});\n\t\t}\n\n\t\tif (!custom.type) {\n\t\t\tresource.billingAddress.custom = undefined;\n\t\t\treturn;\n\t\t}\n\n\t\tconst resolvedType = await this._storage.getByResourceIdentifier<\"type\">(\n\t\t\tcontext.projectKey,\n\t\t\tcustom.type,\n\t\t);\n\n\t\tif (!resolvedType) {\n\t\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>({\n\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\tmessage: `Type ${custom.type} not found`,\n\t\t\t\ttypeId: \"type\",\n\t\t\t\tid: custom.type?.id,\n\t\t\t\tkey: custom.type?.key,\n\t\t\t});\n\t\t}\n\n\t\tresource.billingAddress.custom = {\n\t\t\ttype: {\n\t\t\t\ttypeId: \"type\",\n\t\t\t\tid: resolvedType.id,\n\t\t\t},\n\t\t\tfields: custom.fields || {},\n\t\t};\n\t}\n\n\tsetCountry(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ country }: CartSetCountryAction,\n\t) {\n\t\tresource.country = country;\n\t}\n\n\tsetCustomerEmail(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ email }: CartSetCustomerEmailAction,\n\t) {\n\t\tresource.customerEmail = email;\n\t}\n\n\tsetCustomerId(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ customerId }: CartSetCustomerIdAction,\n\t) {\n\t\tresource.anonymousId = undefined;\n\t\tresource.customerId = customerId;\n\t}\n\n\tsetCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Cart,\n\t\t{ name, value }: CartSetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tasync setCustomShippingMethod(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{\n\t\t\tshippingMethodName,\n\t\t\tshippingRate,\n\t\t\ttaxCategory,\n\t\t\texternalTaxRate,\n\t\t}: CartSetCustomShippingMethodAction,\n\t) {\n\t\tconst isTaxExternal = resource.taxMode === \"External\";\n\n\t\tif (externalTaxRate && !isTaxExternal) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"An external tax rate can only be set for a Cart with External tax mode.\",\n\t\t\t});\n\t\t}\n\n\t\tconst tax =\n\t\t\t!isTaxExternal && taxCategory\n\t\t\t\t? await this._storage.getByResourceIdentifier<\"tax-category\">(\n\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\ttaxCategory,\n\t\t\t\t\t)\n\t\t\t\t: undefined;\n\n\t\tconst taxRate =\n\t\t\tisTaxExternal && externalTaxRate\n\t\t\t\t? taxRateFromExternalDraft(externalTaxRate)\n\t\t\t\t: undefined;\n\n\t\tconst price = createCentPrecisionMoney(shippingRate.price);\n\t\tconst taxedPrice = taxRate\n\t\t\t? calculateTaxedPriceFromRate(\n\t\t\t\t\tprice.centAmount,\n\t\t\t\t\tprice.currencyCode,\n\t\t\t\t\ttaxRate,\n\t\t\t\t\tresource.taxRoundingMode,\n\t\t\t\t)\n\t\t\t: undefined;\n\n\t\tresource.shippingInfo = {\n\t\t\tshippingMethodName,\n\t\t\tprice,\n\t\t\tshippingRate: {\n\t\t\t\tprice,\n\t\t\t\ttiers: [],\n\t\t\t},\n\t\t\ttaxCategory: tax\n\t\t\t\t? {\n\t\t\t\t\t\ttypeId: \"tax-category\",\n\t\t\t\t\t\tid: tax?.id,\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t\ttaxRate,\n\t\t\ttaxedPrice,\n\t\t\tshippingMethodState: \"MatchesCart\",\n\t\t};\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ type, fields }: CartSetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n\n\tsetDirectDiscounts(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ discounts }: CartSetDirectDiscountsAction,\n\t) {\n\t\t// Doesn't apply any discounts logic, just sets the directDiscounts field\n\t\tresource.directDiscounts = discounts.map(\n\t\t\t(discount) =>\n\t\t\t\t({\n\t\t\t\t\t...discount,\n\t\t\t\t\tid: uuidv4(),\n\t\t\t\t}) as DirectDiscount,\n\t\t);\n\t}\n\n\tsetLineItemCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{\n\t\t\tlineItemId,\n\t\t\tlineItemKey,\n\t\t\tname,\n\t\t\tvalue,\n\t\t\taction,\n\t\t}: CartSetLineItemCustomFieldAction,\n\t) {\n\t\tconst lineItem = resource.lineItems.find(\n\t\t\t(x) =>\n\t\t\t\t(lineItemId && x.id === lineItemId) ||\n\t\t\t\t(lineItemKey && x.key === lineItemKey),\n\t\t);\n\n\t\tif (!lineItem) {\n\t\t\t// Check if line item is found\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: \"General\",\n\t\t\t\tmessage: lineItemKey\n\t\t\t\t\t? `A line item with key '${lineItemKey}' not found.`\n\t\t\t\t\t: `A line item with ID '${lineItemId}' not found.`,\n\t\t\t});\n\t\t}\n\n\t\tif (!lineItem.custom) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"Resource has no custom field\",\n\t\t\t});\n\t\t}\n\n\t\tlineItem.custom.fields[name] = value;\n\t}\n\n\tasync setLineItemCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ lineItemId, lineItemKey, type, fields }: CartSetLineItemCustomTypeAction,\n\t) {\n\t\tconst lineItem = resource.lineItems.find(\n\t\t\t(x) =>\n\t\t\t\t(lineItemId && x.id === lineItemId) ||\n\t\t\t\t(lineItemKey && x.key === lineItemKey),\n\t\t);\n\n\t\tif (!lineItem) {\n\t\t\t// Check if line item is found\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: \"General\",\n\t\t\t\tmessage: lineItemKey\n\t\t\t\t\t? `A line item with key '${lineItemKey}' not found.`\n\t\t\t\t\t: `A line item with ID '${lineItemId}' not found.`,\n\t\t\t});\n\t\t}\n\n\t\tif (!type) {\n\t\t\tlineItem.custom = undefined;\n\t\t} else {\n\t\t\tconst resolvedType = await this._storage.getByResourceIdentifier(\n\t\t\t\tcontext.projectKey,\n\t\t\t\ttype,\n\t\t\t);\n\t\t\tif (!resolvedType) {\n\t\t\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>({\n\t\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\t\tmessage: `Type ${type} not found`,\n\t\t\t\t\ttypeId: \"type\",\n\t\t\t\t\tid: type?.id,\n\t\t\t\t\tkey: type?.key,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tlineItem.custom = {\n\t\t\t\ttype: {\n\t\t\t\t\ttypeId: \"type\",\n\t\t\t\t\tid: resolvedType.id,\n\t\t\t\t},\n\t\t\t\tfields: fields || {},\n\t\t\t};\n\t\t}\n\t}\n\n\tsetLineItemPrice(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ lineItemId, lineItemKey, externalPrice }: CartSetLineItemPriceAction,\n\t) {\n\t\tconst lineItem = resource.lineItems.find(\n\t\t\t(x) =>\n\t\t\t\t(lineItemId && x.id === lineItemId) ||\n\t\t\t\t(lineItemKey && x.key === lineItemKey),\n\t\t);\n\n\t\tif (!lineItem) {\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: \"General\",\n\t\t\t\tmessage: lineItemKey\n\t\t\t\t\t? `A line item with key '${lineItemKey}' not found.`\n\t\t\t\t\t: `A line item with ID '${lineItemId}' not found.`,\n\t\t\t});\n\t\t}\n\n\t\tif (!externalPrice && lineItem.priceMode !== \"ExternalPrice\") {\n\t\t\treturn;\n\t\t}\n\n\t\tif (\n\t\t\texternalPrice &&\n\t\t\texternalPrice.currencyCode !== resource.totalPrice.currencyCode\n\t\t) {\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: \"General\",\n\t\t\t\tmessage: `Currency mismatch. Expected '${resource.totalPrice.currencyCode}' but got '${externalPrice.currencyCode}'.`,\n\t\t\t});\n\t\t}\n\n\t\tif (externalPrice) {\n\t\t\tlineItem.priceMode = \"ExternalPrice\";\n\t\t\tconst priceValue = createTypedMoney(externalPrice);\n\n\t\t\tlineItem.price = lineItem.price ?? { id: uuidv4() };\n\t\t\tlineItem.price.value = priceValue;\n\t\t} else {\n\t\t\tlineItem.priceMode = \"Platform\";\n\n\t\t\tconst price = selectPrice({\n\t\t\t\tprices: lineItem.variant.prices,\n\t\t\t\tcurrency: resource.totalPrice.currencyCode,\n\t\t\t\tcountry: resource.country,\n\t\t\t});\n\n\t\t\tif (!price) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: `No valid price found for ${lineItem.productId} for country ${resource.country} and currency ${resource.totalPrice.currencyCode}`,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tlineItem.price = price;\n\t\t}\n\n\t\tconst lineItemTotal = calculateLineItemTotalPrice(lineItem);\n\t\tlineItem.totalPrice = createCentPrecisionMoney({\n\t\t\tcurrencyCode: lineItem.price!.value.currencyCode,\n\t\t\tcentAmount: lineItemTotal,\n\t\t});\n\t\tlineItem.taxedPrice = computeItemTaxedPrice(\n\t\t\tlineItem,\n\t\t\tresource.taxRoundingMode,\n\t\t);\n\t\tresource.totalPrice.centAmount = calculateCartTotalPrice(resource);\n\t}\n\n\tsetLineItemShippingDetails(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{\n\t\t\taction,\n\t\t\tshippingDetails,\n\t\t\tlineItemId,\n\t\t\tlineItemKey,\n\t\t}: CartSetLineItemShippingDetailsAction,\n\t) {\n\t\tconst lineItem = resource.lineItems.find(\n\t\t\t(x) =>\n\t\t\t\t(lineItemId && x.id === lineItemId) ||\n\t\t\t\t(lineItemKey && x.key === lineItemKey),\n\t\t);\n\n\t\tif (!lineItem) {\n\t\t\t// Check if line item is found\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: \"General\",\n\t\t\t\tmessage: lineItemKey\n\t\t\t\t\t? `A line item with key '${lineItemKey}' not found.`\n\t\t\t\t\t: `A line item with ID '${lineItemId}' not found.`,\n\t\t\t});\n\t\t}\n\n\t\tlineItem.shippingDetails = {\n\t\t\t...shippingDetails,\n\t\t\tvalid: true,\n\t\t} as ItemShippingDetails;\n\t}\n\n\tsetPurchaseOrderNumber(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ purchaseOrderNumber }: CartSetPurchaseOrderNumberAction,\n\t) {\n\t\tresource.purchaseOrderNumber = purchaseOrderNumber;\n\t}\n\n\tsetLocale(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ locale }: CartSetLocaleAction,\n\t) {\n\t\tresource.locale = locale;\n\t}\n\n\tasync setShippingAddress(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ address }: CartSetShippingAddressAction,\n\t) {\n\t\tif (!address) {\n\t\t\tresource.shippingAddress = undefined;\n\t\t\treturn;\n\t\t}\n\n\t\tlet custom: CustomFields | undefined;\n\t\tif ((address as Address & AddressDraft).custom) {\n\t\t\tcustom = await createCustomFields(\n\t\t\t\t(address as Address & AddressDraft).custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t);\n\t\t}\n\n\t\tresource.shippingAddress = {\n\t\t\t...address,\n\t\t\tcustom: custom,\n\t\t};\n\t}\n\n\tasync setShippingAddressCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\tcustom: CartSetShippingAddressCustomTypeAction,\n\t) {\n\t\tif (!resource.shippingAddress) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"Resource has no shipping address\",\n\t\t\t});\n\t\t}\n\n\t\tif (!custom.type) {\n\t\t\tresource.shippingAddress.custom = undefined;\n\t\t\treturn;\n\t\t}\n\n\t\tconst resolvedType = await this._storage.getByResourceIdentifier<\"type\">(\n\t\t\tcontext.projectKey,\n\t\t\tcustom.type,\n\t\t);\n\n\t\tif (!resolvedType) {\n\t\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>({\n\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\tmessage: `Type ${custom.type} not found`,\n\t\t\t\ttypeId: \"type\",\n\t\t\t\tid: custom.type?.id,\n\t\t\t\tkey: custom.type?.key,\n\t\t\t});\n\t\t}\n\n\t\tresource.shippingAddress.custom = {\n\t\t\ttype: {\n\t\t\t\ttypeId: \"type\",\n\t\t\t\tid: resolvedType.id,\n\t\t\t},\n\t\t\tfields: custom.fields || {},\n\t\t};\n\t}\n\n\tasync setShippingMethod(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ shippingMethod, externalTaxRate }: CartSetShippingMethodAction,\n\t) {\n\t\tif (shippingMethod) {\n\t\t\tresource.shippingInfo = await this.repository.createShippingInfo(\n\t\t\t\tcontext,\n\t\t\t\tresource,\n\t\t\t\tshippingMethod,\n\t\t\t\texternalTaxRate ?? undefined,\n\t\t\t);\n\t\t} else {\n\t\t\tresource.shippingInfo = undefined;\n\t\t}\n\t}\n\n\tsetLineItemTaxRate(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ lineItemId, lineItemKey, externalTaxRate }: CartSetLineItemTaxRateAction,\n\t) {\n\t\tif (resource.taxMode !== \"External\") {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"A line item tax rate can only be set for a Cart with External tax mode.\",\n\t\t\t});\n\t\t}\n\n\t\tconst lineItem = resource.lineItems.find(\n\t\t\t(x) =>\n\t\t\t\t(lineItemId && x.id === lineItemId) ||\n\t\t\t\t(lineItemKey && x.key === lineItemKey),\n\t\t);\n\t\tif (!lineItem) {\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: \"General\",\n\t\t\t\tmessage: lineItemKey\n\t\t\t\t\t? `A line item with key '${lineItemKey}' not found.`\n\t\t\t\t\t: `A line item with ID '${lineItemId}' not found.`,\n\t\t\t});\n\t\t}\n\n\t\tconst writable = lineItem as Writable<LineItem>;\n\t\twritable.taxRate = externalTaxRate\n\t\t\t? taxRateFromExternalDraft(externalTaxRate)\n\t\t\t: undefined;\n\t\twritable.taxedPrice = computeItemTaxedPrice(\n\t\t\twritable,\n\t\t\tresource.taxRoundingMode,\n\t\t);\n\t}\n\n\tsetCustomLineItemTaxRate(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{\n\t\t\tcustomLineItemId,\n\t\t\tcustomLineItemKey,\n\t\t\texternalTaxRate,\n\t\t}: CartSetCustomLineItemTaxRateAction,\n\t) {\n\t\tif (resource.taxMode !== \"External\") {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"A custom line item tax rate can only be set for a Cart with External tax mode.\",\n\t\t\t});\n\t\t}\n\n\t\tconst customLineItem = resource.customLineItems.find(\n\t\t\t(x) =>\n\t\t\t\t(customLineItemId && x.id === customLineItemId) ||\n\t\t\t\t(customLineItemKey && x.key === customLineItemKey),\n\t\t);\n\t\tif (!customLineItem) {\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: \"General\",\n\t\t\t\tmessage: customLineItemKey\n\t\t\t\t\t? `A custom line item with key '${customLineItemKey}' not found.`\n\t\t\t\t\t: `A custom line item with ID '${customLineItemId}' not found.`,\n\t\t\t});\n\t\t}\n\n\t\tconst writable = customLineItem as Writable<CustomLineItem>;\n\t\twritable.taxRate = externalTaxRate\n\t\t\t? taxRateFromExternalDraft(externalTaxRate)\n\t\t\t: undefined;\n\t\twritable.taxedPrice = computeItemTaxedPrice(\n\t\t\twritable,\n\t\t\tresource.taxRoundingMode,\n\t\t);\n\t}\n\n\tsetShippingMethodTaxRate(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ externalTaxRate }: CartSetShippingMethodTaxRateAction,\n\t) {\n\t\tif (resource.taxMode !== \"External\") {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"A shipping method tax rate can only be set for a Cart with External tax mode.\",\n\t\t\t});\n\t\t}\n\t\tif (!resource.shippingInfo) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"Cart has no shipping method.\",\n\t\t\t});\n\t\t}\n\n\t\tconst shippingInfo = resource.shippingInfo as Writable<\n\t\t\ttypeof resource.shippingInfo\n\t\t>;\n\t\tconst taxRate: TaxRate | undefined = externalTaxRate\n\t\t\t? taxRateFromExternalDraft(externalTaxRate)\n\t\t\t: undefined;\n\t\tshippingInfo.taxRate = taxRate;\n\t\tshippingInfo.taxedPrice = taxRate\n\t\t\t? calculateTaxedPriceFromRate(\n\t\t\t\t\tshippingInfo.price.centAmount,\n\t\t\t\t\tshippingInfo.price.currencyCode,\n\t\t\t\t\ttaxRate,\n\t\t\t\t\tresource.taxRoundingMode,\n\t\t\t\t)\n\t\t\t: undefined;\n\t}\n\n\tsetLineItemTaxAmount(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{\n\t\t\tlineItemId,\n\t\t\tlineItemKey,\n\t\t\texternalTaxAmount,\n\t\t}: CartSetLineItemTaxAmountAction,\n\t) {\n\t\tif (resource.taxMode !== \"ExternalAmount\") {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"A line item tax amount can only be set for a Cart with ExternalAmount tax mode.\",\n\t\t\t});\n\t\t}\n\n\t\tconst lineItem = resource.lineItems.find(\n\t\t\t(x) =>\n\t\t\t\t(lineItemId && x.id === lineItemId) ||\n\t\t\t\t(lineItemKey && x.key === lineItemKey),\n\t\t);\n\t\tif (!lineItem) {\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: \"General\",\n\t\t\t\tmessage: lineItemKey\n\t\t\t\t\t? `A line item with key '${lineItemKey}' not found.`\n\t\t\t\t\t: `A line item with ID '${lineItemId}' not found.`,\n\t\t\t});\n\t\t}\n\n\t\tconst writable = lineItem as Writable<LineItem>;\n\t\tif (externalTaxAmount) {\n\t\t\twritable.taxRate = taxRateFromExternalDraft(externalTaxAmount.taxRate);\n\t\t\twritable.taxedPrice = buildTaxedPriceFromExternalAmount(\n\t\t\t\texternalTaxAmount,\n\t\t\t\tresource.taxRoundingMode,\n\t\t\t);\n\t\t} else {\n\t\t\twritable.taxRate = undefined;\n\t\t\twritable.taxedPrice = undefined;\n\t\t}\n\t}\n\n\tsetCustomLineItemTaxAmount(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{\n\t\t\tcustomLineItemId,\n\t\t\tcustomLineItemKey,\n\t\t\texternalTaxAmount,\n\t\t}: CartSetCustomLineItemTaxAmountAction,\n\t) {\n\t\tif (resource.taxMode !== \"ExternalAmount\") {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"A custom line item tax amount can only be set for a Cart with ExternalAmount tax mode.\",\n\t\t\t});\n\t\t}\n\n\t\tconst customLineItem = resource.customLineItems.find(\n\t\t\t(x) =>\n\t\t\t\t(customLineItemId && x.id === customLineItemId) ||\n\t\t\t\t(customLineItemKey && x.key === customLineItemKey),\n\t\t);\n\t\tif (!customLineItem) {\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: \"General\",\n\t\t\t\tmessage: customLineItemKey\n\t\t\t\t\t? `A custom line item with key '${customLineItemKey}' not found.`\n\t\t\t\t\t: `A custom line item with ID '${customLineItemId}' not found.`,\n\t\t\t});\n\t\t}\n\n\t\tconst writable = customLineItem as Writable<CustomLineItem>;\n\t\tif (externalTaxAmount) {\n\t\t\twritable.taxRate = taxRateFromExternalDraft(externalTaxAmount.taxRate);\n\t\t\twritable.taxedPrice = buildTaxedPriceFromExternalAmount(\n\t\t\t\texternalTaxAmount,\n\t\t\t\tresource.taxRoundingMode,\n\t\t\t);\n\t\t} else {\n\t\t\twritable.taxRate = undefined;\n\t\t\twritable.taxedPrice = undefined;\n\t\t}\n\t}\n\n\tsetShippingMethodTaxAmount(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ externalTaxAmount }: CartSetShippingMethodTaxAmountAction,\n\t) {\n\t\tif (resource.taxMode !== \"ExternalAmount\") {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"A shipping method tax amount can only be set for a Cart with ExternalAmount tax mode.\",\n\t\t\t});\n\t\t}\n\t\tif (!resource.shippingInfo) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"Cart has no shipping method.\",\n\t\t\t});\n\t\t}\n\n\t\tconst shippingInfo = resource.shippingInfo as Writable<\n\t\t\ttypeof resource.shippingInfo\n\t\t>;\n\t\tif (externalTaxAmount) {\n\t\t\tshippingInfo.taxRate = taxRateFromExternalDraft(\n\t\t\t\texternalTaxAmount.taxRate,\n\t\t\t);\n\t\t\tshippingInfo.taxedPrice = buildTaxedPriceFromExternalAmount(\n\t\t\t\texternalTaxAmount,\n\t\t\t\tresource.taxRoundingMode,\n\t\t\t);\n\t\t} else {\n\t\t\tshippingInfo.taxRate = undefined;\n\t\t\tshippingInfo.taxedPrice = undefined;\n\t\t}\n\t}\n\n\tsetCartTotalTax(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ externalTotalGross, externalTaxPortions }: CartSetCartTotalTaxAction,\n\t) {\n\t\tif (resource.taxMode !== \"ExternalAmount\") {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"A cart total tax can only be set for a Cart with ExternalAmount tax mode.\",\n\t\t\t});\n\t\t}\n\n\t\tconst totalGross = createCentPrecisionMoney(externalTotalGross);\n\t\tconst currencyCode = totalGross.currencyCode;\n\t\tconst portions =\n\t\t\texternalTaxPortions?.map((portion) => ({\n\t\t\t\tname: portion.name,\n\t\t\t\trate: portion.rate,\n\t\t\t\tamount: createCentPrecisionMoney(portion.amount),\n\t\t\t})) ?? [];\n\t\tconst totalTaxCentAmount = portions.reduce(\n\t\t\t(acc, portion) => acc + portion.amount.centAmount,\n\t\t\t0,\n\t\t);\n\t\tconst totalNet = createCentPrecisionMoney({\n\t\t\tcurrencyCode,\n\t\t\tcentAmount: totalGross.centAmount - totalTaxCentAmount,\n\t\t});\n\n\t\tresource.taxedPrice = {\n\t\t\ttotalNet,\n\t\t\ttotalGross,\n\t\t\ttotalTax:\n\t\t\t\ttotalTaxCentAmount > 0\n\t\t\t\t\t? createCentPrecisionMoney({\n\t\t\t\t\t\t\tcurrencyCode,\n\t\t\t\t\t\t\tcentAmount: totalTaxCentAmount,\n\t\t\t\t\t\t})\n\t\t\t\t\t: undefined,\n\t\t\ttaxPortions: portions,\n\t\t};\n\t}\n\n\tsetShippingAddressCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ name, value }: CartSetShippingAddressCustomFieldAction,\n\t) {\n\t\tif (!resource.shippingAddress) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"Resource has no shipping address\",\n\t\t\t});\n\t\t}\n\t\tif (!resource.shippingAddress.custom) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"Resource has no custom field\",\n\t\t\t});\n\t\t}\n\t\tresource.shippingAddress.custom.fields[name] = value;\n\t}\n\n\tasync removeShippingMethod(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\t{ shippingKey }: CartRemoveShippingMethodAction,\n\t) {\n\t\tif (!resource.shippingInfo) {\n\t\t\treturn;\n\t\t}\n\t\tconst shippingMethod =\n\t\t\tawait this._storage.getByResourceIdentifier<\"shipping-method\">(\n\t\t\t\tcontext.projectKey,\n\t\t\t\t{\n\t\t\t\t\ttypeId: \"shipping-method\",\n\t\t\t\t\tkey: shippingKey,\n\t\t\t\t} as ShippingMethodResourceIdentifier,\n\t\t\t);\n\n\t\tif (resource.shippingInfo?.shippingMethod?.id !== shippingMethod.id) {\n\t\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>({\n\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\tmessage: \"Shipping method with key not found\",\n\t\t\t\ttypeId: \"shipping-method\",\n\t\t\t\tkey: shippingKey,\n\t\t\t});\n\t\t}\n\n\t\tresource.shippingInfo = undefined;\n\t}\n}\n","import type {\n\tBusinessUnit,\n\tCart,\n\tCartDraft,\n\tDiscountCodeInfo,\n\tExternalTaxRateDraft,\n\tGeneralError,\n\tInvalidOperationError,\n\tLineItem,\n\tLineItemDraft,\n\tProduct,\n\tShippingMethodDoesNotMatchCartError,\n} from \"@commercetools/platform-sdk\";\n\nimport { v4 as uuidv4 } from \"uuid\";\nimport type { Config } from \"#src/config.ts\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { getBaseResourceProperties } from \"#src/helpers.ts\";\nimport {\n\tcalculateTaxedPriceFromRate,\n\tcalculateTaxTotals,\n\ttaxRateFromExternalDraft,\n} from \"#src/lib/tax.ts\";\nimport { CartDraftSchema } from \"#src/schemas/generated/cart.ts\";\nimport {\n\tcreateShippingInfoFromMethod,\n\tgetShippingMethodsMatchingCart,\n} from \"#src/shipping.ts\";\nimport type { Writable } from \"#src/types.ts\";\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from \"../abstract.ts\";\nimport {\n\tcalculateMoneyTotalCentAmount,\n\tcreateAddress,\n\tcreateCentPrecisionMoney,\n\tcreateCustomFields,\n} from \"../helpers.ts\";\nimport { CartUpdateHandler } from \"./actions.ts\";\nimport {\n\tcalculateCartTotalPrice,\n\tcreateCustomLineItemFromDraft,\n\tcreateDiscountCodeInfoFromCode,\n\tselectPrice,\n} from \"./helpers.ts\";\n\nexport class CartRepository extends AbstractResourceRepository<\"cart\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"cart\", config);\n\t\tthis.actions = new CartUpdateHandler(this._storage, this);\n\t\tthis.draftSchema = CartDraftSchema;\n\t}\n\n\tasync create(context: RepositoryContext, draft: CartDraft): Promise<Cart> {\n\t\tif (draft.anonymousId && draft.customerId) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"Can set only one of customer OR anonymousId\",\n\t\t\t});\n\t\t}\n\n\t\t// Validate that the customer exists\n\t\tif (draft.customerId) {\n\t\t\tawait this._storage.getByResourceIdentifier(context.projectKey, {\n\t\t\t\ttypeId: \"customer\",\n\t\t\t\tid: draft.customerId,\n\t\t\t});\n\t\t}\n\n\t\tlet storedBusinessUnit: BusinessUnit | undefined;\n\t\tif (draft.businessUnit?.id || draft.businessUnit?.key) {\n\t\t\tstoredBusinessUnit =\n\t\t\t\tawait this._storage.getByResourceIdentifier<\"business-unit\">(\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t{\n\t\t\t\t\t\ttypeId: \"business-unit\",\n\t\t\t\t\t\tid: draft.businessUnit.id,\n\t\t\t\t\t\tkey: draft.businessUnit.key,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t}\n\n\t\tconst taxMode = draft.taxMode ?? \"Platform\";\n\t\tconst taxRoundingMode = draft.taxRoundingMode ?? \"HalfEven\";\n\n\t\tconst lineItems = draft.lineItems\n\t\t\t? await Promise.all(\n\t\t\t\t\tdraft.lineItems.map((draftLineItem) =>\n\t\t\t\t\t\tthis.draftLineItemtoLineItem(\n\t\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\t\tdraftLineItem,\n\t\t\t\t\t\t\tdraft.currency,\n\t\t\t\t\t\t\tdraft.country,\n\t\t\t\t\t\t\ttaxMode,\n\t\t\t\t\t\t\ttaxRoundingMode,\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t: [];\n\n\t\tconst customLineItems = draft.customLineItems\n\t\t\t? await Promise.all(\n\t\t\t\t\tdraft.customLineItems.map((draftCustomLineItem) =>\n\t\t\t\t\t\tcreateCustomLineItemFromDraft(\n\t\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\t\tdraftCustomLineItem,\n\t\t\t\t\t\t\tthis._storage,\n\t\t\t\t\t\t\tdraft.shippingAddress?.country ?? draft.country,\n\t\t\t\t\t\t\ttaxMode,\n\t\t\t\t\t\t\ttaxRoundingMode,\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t: [];\n\n\t\t// Validate that discount codes exist and deduplicate\n\t\tconst discountCodeInfo: DiscountCodeInfo[] = [];\n\t\tif (draft.discountCodes?.length) {\n\t\t\tconst seen = new Set<string>();\n\t\t\tfor (const code of draft.discountCodes) {\n\t\t\t\tconst info = await createDiscountCodeInfoFromCode(\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tthis._storage,\n\t\t\t\t\tcode,\n\t\t\t\t);\n\t\t\t\tif (!seen.has(info.discountCode.id)) {\n\t\t\t\t\tseen.add(info.discountCode.id);\n\t\t\t\t\tdiscountCodeInfo.push(info);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst resource: Writable<Cart> = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tanonymousId: draft.anonymousId,\n\t\t\tbusinessUnit:\n\t\t\t\tstoredBusinessUnit && draft.businessUnit\n\t\t\t\t\t? {\n\t\t\t\t\t\t\ttypeId: draft.businessUnit.typeId,\n\t\t\t\t\t\t\tkey: storedBusinessUnit.key,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\tbillingAddress: draft.billingAddress\n\t\t\t\t? createAddress(draft.billingAddress, context.projectKey, this._storage)\n\t\t\t\t: undefined,\n\t\t\tcartState: \"Active\",\n\t\t\tcountry: draft.country,\n\t\t\tcustomerId: draft.customerId,\n\t\t\tcustomerEmail: draft.customerEmail,\n\t\t\tcustomLineItems,\n\t\t\tdirectDiscounts: [],\n\t\t\tdiscountCodes: discountCodeInfo,\n\t\t\tinventoryMode: \"None\",\n\t\t\titemShippingAddresses: [],\n\t\t\tlineItems,\n\t\t\tlocale: draft.locale,\n\t\t\tpriceRoundingMode: draft.priceRoundingMode ?? \"HalfEven\",\n\t\t\ttaxCalculationMode: draft.taxCalculationMode ?? \"LineItemLevel\",\n\t\t\ttaxMode,\n\t\t\ttaxRoundingMode,\n\t\t\ttotalPrice: {\n\t\t\t\ttype: \"centPrecision\",\n\t\t\t\tcentAmount: 0,\n\t\t\t\tcurrencyCode: draft.currency,\n\t\t\t\tfractionDigits: 0,\n\t\t\t},\n\t\t\tshippingMode: \"Single\",\n\t\t\tshippingAddress: draft.shippingAddress\n\t\t\t\t? createAddress(\n\t\t\t\t\t\tdraft.shippingAddress,\n\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\tthis._storage,\n\t\t\t\t\t)\n\t\t\t\t: undefined,\n\t\t\tshipping: [],\n\t\t\tshippingInfo: undefined,\n\t\t\torigin: draft.origin ?? \"Customer\",\n\t\t\tpurchaseOrderNumber: draft.purchaseOrderNumber,\n\t\t\trefusedGifts: [],\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t};\n\t\tresource.totalPrice.centAmount = calculateCartTotalPrice(resource);\n\t\tresource.store = context.storeKey\n\t\t\t? { typeId: \"store\", key: context.storeKey }\n\t\t\t: draft.store?.key\n\t\t\t\t? { typeId: \"store\", key: draft.store.key }\n\t\t\t\t: undefined;\n\n\t\t// Set shipping info after resource is created\n\t\tif (draft.shippingMethod) {\n\t\t\tresource.shippingInfo = await this.createShippingInfo(\n\t\t\t\tcontext,\n\t\t\t\tresource,\n\t\t\t\tdraft.shippingMethod,\n\t\t\t\tdraft.externalTaxRateForShippingMethod ?? undefined,\n\t\t\t);\n\t\t}\n\n\t\tconst { taxedPrice, taxedShippingPrice } = calculateTaxTotals(resource);\n\t\tresource.taxedPrice = taxedPrice;\n\t\tresource.taxedShippingPrice = taxedShippingPrice;\n\n\t\treturn await this.saveNew(context, resource);\n\t}\n\n\tasync getActiveCart(projectKey: string): Promise<Cart | undefined> {\n\t\t// Get first active cart\n\t\tconst results = await this._storage.query(projectKey, this.getTypeId(), {\n\t\t\twhere: [`cartState=\"Active\"`],\n\t\t});\n\t\tif (results.count > 0) {\n\t\t\treturn results.results[0] as Cart;\n\t\t}\n\n\t\treturn;\n\t}\n\n\tdraftLineItemtoLineItem = async (\n\t\tprojectKey: string,\n\t\tdraftLineItem: LineItemDraft,\n\t\tcurrency: string,\n\t\tcountry: string | undefined,\n\t\ttaxMode: Cart[\"taxMode\"] = \"Platform\",\n\t\troundingMode: Cart[\"taxRoundingMode\"] = \"HalfEven\",\n\t): Promise<LineItem> => {\n\t\tconst { productId, quantity, variantId, sku } = draftLineItem;\n\n\t\tlet product: Product | null = null;\n\n\t\tif (productId && variantId) {\n\t\t\t// Fetch product and variant by ID\n\t\t\tproduct = await this._storage.get(projectKey, \"product\", productId, {});\n\t\t} else if (sku) {\n\t\t\t// Fetch product and variant by SKU\n\t\t\tconst items = await this._storage.query(projectKey, \"product\", {\n\t\t\t\twhere: [\n\t\t\t\t\t`masterData(current(masterVariant(sku=\"${sku}\"))) or masterData(current(variants(sku=\"${sku}\")))`,\n\t\t\t\t],\n\t\t\t});\n\n\t\t\tif (items.count === 1) {\n\t\t\t\tproduct = items.results[0];\n\t\t\t}\n\t\t}\n\n\t\tif (!product) {\n\t\t\t// Check if product is found\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: \"General\",\n\t\t\t\tmessage: sku\n\t\t\t\t\t? `A product containing a variant with SKU '${sku}' not found.`\n\t\t\t\t\t: `A product with ID '${productId}' not found.`,\n\t\t\t});\n\t\t}\n\n\t\t// Find matching variant\n\t\tconst variant = [\n\t\t\tproduct.masterData.current.masterVariant,\n\t\t\t...product.masterData.current.variants,\n\t\t].find((x) => {\n\t\t\tif (sku) return x.sku === sku;\n\t\t\tif (variantId) return x.id === variantId;\n\t\t\treturn false;\n\t\t});\n\n\t\tif (!variant) {\n\t\t\t// Check if variant is found\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: sku\n\t\t\t\t\t? `A variant with SKU '${sku}' for product '${product.id}' not found.`\n\t\t\t\t\t: `A variant with ID '${variantId}' for product '${product.id}' not found.`,\n\t\t\t});\n\t\t}\n\n\t\tconst quant = quantity ?? 1;\n\n\t\tconst price = selectPrice({ prices: variant.prices, currency, country });\n\t\tif (!price) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: `No valid price found for ${productId} for country ${country} and currency ${currency}`,\n\t\t\t});\n\t\t}\n\n\t\tconst totalPrice = createCentPrecisionMoney({\n\t\t\tcurrencyCode: price.value.currencyCode,\n\t\t\tcentAmount: calculateMoneyTotalCentAmount(price.value, quant),\n\t\t});\n\n\t\tconst taxRate =\n\t\t\ttaxMode === \"External\" && draftLineItem.externalTaxRate\n\t\t\t\t? taxRateFromExternalDraft(draftLineItem.externalTaxRate)\n\t\t\t\t: undefined;\n\t\tconst taxedPrice = taxRate\n\t\t\t? calculateTaxedPriceFromRate(\n\t\t\t\t\ttotalPrice.centAmount,\n\t\t\t\t\ttotalPrice.currencyCode,\n\t\t\t\t\ttaxRate,\n\t\t\t\t\troundingMode,\n\t\t\t\t)\n\t\t\t: undefined;\n\n\t\treturn {\n\t\t\tid: uuidv4(),\n\t\t\tproductId: product.id,\n\t\t\tproductKey: product.key,\n\t\t\tproductSlug: product.masterData.current.slug,\n\t\t\tproductType: product.productType,\n\t\t\tname: product.masterData.current.name,\n\t\t\tvariant,\n\t\t\tprice: price,\n\t\t\ttotalPrice,\n\t\t\ttaxRate,\n\t\t\ttaxedPrice,\n\t\t\ttaxedPricePortions: [],\n\t\t\tperMethodTaxRate: [],\n\t\t\tquantity: quant,\n\t\t\tdiscountedPricePerQuantity: [],\n\t\t\tlineItemMode: \"Standard\",\n\t\t\tpriceMode: \"Platform\",\n\t\t\tstate: [],\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tdraftLineItem.custom,\n\t\t\t\tprojectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t};\n\t};\n\n\tasync createShippingInfo(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Cart>,\n\t\tshippingMethodRef: NonNullable<CartDraft[\"shippingMethod\"]>,\n\t\texternalTaxRate?: ExternalTaxRateDraft,\n\t): Promise<NonNullable<Cart[\"shippingInfo\"]>> {\n\t\tif (resource.taxMode === \"External\" && !externalTaxRate) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"An external tax rate is required for a cart with External tax mode.\",\n\t\t\t});\n\t\t}\n\n\t\t// Bit of a hack: calling this checks that the resource identifier is\n\t\t// valid (i.e. id xor key) and that the shipping method exists.\n\t\tawait this._storage.getByResourceIdentifier<\"shipping-method\">(\n\t\t\tcontext.projectKey,\n\t\t\tshippingMethodRef,\n\t\t);\n\n\t\t// getShippingMethodsMatchingCart does the work of determining whether the\n\t\t// shipping method is allowed for the cart, and which shipping rate to use\n\t\tconst shippingMethods = await getShippingMethodsMatchingCart(\n\t\t\tcontext,\n\t\t\tthis._storage,\n\t\t\tresource,\n\t\t\t{\n\t\t\t\texpand: [\"zoneRates[*].zone\"],\n\t\t\t},\n\t\t);\n\n\t\tconst method = shippingMethods.results.find(\n\t\t\t(candidate: { id: string; key?: string }) =>\n\t\t\t\tshippingMethodRef.id\n\t\t\t\t\t? candidate.id === shippingMethodRef.id\n\t\t\t\t\t: candidate.key === shippingMethodRef.key,\n\t\t);\n\n\t\t// Not finding the method in the results means it's not allowed, since\n\t\t// getShippingMethodsMatchingCart only returns allowed methods and we\n\t\t// already checked that the method exists.\n\t\tif (!method) {\n\t\t\tthrow new CommercetoolsError<ShippingMethodDoesNotMatchCartError>({\n\t\t\t\tcode: \"ShippingMethodDoesNotMatchCart\",\n\t\t\t\tmessage: `The shipping method with ${shippingMethodRef.id ? `ID '${shippingMethodRef.id}'` : `key '${shippingMethodRef.key}'`} is not allowed for the cart with ID '${resource.id}'.`,\n\t\t\t});\n\t\t}\n\n\t\t// Use the shared shipping info creation logic\n\t\treturn await createShippingInfoFromMethod(\n\t\t\tcontext,\n\t\t\tthis._storage,\n\t\t\tresource,\n\t\t\tmethod,\n\t\t\tresource.taxMode === \"External\" ? externalTaxRate : undefined,\n\t\t);\n\t}\n}\n","import type {\n\tOrderPagedSearchResponse,\n\tOrderSearchRequest,\n} from \"@commercetools/platform-sdk\";\nimport type { Hit } from \"@commercetools/platform-sdk/dist/declarations/src/generated/models/order\";\nimport type { Config } from \"#src/config.ts\";\nimport type { AbstractStorage } from \"#src/storage/index.ts\";\n\nexport class OrderSearch {\n\tprotected _storage: AbstractStorage;\n\n\tconstructor(config: Config) {\n\t\tthis._storage = config.storage;\n\t}\n\n\tasync search(\n\t\tprojectKey: string,\n\t\tparams: OrderSearchRequest,\n\t): Promise<OrderPagedSearchResponse> {\n\t\tconst orderResources = await this._storage.all(projectKey, \"order\");\n\n\t\t// TODO: implement filtering based on params.query\n\t\tconst offset = params.offset || 0;\n\t\tconst limit = params.limit || 20;\n\t\tconst orderResult = orderResources.slice(offset, offset + limit);\n\n\t\t// Transform orders into Hit objects for the OrderSearchResult\n\t\tconst results: Hit[] = orderResult.map((order) => ({\n\t\t\tid: order.id,\n\t\t\tversion: order.version,\n\t\t}));\n\n\t\treturn {\n\t\t\ttotal: orderResources.length,\n\t\t\toffset: offset,\n\t\t\tlimit: limit,\n\t\t\thits: results,\n\t\t};\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tCartResourceIdentifierSchema,\n\tCustomFieldsDraftSchema,\n\tOrderStateSchema,\n\tPaymentStateSchema,\n\tShipmentStateSchema,\n\tStateResourceIdentifierSchema,\n} from \"./common.ts\";\n\nexport const OrderFromCartDraftSchema = z.object({\n\tid: z.string().nullish(),\n\tcart: CartResourceIdentifierSchema.nullish(),\n\tversion: z.number().int(),\n\torderNumber: z.string().nullish(),\n\tpurchaseOrderNumber: z.string().nullish(),\n\tpaymentState: PaymentStateSchema.nullish(),\n\tshipmentState: ShipmentStateSchema.nullish(),\n\torderState: OrderStateSchema.nullish(),\n\tstate: StateResourceIdentifierSchema.nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n});\n","import { isDeepStrictEqual } from \"node:util\";\nimport type {\n\tAsset,\n\tAssetDraft,\n\tChannelReference,\n\tCustomerGroupReference,\n\tPrice,\n\tPriceDraft,\n\tProduct,\n\tProductData,\n\tProductVariant,\n\tProductVariantDraft,\n\tRecurrencePolicyReference,\n} from \"@commercetools/platform-sdk\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport type { AbstractStorage } from \"#src/storage/index.ts\";\nimport type { Writable } from \"#src/types.ts\";\nimport type { RepositoryContext } from \"../abstract.ts\";\nimport {\n\tcreateCustomFields,\n\tcreateTypedMoney,\n\tgetReferenceFromResourceIdentifier,\n} from \"../helpers.ts\";\n\ninterface VariantResult {\n\tvariant: Writable<ProductVariant> | undefined;\n\tisMasterVariant: boolean;\n\tvariantIndex: number;\n}\n\nexport const getVariant = (\n\tproductData: ProductData,\n\tvariantId?: number,\n\tsku?: string,\n): VariantResult => {\n\tconst variants = [productData.masterVariant, ...productData.variants];\n\tconst foundVariant = variants.find((variant: ProductVariant) => {\n\t\tif (variantId) {\n\t\t\treturn variant.id === variantId;\n\t\t}\n\t\tif (sku) {\n\t\t\treturn variant.sku === sku;\n\t\t}\n\t\treturn false;\n\t});\n\n\tconst isMasterVariant = foundVariant === productData.masterVariant;\n\treturn {\n\t\tvariant: foundVariant,\n\t\tisMasterVariant,\n\t\tvariantIndex:\n\t\t\t!isMasterVariant && foundVariant\n\t\t\t\t? productData.variants.indexOf(foundVariant)\n\t\t\t\t: -1,\n\t};\n};\n\n// Check if the product still has staged data that is different from the\n// current data.\nexport const checkForStagedChanges = (product: Writable<Product>) => {\n\tif (!product.masterData.staged) {\n\t\tproduct.masterData.staged = product.masterData.current;\n\t}\n\n\tif (\n\t\tisDeepStrictEqual(product.masterData.current, product.masterData.staged)\n\t) {\n\t\tproduct.masterData.hasStagedChanges = false;\n\t} else {\n\t\tproduct.masterData.hasStagedChanges = true;\n\t}\n};\n\nexport const variantFromDraft = async (\n\tcontext: RepositoryContext,\n\tstorage: AbstractStorage,\n\tvariantId: number,\n\tvariant: ProductVariantDraft,\n): Promise<ProductVariant> => {\n\tconst prices = variant?.prices\n\t\t? await Promise.all(\n\t\t\t\tvariant.prices.map((p) => priceFromDraft(context, storage, p)),\n\t\t\t)\n\t\t: undefined;\n\tconst assets = variant.assets\n\t\t? await Promise.all(\n\t\t\t\tvariant.assets.map((a) => assetFromDraft(context, storage, a)),\n\t\t\t)\n\t\t: [];\n\n\treturn {\n\t\tid: variantId,\n\t\tsku: variant?.sku,\n\t\tkey: variant?.key,\n\t\tattributes: variant?.attributes ?? [],\n\t\tprices,\n\t\tassets,\n\t\timages: variant.images ?? [],\n\t};\n};\n\nexport const assetFromDraft = async (\n\tcontext: RepositoryContext,\n\tstorage: AbstractStorage,\n\tdraft: AssetDraft,\n): Promise<Asset> => {\n\tconst asset: Asset = {\n\t\t...draft,\n\t\tid: uuidv4(),\n\t\tcustom: await createCustomFields(draft.custom, context.projectKey, storage),\n\t};\n\treturn asset;\n};\n\nexport const priceFromDraft = async (\n\tcontext: RepositoryContext,\n\tstorage: AbstractStorage,\n\tdraft: PriceDraft,\n): Promise<Price> => ({\n\tid: uuidv4(),\n\tkey: draft.key,\n\tcountry: draft.country,\n\tvalue: createTypedMoney(draft.value),\n\tchannel: draft.channel\n\t\t? await getReferenceFromResourceIdentifier<ChannelReference>(\n\t\t\t\tdraft.channel,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tstorage,\n\t\t\t)\n\t\t: undefined,\n\tcustomerGroup: draft.customerGroup\n\t\t? await getReferenceFromResourceIdentifier<CustomerGroupReference>(\n\t\t\t\tdraft.customerGroup,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tstorage,\n\t\t\t)\n\t\t: undefined,\n\trecurrencePolicy: draft.recurrencePolicy\n\t\t? await getReferenceFromResourceIdentifier<RecurrencePolicyReference>(\n\t\t\t\tdraft.recurrencePolicy,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tstorage,\n\t\t\t)\n\t\t: undefined,\n\tvalidFrom: draft.validFrom,\n\tvalidUntil: draft.validUntil,\n\tdiscounted: draft.discounted\n\t\t? {\n\t\t\t\tvalue: createTypedMoney(draft.discounted.value),\n\t\t\t\tdiscount: draft.discounted.discount,\n\t\t\t}\n\t\t: undefined,\n\ttiers: draft.tiers?.map((tier) => ({\n\t\tminimumQuantity: tier.minimumQuantity,\n\t\tvalue: createTypedMoney(tier.value),\n\t})),\n\tcustom: await createCustomFields(draft.custom, context.projectKey, storage),\n});\n","import type {\n\tCustomLineItemReturnItem,\n\tDelivery,\n\tGeneralError,\n\tInvalidOperationError,\n\tLineItemReturnItem,\n\tOrder,\n\tOrderAddDeliveryAction,\n\tOrderAddParcelToDeliveryAction,\n\tOrderAddPaymentAction,\n\tOrderAddReturnInfoAction,\n\tOrderChangeOrderStateAction,\n\tOrderChangePaymentStateAction,\n\tOrderChangeShipmentStateAction,\n\tOrderRemovePaymentAction,\n\tOrderSetBillingAddressAction,\n\tOrderSetCustomerEmailAction,\n\tOrderSetCustomerIdAction,\n\tOrderSetCustomFieldAction,\n\tOrderSetCustomTypeAction,\n\tOrderSetDeliveryCustomFieldAction,\n\tOrderSetLineItemCustomFieldAction,\n\tOrderSetLineItemCustomTypeAction,\n\tOrderSetLocaleAction,\n\tOrderSetOrderNumberAction,\n\tOrderSetParcelCustomFieldAction,\n\tOrderSetPurchaseOrderNumberAction,\n\tOrderSetShippingAddressAction,\n\tOrderSetStoreAction,\n\tOrderTransitionStateAction,\n\tOrderUpdateAction,\n\tOrderUpdateSyncInfoAction,\n\tParcel,\n\tReferencedResourceNotFoundError,\n\tRequiredFieldError,\n\tResourceNotFoundError,\n\tReturnInfo,\n\tState,\n\tStore,\n\tSyncInfo,\n} from \"@commercetools/platform-sdk\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { getBaseResourceProperties } from \"#src/helpers.ts\";\nimport type { Writable } from \"#src/types.ts\";\nimport type { RepositoryContext, UpdateHandlerInterface } from \"../abstract.ts\";\nimport { AbstractUpdateHandler } from \"../abstract.ts\";\nimport { createAddress, createCustomFields } from \"../helpers.ts\";\n\nexport class OrderUpdateHandler\n\textends AbstractUpdateHandler\n\timplements Partial<UpdateHandlerInterface<Order, OrderUpdateAction>>\n{\n\tasync addPayment(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\t{ payment }: OrderAddPaymentAction,\n\t) {\n\t\tconst resolvedPayment = await this._storage.getByResourceIdentifier(\n\t\t\tcontext.projectKey,\n\t\t\tpayment,\n\t\t);\n\t\tif (!resolvedPayment) {\n\t\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>({\n\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\tmessage: `Payment ${payment.id} not found`,\n\t\t\t\ttypeId: \"payment\",\n\t\t\t});\n\t\t}\n\n\t\tif (!resource.paymentInfo) {\n\t\t\tresource.paymentInfo = {\n\t\t\t\tpayments: [],\n\t\t\t};\n\t\t}\n\n\t\tresource.paymentInfo.payments.push({\n\t\t\ttypeId: \"payment\",\n\t\t\tid: payment.id!,\n\t\t});\n\t}\n\n\tasync removePayment(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\t{ payment }: OrderRemovePaymentAction,\n\t) {\n\t\tconst resolvedPayment = await this._storage.getByResourceIdentifier(\n\t\t\tcontext.projectKey,\n\t\t\tpayment,\n\t\t);\n\t\tif (!resolvedPayment) {\n\t\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>({\n\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\tmessage: `Payment ${payment.id} not found`,\n\t\t\t\ttypeId: \"payment\",\n\t\t\t});\n\t\t}\n\n\t\tif (!resource.paymentInfo) {\n\t\t\treturn;\n\t\t}\n\n\t\tresource.paymentInfo.payments = resource.paymentInfo.payments.filter(\n\t\t\t(reference) => reference.id !== resolvedPayment.id,\n\t\t);\n\n\t\tif (resource.paymentInfo.payments.length === 0) {\n\t\t\tresource.paymentInfo = undefined;\n\t\t}\n\t}\n\n\tasync addReturnInfo(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\tinfo: OrderAddReturnInfoAction,\n\t) {\n\t\tif (!resource.returnInfo) {\n\t\t\tresource.returnInfo = [];\n\t\t}\n\n\t\tconst items = await Promise.all(\n\t\t\tinfo.items.map(async (item) => {\n\t\t\t\tconst common = {\n\t\t\t\t\t...getBaseResourceProperties(),\n\t\t\t\t\tquantity: item.quantity,\n\t\t\t\t\tpaymentState: \"Initial\",\n\t\t\t\t\tshipmentState: item.shipmentState ?? \"Advised\",\n\t\t\t\t\tcomment: item.comment,\n\t\t\t\t\tcustom: await createCustomFields(\n\t\t\t\t\t\titem.custom,\n\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\tthis._storage,\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t\tif (item.customLineItemId) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...common,\n\t\t\t\t\t\ttype: \"CustomLineItemReturnItem\",\n\t\t\t\t\t\tcustomLineItemId: item.customLineItemId,\n\t\t\t\t\t} as CustomLineItemReturnItem;\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\t...common,\n\t\t\t\t\ttype: \"LineItemReturnItem\",\n\t\t\t\t\tlineItemId: item.customLineItemId || item.lineItemId,\n\t\t\t\t} as LineItemReturnItem;\n\t\t\t}),\n\t\t);\n\n\t\tconst resolved: ReturnInfo = {\n\t\t\titems,\n\t\t\treturnTrackingId: info.returnTrackingId,\n\t\t\treturnDate: info.returnDate,\n\t\t};\n\n\t\tresource.returnInfo.push(resolved);\n\t}\n\n\tchangeOrderState(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\t{ orderState }: OrderChangeOrderStateAction,\n\t) {\n\t\tresource.orderState = orderState;\n\t}\n\n\tchangePaymentState(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\t{ paymentState }: OrderChangePaymentStateAction,\n\t) {\n\t\tresource.paymentState = paymentState;\n\t}\n\n\tchangeShipmentState(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\t{ shipmentState }: OrderChangeShipmentStateAction,\n\t) {\n\t\tresource.shipmentState = shipmentState;\n\t}\n\n\tsetBillingAddress(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\t{ address }: OrderSetBillingAddressAction,\n\t) {\n\t\tresource.billingAddress = createAddress(\n\t\t\taddress,\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage,\n\t\t);\n\t}\n\n\tsetCustomerEmail(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\t{ email }: OrderSetCustomerEmailAction,\n\t) {\n\t\tresource.customerEmail = email;\n\t}\n\n\tsetCustomerId(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\t{ customerId }: OrderSetCustomerIdAction,\n\t) {\n\t\tresource.customerId = customerId;\n\t}\n\n\tsetCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Order,\n\t\t{ name, value }: OrderSetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\t{ type, fields }: OrderSetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n\n\tasync addDelivery(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\t{ action, items, ...deliveryDraft }: OrderAddDeliveryAction,\n\t) {\n\t\tif (!resource.shippingInfo) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"Resource has no shipping info\",\n\t\t\t});\n\t\t}\n\n\t\tif (!items) {\n\t\t\tthrow new CommercetoolsError<RequiredFieldError>({\n\t\t\t\tcode: \"RequiredField\",\n\t\t\t\tmessage: \"Delivery items are required\",\n\t\t\t\tfield: \"items\",\n\t\t\t});\n\t\t}\n\n\t\tif (!resource.shippingInfo.deliveries) {\n\t\t\tresource.shippingInfo.deliveries = [];\n\t\t}\n\n\t\tconst parcels: Parcel[] = await Promise.all(\n\t\t\tdeliveryDraft.parcels?.map(async (p) => ({\n\t\t\t\t...getBaseResourceProperties(),\n\t\t\t\t...p,\n\t\t\t\tcustom: await createCustomFields(\n\t\t\t\t\tp.custom,\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tthis._storage,\n\t\t\t\t),\n\t\t\t})) ?? [],\n\t\t);\n\n\t\tconst delivery: Delivery = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\t...deliveryDraft,\n\t\t\tparcels,\n\t\t\titems,\n\t\t\taddress: createAddress(\n\t\t\t\tdeliveryDraft.address,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tdeliveryDraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t};\n\n\t\tresource.shippingInfo.deliveries.push(delivery);\n\t}\n\n\tasync addParcelToDelivery(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\t{ deliveryId, deliveryKey, ...parcelDraft }: OrderAddParcelToDeliveryAction,\n\t) {\n\t\tif (!resource.shippingInfo) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"Resource has no shipping info\",\n\t\t\t});\n\t\t}\n\n\t\tif (!deliveryId && !deliveryKey) {\n\t\t\tthrow new CommercetoolsError<RequiredFieldError>({\n\t\t\t\tcode: \"RequiredField\",\n\t\t\t\tmessage: \"Either deliveryId or deliveryKey is required\",\n\t\t\t\tfield: \"deliveryId\",\n\t\t\t});\n\t\t}\n\n\t\tconst delivery = resource.shippingInfo.deliveries?.find((d) =>\n\t\t\tdeliveryId ? d.id === deliveryId : d.key === deliveryKey,\n\t\t) as Writable<Delivery> | undefined;\n\n\t\tif (!delivery) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: `A delivery with ${\n\t\t\t\t\tdeliveryId ? `ID '${deliveryId}'` : `key '${deliveryKey}'`\n\t\t\t\t} was not found on this order.`,\n\t\t\t});\n\t\t}\n\n\t\tconst { parcelKey, ...parcel } = parcelDraft;\n\t\tif (!delivery.parcels) {\n\t\t\tdelivery.parcels = [];\n\t\t}\n\n\t\tdelivery.parcels.push({\n\t\t\t...getBaseResourceProperties(),\n\t\t\t...parcel,\n\t\t\tkey: parcelKey,\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tparcel.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t});\n\t}\n\n\tsetDeliveryCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\t{ deliveryId, name, value }: OrderSetDeliveryCustomFieldAction,\n\t) {\n\t\tif (!resource.shippingInfo) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"Resource has no shipping info\",\n\t\t\t});\n\t\t}\n\n\t\tfor (const delivery of resource.shippingInfo.deliveries || []) {\n\t\t\tif (delivery.id === deliveryId && delivery.custom?.fields) {\n\t\t\t\tdelivery.custom.fields[name] = value;\n\t\t\t}\n\t\t}\n\t}\n\n\tsetLineItemCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Order,\n\t\t{ lineItemId, lineItemKey, name, value }: OrderSetLineItemCustomFieldAction,\n\t) {\n\t\tconst lineItem = resource.lineItems.find(\n\t\t\t(x) =>\n\t\t\t\t(lineItemId && x.id === lineItemId) ||\n\t\t\t\t(lineItemKey && x.key === lineItemKey),\n\t\t);\n\n\t\tif (!lineItem) {\n\t\t\t// Check if line item is found\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: \"General\",\n\t\t\t\tmessage: lineItemKey\n\t\t\t\t\t? `A line item with key '${lineItemKey}' not found.`\n\t\t\t\t\t: `A line item with ID '${lineItemId}' not found.`,\n\t\t\t});\n\t\t}\n\n\t\tif (!lineItem.custom) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"Resource has no custom field\",\n\t\t\t});\n\t\t}\n\n\t\tlineItem.custom.fields[name] = value;\n\t}\n\n\tasync setLineItemCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\t{ lineItemId, lineItemKey, type, fields }: OrderSetLineItemCustomTypeAction,\n\t) {\n\t\tconst lineItem = resource.lineItems.find(\n\t\t\t(x) =>\n\t\t\t\t(lineItemId && x.id === lineItemId) ||\n\t\t\t\t(lineItemKey && x.key === lineItemKey),\n\t\t);\n\n\t\tif (!lineItem) {\n\t\t\t// Check if line item is found\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: \"General\",\n\t\t\t\tmessage: lineItemKey\n\t\t\t\t\t? `A line item with key '${lineItemKey}' not found.`\n\t\t\t\t\t: `A line item with ID '${lineItemId}' not found.`,\n\t\t\t});\n\t\t}\n\n\t\tif (!type) {\n\t\t\tlineItem.custom = undefined;\n\t\t} else {\n\t\t\tconst resolvedType = await this._storage.getByResourceIdentifier(\n\t\t\t\tcontext.projectKey,\n\t\t\t\ttype,\n\t\t\t);\n\t\t\tif (!resolvedType) {\n\t\t\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>({\n\t\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\t\tmessage: `Type ${type} not found`,\n\t\t\t\t\ttypeId: \"type\",\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tlineItem.custom = {\n\t\t\t\ttype: {\n\t\t\t\t\ttypeId: \"type\",\n\t\t\t\t\tid: resolvedType.id,\n\t\t\t\t},\n\t\t\t\tfields: fields || {},\n\t\t\t};\n\t\t}\n\t}\n\n\tsetLocale(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\t{ locale }: OrderSetLocaleAction,\n\t) {\n\t\tresource.locale = locale;\n\t}\n\n\tsetOrderNumber(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\t{ orderNumber }: OrderSetOrderNumberAction,\n\t) {\n\t\tresource.orderNumber = orderNumber;\n\t}\n\n\tsetParcelCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\t{ parcelId, name, value }: OrderSetParcelCustomFieldAction,\n\t) {\n\t\tif (!resource.shippingInfo) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"Resource has no shipping info\",\n\t\t\t});\n\t\t}\n\n\t\tfor (const delivery of resource.shippingInfo.deliveries || []) {\n\t\t\tfor (const parcel of delivery.parcels || []) {\n\t\t\t\tif (parcel.id === parcelId && parcel.custom?.fields) {\n\t\t\t\t\tparcel.custom.fields[name] = value;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tsetPurchaseOrderNumber(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\t{ purchaseOrderNumber }: OrderSetPurchaseOrderNumberAction,\n\t) {\n\t\tresource.purchaseOrderNumber = purchaseOrderNumber;\n\t}\n\n\tsetShippingAddress(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\t{ address }: OrderSetShippingAddressAction,\n\t) {\n\t\tresource.shippingAddress = createAddress(\n\t\t\taddress,\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage,\n\t\t);\n\t}\n\n\tasync setStore(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\t{ store }: OrderSetStoreAction,\n\t) {\n\t\tif (!store) return;\n\t\tconst resolvedType = await this._storage.getByResourceIdentifier(\n\t\t\tcontext.projectKey,\n\t\t\tstore,\n\t\t);\n\t\tif (!resolvedType) {\n\t\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>({\n\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\tmessage: `No store found with key=${store.key}`,\n\t\t\t\ttypeId: \"store\",\n\t\t\t});\n\t\t}\n\n\t\tconst storeReference = resolvedType as Store;\n\t\tresource.store = {\n\t\t\ttypeId: \"store\",\n\t\t\tkey: storeReference.key,\n\t\t};\n\t}\n\n\tasync transitionState(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\t{ state }: OrderTransitionStateAction,\n\t) {\n\t\tconst resolvedType = (await this._storage.getByResourceIdentifier(\n\t\t\tcontext.projectKey,\n\t\t\tstate,\n\t\t)) as State | null;\n\n\t\tif (!resolvedType) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\t\tmessage: `No state found with key=${state.key} or id=${state.key}`,\n\t\t\t\t},\n\t\t\t\t404,\n\t\t\t);\n\t\t}\n\n\t\tresource.state = {\n\t\t\ttypeId: \"state\",\n\t\t\tid: resolvedType.id,\n\t\t\tobj: { ...resolvedType, key: state.key ?? \"\" },\n\t\t};\n\t}\n\n\tasync updateSyncInfo(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\t{ channel, externalId, syncedAt }: OrderUpdateSyncInfoAction,\n\t) {\n\t\tif (!channel) return;\n\t\tconst resolvedType = await this._storage.getByResourceIdentifier(\n\t\t\tcontext.projectKey,\n\t\t\tchannel,\n\t\t);\n\t\tif (!resolvedType) {\n\t\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>({\n\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\tmessage: `Channel ${channel} not found`,\n\t\t\t\ttypeId: \"channel\",\n\t\t\t});\n\t\t}\n\n\t\tconst syncData: SyncInfo = {\n\t\t\tchannel: {\n\t\t\t\ttypeId: \"channel\",\n\t\t\t\tid: resolvedType.id,\n\t\t\t},\n\t\t\texternalId,\n\t\t\tsyncedAt: syncedAt ?? new Date().toISOString(),\n\t\t};\n\n\t\tif (!resource.syncInfo?.length) {\n\t\t\tresource.syncInfo = [syncData];\n\t\t} else {\n\t\t\tconst lastSyncInfo = resource.syncInfo[resource.syncInfo.length - 1];\n\t\t\tif (\n\t\t\t\tlastSyncInfo.channel.id !== syncData.channel.id ||\n\t\t\t\tlastSyncInfo.externalId !== syncData.externalId\n\t\t\t) {\n\t\t\t\tresource.syncInfo.push(syncData);\n\t\t\t}\n\t\t}\n\t}\n}\n","import assert from \"node:assert\";\nimport type {\n\tCart,\n\tCartReference,\n\tCustomLineItem,\n\tCustomLineItemImportDraft,\n\tDelivery,\n\tDuplicateFieldError,\n\tGeneralError,\n\tInvalidOperationError,\n\tLineItem,\n\tLineItemImportDraft,\n\tOrder,\n\tOrderFromCartDraft,\n\tOrderFromQuoteDraft,\n\tOrderImportDraft,\n\tOrderPagedSearchResponse,\n\tOrderSearchRequest,\n\tProduct,\n\tProductVariant,\n\tQuote,\n\tReferencedResourceNotFoundError,\n\tResourceNotFoundError,\n\tShippingInfo,\n\tShippingInfoImportDraft,\n\tShippingMethodDoesNotMatchCartError,\n\tShippingMethodReference,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport {\n\tgenerateRandomString,\n\tgetBaseResourceProperties,\n} from \"#src/helpers.ts\";\nimport {\n\tcalculateTaxedPriceFromRate,\n\tcalculateTaxTotals,\n} from \"#src/lib/tax.ts\";\nimport { OrderSearch } from \"#src/orderSearch.ts\";\nimport { OrderFromCartDraftSchema } from \"#src/schemas/generated/order-from-cart.ts\";\nimport {\n\tcreateShippingInfoFromMethod,\n\tgetShippingMethodsMatchingCart,\n} from \"#src/shipping.ts\";\nimport type { Writable } from \"#src/types.ts\";\nimport type { RepositoryContext } from \"../abstract.ts\";\nimport { AbstractResourceRepository, type QueryParams } from \"../abstract.ts\";\nimport { checkConcurrentModification } from \"../errors.ts\";\nimport {\n\tcalculateMoneyTotalCentAmount,\n\tcreateAddress,\n\tcreateCentPrecisionMoney,\n\tcreateCustomFields,\n\tcreateTypedMoney,\n\tresolveStoreReference,\n} from \"../helpers.ts\";\nimport { priceFromDraft } from \"../product/helpers.ts\";\nimport { OrderUpdateHandler } from \"./actions.ts\";\n\nexport class OrderRepository extends AbstractResourceRepository<\"order\"> {\n\tprotected _searchService: OrderSearch;\n\n\tconstructor(config: Config) {\n\t\tsuper(\"order\", config);\n\t\tthis.actions = new OrderUpdateHandler(config.storage);\n\t\tthis._searchService = new OrderSearch(config);\n\t\tthis.draftSchema = OrderFromCartDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: OrderFromCartDraft,\n\t): Promise<Order> {\n\t\tassert(draft.cart, \"draft.cart is missing\");\n\t\treturn await this.createFromCart(\n\t\t\tcontext,\n\t\t\t{\n\t\t\t\tid: draft.cart.id!,\n\t\t\t\ttypeId: \"cart\",\n\t\t\t},\n\t\t\tdraft.orderNumber,\n\t\t);\n\t}\n\n\tasync createFromCart(\n\t\tcontext: RepositoryContext,\n\t\tcartReference: CartReference,\n\t\torderNumber?: string,\n\t) {\n\t\tconst cart = (await this._storage.getByResourceIdentifier(\n\t\t\tcontext.projectKey,\n\t\t\tcartReference,\n\t\t)) as Cart | null;\n\t\tif (!cart) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\t\tmessage: \"Cannot find cart\",\n\t\t\t\t},\n\t\t\t\t404,\n\t\t\t);\n\t\t}\n\n\t\tconst resource: Writable<Order> = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tanonymousId: cart.anonymousId,\n\t\t\tbillingAddress: cart.billingAddress,\n\t\t\tcart: cartReference,\n\t\t\tcountry: cart.country,\n\t\t\tcustom: cart.custom,\n\t\t\tcustomerEmail: cart.customerEmail,\n\t\t\tcustomerGroup: cart.customerGroup,\n\t\t\tcustomerId: cart.customerId,\n\t\t\tcustomLineItems: [],\n\t\t\tdirectDiscounts: cart.directDiscounts,\n\t\t\tdiscountCodes: cart.discountCodes,\n\t\t\tdiscountOnTotalPrice: cart.discountOnTotalPrice,\n\t\t\tlastMessageSequenceNumber: 0,\n\t\t\tlineItems: cart.lineItems,\n\t\t\tlocale: cart.locale,\n\t\t\torderNumber: orderNumber ?? generateRandomString(10),\n\t\t\torderState: \"Open\",\n\t\t\torigin: \"Customer\",\n\t\t\tpaymentInfo: cart.paymentInfo,\n\t\t\tpurchaseOrderNumber: cart.purchaseOrderNumber,\n\t\t\trefusedGifts: [],\n\t\t\tshipping: cart.shipping,\n\t\t\tshippingAddress: cart.shippingAddress,\n\t\t\tshippingInfo: cart.shippingInfo,\n\t\t\tshippingMode: cart.shippingMode,\n\t\t\tsyncInfo: [],\n\t\t\ttaxCalculationMode: cart.taxCalculationMode,\n\t\t\ttaxedPrice: cart.taxedPrice,\n\t\t\ttaxedShippingPrice: cart.taxedShippingPrice,\n\t\t\ttaxMode: cart.taxMode,\n\t\t\ttaxRoundingMode: cart.taxRoundingMode,\n\t\t\ttotalPrice: cart.totalPrice,\n\t\t\tstore: cart.store,\n\t\t};\n\n\t\tconst { taxedPrice, taxedShippingPrice } = calculateTaxTotals({\n\t\t\tlineItems: cart.lineItems,\n\t\t\tcustomLineItems: cart.customLineItems,\n\t\t\tshippingInfo: cart.shippingInfo,\n\t\t\ttotalPrice: cart.totalPrice,\n\t\t});\n\t\tresource.taxedPrice = resource.taxedPrice ?? taxedPrice;\n\t\tresource.taxedShippingPrice =\n\t\t\tresource.taxedShippingPrice ?? taxedShippingPrice;\n\t\treturn await this.saveNew(context, resource);\n\t}\n\n\tasync createFromQuote(\n\t\tcontext: RepositoryContext,\n\t\tdraft: OrderFromQuoteDraft,\n\t): Promise<Order> {\n\t\t// Resolving the reference raises ReferencedResourceNotFound when the quote\n\t\t// does not exist\n\t\tconst quote = await this._storage.getByResourceIdentifier<\"quote\">(\n\t\t\tcontext.projectKey,\n\t\t\tdraft.quote,\n\t\t);\n\n\t\tcheckConcurrentModification(quote.version, draft.version, quote.id);\n\n\t\tif (quote.quoteState !== \"Pending\") {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: `The quote with ID '${quote.id}' cannot be ordered because it is in state '${quote.quoteState}'.`,\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\tif (quote.validTo && new Date(quote.validTo) < new Date()) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: `The quote with ID '${quote.id}' cannot be ordered because it expired on ${quote.validTo}.`,\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\t// Converting a quote reuses its prices; nothing is recalculated\n\t\tconst resource: Writable<Order> = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tbillingAddress: quote.billingAddress,\n\t\t\tbusinessUnit: quote.businessUnit,\n\t\t\tcountry: quote.country,\n\t\t\tcustom: quote.custom,\n\t\t\tcustomerGroup: quote.customerGroup,\n\t\t\tcustomerId: quote.customer?.id,\n\t\t\tcustomLineItems: quote.customLineItems,\n\t\t\tdirectDiscounts: quote.directDiscounts,\n\t\t\titemShippingAddresses: quote.itemShippingAddresses,\n\t\t\tlastMessageSequenceNumber: 0,\n\t\t\tlineItems: quote.lineItems,\n\t\t\torderNumber: draft.orderNumber ?? generateRandomString(10),\n\t\t\torderState: draft.orderState ?? \"Open\",\n\t\t\torigin: \"Quote\",\n\t\t\tpaymentState: draft.paymentState,\n\t\t\tpurchaseOrderNumber: quote.purchaseOrderNumber,\n\t\t\tquote: {\n\t\t\t\ttypeId: \"quote\",\n\t\t\t\tid: quote.id,\n\t\t\t},\n\t\t\trefusedGifts: [],\n\t\t\tshipmentState: draft.shipmentState,\n\t\t\tshipping: [],\n\t\t\tshippingAddress: quote.shippingAddress,\n\t\t\tshippingInfo: quote.shippingInfo,\n\t\t\tshippingMode: \"Single\",\n\t\t\tstore: quote.store,\n\t\t\tsyncInfo: [],\n\t\t\ttaxCalculationMode: quote.taxCalculationMode,\n\t\t\ttaxedPrice: quote.taxedPrice,\n\t\t\ttaxMode: quote.taxMode,\n\t\t\ttaxRoundingMode: quote.taxRoundingMode,\n\t\t\ttotalPrice: createCentPrecisionMoney(quote.totalPrice),\n\t\t};\n\n\t\tconst order = await this.saveNew(context, resource);\n\n\t\tif (draft.quoteStateToAccepted) {\n\t\t\tconst accepted = {\n\t\t\t\t...quote,\n\t\t\t\tquoteState: \"Accepted\",\n\t\t\t\tversion: quote.version + 1,\n\t\t\t} as Writable<Quote>;\n\t\t\tawait this._storage.add(context.projectKey, \"quote\", accepted);\n\t\t}\n\n\t\treturn order;\n\t}\n\n\tasync import(\n\t\tcontext: RepositoryContext,\n\t\tdraft: OrderImportDraft,\n\t): Promise<Order> {\n\t\t// TODO: Check if order with given orderNumber already exists\n\t\tassert(this, \"OrderRepository not valid\");\n\t\tconst lineItems = await Promise.all(\n\t\t\tdraft.lineItems?.map((item) =>\n\t\t\t\tthis.lineItemFromImportDraft(context, item),\n\t\t\t) || [],\n\t\t);\n\t\tconst customLineItems = await Promise.all(\n\t\t\tdraft.customLineItems?.map((item) =>\n\t\t\t\tthis.customLineItemFromImportDraft(context, item),\n\t\t\t) || [],\n\t\t);\n\n\t\tconst resource: Writable<Order> = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\n\t\t\tbillingAddress: createAddress(\n\t\t\t\tdraft.billingAddress,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t\tshippingAddress: createAddress(\n\t\t\t\tdraft.shippingAddress,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t\tcustomerEmail: draft.customerEmail,\n\t\t\tcustomerId: draft.customerId,\n\t\t\tbusinessUnit: draft.businessUnit?.key\n\t\t\t\t? { typeId: \"business-unit\", key: draft.businessUnit.key }\n\t\t\t\t: undefined,\n\t\t\tlastMessageSequenceNumber: 0,\n\t\t\torderNumber: draft.orderNumber,\n\t\t\torderState: draft.orderState || \"Open\",\n\t\t\torigin: draft.origin || \"Customer\",\n\t\t\tpaymentState: draft.paymentState,\n\t\t\trefusedGifts: [],\n\t\t\tshippingMode: \"Single\",\n\t\t\tshipping: [],\n\t\t\tshippingInfo: undefined,\n\t\t\tstore: await resolveStoreReference(\n\t\t\t\tdraft.store,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t\tsyncInfo: [],\n\n\t\t\tlineItems,\n\t\t\tcustomLineItems,\n\n\t\t\ttotalPrice: createCentPrecisionMoney(draft.totalPrice),\n\t\t};\n\n\t\tif (draft.shippingInfo) {\n\t\t\tresource.shippingInfo = await this.shippingInfoFromImportDraft(\n\t\t\t\tcontext,\n\t\t\t\tresource,\n\t\t\t\tdraft.shippingInfo,\n\t\t\t);\n\t\t}\n\n\t\tconst { taxedPrice, taxedShippingPrice } = calculateTaxTotals({\n\t\t\tlineItems: resource.lineItems,\n\t\t\tcustomLineItems: resource.customLineItems,\n\t\t\tshippingInfo: resource.shippingInfo,\n\t\t\ttotalPrice: resource.totalPrice,\n\t\t});\n\t\tresource.taxedPrice = resource.taxedPrice ?? taxedPrice;\n\t\tresource.taxedShippingPrice =\n\t\t\tresource.taxedShippingPrice ?? taxedShippingPrice;\n\n\t\treturn await this.saveNew(context, resource);\n\t}\n\n\tprivate async lineItemFromImportDraft(\n\t\tcontext: RepositoryContext,\n\t\tdraft: LineItemImportDraft,\n\t): Promise<LineItem> {\n\t\tlet product: Product;\n\t\tlet variant: ProductVariant | undefined;\n\n\t\tif (draft.variant.sku) {\n\t\t\tvariant = {\n\t\t\t\tid: 0,\n\t\t\t\tsku: draft.variant.sku,\n\t\t\t};\n\n\t\t\tconst items = await this._storage.query(context.projectKey, \"product\", {\n\t\t\t\twhere: [\n\t\t\t\t\t`masterData(current(masterVariant(sku=\"${draft.variant.sku}\"))) or masterData(current(variants(sku=\"${draft.variant.sku}\")))`,\n\t\t\t\t],\n\t\t\t});\n\n\t\t\tif (items.count !== 1) {\n\t\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\t\tcode: \"General\",\n\t\t\t\t\tmessage: `A product containing a variant with SKU '${draft.variant.sku}' not found.`,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tproduct = items.results[0];\n\t\t\tif (product.masterData.current.masterVariant.sku === draft.variant.sku) {\n\t\t\t\tvariant = product.masterData.current.masterVariant;\n\t\t\t} else {\n\t\t\t\tvariant = product.masterData.current.variants.find(\n\t\t\t\t\t(v) => v.sku === draft.variant.sku,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!variant) {\n\t\t\t\tthrow new Error(\"Internal state error\");\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>({\n\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\tmessage: \"No product found\",\n\t\t\t\ttypeId: \"product\",\n\t\t\t});\n\t\t}\n\n\t\tconst quantity = draft.quantity ?? 1;\n\t\tconst totalPrice = createCentPrecisionMoney({\n\t\t\tcurrencyCode: draft.price.value.currencyCode,\n\t\t\tcentAmount: calculateMoneyTotalCentAmount(draft.price.value, quantity),\n\t\t});\n\n\t\treturn {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t\tdiscountedPricePerQuantity: [],\n\t\t\tlineItemMode: \"Standard\",\n\t\t\tname: draft.name,\n\t\t\tprice: await priceFromDraft(context, this._storage, draft.price),\n\t\t\tpriceMode: \"Platform\",\n\t\t\tproductId: product.id,\n\t\t\tproductType: product.productType,\n\t\t\tquantity,\n\t\t\tstate: draft.state || [],\n\t\t\ttaxRate: draft.taxRate,\n\t\t\ttaxedPrice: calculateTaxedPriceFromRate(\n\t\t\t\ttotalPrice.centAmount,\n\t\t\t\ttotalPrice.currencyCode,\n\t\t\t\tdraft.taxRate,\n\t\t\t),\n\t\t\ttaxedPricePortions: [],\n\t\t\tperMethodTaxRate: [],\n\t\t\ttotalPrice,\n\t\t\tvariant: {\n\t\t\t\tid: variant.id,\n\t\t\t\tsku: variant.sku,\n\t\t\t\tprice: await priceFromDraft(context, this._storage, draft.price),\n\t\t\t\tattributes: variant.attributes,\n\t\t\t},\n\t\t} satisfies LineItem;\n\t}\n\n\tprivate async customLineItemFromImportDraft(\n\t\tcontext: RepositoryContext,\n\t\tdraft: CustomLineItemImportDraft,\n\t): Promise<CustomLineItem> {\n\t\tconst quantity = draft.quantity ?? 1;\n\t\tconst totalPrice = createCentPrecisionMoney({\n\t\t\tcurrencyCode: draft.money.currencyCode,\n\t\t\tcentAmount: calculateMoneyTotalCentAmount(draft.money, quantity),\n\t\t});\n\n\t\treturn {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t\tdiscountedPricePerQuantity: [],\n\t\t\tmoney: createTypedMoney(draft.money),\n\t\t\tname: draft.name,\n\t\t\tquantity,\n\t\t\tperMethodTaxRate: [],\n\t\t\tpriceMode: draft.priceMode ?? \"Standard\",\n\t\t\tslug: draft.slug,\n\t\t\tstate: [],\n\t\t\ttotalPrice,\n\t\t\ttaxedPrice: calculateTaxedPriceFromRate(\n\t\t\t\ttotalPrice.centAmount,\n\t\t\t\ttotalPrice.currencyCode,\n\t\t\t\tdraft.taxRate,\n\t\t\t),\n\t\t\ttaxedPricePortions: [],\n\t\t} satisfies CustomLineItem;\n\t}\n\n\tasync getWithOrderNumber(\n\t\tcontext: RepositoryContext,\n\t\torderNumber: string,\n\t\tparams: QueryParams = {},\n\t): Promise<Order | undefined> {\n\t\tconst result = await this._storage.query(\n\t\t\tcontext.projectKey,\n\t\t\tthis.getTypeId(),\n\t\t\t{\n\t\t\t\t...params,\n\t\t\t\twhere: [`orderNumber=\"${orderNumber}\"`],\n\t\t\t},\n\t\t);\n\t\tif (result.count === 1) {\n\t\t\treturn result.results[0] as Order;\n\t\t}\n\n\t\t// Catch this for now, should be checked when creating/updating\n\t\tif (result.count > 1) {\n\t\t\tthrow new CommercetoolsError<DuplicateFieldError>({\n\t\t\t\tcode: \"DuplicateField\",\n\t\t\t\tmessage: \"Duplicate order numbers\",\n\t\t\t\tfield: \"orderNumber\",\n\t\t\t\tduplicateValue: orderNumber,\n\t\t\t});\n\t\t}\n\n\t\treturn;\n\t}\n\n\tasync createShippingInfo(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\tshippingMethodRef: ShippingMethodReference,\n\t): Promise<Writable<ShippingInfo>> {\n\t\tconst cartLikeForMatching: Writable<Cart> = {\n\t\t\t...resource,\n\t\t\tcartState: \"Active\" as const,\n\t\t\tinventoryMode: \"None\" as const,\n\t\t\titemShippingAddresses: [],\n\t\t\tpriceRoundingMode: resource.taxRoundingMode || \"HalfEven\",\n\t\t\ttaxMode: resource.taxMode || \"Platform\",\n\t\t\ttaxCalculationMode: resource.taxCalculationMode || \"LineItemLevel\",\n\t\t\ttaxRoundingMode: resource.taxRoundingMode || \"HalfEven\",\n\t\t\tdiscountCodes: resource.discountCodes || [],\n\t\t\tdirectDiscounts: resource.directDiscounts || [],\n\t\t\tshippingInfo: undefined,\n\t\t};\n\n\t\tconst shippingMethods = await getShippingMethodsMatchingCart(\n\t\t\tcontext,\n\t\t\tthis._storage,\n\t\t\tcartLikeForMatching,\n\t\t\t{\n\t\t\t\texpand: [\"zoneRates[*].zone\"],\n\t\t\t},\n\t\t);\n\n\t\tconst method = shippingMethods.results.find(\n\t\t\t(candidate) => candidate.id === shippingMethodRef.id,\n\t\t);\n\n\t\tif (!method) {\n\t\t\tthrow new CommercetoolsError<ShippingMethodDoesNotMatchCartError>({\n\t\t\t\tcode: \"ShippingMethodDoesNotMatchCart\",\n\t\t\t\tmessage: `The shipping method with ID '${shippingMethodRef.id}' is not allowed for the order with ID '${resource.id}'.`,\n\t\t\t});\n\t\t}\n\n\t\tconst baseShippingInfo = await createShippingInfoFromMethod(\n\t\t\tcontext,\n\t\t\tthis._storage,\n\t\t\tresource,\n\t\t\tmethod,\n\t\t);\n\n\t\treturn {\n\t\t\t...baseShippingInfo,\n\t\t\tdeliveries: [],\n\t\t};\n\t}\n\n\tprivate async shippingInfoFromImportDraft(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Order>,\n\t\tdraft: ShippingInfoImportDraft,\n\t): Promise<ShippingInfo | undefined> {\n\t\tif (!draft.shippingMethod) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst { ...shippingMethodRef } = draft.shippingMethod;\n\t\tif (shippingMethodRef.key && !shippingMethodRef.id) {\n\t\t\tconst shippingMethod =\n\t\t\t\tawait this._storage.getByResourceIdentifier<\"shipping-method\">(\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tshippingMethodRef,\n\t\t\t\t);\n\t\t\tif (!shippingMethod) {\n\t\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\t\tcode: \"General\",\n\t\t\t\t\tmessage: `A shipping method with key '${shippingMethodRef.key}' does not exist.`,\n\t\t\t\t});\n\t\t\t}\n\t\t\tshippingMethodRef.id = shippingMethod.id;\n\t\t}\n\n\t\tconst shippingInfo = await this.createShippingInfo(context, resource, {\n\t\t\ttypeId: \"shipping-method\",\n\t\t\tid: shippingMethodRef.id as string,\n\t\t});\n\n\t\tshippingInfo.deliveries = await this.deliveriesFromImportDraft(\n\t\t\tcontext,\n\t\t\tdraft,\n\t\t);\n\t\treturn shippingInfo;\n\t}\n\n\tprivate async deliveriesFromImportDraft(\n\t\tcontext: RepositoryContext,\n\t\tdraft: ShippingInfoImportDraft,\n\t): Promise<Delivery[]> {\n\t\tif (!draft.deliveries) return [];\n\n\t\treturn Promise.all(\n\t\t\tdraft.deliveries.map(async (deliveryDraft) => ({\n\t\t\t\t...getBaseResourceProperties(),\n\t\t\t\tkey: deliveryDraft.key,\n\t\t\t\titems: deliveryDraft.items ?? [],\n\t\t\t\tparcels: await Promise.all(\n\t\t\t\t\tdeliveryDraft.parcels?.map(async (parcel) => ({\n\t\t\t\t\t\t...getBaseResourceProperties(),\n\t\t\t\t\t\t...parcel,\n\t\t\t\t\t\tcustom: await createCustomFields(\n\t\t\t\t\t\t\tparcel.custom,\n\t\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\t\tthis._storage,\n\t\t\t\t\t\t),\n\t\t\t\t\t})) ?? [],\n\t\t\t\t),\n\t\t\t\taddress: createAddress(\n\t\t\t\t\tdeliveryDraft.address,\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tthis._storage,\n\t\t\t\t),\n\t\t\t\tcustom: await createCustomFields(\n\t\t\t\t\tdeliveryDraft.custom,\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tthis._storage,\n\t\t\t\t),\n\t\t\t})),\n\t\t);\n\t}\n\n\tasync search(\n\t\tcontext: RepositoryContext,\n\t\tsearchRequest: OrderSearchRequest,\n\t): Promise<OrderPagedSearchResponse> {\n\t\treturn await this._searchService.search(context.projectKey, searchRequest);\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tCustomFieldsDraftSchema,\n\tStagedQuoteResourceIdentifierSchema,\n\tStateReferenceSchema,\n} from \"./common.ts\";\n\nexport const QuoteDraftSchema = z.object({\n\tkey: z.string().nullish(),\n\tstagedQuote: StagedQuoteResourceIdentifierSchema,\n\tstagedQuoteVersion: z.number().int(),\n\tstagedQuoteStateToSent: z.boolean().nullish(),\n\tstate: StateReferenceSchema.nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n});\n","import type {\n\tInvalidJsonInputError,\n\tQuote,\n\tQuoteSetCustomFieldAction,\n\tQuoteSetCustomTypeAction,\n\tQuoteTransitionStateAction,\n\tQuoteUpdateAction,\n\tStateReference,\n} from \"@commercetools/platform-sdk\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport type { Writable } from \"#src/types.ts\";\nimport type { RepositoryContext, UpdateHandlerInterface } from \"../abstract.ts\";\nimport { AbstractUpdateHandler } from \"../abstract.ts\";\nimport { getReferenceFromResourceIdentifier } from \"../helpers.ts\";\n\nexport class QuoteUpdateHandler\n\textends AbstractUpdateHandler\n\timplements Partial<UpdateHandlerInterface<Quote, QuoteUpdateAction>>\n{\n\tsetCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Quote,\n\t\t{ name, value }: QuoteSetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Quote>,\n\t\t{ type, fields }: QuoteSetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n\n\tasync transitionState(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Quote>,\n\t\t{ state, force }: QuoteTransitionStateAction,\n\t) {\n\t\tlet stateReference: StateReference | undefined;\n\t\tif (state) {\n\t\t\tstateReference = await getReferenceFromResourceIdentifier<StateReference>(\n\t\t\t\tstate,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t);\n\t\t\tresource.state = stateReference;\n\t\t} else {\n\t\t\tthrow new CommercetoolsError<InvalidJsonInputError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidJsonInput\",\n\t\t\t\t\tmessage: \"Request body does not contain valid JSON.\",\n\t\t\t\t\tdetailedErrorMessage: \"actions -> state: Missing required value\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t}\n}\n","import type {\n\tInvalidOperationError,\n\tQuote,\n\tQuoteDraft,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { getBaseResourceProperties } from \"#src/helpers.ts\";\nimport { QuoteDraftSchema } from \"#src/schemas/generated/quote.ts\";\nimport type { RepositoryContext } from \"../abstract.ts\";\nimport { AbstractResourceRepository } from \"../abstract.ts\";\nimport { QuoteUpdateHandler } from \"./actions.ts\";\n\nexport class QuoteRepository extends AbstractResourceRepository<\"quote\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"quote\", config);\n\t\tthis.actions = new QuoteUpdateHandler(config.storage);\n\t\tthis.draftSchema = QuoteDraftSchema;\n\t}\n\n\tasync create(context: RepositoryContext, draft: QuoteDraft): Promise<Quote> {\n\t\tconst staged = await this._storage.getByResourceIdentifier<\"staged-quote\">(\n\t\t\tcontext.projectKey,\n\t\t\tdraft.stagedQuote,\n\t\t);\n\n\t\tif (!staged.quotationCart) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: \"Staged quote does not have a quotation cart\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\tconst cart = await this._storage.getByResourceIdentifier<\"cart\">(\n\t\t\tcontext.projectKey,\n\t\t\tstaged.quotationCart,\n\t\t);\n\n\t\tif (!cart.customerId) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: \"Cart does not have a customer\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\tconst resource: Quote = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tquoteState: \"Accepted\",\n\t\t\tquoteRequest: staged.quoteRequest,\n\t\t\tlineItems: cart.lineItems,\n\t\t\tcustomLineItems: cart.customLineItems,\n\t\t\tcustomer: {\n\t\t\t\ttypeId: \"customer\",\n\t\t\t\tid: cart.customerId,\n\t\t\t},\n\t\t\tstagedQuote: {\n\t\t\t\ttypeId: \"staged-quote\",\n\t\t\t\tid: staged.id,\n\t\t\t},\n\t\t\tpriceRoundingMode: cart.priceRoundingMode,\n\t\t\ttotalPrice: cart.totalPrice,\n\t\t\ttaxedPrice: cart.taxedPrice,\n\t\t\ttaxMode: cart.taxMode,\n\t\t\ttaxRoundingMode: cart.taxRoundingMode,\n\t\t\ttaxCalculationMode: cart.taxCalculationMode,\n\t\t\tbillingAddress: cart.billingAddress,\n\t\t\tshippingAddress: cart.shippingAddress,\n\t\t};\n\n\t\treturn resource;\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tCartResourceIdentifierSchema,\n\tCustomFieldsDraftSchema,\n\tStateReferenceSchema,\n} from \"./common.ts\";\n\nexport const QuoteRequestDraftSchema = z.object({\n\tcart: CartResourceIdentifierSchema,\n\tcartVersion: z.number().int(),\n\tkey: z.string().nullish(),\n\tcomment: z.string().nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\tstate: StateReferenceSchema.nullish(),\n\tpurchaseOrderNumber: z.string().nullish(),\n});\n","import type {\n\tInvalidJsonInputError,\n\tQuoteRequest,\n\tQuoteRequestChangeQuoteRequestStateAction,\n\tQuoteRequestSetCustomFieldAction,\n\tQuoteRequestSetCustomTypeAction,\n\tQuoteRequestTransitionStateAction,\n\tQuoteRequestUpdateAction,\n\tStateReference,\n} from \"@commercetools/platform-sdk\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport type { Writable } from \"#src/types.ts\";\nimport type { RepositoryContext, UpdateHandlerInterface } from \"../abstract.ts\";\nimport { AbstractUpdateHandler } from \"../abstract.ts\";\nimport { getReferenceFromResourceIdentifier } from \"../helpers.ts\";\n\nexport class QuoteRequestUpdateHandler\n\textends AbstractUpdateHandler\n\timplements\n\t\tPartial<UpdateHandlerInterface<QuoteRequest, QuoteRequestUpdateAction>>\n{\n\tchangeQuoteRequestState(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<QuoteRequest>,\n\t\t{ quoteRequestState }: QuoteRequestChangeQuoteRequestStateAction,\n\t) {\n\t\tresource.quoteRequestState = quoteRequestState;\n\t}\n\n\tsetCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: QuoteRequest,\n\t\t{ name, value }: QuoteRequestSetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<QuoteRequest>,\n\t\t{ type, fields }: QuoteRequestSetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n\n\tasync transitionState(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<QuoteRequest>,\n\t\t{ state, force }: QuoteRequestTransitionStateAction,\n\t) {\n\t\tlet stateReference: StateReference | undefined;\n\t\tif (state) {\n\t\t\tstateReference = await getReferenceFromResourceIdentifier<StateReference>(\n\t\t\t\tstate,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t);\n\t\t\tresource.state = stateReference;\n\t\t} else {\n\t\t\tthrow new CommercetoolsError<InvalidJsonInputError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidJsonInput\",\n\t\t\t\t\tmessage: \"Request body does not contain valid JSON.\",\n\t\t\t\t\tdetailedErrorMessage: \"actions -> state: Missing required value\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t}\n}\n","import assert from \"node:assert\";\nimport type {\n\tCart,\n\tCartReference,\n\tInvalidOperationError,\n\tMyQuoteRequestDraft,\n\tQuoteRequest,\n\tQuoteRequestDraft,\n\tResourceNotFoundError,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { getBaseResourceProperties } from \"#src/helpers.ts\";\nimport { QuoteRequestDraftSchema } from \"#src/schemas/generated/quote-request.ts\";\nimport type { RepositoryContext } from \"../abstract.ts\";\nimport { AbstractResourceRepository } from \"../abstract.ts\";\nimport { QuoteRequestUpdateHandler } from \"./actions.ts\";\n\nexport class QuoteRequestRepository extends AbstractResourceRepository<\"quote-request\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"quote-request\", config);\n\t\tthis.actions = new QuoteRequestUpdateHandler(config.storage);\n\t\tthis.draftSchema = QuoteRequestDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: QuoteRequestDraft | MyQuoteRequestDraft,\n\t): Promise<QuoteRequest> {\n\t\t// Handle the 'my' version of the draft\n\t\tif (\"cartId\" in draft) {\n\t\t\treturn await this.createFromCart(context, {\n\t\t\t\tid: draft.cartId,\n\t\t\t\ttypeId: \"cart\",\n\t\t\t});\n\t\t}\n\n\t\tassert(draft.cart, \"draft.cart is missing\");\n\t\treturn await this.createFromCart(context, {\n\t\t\tid: draft.cart.id!,\n\t\t\ttypeId: \"cart\",\n\t\t});\n\t}\n\n\tasync createFromCart(\n\t\tcontext: RepositoryContext,\n\t\tcartReference: CartReference,\n\t) {\n\t\tconst cart = (await this._storage.getByResourceIdentifier(\n\t\t\tcontext.projectKey,\n\t\t\tcartReference,\n\t\t)) as Cart | null;\n\t\tif (!cart) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\t\tmessage: \"Cannot find cart\",\n\t\t\t\t},\n\t\t\t\t404,\n\t\t\t);\n\t\t}\n\n\t\tif (!cart.customerId) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: \"Cart does not have a customer\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\tconst resource: QuoteRequest = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tbillingAddress: cart.billingAddress,\n\t\t\tcart: cartReference,\n\t\t\tcountry: cart.country,\n\t\t\tcustom: cart.custom,\n\t\t\tcustomer: {\n\t\t\t\ttypeId: \"customer\",\n\t\t\t\tid: cart.customerId,\n\t\t\t},\n\t\t\tcustomerGroup: cart.customerGroup,\n\t\t\tcustomLineItems: [],\n\t\t\tdirectDiscounts: cart.directDiscounts,\n\t\t\tlineItems: cart.lineItems,\n\t\t\tpaymentInfo: cart.paymentInfo,\n\t\t\tpriceRoundingMode: cart.priceRoundingMode,\n\t\t\tquoteRequestState: \"Submitted\",\n\t\t\tshippingAddress: cart.shippingAddress,\n\t\t\ttaxCalculationMode: cart.taxCalculationMode,\n\t\t\ttaxedPrice: cart.taxedPrice,\n\t\t\ttaxMode: cart.taxMode,\n\t\t\ttaxRoundingMode: cart.taxRoundingMode,\n\t\t\ttotalPrice: cart.totalPrice,\n\t\t\tstore: cart.store,\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tBusinessUnitResourceIdentifierSchema,\n\tCustomerResourceIdentifierSchema,\n\tCustomFieldsDraftSchema,\n\tLocalizedStringSchema,\n\tShoppingListLineItemDraftSchema,\n\tStoreResourceIdentifierSchema,\n\tTextLineItemDraftSchema,\n} from \"./common.ts\";\n\nexport const ShoppingListDraftSchema = z.object({\n\tname: LocalizedStringSchema,\n\tslug: LocalizedStringSchema.nullish(),\n\tcustomer: CustomerResourceIdentifierSchema.nullish(),\n\tkey: z.string().nullish(),\n\tdescription: LocalizedStringSchema.nullish(),\n\tanonymousId: z.string().nullish(),\n\tdeleteDaysAfterLastModification: z.number().int().nullish(),\n\tlineItems: z.array(ShoppingListLineItemDraftSchema).nullish(),\n\ttextLineItems: z.array(TextLineItemDraftSchema).nullish(),\n\tstore: StoreResourceIdentifierSchema.nullish(),\n\tbusinessUnit: BusinessUnitResourceIdentifierSchema.nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n});\n","import type {\n\tGeneralError,\n\tInvalidOperationError,\n\tProduct,\n\tShoppingList,\n\tShoppingListAddLineItemAction,\n\tShoppingListChangeLineItemQuantityAction,\n\tShoppingListChangeNameAction,\n\tShoppingListLineItem,\n\tShoppingListRemoveLineItemAction,\n\tShoppingListSetAnonymousIdAction,\n\tShoppingListSetCustomerAction,\n\tShoppingListSetCustomFieldAction,\n\tShoppingListSetCustomTypeAction,\n\tShoppingListSetDeleteDaysAfterLastModificationAction,\n\tShoppingListSetDescriptionAction,\n\tShoppingListSetKeyAction,\n\tShoppingListSetSlugAction,\n\tShoppingListSetStoreAction,\n\tShoppingListUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport type { Writable } from \"../../types.ts\";\nimport type { RepositoryContext, UpdateHandlerInterface } from \"../abstract.ts\";\nimport { AbstractUpdateHandler } from \"../abstract.ts\";\n\nexport class ShoppingListUpdateHandler\n\textends AbstractUpdateHandler\n\timplements\n\t\tPartial<UpdateHandlerInterface<ShoppingList, ShoppingListUpdateAction>>\n{\n\tasync addLineItem(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ShoppingList>,\n\t\t{\n\t\t\tproductId,\n\t\t\tvariantId,\n\t\t\tsku,\n\t\t\tquantity = 1,\n\t\t\taddedAt,\n\t\t\tkey,\n\t\t}: ShoppingListAddLineItemAction,\n\t) {\n\t\tlet product: Product | null = null;\n\n\t\tif (productId) {\n\t\t\t// Fetch product and variant by ID\n\t\t\tproduct = await this._storage.get(\n\t\t\t\tcontext.projectKey,\n\t\t\t\t\"product\",\n\t\t\t\tproductId,\n\t\t\t\t{},\n\t\t\t);\n\t\t} else if (sku) {\n\t\t\t// Fetch product and variant by SKU\n\t\t\tconst items = await this._storage.query(context.projectKey, \"product\", {\n\t\t\t\twhere: [\n\t\t\t\t\t`masterData(current(masterVariant(sku=\"${sku}\"))) or masterData(current(variants(sku=\"${sku}\")))`,\n\t\t\t\t],\n\t\t\t});\n\n\t\t\tif (items.count === 1) {\n\t\t\t\tproduct = items.results[0];\n\t\t\t}\n\t\t}\n\n\t\tif (!product) {\n\t\t\t// Check if product is found\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: \"General\",\n\t\t\t\tmessage: sku\n\t\t\t\t\t? `A product containing a variant with SKU '${sku}' not found.`\n\t\t\t\t\t: `A product with ID '${productId}' not found.`,\n\t\t\t});\n\t\t}\n\n\t\tlet varId: number | undefined = variantId;\n\t\tif (sku) {\n\t\t\tvarId = [\n\t\t\t\tproduct.masterData.current.masterVariant,\n\t\t\t\t...product.masterData.current.variants,\n\t\t\t].find((x) => x.sku === sku)?.id;\n\t\t}\n\t\tif (!varId) {\n\t\t\tvarId = product.masterData.current.masterVariant.id;\n\t\t}\n\n\t\tconst alreadyAdded = resource.lineItems.some(\n\t\t\t(x) => x.productId === product?.id && x.variantId === varId,\n\t\t);\n\t\tif (alreadyAdded) {\n\t\t\t// increase quantity and update total price\n\t\t\tresource.lineItems.forEach((x) => {\n\t\t\t\tif (x.productId === product?.id && x.variantId === varId) {\n\t\t\t\t\tx.quantity += quantity;\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\t// add line item\n\t\t\tresource.lineItems.push({\n\t\t\t\taddedAt: addedAt ? addedAt : new Date().toISOString(),\n\t\t\t\tid: uuidv4(),\n\t\t\t\tkey,\n\t\t\t\tproductId: product.id,\n\t\t\t\tproductSlug: product.masterData.current.slug,\n\t\t\t\tproductType: product.productType,\n\t\t\t\tname: product.masterData.current.name,\n\t\t\t\tvariantId: varId,\n\t\t\t\tquantity,\n\t\t\t\tpublished: Boolean(product.masterData.current),\n\t\t\t});\n\t\t}\n\t}\n\n\tchangeLineItemQuantity(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ShoppingList>,\n\t\t{\n\t\t\tlineItemId,\n\t\t\tlineItemKey,\n\t\t\tquantity,\n\t\t}: ShoppingListChangeLineItemQuantityAction,\n\t) {\n\t\tlet lineItem: Writable<ShoppingListLineItem> | undefined;\n\n\t\tif (lineItemId) {\n\t\t\tlineItem = resource.lineItems.find((x) => x.id === lineItemId);\n\t\t\tif (!lineItem) {\n\t\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\t\tcode: \"General\",\n\t\t\t\t\tmessage: `A line item with ID '${lineItemId}' not found.`,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (lineItemKey) {\n\t\t\tlineItem = resource.lineItems.find((x) => x.id === lineItemId);\n\t\t\tif (!lineItem) {\n\t\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\t\tcode: \"General\",\n\t\t\t\t\tmessage: `A line item with Key '${lineItemKey}' not found.`,\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: \"General\",\n\t\t\t\tmessage: \"Either lineItemid or lineItemKey needs to be provided.\",\n\t\t\t});\n\t\t}\n\n\t\tif (quantity === 0) {\n\t\t\t// delete line item\n\t\t\tresource.lineItems = resource.lineItems.filter(\n\t\t\t\t(x) => x.id !== lineItemId,\n\t\t\t);\n\t\t} else {\n\t\t\tresource.lineItems.forEach((x) => {\n\t\t\t\tif (x.id === lineItemId && quantity) {\n\t\t\t\t\tx.quantity = quantity;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\tchangeName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ShoppingList>,\n\t\t{ name }: ShoppingListChangeNameAction,\n\t) {\n\t\tresource.name = name;\n\t}\n\n\tremoveLineItem(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ShoppingList>,\n\t\t{ lineItemId, quantity }: ShoppingListRemoveLineItemAction,\n\t) {\n\t\tconst lineItem = resource.lineItems.find((x) => x.id === lineItemId);\n\t\tif (!lineItem) {\n\t\t\t// Check if product is found\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: \"General\",\n\t\t\t\tmessage: `A line item with ID '${lineItemId}' not found.`,\n\t\t\t});\n\t\t}\n\n\t\tconst shouldDelete = !quantity || quantity >= lineItem.quantity;\n\t\tif (shouldDelete) {\n\t\t\t// delete line item\n\t\t\tresource.lineItems = resource.lineItems.filter(\n\t\t\t\t(x) => x.id !== lineItemId,\n\t\t\t);\n\t\t} else {\n\t\t\t// decrease quantity and update total price\n\t\t\tresource.lineItems.forEach((x) => {\n\t\t\t\tif (x.id === lineItemId && quantity) {\n\t\t\t\t\tx.quantity -= quantity;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\tsetAnonymousId(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ShoppingList>,\n\t\t{ anonymousId }: ShoppingListSetAnonymousIdAction,\n\t) {\n\t\tresource.anonymousId = anonymousId;\n\t}\n\n\tsetCustomer(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ShoppingList>,\n\t\t{ customer }: ShoppingListSetCustomerAction,\n\t) {\n\t\tif (customer?.key) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"set customer on shoppinglist by key not implemented\",\n\t\t\t});\n\t\t}\n\t\tif (customer?.id) {\n\t\t\tresource.customer = { typeId: \"customer\", id: customer.id };\n\t\t}\n\t}\n\n\tsetCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: ShoppingList,\n\t\t{ name, value }: ShoppingListSetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ShoppingList>,\n\t\t{ type, fields }: ShoppingListSetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n\n\tsetDeleteDaysAfterLastModification(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ShoppingList>,\n\t\t{\n\t\t\tdeleteDaysAfterLastModification,\n\t\t}: ShoppingListSetDeleteDaysAfterLastModificationAction,\n\t) {\n\t\tresource.deleteDaysAfterLastModification = deleteDaysAfterLastModification;\n\t}\n\n\tsetDescription(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ShoppingList>,\n\t\t{ description }: ShoppingListSetDescriptionAction,\n\t) {\n\t\tresource.description = description;\n\t}\n\n\tsetKey(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ShoppingList>,\n\t\t{ key }: ShoppingListSetKeyAction,\n\t) {\n\t\tresource.key = key;\n\t}\n\n\tsetSlug(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ShoppingList>,\n\t\t{ slug }: ShoppingListSetSlugAction,\n\t) {\n\t\tresource.slug = slug;\n\t}\n\n\tsetStore(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ShoppingList>,\n\t\t{ store }: ShoppingListSetStoreAction,\n\t) {\n\t\tif (store?.key) {\n\t\t\tresource.store = { typeId: \"store\", key: store.key };\n\t\t}\n\t\tif (store?.id) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"set store on shoppinglist by id not implemented\",\n\t\t\t});\n\t\t}\n\t}\n}\n","import type {\n\tCustomerReference,\n\tLineItemDraft,\n\tReferencedResourceNotFoundError,\n\tShoppingList,\n\tShoppingListDraft,\n\tShoppingListLineItem,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { ShoppingListDraftSchema } from \"#src/schemas/generated/shopping-list.ts\";\nimport { getBaseResourceProperties } from \"../../helpers.ts\";\nimport type { Writable } from \"../../types.ts\";\nimport type { RepositoryContext } from \"../abstract.ts\";\nimport { AbstractResourceRepository } from \"../abstract.ts\";\nimport {\n\tcreateCustomFields,\n\tgetBusinessUnitKeyReference,\n\tgetReferenceFromResourceIdentifier,\n\tgetStoreKeyReference,\n} from \"../helpers.ts\";\nimport { ShoppingListUpdateHandler } from \"./actions.ts\";\n\nexport class ShoppingListRepository extends AbstractResourceRepository<\"shopping-list\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"shopping-list\", config);\n\t\tthis.actions = new ShoppingListUpdateHandler(config.storage);\n\t\tthis.draftSchema = ShoppingListDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: ShoppingListDraft,\n\t): Promise<ShoppingList> {\n\t\tconst lineItems = await Promise.all(\n\t\t\tdraft.lineItems?.map((draftLineItem) =>\n\t\t\t\tthis.draftLineItemtoLineItem(context.projectKey, draftLineItem),\n\t\t\t) ?? [],\n\t\t);\n\n\t\tconst resource: ShoppingList = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\t...draft,\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t\ttextLineItems: [],\n\t\t\tlineItems,\n\t\t\tcustomer: draft.customer\n\t\t\t\t? await getReferenceFromResourceIdentifier<CustomerReference>(\n\t\t\t\t\t\tdraft.customer,\n\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\tthis._storage,\n\t\t\t\t\t)\n\t\t\t\t: undefined,\n\t\t\tstore: draft.store\n\t\t\t\t? await getStoreKeyReference(\n\t\t\t\t\t\tdraft.store,\n\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\tthis._storage,\n\t\t\t\t\t)\n\t\t\t\t: undefined,\n\t\t\tbusinessUnit: draft.businessUnit\n\t\t\t\t? await getBusinessUnitKeyReference(\n\t\t\t\t\t\tdraft.businessUnit,\n\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\tthis._storage,\n\t\t\t\t\t)\n\t\t\t\t: undefined,\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n\n\tdraftLineItemtoLineItem = async (\n\t\tprojectKey: string,\n\t\tdraftLineItem: LineItemDraft,\n\t): Promise<ShoppingListLineItem> => {\n\t\tconst { sku, productId, variantId } = draftLineItem;\n\n\t\tconst lineItem: Writable<ShoppingListLineItem> = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\t...draftLineItem,\n\t\t\taddedAt: draftLineItem.addedAt ?? \"\",\n\t\t\tproductId: draftLineItem.productId ?? \"\",\n\t\t\tname: {},\n\t\t\tvariantId,\n\t\t\tpublished: true,\n\t\t\tquantity: draftLineItem.quantity ?? 1,\n\t\t\tproductType: { typeId: \"product-type\", id: \"\" },\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tdraftLineItem.custom,\n\t\t\t\tprojectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t};\n\n\t\tif (productId && variantId) {\n\t\t\treturn lineItem;\n\t\t}\n\n\t\tif (sku) {\n\t\t\tconst items = await this._storage.query(projectKey, \"product\", {\n\t\t\t\twhere: [\n\t\t\t\t\t`masterData(current(masterVariant(sku=\"${sku}\"))) or masterData(current(variants(sku=\"${sku}\")))`,\n\t\t\t\t],\n\t\t\t});\n\n\t\t\tif (items.count === 0) {\n\t\t\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>({\n\t\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\t\tmessage: `Product with sku ${sku} not found`,\n\t\t\t\t\ttypeId: \"product\",\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst product = items.results[0];\n\t\t\tconst allVariants = [\n\t\t\t\tproduct.masterData.current.masterVariant,\n\t\t\t\t...product.masterData.current.variants,\n\t\t\t];\n\t\t\tconst variantId = allVariants.find((e) => e.sku === sku)?.id;\n\t\t\tlineItem.variantId = variantId;\n\t\t\tlineItem.productId = product.id;\n\t\t\treturn lineItem;\n\t\t}\n\n\t\tif (productId) {\n\t\t\tconst items = await this._storage.query(projectKey, \"product\", {\n\t\t\t\twhere: [`id=\"${productId}\"`],\n\t\t\t});\n\n\t\t\tif (items.count === 0) {\n\t\t\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>({\n\t\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\t\tmessage: `Product with id ${productId} not found`,\n\t\t\t\t\ttypeId: \"product\",\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst variantId = items.results[0].masterData.current.masterVariant.id;\n\t\t\tlineItem.variantId = variantId;\n\t\t\treturn lineItem;\n\t\t}\n\n\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>({\n\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\tmessage:\n\t\t\t\t\"must provide either sku, productId or variantId for ShoppingListLineItem\",\n\t\t\ttypeId: \"product\",\n\t\t});\n\t};\n}\n","import { ApprovalFlowRepository } from \"./approval-flow.ts\";\nimport { ApprovalRuleRepository } from \"./approval-rule.ts\";\nimport { BusinessUnitRepository } from \"./business-unit.ts\";\nimport { CartRepository } from \"./cart/index.ts\";\nimport { OrderRepository } from \"./order/index.ts\";\nimport { QuoteRepository } from \"./quote/index.ts\";\nimport { QuoteRequestRepository } from \"./quote-request/index.ts\";\nimport { ShoppingListRepository } from \"./shopping-list/index.ts\";\n\nexport class AsAssociateOrderRepository extends OrderRepository {}\nexport class AsAssociateCartRepository extends CartRepository {}\nexport class AsAssociateQuoteRepository extends QuoteRepository {}\nexport class AsAssociateQuoteRequestRepository extends QuoteRequestRepository {}\nexport class AsAssociateShoppingListRepository extends ShoppingListRepository {}\nexport class AsAssociateBusinessUnitRepository extends BusinessUnitRepository {}\nexport class AsAssociateApprovalFlowRepository extends ApprovalFlowRepository {}\nexport class AsAssociateApprovalRuleRepository extends ApprovalRuleRepository {}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport { CustomFieldsDraftSchema, PermissionSchema } from \"./common.ts\";\n\nexport const AssociateRoleDraftSchema = z.object({\n\tkey: z.string(),\n\tname: z.string().nullish(),\n\tbuyerAssignable: z.boolean().nullish(),\n\tpermissions: z.array(PermissionSchema).nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n});\n","import type {\n\tAssociateRole,\n\tAssociateRoleAddPermissionAction,\n\tAssociateRoleChangeBuyerAssignableAction,\n\tAssociateRoleDraft,\n\tAssociateRoleRemovePermissionAction,\n\tAssociateRoleSetCustomFieldAction,\n\tAssociateRoleSetCustomTypeAction,\n\tAssociateRoleSetNameAction,\n\tAssociateRoleSetPermissionsAction,\n\tAssociateRoleUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { AssociateRoleDraftSchema } from \"#src/schemas/generated/associate-role.ts\";\nimport { getBaseResourceProperties } from \"../helpers.ts\";\nimport type { Writable } from \"../types.ts\";\nimport type { UpdateHandlerInterface } from \"./abstract.ts\";\nimport {\n\tAbstractResourceRepository,\n\tAbstractUpdateHandler,\n\ttype RepositoryContext,\n} from \"./abstract.ts\";\nimport { createCustomFields } from \"./helpers.ts\";\n\nexport class AssociateRoleRepository extends AbstractResourceRepository<\"associate-role\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"associate-role\", config);\n\t\tthis.actions = new AssociateRoleUpdateHandler(this._storage);\n\t\tthis.draftSchema = AssociateRoleDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: AssociateRoleDraft,\n\t): Promise<AssociateRole> {\n\t\tconst resource: AssociateRole = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tkey: draft.key,\n\t\t\tname: draft.name,\n\t\t\tbuyerAssignable: draft.buyerAssignable || false,\n\t\t\tpermissions: draft.permissions || [],\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t};\n\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n\nclass AssociateRoleUpdateHandler\n\textends AbstractUpdateHandler\n\timplements\n\t\tPartial<UpdateHandlerInterface<AssociateRole, AssociateRoleUpdateAction>>\n{\n\taddPermission(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<AssociateRole>,\n\t\t{ permission }: AssociateRoleAddPermissionAction,\n\t) {\n\t\tif (!resource.permissions) {\n\t\t\tresource.permissions = [permission];\n\t\t} else {\n\t\t\tresource.permissions.push(permission);\n\t\t}\n\t}\n\n\tchangeBuyerAssignable(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<AssociateRole>,\n\t\t{ buyerAssignable }: AssociateRoleChangeBuyerAssignableAction,\n\t) {\n\t\tresource.buyerAssignable = buyerAssignable;\n\t}\n\n\tremovePermission(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<AssociateRole>,\n\t\t{ permission }: AssociateRoleRemovePermissionAction,\n\t) {\n\t\tif (!resource.permissions) {\n\t\t\treturn;\n\t\t}\n\n\t\tresource.permissions = resource.permissions.filter((p) => p !== permission);\n\t}\n\n\tsetBuyerAssignable(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<AssociateRole>,\n\t\t{ buyerAssignable }: AssociateRoleChangeBuyerAssignableAction,\n\t) {\n\t\tresource.buyerAssignable = buyerAssignable;\n\t}\n\n\tsetCustomFields(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<AssociateRole>,\n\t\t{ name, value }: AssociateRoleSetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<AssociateRole>,\n\t\t{ type, fields }: AssociateRoleSetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n\n\tsetName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<AssociateRole>,\n\t\t{ name }: AssociateRoleSetNameAction,\n\t) {\n\t\tresource.name = name;\n\t}\n\n\tsetPermissions(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<AssociateRole>,\n\t\t{ permissions }: AssociateRoleSetPermissionsAction,\n\t) {\n\t\tresource.permissions = permissions || [];\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport { AttributeReferenceSchema, LocalizedStringSchema } from \"./common.ts\";\n\nexport const AttributeGroupDraftSchema = z.object({\n\tname: LocalizedStringSchema,\n\tdescription: LocalizedStringSchema.nullish(),\n\tattributes: z.array(AttributeReferenceSchema),\n\tkey: z.string().nullish(),\n});\n","import type {\n\tAttributeGroup,\n\tAttributeGroupChangeNameAction,\n\tAttributeGroupDraft,\n\tAttributeGroupSetAttributesAction,\n\tAttributeGroupSetDescriptionAction,\n\tAttributeGroupSetKeyAction,\n\tAttributeGroupUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { AttributeGroupDraftSchema } from \"#src/schemas/generated/attribute-group.ts\";\nimport { getBaseResourceProperties } from \"../helpers.ts\";\nimport type { Writable } from \"../types.ts\";\nimport type { UpdateHandlerInterface } from \"./abstract.ts\";\nimport {\n\tAbstractResourceRepository,\n\tAbstractUpdateHandler,\n\ttype RepositoryContext,\n} from \"./abstract.ts\";\n\nexport class AttributeGroupRepository extends AbstractResourceRepository<\"attribute-group\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"attribute-group\", config);\n\t\tthis.actions = new AttributeGroupUpdateHandler(this._storage);\n\t\tthis.draftSchema = AttributeGroupDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: AttributeGroupDraft,\n\t): Promise<AttributeGroup> {\n\t\tconst resource: AttributeGroup = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tname: draft.name,\n\t\t\tdescription: draft.description,\n\t\t\tkey: draft.key,\n\t\t\tattributes: draft.attributes,\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n\nclass AttributeGroupUpdateHandler\n\textends AbstractUpdateHandler\n\timplements\n\t\tPartial<UpdateHandlerInterface<AttributeGroup, AttributeGroupUpdateAction>>\n{\n\tchangeName(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<AttributeGroup>,\n\t\t{ name }: AttributeGroupChangeNameAction,\n\t) {\n\t\tresource.name = name;\n\t}\n\n\tsetAttributes(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<AttributeGroup>,\n\t\t{ attributes }: AttributeGroupSetAttributesAction,\n\t) {\n\t\tresource.attributes = attributes;\n\t}\n\n\tsetDescription(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<AttributeGroup>,\n\t\t{ description }: AttributeGroupSetDescriptionAction,\n\t) {\n\t\tresource.description = description;\n\t}\n\n\tsetKey(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<AttributeGroup>,\n\t\t{ key }: AttributeGroupSetKeyAction,\n\t) {\n\t\tresource.key = key;\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tCartDiscountTargetSchema,\n\tCartDiscountValueDraftSchema,\n\tCustomFieldsDraftSchema,\n\tDiscountGroupResourceIdentifierSchema,\n\tLocalizedStringSchema,\n\tRecurringOrderScopeDraftSchema,\n\tStackingModeSchema,\n\tStoreResourceIdentifierSchema,\n} from \"./common.ts\";\n\nexport const CartDiscountDraftSchema = z.object({\n\tname: LocalizedStringSchema,\n\tkey: z.string().nullish(),\n\tdescription: LocalizedStringSchema.nullish(),\n\tvalue: CartDiscountValueDraftSchema,\n\tcartPredicate: z.string(),\n\ttarget: CartDiscountTargetSchema.nullish(),\n\tsortOrder: z.string().nullish(),\n\tstores: z.array(StoreResourceIdentifierSchema).nullish(),\n\tisActive: z.boolean().nullish(),\n\tvalidFrom: z.string().nullish(),\n\tvalidUntil: z.string().nullish(),\n\trequiresDiscountCode: z.boolean().nullish(),\n\tstackingMode: StackingModeSchema.nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\tdiscountGroup: DiscountGroupResourceIdentifierSchema.nullish(),\n\trecurringOrderScope: RecurringOrderScopeDraftSchema.nullish(),\n});\n","import type {\n\tCartDiscount,\n\tCartDiscountChangeIsActiveAction,\n\tCartDiscountChangeSortOrderAction,\n\tCartDiscountChangeTargetAction,\n\tCartDiscountSetCustomFieldAction,\n\tCartDiscountSetCustomTypeAction,\n\tCartDiscountSetDescriptionAction,\n\tCartDiscountSetKeyAction,\n\tCartDiscountSetStoresAction,\n\tCartDiscountSetValidFromAction,\n\tCartDiscountSetValidFromAndUntilAction,\n\tCartDiscountSetValidUntilAction,\n\tCartDiscountUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport { getStoreKeyReference } from \"#src/repositories/helpers.ts\";\nimport type { Writable } from \"#src/types.ts\";\nimport type { UpdateHandlerInterface } from \"../abstract.ts\";\nimport { AbstractUpdateHandler, type RepositoryContext } from \"../abstract.ts\";\n\nexport class CartDiscountUpdateHandler\n\textends AbstractUpdateHandler\n\timplements\n\t\tPartial<UpdateHandlerInterface<CartDiscount, CartDiscountUpdateAction>>\n{\n\tchangeIsActive(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<CartDiscount>,\n\t\t{ isActive }: CartDiscountChangeIsActiveAction,\n\t) {\n\t\tresource.isActive = isActive;\n\t}\n\n\tchangeSortOrder(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<CartDiscount>,\n\t\t{ sortOrder }: CartDiscountChangeSortOrderAction,\n\t) {\n\t\tresource.sortOrder = sortOrder;\n\t}\n\n\tchangeTarget(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<CartDiscount>,\n\t\t{ target }: CartDiscountChangeTargetAction,\n\t) {\n\t\tresource.target = target;\n\t}\n\n\tsetCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<CartDiscount>,\n\t\t{ name, value }: CartDiscountSetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<CartDiscount>,\n\t\t{ type, fields }: CartDiscountSetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n\n\tsetDescription(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<CartDiscount>,\n\t\t{ description }: CartDiscountSetDescriptionAction,\n\t) {\n\t\tresource.description = description;\n\t}\n\n\tsetKey(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<CartDiscount>,\n\t\t{ key }: CartDiscountSetKeyAction,\n\t) {\n\t\tresource.key = key;\n\t}\n\n\tasync setStores(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<CartDiscount>,\n\t\t{ stores }: CartDiscountSetStoresAction,\n\t) {\n\t\tconst resolvedStores = stores\n\t\t\t? await Promise.all(\n\t\t\t\t\tstores.map((s) =>\n\t\t\t\t\t\tgetStoreKeyReference(s, context.projectKey, this._storage),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t: undefined;\n\t\tresource.stores = resolvedStores as Writable<CartDiscount>[\"stores\"];\n\t}\n\n\tsetValidFrom(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<CartDiscount>,\n\t\t{ validFrom }: CartDiscountSetValidFromAction,\n\t) {\n\t\tresource.validFrom = validFrom;\n\t}\n\n\tsetValidFromAndUntil(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<CartDiscount>,\n\t\t{ validFrom, validUntil }: CartDiscountSetValidFromAndUntilAction,\n\t) {\n\t\tresource.validFrom = validFrom;\n\t\tresource.validUntil = validUntil;\n\t}\n\n\tsetValidUntil(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<CartDiscount>,\n\t\t{ validUntil }: CartDiscountSetValidUntilAction,\n\t) {\n\t\tresource.validUntil = validUntil;\n\t}\n}\n","import type {\n\tCartDiscount,\n\tCartDiscountDraft,\n\tCartDiscountValueAbsolute,\n\tCartDiscountValueDraft,\n\tCartDiscountValueFixed,\n\tCartDiscountValueGiftLineItem,\n\tCartDiscountValueRelative,\n\tRecurringOrderScope,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { getBaseResourceProperties } from \"#src/helpers.ts\";\nimport { CartDiscountDraftSchema } from \"#src/schemas/generated/cart-discount.ts\";\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from \"../abstract.ts\";\nimport {\n\tcreateCustomFields,\n\tcreateTypedMoney,\n\tgetStoreKeyReference,\n} from \"../helpers.ts\";\nimport { CartDiscountUpdateHandler } from \"./actions.ts\";\n\nexport class CartDiscountRepository extends AbstractResourceRepository<\"cart-discount\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"cart-discount\", config);\n\t\tthis.actions = new CartDiscountUpdateHandler(config.storage);\n\t\tthis.draftSchema = CartDiscountDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: CartDiscountDraft,\n\t): Promise<CartDiscount> {\n\t\tconst stores = await Promise.all(\n\t\t\tdraft.stores?.map((s) =>\n\t\t\t\tgetStoreKeyReference(s, context.projectKey, this._storage),\n\t\t\t) ?? [],\n\t\t);\n\n\t\tconst resource: CartDiscount = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tkey: draft.key,\n\t\t\tdescription: draft.description,\n\t\t\tcartPredicate: draft.cartPredicate,\n\t\t\tisActive: draft.isActive || false,\n\t\t\tname: draft.name,\n\t\t\tstores,\n\t\t\treferences: [],\n\t\t\ttarget: draft.target,\n\t\t\trequiresDiscountCode: draft.requiresDiscountCode || false,\n\t\t\tsortOrder: draft.sortOrder ?? \"0.1\",\n\t\t\tstackingMode: draft.stackingMode || \"Stacking\",\n\t\t\tvalidFrom: draft.validFrom,\n\t\t\tvalidUntil: draft.validUntil,\n\t\t\tvalue: this.transformValueDraft(draft.value),\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t\trecurringOrderScope: draft.recurringOrderScope\n\t\t\t\t? ({ type: draft.recurringOrderScope.type } as RecurringOrderScope)\n\t\t\t\t: ({ type: \"AnyOrder\" } as RecurringOrderScope),\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n\n\tprivate transformValueDraft(value: CartDiscountValueDraft) {\n\t\tswitch (value.type) {\n\t\t\tcase \"absolute\": {\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"absolute\",\n\t\t\t\t\tmoney: value.money.map(createTypedMoney),\n\t\t\t\t} as CartDiscountValueAbsolute;\n\t\t\t}\n\t\t\tcase \"fixed\": {\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"fixed\",\n\t\t\t\t\tmoney: value.money.map(createTypedMoney),\n\t\t\t\t} as CartDiscountValueFixed;\n\t\t\t}\n\t\t\tcase \"giftLineItem\": {\n\t\t\t\treturn {\n\t\t\t\t\t...value,\n\t\t\t\t} as CartDiscountValueGiftLineItem;\n\t\t\t}\n\t\t\tcase \"relative\": {\n\t\t\t\treturn {\n\t\t\t\t\t...value,\n\t\t\t\t} as CartDiscountValueRelative;\n\t\t\t}\n\t\t}\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tAssetDraftSchema,\n\tCategoryResourceIdentifierSchema,\n\tCustomFieldsDraftSchema,\n\tLocalizedStringSchema,\n} from \"./common.ts\";\n\nexport const CategoryDraftSchema = z.object({\n\tname: LocalizedStringSchema,\n\tslug: LocalizedStringSchema,\n\tdescription: LocalizedStringSchema.nullish(),\n\tparent: CategoryResourceIdentifierSchema.nullish(),\n\torderHint: z.string().nullish(),\n\texternalId: z.string().nullish(),\n\tmetaTitle: LocalizedStringSchema.nullish(),\n\tmetaDescription: LocalizedStringSchema.nullish(),\n\tmetaKeywords: LocalizedStringSchema.nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\tassets: z.array(AssetDraftSchema).nullish(),\n\tkey: z.string().nullish(),\n});\n","import type {\n\tAsset,\n\tAssetDraft,\n\tCategory,\n\tCategoryAddAssetAction,\n\tCategoryChangeAssetNameAction,\n\tCategoryChangeNameAction,\n\tCategoryChangeParentAction,\n\tCategoryChangeSlugAction,\n\tCategoryRemoveAssetAction,\n\tCategorySetAssetDescriptionAction,\n\tCategorySetAssetSourcesAction,\n\tCategorySetCustomFieldAction,\n\tCategorySetCustomTypeAction,\n\tCategorySetDescriptionAction,\n\tCategorySetKeyAction,\n\tCategorySetMetaDescriptionAction,\n\tCategorySetMetaKeywordsAction,\n\tCategorySetMetaTitleAction,\n\tCategoryUpdateAction,\n\tReferencedResourceNotFoundError,\n} from \"@commercetools/platform-sdk\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport type { Writable } from \"#src/types.ts\";\nimport type { RepositoryContext, UpdateHandlerInterface } from \"../abstract.ts\";\nimport { AbstractUpdateHandler } from \"../abstract.ts\";\nimport { createCustomFields } from \"../helpers.ts\";\n\nexport class CategoryUpdateHandler\n\textends AbstractUpdateHandler\n\timplements Partial<UpdateHandlerInterface<Category, CategoryUpdateAction>>\n{\n\tasync addAsset(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Category>,\n\t\t{ asset }: CategoryAddAssetAction,\n\t) {\n\t\tif (!resource.assets) {\n\t\t\tresource.assets = [await this.assetFromAssetDraft(asset, context)];\n\t\t} else {\n\t\t\tresource.assets.push(await this.assetFromAssetDraft(asset, context));\n\t\t}\n\t}\n\n\tchangeAssetName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Category>,\n\t\t{ assetId, assetKey, name }: CategoryChangeAssetNameAction,\n\t) {\n\t\tresource.assets?.forEach((asset) => {\n\t\t\tif (assetId && assetId === asset.id) {\n\t\t\t\tasset.name = name;\n\t\t\t}\n\t\t\tif (assetKey && assetKey === asset.key) {\n\t\t\t\tasset.name = name;\n\t\t\t}\n\t\t});\n\t}\n\n\tchangeName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Category>,\n\t\t{ name }: CategoryChangeNameAction,\n\t) {\n\t\tresource.name = name;\n\t}\n\n\tasync changeParent(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Category>,\n\t\t{ parent }: CategoryChangeParentAction,\n\t) {\n\t\tconst category = await this._storage.getByResourceIdentifier(\n\t\t\tcontext.projectKey,\n\t\t\tparent,\n\t\t);\n\t\tif (!category) {\n\t\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\t\tmessage: \"No category found for reference\",\n\t\t\t\t\ttypeId: \"category\",\n\t\t\t\t\tid: parent.id,\n\t\t\t\t\tkey: parent.key,\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tresource.parent = {\n\t\t\ttypeId: \"category\",\n\t\t\tid: category.id,\n\t\t};\n\t}\n\n\tchangeSlug(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Category>,\n\t\t{ slug }: CategoryChangeSlugAction,\n\t) {\n\t\tresource.slug = slug;\n\t}\n\n\tremoveAsset(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Category>,\n\t\t{ assetId, assetKey }: CategoryRemoveAssetAction,\n\t) {\n\t\tif (!resource.assets) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (assetId) {\n\t\t\tresource.assets = resource.assets.filter((obj) => obj.id !== assetId);\n\n\t\t\treturn;\n\t\t}\n\n\t\tif (assetKey) {\n\t\t\tresource.assets = resource.assets.filter((obj) => obj.key !== assetKey);\n\n\t\t\treturn;\n\t\t}\n\t}\n\n\tsetAssetDescription(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Category>,\n\t\t{ assetId, assetKey, description }: CategorySetAssetDescriptionAction,\n\t) {\n\t\tresource.assets?.forEach((asset) => {\n\t\t\tif (assetId && assetId === asset.id) {\n\t\t\t\tasset.description = description;\n\t\t\t}\n\t\t\tif (assetKey && assetKey === asset.key) {\n\t\t\t\tasset.description = description;\n\t\t\t}\n\t\t});\n\t}\n\n\tsetAssetSources(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Category>,\n\t\t{ assetId, assetKey, sources }: CategorySetAssetSourcesAction,\n\t) {\n\t\tresource.assets?.forEach((asset) => {\n\t\t\tif (assetId && assetId === asset.id) {\n\t\t\t\tasset.sources = sources;\n\t\t\t}\n\t\t\tif (assetKey && assetKey === asset.key) {\n\t\t\t\tasset.sources = sources;\n\t\t\t}\n\t\t});\n\t}\n\n\tsetCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Category>,\n\t\t{ name, value }: CategorySetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Category>,\n\t\t{ type, fields }: CategorySetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n\n\tsetDescription(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Category>,\n\t\t{ description }: CategorySetDescriptionAction,\n\t) {\n\t\tresource.description = description;\n\t}\n\n\tsetKey(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Category>,\n\t\t{ key }: CategorySetKeyAction,\n\t) {\n\t\tresource.key = key;\n\t}\n\n\tsetMetaDescription(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Category>,\n\t\t{ metaDescription }: CategorySetMetaDescriptionAction,\n\t) {\n\t\tresource.metaDescription = metaDescription;\n\t}\n\n\tsetMetaKeywords(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Category>,\n\t\t{ metaKeywords }: CategorySetMetaKeywordsAction,\n\t) {\n\t\tresource.metaKeywords = metaKeywords;\n\t}\n\n\tsetMetaTitle(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Category>,\n\t\t{ metaTitle }: CategorySetMetaTitleAction,\n\t) {\n\t\tresource.metaTitle = metaTitle;\n\t}\n\n\tassetFromAssetDraft = async (\n\t\tdraft: AssetDraft,\n\t\tcontext: RepositoryContext,\n\t): Promise<Asset> => ({\n\t\t...draft,\n\t\tid: uuidv4(),\n\t\tcustom: await createCustomFields(\n\t\t\tdraft.custom,\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage,\n\t\t),\n\t});\n}\n","import type {\n\tCategory,\n\tCategoryDraft,\n\tCategoryReference,\n} from \"@commercetools/platform-sdk\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport type { Config } from \"#src/config.ts\";\nimport { getBaseResourceProperties } from \"#src/helpers.ts\";\nimport { parseExpandClause } from \"#src/lib/expandParser.ts\";\nimport { CategoryDraftSchema } from \"#src/schemas/generated/category.ts\";\nimport type { Writable } from \"#src/types.ts\";\nimport type { GetParams } from \"../abstract.ts\";\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from \"../abstract.ts\";\nimport {\n\tcreateCustomFields,\n\tgetReferenceFromResourceIdentifier,\n} from \"../helpers.ts\";\nimport { CategoryUpdateHandler } from \"./actions.ts\";\n\nexport class CategoryRepository extends AbstractResourceRepository<\"category\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"category\", config);\n\t\tthis.actions = new CategoryUpdateHandler(this._storage);\n\t\tthis.draftSchema = CategoryDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: CategoryDraft,\n\t): Promise<Category> {\n\t\tconst assets = draft.assets\n\t\t\t? await Promise.all(\n\t\t\t\t\tdraft.assets.map(async (d) => ({\n\t\t\t\t\t\tid: uuidv4(),\n\t\t\t\t\t\tname: d.name,\n\t\t\t\t\t\tdescription: d.description,\n\t\t\t\t\t\tsources: d.sources,\n\t\t\t\t\t\ttags: d.tags,\n\t\t\t\t\t\tkey: d.key,\n\t\t\t\t\t\tcustom: await createCustomFields(\n\t\t\t\t\t\t\td.custom,\n\t\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\t\tthis._storage,\n\t\t\t\t\t\t),\n\t\t\t\t\t})),\n\t\t\t\t)\n\t\t\t: [];\n\n\t\tconst resource: Category = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tkey: draft.key,\n\t\t\tname: draft.name,\n\t\t\tslug: draft.slug,\n\t\t\tdescription: draft.description,\n\t\t\tmetaDescription: draft.metaDescription,\n\t\t\tmetaKeywords: draft.metaKeywords,\n\t\t\torderHint: draft.orderHint || \"\",\n\t\t\texternalId: draft.externalId || \"\",\n\t\t\tparent: draft.parent\n\t\t\t\t? await getReferenceFromResourceIdentifier<CategoryReference>(\n\t\t\t\t\t\tdraft.parent,\n\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\tthis._storage,\n\t\t\t\t\t)\n\t\t\t\t: undefined,\n\t\t\tancestors: [], // Resolved at runtime\n\t\t\tassets,\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n\n\tasync postProcessResource(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Category>,\n\t\tparams?: GetParams,\n\t): Promise<Category> {\n\t\tlet node: Category = resource;\n\t\tconst ancestors: CategoryReference[] = [];\n\n\t\t// TODO: The expand clause here is a hack, the current expand architecture\n\t\t// is not able to handle the case for 'dynamic' fields like ancestors which\n\t\t// are resolved at runtime.  We should do the expand resolution post query\n\t\t// execution for all resources\n\n\t\tconst expandClauses = params?.expand?.map(parseExpandClause) ?? [];\n\t\tconst addExpand = expandClauses?.find(\n\t\t\t(c) => c.element === \"ancestors\" && c.index === \"*\",\n\t\t);\n\n\t\twhile (node.parent) {\n\t\t\tnode = await this._storage.getByResourceIdentifier<\"category\">(\n\t\t\t\tcontext.projectKey,\n\t\t\t\tnode.parent,\n\t\t\t);\n\t\t\tancestors.push({\n\t\t\t\ttypeId: \"category\",\n\t\t\t\tid: node.id,\n\t\t\t\tobj: addExpand ? node : undefined,\n\t\t\t});\n\t\t}\n\n\t\tresource.ancestors = ancestors;\n\t\treturn resource;\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tBaseAddressSchema,\n\tChannelRoleEnumSchema,\n\tCustomFieldsDraftSchema,\n\tGeoJsonSchema,\n\tLocalizedStringSchema,\n} from \"./common.ts\";\n\nexport const ChannelDraftSchema = z.object({\n\tkey: z.string(),\n\troles: z.array(ChannelRoleEnumSchema).nullish(),\n\tname: LocalizedStringSchema.nullish(),\n\tdescription: LocalizedStringSchema.nullish(),\n\taddress: BaseAddressSchema.nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\tgeoLocation: GeoJsonSchema.nullish(),\n});\n","import type {\n\tChannel,\n\tChannelChangeDescriptionAction,\n\tChannelChangeKeyAction,\n\tChannelChangeNameAction,\n\tChannelDraft,\n\tChannelSetAddressAction,\n\tChannelSetCustomFieldAction,\n\tChannelSetCustomTypeAction,\n\tChannelSetGeoLocationAction,\n\tChannelUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { ChannelDraftSchema } from \"#src/schemas/generated/channel.ts\";\nimport { getBaseResourceProperties } from \"../helpers.ts\";\nimport type { Writable } from \"../types.ts\";\nimport type { UpdateHandlerInterface } from \"./abstract.ts\";\nimport {\n\tAbstractResourceRepository,\n\tAbstractUpdateHandler,\n\ttype RepositoryContext,\n} from \"./abstract.ts\";\nimport { createAddress, createCustomFields } from \"./helpers.ts\";\n\nexport class ChannelRepository extends AbstractResourceRepository<\"channel\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"channel\", config);\n\t\tthis.actions = new ChannelUpdateHandler(this._storage);\n\t\tthis.draftSchema = ChannelDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: ChannelDraft,\n\t): Promise<Channel> {\n\t\tconst resource: Channel = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tkey: draft.key,\n\t\t\tname: draft.name,\n\t\t\tdescription: draft.description,\n\t\t\troles: draft.roles || [],\n\t\t\tgeoLocation: draft.geoLocation,\n\t\t\taddress: createAddress(draft.address, context.projectKey, this._storage),\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n\nclass ChannelUpdateHandler\n\textends AbstractUpdateHandler\n\timplements Partial<UpdateHandlerInterface<Channel, ChannelUpdateAction>>\n{\n\tchangeDescription(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Channel>,\n\t\t{ description }: ChannelChangeDescriptionAction,\n\t) {\n\t\tresource.description = description;\n\t}\n\n\tchangeKey(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Channel>,\n\t\t{ key }: ChannelChangeKeyAction,\n\t) {\n\t\tresource.key = key;\n\t}\n\n\tchangeName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Channel>,\n\t\t{ name }: ChannelChangeNameAction,\n\t) {\n\t\tresource.name = name;\n\t}\n\n\tsetAddress(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Channel>,\n\t\t{ address }: ChannelSetAddressAction,\n\t) {\n\t\tresource.address = createAddress(\n\t\t\taddress,\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage,\n\t\t);\n\t}\n\n\tsetCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Channel>,\n\t\t{ name, value }: ChannelSetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Channel>,\n\t\t{ type, fields }: ChannelSetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n\n\tsetGeoLocation(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Channel>,\n\t\t{ geoLocation }: ChannelSetGeoLocationAction,\n\t) {\n\t\tresource.geoLocation = geoLocation;\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\n\nexport const CustomObjectDraftSchema = z.object({\n\tcontainer: z.string(),\n\tkey: z.string(),\n\tvalue: z.unknown(),\n\tversion: z.number().int().nullish(),\n});\n","import type {\n\tCustomObject,\n\tCustomObjectDraft,\n\tInvalidOperationError,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { CustomObjectDraftSchema } from \"#src/schemas/generated/custom-object.ts\";\nimport { getBaseResourceProperties } from \"../helpers.ts\";\nimport type { Writable } from \"../types.ts\";\nimport type { QueryParams } from \"./abstract.ts\";\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from \"./abstract.ts\";\nimport { checkConcurrentModification } from \"./errors.ts\";\n\nexport class CustomObjectRepository extends AbstractResourceRepository<\"key-value-document\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"key-value-document\", config);\n\t\tthis.draftSchema = CustomObjectDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: Writable<CustomObjectDraft>,\n\t): Promise<CustomObject> {\n\t\tconst current = (await this.getWithContainerAndKey(\n\t\t\tcontext,\n\t\t\tdraft.container,\n\t\t\tdraft.key,\n\t\t)) as Writable<CustomObject | undefined>;\n\n\t\tif (current) {\n\t\t\t// Only check version if it is passed in the draft\n\t\t\tif (draft.version) {\n\t\t\t\tcheckConcurrentModification(current.version, draft.version, current.id);\n\t\t\t} else {\n\t\t\t\tdraft.version = current.version;\n\t\t\t}\n\n\t\t\tif (draft.value !== current.value) {\n\t\t\t\t// current is already a clone from storage retrieval, safe to mutate\n\t\t\t\tcurrent.value = draft.value;\n\t\t\t\tcurrent.version += 1;\n\t\t\t\tawait this.saveUpdate(context, draft.version, current);\n\t\t\t\treturn current;\n\t\t\t}\n\t\t\treturn current;\n\t\t}\n\t\t// If the resource is new the only valid version is 0\n\t\tif (draft.version) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: \"version on create must be 0\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tconst baseProperties = getBaseResourceProperties(context.clientId);\n\t\tconst resource: CustomObject = {\n\t\t\t...baseProperties,\n\t\t\tcontainer: draft.container,\n\t\t\tkey: draft.key,\n\t\t\tvalue: draft.value,\n\t\t};\n\n\t\tawait this.saveNew(context, resource);\n\t\treturn resource;\n\t}\n\n\tasync getWithContainerAndKey(\n\t\tcontext: RepositoryContext,\n\t\tcontainer: string,\n\t\tkey: string,\n\t) {\n\t\treturn this._storage.getByContainerAndKey(\n\t\t\tcontext.projectKey,\n\t\t\tcontainer,\n\t\t\tkey,\n\t\t);\n\t}\n\n\tasync queryWithContainer(\n\t\tcontext: RepositoryContext,\n\t\tcontainer: string,\n\t\tparams: QueryParams = {},\n\t) {\n\t\tconst whereClause = params.where || [];\n\t\twhereClause.push(`container=\"${container}\"`);\n\t\tconst result = await this._storage.query(\n\t\t\tcontext.projectKey,\n\t\t\tthis.getTypeId(),\n\t\t\t{\n\t\t\t\t...params,\n\t\t\t\twhere: whereClause,\n\t\t\t},\n\t\t);\n\n\t\t// @ts-expect-error\n\t\tresult.results = await Promise.all(\n\t\t\tresult.results.map((r) =>\n\t\t\t\tthis.postProcessResource(context, r as CustomObject, {\n\t\t\t\t\texpand: params.expand,\n\t\t\t\t}),\n\t\t\t),\n\t\t);\n\t\treturn result;\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tAuthenticationModeSchema,\n\tBaseAddressSchema,\n\tCartResourceIdentifierSchema,\n\tCustomerGroupAssignmentDraftSchema,\n\tCustomerGroupResourceIdentifierSchema,\n\tCustomFieldsDraftSchema,\n\tLocaleSchema,\n\tStoreResourceIdentifierSchema,\n} from \"./common.ts\";\n\nexport const CustomerDraftSchema = z.object({\n\tkey: z.string().nullish(),\n\tcustomerNumber: z.string().nullish(),\n\texternalId: z.string().nullish(),\n\temail: z.string(),\n\tpassword: z.string().nullish(),\n\tfirstName: z.string().nullish(),\n\tlastName: z.string().nullish(),\n\tmiddleName: z.string().nullish(),\n\ttitle: z.string().nullish(),\n\tanonymousCartId: z.string().nullish(),\n\tanonymousCart: CartResourceIdentifierSchema.nullish(),\n\tanonymousId: z.string().nullish(),\n\tdateOfBirth: z.string().nullish(),\n\tcompanyName: z.string().nullish(),\n\tvatId: z.string().nullish(),\n\taddresses: z.array(BaseAddressSchema).nullish(),\n\tdefaultShippingAddress: z.number().int().nullish(),\n\tshippingAddresses: z.array(z.number().int()).nullish(),\n\tdefaultBillingAddress: z.number().int().nullish(),\n\tbillingAddresses: z.array(z.number().int()).nullish(),\n\tisEmailVerified: z.boolean().nullish(),\n\tcustomerGroup: CustomerGroupResourceIdentifierSchema.nullish(),\n\tcustomerGroupAssignments: z\n\t\t.array(CustomerGroupAssignmentDraftSchema)\n\t\t.nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\tlocale: LocaleSchema.nullish(),\n\tsalutation: z.string().nullish(),\n\tstores: z.array(StoreResourceIdentifierSchema).nullish(),\n\tauthenticationMode: AuthenticationModeSchema.nullish(),\n});\n","import assert from \"node:assert\";\nimport type {\n\tAddress,\n\tBaseAddress,\n\tCustomer,\n\tCustomerAddAddressAction,\n\tCustomerAddBillingAddressIdAction,\n\tCustomerAddShippingAddressIdAction,\n\tCustomerAddStoreAction,\n\tCustomerChangeAddressAction,\n\tCustomerChangeEmailAction,\n\tCustomerRemoveAddressAction,\n\tCustomerRemoveBillingAddressIdAction,\n\tCustomerRemoveShippingAddressIdAction,\n\tCustomerRemoveStoreAction,\n\tCustomerSetAddressCustomFieldAction,\n\tCustomerSetAddressCustomTypeAction,\n\tCustomerSetAuthenticationModeAction,\n\tCustomerSetCompanyNameAction,\n\tCustomerSetCustomerGroupAction,\n\tCustomerSetCustomerNumberAction,\n\tCustomerSetCustomFieldAction,\n\tCustomerSetCustomTypeAction,\n\tCustomerSetDateOfBirthAction,\n\tCustomerSetDefaultBillingAddressAction,\n\tCustomerSetDefaultShippingAddressAction,\n\tCustomerSetExternalIdAction,\n\tCustomerSetFirstNameAction,\n\tCustomerSetKeyAction,\n\tCustomerSetLastNameAction,\n\tCustomerSetLocaleAction,\n\tCustomerSetMiddleNameAction,\n\tCustomerSetSalutationAction,\n\tCustomerSetStoresAction,\n\tCustomerSetTitleAction,\n\tCustomerSetVatIdAction,\n\tCustomerUpdateAction,\n\tInvalidInputError,\n\tInvalidJsonInputError,\n\tInvalidOperationError,\n} from \"@commercetools/platform-sdk\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { generateRandomString } from \"#src/helpers.ts\";\nimport { hashPassword } from \"#src/lib/password.ts\";\nimport type { Writable } from \"#src/types.ts\";\nimport type { UpdateHandlerInterface } from \"../abstract.ts\";\nimport { AbstractUpdateHandler, type RepositoryContext } from \"../abstract.ts\";\nimport { createAddress } from \"../helpers.ts\";\n\nexport class CustomerUpdateHandler\n\textends AbstractUpdateHandler\n\timplements Partial<UpdateHandlerInterface<Customer, CustomerUpdateAction>>\n{\n\taddAddress(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\t{ address }: CustomerAddAddressAction,\n\t) {\n\t\tresource.addresses.push({\n\t\t\t...address,\n\t\t\tid: address.id ?? generateRandomString(5),\n\t\t} as BaseAddress);\n\t}\n\n\taddBillingAddressId(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\t{ addressId, addressKey }: CustomerAddBillingAddressIdAction,\n\t) {\n\t\tconst address = this._findAddress(resource, addressId, addressKey, true);\n\t\tassert(address?.id); // always true since we set required to true\n\n\t\tif (resource.billingAddressIds === undefined) {\n\t\t\tresource.billingAddressIds = [];\n\t\t}\n\n\t\tif (!resource.billingAddressIds.includes(address.id)) {\n\t\t\tresource.billingAddressIds.push(address.id);\n\t\t}\n\t}\n\n\taddShippingAddressId(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\t{ addressId, addressKey }: CustomerAddShippingAddressIdAction,\n\t) {\n\t\tconst address = this._findAddress(resource, addressId, addressKey, true);\n\t\tassert(address?.id); // always true since we set required to true\n\n\t\tif (resource.shippingAddressIds === undefined) {\n\t\t\tresource.shippingAddressIds = [];\n\t\t}\n\n\t\tif (!resource.shippingAddressIds.includes(address.id)) {\n\t\t\tresource.shippingAddressIds.push(address.id);\n\t\t}\n\t}\n\n\taddStore(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\taction: CustomerAddStoreAction,\n\t) {\n\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t{\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"The action 'addStore' is not implemented yet\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\tchangeAddress(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\t{ addressId, addressKey, address }: CustomerChangeAddressAction,\n\t) {\n\t\tconst current = this._findAddress(resource, addressId, addressKey, true);\n\t\tassert(current?.id); // always true since we set required to true\n\n\t\tconst oldAddressIndex = resource.addresses.findIndex(\n\t\t\t(a) => a.id === current.id,\n\t\t);\n\n\t\tconst newAddress = createAddress(\n\t\t\t{ ...address, id: current.id },\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage,\n\t\t);\n\n\t\tif (newAddress) {\n\t\t\tresource.addresses[oldAddressIndex] = newAddress;\n\t\t}\n\t}\n\n\tchangeEmail(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\t{ email }: CustomerChangeEmailAction,\n\t) {\n\t\tresource.email = email;\n\t}\n\n\tremoveAddress(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\taction: CustomerRemoveAddressAction,\n\t) {\n\t\tconst address = this._findAddress(\n\t\t\tresource,\n\t\t\taction.addressId,\n\t\t\taction.addressKey,\n\t\t\ttrue,\n\t\t);\n\t\tassert(address?.id); // always true since we set required to true\n\t\tresource.addresses = resource.addresses.filter((a) => a.id !== address.id);\n\n\t\tif (resource.shippingAddressIds) {\n\t\t\tresource.shippingAddressIds = resource.shippingAddressIds.filter(\n\t\t\t\t(id) => id !== address.id,\n\t\t\t);\n\t\t}\n\t\tif (resource.billingAddressIds) {\n\t\t\tresource.billingAddressIds = resource.billingAddressIds.filter(\n\t\t\t\t(id) => id !== address.id,\n\t\t\t);\n\t\t}\n\n\t\tif (resource.defaultShippingAddressId === address.id) {\n\t\t\tresource.defaultShippingAddressId = undefined;\n\t\t}\n\t\tif (resource.defaultBillingAddressId === address.id) {\n\t\t\tresource.defaultBillingAddressId = undefined;\n\t\t}\n\t}\n\n\tremoveBillingAddressId(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\taction: CustomerRemoveBillingAddressIdAction,\n\t) {\n\t\tconst address = this._findAddress(\n\t\t\tresource,\n\t\t\taction.addressId,\n\t\t\taction.addressKey,\n\t\t\ttrue,\n\t\t);\n\t\tassert(address?.id); // always true since we set required to true\n\t\tresource.billingAddressIds = resource.billingAddressIds?.filter(\n\t\t\t(id) => id !== address.id,\n\t\t);\n\t\tif (resource.defaultBillingAddressId === address.id) {\n\t\t\tresource.defaultBillingAddressId = undefined;\n\t\t}\n\t}\n\n\tremoveShippingAddressId(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\taction: CustomerRemoveShippingAddressIdAction,\n\t) {\n\t\tconst address = this._findAddress(\n\t\t\tresource,\n\t\t\taction.addressId,\n\t\t\taction.addressKey,\n\t\t\ttrue,\n\t\t);\n\t\tassert(address?.id); // always true since we set required to true\n\t\tresource.shippingAddressIds = resource.shippingAddressIds?.filter(\n\t\t\t(id) => id !== address.id,\n\t\t);\n\t\tif (resource.defaultShippingAddressId === address.id) {\n\t\t\tresource.defaultShippingAddressId = undefined;\n\t\t}\n\t}\n\n\tremoveStore(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\taction: CustomerRemoveStoreAction,\n\t) {\n\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t{\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"The action 'removeStore' is not implemented yet\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\tsetAddressCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\taction: CustomerSetAddressCustomFieldAction,\n\t) {\n\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t{\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"The action 'setAddressCustomField' is not implemented yet\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\tsetAddressCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\taction: CustomerSetAddressCustomTypeAction,\n\t) {\n\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t{\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"The action 'setAddressCustomType' is not implemented yet\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\tsetAuthenticationMode(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\t{ authMode, password }: CustomerSetAuthenticationModeAction,\n\t) {\n\t\tif (resource.authenticationMode === authMode) {\n\t\t\tthrow new CommercetoolsError<InvalidInputError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidInput\",\n\t\t\t\t\tmessage: `The customer is already using the '${resource.authenticationMode}' authentication mode.`,\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tresource.authenticationMode = authMode;\n\t\tif (authMode === \"ExternalAuth\") {\n\t\t\tresource.password = undefined;\n\t\t\treturn;\n\t\t}\n\t\tif (authMode === \"Password\") {\n\t\t\tresource.password = password ? hashPassword(password) : undefined;\n\t\t\treturn;\n\t\t}\n\t\tthrow new CommercetoolsError<InvalidJsonInputError>(\n\t\t\t{\n\t\t\t\tcode: \"InvalidJsonInput\",\n\t\t\t\tmessage: \"Request body does not contain valid JSON.\",\n\t\t\t\tdetailedErrorMessage: `actions -> authMode: Invalid enum value: '${authMode}'. Expected one of: 'Password','ExternalAuth'`,\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\tsetCompanyName(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\t{ companyName }: CustomerSetCompanyNameAction,\n\t) {\n\t\tresource.companyName = companyName;\n\t}\n\n\tasync setCustomerGroup(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\taction: CustomerSetCustomerGroupAction,\n\t) {\n\t\tif (!action.customerGroup) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: \"CustomerGroup is required.\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\tconst group = await this._storage.getByResourceIdentifier<\"customer-group\">(\n\t\t\tcontext.projectKey,\n\t\t\taction.customerGroup,\n\t\t);\n\n\t\tresource.customerGroup = {\n\t\t\ttypeId: \"customer-group\",\n\t\t\tid: group.id,\n\t\t};\n\t}\n\n\tsetCustomerNumber(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\t{ customerNumber }: CustomerSetCustomerNumberAction,\n\t) {\n\t\tif (resource.customerNumber) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: \"A Customer number already exists and cannot be set again.\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tresource.customerNumber = customerNumber;\n\t}\n\n\tsetCustomField(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\t{ name, value }: CustomerSetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\t{ type, fields }: CustomerSetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n\n\tsetDateOfBirth(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\taction: CustomerSetDateOfBirthAction,\n\t) {\n\t\tresource.dateOfBirth = action.dateOfBirth;\n\t}\n\n\tsetDefaultBillingAddress(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\taction: CustomerSetDefaultBillingAddressAction,\n\t) {\n\t\tconst address = this._findAddress(\n\t\t\tresource,\n\t\t\taction.addressId,\n\t\t\taction.addressKey,\n\t\t\ttrue,\n\t\t);\n\t\tassert(address?.id); // always true since we set required to true\n\n\t\tresource.defaultBillingAddressId = address.id;\n\t\tif (resource.billingAddressIds === undefined) {\n\t\t\tresource.billingAddressIds = [];\n\t\t}\n\t\tif (!resource.billingAddressIds.includes(address.id)) {\n\t\t\tresource.billingAddressIds.push(address.id);\n\t\t}\n\t}\n\n\tsetDefaultShippingAddress(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\taction: CustomerSetDefaultShippingAddressAction,\n\t) {\n\t\tconst address = this._findAddress(\n\t\t\tresource,\n\t\t\taction.addressId,\n\t\t\taction.addressKey,\n\t\t\ttrue,\n\t\t);\n\t\tassert(address?.id); // always true since we set required to true\n\n\t\tresource.defaultShippingAddressId = address.id;\n\t\tif (resource.shippingAddressIds === undefined) {\n\t\t\tresource.shippingAddressIds = [];\n\t\t}\n\t\tif (!resource.shippingAddressIds.includes(address.id)) {\n\t\t\tresource.shippingAddressIds.push(address.id);\n\t\t}\n\t}\n\n\tsetExternalId(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\t{ externalId }: CustomerSetExternalIdAction,\n\t) {\n\t\tresource.externalId = externalId;\n\t}\n\n\tsetFirstName(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\t{ firstName }: CustomerSetFirstNameAction,\n\t) {\n\t\tresource.firstName = firstName;\n\t}\n\n\tsetKey(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\t{ key }: CustomerSetKeyAction,\n\t) {\n\t\tresource.key = key;\n\t}\n\n\tsetLastName(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\t{ lastName }: CustomerSetLastNameAction,\n\t) {\n\t\tresource.lastName = lastName;\n\t}\n\n\tsetLocale(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\t{ locale }: CustomerSetLocaleAction,\n\t) {\n\t\tresource.locale = locale;\n\t}\n\n\tsetMiddleName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\taction: CustomerSetMiddleNameAction,\n\t) {\n\t\tresource.middleName = action.middleName;\n\t}\n\n\tsetSalutation(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\t{ salutation }: CustomerSetSalutationAction,\n\t) {\n\t\tresource.salutation = salutation;\n\t}\n\n\tsetStores(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\taction: CustomerSetStoresAction,\n\t) {\n\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t{\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"The action 'setStores' is not implemented yet\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\tsetTitle(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\taction: CustomerSetTitleAction,\n\t) {\n\t\tresource.title = action.title;\n\t}\n\n\tsetVatId(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Customer>,\n\t\t{ vatId }: CustomerSetVatIdAction,\n\t) {\n\t\tresource.vatId = vatId;\n\t}\n\n\tprivate _findAddress(\n\t\tresource: Writable<Customer>,\n\t\taddressId: string | undefined,\n\t\taddressKey: string | undefined,\n\t\trequired = false,\n\t): Address | undefined {\n\t\tif (addressKey) {\n\t\t\tconst address = resource.addresses.find((a) => a.key === addressKey);\n\t\t\tif (!address) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: `Customer does not contain an address with the key ${addressKey}.`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn address;\n\t\t}\n\n\t\tif (addressId) {\n\t\t\tconst address = resource.addresses.find((a) => a.id === addressId);\n\t\t\tif (!address) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: `Customer does not contain an address with the id ${addressId}.`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn address;\n\t\t}\n\n\t\tif (required) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: \"One of address 'addressId' or 'addressKey' is required.\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t}\n}\n","import type {\n\tAddress,\n\tCustomer,\n\tCustomerCreatePasswordResetToken,\n\tCustomerDraft,\n\tCustomerResetPassword,\n\tCustomerToken,\n\tDuplicateFieldError,\n\tInvalidInputError,\n\tMyCustomerResetPassword,\n\tRequiredFieldError,\n\tResourceNotFoundError,\n\tStore,\n\tStoreKeyReference,\n\tStoreResourceIdentifier,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport {\n\tgenerateRandomString,\n\tgetBaseResourceProperties,\n} from \"#src/helpers.ts\";\nimport {\n\tcreateEmailVerifyToken,\n\tcreatePasswordResetToken,\n\thashPassword,\n\tvalidateEmailVerifyToken,\n\tvalidatePasswordResetToken,\n} from \"#src/lib/password.ts\";\nimport { CustomerDraftSchema } from \"#src/schemas/generated/customer.ts\";\nimport type { ResourceMap, ShallowWritable, Writable } from \"#src/types.ts\";\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from \"../abstract.ts\";\nimport { createCustomFields } from \"../helpers.ts\";\nimport { CustomerUpdateHandler } from \"./actions.ts\";\n\nexport class CustomerRepository extends AbstractResourceRepository<\"customer\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"customer\", config);\n\t\tthis.actions = new CustomerUpdateHandler(config.storage);\n\t\tthis.draftSchema = CustomerDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: CustomerDraft,\n\t): Promise<Customer> {\n\t\t// Check uniqueness\n\t\tconst results = await this._storage.query(\n\t\t\tcontext.projectKey,\n\t\t\tthis.getTypeId(),\n\t\t\t{\n\t\t\t\twhere: [`lowercaseEmail=\"${draft.email.toLowerCase()}\"`],\n\t\t\t},\n\t\t);\n\t\tif (results.count > 0) {\n\t\t\tthrow new CommercetoolsError<any>({\n\t\t\t\tcode: \"CustomerAlreadyExists\",\n\t\t\t\tstatusCode: 400,\n\t\t\t\tmessage:\n\t\t\t\t\t\"There is already an existing customer with the provided email.\",\n\t\t\t\terrors: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"DuplicateField\",\n\t\t\t\t\t\tmessage: `Customer with email '${draft.email}' already exists.`,\n\t\t\t\t\t\tduplicateValue: draft.email,\n\t\t\t\t\t\tfield: \"email\",\n\t\t\t\t\t} as DuplicateFieldError,\n\t\t\t\t],\n\t\t\t});\n\t\t}\n\n\t\tconst addresses: Address[] =\n\t\t\tdraft.addresses?.map((address) => ({\n\t\t\t\t...address,\n\t\t\t\tid: generateRandomString(5),\n\t\t\t})) ?? [];\n\n\t\tconst lookupAdressId = (\n\t\t\taddresses: Address[],\n\t\t\taddressId: number,\n\t\t): string => {\n\t\t\tif (addressId < addresses.length) {\n\t\t\t\tconst id = addresses[addressId].id;\n\t\t\t\tif (!id) {\n\t\t\t\t\tthrow new CommercetoolsError<RequiredFieldError>(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcode: \"RequiredField\",\n\t\t\t\t\t\t\tmessage: \"Address ID is missing\",\n\t\t\t\t\t\t\tfield: \"addressId\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t400,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn id;\n\t\t\t}\n\t\t\tthrow new CommercetoolsError<InvalidInputError>({\n\t\t\t\tcode: \"InvalidInput\",\n\t\t\t\tmessage: `Address with ID '${addressId}' not found.`,\n\t\t\t\terrors: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidInput\",\n\t\t\t\t\t\tmessage: `Address with ID '${addressId}' not found.`,\n\t\t\t\t\t\tfield: \"addressId\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t});\n\t\t};\n\n\t\tconst defaultBillingAddressId =\n\t\t\tdraft.defaultBillingAddress !== undefined\n\t\t\t\t? lookupAdressId(addresses, draft.defaultBillingAddress)\n\t\t\t\t: undefined;\n\t\tconst defaultShippingAddressId =\n\t\t\tdraft.defaultShippingAddress !== undefined\n\t\t\t\t? lookupAdressId(addresses, draft.defaultShippingAddress)\n\t\t\t\t: undefined;\n\t\tconst shippingAddressIds =\n\t\t\tdraft.shippingAddresses?.map((addressId) =>\n\t\t\t\tlookupAdressId(addresses, addressId),\n\t\t\t) ?? [];\n\t\tconst billingAddressIds =\n\t\t\tdraft.billingAddresses?.map((addressId) =>\n\t\t\t\tlookupAdressId(addresses, addressId),\n\t\t\t) ?? [];\n\n\t\tlet storesForCustomer: StoreKeyReference[] = [];\n\n\t\tif (draft.stores && draft.stores.length > 0) {\n\t\t\tstoresForCustomer = await this.storeReferenceToStoreKeyReference(\n\t\t\t\tdraft.stores,\n\t\t\t\tcontext.projectKey,\n\t\t\t);\n\t\t}\n\n\t\tconst resource: Customer = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tkey: draft.key,\n\t\t\tauthenticationMode: draft.authenticationMode || \"Password\",\n\t\t\tfirstName: draft.firstName,\n\t\t\tlastName: draft.lastName,\n\t\t\tmiddleName: draft.middleName,\n\t\t\ttitle: draft.title,\n\t\t\tdateOfBirth: draft.dateOfBirth,\n\t\t\tcompanyName: draft.companyName,\n\t\t\temail: draft.email.toLowerCase(),\n\t\t\tlowercaseEmail: draft.email.toLowerCase(),\n\t\t\tpassword: draft.password ? hashPassword(draft.password) : undefined,\n\t\t\tisEmailVerified: draft.isEmailVerified || false,\n\t\t\taddresses: addresses,\n\t\t\tcustomerNumber: draft.customerNumber,\n\t\t\texternalId: draft.externalId,\n\t\t\tdefaultBillingAddressId: defaultBillingAddressId,\n\t\t\tdefaultShippingAddressId: defaultShippingAddressId,\n\t\t\tshippingAddressIds: shippingAddressIds,\n\t\t\tbillingAddressIds: billingAddressIds,\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t\tstores: storesForCustomer,\n\t\t\tcustomerGroupAssignments: [],\n\t\t} satisfies unknown as Customer;\n\n\t\treturn await this.saveNew(context, resource);\n\t}\n\n\tasync saveUpdate(\n\t\tcontext: RepositoryContext,\n\t\tversion: number,\n\t\tresource: ShallowWritable<ResourceMap[\"customer\"]>,\n\t): Promise<ShallowWritable<ResourceMap[\"customer\"]>> {\n\t\t// Also update lowercaseEmail attribute\n\t\tconst updatedResource: Customer = {\n\t\t\t...resource,\n\t\t\tlowercaseEmail: resource.email.toLowerCase(),\n\t\t} satisfies unknown as Customer;\n\n\t\treturn await super.saveUpdate(context, version, updatedResource);\n\t}\n\n\tasync passwordResetToken(\n\t\tcontext: RepositoryContext,\n\t\trequest: CustomerCreatePasswordResetToken,\n\t): Promise<CustomerToken> {\n\t\tconst results = await this._storage.query(\n\t\t\tcontext.projectKey,\n\t\t\tthis.getTypeId(),\n\t\t\t{\n\t\t\t\twhere: [`email=\"${request.email.toLocaleLowerCase()}\"`],\n\t\t\t},\n\t\t);\n\t\tif (results.count === 0) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>({\n\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\tmessage: `The Customer with ID '${request.email}' was not found.`,\n\t\t\t});\n\t\t}\n\n\t\tconst ttlMinutes = request.ttlMinutes ?? 34560; // 34560 is CT default\n\n\t\tconst expiresAt = new Date(Date.now() + ttlMinutes * 60 * 1000);\n\t\tconst customer = results.results[0] as Customer;\n\t\tconst rest = getBaseResourceProperties(context.clientId);\n\n\t\tconst token = createPasswordResetToken(customer, expiresAt);\n\n\t\treturn {\n\t\t\tid: rest.id,\n\t\t\tcreatedAt: rest.createdAt,\n\t\t\tlastModifiedAt: rest.lastModifiedAt,\n\t\t\tcustomerId: customer.id,\n\t\t\texpiresAt: expiresAt.toISOString(),\n\t\t\tvalue: token,\n\t\t\tinvalidateOlderTokens: request.invalidateOlderTokens || false,\n\t\t};\n\t}\n\n\tasync passwordReset(\n\t\tcontext: RepositoryContext,\n\t\tresetPassword: CustomerResetPassword | MyCustomerResetPassword,\n\t) {\n\t\tconst { newPassword, tokenValue } = resetPassword;\n\n\t\tconst customerId = validatePasswordResetToken(tokenValue);\n\t\tif (!customerId) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>({\n\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\tmessage: `The Customer with ID 'Token(${tokenValue})' was not found.`,\n\t\t\t});\n\t\t}\n\n\t\tconst customer = (await this._storage.get(\n\t\t\tcontext.projectKey,\n\t\t\t\"customer\",\n\t\t\tcustomerId,\n\t\t)) as Writable<Customer> | undefined;\n\n\t\tif (!customer) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>({\n\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\tmessage: `The Customer with ID 'Token(${tokenValue})' was not found.`,\n\t\t\t});\n\t\t}\n\n\t\tcustomer.password = hashPassword(newPassword);\n\t\tcustomer.version += 1;\n\n\t\t// Update storage\n\t\tawait this._storage.add(context.projectKey, \"customer\", customer);\n\t\treturn customer;\n\t}\n\n\tasync emailToken(\n\t\tcontext: RepositoryContext,\n\t\tid: string,\n\t): Promise<CustomerToken> {\n\t\tconst results = await this._storage.query(\n\t\t\tcontext.projectKey,\n\t\t\tthis.getTypeId(),\n\t\t\t{\n\t\t\t\twhere: [`id=\"${id.toLocaleLowerCase()}\"`],\n\t\t\t},\n\t\t);\n\t\tif (results.count === 0) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>({\n\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\tmessage: `The Customer with ID '${id}' was not found.`,\n\t\t\t});\n\t\t}\n\t\tconst expiresAt = new Date(Date.now() + 30 * 60);\n\t\tconst customer = results.results[0] as Customer;\n\t\tconst rest = getBaseResourceProperties(context.clientId);\n\n\t\tconst token = createEmailVerifyToken(customer);\n\t\treturn {\n\t\t\tid: rest.id,\n\t\t\tcreatedAt: rest.createdAt,\n\t\t\tlastModifiedAt: rest.lastModifiedAt,\n\t\t\tcustomerId: customer.id,\n\t\t\texpiresAt: expiresAt.toISOString(),\n\t\t\tvalue: token,\n\t\t\tinvalidateOlderTokens: false,\n\t\t};\n\t}\n\n\tasync emailTokenConfirm(\n\t\tcontext: RepositoryContext,\n\t\trequest: { tokenValue: string },\n\t) {\n\t\tconst customerId = validateEmailVerifyToken(request.tokenValue);\n\t\tif (!customerId) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>({\n\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\tmessage: `The Customer with ID 'Token(${request.tokenValue})' was not found.`,\n\t\t\t});\n\t\t}\n\n\t\tconst customer = (await this._storage.get(\n\t\t\tcontext.projectKey,\n\t\t\t\"customer\",\n\t\t\tcustomerId,\n\t\t)) as Writable<Customer> | undefined;\n\n\t\tif (!customer) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>({\n\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\tmessage: `The Customer with ID 'Token(${request.tokenValue})' was not found.`,\n\t\t\t});\n\t\t}\n\n\t\tcustomer.isEmailVerified = true;\n\t\tcustomer.version += 1;\n\n\t\t// Update storage\n\t\tawait this._storage.add(context.projectKey, \"customer\", customer);\n\t\treturn customer;\n\t}\n\n\tprivate async storeReferenceToStoreKeyReference(\n\t\tdraftStores: StoreResourceIdentifier[],\n\t\tprojectKey: string,\n\t): Promise<StoreKeyReference[]> {\n\t\tconst storeIds = draftStores\n\t\t\t.map((storeReference) => storeReference.id)\n\t\t\t.filter(Boolean);\n\n\t\tlet stores: Store[] = [];\n\n\t\tif (storeIds.length > 0) {\n\t\t\tconst storeResult = await this._storage.query(projectKey, \"store\", {\n\t\t\t\twhere: storeIds.map((id) => `id=\"${id}\"`),\n\t\t\t});\n\t\t\tstores = storeResult.results;\n\n\t\t\tif (storeIds.length !== stores.length) {\n\t\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>({\n\t\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\t\tmessage: `Store with ID '${storeIds.find((id) => !stores.some((store) => store.id === id))}' was not found.`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn draftStores.map((storeReference) => ({\n\t\t\ttypeId: \"store\",\n\t\t\tkey:\n\t\t\t\tstoreReference.key ??\n\t\t\t\t(stores.find((store) => store.id === storeReference.id)?.key as string),\n\t\t}));\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport { CustomFieldsDraftSchema } from \"./common.ts\";\n\nexport const CustomerGroupDraftSchema = z.object({\n\tkey: z.string().nullish(),\n\tgroupName: z.string(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n});\n","import type {\n\tCustomerGroup,\n\tCustomerGroupChangeNameAction,\n\tCustomerGroupDraft,\n\tCustomerGroupSetCustomFieldAction,\n\tCustomerGroupSetCustomTypeAction,\n\tCustomerGroupSetKeyAction,\n\tCustomerGroupUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { CustomerGroupDraftSchema } from \"#src/schemas/generated/customer-group.ts\";\nimport { getBaseResourceProperties } from \"../helpers.ts\";\nimport type { Writable } from \"../types.ts\";\nimport type { UpdateHandlerInterface } from \"./abstract.ts\";\nimport {\n\tAbstractResourceRepository,\n\tAbstractUpdateHandler,\n\ttype RepositoryContext,\n} from \"./abstract.ts\";\nimport { createCustomFields } from \"./helpers.ts\";\n\nexport class CustomerGroupRepository extends AbstractResourceRepository<\"customer-group\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"customer-group\", config);\n\t\tthis.actions = new CustomerGroupUpdateHandler(config.storage);\n\t\tthis.draftSchema = CustomerGroupDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: CustomerGroupDraft,\n\t): Promise<CustomerGroup> {\n\t\tconst resource: CustomerGroup = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tkey: draft.key,\n\t\t\tname: draft.groupName,\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n\nclass CustomerGroupUpdateHandler\n\textends AbstractUpdateHandler\n\timplements UpdateHandlerInterface<CustomerGroup, CustomerGroupUpdateAction>\n{\n\tchangeName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<CustomerGroup>,\n\t\t{ name }: CustomerGroupChangeNameAction,\n\t) {\n\t\tresource.name = name;\n\t}\n\n\tsetCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<CustomerGroup>,\n\t\t{ name, value }: CustomerGroupSetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<CustomerGroup>,\n\t\t{ type, fields }: CustomerGroupSetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n\n\tsetKey(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<CustomerGroup>,\n\t\t{ key }: CustomerGroupSetKeyAction,\n\t) {\n\t\tresource.key = key;\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tCartDiscountResourceIdentifierSchema,\n\tCustomFieldsDraftSchema,\n\tLocalizedStringSchema,\n} from \"./common.ts\";\n\nexport const DiscountCodeDraftSchema = z.object({\n\tkey: z.string().nullish(),\n\tname: LocalizedStringSchema.nullish(),\n\tdescription: LocalizedStringSchema.nullish(),\n\tcode: z.string(),\n\tcartDiscounts: z.array(CartDiscountResourceIdentifierSchema),\n\tcartPredicate: z.string().nullish(),\n\tisActive: z.boolean().nullish(),\n\tmaxApplications: z.number().int().nullish(),\n\tmaxApplicationsPerCustomer: z.number().int().nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\tgroups: z.array(z.string()).nullish(),\n\tvalidFrom: z.string().nullish(),\n\tvalidUntil: z.string().nullish(),\n});\n","import type {\n\tCartDiscountReference,\n\tDiscountCode,\n\tDiscountCodeChangeCartDiscountsAction,\n\tDiscountCodeChangeIsActiveAction,\n\tDiscountCodeSetCartPredicateAction,\n\tDiscountCodeSetCustomFieldAction,\n\tDiscountCodeSetCustomTypeAction,\n\tDiscountCodeSetDescriptionAction,\n\tDiscountCodeSetMaxApplicationsAction,\n\tDiscountCodeSetMaxApplicationsPerCustomerAction,\n\tDiscountCodeSetNameAction,\n\tDiscountCodeSetValidFromAction,\n\tDiscountCodeSetValidFromAndUntilAction,\n\tDiscountCodeSetValidUntilAction,\n\tDiscountCodeUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type { Writable } from \"#src/types.ts\";\nimport type { UpdateHandlerInterface } from \"../abstract.ts\";\nimport { AbstractUpdateHandler, type RepositoryContext } from \"../abstract.ts\";\n\nexport class DiscountCodeUpdateHandler\n\textends AbstractUpdateHandler\n\timplements\n\t\tPartial<UpdateHandlerInterface<DiscountCode, DiscountCodeUpdateAction>>\n{\n\tchangeCartDiscounts(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<DiscountCode>,\n\t\t{ cartDiscounts }: DiscountCodeChangeCartDiscountsAction,\n\t) {\n\t\tresource.cartDiscounts = cartDiscounts.map(\n\t\t\t(obj): CartDiscountReference => ({\n\t\t\t\ttypeId: \"cart-discount\",\n\t\t\t\tid: obj.id!,\n\t\t\t}),\n\t\t);\n\t}\n\n\tchangeIsActive(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<DiscountCode>,\n\t\t{ isActive }: DiscountCodeChangeIsActiveAction,\n\t) {\n\t\tresource.isActive = isActive;\n\t}\n\n\tsetCartPredicate(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<DiscountCode>,\n\t\t{ cartPredicate }: DiscountCodeSetCartPredicateAction,\n\t) {\n\t\tresource.cartPredicate = cartPredicate;\n\t}\n\n\tsetCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<DiscountCode>,\n\t\t{ name, value }: DiscountCodeSetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<DiscountCode>,\n\t\t{ type, fields }: DiscountCodeSetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n\n\tsetDescription(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<DiscountCode>,\n\t\t{ description }: DiscountCodeSetDescriptionAction,\n\t) {\n\t\tresource.description = description;\n\t}\n\n\tsetMaxApplications(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<DiscountCode>,\n\t\t{ maxApplications }: DiscountCodeSetMaxApplicationsAction,\n\t) {\n\t\tresource.maxApplications = maxApplications;\n\t}\n\n\tsetMaxApplicationsPerCustomer(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<DiscountCode>,\n\t\t{\n\t\t\tmaxApplicationsPerCustomer,\n\t\t}: DiscountCodeSetMaxApplicationsPerCustomerAction,\n\t) {\n\t\tresource.maxApplicationsPerCustomer = maxApplicationsPerCustomer;\n\t}\n\n\tsetName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<DiscountCode>,\n\t\t{ name }: DiscountCodeSetNameAction,\n\t) {\n\t\tresource.name = name;\n\t}\n\n\tsetValidFrom(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<DiscountCode>,\n\t\t{ validFrom }: DiscountCodeSetValidFromAction,\n\t) {\n\t\tresource.validFrom = validFrom;\n\t}\n\n\tsetValidFromAndUntil(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<DiscountCode>,\n\t\t{ validFrom, validUntil }: DiscountCodeSetValidFromAndUntilAction,\n\t) {\n\t\tresource.validFrom = validFrom;\n\t\tresource.validUntil = validUntil;\n\t}\n\n\tsetValidUntil(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<DiscountCode>,\n\t\t{ validUntil }: DiscountCodeSetValidUntilAction,\n\t) {\n\t\tresource.validUntil = validUntil;\n\t}\n}\n","import type {\n\tCartDiscountReference,\n\tDiscountCode,\n\tDiscountCodeDraft,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { getBaseResourceProperties } from \"#src/helpers.ts\";\nimport { DiscountCodeDraftSchema } from \"#src/schemas/generated/discount-code.ts\";\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from \"../abstract.ts\";\nimport { createCustomFields } from \"../helpers.ts\";\nimport { DiscountCodeUpdateHandler } from \"./actions.ts\";\n\nexport class DiscountCodeRepository extends AbstractResourceRepository<\"discount-code\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"discount-code\", config);\n\t\tthis.actions = new DiscountCodeUpdateHandler(config.storage);\n\t\tthis.draftSchema = DiscountCodeDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: DiscountCodeDraft,\n\t): Promise<DiscountCode> {\n\t\tconst resource: DiscountCode = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tapplicationVersion: 1,\n\t\t\tcartDiscounts: draft.cartDiscounts.map(\n\t\t\t\t(obj): CartDiscountReference => ({\n\t\t\t\t\ttypeId: \"cart-discount\",\n\t\t\t\t\tid: obj.id!,\n\t\t\t\t}),\n\t\t\t),\n\t\t\tcartPredicate: draft.cartPredicate,\n\t\t\tcode: draft.code,\n\t\t\tdescription: draft.description,\n\t\t\tgroups: draft.groups || [],\n\t\t\tisActive: draft.isActive || true,\n\t\t\tname: draft.name,\n\t\t\treferences: [],\n\t\t\tstores: [],\n\t\t\tvalidFrom: draft.validFrom,\n\t\t\tvalidUntil: draft.validUntil,\n\t\t\tmaxApplications: draft.maxApplications,\n\t\t\tmaxApplicationsPerCustomer: draft.maxApplicationsPerCustomer,\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport { LocalizedStringSchema } from \"./common.ts\";\n\nexport const DiscountGroupDraftSchema = z.object({\n\tname: LocalizedStringSchema.nullish(),\n\tkey: z.string(),\n\tdescription: LocalizedStringSchema.nullish(),\n\tsortOrder: z.string(),\n\tisActive: z.boolean().nullish(),\n});\n","import type {\n\tDiscountGroup,\n\tDiscountGroupSetDescriptionAction,\n\tDiscountGroupSetKeyAction,\n\tDiscountGroupSetNameAction,\n\tDiscountGroupSetSortOrderAction,\n\tDiscountGroupUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type { Writable } from \"#src/types.ts\";\nimport type { UpdateHandlerInterface } from \"../abstract.ts\";\nimport { AbstractUpdateHandler, type RepositoryContext } from \"../abstract.ts\";\n\nexport class DiscountGroupUpdateHandler\n\textends AbstractUpdateHandler\n\timplements\n\t\tPartial<UpdateHandlerInterface<DiscountGroup, DiscountGroupUpdateAction>>\n{\n\tsetDescription(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<DiscountGroup>,\n\t\t{ description }: DiscountGroupSetDescriptionAction,\n\t) {\n\t\tresource.description = description;\n\t}\n\n\tsetKey(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<DiscountGroup>,\n\t\t{ key }: DiscountGroupSetKeyAction,\n\t) {\n\t\tresource.key = key;\n\t}\n\n\tsetName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<DiscountGroup>,\n\t\t{ name }: DiscountGroupSetNameAction,\n\t) {\n\t\tresource.name = name;\n\t}\n\n\tsetSortOrder(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<DiscountGroup>,\n\t\t{ sortOrder }: DiscountGroupSetSortOrderAction,\n\t) {\n\t\tresource.sortOrder = sortOrder;\n\t}\n}\n","import type {\n\tDiscountGroup,\n\tDiscountGroupDraft,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { getBaseResourceProperties } from \"#src/helpers.ts\";\nimport { DiscountGroupDraftSchema } from \"#src/schemas/generated/discount-group.ts\";\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from \"../abstract.ts\";\nimport { DiscountGroupUpdateHandler } from \"./actions.ts\";\n\nexport class DiscountGroupRepository extends AbstractResourceRepository<\"discount-group\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"discount-group\", config);\n\t\tthis.actions = new DiscountGroupUpdateHandler(config.storage);\n\t\tthis.draftSchema = DiscountGroupDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: DiscountGroupDraft,\n\t): Promise<DiscountGroup> {\n\t\tconst resource: DiscountGroup = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tdescription: draft.description,\n\t\t\tname: draft.name,\n\t\t\tkey: draft.key,\n\t\t\tsortOrder: draft.sortOrder,\n\t\t\tisActive: true,\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tExtensionAdditionalContextDraftSchema,\n\tExtensionDestinationSchema,\n\tExtensionResourceIdentifierSchema,\n\tExtensionTriggerSchema,\n} from \"./common.ts\";\n\nexport const ExtensionDraftSchema = z.object({\n\tkey: z.string().nullish(),\n\tdestination: ExtensionDestinationSchema,\n\ttriggers: z.array(ExtensionTriggerSchema),\n\ttimeoutInMs: z.number().int().nullish(),\n\tdependencies: z.array(ExtensionResourceIdentifierSchema).nullish(),\n\texpansionPaths: z.array(z.string()).nullish(),\n\tadditionalContext: ExtensionAdditionalContextDraftSchema.nullish(),\n});\n","export const maskSecretValue = <T>(resource: T, path: string): T => {\n\tconst parts = path.split(\".\");\n\t// Callers are expected to pass objects that are safe to mutate\n\t// (e.g. clones from storage retrieval).\n\tlet val = resource as any;\n\n\tconst target = parts.pop();\n\tfor (let i = 0; i < parts.length; i++) {\n\t\tconst part = parts[i];\n\t\tval = val[part];\n\n\t\tif (val === undefined) {\n\t\t\treturn resource;\n\t\t}\n\t}\n\n\tif (val && target && val[target]) {\n\t\tval[target] = \"****\";\n\t}\n\treturn resource;\n};\n","import type {\n\tExtension,\n\tExtensionChangeDestinationAction,\n\tExtensionChangeTriggersAction,\n\tExtensionDraft,\n\tExtensionReference,\n\tExtensionSetAdditionalContextAction,\n\tExtensionSetDependenciesAction,\n\tExtensionSetExpansionPathsAction,\n\tExtensionSetKeyAction,\n\tExtensionSetTimeoutInMsAction,\n\tExtensionUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { ExtensionDraftSchema } from \"#src/schemas/generated/extension.ts\";\nimport { getBaseResourceProperties } from \"../helpers.ts\";\nimport { maskSecretValue } from \"../lib/masking.ts\";\nimport type { Writable } from \"../types.ts\";\nimport type { UpdateHandlerInterface } from \"./abstract.ts\";\nimport {\n\tAbstractResourceRepository,\n\tAbstractUpdateHandler,\n\ttype RepositoryContext,\n} from \"./abstract.ts\";\n\nexport class ExtensionRepository extends AbstractResourceRepository<\"extension\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"extension\", config);\n\t\tthis.actions = new ExtensionUpdateHandler(config.storage);\n\t\tthis.draftSchema = ExtensionDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: ExtensionDraft,\n\t): Promise<Extension> {\n\t\tconst resource: Extension = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tkey: draft.key,\n\t\t\ttimeoutInMs: draft.timeoutInMs,\n\t\t\tdestination: draft.destination,\n\t\t\ttriggers: draft.triggers,\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n\n\tasync postProcessResource(\n\t\tcontext: RepositoryContext,\n\t\tresource: Extension,\n\t): Promise<Extension> {\n\t\tif (resource) {\n\t\t\tconst extension = resource as Extension;\n\t\t\tif (\n\t\t\t\textension.destination.type === \"HTTP\" &&\n\t\t\t\textension.destination.authentication?.type === \"AuthorizationHeader\"\n\t\t\t) {\n\t\t\t\treturn maskSecretValue(\n\t\t\t\t\textension,\n\t\t\t\t\t\"destination.authentication.headerValue\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (extension.destination.type === \"AWSLambda\") {\n\t\t\t\treturn maskSecretValue(resource, \"destination.accessSecret\");\n\t\t\t}\n\t\t}\n\t\treturn resource;\n\t}\n}\n\nclass ExtensionUpdateHandler\n\textends AbstractUpdateHandler\n\timplements UpdateHandlerInterface<Extension, ExtensionUpdateAction>\n{\n\tchangeDestination(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Extension>,\n\t\taction: ExtensionChangeDestinationAction,\n\t): void {\n\t\tresource.destination = action.destination;\n\t}\n\n\tchangeTriggers(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Extension>,\n\t\taction: ExtensionChangeTriggersAction,\n\t): void {\n\t\tresource.triggers = action.triggers;\n\t}\n\n\tsetAdditionalContext(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Extension>,\n\t\taction: ExtensionSetAdditionalContextAction,\n\t): void {\n\t\tresource.additionalContext = {\n\t\t\tincludeOldResource: action.additionalContext.includeOldResource ?? false,\n\t\t};\n\t}\n\n\tsetDependencies(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Extension>,\n\t\taction: ExtensionSetDependenciesAction,\n\t): void {\n\t\tresource.dependencies = action.dependencies.map(\n\t\t\t(identifier): ExtensionReference => ({\n\t\t\t\ttypeId: \"extension\",\n\t\t\t\tid: identifier.id!,\n\t\t\t}),\n\t\t);\n\t}\n\n\tsetExpansionPaths(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Extension>,\n\t\taction: ExtensionSetExpansionPathsAction,\n\t): void {\n\t\tresource.expansionPaths = action.expansionPaths;\n\t}\n\n\tsetKey(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Extension>,\n\t\taction: ExtensionSetKeyAction,\n\t): void {\n\t\tresource.key = action.key;\n\t}\n\n\tsetTimeoutInMs(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Extension>,\n\t\taction: ExtensionSetTimeoutInMsAction,\n\t): void {\n\t\tresource.timeoutInMs = action.timeoutInMs;\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tChannelResourceIdentifierSchema,\n\tCustomFieldsDraftSchema,\n\tInventoryEntryStockLevelsSchema,\n} from \"./common.ts\";\n\nexport const InventoryEntryDraftSchema = z.object({\n\tsku: z.string(),\n\tkey: z.string().nullish(),\n\tsupplyChannel: ChannelResourceIdentifierSchema.nullish(),\n\tquantityOnStock: z.number().int(),\n\tminCartQuantity: z.number().int().nullish(),\n\tmaxCartQuantity: z.number().int().nullish(),\n\trestockableInDays: z.number().int().nullish(),\n\texpectedDelivery: z.string().nullish(),\n\treservationExpirationInMinutes: z.number().int().nullish(),\n\tstockLevels: InventoryEntryStockLevelsSchema.nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n});\n","import type {\n\tInventoryEntry,\n\tInventoryEntryChangeQuantityAction,\n\tInventoryEntryRemoveQuantityAction,\n\tInventoryEntrySetCustomFieldAction,\n\tInventoryEntrySetCustomTypeAction,\n\tInventoryEntrySetExpectedDeliveryAction,\n\tInventoryEntrySetRestockableInDaysAction,\n\tInventoryEntryUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type { Writable } from \"#src/types.ts\";\nimport type { UpdateHandlerInterface } from \"../abstract.ts\";\nimport { AbstractUpdateHandler, type RepositoryContext } from \"../abstract.ts\";\n\nexport class InventoryEntryUpdateHandler\n\textends AbstractUpdateHandler\n\timplements\n\t\tPartial<UpdateHandlerInterface<InventoryEntry, InventoryEntryUpdateAction>>\n{\n\tchangeQuantity(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<InventoryEntry>,\n\t\t{ quantity }: InventoryEntryChangeQuantityAction,\n\t) {\n\t\tresource.quantityOnStock = quantity;\n\t\t// don't know active reservations so just set to same value\n\t\tresource.availableQuantity = quantity;\n\t}\n\n\tremoveQuantity(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<InventoryEntry>,\n\t\t{ quantity }: InventoryEntryRemoveQuantityAction,\n\t) {\n\t\tconst newQuantity = Math.max(0, resource.quantityOnStock - quantity);\n\t\tresource.quantityOnStock = newQuantity;\n\t\t// don't know active reservations so just set to same value\n\t\tresource.availableQuantity = newQuantity;\n\t}\n\n\tsetCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: InventoryEntry,\n\t\t{ name, value }: InventoryEntrySetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<InventoryEntry>,\n\t\t{ type, fields }: InventoryEntrySetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n\n\tsetExpectedDelivery(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<InventoryEntry>,\n\t\t{ expectedDelivery }: InventoryEntrySetExpectedDeliveryAction,\n\t) {\n\t\tresource.expectedDelivery = new Date(expectedDelivery!).toISOString();\n\t}\n\n\tsetRestockableInDays(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<InventoryEntry>,\n\t\t{ restockableInDays }: InventoryEntrySetRestockableInDaysAction,\n\t) {\n\t\tresource.restockableInDays = restockableInDays;\n\t}\n}\n","import type {\n\tChannelReference,\n\tInventoryEntry,\n\tInventoryEntryDraft,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { getBaseResourceProperties } from \"#src/helpers.ts\";\nimport { InventoryEntryDraftSchema } from \"#src/schemas/generated/inventory-entry.ts\";\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from \"../abstract.ts\";\nimport {\n\tcreateCustomFields,\n\tgetReferenceFromResourceIdentifier,\n} from \"../helpers.ts\";\nimport { InventoryEntryUpdateHandler } from \"./actions.ts\";\n\nexport class InventoryEntryRepository extends AbstractResourceRepository<\"inventory-entry\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"inventory-entry\", config);\n\t\tthis.actions = new InventoryEntryUpdateHandler(config.storage);\n\t\tthis.draftSchema = InventoryEntryDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: InventoryEntryDraft,\n\t): Promise<InventoryEntry> {\n\t\tconst resource: InventoryEntry = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tsku: draft.sku,\n\t\t\tquantityOnStock: draft.quantityOnStock,\n\t\t\tavailableQuantity: draft.quantityOnStock,\n\t\t\texpectedDelivery: draft.expectedDelivery,\n\t\t\trestockableInDays: draft.restockableInDays,\n\t\t\tsupplyChannel: draft.supplyChannel\n\t\t\t\t? await getReferenceFromResourceIdentifier<ChannelReference>(\n\t\t\t\t\t\tdraft.supplyChannel,\n\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\tthis._storage,\n\t\t\t\t\t)\n\t\t\t\t: undefined,\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n","import type {\n\tCustomer,\n\tInvalidCurrentPasswordError,\n\tMyCustomerChangePassword,\n\tMyCustomerEmailVerify,\n\tResourceNotFoundError,\n} from \"@commercetools/platform-sdk\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { hashPassword, validateEmailVerifyToken } from \"../lib/password.ts\";\nimport type { Writable } from \"../types.ts\";\nimport type { RepositoryContext } from \"./abstract.ts\";\nimport { CustomerRepository } from \"./customer/index.ts\";\n\nexport class MyCustomerRepository extends CustomerRepository {\n\tasync changePassword(\n\t\tcontext: RepositoryContext,\n\t\tchangePassword: MyCustomerChangePassword,\n\t) {\n\t\tconst { currentPassword, newPassword } = changePassword;\n\t\tconst encodedPassword = hashPassword(currentPassword);\n\n\t\tconst result = await this._storage.query(context.projectKey, \"customer\", {\n\t\t\twhere: [`password = \"${encodedPassword}\"`],\n\t\t});\n\t\tif (result.count === 0) {\n\t\t\tthrow new CommercetoolsError<InvalidCurrentPasswordError>({\n\t\t\t\tcode: \"InvalidCurrentPassword\",\n\t\t\t\tmessage: \"Account with the given credentials not found.\",\n\t\t\t});\n\t\t}\n\n\t\tconst customer = result.results[0] as Writable<Customer>;\n\t\tif (customer.password !== hashPassword(currentPassword)) {\n\t\t\tthrow new CommercetoolsError<InvalidCurrentPasswordError>({\n\t\t\t\tcode: \"InvalidCurrentPassword\",\n\t\t\t\tmessage: \"The current password is invalid.\",\n\t\t\t});\n\t\t}\n\n\t\tcustomer.password = hashPassword(newPassword);\n\t\tcustomer.version += 1;\n\n\t\t// Update storage\n\t\tawait this._storage.add(context.projectKey, \"customer\", customer);\n\t\treturn customer;\n\t}\n\n\tasync confirmEmail(\n\t\tcontext: RepositoryContext,\n\t\tresetPassword: MyCustomerEmailVerify,\n\t) {\n\t\tconst { tokenValue } = resetPassword;\n\n\t\tconst customerId = validateEmailVerifyToken(tokenValue);\n\t\tif (!customerId) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>({\n\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\tmessage: `The Customer with ID 'Token(${tokenValue})' was not found.`,\n\t\t\t});\n\t\t}\n\n\t\tconst customer = (await this._storage.get(\n\t\t\tcontext.projectKey,\n\t\t\t\"customer\",\n\t\t\tcustomerId,\n\t\t)) as Writable<Customer> | undefined;\n\n\t\tif (!customer) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>({\n\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\tmessage: `The Customer with ID 'Token(${tokenValue})' was not found.`,\n\t\t\t});\n\t\t}\n\n\t\tcustomer.isEmailVerified = true;\n\t\tcustomer.version += 1;\n\n\t\t// Update storage\n\t\tawait this._storage.add(context.projectKey, \"customer\", customer);\n\t\treturn customer;\n\t}\n\n\tasync deleteMe(context: RepositoryContext): Promise<Customer | undefined> {\n\t\t// grab the first customer you can find for now. In the future we should\n\t\t// use the customer id from the scope of the token\n\t\tconst results = await this._storage.query(\n\t\t\tcontext.projectKey,\n\t\t\tthis.getTypeId(),\n\t\t\t{},\n\t\t);\n\n\t\tif (results.count > 0) {\n\t\t\tconst deleted = await this.delete(context, results.results[0].id);\n\t\t\treturn deleted as Customer;\n\t\t}\n\n\t\treturn;\n\t}\n\n\tasync getMe(context: RepositoryContext): Promise<Customer | undefined> {\n\t\t// grab the first customer you can find for now. In the future we should\n\t\t// use the customer id from the scope of the token\n\t\tconst results = await this._storage.query(\n\t\t\tcontext.projectKey,\n\t\t\tthis.getTypeId(),\n\t\t\t{},\n\t\t);\n\n\t\tif (results.count > 0) {\n\t\t\treturn results.results[0] as Customer;\n\t\t}\n\n\t\treturn;\n\t}\n}\n","import assert from \"node:assert\";\nimport type {\n\tCartReference,\n\tMyOrderFromCartDraft,\n\tOrder,\n} from \"@commercetools/platform-sdk\";\nimport type { RepositoryContext } from \"./abstract.ts\";\nimport { OrderRepository } from \"./order/index.ts\";\n\nexport class MyOrderRepository extends OrderRepository {\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: MyOrderFromCartDraft,\n\t): Promise<Order> {\n\t\tassert(draft.id, \"draft.id is missing\");\n\t\tconst cartIdentifier = {\n\t\t\tid: draft.id,\n\t\t\ttypeId: \"cart\",\n\t\t} as CartReference;\n\t\treturn await this.createFromCart(context, cartIdentifier);\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tCustomFieldsDraftSchema,\n\tOrderReferenceSchema,\n\tStagedOrderUpdateActionSchema,\n} from \"./common.ts\";\n\nexport const OrderEditDraftSchema = z.object({\n\tkey: z.string().nullish(),\n\tresource: OrderReferenceSchema,\n\tstagedActions: z.array(StagedOrderUpdateActionSchema).nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\tcomment: z.string().nullish(),\n\tdryRun: z.boolean().nullish(),\n});\n","import type {\n\tOrderEdit,\n\tOrderEditDraft,\n\tOrderEditResult,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { OrderEditDraftSchema } from \"#src/schemas/generated/order-edit.ts\";\nimport { getBaseResourceProperties } from \"../helpers.ts\";\nimport type { RepositoryContext } from \"./abstract.ts\";\nimport { AbstractResourceRepository } from \"./abstract.ts\";\n\nexport class OrderEditRepository extends AbstractResourceRepository<\"order-edit\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"order-edit\", config);\n\t\tthis.draftSchema = OrderEditDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: OrderEditDraft,\n\t): Promise<OrderEdit> {\n\t\tconst resource: OrderEdit = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tstagedActions: draft.stagedActions ?? [],\n\t\t\tresource: draft.resource,\n\t\t\tresult: {\n\t\t\t\ttype: \"NotProcessed\",\n\t\t\t} as OrderEditResult,\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tCustomerResourceIdentifierSchema,\n\tCustomFieldsDraftSchema,\n\tMoneySchema,\n\tPaymentMethodInfoDraftSchema,\n\tPaymentStatusDraftSchema,\n\tTransactionDraftSchema,\n} from \"./common.ts\";\n\nexport const PaymentDraftSchema = z.object({\n\tcustomer: CustomerResourceIdentifierSchema.nullish(),\n\tanonymousId: z.string().nullish(),\n\texternalId: z.string().nullish(),\n\tinterfaceId: z.string().nullish(),\n\tamountPlanned: MoneySchema,\n\tamountAuthorized: MoneySchema.nullish(),\n\tauthorizedUntil: z.string().nullish(),\n\tamountPaid: MoneySchema.nullish(),\n\tamountRefunded: MoneySchema.nullish(),\n\tpaymentMethodInfo: PaymentMethodInfoDraftSchema.nullish(),\n\tpaymentStatus: PaymentStatusDraftSchema.nullish(),\n\ttransactions: z.array(TransactionDraftSchema).nullish(),\n\tinterfaceInteractions: z.array(CustomFieldsDraftSchema).nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\tkey: z.string().nullish(),\n});\n","import type {\n\tTransaction,\n\tTransactionDraft,\n} from \"@commercetools/platform-sdk\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport type { AbstractStorage } from \"#src/storage/index.ts\";\nimport type { RepositoryContext } from \"../abstract.ts\";\nimport { createCentPrecisionMoney, createCustomFields } from \"../helpers.ts\";\n\nexport const transactionFromTransactionDraft = async (\n\tcontext: RepositoryContext,\n\tstorage: AbstractStorage,\n\tdraft: TransactionDraft,\n): Promise<Transaction> => ({\n\t...draft,\n\tid: uuidv4(),\n\tamount: createCentPrecisionMoney(draft.amount),\n\tcustom: await createCustomFields(draft.custom, context.projectKey, storage),\n\tstate: draft.state ?? \"Initial\", // Documented as default\n});\n","import type {\n\tCustomerReference,\n\tInvalidOperationError,\n\tPayment,\n\tPaymentAddInterfaceInteractionAction,\n\tPaymentAddTransactionAction,\n\tPaymentChangeAmountPlannedAction,\n\tPaymentChangeTransactionInteractionIdAction,\n\tPaymentChangeTransactionStateAction,\n\tPaymentChangeTransactionTimestampAction,\n\tPaymentSetAnonymousIdAction,\n\tPaymentSetCustomerAction,\n\tPaymentSetCustomFieldAction,\n\tPaymentSetCustomTypeAction,\n\tPaymentSetInterfaceIdAction,\n\tPaymentSetKeyAction,\n\tPaymentSetMethodInfoAction,\n\tPaymentSetMethodInfoCustomFieldAction,\n\tPaymentSetMethodInfoCustomTypeAction,\n\tPaymentSetMethodInfoInterfaceAccountAction,\n\tPaymentSetMethodInfoInterfaceAction,\n\tPaymentSetMethodInfoMethodAction,\n\tPaymentSetMethodInfoNameAction,\n\tPaymentSetMethodInfoTokenAction,\n\tPaymentSetStatusInterfaceCodeAction,\n\tPaymentSetStatusInterfaceTextAction,\n\tPaymentSetTransactionCustomFieldAction,\n\tPaymentSetTransactionCustomTypeAction,\n\tPaymentSetTransactionInterfaceIdAction,\n\tPaymentTransitionStateAction,\n\tPaymentUpdateAction,\n\tReferencedResourceNotFoundError,\n\tState,\n\tTransaction,\n} from \"@commercetools/platform-sdk\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport type { Writable } from \"#src/types.ts\";\nimport type { RepositoryContext, UpdateHandlerInterface } from \"../abstract.ts\";\nimport { AbstractUpdateHandler } from \"../abstract.ts\";\nimport {\n\tcreateCentPrecisionMoney,\n\tcreateCustomFields,\n\tgetReferenceFromResourceIdentifier,\n} from \"../helpers.ts\";\nimport { transactionFromTransactionDraft } from \"./helpers.ts\";\n\nexport class PaymentUpdateHandler\n\textends AbstractUpdateHandler\n\timplements UpdateHandlerInterface<Payment, PaymentUpdateAction>\n{\n\tasync addInterfaceInteraction(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ type, fields }: PaymentAddInterfaceInteractionAction,\n\t) {\n\t\tconst customFields = await createCustomFields(\n\t\t\t{ type, fields },\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage,\n\t\t);\n\t\tresource.interfaceInteractions.push(customFields!);\n\t}\n\n\tasync addTransaction(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ transaction }: PaymentAddTransactionAction,\n\t) {\n\t\tresource.transactions = [\n\t\t\t...resource.transactions,\n\t\t\tawait transactionFromTransactionDraft(\n\t\t\t\tcontext,\n\t\t\t\tthis._storage,\n\t\t\t\ttransaction,\n\t\t\t),\n\t\t];\n\t}\n\n\tchangeAmountPlanned(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ amount }: PaymentChangeAmountPlannedAction,\n\t) {\n\t\tresource.amountPlanned = createCentPrecisionMoney(amount);\n\t}\n\n\tchangeTransactionInteractionId(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{\n\t\t\ttransactionId,\n\t\t\tinteractionId,\n\t\t}: PaymentChangeTransactionInteractionIdAction,\n\t) {\n\t\tconst transaction = resource.transactions.find(\n\t\t\t(e: Transaction) => e.id === transactionId,\n\t\t);\n\t\tif (transaction) {\n\t\t\ttransaction.interactionId = interactionId;\n\t\t}\n\t}\n\n\tsetTransactionInterfaceId(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ transactionId, interfaceId }: PaymentSetTransactionInterfaceIdAction,\n\t) {\n\t\tconst transaction = resource.transactions.find(\n\t\t\t(e: Transaction) => e.id === transactionId,\n\t\t);\n\t\tif (transaction) {\n\t\t\ttransaction.interfaceId = interfaceId;\n\t\t}\n\t}\n\n\tchangeTransactionState(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ transactionId, state }: PaymentChangeTransactionStateAction,\n\t) {\n\t\tconst index = resource.transactions.findIndex(\n\t\t\t(e: Transaction) => e.id === transactionId,\n\t\t);\n\t\tconst updatedTransaction: Transaction = {\n\t\t\t...resource.transactions[index],\n\t\t\tstate,\n\t\t};\n\t\tresource.transactions[index] = updatedTransaction;\n\t}\n\n\tchangeTransactionTimestamp(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ transactionId, timestamp }: PaymentChangeTransactionTimestampAction,\n\t) {\n\t\tconst transaction = resource.transactions.find(\n\t\t\t(e: Transaction) => e.id === transactionId,\n\t\t);\n\t\tif (transaction) {\n\t\t\ttransaction.timestamp = timestamp;\n\t\t}\n\t}\n\n\tsetAnonymousId(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ anonymousId }: PaymentSetAnonymousIdAction,\n\t) {\n\t\tresource.anonymousId = anonymousId;\n\t\tresource.customer = undefined;\n\t}\n\n\tasync setCustomer(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ customer }: PaymentSetCustomerAction,\n\t) {\n\t\tif (customer) {\n\t\t\tconst c = await getReferenceFromResourceIdentifier<CustomerReference>(\n\t\t\t\tcustomer,\n\t\t\t\t_context.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t);\n\t\t\tresource.customer = c;\n\t\t\tresource.anonymousId = undefined;\n\t\t}\n\t}\n\n\tsetCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Payment,\n\t\t{ name, value }: PaymentSetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ type, fields }: PaymentSetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n\n\tsetInterfaceId(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ interfaceId }: PaymentSetInterfaceIdAction,\n\t) {\n\t\tresource.interfaceId = interfaceId;\n\t}\n\n\tsetKey(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ key }: PaymentSetKeyAction,\n\t) {\n\t\tresource.key = key;\n\t}\n\n\tsetMethodInfoInterface(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\targs: PaymentSetMethodInfoInterfaceAction,\n\t) {\n\t\tresource.paymentMethodInfo.paymentInterface = args.interface;\n\t}\n\n\tsetMethodInfoMethod(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ method }: PaymentSetMethodInfoMethodAction,\n\t) {\n\t\tresource.paymentMethodInfo.method = method;\n\t}\n\n\tsetMethodInfoName(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ name }: PaymentSetMethodInfoNameAction,\n\t) {\n\t\tresource.paymentMethodInfo.name = name;\n\t}\n\n\tsetStatusInterfaceCode(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ interfaceCode }: PaymentSetStatusInterfaceCodeAction,\n\t) {\n\t\tresource.paymentStatus.interfaceCode = interfaceCode;\n\t}\n\n\tsetStatusInterfaceText(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ interfaceText }: PaymentSetStatusInterfaceTextAction,\n\t) {\n\t\tresource.paymentStatus.interfaceText = interfaceText;\n\t}\n\n\tsetTransactionCustomField(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ transactionId, name, value }: PaymentSetTransactionCustomFieldAction,\n\t) {\n\t\tconst transaction = resource.transactions.find(\n\t\t\t(e: Transaction) => e.id === transactionId,\n\t\t);\n\t\tif (transaction) {\n\t\t\tif (!transaction.custom) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: \"Transaction has no custom field\",\n\t\t\t\t});\n\t\t\t}\n\n\t\t\ttransaction.custom.fields[name] = value;\n\t\t}\n\t}\n\n\tasync setTransactionCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ transactionId, type, fields }: PaymentSetTransactionCustomTypeAction,\n\t) {\n\t\tconst transaction = resource.transactions.find(\n\t\t\t(e: Transaction) => e.id === transactionId,\n\t\t);\n\t\tif (transaction) {\n\t\t\tif (!type) {\n\t\t\t\ttransaction.custom = undefined;\n\t\t\t} else {\n\t\t\t\tconst resolvedType = await this._storage.getByResourceIdentifier(\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\ttype,\n\t\t\t\t);\n\t\t\t\tif (!resolvedType) {\n\t\t\t\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>({\n\t\t\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\t\t\tmessage: `Type ${type} not found`,\n\t\t\t\t\t\ttypeId: \"type\",\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\ttransaction.custom = {\n\t\t\t\t\ttype: {\n\t\t\t\t\t\ttypeId: \"type\",\n\t\t\t\t\t\tid: resolvedType.id,\n\t\t\t\t\t},\n\t\t\t\t\tfields: fields ?? {},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tasync transitionState(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ state }: PaymentTransitionStateAction,\n\t) {\n\t\tconst stateObj = (await this._storage.getByResourceIdentifier(\n\t\t\tcontext.projectKey,\n\t\t\tstate,\n\t\t)) as State | null;\n\n\t\tif (!stateObj) {\n\t\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>({\n\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\tmessage: `State ${state} not found`,\n\t\t\t\ttypeId: \"state\",\n\t\t\t});\n\t\t}\n\n\t\tresource.paymentStatus.state = {\n\t\t\ttypeId: \"state\",\n\t\t\tid: stateObj.id,\n\t\t\tobj: stateObj,\n\t\t};\n\t}\n\n\tsetMethodInfo(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{\n\t\t\tpaymentInterface,\n\t\t\tmethod,\n\t\t\tname,\n\t\t\tinterfaceAccount,\n\t\t\ttoken,\n\t\t}: PaymentSetMethodInfoAction,\n\t) {\n\t\tif (paymentInterface !== undefined) {\n\t\t\tresource.paymentMethodInfo.paymentInterface = paymentInterface;\n\t\t}\n\t\tif (method !== undefined) {\n\t\t\tresource.paymentMethodInfo.method = method;\n\t\t}\n\t\tif (name !== undefined) {\n\t\t\tresource.paymentMethodInfo.name = name;\n\t\t}\n\t\tif (interfaceAccount !== undefined) {\n\t\t\tresource.paymentMethodInfo.interfaceAccount = interfaceAccount;\n\t\t}\n\t\tif (token !== undefined) {\n\t\t\tresource.paymentMethodInfo.token = token;\n\t\t}\n\t}\n\n\tsetMethodInfoCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ name, value }: PaymentSetMethodInfoCustomFieldAction,\n\t) {\n\t\tif (!resource.paymentMethodInfo.custom) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"PaymentMethodInfo has no custom field\",\n\t\t\t});\n\t\t}\n\n\t\tresource.paymentMethodInfo.custom.fields[name] = value;\n\t}\n\n\tasync setMethodInfoCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ type, fields }: PaymentSetMethodInfoCustomTypeAction,\n\t) {\n\t\tif (!type) {\n\t\t\tresource.paymentMethodInfo.custom = undefined;\n\t\t} else {\n\t\t\tconst resolvedType = await this._storage.getByResourceIdentifier(\n\t\t\t\tcontext.projectKey,\n\t\t\t\ttype,\n\t\t\t);\n\t\t\tif (!resolvedType) {\n\t\t\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>({\n\t\t\t\t\tcode: \"ReferencedResourceNotFound\",\n\t\t\t\t\tmessage: `Type ${type} not found`,\n\t\t\t\t\ttypeId: \"type\",\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tresource.paymentMethodInfo.custom = {\n\t\t\t\ttype: {\n\t\t\t\t\ttypeId: \"type\",\n\t\t\t\t\tid: resolvedType.id,\n\t\t\t\t},\n\t\t\t\tfields: fields ?? {},\n\t\t\t};\n\t\t}\n\t}\n\n\tsetMethodInfoInterfaceAccount(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ interfaceAccount }: PaymentSetMethodInfoInterfaceAccountAction,\n\t) {\n\t\tresource.paymentMethodInfo.interfaceAccount = interfaceAccount;\n\t}\n\n\tsetMethodInfoToken(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Payment>,\n\t\t{ token }: PaymentSetMethodInfoTokenAction,\n\t) {\n\t\tresource.paymentMethodInfo.token = token;\n\t}\n}\n","import type {\n\tPayment,\n\tPaymentDraft,\n\tStateReference,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { getBaseResourceProperties } from \"#src/helpers.ts\";\nimport { PaymentDraftSchema } from \"#src/schemas/generated/payment.ts\";\nimport type { RepositoryContext } from \"../abstract.ts\";\nimport { AbstractResourceRepository } from \"../abstract.ts\";\nimport {\n\tcreateCentPrecisionMoney,\n\tcreateCustomFields,\n\tgetReferenceFromResourceIdentifier,\n} from \"../helpers.ts\";\nimport { PaymentUpdateHandler } from \"./actions.ts\";\nimport { transactionFromTransactionDraft } from \"./helpers.ts\";\n\nexport class PaymentRepository extends AbstractResourceRepository<\"payment\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"payment\", config);\n\t\tthis.actions = new PaymentUpdateHandler(this._storage);\n\t\tthis.draftSchema = PaymentDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: PaymentDraft,\n\t): Promise<Payment> {\n\t\tconst transactions = await Promise.all(\n\t\t\t(draft.transactions || []).map((t) =>\n\t\t\t\ttransactionFromTransactionDraft(context, this._storage, t),\n\t\t\t),\n\t\t);\n\t\tconst interfaceInteractions = await Promise.all(\n\t\t\t(draft.interfaceInteractions || []).map(async (interaction) => {\n\t\t\t\tconst customFields = await createCustomFields(\n\t\t\t\t\tinteraction,\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tthis._storage,\n\t\t\t\t);\n\t\t\t\treturn customFields!;\n\t\t\t}),\n\t\t);\n\n\t\tconst resource: Payment = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tkey: draft.key,\n\t\t\tamountPlanned: createCentPrecisionMoney(draft.amountPlanned),\n\t\t\tpaymentMethodInfo: { ...draft.paymentMethodInfo!, custom: undefined },\n\t\t\tpaymentStatus: draft.paymentStatus\n\t\t\t\t? {\n\t\t\t\t\t\t...draft.paymentStatus,\n\t\t\t\t\t\tstate: draft.paymentStatus.state\n\t\t\t\t\t\t\t? await getReferenceFromResourceIdentifier<StateReference>(\n\t\t\t\t\t\t\t\t\tdraft.paymentStatus.state,\n\t\t\t\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\t\t\t\tthis._storage,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t}\n\t\t\t\t: {},\n\t\t\ttransactions,\n\t\t\tinterfaceInteractions,\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t};\n\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n","import type {\n\tReview,\n\tReviewRatingStatistics,\n} from \"@commercetools/platform-sdk\";\nimport type { AbstractStorage } from \"../storage/index.ts\";\n\nexport class ReviewStatisticsService {\n\tprivate _storage: AbstractStorage;\n\n\tconstructor(_storage: AbstractStorage) {\n\t\tthis._storage = _storage;\n\t}\n\n\tasync calculateProductReviewStatistics(\n\t\tprojectKey: string,\n\t\tproductId: string,\n\t): Promise<ReviewRatingStatistics | undefined> {\n\t\t// Fast path: if there are no reviews at all, skip the expensive load\n\t\tconst reviewCount = await this._storage.count(projectKey, \"review\");\n\t\tif (reviewCount === 0) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// Get all reviews for this product\n\t\tconst allReviews = (await this._storage.all(\n\t\t\tprojectKey,\n\t\t\t\"review\",\n\t\t)) as Review[];\n\t\tconst productReviews = allReviews.filter(\n\t\t\t(review) =>\n\t\t\t\treview.target?.typeId === \"product\" &&\n\t\t\t\treview.target?.id === productId &&\n\t\t\t\treview.includedInStatistics &&\n\t\t\t\treview.rating !== undefined,\n\t\t);\n\n\t\tif (productReviews.length === 0) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst ratings = productReviews\n\t\t\t.map((review) => review.rating!)\n\t\t\t.filter((rating) => rating !== undefined);\n\n\t\tif (ratings.length === 0) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// Calculate statistics\n\t\tconst count = ratings.length;\n\t\tconst sum = ratings.reduce((acc, rating) => acc + rating, 0);\n\t\tconst averageRating = Math.round((sum / count) * 100000) / 100000; // Round to 5 decimals\n\t\tconst highestRating = Math.max(...ratings);\n\t\tconst lowestRating = Math.min(...ratings);\n\n\t\t// Calculate ratings distribution\n\t\tconst ratingsDistribution: { [key: string]: number } = {};\n\t\tfor (const rating of ratings) {\n\t\t\tconst key = rating.toString();\n\t\t\tratingsDistribution[key] = (ratingsDistribution[key] || 0) + 1;\n\t\t}\n\n\t\treturn {\n\t\t\taverageRating,\n\t\t\thighestRating,\n\t\t\tlowestRating,\n\t\t\tcount,\n\t\t\tratingsDistribution,\n\t\t};\n\t}\n}\n","/**\n * This module implements the commercetools product projection filter expression.\n */\n\nimport type {\n\tProductProjection,\n\tProductVariant,\n} from \"@commercetools/platform-sdk\";\nimport { nestedLookup } from \"../helpers.ts\";\nimport type { Writable } from \"../types.ts\";\nimport { Lexer, Parser } from \"./parser.ts\";\n\ntype MatchFunc = (target: any) => boolean;\n\ntype ProductProjectionFilter = (\n\tp: Writable<ProductProjection>,\n\tmarkMatchingVariants: boolean,\n) => boolean;\n\ntype TypeSymbol = {\n\ttype: \"Symbol\";\n\tkind: \"int\" | \"string\" | \"any\";\n\tvalue: any;\n};\n\ntype RangeExpressionSet = {\n\tsource: string;\n\ttype: \"RangeExpression\";\n\tchildren?: RangeExpression[];\n};\n\ntype FilterExpressionSet = {\n\tsource: string;\n\ttype: \"FilterExpression\";\n\tchildren?: FilterExpression[];\n};\n\ntype TermExpressionSet = {\n\tsource: string;\n\ttype: \"TermExpression\";\n};\n\ntype ExpressionSet =\n\t| RangeExpressionSet\n\t| FilterExpressionSet\n\t| TermExpressionSet;\n\nexport type RangeExpression = {\n\ttype: \"RangeExpression\";\n\tstart?: number;\n\tstop?: number;\n\tmatch: (obj: any) => boolean;\n};\n\nexport type FilterExpression = {\n\ttype: \"FilterExpression\";\n\tmatch: (obj: any) => boolean;\n};\n\n/**\n * Returns a function (ProductProjectionFilter).\n * NOTE: The filter can alter the resources in-place (FIXME)\n */\nexport const parseFilterExpression = (\n\tfilter: string,\n): ProductProjectionFilter => {\n\tconst exprFunc = generateMatchFunc(filter);\n\tconst [source] = filter.split(\":\", 1);\n\n\tif (source.startsWith(\"variants.\")) {\n\t\treturn filterVariants(source, exprFunc);\n\t}\n\treturn filterProduct(source, exprFunc);\n};\n\nconst getLexer = (value: string) =>\n\tnew Lexer(value)\n\t\t.token(\"MISSING\", /missing(?![-_a-z0-9]+)/i)\n\t\t.token(\"EXISTS\", /exists(?![-_a-z0-9]+)/i)\n\t\t.token(\"RANGE\", /range(?![-_a-z0-9]+)/i)\n\t\t.token(\"TO\", /to(?![-_a-z0-9]+)/i)\n\t\t.token(\"IDENTIFIER\", /[-_.a-z]+/i)\n\n\t\t.token(\"FLOAT\", /\\d+\\.\\d+/)\n\t\t.token(\"INT\", /\\d+/)\n\t\t.token(\"STRING\", /\"((?:\\\\.|[^\"\\\\])*)\"/)\n\t\t.token(\"STRING\", /'((?:\\\\.|[^'\\\\])*)'/)\n\n\t\t.token(\"COMMA\", \",\")\n\t\t.token(\"STAR\", \"*\")\n\t\t.token(\"(\", \"(\")\n\t\t.token(\":\", \":\")\n\t\t.token(\")\", \")\")\n\t\t.token('\"', '\"')\n\t\t.token(\"WS\", /\\s+/, true); // skip\n\nconst parseFilter = (filter: string): ExpressionSet => {\n\tconst lexer = getLexer(filter);\n\tconst parser = new Parser(lexer)\n\t\t.builder()\n\t\t.nud(\"IDENTIFIER\", 100, (t) => t.token.match)\n\t\t.led(\":\", 100, ({ left, bp }) => {\n\t\t\tconst parsed: any = parser.parse({ terminals: [bp - 1] });\n\t\t\tconst expressions: RangeExpression[] | FilterExpression[] | TypeSymbol[] =\n\t\t\t\t!Array.isArray(parsed) ? [parsed] : parsed;\n\n\t\t\t// Make sure we only have one type of expression (cannot mix)\n\t\t\tconst unique = new Set(expressions.map((expr) => expr.type));\n\t\t\tif (unique.size > 1) {\n\t\t\t\tthrow new Error(\"Invalid expression\");\n\t\t\t}\n\n\t\t\t// Convert plain symbols to a filter expression. For example\n\t\t\t// variants.attribute.foobar:4 where 4 is a Symbol should result\n\t\t\t// in a comparison\n\t\t\tif (expressions.some((expr) => expr.type === \"Symbol\")) {\n\t\t\t\treturn {\n\t\t\t\t\tsource: left as string,\n\t\t\t\t\ttype: \"FilterExpression\",\n\t\t\t\t\tchildren: expressions.map((e): FilterExpression => {\n\t\t\t\t\t\tif (e.type !== \"Symbol\") {\n\t\t\t\t\t\t\tthrow new Error(\"Invalid expression\");\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"FilterExpression\",\n\t\t\t\t\t\t\tmatch: (obj: any): boolean => obj === e.value,\n\t\t\t\t\t\t};\n\t\t\t\t\t}),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tsource: left,\n\t\t\t\ttype: expressions[0].type,\n\t\t\t\tchildren: expressions,\n\t\t\t};\n\t\t})\n\t\t.nud(\n\t\t\t\"STRING\",\n\t\t\t20,\n\t\t\t(t) =>\n\t\t\t\t({\n\t\t\t\t\ttype: \"Symbol\",\n\t\t\t\t\tkind: \"string\",\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tvalue: t.token.groups[1],\n\t\t\t\t}) as TypeSymbol,\n\t\t)\n\t\t.nud(\n\t\t\t\"INT\",\n\t\t\t5,\n\t\t\t(t) =>\n\t\t\t\t({\n\t\t\t\t\ttype: \"Symbol\",\n\t\t\t\t\tkind: \"int\",\n\t\t\t\t\tvalue: Number.parseInt(t.token.match, 10),\n\t\t\t\t}) as TypeSymbol,\n\t\t)\n\t\t.nud(\"STAR\", 5, (_) => ({\n\t\t\ttype: \"Symbol\",\n\t\t\tkind: \"any\",\n\t\t\tvalue: null,\n\t\t}))\n\t\t.nud(\n\t\t\t\"EXISTS\",\n\t\t\t10,\n\t\t\t({ bp }) =>\n\t\t\t\t({\n\t\t\t\t\ttype: \"FilterExpression\",\n\t\t\t\t\tmatch: (obj: any): boolean => obj !== undefined,\n\t\t\t\t}) as FilterExpression,\n\t\t)\n\t\t.nud(\n\t\t\t\"MISSING\",\n\t\t\t10,\n\t\t\t({ bp }) =>\n\t\t\t\t({\n\t\t\t\t\ttype: \"FilterExpression\",\n\t\t\t\t\tmatch: (obj: any): boolean => obj === undefined,\n\t\t\t\t}) as FilterExpression,\n\t\t)\n\t\t.led(\"COMMA\", 200, ({ left, token, bp }) => {\n\t\t\tconst expr: any = parser.parse({ terminals: [bp - 1] });\n\t\t\tif (Array.isArray(expr)) {\n\t\t\t\treturn [left, ...expr];\n\t\t\t}\n\t\t\treturn [left, expr];\n\t\t})\n\t\t.nud(\"(\", 100, (t) => {\n\t\t\tconst expr: any = parser.parse({ terminals: [\")\"] });\n\t\t\tlexer.expect(\")\");\n\t\t\treturn expr;\n\t\t})\n\t\t.bp(\")\", 0)\n\t\t.led(\"TO\", 20, ({ left, bp }) => {\n\t\t\tconst expr: any = parser.parse({ terminals: [bp - 1] });\n\t\t\treturn {\n\t\t\t\tstart: left.value,\n\t\t\t\tstop: expr.value,\n\t\t\t};\n\t\t})\n\t\t.nud(\"RANGE\", 20, ({ bp }) => {\n\t\t\tlet ranges: any = parser.parse();\n\n\t\t\t// If multiple ranges are defined we receive an array of ranges. So let's\n\t\t\t// make sure we always have an array\n\t\t\tif (!Array.isArray(ranges)) {\n\t\t\t\tranges = [ranges];\n\t\t\t}\n\n\t\t\t// Return a list of functions which matches the ranges. These functions\n\t\t\t// are processed as an OR clause\n\t\t\treturn ranges.map((range: any) => {\n\t\t\t\tlet func: (obj: any) => boolean;\n\n\t\t\t\tif (range.start !== null && range.stop !== null) {\n\t\t\t\t\tfunc = (obj: any): boolean => obj >= range.start && obj <= range.stop;\n\t\t\t\t} else if (range.start === null && range.stop !== null) {\n\t\t\t\t\tfunc = (obj: any): boolean => obj <= range.stop;\n\t\t\t\t} else if (range.start !== null && range.stop === null) {\n\t\t\t\t\tfunc = (obj: any): boolean => obj >= range.start;\n\t\t\t\t} else {\n\t\t\t\t\tfunc = (obj: any): boolean => true;\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"RangeExpression\",\n\t\t\t\t\tstart: range.start,\n\t\t\t\t\tstop: range.stop,\n\t\t\t\t\tmatch: func,\n\t\t\t\t} as RangeExpression;\n\t\t\t});\n\t\t})\n\t\t.build();\n\n\treturn parser.parse();\n};\n\nconst generateMatchFunc = (filter: string) => {\n\tconst result = parseFilter(filter);\n\tif (!result) {\n\t\t// const lines = filter.split('\\n')\n\t\t// const column = lines[lines.length - 1].length\n\t\tthrow new Error(`Syntax error while parsing '${filter}'.`);\n\t}\n\tif (result.type === \"TermExpression\") {\n\t\tthrow new Error(`Syntax error while parsing '${filter}'.`);\n\t}\n\n\treturn (obj: any) => {\n\t\tif (!result.children) return false;\n\t\treturn result.children.some((c) => c.match(obj));\n\t};\n};\n\nexport const generateFacetFunc = (filter: string): ExpressionSet => {\n\tif (!filter.includes(\":\")) {\n\t\treturn {\n\t\t\tsource: filter,\n\t\t\ttype: \"TermExpression\",\n\t\t};\n\t}\n\treturn parseFilter(filter);\n};\n\nconst filterProduct =\n\t(source: string, exprFunc: MatchFunc): ProductProjectionFilter =>\n\t(p: ProductProjection, markMatchingVariants: boolean): boolean => {\n\t\tconst value = nestedLookup(p, source);\n\t\treturn exprFunc(value);\n\t};\n\nconst filterVariants =\n\t(source: string, exprFunc: MatchFunc): ProductProjectionFilter =>\n\t(p: ProductProjection, markMatchingVariants: boolean): boolean => {\n\t\tconst [, ...paths] = source.split(\".\");\n\t\tconst path = paths.join(\".\");\n\n\t\tconst variants = getVariants(p) as Writable<ProductVariant>[];\n\t\tfor (const variant of variants) {\n\t\t\tconst value = resolveVariantValue(variant, path);\n\n\t\t\tif (exprFunc(value)) {\n\t\t\t\t// If markMatchingVariants parameter is true those ProductVariants that\n\t\t\t\t// match the search query have the additional field isMatchingVariant\n\t\t\t\t// set to true. For the other variants in the same product projection\n\t\t\t\t// this field is set to false.\n\t\t\t\tif (markMatchingVariants) {\n\t\t\t\t\tfor (const v of variants) {\n\t\t\t\t\t\tv.isMatchingVariant = false;\n\t\t\t\t\t}\n\t\t\t\t\tvariant.isMatchingVariant = true;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t};\n\nexport const resolveVariantValue = (obj: ProductVariant, path: string): any => {\n\tif (path === undefined) {\n\t\treturn obj;\n\t}\n\tif (path.startsWith(\"variants.\")) {\n\t\tpath = path.substring(path.indexOf(\".\") + 1);\n\t}\n\n\tif (path.startsWith(\"attributes.\")) {\n\t\tconst [, attrName, ...rest] = path.split(\".\");\n\t\tif (!obj.attributes) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tfor (const attr of obj.attributes) {\n\t\t\tif (attr.name === attrName) {\n\t\t\t\treturn nestedLookup(attr.value, rest.join(\".\"));\n\t\t\t}\n\t\t}\n\t}\n\n\tif (path === \"price.centAmount\") {\n\t\treturn obj.prices && obj.prices.length > 0\n\t\t\t? obj.prices[0].value.centAmount\n\t\t\t: undefined;\n\t}\n\n\treturn nestedLookup(obj, path);\n};\n\nexport const getVariants = (p: ProductProjection): ProductVariant[] => [\n\tp.masterVariant,\n\t...(p.variants ?? []),\n];\n","import type {\n\t_SearchQuery,\n\t_SearchQueryExpression,\n\t_SearchQueryExpressionValue,\n\tCategoryReference,\n\tProductProjection,\n\tProductVariant,\n\tSearchAndExpression,\n\tSearchDateRangeExpression,\n\tSearchDateTimeRangeExpression,\n\tSearchExactExpression,\n\tSearchExistsExpression,\n\tSearchFilterExpression,\n\tSearchFullTextExpression,\n\tSearchFullTextPrefixExpression,\n\tSearchLongRangeExpression,\n\tSearchNotExpression,\n\tSearchNumberRangeExpression,\n\tSearchOrExpression,\n\tSearchPrefixExpression,\n\tSearchTimeRangeExpression,\n\tSearchWildCardExpression,\n} from \"@commercetools/platform-sdk\";\nimport { nestedLookup } from \"#src/helpers.ts\";\nimport type { Writable } from \"../types.ts\";\nimport { getVariants } from \"./projectionSearchFilter.ts\";\n\ntype ProductSearchFilterFunc = (\n\tp: Writable<ProductProjection>,\n\tmarkMatchingVariants: boolean,\n) => boolean;\n\n// @TODO: Implement field boosting:\n// https://docs.commercetools.com/merchant-center/advanced-product-search#boost-field\nexport const parseSearchQuery = (\n\tsearchQuery: _SearchQuery,\n): ProductSearchFilterFunc => {\n\tif (isSearchAndExpression(searchQuery)) {\n\t\treturn (obj, markMatchingVariant) =>\n\t\t\tsearchQuery.and.every((expr) => {\n\t\t\t\tconst filterFunc = parseSearchQuery(expr);\n\n\t\t\t\treturn filterFunc(obj, markMatchingVariant);\n\t\t\t});\n\t}\n\n\tif (isSearchOrExpression(searchQuery)) {\n\t\treturn (obj, markMatchingVariant) =>\n\t\t\tsearchQuery.or.some((expr) => {\n\t\t\t\tconst filterFunc = parseSearchQuery(expr);\n\n\t\t\t\treturn filterFunc(obj, markMatchingVariant);\n\t\t\t});\n\t}\n\n\tif (isSearchNotExpression(searchQuery)) {\n\t\treturn (obj, markMatchingVariant) =>\n\t\t\tsearchQuery.not.every(\n\t\t\t\t(expr) => !parseSearchQuery(expr)(obj, markMatchingVariant),\n\t\t\t);\n\t}\n\n\tif (isSearchFilterExpression(searchQuery)) {\n\t\t// Matching resources of a query are checked for their relevancy to the search.\n\t\t// The relevancy is expressed by an internal score.\n\t\t// All expressions except filter expressions contribute to that score.\n\t\t// All sub-expressions of a filter are implicitly connected with an and expression.\n\t\t// NOTE: for now just implementing it like a AND expression\n\t\treturn (obj, markMatchingVariant) =>\n\t\t\tsearchQuery.filter.every((expr) => {\n\t\t\t\tconst filterFunc = parseSearchQuery(expr);\n\n\t\t\t\treturn filterFunc(obj, markMatchingVariant);\n\t\t\t});\n\t}\n\n\tif (isSearchRangeExpression(searchQuery)) {\n\t\tconst generateRangeMatchFunc = (value: any) => {\n\t\t\tconst rangeFilters = [];\n\n\t\t\tif (searchQuery.range.gte) {\n\t\t\t\trangeFilters.push(value >= searchQuery.range.gte);\n\t\t\t}\n\n\t\t\tif (searchQuery.range.gt) {\n\t\t\t\trangeFilters.push(value > searchQuery.range.gt);\n\t\t\t}\n\n\t\t\tif (searchQuery.range.lte) {\n\t\t\t\trangeFilters.push(value <= searchQuery.range.lte);\n\t\t\t}\n\n\t\t\tif (searchQuery.range.lt) {\n\t\t\t\trangeFilters.push(value < searchQuery.range.lt);\n\t\t\t}\n\n\t\t\treturn rangeFilters.every((filter) => filter);\n\t\t};\n\n\t\treturn generateFieldMatchFunc(generateRangeMatchFunc, searchQuery.range);\n\t}\n\n\tif (isSearchExactExpression(searchQuery)) {\n\t\tif (Array.isArray(searchQuery.exact.values)) {\n\t\t\treturn generateFieldMatchFunc(\n\t\t\t\t(value: any) => (searchQuery.exact.values ?? []).includes(value),\n\t\t\t\tsearchQuery.exact,\n\t\t\t);\n\t\t}\n\n\t\treturn generateFieldMatchFunc(\n\t\t\t(value: any) => value === searchQuery.exact.value,\n\t\t\tsearchQuery.exact,\n\t\t);\n\t}\n\n\tif (isSearchExistsExpression(searchQuery)) {\n\t\treturn generateFieldMatchFunc((value: any) => !!value, searchQuery.exists);\n\t}\n\n\tif (isSearchFullTextExpression(searchQuery)) {\n\t\t// @TODO: Implement fulltext search, to fully support functionality offered by commercetools:\n\t\t// https://docs.commercetools.com/api/search-query-language#fulltext\n\t\treturn generateFieldMatchFunc(\n\t\t\t(value: any) => value.includes(searchQuery.fullText.value),\n\t\t\tsearchQuery.fullText,\n\t\t);\n\t}\n\n\tif (isSearchFullTextPrefixExpression(searchQuery)) {\n\t\t// @TODO: Implement fulltext search, to fully support functionality offered by commercetools:\n\t\t// https://docs.commercetools.com/api/search-query-language#fulltext\n\t\treturn generateFieldMatchFunc(\n\t\t\t(value: any) => value.startsWith(searchQuery.fullTextPrefix.value),\n\t\t\tsearchQuery.fullTextPrefix,\n\t\t);\n\t}\n\n\tif (isSearchPrefixExpression(searchQuery)) {\n\t\treturn generateFieldMatchFunc(\n\t\t\t(value: any) => value.startsWith(searchQuery.prefix.value),\n\t\t\tsearchQuery.prefix,\n\t\t);\n\t}\n\n\tif (isSearchWildCardExpression(searchQuery)) {\n\t\t// @TODO: Fully implement wildcard search, as specified:\n\t\t// https://docs.commercetools.com/api/search-query-language#fulltext\n\t\tconst generateWildcardMatchFunc = (value: any) => {\n\t\t\tconst wildCardValues = searchQuery.wildcard.value\n\t\t\t\t.split(\"*\")\n\t\t\t\t.filter((v: string) => !!v);\n\n\t\t\tif (searchQuery.wildcard.caseInsensitive) {\n\t\t\t\treturn wildCardValues.every((wildCardValue: string) =>\n\t\t\t\t\tvalue.toLowerCase().includes(wildCardValue.toLowerCase()),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn wildCardValues.every((wildCardValue: string) =>\n\t\t\t\tvalue.includes(wildCardValue),\n\t\t\t);\n\t\t};\n\n\t\treturn generateFieldMatchFunc(\n\t\t\tgenerateWildcardMatchFunc,\n\t\t\tsearchQuery.wildcard,\n\t\t);\n\t}\n\n\tthrow new Error(\"Unsupported search query expression\");\n};\n\nconst generateFieldMatchFunc = (\n\tmatchFunc: (value: any) => boolean,\n\tsearchQuery: _SearchQueryExpressionValue,\n) => {\n\tconst generateMatchFunc = (\n\t\tobj: ProductProjection,\n\t\tmarkMatchingVariants: boolean,\n\t) => {\n\t\tif (searchQuery.field.startsWith(\"variants.\")) {\n\t\t\tconst variantField = searchQuery.field.substring(\n\t\t\t\tsearchQuery.field.indexOf(\".\") + 1,\n\t\t\t);\n\n\t\t\tconst variants = getVariants(obj) as Writable<ProductVariant>[];\n\t\t\tfor (const variant of variants) {\n\t\t\t\tconst value = resolveFieldValue(variant, {\n\t\t\t\t\t...searchQuery,\n\t\t\t\t\tfield: variantField,\n\t\t\t\t});\n\n\t\t\t\tif (matchFunc(value)) {\n\t\t\t\t\tif (markMatchingVariants) {\n\t\t\t\t\t\tfor (const v of variants) {\n\t\t\t\t\t\t\tv.isMatchingVariant = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvariant.isMatchingVariant = true;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\n\t\tconst value = resolveFieldValue(obj, searchQuery);\n\n\t\treturn Array.isArray(value)\n\t\t\t? value.some((v) => matchFunc(v))\n\t\t\t: matchFunc(value);\n\t};\n\n\treturn generateMatchFunc;\n};\n\nconst resolveFieldValue = (\n\tobj: any,\n\tsearchQuery: _SearchQueryExpressionValue,\n) => {\n\tif (searchQuery.field === undefined) {\n\t\tthrow new Error(\"Missing field path in query expression\");\n\t}\n\n\tlet fieldPath = searchQuery.field;\n\tconst language = \"language\" in searchQuery ? searchQuery.language : undefined;\n\n\tif (fieldPath.startsWith(\"variants.\")) {\n\t\tfieldPath = fieldPath.substring(fieldPath.indexOf(\".\") + 1);\n\t}\n\n\tif (fieldPath.startsWith(\"attributes.\")) {\n\t\tconst [, attrName, ...rest] = fieldPath.split(\".\");\n\t\tif (!obj.attributes) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tfor (const attr of obj.attributes) {\n\t\t\tif (attr.name === attrName) {\n\t\t\t\treturn nestedLookupByLanguage(attr.value, rest.join(\".\"), language);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (fieldPath === \"prices.currentCentAmount\") {\n\t\treturn obj.prices && obj.prices.length > 0\n\t\t\t? obj.prices[0].value.centAmount\n\t\t\t: undefined;\n\t}\n\n\tif (fieldPath === \"categoriesSubTree\") {\n\t\tif (!Array.isArray(obj.categories) || obj.categories.length === 0) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\treturn obj.categories.flatMap((category: CategoryReference) => {\n\t\t\tconst ancestorIds =\n\t\t\t\tcategory.obj?.ancestors?.map((ancestor) => ancestor.id) ?? [];\n\n\t\t\treturn [category.id, ...ancestorIds];\n\t\t});\n\t}\n\n\treturn nestedLookupByLanguage(obj, fieldPath, language);\n};\n\nconst nestedLookupByLanguage = (\n\tobj: any,\n\tpath: string,\n\tlanguage?: string,\n): any => {\n\tconst value = nestedLookup(obj, path);\n\n\tif (language && value && typeof value === \"object\") {\n\t\t// Due to Commercetools supporting \"en\", but also \"en-US\" as language, we need to find the best match\n\t\tconst matchingLanguageKey = Object.keys(value).find((key) =>\n\t\t\tkey.toLowerCase().startsWith(language.toLowerCase()),\n\t\t);\n\n\t\treturn matchingLanguageKey ? value[matchingLanguageKey] : undefined;\n\t}\n\n\treturn value;\n};\n\n// type guards\nconst isSearchAndExpression = (\n\texpr: _SearchQuery,\n): expr is SearchAndExpression =>\n\t(expr as SearchAndExpression).and !== undefined;\n\nconst isSearchOrExpression = (expr: _SearchQuery): expr is SearchOrExpression =>\n\t(expr as SearchOrExpression).or !== undefined;\n\ntype SearchRangeExpression =\n\t| SearchDateRangeExpression\n\t| SearchDateTimeRangeExpression\n\t| SearchLongRangeExpression\n\t| SearchNumberRangeExpression\n\t| SearchTimeRangeExpression;\n\n// Type guard for SearchNotExpression\nconst isSearchNotExpression = (\n\texpr: _SearchQueryExpression,\n): expr is SearchNotExpression =>\n\t(expr as SearchNotExpression).not !== undefined;\n\n// Type guard for SearchFilterExpression\nconst isSearchFilterExpression = (\n\texpr: _SearchQueryExpression,\n): expr is SearchFilterExpression =>\n\t(expr as SearchFilterExpression).filter !== undefined;\n\n// Type guard for SearchDateRangeExpression\nconst isSearchRangeExpression = (\n\texpr: _SearchQueryExpression,\n): expr is SearchRangeExpression =>\n\t(expr as SearchRangeExpression).range !== undefined;\n\n// Type guard for SearchExactExpression\nconst isSearchExactExpression = (\n\texpr: _SearchQueryExpression,\n): expr is SearchExactExpression =>\n\t(expr as SearchExactExpression).exact !== undefined;\n\n// Type guard for SearchExistsExpression\nconst isSearchExistsExpression = (\n\texpr: _SearchQueryExpression,\n): expr is SearchExistsExpression =>\n\t(expr as SearchExistsExpression).exists !== undefined;\n\n// Type guard for SearchFullTextExpression\nconst isSearchFullTextExpression = (\n\texpr: _SearchQueryExpression,\n): expr is SearchFullTextExpression =>\n\t(expr as SearchFullTextExpression).fullText !== undefined;\n\n// Type guard for SearchFullTextPrefixExpression\nconst isSearchFullTextPrefixExpression = (\n\texpr: _SearchQueryExpression,\n): expr is SearchFullTextPrefixExpression =>\n\t(expr as SearchFullTextPrefixExpression).fullTextPrefix !== undefined;\n\n// Type guard for SearchPrefixExpression\nconst isSearchPrefixExpression = (\n\texpr: _SearchQueryExpression,\n): expr is SearchPrefixExpression =>\n\t(expr as SearchPrefixExpression).prefix !== undefined;\n\n// Type guard for SearchWildCardExpression\nconst isSearchWildCardExpression = (\n\texpr: _SearchQueryExpression,\n): expr is SearchWildCardExpression =>\n\t(expr as SearchWildCardExpression).wildcard !== undefined;\n","import type {\n\t_SearchQuery,\n\t_SearchQueryExpression,\n\tSearchAndExpression,\n\tSearchAnyValue,\n\tSearchDateRangeExpression,\n\tSearchDateTimeRangeExpression,\n\tSearchExactExpression,\n\tSearchExistsExpression,\n\tSearchFilterExpression,\n\tSearchFullTextExpression,\n\tSearchFullTextPrefixExpression,\n\tSearchLongRangeExpression,\n\tSearchNotExpression,\n\tSearchNumberRangeExpression,\n\tSearchOrExpression,\n\tSearchPrefixExpression,\n\tSearchTimeRangeExpression,\n\tSearchWildCardExpression,\n} from \"@commercetools/platform-sdk\";\n\nexport const validateSearchQuery = (query: _SearchQuery): void => {\n\tif (isSearchAndExpression(query)) {\n\t\tfor (const expr of query.and) {\n\t\t\tvalidateSearchQuery(expr);\n\t\t}\n\t} else if (isSearchOrExpression(query)) {\n\t\tfor (const expr of query.or) {\n\t\t\tvalidateSearchQuery(expr);\n\t\t}\n\t} else if (isSearchNotExpression(query)) {\n\t\tvalidateSearchQuery(query.not);\n\t} else if (\n\t\tisSearchFilterExpression(query) ||\n\t\tisSearchRangeExpression(query) ||\n\t\tisSearchExactExpression(query) ||\n\t\tisSearchExistsExpression(query) ||\n\t\tisSearchFullTextExpression(query) ||\n\t\tisSearchFullTextPrefixExpression(query) ||\n\t\tisSearchPrefixExpression(query) ||\n\t\tisSearchWildCardExpression(query) ||\n\t\tisSearchAnyValue(query)\n\t) {\n\t\treturn;\n\t} else {\n\t\tthrow new Error(\"Unsupported search query expression\");\n\t}\n};\n\n// Type guards\nexport const isSearchAndExpression = (\n\texpr: _SearchQuery,\n): expr is SearchAndExpression =>\n\t(expr as SearchAndExpression).and !== undefined;\n\nexport const isSearchOrExpression = (\n\texpr: _SearchQuery,\n): expr is SearchOrExpression => (expr as SearchOrExpression).or !== undefined;\n\nexport type SearchRangeExpression =\n\t| SearchDateRangeExpression\n\t| SearchDateTimeRangeExpression\n\t| SearchLongRangeExpression\n\t| SearchNumberRangeExpression\n\t| SearchTimeRangeExpression;\n\n// Type guard for SearchNotExpression\nexport const isSearchNotExpression = (\n\texpr: _SearchQueryExpression,\n): expr is SearchNotExpression =>\n\t(expr as SearchNotExpression).not !== undefined;\n\n// Type guard for SearchFilterExpression\nexport const isSearchFilterExpression = (\n\texpr: _SearchQueryExpression,\n): expr is SearchFilterExpression =>\n\t(expr as SearchFilterExpression).filter !== undefined;\n\n// Type guard for SearchDateRangeExpression\nexport const isSearchRangeExpression = (\n\texpr: _SearchQueryExpression,\n): expr is SearchRangeExpression =>\n\t(expr as SearchRangeExpression).range !== undefined;\n\n// Type guard for SearchExactExpression\nexport const isSearchExactExpression = (\n\texpr: _SearchQueryExpression,\n): expr is SearchExactExpression =>\n\t(expr as SearchExactExpression).exact !== undefined;\n\n// Type guard for SearchExistsExpression\nexport const isSearchExistsExpression = (\n\texpr: _SearchQueryExpression,\n): expr is SearchExistsExpression =>\n\t(expr as SearchExistsExpression).exists !== undefined;\n\n// Type guard for SearchFullTextExpression\nexport const isSearchFullTextExpression = (\n\texpr: _SearchQueryExpression,\n): expr is SearchFullTextExpression =>\n\t(expr as SearchFullTextExpression).fullText !== undefined;\n\n// Type guard for SearchFullTextPrefixExpression\nexport const isSearchFullTextPrefixExpression = (\n\texpr: _SearchQueryExpression,\n): expr is SearchFullTextPrefixExpression =>\n\t(expr as SearchFullTextPrefixExpression).fullTextPrefix !== undefined;\n\n// Type guard for SearchPrefixExpression\nexport const isSearchPrefixExpression = (\n\texpr: _SearchQueryExpression,\n): expr is SearchPrefixExpression =>\n\t(expr as SearchPrefixExpression).prefix !== undefined;\n\n// Type guard for SearchWildCardExpression\nexport const isSearchWildCardExpression = (\n\texpr: _SearchQueryExpression,\n): expr is SearchWildCardExpression =>\n\t(expr as SearchWildCardExpression).wildcard !== undefined;\n\n// Type guard for SearchAnyValue\nexport const isSearchAnyValue = (\n\texpr: _SearchQueryExpression,\n): expr is SearchAnyValue => (expr as SearchAnyValue).value !== undefined;\n","import type {\n\tInvalidInputError,\n\tPrice,\n\tProductProjection,\n\tProductVariant,\n} from \"@commercetools/platform-sdk\";\nimport { CommercetoolsError } from \"./exceptions.ts\";\nimport type { Writable } from \"./types.ts\";\n\nexport type PriceSelector = {\n\tcurrency?: string;\n\tcountry?: string;\n\tcustomerGroup?: string;\n\tchannel?: string;\n};\n\n/**\n * Apply the price selector on all the variants. The price selector is applied\n * on all the prices per variant and the first match per variant is stored in\n * the scopedPrice attribute\n */\nexport const applyPriceSelector = (\n\tproducts: ProductProjection[],\n\tselector: PriceSelector,\n\tnoScopedPrice = false,\n) => {\n\tvalidatePriceSelector(selector);\n\n\tfor (const product of products) {\n\t\t// Get list of all variants (master + variants)\n\t\tconst variants: Writable<ProductVariant>[] = [\n\t\t\tproduct.masterVariant,\n\t\t\t...(product.variants ?? []),\n\t\t].filter((x) => x !== undefined);\n\n\t\tfor (const variant of variants) {\n\t\t\tconst scopedPrices =\n\t\t\t\tvariant.prices?.filter((p) => priceSelectorFilter(p, selector)) ?? [];\n\n\t\t\tif (scopedPrices.length > 0) {\n\t\t\t\tconst price = scopedPrices[0];\n\n\t\t\t\tvariant.price = scopedPrices[0];\n\t\t\t\tif (!noScopedPrice) {\n\t\t\t\t\tvariant.scopedPriceDiscounted = false;\n\t\t\t\t\tvariant.scopedPrice = {\n\t\t\t\t\t\t...price,\n\t\t\t\t\t\tcurrentValue: price.value,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n};\n\nconst validatePriceSelector = (selector: PriceSelector) => {\n\tif (\n\t\t(selector.country || selector.channel || selector.customerGroup) &&\n\t\t!selector.currency\n\t) {\n\t\tthrow new CommercetoolsError<InvalidInputError>(\n\t\t\t{\n\t\t\t\tcode: \"InvalidInput\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"The price selecting parameters country, channel and customerGroup \" +\n\t\t\t\t\t\"cannot be used without the currency.\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n};\n\n/**\n * Return a boolean to indicate if the price matches the selector. Price\n * selection requires that if the selector or the price has a specific value\n * then it should match.\n */\nexport const priceSelectorFilter = (\n\tprice: Price,\n\tselector: PriceSelector,\n): boolean => {\n\tif (\n\t\t(selector.country || price.country) &&\n\t\tselector.country !== price.country\n\t) {\n\t\treturn false;\n\t}\n\n\tif (\n\t\t(selector.currency || price.value.currencyCode) &&\n\t\tselector.currency !== price.value.currencyCode\n\t) {\n\t\treturn false;\n\t}\n\n\tif (\n\t\t(selector.channel || price.channel?.id) &&\n\t\tselector.channel !== price.channel?.id\n\t) {\n\t\treturn false;\n\t}\n\n\tif (\n\t\t(selector.customerGroup || price.customerGroup?.id) &&\n\t\tselector.customerGroup !== price.customerGroup?.id\n\t) {\n\t\treturn false;\n\t}\n\n\treturn true;\n};\n","import type {\n\tCategory,\n\tInvalidInputError,\n\tInventoryEntry,\n\tProduct,\n\tProductPagedSearchResponse,\n\tProductProjection,\n\tProductSearchRequest,\n\tProductSearchResult,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"./config.ts\";\nimport { CommercetoolsError } from \"./exceptions.ts\";\nimport { parseSearchQuery } from \"./lib/productSearchFilter.ts\";\nimport { validateSearchQuery } from \"./lib/searchQueryTypeChecker.ts\";\nimport { applyPriceSelector } from \"./priceSelector.ts\";\nimport type { AbstractStorage } from \"./storage/index.ts\";\n\ninterface ProductSearchVariantAvailability {\n\tisOnStock: boolean;\n\tavailableQuantity: number;\n\tisOnStockForChannel: string | undefined;\n}\n\nexport class ProductSearch {\n\tprotected _storage: AbstractStorage;\n\n\tconstructor(config: Config) {\n\t\tthis._storage = config.storage;\n\t}\n\n\tasync search(\n\t\tprojectKey: string,\n\t\tparams: ProductSearchRequest,\n\t): Promise<ProductPagedSearchResponse> {\n\t\tconst inventoryEntries = await this._storage.all(\n\t\t\tprojectKey,\n\t\t\t\"inventory-entry\",\n\t\t);\n\t\tconst availabilityBySku = inventoryEntries.reduce(\n\t\t\t(\n\t\t\t\tacc: Map<string, ProductSearchVariantAvailability>,\n\t\t\t\tentry: InventoryEntry,\n\t\t\t) => {\n\t\t\t\tconst existingEntry = acc.get(entry.sku);\n\n\t\t\t\tacc.set(entry.sku, {\n\t\t\t\t\tisOnStock: existingEntry?.isOnStock || entry.quantityOnStock > 0,\n\t\t\t\t\tavailableQuantity:\n\t\t\t\t\t\texistingEntry?.availableQuantity ?? 0 + entry.quantityOnStock,\n\t\t\t\t\t// NOTE: This doesn't handle inventory entries for multiple channels,\n\t\t\t\t\t// so it doesn't exactly replicate the behavior of the commercetools api.\n\t\t\t\t\tisOnStockForChannel:\n\t\t\t\t\t\texistingEntry?.isOnStockForChannel ?? entry.supplyChannel?.id,\n\t\t\t\t});\n\n\t\t\t\treturn acc;\n\t\t\t},\n\t\t\tnew Map<string, ProductSearchVariantAvailability>(),\n\t\t);\n\n\t\tconst categories = await this._storage.all(projectKey, \"category\");\n\t\tconst categoriesById = categories.reduce(\n\t\t\t(acc: Map<string, Category>, category: Category) => {\n\t\t\t\treturn acc.set(category.id, category);\n\t\t\t},\n\t\t\tnew Map<string, Category>(),\n\t\t);\n\n\t\tconst allProducts = await this._storage.all(projectKey, \"product\");\n\t\tlet productResources = allProducts\n\t\t\t.map((r: Product) =>\n\t\t\t\tthis.transformProduct(\n\t\t\t\t\tr,\n\t\t\t\t\tparams.productProjectionParameters?.staged ?? false,\n\t\t\t\t\tavailabilityBySku,\n\t\t\t\t\tcategoriesById,\n\t\t\t\t),\n\t\t\t)\n\t\t\t.filter((p: ProductProjection) => {\n\t\t\t\tif (!(params.productProjectionParameters?.staged ?? false)) {\n\t\t\t\t\treturn p.published;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t});\n\n\t\tconst markMatchingVariant = params.markMatchingVariants ?? false;\n\n\t\t// Apply filters pre facetting\n\t\tif (params.query) {\n\t\t\ttry {\n\t\t\t\tvalidateSearchQuery(params.query);\n\n\t\t\t\tconst matchFunc = parseSearchQuery(params.query);\n\n\t\t\t\t// Filters can modify the output. So clone the resources first.\n\t\t\t\tproductResources = productResources.filter((resource) =>\n\t\t\t\t\tmatchFunc(resource, markMatchingVariant),\n\t\t\t\t);\n\t\t\t} catch (err) {\n\t\t\t\tthrow new CommercetoolsError<InvalidInputError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidInput\",\n\t\t\t\t\t\tmessage: (err as any).message,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Apply the priceSelector\n\t\tif (params.productProjectionParameters) {\n\t\t\tapplyPriceSelector(productResources, {\n\t\t\t\tcountry: params.productProjectionParameters.priceCountry,\n\t\t\t\tchannel: params.productProjectionParameters.priceChannel,\n\t\t\t\tcustomerGroup: params.productProjectionParameters.priceCustomerGroup,\n\t\t\t\tcurrency: params.productProjectionParameters.priceCurrency,\n\t\t\t});\n\t\t}\n\n\t\t// @TODO: Determine whether or not to spoof search, facet filtering, wildcard, boosting and/or sorting.\n\t\t//        For now this is deliberately not supported.\n\n\t\tconst offset = params.offset || 0;\n\t\tconst limit = params.limit || 20;\n\t\tconst productProjectionsResult = productResources.slice(\n\t\t\toffset,\n\t\t\toffset + limit,\n\t\t);\n\n\t\t/**\n\t\t * Do not supply productProjection if productProjectionParameters are not given\n\t\t * https://docs.commercetools.com/api/projects/product-search#with-product-projection-parameters\n\t\t */\n\t\tconst productProjectionsParameterGiven =\n\t\t\t!!params?.productProjectionParameters;\n\n\t\t// Transform to ProductSearchResult\n\t\tconst results: ProductSearchResult[] = productProjectionsResult.map(\n\t\t\t(product) => ({\n\t\t\t\tproductProjection: productProjectionsParameterGiven\n\t\t\t\t\t? product\n\t\t\t\t\t: undefined,\n\t\t\t\tid: product.id,\n\t\t\t\t/**\n\t\t\t\t * @TODO: possibly add support for optional matchingVariants\n\t\t\t\t * \t\thttps://docs.commercetools.com/api/projects/product-search#productsearchmatchingvariants\n\t\t\t\t */\n\t\t\t}),\n\t\t);\n\n\t\treturn {\n\t\t\ttotal: productResources.length,\n\t\t\toffset: offset,\n\t\t\tlimit: limit,\n\t\t\tresults: results,\n\t\t\tfacets: [],\n\t\t};\n\t}\n\n\ttransformProduct(\n\t\tproduct: Product,\n\t\tstaged: boolean,\n\t\tavailabilityBySku: Map<string, ProductSearchVariantAvailability>,\n\t\tcategoriesById: Map<string, Category>,\n\t): ProductProjection {\n\t\tconst obj = !staged\n\t\t\t? product.masterData.current\n\t\t\t: product.masterData.staged;\n\n\t\tconst getVariantAvailability = (sku?: string) => {\n\t\t\tif (!sku) {\n\t\t\t\treturn {\n\t\t\t\t\tisOnStock: false,\n\t\t\t\t\tavailableQuantity: 0,\n\t\t\t\t\tisOnStockForChannel: undefined,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn (\n\t\t\t\tavailabilityBySku.get(sku) || {\n\t\t\t\t\tisOnStock: false,\n\t\t\t\t\tavailableQuantity: 0,\n\t\t\t\t\tisOnStockForChannel: undefined,\n\t\t\t\t}\n\t\t\t);\n\t\t};\n\n\t\treturn {\n\t\t\tid: product.id,\n\t\t\tcreatedAt: product.createdAt,\n\t\t\tlastModifiedAt: product.lastModifiedAt,\n\t\t\tversion: product.version,\n\t\t\tname: obj.name,\n\t\t\tkey: product.key,\n\t\t\tdescription: obj.description,\n\t\t\tmetaTitle: obj.metaTitle,\n\t\t\tmetaDescription: obj.metaDescription,\n\t\t\tmetaKeywords: obj.metaKeywords,\n\t\t\tsearchKeywords: obj.searchKeywords,\n\t\t\tslug: obj.slug,\n\t\t\tcategories: obj.categories.map((category) => ({\n\t\t\t\t...category,\n\t\t\t\tobj: categoriesById.get(category.id),\n\t\t\t})),\n\t\t\tattributes: obj.attributes,\n\t\t\tmasterVariant: {\n\t\t\t\t...obj.masterVariant,\n\t\t\t\tavailability: getVariantAvailability(obj.masterVariant.sku),\n\t\t\t},\n\t\t\tvariants: obj.variants.map((variant) => ({\n\t\t\t\t...variant,\n\t\t\t\tavailability: getVariantAvailability(variant.sku),\n\t\t\t})),\n\t\t\tproductType: product.productType,\n\t\t\ttaxCategory: product.taxCategory,\n\t\t\tstate: product.state,\n\t\t\tpriceMode: product.priceMode,\n\t\t\thasStagedChanges: product.masterData.hasStagedChanges,\n\t\t\tpublished: product.masterData.published,\n\t\t};\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tAttributeSchema,\n\tCategoryOrderHintsSchema,\n\tCategoryResourceIdentifierSchema,\n\tLocalizedStringSchema,\n\tProductPriceModeEnumSchema,\n\tProductTypeResourceIdentifierSchema,\n\tProductVariantDraftSchema,\n\tSearchKeywordsSchema,\n\tStateResourceIdentifierSchema,\n\tTaxCategoryResourceIdentifierSchema,\n} from \"./common.ts\";\n\nexport const ProductDraftSchema = z.object({\n\tproductType: ProductTypeResourceIdentifierSchema,\n\tname: LocalizedStringSchema,\n\tslug: LocalizedStringSchema,\n\tkey: z.string().nullish(),\n\tdescription: LocalizedStringSchema.nullish(),\n\tcategories: z.array(CategoryResourceIdentifierSchema).nullish(),\n\tcategoryOrderHints: CategoryOrderHintsSchema.nullish(),\n\tmetaTitle: LocalizedStringSchema.nullish(),\n\tmetaDescription: LocalizedStringSchema.nullish(),\n\tmetaKeywords: LocalizedStringSchema.nullish(),\n\tmasterVariant: ProductVariantDraftSchema.nullish(),\n\tvariants: z.array(ProductVariantDraftSchema).nullish(),\n\ttaxCategory: TaxCategoryResourceIdentifierSchema.nullish(),\n\tsearchKeywords: SearchKeywordsSchema.nullish(),\n\tstate: StateResourceIdentifierSchema.nullish(),\n\tpublish: z.boolean().nullish(),\n\tpriceMode: ProductPriceModeEnumSchema.nullish(),\n\tattributes: z.array(AttributeSchema).nullish(),\n});\n","import type {\n\tCategoryReference,\n\tInvalidJsonInputError,\n\tInvalidOperationError,\n\tPrice,\n\tProduct,\n\tProductAddExternalImageAction,\n\tProductAddPriceAction,\n\tProductAddToCategoryAction,\n\tProductAddVariantAction,\n\tProductChangeMasterVariantAction,\n\tProductChangeNameAction,\n\tProductChangePriceAction,\n\tProductChangeSlugAction,\n\tProductData,\n\tProductMoveImageToPositionAction,\n\tProductPublishAction,\n\tProductRemoveFromCategoryAction,\n\tProductRemoveImageAction,\n\tProductRemovePriceAction,\n\tProductRemoveVariantAction,\n\tProductSetAttributeAction,\n\tProductSetAttributeInAllVariantsAction,\n\tProductSetDescriptionAction,\n\tProductSetKeyAction,\n\tProductSetMetaDescriptionAction,\n\tProductSetMetaKeywordsAction,\n\tProductSetMetaTitleAction,\n\tProductSetProductPriceCustomFieldAction,\n\tProductSetProductPriceCustomTypeAction,\n\tProductSetTaxCategoryAction,\n\tProductTransitionStateAction,\n\tProductUpdateAction,\n\tProductVariantDraft,\n\tStateReference,\n\tTaxCategoryReference,\n} from \"@commercetools/platform-sdk\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport type { Writable } from \"#src/types.ts\";\nimport { AbstractUpdateHandler, type RepositoryContext } from \"../abstract.ts\";\nimport {\n\tcreateCustomFields,\n\tgetReferenceFromResourceIdentifier,\n} from \"../helpers.ts\";\nimport {\n\tcheckForStagedChanges,\n\tgetVariant,\n\tpriceFromDraft,\n\tvariantFromDraft,\n} from \"./helpers.ts\";\n\ntype ProductUpdateHandlerMethod<T> = (\n\tcontext: RepositoryContext,\n\tresource: Writable<Product>,\n\taction: T,\n) => void | Promise<void>;\n\ntype ProductUpdateActions = Partial<{\n\t[P in ProductUpdateAction as P[\"action\"]]: ProductUpdateHandlerMethod<P>;\n}>;\n\nexport class ProductUpdateHandler\n\textends AbstractUpdateHandler\n\timplements ProductUpdateActions\n{\n\taddExternalImage(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ variantId, sku, image, staged }: ProductAddExternalImageAction,\n\t) {\n\t\tconst addImg = (data: Writable<ProductData>) => {\n\t\t\tconst { variant, isMasterVariant, variantIndex } = getVariant(\n\t\t\t\tdata,\n\t\t\t\tvariantId,\n\t\t\t\tsku,\n\t\t\t);\n\t\t\tif (!variant) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: `Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (!variant.images) {\n\t\t\t\tvariant.images = [];\n\t\t\t} else {\n\t\t\t\tconst existingImage = variant.images.find((x) => x.url === image.url);\n\t\t\t\tif (existingImage) {\n\t\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\t\tmessage: `Cannot add image '${image.url}' because product '${resource.id}' already has that image.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t400,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Add image\n\t\t\tvariant.images.push(image);\n\n\t\t\tif (isMasterVariant) {\n\t\t\t\tdata.masterVariant = variant;\n\t\t\t} else {\n\t\t\t\tdata.variants[variantIndex] = variant;\n\t\t\t}\n\t\t};\n\n\t\t// If true, only the staged Attribute is set. If false, both current and\n\t\t// staged Attribute is set.  Default is true\n\t\tconst onlyStaged = staged !== undefined ? staged : true;\n\n\t\t// Write the attribute to the staged data\n\t\taddImg(resource.masterData.staged);\n\n\t\t// Also write to published data is isStaged = false\n\t\t// if isStaged is false we set the attribute on both the staged and\n\t\t// published data.\n\t\tif (!onlyStaged) {\n\t\t\taddImg(resource.masterData.current);\n\t\t}\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tasync addPrice(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ variantId, sku, price, staged }: ProductAddPriceAction,\n\t) {\n\t\tconst addVariantPrice = (\n\t\t\tdata: Writable<ProductData>,\n\t\t\tpriceToAdd: Price,\n\t\t) => {\n\t\t\tconst { variant, isMasterVariant, variantIndex } = getVariant(\n\t\t\t\tdata,\n\t\t\t\tvariantId,\n\t\t\t\tsku,\n\t\t\t);\n\t\t\tif (!variant) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: `Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (variant.prices === undefined) {\n\t\t\t\tvariant.prices = [priceToAdd];\n\t\t\t} else {\n\t\t\t\tvariant.prices.push(priceToAdd);\n\t\t\t}\n\n\t\t\tif (isMasterVariant) {\n\t\t\t\tdata.masterVariant = variant;\n\t\t\t} else {\n\t\t\t\tdata.variants[variantIndex] = variant;\n\t\t\t}\n\t\t};\n\n\t\t// Pre-creating the price object ensures consistency between staged and current versions\n\t\tconst priceToAdd = await priceFromDraft(context, this._storage, price);\n\n\t\t// If true, only the staged Attribute is set. If false, both current and\n\t\t// staged Attribute is set.  Default is true\n\t\tconst onlyStaged = staged !== undefined ? staged : true;\n\n\t\t// Write the attribute to the staged data\n\t\taddVariantPrice(resource.masterData.staged, priceToAdd);\n\n\t\t// Also write to published data is isStaged = false\n\t\t// if isStaged is false we set the attribute on both the staged and\n\t\t// published data.\n\t\tif (!onlyStaged) {\n\t\t\taddVariantPrice(resource.masterData.current, priceToAdd);\n\t\t}\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tasync addToCategory(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ category, staged, orderHint }: ProductAddToCategoryAction,\n\t) {\n\t\tconst addCategory = async (data: Writable<ProductData>) => {\n\t\t\tif (category) {\n\t\t\t\tdata.categories.push(\n\t\t\t\t\tawait getReferenceFromResourceIdentifier<CategoryReference>(\n\t\t\t\t\t\tcategory,\n\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\tthis._storage,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthrow new CommercetoolsError<InvalidJsonInputError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidJsonInput\",\n\t\t\t\t\t\tmessage: \"Request body does not contain valid JSON.\",\n\t\t\t\t\t\tdetailedErrorMessage: \"actions -> category: Missing required value\",\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\n\t\tconst onlyStaged = staged !== undefined ? staged : true;\n\n\t\tawait addCategory(resource.masterData.staged);\n\n\t\tif (!onlyStaged) {\n\t\t\tawait addCategory(resource.masterData.current);\n\t\t}\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tasync addVariant(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{\n\t\t\tsku,\n\t\t\tkey,\n\t\t\tprices,\n\t\t\timages,\n\t\t\tattributes,\n\t\t\tstaged,\n\t\t\tassets,\n\t\t}: ProductAddVariantAction,\n\t) {\n\t\tconst variantDraft: ProductVariantDraft = {\n\t\t\tsku: sku,\n\t\t\tkey: key,\n\t\t\tprices: prices,\n\t\t\timages: images,\n\t\t\tattributes: attributes,\n\t\t\tassets: assets,\n\t\t};\n\n\t\tconst dataStaged = resource.masterData.staged;\n\t\tconst allVariants = [\n\t\t\tdataStaged.masterVariant,\n\t\t\t...(dataStaged.variants ?? []),\n\t\t];\n\t\tconst maxId = allVariants.reduce(\n\t\t\t(max, element) => (element.id > max ? element.id : max),\n\t\t\t0,\n\t\t);\n\t\tconst variant = await variantFromDraft(\n\t\t\tcontext,\n\t\t\tthis._storage,\n\t\t\tmaxId + 1,\n\t\t\tvariantDraft,\n\t\t);\n\t\tdataStaged.variants.push(variant);\n\n\t\tconst onlyStaged = staged !== undefined ? staged : true;\n\n\t\tif (!onlyStaged) {\n\t\t\tresource.masterData.current.variants.push(variant);\n\t\t}\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tchangeMasterVariant(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ variantId, sku, staged }: ProductChangeMasterVariantAction,\n\t) {\n\t\tconst setMaster = (data: Writable<ProductData>) => {\n\t\t\tconst { variant, isMasterVariant, variantIndex } = getVariant(\n\t\t\t\tdata,\n\t\t\t\tvariantId,\n\t\t\t\tsku,\n\t\t\t);\n\t\t\tif (!variant) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: `Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (!isMasterVariant) {\n\t\t\t\t// Save previous master variant\n\t\t\t\tconst masterVariantPrev = data.masterVariant;\n\t\t\t\tdata.masterVariant = variant;\n\t\t\t\t// Remove new master from variants\n\t\t\t\tdata.variants.splice(variantIndex, 1);\n\t\t\t\t// Add previous master to variants\n\t\t\t\tdata.variants.push(masterVariantPrev);\n\t\t\t}\n\t\t};\n\n\t\tconst onlyStaged = staged !== undefined ? staged : true;\n\n\t\tsetMaster(resource.masterData.staged);\n\n\t\tif (!onlyStaged) {\n\t\t\tsetMaster(resource.masterData.current);\n\t\t}\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tchangeName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ name, staged }: ProductChangeNameAction,\n\t) {\n\t\tconst onlyStaged = staged !== undefined ? staged : true;\n\t\tresource.masterData.staged.name = name;\n\t\tif (!onlyStaged) {\n\t\t\tresource.masterData.current.name = name;\n\t\t}\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tchangePrice(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ priceId, price, staged }: ProductChangePriceAction,\n\t) {\n\t\tconst changeVariantPrice = (data: Writable<ProductData>) => {\n\t\t\tconst allVariants = [data.masterVariant, ...(data.variants ?? [])];\n\t\t\tconst priceVariant = allVariants.find((variant) =>\n\t\t\t\tvariant.prices?.some((x) => x.id === priceId),\n\t\t\t);\n\t\t\tif (!priceVariant) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: `Price with id ${priceId} not found on product ${resource.id}`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst { variant, isMasterVariant, variantIndex } = getVariant(\n\t\t\t\tdata,\n\t\t\t\tpriceVariant.id,\n\t\t\t\tpriceVariant.sku,\n\t\t\t);\n\t\t\tif (!variant) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: `Variant with id ${priceVariant.id} or sku ${priceVariant.sku} not found on product ${resource.id}`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tvariant.prices = variant.prices?.map((x) => {\n\t\t\t\tif (x.id === priceId) {\n\t\t\t\t\treturn { ...x, ...price } as Price;\n\t\t\t\t}\n\t\t\t\treturn x;\n\t\t\t});\n\n\t\t\tif (isMasterVariant) {\n\t\t\t\tdata.masterVariant = variant;\n\t\t\t} else {\n\t\t\t\tdata.variants[variantIndex] = variant;\n\t\t\t}\n\t\t};\n\n\t\t// If true, only the staged Attribute is set. If false, both current and\n\t\t// staged Attribute is set.  Default is true\n\t\tconst onlyStaged = staged !== undefined ? staged : true;\n\n\t\t// Write the attribute to the staged data\n\t\tchangeVariantPrice(resource.masterData.staged);\n\n\t\t// Also write to published data is isStaged = false\n\t\t// if isStaged is false we set the attribute on both the staged and\n\t\t// published data.\n\t\tif (!onlyStaged) {\n\t\t\tchangeVariantPrice(resource.masterData.current);\n\t\t}\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tchangeSlug(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ slug, staged }: ProductChangeSlugAction,\n\t) {\n\t\tconst onlyStaged = staged !== undefined ? staged : true;\n\t\tresource.masterData.staged.slug = slug;\n\t\tif (!onlyStaged) {\n\t\t\tresource.masterData.current.slug = slug;\n\t\t}\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tmoveImageToPosition(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{\n\t\t\tvariantId,\n\t\t\tsku,\n\t\t\timageUrl,\n\t\t\tposition,\n\t\t\tstaged,\n\t\t}: ProductMoveImageToPositionAction,\n\t) {\n\t\tconst moveImg = (data: Writable<ProductData>) => {\n\t\t\tconst { variant, isMasterVariant, variantIndex } = getVariant(\n\t\t\t\tdata,\n\t\t\t\tvariantId,\n\t\t\t\tsku,\n\t\t\t);\n\t\t\tif (!variant) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: `Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst variantImages = variant.images ?? [];\n\t\t\tconst existingImage = variantImages.find((x) => x.url === imageUrl);\n\t\t\tif (!existingImage) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: `Cannot move image '${imageUrl}' because product '${resource.id}' does not have that image.`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (position >= variantImages.length) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\"Invalid position given. Position in images where the image should be moved. Must be between 0 and the total number of images minus 1.\",\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Remove image\n\t\t\tvariant.images = variantImages.filter((image) => image.url !== imageUrl);\n\n\t\t\t// Re-add image to the correct position\n\t\t\tvariant.images.splice(position, 0, existingImage);\n\n\t\t\tif (isMasterVariant) {\n\t\t\t\tdata.masterVariant = variant;\n\t\t\t} else {\n\t\t\t\tdata.variants[variantIndex] = variant;\n\t\t\t}\n\t\t};\n\n\t\t// If true, only the staged Attribute is set. If false, both current and\n\t\t// staged Attribute is set.  Default is true\n\t\tconst onlyStaged = staged !== undefined ? staged : true;\n\n\t\t// Write the attribute to the staged data\n\t\tmoveImg(resource.masterData.staged);\n\n\t\t// Also write to published data is isStaged = false\n\t\t// if isStaged is false we set the attribute on both the staged and\n\t\t// published data.\n\t\tif (!onlyStaged) {\n\t\t\tmoveImg(resource.masterData.current);\n\t\t}\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tpublish(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ scope }: ProductPublishAction,\n\t) {\n\t\tresource.masterData.current = resource.masterData.staged;\n\t\tresource.masterData.published = true;\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tasync removeFromCategory(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ category, staged }: ProductRemoveFromCategoryAction,\n\t) {\n\t\tconst removeCategory = async (data: Writable<ProductData>) => {\n\t\t\tif (category) {\n\t\t\t\tconst resolvedCategory =\n\t\t\t\t\tawait getReferenceFromResourceIdentifier<CategoryReference>(\n\t\t\t\t\t\tcategory,\n\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\tthis._storage,\n\t\t\t\t\t);\n\n\t\t\t\tconst foundCategory = data.categories.find(\n\t\t\t\t\t(productCategory: CategoryReference) => {\n\t\t\t\t\t\tif (productCategory.id === resolvedCategory.id) {\n\t\t\t\t\t\t\treturn productCategory;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t},\n\t\t\t\t);\n\n\t\t\t\tif (!foundCategory) {\n\t\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\t`Cannot remove from category '${resolvedCategory.id}' because product ` +\n\t\t\t\t\t\t\t\t`'${resource.masterData.current.name}' is not in that category.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t400,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tdata.categories = data.categories.filter(\n\t\t\t\t\t(productCategory: CategoryReference) => {\n\t\t\t\t\t\tif (productCategory.id === resolvedCategory.id) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthrow new CommercetoolsError<InvalidJsonInputError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidJsonInput\",\n\t\t\t\t\t\tmessage: \"Request body does not contain valid JSON.\",\n\t\t\t\t\t\tdetailedErrorMessage: \"actions -> category: Missing required value\",\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\n\t\tconst onlyStaged = staged !== undefined ? staged : true;\n\t\tawait removeCategory(resource.masterData.staged);\n\n\t\tif (!onlyStaged) {\n\t\t\tawait removeCategory(resource.masterData.current);\n\t\t}\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tremoveImage(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ variantId, sku, imageUrl, staged }: ProductRemoveImageAction,\n\t) {\n\t\tconst removeImg = (data: Writable<ProductData>) => {\n\t\t\tconst { variant, isMasterVariant, variantIndex } = getVariant(\n\t\t\t\tdata,\n\t\t\t\tvariantId,\n\t\t\t\tsku,\n\t\t\t);\n\t\t\tif (!variant) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: `Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst variantImages = variant.images ?? [];\n\t\t\tconst existingImage = variantImages.find((x) => x.url === imageUrl);\n\t\t\tif (!existingImage) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: `Cannot remove image '${imageUrl}' because product '${resource.id}' does not have that image.`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Remove image\n\t\t\tvariant.images = variantImages.filter((image) => image.url !== imageUrl);\n\n\t\t\tif (isMasterVariant) {\n\t\t\t\tdata.masterVariant = variant;\n\t\t\t} else {\n\t\t\t\tdata.variants[variantIndex] = variant;\n\t\t\t}\n\t\t};\n\n\t\t// If true, only the staged Attribute is set. If false, both current and\n\t\t// staged Attribute is set.  Default is true\n\t\tconst onlyStaged = staged !== undefined ? staged : true;\n\n\t\t// Write the attribute to the staged data\n\t\tremoveImg(resource.masterData.staged);\n\n\t\t// Also write to published data is isStaged = false\n\t\t// if isStaged is false we set the attribute on both the staged and\n\t\t// published data.\n\t\tif (!onlyStaged) {\n\t\t\tremoveImg(resource.masterData.current);\n\t\t}\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tremovePrice(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ priceId, staged }: ProductRemovePriceAction,\n\t) {\n\t\tconst removeVariantPrice = (data: Writable<ProductData>) => {\n\t\t\tconst allVariants = [data.masterVariant, ...(data.variants ?? [])];\n\t\t\tconst priceVariant = allVariants.find((variant) =>\n\t\t\t\tvariant.prices?.some((x) => x.id === priceId),\n\t\t\t);\n\t\t\tif (!priceVariant) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: `Price with id ${priceId} not found on product ${resource.id}`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst { variant, isMasterVariant, variantIndex } = getVariant(\n\t\t\t\tdata,\n\t\t\t\tpriceVariant.id,\n\t\t\t\tpriceVariant.sku,\n\t\t\t);\n\t\t\tif (!variant) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: `Variant with id ${priceVariant.id} or sku ${priceVariant.sku} not found on product ${resource.id}`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tvariant.prices = variant.prices?.filter((x) => x.id !== priceId);\n\n\t\t\tif (isMasterVariant) {\n\t\t\t\tdata.masterVariant = variant;\n\t\t\t} else {\n\t\t\t\tdata.variants[variantIndex] = variant;\n\t\t\t}\n\t\t};\n\n\t\t// If true, only the staged Attribute is set. If false, both current and\n\t\t// staged Attribute is set.  Default is true\n\t\tconst onlyStaged = staged !== undefined ? staged : true;\n\n\t\t// Write the attribute to the staged data\n\t\tremoveVariantPrice(resource.masterData.staged);\n\n\t\t// Also write to published data is isStaged = false\n\t\t// if isStaged is false we set the attribute on both the staged and\n\t\t// published data.\n\t\tif (!onlyStaged) {\n\t\t\tremoveVariantPrice(resource.masterData.current);\n\t\t}\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tremoveVariant(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ id, sku, staged }: ProductRemoveVariantAction,\n\t) {\n\t\tconst removeVariant = (data: Writable<ProductData>) => {\n\t\t\tconst { variant, isMasterVariant, variantIndex } = getVariant(\n\t\t\t\tdata,\n\t\t\t\tid,\n\t\t\t\tsku,\n\t\t\t);\n\t\t\tif (!variant) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: `Variant with id ${id} or sku ${sku} not found on product ${resource.id}`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (isMasterVariant) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: `Can not remove the variant [ID:${id}] for [Product:${resource.id}] since it's the master variant`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tdata.variants.splice(variantIndex, 1);\n\t\t};\n\n\t\tconst onlyStaged = staged !== undefined ? staged : true;\n\n\t\tremoveVariant(resource.masterData.staged);\n\n\t\tif (!onlyStaged) {\n\t\t\tremoveVariant(resource.masterData.current);\n\t\t}\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tsetAttribute(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ variantId, sku, name, value, staged }: ProductSetAttributeAction,\n\t) {\n\t\tconst setAttr = (data: Writable<ProductData>) => {\n\t\t\tconst { variant, isMasterVariant, variantIndex } = getVariant(\n\t\t\t\tdata,\n\t\t\t\tvariantId,\n\t\t\t\tsku,\n\t\t\t);\n\t\t\tif (!variant) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: `Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (!variant.attributes) {\n\t\t\t\tvariant.attributes = [];\n\t\t\t}\n\n\t\t\tconst existingAttr = variant.attributes.find(\n\t\t\t\t(attr) => attr.name === name,\n\t\t\t);\n\t\t\tif (existingAttr) {\n\t\t\t\texistingAttr.value = value;\n\t\t\t} else {\n\t\t\t\tvariant.attributes.push({\n\t\t\t\t\tname,\n\t\t\t\t\tvalue,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (isMasterVariant) {\n\t\t\t\tdata.masterVariant = variant;\n\t\t\t} else {\n\t\t\t\tdata.variants[variantIndex] = variant;\n\t\t\t}\n\t\t};\n\n\t\t// If true, only the staged Attribute is set. If false, both current and\n\t\t// staged Attribute is set.  Default is true\n\t\tconst onlyStaged = staged !== undefined ? staged : true;\n\n\t\t// Write the attribute to the staged data\n\t\tsetAttr(resource.masterData.staged);\n\n\t\t// Also write to published data is isStaged = false\n\t\t// if isStaged is false we set the attribute on both the staged and\n\t\t// published data.\n\t\tif (!onlyStaged) {\n\t\t\tsetAttr(resource.masterData.current);\n\t\t}\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tsetAttributeInAllVariants(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ name, value, staged }: ProductSetAttributeInAllVariantsAction,\n\t) {\n\t\tconst setAttrInAllVariants = (data: Writable<ProductData>) => {\n\t\t\tif (!data.masterVariant.attributes) {\n\t\t\t\tdata.masterVariant.attributes = [];\n\t\t\t}\n\n\t\t\tconst existingAttr = data.masterVariant.attributes?.find(\n\t\t\t\t(attr) => attr.name === name,\n\t\t\t);\n\n\t\t\tif (existingAttr) {\n\t\t\t\texistingAttr.value = value;\n\t\t\t} else {\n\t\t\t\tdata.masterVariant.attributes.push({\n\t\t\t\t\tname,\n\t\t\t\t\tvalue,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tdata.variants.forEach((variant) => {\n\t\t\t\tif (!variant.attributes) {\n\t\t\t\t\tvariant.attributes = [];\n\t\t\t\t}\n\n\t\t\t\tconst existingAttr = variant.attributes.find(\n\t\t\t\t\t(attr) => attr.name === name,\n\t\t\t\t);\n\t\t\t\tif (existingAttr) {\n\t\t\t\t\texistingAttr.value = value;\n\t\t\t\t} else {\n\t\t\t\t\tvariant.attributes.push({\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tvalue,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t};\n\n\t\t// If true, only the staged Attribute is set. If false, both current and\n\t\t// staged Attribute is set.  Default is true\n\t\tconst onlyStaged = staged !== undefined ? staged : true;\n\n\t\t// Write the attribute to the staged data\n\t\tsetAttrInAllVariants(resource.masterData.staged);\n\n\t\t// Also write to published data is isStaged = false\n\t\t// if isStaged is false we set the attribute on both the staged and\n\t\t// published data.\n\t\tif (!onlyStaged) {\n\t\t\tsetAttrInAllVariants(resource.masterData.current);\n\t\t}\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tsetDescription(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ description, staged }: ProductSetDescriptionAction,\n\t) {\n\t\tconst onlyStaged = staged !== undefined ? staged : true;\n\n\t\tresource.masterData.staged.description = description;\n\t\tif (!onlyStaged) {\n\t\t\tresource.masterData.current.description = description;\n\t\t}\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tsetKey(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ key }: ProductSetKeyAction,\n\t) {\n\t\tresource.key = key;\n\t}\n\n\tsetMetaDescription(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ metaDescription, staged }: ProductSetMetaDescriptionAction,\n\t) {\n\t\tconst onlyStaged = staged !== undefined ? staged : true;\n\t\tresource.masterData.staged.metaDescription = metaDescription;\n\t\tif (!onlyStaged) {\n\t\t\tresource.masterData.current.metaDescription = metaDescription;\n\t\t}\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tsetMetaKeywords(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ metaKeywords, staged }: ProductSetMetaKeywordsAction,\n\t) {\n\t\tconst onlyStaged = staged !== undefined ? staged : true;\n\t\tresource.masterData.staged.metaKeywords = metaKeywords;\n\t\tif (!onlyStaged) {\n\t\t\tresource.masterData.current.metaKeywords = metaKeywords;\n\t\t}\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tsetMetaTitle(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ metaTitle, staged }: ProductSetMetaTitleAction,\n\t) {\n\t\tconst onlyStaged = staged !== undefined ? staged : true;\n\t\tresource.masterData.staged.metaTitle = metaTitle;\n\t\tif (!onlyStaged) {\n\t\t\tresource.masterData.current.metaTitle = metaTitle;\n\t\t}\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tsetProductPriceCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ name, value, staged, priceId }: ProductSetProductPriceCustomFieldAction,\n\t) {\n\t\tconst updatePriceCustomFields = (data: Writable<ProductData>) => {\n\t\t\tconst price = [data.masterVariant, ...(data.variants ?? [])]\n\t\t\t\t.flatMap((variant) => variant.prices ?? [])\n\t\t\t\t.find((price) => price.id === priceId);\n\n\t\t\tif (!price) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: `Price with id ${priceId} not found on product ${resource.id}`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (price.custom) {\n\t\t\t\tif (value === null) {\n\t\t\t\t\tdelete price.custom.fields[name];\n\t\t\t\t} else {\n\t\t\t\t\tprice.custom.fields[name] = value;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn data;\n\t\t};\n\n\t\tresource.masterData.staged = updatePriceCustomFields(\n\t\t\tresource.masterData.staged,\n\t\t);\n\n\t\tconst onlyStaged = staged !== undefined ? staged : true;\n\t\tif (!onlyStaged) {\n\t\t\tresource.masterData.current = updatePriceCustomFields(\n\t\t\t\tresource.masterData.current,\n\t\t\t);\n\t\t}\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tasync setProductPriceCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ type, fields, staged, priceId }: ProductSetProductPriceCustomTypeAction,\n\t) {\n\t\tconst updatePriceCustomType = async (data: Writable<ProductData>) => {\n\t\t\tconst price = [data.masterVariant, ...(data.variants ?? [])]\n\t\t\t\t.flatMap((variant) => variant.prices ?? [])\n\t\t\t\t.find((price) => price.id === priceId);\n\n\t\t\tif (price) {\n\t\t\t\tif (type) {\n\t\t\t\t\tprice.custom = await createCustomFields(\n\t\t\t\t\t\t{ type, fields },\n\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\tthis._storage,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tprice.custom = undefined;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: `Price with id ${priceId} not found on product ${resource.id}`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn data;\n\t\t};\n\n\t\tresource.masterData.staged = await updatePriceCustomType(\n\t\t\tresource.masterData.staged,\n\t\t);\n\n\t\tconst onlyStaged = staged !== undefined ? staged : true;\n\t\tif (!onlyStaged) {\n\t\t\tresource.masterData.current = await updatePriceCustomType(\n\t\t\t\tresource.masterData.current,\n\t\t\t);\n\t\t}\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\tasync setTaxCategory(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ taxCategory }: ProductSetTaxCategoryAction,\n\t) {\n\t\tlet taxCategoryReference: TaxCategoryReference | undefined;\n\t\tif (taxCategory) {\n\t\t\ttaxCategoryReference =\n\t\t\t\tawait getReferenceFromResourceIdentifier<TaxCategoryReference>(\n\t\t\t\t\ttaxCategory,\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tthis._storage,\n\t\t\t\t);\n\t\t} else {\n\t\t\tthrow new CommercetoolsError<InvalidJsonInputError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidJsonInput\",\n\t\t\t\t\tmessage: \"Request body does not contain valid JSON.\",\n\t\t\t\t\tdetailedErrorMessage:\n\t\t\t\t\t\t\"actions -> taxCategory: Missing required value\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tresource.taxCategory = taxCategoryReference;\n\t}\n\n\tasync transitionState(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t{ state, force }: ProductTransitionStateAction,\n\t) {\n\t\tlet productStateReference: StateReference | undefined;\n\t\tif (state) {\n\t\t\tproductStateReference =\n\t\t\t\tawait getReferenceFromResourceIdentifier<StateReference>(\n\t\t\t\t\tstate,\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tthis._storage,\n\t\t\t\t);\n\t\t\tresource.state = productStateReference;\n\t\t} else {\n\t\t\tthrow new CommercetoolsError<InvalidJsonInputError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidJsonInput\",\n\t\t\t\t\tmessage: \"Request body does not contain valid JSON.\",\n\t\t\t\t\tdetailedErrorMessage: \"actions -> state: Missing required value\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t}\n\n\tunpublish(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Product>,\n\t\t// { action }: ProductUnpublishAction\n\t) {\n\t\tresource.masterData.published = false;\n\t\tcheckForStagedChanges(resource);\n\t}\n\n\t// 'setPrices': () => {},\n\t// 'setDiscountedPrice': () => {},\n\t// 'setAttributeInAllVariants': () => {},\n\t// 'setCategoryOrderHint': () => {},\n\t// 'setSku': () => {},\n\t// 'setProductVariantKey': () => {},\n\t// 'setImageLabel': () => {},\n\t// 'addAsset': () => {},\n\t// 'removeAsset': () => {},\n\t// 'setAssetKey': () => {},\n\t// 'changeAssetOrder': () => {},\n\t// 'changeAssetName': () => {},\n\t// 'setAssetDescription': () => {},\n\t// 'setAssetTags': () => {},\n\t// 'setAssetSources': () => {},\n\t// 'setAssetCustomType': () => {},\n\t// 'setAssetCustomField': () => {},\n\t// 'setSearchKeywords': () => {},\n\t// 'revertStagedChanges': () => {},\n\t// 'revertStagedVariantChanges': () => {},\n}\n","import type {\n\tCategoryReference,\n\tInvalidJsonInputError,\n\tProduct,\n\tProductData,\n\tProductDraft,\n\tProductPagedSearchResponse,\n\tProductSearchRequest,\n\tProductTypeReference,\n\tRequiredFieldError,\n\tStateReference,\n\tTaxCategoryReference,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { getBaseResourceProperties } from \"#src/helpers.ts\";\nimport { ReviewStatisticsService } from \"#src/lib/review-statistics.ts\";\nimport { ProductSearch } from \"#src/product-search.ts\";\nimport { ProductDraftSchema } from \"#src/schemas/generated/product.ts\";\nimport type { GetParams, RepositoryContext } from \"../abstract.ts\";\nimport { AbstractResourceRepository } from \"../abstract.ts\";\nimport { getReferenceFromResourceIdentifier } from \"../helpers.ts\";\nimport { ProductUpdateHandler } from \"./actions.ts\";\nimport { variantFromDraft } from \"./helpers.ts\";\n\nexport class ProductRepository extends AbstractResourceRepository<\"product\"> {\n\tprotected _searchService: ProductSearch;\n\tprotected _reviewStatisticsService: ReviewStatisticsService;\n\n\tconstructor(config: Config) {\n\t\tsuper(\"product\", config);\n\t\tthis.actions = new ProductUpdateHandler(config.storage);\n\t\tthis._searchService = new ProductSearch(config);\n\t\tthis._reviewStatisticsService = new ReviewStatisticsService(config.storage);\n\t\tthis.draftSchema = ProductDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: ProductDraft,\n\t): Promise<Product> {\n\t\tif (!draft.masterVariant) {\n\t\t\tthrow new CommercetoolsError<RequiredFieldError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"RequiredField\",\n\t\t\t\t\tmessage: \"Missing master variant\",\n\t\t\t\t\tfield: \"masterVariant\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\tlet productType: ProductTypeReference | undefined;\n\t\ttry {\n\t\t\tproductType =\n\t\t\t\tawait getReferenceFromResourceIdentifier<ProductTypeReference>(\n\t\t\t\t\tdraft.productType,\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tthis._storage,\n\t\t\t\t);\n\t\t} catch (err) {\n\t\t\tif (this.config.strict) {\n\t\t\t\tthrow err;\n\t\t\t}\n\n\t\t\t// For now accept missing product types (but warn)\n\t\t\tprocess.emitWarning(\n\t\t\t\t`Error resolving product-type '${draft.productType.id}'. This will throw an error in later releases.`,\n\t\t\t);\n\t\t\tproductType = {\n\t\t\t\ttypeId: \"product-type\",\n\t\t\t\tid: draft.productType.id || \"\",\n\t\t\t};\n\t\t}\n\n\t\t// Resolve Product categories\n\t\tconst categoryReferences: CategoryReference[] = [];\n\t\tfor (const category of draft.categories ?? []) {\n\t\t\tif (category) {\n\t\t\t\tcategoryReferences.push(\n\t\t\t\t\tawait getReferenceFromResourceIdentifier<CategoryReference>(\n\t\t\t\t\t\tcategory,\n\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\tthis._storage,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthrow new CommercetoolsError<InvalidJsonInputError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidJsonInput\",\n\t\t\t\t\t\tmessage: \"Request body does not contain valid JSON.\",\n\t\t\t\t\t\tdetailedErrorMessage: \"categories: JSON object expected.\",\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Resolve Tax category\n\t\tlet taxCategoryReference: TaxCategoryReference | undefined;\n\t\tif (draft.taxCategory) {\n\t\t\ttaxCategoryReference =\n\t\t\t\tawait getReferenceFromResourceIdentifier<TaxCategoryReference>(\n\t\t\t\t\tdraft.taxCategory,\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tthis._storage,\n\t\t\t\t);\n\t\t}\n\n\t\t// Resolve Product State\n\t\tlet productStateReference: StateReference | undefined;\n\t\tif (draft.state) {\n\t\t\tproductStateReference =\n\t\t\t\tawait getReferenceFromResourceIdentifier<StateReference>(\n\t\t\t\t\tdraft.state,\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tthis._storage,\n\t\t\t\t);\n\t\t}\n\n\t\tconst variants = await Promise.all(\n\t\t\tdraft.variants?.map((variant, index) =>\n\t\t\t\tvariantFromDraft(context, this._storage, index + 2, variant),\n\t\t\t) ?? [],\n\t\t);\n\n\t\tconst productData: ProductData = {\n\t\t\tname: draft.name,\n\t\t\tslug: draft.slug,\n\t\t\tdescription: draft.description,\n\t\t\tattributes: draft.attributes ?? [],\n\t\t\tcategories: categoryReferences,\n\t\t\tmasterVariant: await variantFromDraft(\n\t\t\t\tcontext,\n\t\t\t\tthis._storage,\n\t\t\t\t1,\n\t\t\t\tdraft.masterVariant,\n\t\t\t),\n\t\t\tvariants,\n\t\t\tmetaTitle: draft.metaTitle,\n\t\t\tmetaDescription: draft.metaDescription,\n\t\t\tmetaKeywords: draft.metaKeywords,\n\t\t\tsearchKeywords: draft.searchKeywords ?? {},\n\t\t};\n\n\t\tconst resource: Product = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tkey: draft.key,\n\t\t\tproductType: productType,\n\t\t\ttaxCategory: taxCategoryReference,\n\t\t\tstate: productStateReference,\n\t\t\tmasterData: {\n\t\t\t\tcurrent: productData,\n\t\t\t\tstaged: productData,\n\t\t\t\thasStagedChanges: false,\n\t\t\t\tpublished: draft.publish ?? false,\n\t\t\t},\n\t\t};\n\n\t\treturn await this.saveNew(context, resource);\n\t}\n\n\tasync postProcessResource(\n\t\tcontext: RepositoryContext,\n\t\tresource: Product,\n\t\tparams?: GetParams,\n\t): Promise<Product> {\n\t\t// Add review statistics to the product\n\t\tconst reviewStatistics =\n\t\t\tawait this._reviewStatisticsService.calculateProductReviewStatistics(\n\t\t\t\tcontext.projectKey,\n\t\t\t\tresource.id,\n\t\t\t);\n\n\t\treturn {\n\t\t\t...resource,\n\t\t\treviewRatingStatistics: reviewStatistics,\n\t\t};\n\t}\n\n\tasync search(\n\t\tcontext: RepositoryContext,\n\t\tsearchRequest: ProductSearchRequest,\n\t): Promise<ProductPagedSearchResponse> {\n\t\treturn this._searchService.search(context.projectKey, searchRequest);\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tLocalizedStringSchema,\n\tProductDiscountValueDraftSchema,\n} from \"./common.ts\";\n\nexport const ProductDiscountDraftSchema = z.object({\n\tname: LocalizedStringSchema,\n\tkey: z.string().nullish(),\n\tdescription: LocalizedStringSchema.nullish(),\n\tvalue: ProductDiscountValueDraftSchema,\n\tpredicate: z.string(),\n\tsortOrder: z.string(),\n\tisActive: z.boolean(),\n\tvalidFrom: z.string().nullish(),\n\tvalidUntil: z.string().nullish(),\n});\n","import type {\n\tProductDiscount,\n\tProductDiscountChangeIsActiveAction,\n\tProductDiscountChangeNameAction,\n\tProductDiscountChangePredicateAction,\n\tProductDiscountChangeSortOrderAction,\n\tProductDiscountChangeValueAction,\n\tProductDiscountDraft,\n\tProductDiscountSetDescriptionAction,\n\tProductDiscountSetKeyAction,\n\tProductDiscountSetValidFromAction,\n\tProductDiscountSetValidFromAndUntilAction,\n\tProductDiscountSetValidUntilAction,\n\tProductDiscountUpdateAction,\n\tProductDiscountValue,\n\tProductDiscountValueAbsolute,\n\tProductDiscountValueDraft,\n\tProductDiscountValueExternal,\n\tProductDiscountValueRelative,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { ProductDiscountDraftSchema } from \"#src/schemas/generated/product-discount.ts\";\nimport { getBaseResourceProperties } from \"../helpers.ts\";\nimport type { Writable } from \"../types.ts\";\nimport type { RepositoryContext, UpdateHandlerInterface } from \"./abstract.ts\";\nimport {\n\tAbstractResourceRepository,\n\tAbstractUpdateHandler,\n} from \"./abstract.ts\";\nimport { createTypedMoney } from \"./helpers.ts\";\n\nexport class ProductDiscountRepository extends AbstractResourceRepository<\"product-discount\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"product-discount\", config);\n\t\tthis.actions = new ProductDiscountUpdateHandler(this._storage);\n\t\tthis.draftSchema = ProductDiscountDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: ProductDiscountDraft,\n\t): Promise<ProductDiscount> {\n\t\tconst resource: ProductDiscount = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tkey: draft.key,\n\t\t\tname: draft.name,\n\t\t\tdescription: draft.description,\n\t\t\tvalue: transformValueDraft(draft.value),\n\t\t\tpredicate: draft.predicate,\n\t\t\tsortOrder: draft.sortOrder,\n\t\t\tisActive: draft.isActive || false,\n\t\t\tvalidFrom: draft.validFrom,\n\t\t\tvalidUntil: draft.validUntil,\n\t\t\treferences: [],\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n\nconst transformValueDraft = (\n\tvalue: ProductDiscountValueDraft,\n): ProductDiscountValue => {\n\tswitch (value.type) {\n\t\tcase \"absolute\": {\n\t\t\treturn {\n\t\t\t\ttype: \"absolute\",\n\t\t\t\tmoney: value.money.map(createTypedMoney),\n\t\t\t} as ProductDiscountValueAbsolute;\n\t\t}\n\t\tcase \"external\": {\n\t\t\treturn {\n\t\t\t\ttype: \"external\",\n\t\t\t} as ProductDiscountValueExternal;\n\t\t}\n\t\tcase \"relative\": {\n\t\t\treturn {\n\t\t\t\t...value,\n\t\t\t} as ProductDiscountValueRelative;\n\t\t}\n\t}\n};\n\nexport class ProductDiscountUpdateHandler\n\textends AbstractUpdateHandler\n\timplements\n\t\tUpdateHandlerInterface<ProductDiscount, ProductDiscountUpdateAction>\n{\n\tchangeIsActive(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ProductDiscount>,\n\t\t{ isActive }: ProductDiscountChangeIsActiveAction,\n\t) {\n\t\tresource.isActive = isActive;\n\t}\n\n\tchangeName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ProductDiscount>,\n\t\t{ name }: ProductDiscountChangeNameAction,\n\t) {\n\t\tresource.name = name;\n\t}\n\n\tchangePredicate(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ProductDiscount>,\n\t\t{ predicate }: ProductDiscountChangePredicateAction,\n\t) {\n\t\tresource.predicate = predicate;\n\t}\n\n\tchangeSortOrder(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ProductDiscount>,\n\t\t{ sortOrder }: ProductDiscountChangeSortOrderAction,\n\t) {\n\t\tresource.sortOrder = sortOrder;\n\t}\n\n\tchangeValue(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ProductDiscount>,\n\t\t{ value }: ProductDiscountChangeValueAction,\n\t) {\n\t\tresource.value = transformValueDraft(value);\n\t}\n\n\tsetDescription(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ProductDiscount>,\n\t\t{ description }: ProductDiscountSetDescriptionAction,\n\t) {\n\t\tif (description && Object.keys(description).length > 0) {\n\t\t\tresource.description = description;\n\t\t} else {\n\t\t\tresource.description = undefined;\n\t\t}\n\t}\n\n\tsetKey(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ProductDiscount>,\n\t\t{ key }: ProductDiscountSetKeyAction,\n\t) {\n\t\tresource.key = key;\n\t}\n\n\tsetValidFrom(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ProductDiscount>,\n\t\t{ validFrom }: ProductDiscountSetValidFromAction,\n\t) {\n\t\tresource.validFrom = validFrom;\n\t}\n\n\tsetValidFromAndUntil(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ProductDiscount>,\n\t\t{ validFrom, validUntil }: ProductDiscountSetValidFromAndUntilAction,\n\t) {\n\t\tresource.validFrom = validFrom;\n\t\tresource.validUntil = validUntil;\n\t}\n\n\tsetValidUntil(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ProductDiscount>,\n\t\t{ validUntil }: ProductDiscountSetValidUntilAction,\n\t) {\n\t\tresource.validUntil = validUntil;\n\t}\n}\n","import type {\n\tFacetResults,\n\tFilteredFacetResult,\n\tInvalidInputError,\n\tInvalidOperationError,\n\tProduct,\n\tProductProjection,\n\tProductProjectionPagedSearchResponse,\n\tQueryParam,\n\tRangeFacetResult,\n\tTermFacetResult,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"./config.ts\";\nimport { CommercetoolsError } from \"./exceptions.ts\";\nimport { nestedLookup } from \"./helpers.ts\";\nimport type {\n\tFilterExpression,\n\tRangeExpression,\n} from \"./lib/projectionSearchFilter.ts\";\nimport {\n\tgenerateFacetFunc,\n\tgetVariants,\n\tparseFilterExpression,\n\tresolveVariantValue,\n} from \"./lib/projectionSearchFilter.ts\";\nimport { ReviewStatisticsService } from \"./lib/review-statistics.ts\";\nimport { applyPriceSelector } from \"./priceSelector.ts\";\nimport type { AbstractStorage } from \"./storage/index.ts\";\nimport type { Writable } from \"./types.ts\";\n\nexport type ProductProjectionSearchParams = {\n\tfuzzy?: boolean;\n\tfuzzyLevel?: number;\n\tmarkMatchingVariants?: boolean;\n\tstaged?: boolean;\n\tfilter?: string[];\n\t\"filter.facets\"?: string[];\n\t\"filter.query\"?: string[];\n\tfacet?: string | string[];\n\tsort?: string | string[];\n\tlimit?: number;\n\toffset?: number;\n\twithTotal?: boolean;\n\tpriceCurrency?: string;\n\tpriceCountry?: string;\n\tpriceCustomerGroup?: string;\n\tpriceChannel?: string;\n\tlocaleProjection?: string;\n\tstoreProjection?: string;\n\texpand?: string | string[];\n\t[key: string]: QueryParam;\n};\n\nexport class ProductProjectionSearch {\n\tprotected _storage: AbstractStorage;\n\tprotected _reviewStatisticsService: ReviewStatisticsService;\n\n\tconstructor(config: Config) {\n\t\tthis._storage = config.storage;\n\t\tthis._reviewStatisticsService = new ReviewStatisticsService(config.storage);\n\t}\n\n\tasync search(\n\t\tprojectKey: string,\n\t\tparams: ProductProjectionSearchParams,\n\t): Promise<ProductProjectionPagedSearchResponse> {\n\t\tconst allProducts = await this._storage.all(projectKey, \"product\");\n\t\tlet resources = await Promise.all(\n\t\t\tallProducts.map((r) =>\n\t\t\t\tthis.transform(r, params.staged ?? false, projectKey),\n\t\t\t),\n\t\t);\n\t\tresources = resources.filter((p) => {\n\t\t\tif (!(params.staged ?? false)) {\n\t\t\t\treturn p.published;\n\t\t\t}\n\t\t\treturn true;\n\t\t});\n\n\t\tconst markMatchingVariant = params.markMatchingVariants ?? false;\n\n\t\t// Apply the priceSelector\n\t\tapplyPriceSelector(resources, {\n\t\t\tcountry: params.priceCountry,\n\t\t\tchannel: params.priceChannel,\n\t\t\tcustomerGroup: params.priceCustomerGroup,\n\t\t\tcurrency: params.priceCurrency,\n\t\t});\n\n\t\t// Apply filters pre faceting\n\t\tif (params.filter) {\n\t\t\ttry {\n\t\t\t\tconst filters = params.filter.map(parseFilterExpression);\n\n\t\t\t\t// Filters can modify the output. So clone the resources first.\n\t\t\t\tresources = resources.filter((resource) =>\n\t\t\t\t\tfilters.every((f) => f(resource, markMatchingVariant)),\n\t\t\t\t);\n\t\t\t} catch (err) {\n\t\t\t\tthrow new CommercetoolsError<InvalidInputError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidInput\",\n\t\t\t\t\t\tmessage: (err as any).message,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// TODO: Calculate facets\n\t\tconst facets = this.getFacets(params, resources);\n\n\t\t// Apply filters post facetting\n\t\tif (params[\"filter.query\"]) {\n\t\t\ttry {\n\t\t\t\tconst filters = params[\"filter.query\"].map(parseFilterExpression);\n\t\t\t\tresources = resources.filter((resource) =>\n\t\t\t\t\tfilters.every((f) => f(resource, markMatchingVariant)),\n\t\t\t\t);\n\t\t\t} catch (err) {\n\t\t\t\tthrow new CommercetoolsError<InvalidInputError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidInput\",\n\t\t\t\t\t\tmessage: (err as any).message,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Expand the resources\n\t\tif (params.expand !== undefined) {\n\t\t\tresources = await Promise.all(\n\t\t\t\tresources.map((resource) =>\n\t\t\t\t\tthis._storage.expand(projectKey, resource, params.expand),\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\n\t\t// Create a slice for the pagination. If we were working with large datasets\n\t\t// then we should have done this before transforming. But that isn't the\n\t\t// goal of this library. So lets keep it simple.\n\t\tconst totalResults = resources.length;\n\t\tconst offset = params.offset || 0;\n\t\tconst limit = params.limit || 20;\n\t\tconst results = resources.slice(offset, offset + limit);\n\n\t\treturn {\n\t\t\tcount: results.length,\n\t\t\ttotal: totalResults,\n\t\t\toffset: offset,\n\t\t\tlimit: limit,\n\t\t\tresults: results,\n\t\t\tfacets: facets,\n\t\t};\n\t}\n\n\tasync transform(\n\t\tproduct: Product,\n\t\tstaged: boolean,\n\t\tprojectKey: string,\n\t): Promise<ProductProjection> {\n\t\tconst obj = !staged\n\t\t\t? product.masterData.current\n\t\t\t: product.masterData.staged;\n\n\t\t// Calculate review statistics for this product\n\t\tconst reviewRatingStatistics =\n\t\t\tawait this._reviewStatisticsService.calculateProductReviewStatistics(\n\t\t\t\tprojectKey,\n\t\t\t\tproduct.id,\n\t\t\t);\n\n\t\treturn {\n\t\t\tid: product.id,\n\t\t\tcreatedAt: product.createdAt,\n\t\t\tattributes: obj.attributes,\n\t\t\tlastModifiedAt: product.lastModifiedAt,\n\t\t\tversion: product.version,\n\t\t\tname: obj.name,\n\t\t\tkey: product.key,\n\t\t\tdescription: obj.description,\n\t\t\tmetaTitle: obj.metaTitle,\n\t\t\tmetaDescription: obj.metaDescription,\n\t\t\tmetaKeywords: obj.metaKeywords,\n\t\t\tsearchKeywords: obj.searchKeywords,\n\t\t\tslug: obj.slug,\n\t\t\tcategories: obj.categories,\n\t\t\tmasterVariant: obj.masterVariant,\n\t\t\tvariants: obj.variants,\n\t\t\tproductType: product.productType,\n\t\t\ttaxCategory: product.taxCategory,\n\t\t\tstate: product.state,\n\t\t\tpriceMode: product.priceMode,\n\t\t\thasStagedChanges: product.masterData.hasStagedChanges,\n\t\t\tpublished: product.masterData.published,\n\t\t\treviewRatingStatistics,\n\t\t};\n\t}\n\n\tgetFacets(\n\t\tparams: ProductProjectionSearchParams,\n\t\tproducts: ProductProjection[],\n\t): FacetResults {\n\t\tif (!params.facet) return {};\n\t\tconst result: FacetResults = {};\n\n\t\tconst regexp = new RegExp(/ counting products$/);\n\t\tfor (let facet of params.facet) {\n\t\t\tlet countProducts = false;\n\t\t\tif (facet.endsWith(\" counting products\")) {\n\t\t\t\tfacet = facet.replace(regexp, \"\");\n\t\t\t\tcountProducts = true;\n\t\t\t}\n\n\t\t\tconst expression = generateFacetFunc(facet);\n\n\t\t\t// Term Facet\n\t\t\tif (expression.type === \"TermExpression\") {\n\t\t\t\tresult[facet] = this.termFacet(\n\t\t\t\t\texpression.source,\n\t\t\t\t\tproducts,\n\t\t\t\t\tcountProducts,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Range Facet\n\t\t\tif (expression.type === \"RangeExpression\") {\n\t\t\t\tresult[expression.source] = this.rangeFacet(\n\t\t\t\t\texpression.source,\n\t\t\t\t\texpression.children,\n\t\t\t\t\tproducts,\n\t\t\t\t\tcountProducts,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// FilteredFacet\n\t\t\tif (expression.type === \"FilterExpression\") {\n\t\t\t\tresult[expression.source] = this.filterFacet(\n\t\t\t\t\texpression.source,\n\t\t\t\t\texpression.children,\n\t\t\t\t\tproducts,\n\t\t\t\t\tcountProducts,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * TODO: This implemention needs the following additional features:\n\t *  - counting products\n\t *  - correct dataType\n\t */\n\ttermFacet(\n\t\tfacet: string,\n\t\tproducts: ProductProjection[],\n\t\tcountProducts: boolean,\n\t): TermFacetResult {\n\t\tconst result: Writable<TermFacetResult> = {\n\t\t\ttype: \"terms\",\n\t\t\tdataType: \"text\",\n\t\t\tmissing: 0,\n\t\t\ttotal: 0,\n\t\t\tother: 0,\n\t\t\tterms: [],\n\t\t};\n\t\tconst terms: Record<any, number> = {};\n\n\t\tif (facet.startsWith(\"variants.\")) {\n\t\t\tfor (const p of products) {\n\t\t\t\tconst variants = getVariants(p);\n\t\t\t\tfor (const v of variants) {\n\t\t\t\t\tresult.total++;\n\n\t\t\t\t\tlet value = resolveVariantValue(v, facet);\n\t\t\t\t\tif (value === undefined) {\n\t\t\t\t\t\tresult.missing++;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (typeof value === \"number\") {\n\t\t\t\t\t\t\tvalue = Number(value).toFixed(1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tterms[value] = value in terms ? terms[value] + 1 : 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfor (const p of products) {\n\t\t\t\tconst value = nestedLookup(p, facet);\n\t\t\t\tresult.total++;\n\t\t\t\tif (value === undefined) {\n\t\t\t\t\tresult.missing++;\n\t\t\t\t} else {\n\t\t\t\t\tterms[value] = value in terms ? terms[value] + 1 : 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (const term in terms) {\n\t\t\tresult.terms.push({\n\t\t\t\tterm: term as any,\n\t\t\t\tcount: terms[term],\n\t\t\t});\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tfilterFacet(\n\t\tsource: string,\n\t\tfilters: FilterExpression[] | undefined,\n\t\tproducts: ProductProjection[],\n\t\tcountProducts: boolean,\n\t): FilteredFacetResult {\n\t\tlet count = 0;\n\t\tif (source.startsWith(\"variants.\")) {\n\t\t\tfor (const p of products) {\n\t\t\t\tfor (const v of getVariants(p)) {\n\t\t\t\t\tconst val = resolveVariantValue(v, source);\n\t\t\t\t\tif (filters?.some((f) => f.match(val))) {\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: \"not supported\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\treturn {\n\t\t\ttype: \"filter\",\n\t\t\tcount: count,\n\t\t};\n\t}\n\n\trangeFacet(\n\t\tsource: string,\n\t\tranges: RangeExpression[] | undefined,\n\t\tproducts: ProductProjection[],\n\t\tcountProducts: boolean,\n\t): RangeFacetResult {\n\t\tconst counts =\n\t\t\tranges?.map((range) => {\n\t\t\t\tif (source.startsWith(\"variants.\")) {\n\t\t\t\t\tconst values: number[] = [];\n\t\t\t\t\tfor (const p of products) {\n\t\t\t\t\t\tfor (const v of getVariants(p)) {\n\t\t\t\t\t\t\tconst val = resolveVariantValue(v, source);\n\t\t\t\t\t\t\tif (val === undefined) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (range.match(val)) {\n\t\t\t\t\t\t\t\tvalues.push(val);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst numValues = values.length;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"double\",\n\t\t\t\t\t\tfrom: range.start || 0,\n\t\t\t\t\t\tfromStr: range.start !== null ? Number(range.start).toFixed(1) : \"\",\n\t\t\t\t\t\tto: range.stop || 0,\n\t\t\t\t\t\ttoStr: range.stop !== null ? Number(range.stop).toFixed(1) : \"\",\n\t\t\t\t\t\tcount: numValues,\n\t\t\t\t\t\t// totalCount: 0,\n\t\t\t\t\t\ttotal: values.reduce((a, b) => a + b, 0),\n\t\t\t\t\t\tmin: numValues > 0 ? Math.min(...values) : 0,\n\t\t\t\t\t\tmax: numValues > 0 ? Math.max(...values) : 0,\n\t\t\t\t\t\tmean: numValues > 0 ? mean(values) : 0,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: \"not supported\",\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}) || [];\n\t\tconst data: RangeFacetResult = {\n\t\t\ttype: \"range\",\n\t\t\t// @ts-expect-error\n\t\t\tdataType: \"number\",\n\t\t\tranges: counts,\n\t\t};\n\t\treturn data;\n\t}\n}\n\nconst mean = (arr: number[]) => {\n\tlet total = 0;\n\tfor (let i = 0; i < arr.length; i++) {\n\t\ttotal += arr[i];\n\t}\n\treturn total / arr.length;\n};\n","import type {\n\tInvalidInputError,\n\tInvalidOperationError,\n\tProductDraft,\n\tProductProjection,\n\tQueryParam,\n\tSearchKeyword,\n\tSuggestionResult,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { parseQueryExpression } from \"../lib/predicateParser.ts\";\nimport { applySort } from \"../lib/sortParser.ts\";\nimport { applyPriceSelector } from \"../priceSelector.ts\";\nimport { ProductProjectionSearch } from \"../product-projection-search.ts\";\nimport type { GetParams, RepositoryContext } from \"./abstract.ts\";\nimport { AbstractResourceRepository } from \"./abstract.ts\";\n\nexport type ProductProjectionQueryParams = {\n\tstaged?: boolean;\n\tpriceCurrency?: string;\n\tpriceCountry?: string;\n\tpriceCustomerGroup?: string;\n\tpriceChannel?: string;\n\tlocaleProjection?: string;\n\tstoreProjection?: string;\n\texpand?: string | string[];\n\tsort?: string | string[];\n\tlimit?: number;\n\toffset?: number;\n\twithTotal?: boolean;\n\twhere?: string | string[];\n\t[key: string]: QueryParam;\n};\n\nexport type ProductProjectionSuggestParams = {\n\tsearchKeywords: Record<string, string>;\n\tstaged?: boolean;\n\tfuzzy?: boolean;\n\tfuzzyLevel?: number;\n\tlimit?: number;\n};\n\nconst DEFAULT_SUGGEST_LIMIT = 10;\n\n/**\n * commercetools suggests on the tokens of a search keyword, so \"tool\" only\n * matches \"Multi tool\" when the keyword is tokenized.\n */\nconst keywordTokens = (keyword: SearchKeyword): string[] => {\n\tconst tokenizer = keyword.suggestTokenizer;\n\tif (!tokenizer) {\n\t\treturn [keyword.text];\n\t}\n\tif (tokenizer.type === \"custom\") {\n\t\treturn tokenizer.inputs;\n\t}\n\treturn keyword.text.split(/\\s+/).filter(Boolean);\n};\n\n/**\n * The fuzzy level commercetools derives from the length of the search term when\n * `fuzzyLevel` is not given.\n *\n * @see https://docs.commercetools.com/api/projects/products-search#fuzzy-search\n */\nconst defaultFuzzyLevel = (term: string) => {\n\tif (term.length < 3) return 0;\n\tif (term.length < 6) return 1;\n\treturn 2;\n};\n\n/**\n * Damerau-Levenshtein (optimal string alignment) distance: the same metric\n * Elasticsearch uses for fuzziness, so a transposed pair of characters counts\n * as one edit rather than two.\n */\nconst editDistance = (a: string, b: string): number => {\n\tconst rows: number[][] = [Array.from({ length: b.length + 1 }, (_, i) => i)];\n\n\tfor (let i = 1; i <= a.length; i++) {\n\t\tconst current = [i];\n\t\tfor (let j = 1; j <= b.length; j++) {\n\t\t\tconst previous = rows[i - 1];\n\t\t\tcurrent[j] = Math.min(\n\t\t\t\tprevious[j] + 1,\n\t\t\t\tcurrent[j - 1] + 1,\n\t\t\t\tprevious[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1),\n\t\t\t);\n\t\t\tif (\n\t\t\t\ti > 1 &&\n\t\t\t\tj > 1 &&\n\t\t\t\ta[i - 1] === b[j - 2] &&\n\t\t\t\ta[i - 2] === b[j - 1] &&\n\t\t\t\trows[i - 2] !== undefined\n\t\t\t) {\n\t\t\t\tcurrent[j] = Math.min(current[j], rows[i - 2][j - 2] + 1);\n\t\t\t}\n\t\t}\n\t\trows[i] = current;\n\t}\n\n\treturn rows[a.length][b.length];\n};\n\nexport class ProductProjectionRepository extends AbstractResourceRepository<\"product-projection\"> {\n\tprotected _searchService: ProductProjectionSearch;\n\n\tconstructor(config: Config) {\n\t\tsuper(\"product-projection\", config);\n\t\tthis._searchService = new ProductProjectionSearch(config);\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: ProductDraft,\n\t): Promise<ProductProjection> {\n\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t{\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"No valid action\",\n\t\t\t},\n\t\t\t400,\n\t\t);\n\t}\n\n\tasync get(\n\t\tcontext: RepositoryContext,\n\t\tid: string,\n\t\tparams: GetParams = {},\n\t): Promise<ProductProjection | null> {\n\t\tconst resource = await this._storage.get(\n\t\t\tcontext.projectKey,\n\t\t\t\"product\",\n\t\t\tid,\n\t\t\tparams,\n\t\t);\n\t\tif (resource) {\n\t\t\treturn await this._searchService.transform(\n\t\t\t\tresource,\n\t\t\t\tfalse,\n\t\t\t\tcontext.projectKey,\n\t\t\t);\n\t\t}\n\t\treturn null;\n\t}\n\n\tasync query(\n\t\tcontext: RepositoryContext,\n\t\tparams: ProductProjectionQueryParams = {},\n\t) {\n\t\tconst allProducts = await this._storage.all(context.projectKey, \"product\");\n\t\tlet resources = await Promise.all(\n\t\t\tallProducts.map((r) =>\n\t\t\t\tthis._searchService.transform(\n\t\t\t\t\tr,\n\t\t\t\t\tparams.staged ?? false,\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\t\tresources = resources.filter((p) => {\n\t\t\tif (!(params.staged ?? false)) {\n\t\t\t\treturn p.published;\n\t\t\t}\n\t\t\treturn true;\n\t\t});\n\n\t\t// Apply predicates\n\t\tif (params.where) {\n\t\t\tconst variableMap: Record<string, QueryParam> = {};\n\t\t\tfor (const [k, v] of Object.entries(params)) {\n\t\t\t\tif (k.startsWith(\"var.\")) {\n\t\t\t\t\tvariableMap[k.substring(4)] = v;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst filterFunc = parseQueryExpression(params.where);\n\t\t\t\tresources = resources.filter((resource) =>\n\t\t\t\t\tfilterFunc(resource, variableMap),\n\t\t\t\t);\n\t\t\t} catch (err) {\n\t\t\t\tthrow new CommercetoolsError<InvalidInputError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidInput\",\n\t\t\t\t\t\tmessage: (err as any).message,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// We do this after the filtering, since the docs mention:\n\t\t// Only available when Price selection is used. Cannot be used in a Query\n\t\t// Predicate.\n\t\tapplyPriceSelector(\n\t\t\tresources,\n\t\t\t{\n\t\t\t\tcountry: params.priceCountry,\n\t\t\t\tchannel: params.priceChannel,\n\t\t\t\tcustomerGroup: params.priceCustomerGroup,\n\t\t\t\tcurrency: params.priceCurrency,\n\t\t\t},\n\t\t\ttrue,\n\t\t);\n\n\t\t// Expand the resources\n\t\tif (params.expand !== undefined) {\n\t\t\tresources = await Promise.all(\n\t\t\t\tresources.map((resource) =>\n\t\t\t\t\tthis._storage.expand(context.projectKey, resource, params.expand),\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\n\t\t// Sort before paging. This repository does not go through\n\t\t// AbstractStorage.query, so it needs its own call — without it a\n\t\t// cursor-paged walk (`sort: \"id asc\"` with `where: 'id > \"<last>\"'`) takes\n\t\t// its cursor from an unsorted page and skips products.\n\t\tresources = applySort(resources, params.sort);\n\n\t\t// Create a slice for the pagination. If we were working with large datasets\n\t\t// then we should have done this before transforming. But that isn't the\n\t\t// goal of this library. So lets keep it simple.\n\t\tconst totalResults = resources.length;\n\t\tconst offset = params.offset || 0;\n\t\tconst limit = params.limit || 20;\n\t\tconst results = resources.slice(offset, offset + limit);\n\n\t\treturn {\n\t\t\tcount: results.length,\n\t\t\ttotal: totalResults,\n\t\t\toffset: offset,\n\t\t\tlimit: limit,\n\t\t\tresults: results,\n\t\t};\n\t}\n\n\tsearch(context: RepositoryContext, query: ProductProjectionQueryParams) {\n\t\treturn this._searchService.search(context.projectKey, query);\n\t}\n\n\tasync suggest(\n\t\tcontext: RepositoryContext,\n\t\tparams: ProductProjectionSuggestParams,\n\t): Promise<SuggestionResult> {\n\t\tconst staged = params.staged ?? false;\n\t\tconst allProducts = await this._storage.all(context.projectKey, \"product\");\n\t\tconst projections = (\n\t\t\tawait Promise.all(\n\t\t\t\tallProducts.map((product) =>\n\t\t\t\t\tthis._searchService.transform(product, staged, context.projectKey),\n\t\t\t\t),\n\t\t\t)\n\t\t).filter((projection) => staged || projection.published);\n\n\t\tconst limit = params.limit ?? DEFAULT_SUGGEST_LIMIT;\n\t\tconst result: SuggestionResult = {};\n\n\t\tfor (const [locale, term] of Object.entries(params.searchKeywords)) {\n\t\t\tconst needle = term.toLowerCase();\n\t\t\tconst level = params.fuzzy\n\t\t\t\t? (params.fuzzyLevel ?? defaultFuzzyLevel(term))\n\t\t\t\t: 0;\n\n\t\t\tconst texts = new Set<string>();\n\t\t\tfor (const projection of projections) {\n\t\t\t\tfor (const keyword of projection.searchKeywords?.[locale] ?? []) {\n\t\t\t\t\tconst matches = keywordTokens(keyword).some((token) => {\n\t\t\t\t\t\tconst prefix = token.slice(0, needle.length).toLowerCase();\n\t\t\t\t\t\treturn level === 0\n\t\t\t\t\t\t\t? prefix === needle\n\t\t\t\t\t\t\t: editDistance(prefix, needle) <= level;\n\t\t\t\t\t});\n\t\t\t\t\tif (matches) {\n\t\t\t\t\t\ttexts.add(keyword.text);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresult[`searchKeywords.${locale}`] = [...texts]\n\t\t\t\t.slice(0, limit)\n\t\t\t\t.map((text) => ({ text }));\n\t\t}\n\n\t\treturn result;\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tCustomFieldsDraftSchema,\n\tLocalizedStringSchema,\n\tProductSelectionModeSchema,\n\tProductSelectionTypeEnumSchema,\n} from \"./common.ts\";\n\nexport const ProductSelectionDraftSchema = z.object({\n\tkey: z.string().nullish(),\n\tname: LocalizedStringSchema,\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\ttype: ProductSelectionTypeEnumSchema.nullish(),\n\tmode: ProductSelectionModeSchema.nullish(),\n});\n","import type {\n\tProductSelection,\n\tProductSelectionChangeNameAction,\n\tProductSelectionDraft,\n\tProductSelectionSetCustomTypeAction,\n\tProductSelectionUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { ProductSelectionDraftSchema } from \"#src/schemas/generated/product-selection.ts\";\nimport { getBaseResourceProperties } from \"../helpers.ts\";\nimport type { Writable } from \"../types.ts\";\nimport type { RepositoryContext, UpdateHandlerInterface } from \"./abstract.ts\";\nimport {\n\tAbstractResourceRepository,\n\tAbstractUpdateHandler,\n} from \"./abstract.ts\";\n\nexport class ProductSelectionRepository extends AbstractResourceRepository<\"product-selection\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"product-selection\", config);\n\t\tthis.actions = new ProductSelectionUpdateHandler(this._storage);\n\t\tthis.draftSchema = ProductSelectionDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: ProductSelectionDraft,\n\t): Promise<ProductSelection> {\n\t\tconst resource: ProductSelection = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tproductCount: 0,\n\t\t\tkey: draft.key,\n\t\t\tname: draft.name,\n\t\t\tmode: \"Individual\",\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n\nclass ProductSelectionUpdateHandler\n\textends AbstractUpdateHandler\n\timplements\n\t\tPartial<\n\t\t\tUpdateHandlerInterface<ProductSelection, ProductSelectionUpdateAction>\n\t\t>\n{\n\tchangeName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ProductSelection>,\n\t\t{ name }: ProductSelectionChangeNameAction,\n\t) {\n\t\tresource.name = name;\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ProductSelection>,\n\t\t{ type, fields }: ProductSelectionSetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport { AttributeDefinitionDraftSchema } from \"./common.ts\";\n\nexport const ProductTypeDraftSchema = z.object({\n\tkey: z.string().nullish(),\n\tname: z.string(),\n\tdescription: z.string(),\n\tattributes: z.array(AttributeDefinitionDraftSchema).nullish(),\n});\n","import type {\n\tAttributeDefinition,\n\tAttributeDefinitionDraft,\n\tAttributeType,\n\tInvalidOperationError,\n\tProductType,\n\tProductTypeAddAttributeDefinitionAction,\n\tProductTypeChangeAttributeOrderByNameAction,\n\tProductTypeChangeDescriptionAction,\n\tProductTypeChangeLabelAction,\n\tProductTypeChangeLocalizedEnumValueLabelAction,\n\tProductTypeChangeNameAction,\n\tProductTypeDraft,\n\tProductTypeRemoveAttributeDefinitionAction,\n\tProductTypeRemoveEnumValuesAction,\n\tProductTypeSetKeyAction,\n\tProductTypeUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { ProductTypeDraftSchema } from \"#src/schemas/generated/product-type.ts\";\nimport { getBaseResourceProperties } from \"../helpers.ts\";\nimport type { Writable } from \"../types.ts\";\nimport type { RepositoryContext, UpdateHandlerInterface } from \"./abstract.ts\";\nimport {\n\tAbstractResourceRepository,\n\tAbstractUpdateHandler,\n} from \"./abstract.ts\";\n\nexport class ProductTypeRepository extends AbstractResourceRepository<\"product-type\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"product-type\", config);\n\t\tthis.actions = new ProductTypeUpdateHandler(config.storage);\n\t\tthis.draftSchema = ProductTypeDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: ProductTypeDraft,\n\t): Promise<ProductType> {\n\t\tconst resource: ProductType = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tkey: draft.key,\n\t\t\tname: draft.name,\n\t\t\tdescription: draft.description,\n\t\t\tattributes: (draft.attributes ?? []).map((a) =>\n\t\t\t\tattributeDefinitionFromAttributeDefinitionDraft(context, a),\n\t\t\t),\n\t\t};\n\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n\nconst attributeDefinitionFromAttributeDefinitionDraft = (\n\t_context: RepositoryContext,\n\tdraft: AttributeDefinitionDraft,\n): AttributeDefinition => ({\n\t...draft,\n\tlevel: draft.level ?? \"Variant\",\n\tattributeConstraint: draft.attributeConstraint ?? \"None\",\n\tinputHint: draft.inputHint ?? \"SingleLine\",\n\tinputTip:\n\t\tdraft.inputTip && Object.keys(draft.inputTip).length > 0\n\t\t\t? draft.inputTip\n\t\t\t: undefined,\n\tisSearchable: draft.isSearchable ?? true,\n});\n\nclass ProductTypeUpdateHandler\n\textends AbstractUpdateHandler\n\timplements\n\t\tPartial<UpdateHandlerInterface<ProductType, ProductTypeUpdateAction>>\n{\n\taddAttributeDefinition(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ProductType>,\n\t\t{ attribute }: ProductTypeAddAttributeDefinitionAction,\n\t) {\n\t\tresource.attributes?.push(\n\t\t\tattributeDefinitionFromAttributeDefinitionDraft(context, attribute),\n\t\t);\n\t}\n\n\tchangeAttributeOrderByName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ProductType>,\n\t\t{ attributeNames }: ProductTypeChangeAttributeOrderByNameAction,\n\t) {\n\t\tconst attrs = new Map(\n\t\t\tresource.attributes?.map((item) => [item.name, item]),\n\t\t);\n\t\tconst result: AttributeDefinition[] = [];\n\t\tlet current = resource.attributes;\n\n\t\tattributeNames.forEach((attrName) => {\n\t\t\tconst attr = attrs.get(attrName);\n\t\t\tif (attr === undefined) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\"Adding new attribute definitions is not fully supported yet\",\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tresult.push(attr);\n\n\t\t\t// Remove from current items\n\t\t\tcurrent = current?.filter((f) => f.name !== attrName);\n\t\t});\n\n\t\tresource.attributes = result;\n\t\t// Add attrs which were not specified in the order as last items. Not\n\t\t// sure if this follows commercetools\n\t\tif (current) {\n\t\t\tresource.attributes.push(...current);\n\t\t}\n\t}\n\n\tchangeLabel(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ProductType>,\n\t\t{ attributeName, label }: ProductTypeChangeLabelAction,\n\t) {\n\t\tresource.attributes?.forEach((value) => {\n\t\t\tif (value.name === attributeName) {\n\t\t\t\tvalue.label = label;\n\t\t\t}\n\t\t});\n\t}\n\n\tchangeLocalizedEnumValueLabel(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ProductType>,\n\t\t{ attributeName, newValue }: ProductTypeChangeLocalizedEnumValueLabelAction,\n\t) {\n\t\tconst updateAttributeType = (type: Writable<AttributeType>) => {\n\t\t\tswitch (type.name) {\n\t\t\t\tcase \"lenum\":\n\t\t\t\t\ttype.values.forEach((v) => {\n\t\t\t\t\t\tif (v.key === newValue.key) {\n\t\t\t\t\t\t\tv.label = newValue.label;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\tcase \"set\":\n\t\t\t\t\tupdateAttributeType(type.elementType);\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t};\n\n\t\tresource.attributes?.forEach((value) => {\n\t\t\tif (value.name === attributeName) {\n\t\t\t\tupdateAttributeType(value.type);\n\t\t\t}\n\t\t});\n\t}\n\n\tremoveAttributeDefinition(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ProductType>,\n\t\t{ name }: ProductTypeRemoveAttributeDefinitionAction,\n\t) {\n\t\tresource.attributes = resource.attributes?.filter((f) => f.name !== name);\n\t}\n\n\tremoveEnumValues(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ProductType>,\n\t\t{ attributeName, keys }: ProductTypeRemoveEnumValuesAction,\n\t) {\n\t\tresource.attributes?.forEach((attr) => {\n\t\t\tif (attr.name === attributeName) {\n\t\t\t\tif (attr.type.name === \"enum\") {\n\t\t\t\t\tattr.type.values = attr.type.values.filter(\n\t\t\t\t\t\t(v) => !keys.includes(v.key),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (attr.type.name === \"set\") {\n\t\t\t\t\tif (attr.type.elementType.name === \"enum\") {\n\t\t\t\t\t\tattr.type.elementType.values = attr.type.elementType.values.filter(\n\t\t\t\t\t\t\t(v) => !keys.includes(v.key),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tsetKey(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ProductType>,\n\t\t{ key }: ProductTypeSetKeyAction,\n\t) {\n\t\tresource.key = key;\n\t}\n\n\tchangeName(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ProductType>,\n\t\t{ name }: ProductTypeChangeNameAction,\n\t) {\n\t\tresource.name = name;\n\t}\n\n\tchangeDescription(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ProductType>,\n\t\t{ description }: ProductTypeChangeDescriptionAction,\n\t) {\n\t\tresource.description = description;\n\t}\n}\n","import type {\n\tInvalidOperationError,\n\tProject,\n\tProjectChangeBusinessUnitSearchStatusAction,\n\tProjectChangeBusinessUnitStatusOnCreationAction,\n\tProjectChangeCartsConfigurationAction,\n\tProjectChangeCountriesAction,\n\tProjectChangeCountryTaxRateFallbackEnabledAction,\n\tProjectChangeCurrenciesAction,\n\tProjectChangeCustomerSearchStatusAction,\n\tProjectChangeLanguagesAction,\n\tProjectChangeMessagesConfigurationAction,\n\tProjectChangeNameAction,\n\tProjectChangeOrderSearchStatusAction,\n\tProjectChangePriceRoundingModeAction,\n\tProjectChangeProductSearchIndexingEnabledAction,\n\tProjectChangeShoppingListsConfigurationAction,\n\tProjectChangeTaxRoundingModeAction,\n\tProjectSetExternalOAuthAction,\n\tProjectSetShippingRateInputTypeAction,\n\tProjectUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type { ProjectSetBusinessUnitAssociateRoleOnCreationAction } from \"@commercetools/platform-sdk/dist/declarations/src/generated/models/project\";\nimport type { Config } from \"#src/config.ts\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { maskSecretValue } from \"../lib/masking.ts\";\nimport type { Writable } from \"../types.ts\";\nimport type { RepositoryContext, UpdateHandlerInterface } from \"./abstract.ts\";\nimport { AbstractRepository, AbstractUpdateHandler } from \"./abstract.ts\";\n\nexport class ProjectRepository extends AbstractRepository<Project> {\n\tconstructor(config: Config) {\n\t\tsuper(config);\n\t\tthis.actions = new ProjectUpdateHandler(config.storage);\n\t}\n\n\tasync get(context: RepositoryContext): Promise<Project | null> {\n\t\tconst resource = await this._storage.getProject(context.projectKey);\n\t\treturn await this.postProcessResource(context, resource);\n\t}\n\n\tasync postProcessResource(\n\t\tcontext: RepositoryContext,\n\t\tresource: Project | null,\n\t): Promise<Project | null> {\n\t\tif (resource) {\n\t\t\treturn maskSecretValue(resource, \"externalOAuth.authorizationHeader\");\n\t\t}\n\t\treturn resource;\n\t}\n\n\tasync saveNew(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Project>,\n\t): Promise<Project> {\n\t\tresource.version = 1;\n\t\tawait this._storage.saveProject(resource);\n\t\treturn resource;\n\t}\n\n\tasync saveUpdate(\n\t\tcontext: RepositoryContext,\n\t\tversion: number,\n\t\tresource: Project,\n\t): Promise<Project> {\n\t\tawait this._storage.saveProject(resource);\n\t\treturn resource;\n\t}\n}\n\nclass ProjectUpdateHandler\n\textends AbstractUpdateHandler\n\timplements Partial<UpdateHandlerInterface<Project, ProjectUpdateAction>>\n{\n\tchangeCartsConfiguration(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Project>,\n\t\t{ cartsConfiguration }: ProjectChangeCartsConfigurationAction,\n\t) {\n\t\tresource.carts = cartsConfiguration || {\n\t\t\tcountryTaxRateFallbackEnabled: false,\n\t\t\tdeleteDaysAfterLastModification: 90,\n\t\t\tpriceRoundingMode: \"HalfEven\",\n\t\t\ttaxRoundingMode: \"HalfEven\",\n\t\t};\n\t}\n\n\tchangeShoppingListsConfiguration(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Project>,\n\t\t{\n\t\t\tshoppingListsConfiguration,\n\t\t}: ProjectChangeShoppingListsConfigurationAction,\n\t) {\n\t\tresource.shoppingLists = shoppingListsConfiguration || {\n\t\t\tdeleteDaysAfterLastModification: 90,\n\t\t};\n\t}\n\n\tchangeCountries(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Project>,\n\t\t{ countries }: ProjectChangeCountriesAction,\n\t) {\n\t\tresource.countries = countries;\n\t}\n\n\tchangeCountryTaxRateFallbackEnabled(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Project>,\n\t\t{\n\t\t\tcountryTaxRateFallbackEnabled,\n\t\t}: ProjectChangeCountryTaxRateFallbackEnabledAction,\n\t) {\n\t\tresource.carts.countryTaxRateFallbackEnabled =\n\t\t\tcountryTaxRateFallbackEnabled;\n\t}\n\n\tchangePriceRoundingMode(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Project>,\n\t\t{ priceRoundingMode }: ProjectChangePriceRoundingModeAction,\n\t) {\n\t\tresource.carts.priceRoundingMode = priceRoundingMode;\n\t}\n\n\tchangeTaxRoundingMode(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Project>,\n\t\t{ taxRoundingMode }: ProjectChangeTaxRoundingModeAction,\n\t) {\n\t\tresource.carts.taxRoundingMode = taxRoundingMode;\n\t}\n\n\tchangeCurrencies(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Project>,\n\t\t{ currencies }: ProjectChangeCurrenciesAction,\n\t) {\n\t\tresource.currencies = currencies;\n\t}\n\n\tchangeCustomerSearchStatus(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Project>,\n\t\t{ status }: ProjectChangeCustomerSearchStatusAction,\n\t) {\n\t\tif (!resource.searchIndexing?.customers) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: \"Invalid project state\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tresource.searchIndexing.customers.status = status;\n\t\tresource.searchIndexing.customers.lastModifiedAt = new Date().toISOString();\n\t}\n\n\tchangeBusinessUnitSearchStatus(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Project>,\n\t\t{ status }: ProjectChangeBusinessUnitSearchStatusAction,\n\t) {\n\t\tif (!resource.searchIndexing?.businessUnits) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: \"Invalid project state\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tresource.searchIndexing.businessUnits.status = status;\n\t\tresource.searchIndexing.businessUnits.lastModifiedAt =\n\t\t\tnew Date().toISOString();\n\t}\n\n\tchangeLanguages(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Project>,\n\t\t{ languages }: ProjectChangeLanguagesAction,\n\t) {\n\t\tresource.languages = languages;\n\t}\n\n\tchangeMessagesConfiguration(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Project>,\n\t\t{ messagesConfiguration }: ProjectChangeMessagesConfigurationAction,\n\t) {\n\t\tresource.messages.enabled = messagesConfiguration.enabled;\n\t\tresource.messages.deleteDaysAfterCreation =\n\t\t\tmessagesConfiguration.deleteDaysAfterCreation;\n\t}\n\n\tchangeMyBusinessUnitStatusOnCreation(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Project>,\n\t\t{ status }: ProjectChangeBusinessUnitStatusOnCreationAction,\n\t) {\n\t\tif (resource.businessUnits === undefined) {\n\t\t\tresource.businessUnits = {\n\t\t\t\tmyBusinessUnitStatusOnCreation: \"Inactive\",\n\t\t\t};\n\t\t}\n\n\t\tresource.businessUnits.myBusinessUnitStatusOnCreation = status;\n\t}\n\n\tchangeName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Project>,\n\t\t{ name }: ProjectChangeNameAction,\n\t) {\n\t\tresource.name = name;\n\t}\n\n\tchangeOrderSearchStatus(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Project>,\n\t\t{ status }: ProjectChangeOrderSearchStatusAction,\n\t) {\n\t\tif (!resource.searchIndexing?.orders) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: \"Invalid project state\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tresource.searchIndexing.orders.status = status;\n\t\tresource.searchIndexing.orders.lastModifiedAt = new Date().toISOString();\n\t}\n\n\tchangeProductSearchIndexingEnabled(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Project>,\n\t\t{ enabled, mode }: ProjectChangeProductSearchIndexingEnabledAction,\n\t) {\n\t\tif (mode === \"ProductsSearch\") {\n\t\t\tif (!resource.searchIndexing?.productsSearch) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: \"Invalid project state\",\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tresource.searchIndexing.productsSearch.status = enabled\n\t\t\t\t? \"Activated\"\n\t\t\t\t: \"Deactivated\";\n\t\t\tresource.searchIndexing.productsSearch.lastModifiedAt =\n\t\t\t\tnew Date().toISOString();\n\t\t\treturn;\n\t\t}\n\n\t\tif (!resource.searchIndexing?.products) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\tmessage: \"Invalid project state\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tresource.searchIndexing.products.status = enabled\n\t\t\t? \"Activated\"\n\t\t\t: \"Deactivated\";\n\t\tresource.searchIndexing.products.lastModifiedAt = new Date().toISOString();\n\t}\n\n\tsetExternalOAuth(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Project>,\n\t\t{ externalOAuth }: ProjectSetExternalOAuthAction,\n\t) {\n\t\tresource.externalOAuth = externalOAuth;\n\t}\n\n\tsetMyBusinessUnitAssociateRoleOnCreation(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Project>,\n\t\t{ associateRole }: ProjectSetBusinessUnitAssociateRoleOnCreationAction,\n\t) {\n\t\tif (resource.businessUnits === undefined) {\n\t\t\tresource.businessUnits = {\n\t\t\t\t//Default status, so we set it here also\n\t\t\t\tmyBusinessUnitStatusOnCreation: \"Inactive\",\n\t\t\t};\n\t\t}\n\n\t\tresource.businessUnits.myBusinessUnitAssociateRoleOnCreation = {\n\t\t\ttypeId: associateRole.typeId,\n\t\t\tkey: associateRole.key ?? \"unknown\",\n\t\t};\n\t}\n\n\tsetShippingRateInputType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Project>,\n\t\t{ shippingRateInputType }: ProjectSetShippingRateInputTypeAction,\n\t) {\n\t\tresource.shippingRateInputType = shippingRateInputType;\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tCustomFieldsDraftSchema,\n\tQuoteRequestResourceIdentifierSchema,\n\tStateReferenceSchema,\n} from \"./common.ts\";\n\nexport const StagedQuoteDraftSchema = z.object({\n\tquoteRequest: QuoteRequestResourceIdentifierSchema,\n\tquoteRequestVersion: z.number().int(),\n\tquoteRequestStateToAccepted: z.boolean().nullish(),\n\tkey: z.string().nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\tstate: StateReferenceSchema.nullish(),\n});\n","import type {\n\tInvalidJsonInputError,\n\tStagedQuote,\n\tStagedQuoteSetCustomFieldAction,\n\tStagedQuoteSetCustomTypeAction,\n\tStagedQuoteTransitionStateAction,\n\tStagedQuoteUpdateAction,\n\tStateReference,\n} from \"@commercetools/platform-sdk\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport type { Writable } from \"#src/types.ts\";\nimport type { RepositoryContext, UpdateHandlerInterface } from \"../abstract.ts\";\nimport { AbstractUpdateHandler } from \"../abstract.ts\";\nimport { getReferenceFromResourceIdentifier } from \"../helpers.ts\";\n\nexport class StagedQuoteUpdateHandler\n\textends AbstractUpdateHandler\n\timplements\n\t\tPartial<UpdateHandlerInterface<StagedQuote, StagedQuoteUpdateAction>>\n{\n\tsetCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: StagedQuote,\n\t\t{ name, value }: StagedQuoteSetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<StagedQuote>,\n\t\t{ type, fields }: StagedQuoteSetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n\n\tasync transitionState(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<StagedQuote>,\n\t\t{ state, force }: StagedQuoteTransitionStateAction,\n\t) {\n\t\tlet stateReference: StateReference | undefined;\n\t\tif (state) {\n\t\t\tstateReference = await getReferenceFromResourceIdentifier<StateReference>(\n\t\t\t\tstate,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t);\n\t\t\tresource.state = stateReference;\n\t\t} else {\n\t\t\tthrow new CommercetoolsError<InvalidJsonInputError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidJsonInput\",\n\t\t\t\t\tmessage: \"Request body does not contain valid JSON.\",\n\t\t\t\t\tdetailedErrorMessage: \"actions -> state: Missing required value\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t}\n}\n","import type {\n\tResourceNotFoundError,\n\tStagedQuote,\n\tStagedQuoteDraft,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { getBaseResourceProperties } from \"#src/helpers.ts\";\nimport { StagedQuoteDraftSchema } from \"#src/schemas/generated/staged-quote.ts\";\nimport type { RepositoryContext } from \"../abstract.ts\";\nimport { AbstractResourceRepository } from \"../abstract.ts\";\nimport { StagedQuoteUpdateHandler } from \"./actions.ts\";\n\nexport class StagedQuoteRepository extends AbstractResourceRepository<\"staged-quote\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"staged-quote\", config);\n\t\tthis.actions = new StagedQuoteUpdateHandler(config.storage);\n\t\tthis.draftSchema = StagedQuoteDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: StagedQuoteDraft,\n\t): Promise<StagedQuote> {\n\t\tconst quoteRequest =\n\t\t\tawait this._storage.getByResourceIdentifier<\"quote-request\">(\n\t\t\t\tcontext.projectKey,\n\t\t\t\tdraft.quoteRequest,\n\t\t\t);\n\n\t\tif (!quoteRequest.cart) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\t\tmessage: \"Cannot find quote request\",\n\t\t\t\t},\n\t\t\t\t404,\n\t\t\t);\n\t\t}\n\n\t\tconst cart = await this._storage.getByResourceIdentifier<\"cart\">(\n\t\t\tcontext.projectKey,\n\t\t\tquoteRequest.cart,\n\t\t);\n\n\t\tconst resource: StagedQuote = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tstagedQuoteState: \"InProgress\",\n\t\t\tquoteRequest: {\n\t\t\t\ttypeId: \"quote-request\",\n\t\t\t\tid: quoteRequest.id,\n\t\t\t},\n\t\t\tquotationCart: {\n\t\t\t\ttypeId: \"cart\",\n\t\t\t\tid: cart.id,\n\t\t\t},\n\t\t};\n\n\t\treturn resource;\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tLocalizedStringSchema,\n\tRecurrencePolicyScheduleDraftSchema,\n} from \"./common.ts\";\n\nexport const RecurrencePolicyDraftSchema = z.object({\n\tkey: z.string(),\n\tname: LocalizedStringSchema.nullish(),\n\tdescription: LocalizedStringSchema.nullish(),\n\tschedule: RecurrencePolicyScheduleDraftSchema,\n});\n","import type {\n\tRecurrencePolicy,\n\tRecurrencePolicySetDescriptionAction,\n\tRecurrencePolicySetKeyAction,\n\tRecurrencePolicySetNameAction,\n\tRecurrencePolicySetScheduleAction,\n\tRecurrencePolicyUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type { Writable } from \"#src/types.ts\";\nimport type { UpdateHandlerInterface } from \"../abstract.ts\";\nimport { AbstractUpdateHandler, type RepositoryContext } from \"../abstract.ts\";\n\nexport class RecurrencePolicyUpdateHandler\n\textends AbstractUpdateHandler\n\timplements\n\t\tPartial<\n\t\t\tUpdateHandlerInterface<RecurrencePolicy, RecurrencePolicyUpdateAction>\n\t\t>\n{\n\tsetKey(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<RecurrencePolicy>,\n\t\t{ key }: RecurrencePolicySetKeyAction,\n\t) {\n\t\tif (key) {\n\t\t\tresource.key = key;\n\t\t}\n\t}\n\n\tsetDescription(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<RecurrencePolicy>,\n\t\t{ description }: RecurrencePolicySetDescriptionAction,\n\t) {\n\t\tresource.description = description;\n\t}\n\n\tsetName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<RecurrencePolicy>,\n\t\t{ name }: RecurrencePolicySetNameAction,\n\t) {\n\t\tresource.name = name;\n\t}\n\n\tsetSchedule(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<RecurrencePolicy>,\n\t\t{ schedule }: RecurrencePolicySetScheduleAction,\n\t) {\n\t\tresource.schedule = schedule;\n\t}\n}\n","import type {\n\tRecurrencePolicy,\n\tRecurrencePolicyDraft,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { getBaseResourceProperties } from \"#src/helpers.ts\";\nimport { RecurrencePolicyDraftSchema } from \"#src/schemas/generated/recurrence-policy.ts\";\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from \"../abstract.ts\";\nimport { RecurrencePolicyUpdateHandler } from \"./actions.ts\";\n\nexport class RecurrencePolicyRepository extends AbstractResourceRepository<\"recurrence-policy\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"recurrence-policy\", config);\n\t\tthis.actions = new RecurrencePolicyUpdateHandler(config.storage);\n\t\tthis.draftSchema = RecurrencePolicyDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: RecurrencePolicyDraft,\n\t): Promise<RecurrencePolicy> {\n\t\tconst resource: RecurrencePolicy = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tkey: draft.key,\n\t\t\tname: draft.name,\n\t\t\tdescription: draft.description,\n\t\t\tschedule: draft.schedule,\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tCartResourceIdentifierSchema,\n\tCustomFieldsDraftSchema,\n\tStateResourceIdentifierSchema,\n} from \"./common.ts\";\n\nexport const RecurringOrderDraftSchema = z.object({\n\tkey: z.string().nullish(),\n\tcart: CartResourceIdentifierSchema,\n\tcartVersion: z.number().int(),\n\tstartsAt: z.string().nullish(),\n\texpiresAt: z.string().nullish(),\n\tstate: StateResourceIdentifierSchema.nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n});\n","import type {\n\tRecurringOrder,\n\tRecurringOrderSetCustomFieldAction,\n\tRecurringOrderSetCustomTypeAction,\n\tRecurringOrderSetExpiresAtAction,\n\tRecurringOrderSetKeyAction,\n\tRecurringOrderSetOrderSkipConfigurationAction,\n\tRecurringOrderSetScheduleAction,\n\tRecurringOrderSetStartsAtAction,\n\tRecurringOrderSetStateAction,\n\tRecurringOrderTransitionStateAction,\n\tRecurringOrderUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type { Writable } from \"#src/types.ts\";\nimport type { UpdateHandlerInterface } from \"../abstract.ts\";\nimport { AbstractUpdateHandler, type RepositoryContext } from \"../abstract.ts\";\n\nexport class RecurringOrderUpdateHandler\n\textends AbstractUpdateHandler\n\timplements\n\t\tPartial<UpdateHandlerInterface<RecurringOrder, RecurringOrderUpdateAction>>\n{\n\tsetCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<RecurringOrder>,\n\t\t{ name, value }: RecurringOrderSetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<RecurringOrder>,\n\t\t{ type, fields }: RecurringOrderSetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n\n\tsetExpiresAt(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<RecurringOrder>,\n\t\t{ expiresAt }: RecurringOrderSetExpiresAtAction,\n\t) {\n\t\tresource.expiresAt = expiresAt;\n\t}\n\n\tsetKey(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<RecurringOrder>,\n\t\t{ key }: RecurringOrderSetKeyAction,\n\t) {\n\t\tresource.key = key;\n\t}\n\n\tsetOrderSkipConfiguration(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<RecurringOrder>,\n\t\t{\n\t\t\tskipConfigurationInputDraft,\n\t\t\tupdatedExpiresAt,\n\t\t}: RecurringOrderSetOrderSkipConfigurationAction,\n\t) {\n\t\tif (skipConfigurationInputDraft) {\n\t\t\tresource.skipConfiguration = {\n\t\t\t\ttype: skipConfigurationInputDraft.type,\n\t\t\t\ttotalToSkip: skipConfigurationInputDraft.totalToSkip,\n\t\t\t\tskipped: 0,\n\t\t\t\tlastSkippedAt: undefined,\n\t\t\t};\n\t\t} else {\n\t\t\tresource.skipConfiguration = undefined;\n\t\t}\n\t\tif (updatedExpiresAt !== undefined) {\n\t\t\tresource.expiresAt = updatedExpiresAt;\n\t\t}\n\t}\n\n\tsetSchedule(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<RecurringOrder>,\n\t\t{ recurrencePolicy }: RecurringOrderSetScheduleAction,\n\t) {\n\t\tresource.schedule = {\n\t\t\t...resource.schedule,\n\t\t\t...recurrencePolicy,\n\t\t};\n\t}\n\n\tsetStartsAt(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<RecurringOrder>,\n\t\t{ startsAt }: RecurringOrderSetStartsAtAction,\n\t) {\n\t\tresource.startsAt = startsAt;\n\t}\n\n\tsetRecurringOrderState(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<RecurringOrder>,\n\t\t{ recurringOrderState }: RecurringOrderSetStateAction,\n\t) {\n\t\t// Map the state draft to the actual state\n\t\tswitch (recurringOrderState.type) {\n\t\t\tcase \"active\":\n\t\t\t\tresource.recurringOrderState = \"Active\";\n\t\t\t\tif (recurringOrderState.resumesAt) {\n\t\t\t\t\tresource.resumesAt = recurringOrderState.resumesAt;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"canceled\":\n\t\t\t\tresource.recurringOrderState = \"Canceled\";\n\t\t\t\tbreak;\n\t\t\tcase \"expired\":\n\t\t\t\tresource.recurringOrderState = \"Expired\";\n\t\t\t\tbreak;\n\t\t\tcase \"paused\":\n\t\t\t\tresource.recurringOrderState = \"Paused\";\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\ttransitionState(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<RecurringOrder>,\n\t\t{ state, force }: RecurringOrderTransitionStateAction,\n\t) {\n\t\tresource.state = {\n\t\t\ttypeId: \"state\",\n\t\t\tid: state.id!,\n\t\t};\n\t}\n}\n","import assert from \"node:assert\";\nimport type {\n\tRecurringOrder,\n\tRecurringOrderDraft,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { getBaseResourceProperties } from \"#src/helpers.ts\";\nimport { RecurringOrderDraftSchema } from \"#src/schemas/generated/recurring-order.ts\";\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from \"../abstract.ts\";\nimport { OrderRepository } from \"../order/index.ts\";\nimport { RecurringOrderUpdateHandler } from \"./actions.ts\";\n\nexport class RecurringOrderRepository extends AbstractResourceRepository<\"recurring-order\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"recurring-order\", config);\n\t\tthis.actions = new RecurringOrderUpdateHandler(config.storage);\n\t\tthis.draftSchema = RecurringOrderDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: RecurringOrderDraft,\n\t): Promise<RecurringOrder> {\n\t\tassert(draft.cart, \"draft.cart is missing\");\n\n\t\tconst orderRepo = new OrderRepository(this.config);\n\n\t\tconst initialOrder = await orderRepo.createFromCart(context, {\n\t\t\tid: draft.cart.id!,\n\t\t\ttypeId: \"cart\",\n\t\t});\n\n\t\tconst resource: RecurringOrder = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tkey: draft.key,\n\t\t\tcart: {\n\t\t\t\ttypeId: \"cart\",\n\t\t\t\tid: draft.cart.id!,\n\t\t\t},\n\t\t\toriginOrder: {\n\t\t\t\ttypeId: \"order\",\n\t\t\t\tid: initialOrder.id,\n\t\t\t},\n\t\t\tstartsAt: draft.startsAt ?? new Date().toISOString(),\n\t\t\texpiresAt: draft.expiresAt,\n\t\t\trecurringOrderState: \"Active\",\n\t\t\tschedule: { type: \"standard\", intervalUnit: \"month\", value: 1 },\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tCustomerResourceIdentifierSchema,\n\tCustomFieldsDraftSchema,\n\tLocaleSchema,\n\tStateResourceIdentifierSchema,\n} from \"./common.ts\";\n\nexport const ReviewDraftSchema = z.object({\n\tkey: z.string().nullish(),\n\tuniquenessValue: z.string().nullish(),\n\tlocale: LocaleSchema.nullish(),\n\tauthorName: z.string().nullish(),\n\ttitle: z.string().nullish(),\n\ttext: z.string().nullish(),\n\ttarget: z.unknown().nullish(),\n\tstate: StateResourceIdentifierSchema.nullish(),\n\trating: z.number().int().nullish(),\n\tcustomer: CustomerResourceIdentifierSchema.nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n});\n","import type {\n\tChannelReference,\n\tCustomerReference,\n\tProductReference,\n\tRequiredFieldError,\n\tReview,\n\tReviewDraft,\n\tReviewSetAuthorNameAction,\n\tReviewSetCustomerAction,\n\tReviewSetCustomFieldAction,\n\tReviewSetCustomTypeAction,\n\tReviewSetKeyAction,\n\tReviewSetLocaleAction,\n\tReviewSetRatingAction,\n\tReviewSetTargetAction,\n\tReviewSetTextAction,\n\tReviewSetTitleAction,\n\tReviewTransitionStateAction,\n\tReviewUpdateAction,\n\tStateReference,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { ReviewDraftSchema } from \"#src/schemas/generated/review.ts\";\nimport { getBaseResourceProperties } from \"../helpers.ts\";\nimport type { Writable } from \"../types.ts\";\nimport type { RepositoryContext, UpdateHandlerInterface } from \"./abstract.ts\";\nimport {\n\tAbstractResourceRepository,\n\tAbstractUpdateHandler,\n} from \"./abstract.ts\";\nimport {\n\tcreateCustomFields,\n\tgetReferenceFromResourceIdentifier,\n} from \"./helpers.ts\";\n\nexport class ReviewRepository extends AbstractResourceRepository<\"review\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"review\", config);\n\t\tthis.actions = new ReviewUpdateHandler(config.storage);\n\t\tthis.draftSchema = ReviewDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: ReviewDraft,\n\t): Promise<Review> {\n\t\tif (!draft.target)\n\t\t\tthrow new CommercetoolsError<RequiredFieldError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"RequiredField\",\n\t\t\t\t\tmessage: \"Missing target\",\n\t\t\t\t\tfield: \"target\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\tconst resource: Review = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tkey: draft.key,\n\t\t\tlocale: draft.locale,\n\t\t\tauthorName: draft.authorName,\n\t\t\ttitle: draft.title,\n\t\t\ttext: draft.text,\n\t\t\trating: draft.rating,\n\t\t\tuniquenessValue: draft.uniquenessValue,\n\t\t\tstate: draft.state\n\t\t\t\t? await getReferenceFromResourceIdentifier<StateReference>(\n\t\t\t\t\t\tdraft.state,\n\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\tthis._storage,\n\t\t\t\t\t)\n\t\t\t\t: undefined,\n\t\t\ttarget: draft.target\n\t\t\t\t? await getReferenceFromResourceIdentifier<\n\t\t\t\t\t\tProductReference | ChannelReference\n\t\t\t\t\t>(draft.target, context.projectKey, this._storage)\n\t\t\t\t: undefined,\n\t\t\tincludedInStatistics: true,\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n\nclass ReviewUpdateHandler\n\textends AbstractUpdateHandler\n\timplements UpdateHandlerInterface<Review, ReviewUpdateAction>\n{\n\tsetAuthorName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Review>,\n\t\t{ authorName }: ReviewSetAuthorNameAction,\n\t) {\n\t\tresource.authorName = authorName;\n\t}\n\n\tsetCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Review>,\n\t\t{ name, value }: ReviewSetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Review>,\n\t\t{ type, fields }: ReviewSetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n\n\tasync setCustomer(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Review>,\n\t\t{ customer }: ReviewSetCustomerAction,\n\t) {\n\t\tresource.customer = customer\n\t\t\t? await getReferenceFromResourceIdentifier<CustomerReference>(\n\t\t\t\t\tcustomer,\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tthis._storage,\n\t\t\t\t)\n\t\t\t: undefined;\n\t}\n\n\tsetKey(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Review>,\n\t\t{ key }: ReviewSetKeyAction,\n\t) {\n\t\tresource.key = key;\n\t}\n\n\tsetLocale(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Review>,\n\t\t{ locale }: ReviewSetLocaleAction,\n\t) {\n\t\tresource.locale = locale;\n\t}\n\n\tsetRating(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Review>,\n\t\t{ rating }: ReviewSetRatingAction,\n\t) {\n\t\tresource.rating = rating;\n\t}\n\n\tasync setTarget(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Review>,\n\t\t{ target }: ReviewSetTargetAction,\n\t) {\n\t\tresource.target = await getReferenceFromResourceIdentifier<\n\t\t\tProductReference | ChannelReference\n\t\t>(target, context.projectKey, this._storage);\n\t}\n\n\tsetText(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Review>,\n\t\t{ text }: ReviewSetTextAction,\n\t) {\n\t\tresource.text = text;\n\t}\n\n\tsetTitle(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Review>,\n\t\t{ title }: ReviewSetTitleAction,\n\t) {\n\t\tresource.title = title;\n\t}\n\n\tasync transitionState(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Review>,\n\t\t{ state }: ReviewTransitionStateAction,\n\t) {\n\t\tresource.state = await getReferenceFromResourceIdentifier<StateReference>(\n\t\t\tstate,\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage,\n\t\t);\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tCustomFieldsDraftSchema,\n\tLocalizedStringSchema,\n\tStoreResourceIdentifierSchema,\n\tTaxCategoryResourceIdentifierSchema,\n\tZoneRateDraftSchema,\n} from \"./common.ts\";\n\nexport const ShippingMethodDraftSchema = z.object({\n\tkey: z.string().nullish(),\n\tname: z.string(),\n\tlocalizedName: LocalizedStringSchema.nullish(),\n\tdescription: z.string().nullish(),\n\tlocalizedDescription: LocalizedStringSchema.nullish(),\n\ttaxCategory: TaxCategoryResourceIdentifierSchema,\n\tzoneRates: z.array(ZoneRateDraftSchema),\n\tactive: z.boolean().nullish(),\n\tisDefault: z.boolean(),\n\tpredicate: z.string().nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\tstores: z.array(StoreResourceIdentifierSchema).nullish(),\n\tcarrier: z.string().nullish(),\n});\n","import type {\n\tShippingRate,\n\tShippingRateDraft,\n} from \"@commercetools/platform-sdk\";\nimport { createCentPrecisionMoney } from \"../helpers.ts\";\n\nexport const transformShippingRate = (\n\trate: ShippingRateDraft,\n): ShippingRate => ({\n\tprice: createCentPrecisionMoney(rate.price),\n\tfreeAbove: rate.freeAbove && createCentPrecisionMoney(rate.freeAbove),\n\ttiers: rate.tiers || [],\n});\n","import { isDeepStrictEqual } from \"node:util\";\nimport type {\n\tShippingMethod,\n\tShippingMethodAddShippingRateAction,\n\tShippingMethodAddStoreAction,\n\tShippingMethodAddZoneAction,\n\tShippingMethodChangeActiveAction,\n\tShippingMethodChangeIsDefaultAction,\n\tShippingMethodChangeNameAction,\n\tShippingMethodChangeTaxCategoryAction,\n\tShippingMethodRemoveShippingRateAction,\n\tShippingMethodRemoveStoreAction,\n\tShippingMethodRemoveZoneAction,\n\tShippingMethodSetCustomFieldAction,\n\tShippingMethodSetCustomTypeAction,\n\tShippingMethodSetDescriptionAction,\n\tShippingMethodSetKeyAction,\n\tShippingMethodSetLocalizedDescriptionAction,\n\tShippingMethodSetLocalizedNameAction,\n\tShippingMethodSetPredicateAction,\n\tShippingMethodSetStoresAction,\n\tShippingMethodUpdateAction,\n\tZoneReference,\n} from \"@commercetools/platform-sdk\";\nimport type { Writable } from \"#src/types.ts\";\nimport type { RepositoryContext, UpdateHandlerInterface } from \"../abstract.ts\";\nimport { AbstractUpdateHandler } from \"../abstract.ts\";\nimport {\n\tgetReferenceFromResourceIdentifier,\n\tgetStoreKeyReference,\n} from \"../helpers.ts\";\nimport { transformShippingRate } from \"./helpers.ts\";\n\nexport class ShippingMethodUpdateHandler\n\textends AbstractUpdateHandler\n\timplements UpdateHandlerInterface<ShippingMethod, ShippingMethodUpdateAction>\n{\n\tchangeTaxCategory: (\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ShippingMethod>,\n\t\taction: ShippingMethodChangeTaxCategoryAction,\n\t) => void;\n\n\taddShippingRate(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ShippingMethod>,\n\t\t{ shippingRate, zone }: ShippingMethodAddShippingRateAction,\n\t) {\n\t\tconst rate = transformShippingRate(shippingRate);\n\n\t\tresource.zoneRates.forEach((zoneRate) => {\n\t\t\tif (zoneRate.zone.id === zone.id) {\n\t\t\t\tzoneRate.shippingRates.push(rate);\n\t\t\t\treturn;\n\t\t\t}\n\t\t});\n\t\tresource.zoneRates.push({\n\t\t\tzone: {\n\t\t\t\ttypeId: \"zone\",\n\t\t\t\tid: zone.id!,\n\t\t\t},\n\t\t\tshippingRates: [rate],\n\t\t});\n\t}\n\n\tasync addZone(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ShippingMethod>,\n\t\t{ zone }: ShippingMethodAddZoneAction,\n\t) {\n\t\tconst zoneReference =\n\t\t\tawait getReferenceFromResourceIdentifier<ZoneReference>(\n\t\t\t\tzone,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t);\n\n\t\tif (resource.zoneRates === undefined) {\n\t\t\tresource.zoneRates = [];\n\t\t}\n\n\t\tresource.zoneRates.push({\n\t\t\tzone: zoneReference,\n\t\t\tshippingRates: [],\n\t\t});\n\t}\n\n\tchangeActive(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ShippingMethod>,\n\t\t{ active }: ShippingMethodChangeActiveAction,\n\t) {\n\t\tresource.active = active;\n\t}\n\n\tchangeIsDefault(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ShippingMethod>,\n\t\t{ isDefault }: ShippingMethodChangeIsDefaultAction,\n\t) {\n\t\tresource.isDefault = isDefault;\n\t}\n\n\tchangeName(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ShippingMethod>,\n\t\t{ name }: ShippingMethodChangeNameAction,\n\t) {\n\t\tresource.name = name;\n\t}\n\n\tremoveShippingRate(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ShippingMethod>,\n\t\t{ shippingRate, zone }: ShippingMethodRemoveShippingRateAction,\n\t) {\n\t\tconst rate = transformShippingRate(shippingRate);\n\n\t\tresource.zoneRates.forEach((zoneRate) => {\n\t\t\tif (zoneRate.zone.id === zone.id) {\n\t\t\t\tzoneRate.shippingRates = zoneRate.shippingRates.filter(\n\t\t\t\t\t(otherRate) => !isDeepStrictEqual(rate, otherRate),\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t}\n\n\tasync addStore(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ShippingMethod>,\n\t\t{ store }: ShippingMethodAddStoreAction,\n\t) {\n\t\tconst reference = await getStoreKeyReference(\n\t\t\tstore,\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage,\n\t\t);\n\t\tif (!resource.stores.some((s) => s.key === reference.key)) {\n\t\t\tresource.stores.push(reference);\n\t\t}\n\t}\n\n\tasync removeStore(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ShippingMethod>,\n\t\t{ store }: ShippingMethodRemoveStoreAction,\n\t) {\n\t\tconst reference = await getStoreKeyReference(\n\t\t\tstore,\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage,\n\t\t);\n\t\tresource.stores = resource.stores.filter((s) => s.key !== reference.key);\n\t}\n\n\tasync setStores(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ShippingMethod>,\n\t\t{ stores }: ShippingMethodSetStoresAction,\n\t) {\n\t\tresource.stores = stores\n\t\t\t? await Promise.all(\n\t\t\t\t\tstores.map((s) =>\n\t\t\t\t\t\tgetStoreKeyReference(s, context.projectKey, this._storage),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t: [];\n\t}\n\n\tremoveZone(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ShippingMethod>,\n\t\t{ zone }: ShippingMethodRemoveZoneAction,\n\t) {\n\t\tresource.zoneRates = resource.zoneRates.filter(\n\t\t\t(zoneRate) => zoneRate.zone.id !== zone.id,\n\t\t);\n\t}\n\n\tsetCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ShippingMethod>,\n\t\t{ name, value }: ShippingMethodSetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<ShippingMethod>,\n\t\t{ type, fields }: ShippingMethodSetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n\n\tsetDescription(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ShippingMethod>,\n\t\t{ description }: ShippingMethodSetDescriptionAction,\n\t) {\n\t\tresource.description = description;\n\t}\n\n\tsetKey(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ShippingMethod>,\n\t\t{ key }: ShippingMethodSetKeyAction,\n\t) {\n\t\tresource.key = key;\n\t}\n\n\tsetLocalizedDescription(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ShippingMethod>,\n\t\t{ localizedDescription }: ShippingMethodSetLocalizedDescriptionAction,\n\t) {\n\t\tresource.localizedDescription = localizedDescription;\n\t}\n\n\tsetLocalizedName(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ShippingMethod>,\n\t\t{ localizedName }: ShippingMethodSetLocalizedNameAction,\n\t) {\n\t\tresource.localizedName = localizedName;\n\t}\n\n\tsetPredicate(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<ShippingMethod>,\n\t\t{ predicate }: ShippingMethodSetPredicateAction,\n\t) {\n\t\tresource.predicate = predicate;\n\t}\n}\n","import type {\n\tShippingMethod,\n\tShippingMethodDraft,\n\tZoneRate,\n\tZoneRateDraft,\n\tZoneReference,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { ShippingMethodDraftSchema } from \"#src/schemas/generated/shipping-method.ts\";\nimport { getBaseResourceProperties } from \"../../helpers.ts\";\nimport { getShippingMethodsMatchingCart } from \"../../shipping.ts\";\nimport type { GetParams, RepositoryContext } from \"../abstract.ts\";\nimport { AbstractResourceRepository } from \"../abstract.ts\";\nimport {\n\tcreateCustomFields,\n\tgetReferenceFromResourceIdentifier,\n\tgetStoreKeyReference,\n} from \"../helpers.ts\";\nimport { ShippingMethodUpdateHandler } from \"./actions.ts\";\nimport { transformShippingRate } from \"./helpers.ts\";\n\nexport class ShippingMethodRepository extends AbstractResourceRepository<\"shipping-method\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"shipping-method\", config);\n\t\tthis.actions = new ShippingMethodUpdateHandler(config.storage);\n\t\tthis.draftSchema = ShippingMethodDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: ShippingMethodDraft,\n\t): Promise<ShippingMethod> {\n\t\tconst zoneRates = draft.zoneRates\n\t\t\t? await Promise.all(\n\t\t\t\t\tdraft.zoneRates.map((z) => this._transformZoneRateDraft(context, z)),\n\t\t\t\t)\n\t\t\t: [];\n\n\t\tconst stores = draft.stores\n\t\t\t? await Promise.all(\n\t\t\t\t\tdraft.stores.map((s) =>\n\t\t\t\t\t\tgetStoreKeyReference(s, context.projectKey, this._storage),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t: [];\n\n\t\tconst resource: ShippingMethod = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\t...draft,\n\t\t\tactive: draft.active ?? true,\n\t\t\tstores,\n\t\t\ttaxCategory: await getReferenceFromResourceIdentifier(\n\t\t\t\tdraft.taxCategory,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t\tzoneRates,\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n\n\t/*\n\t * Retrieves all the ShippingMethods that can ship to the shipping address of\n\t * the given Cart. Each ShippingMethod contains exactly one ShippingRate with\n\t * the flag isMatching set to true. This ShippingRate is used when the\n\t * ShippingMethod is added to the Cart.\n\t */\n\tpublic async matchingCart(\n\t\tcontext: RepositoryContext,\n\t\tcartId: string,\n\t\tparams: GetParams = {},\n\t) {\n\t\tconst cart = await this._storage.get(context.projectKey, \"cart\", cartId);\n\t\tif (!cart) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\treturn await getShippingMethodsMatchingCart(\n\t\t\tcontext,\n\t\t\tthis._storage,\n\t\t\tcart,\n\t\t\tparams,\n\t\t);\n\t}\n\n\tprivate async _transformZoneRateDraft(\n\t\tcontext: RepositoryContext,\n\t\tdraft: ZoneRateDraft,\n\t): Promise<ZoneRate> {\n\t\treturn {\n\t\t\t...draft,\n\t\t\tzone: await getReferenceFromResourceIdentifier<ZoneReference>(\n\t\t\t\tdraft.zone,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t\tshippingRates: draft.shippingRates?.map(transformShippingRate),\n\t\t};\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tChannelResourceIdentifierSchema,\n\tCountryCodeSchema,\n\tCustomerGroupResourceIdentifierSchema,\n\tCustomFieldsDraftSchema,\n\tDiscountedPriceDraftSchema,\n\tMoneySchema,\n\tPriceTierDraftSchema,\n\tRecurrencePolicyResourceIdentifierSchema,\n\tStagedPriceDraftSchema,\n} from \"./common.ts\";\n\nexport const StandalonePriceDraftSchema = z.object({\n\tkey: z.string().nullish(),\n\tsku: z.string(),\n\tvalue: MoneySchema,\n\tcountry: CountryCodeSchema.nullish(),\n\tcustomerGroup: CustomerGroupResourceIdentifierSchema.nullish(),\n\tchannel: ChannelResourceIdentifierSchema.nullish(),\n\tvalidFrom: z.string().nullish(),\n\tvalidUntil: z.string().nullish(),\n\ttiers: z.array(PriceTierDraftSchema).nullish(),\n\tdiscounted: DiscountedPriceDraftSchema.nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\trecurrencePolicy: RecurrencePolicyResourceIdentifierSchema.nullish(),\n\tstaged: StagedPriceDraftSchema.nullish(),\n\tactive: z.boolean().nullish(),\n});\n","import type {\n\tChannelReference,\n\tChannelResourceIdentifier,\n\tDiscountedPriceDraft,\n\tStandalonePrice,\n\tStandalonePriceChangeActiveAction,\n\tStandalonePriceChangeValueAction,\n\tStandalonePriceDraft,\n\tStandalonePriceSetDiscountedPriceAction,\n\tStandalonePriceUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { StandalonePriceDraftSchema } from \"#src/schemas/generated/standalone-price.ts\";\nimport { getBaseResourceProperties } from \"../helpers.ts\";\nimport type { Writable } from \"../types.ts\";\nimport type { RepositoryContext, UpdateHandlerInterface } from \"./abstract.ts\";\nimport {\n\tAbstractResourceRepository,\n\tAbstractUpdateHandler,\n} from \"./abstract.ts\";\nimport { createTypedMoney } from \"./helpers.ts\";\n\nexport class StandAlonePriceRepository extends AbstractResourceRepository<\"standalone-price\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"standalone-price\", config);\n\t\tthis.actions = new StandalonePriceUpdateHandler(this._storage);\n\t\tthis.draftSchema = StandalonePriceDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: StandalonePriceDraft,\n\t): Promise<StandalonePrice> {\n\t\tconst resource: StandalonePrice = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tactive: draft.active ? draft.active : false,\n\t\t\tsku: draft.sku,\n\t\t\tvalue: createTypedMoney(draft.value),\n\t\t\tcountry: draft.country,\n\t\t\tdiscounted: draft.discounted\n\t\t\t\t? transformDiscountDraft(draft.discounted)\n\t\t\t\t: undefined,\n\t\t\tchannel: draft.channel?.id\n\t\t\t\t? this.transformChannelReferenceDraft(draft.channel)\n\t\t\t\t: undefined,\n\t\t\tvalidFrom: draft.validFrom,\n\t\t\tvalidUntil: draft.validUntil,\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n\n\ttransformChannelReferenceDraft(\n\t\tchannel: ChannelResourceIdentifier,\n\t): ChannelReference {\n\t\treturn {\n\t\t\ttypeId: channel.typeId,\n\t\t\tid: channel.id as string,\n\t\t};\n\t}\n}\n\nconst transformDiscountDraft = (discounted: DiscountedPriceDraft) => ({\n\tvalue: createTypedMoney(discounted.value),\n\tdiscount: discounted.discount,\n});\n\nclass StandalonePriceUpdateHandler\n\textends AbstractUpdateHandler\n\timplements\n\t\tPartial<\n\t\t\tUpdateHandlerInterface<StandalonePrice, StandalonePriceUpdateAction>\n\t\t>\n{\n\tchangeValue(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<StandalonePrice>,\n\t\taction: StandalonePriceChangeValueAction,\n\t) {\n\t\tresource.value = createTypedMoney(action.value);\n\t}\n\n\tsetActive(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<StandalonePrice>,\n\t\taction: StandalonePriceChangeActiveAction,\n\t) {\n\t\tresource.active = action.active;\n\t}\n\n\tsetDiscountedPrice(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<StandalonePrice>,\n\t\taction: StandalonePriceSetDiscountedPriceAction,\n\t) {\n\t\tresource.discounted = action.discounted\n\t\t\t? transformDiscountDraft(action.discounted)\n\t\t\t: undefined;\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tLocalizedStringSchema,\n\tStateResourceIdentifierSchema,\n\tStateRoleEnumSchema,\n\tStateTypeEnumSchema,\n} from \"./common.ts\";\n\nexport const StateDraftSchema = z.object({\n\tkey: z.string(),\n\ttype: StateTypeEnumSchema,\n\tname: LocalizedStringSchema.nullish(),\n\tdescription: LocalizedStringSchema.nullish(),\n\tinitial: z.boolean().nullish(),\n\troles: z.array(StateRoleEnumSchema).nullish(),\n\ttransitions: z.array(StateResourceIdentifierSchema).nullish(),\n});\n","import type {\n\tState,\n\tStateAddRolesAction,\n\tStateChangeInitialAction,\n\tStateChangeKeyAction,\n\tStateChangeTypeAction,\n\tStateDraft,\n\tStateReference,\n\tStateRemoveRolesAction,\n\tStateSetDescriptionAction,\n\tStateSetNameAction,\n\tStateSetRolesAction,\n\tStateSetTransitionsAction,\n\tStateUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { StateDraftSchema } from \"#src/schemas/generated/state.ts\";\nimport { getBaseResourceProperties } from \"../helpers.ts\";\nimport type { Writable } from \"../types.ts\";\nimport type { RepositoryContext, UpdateHandlerInterface } from \"./abstract.ts\";\nimport {\n\tAbstractResourceRepository,\n\tAbstractUpdateHandler,\n} from \"./abstract.ts\";\nimport { getReferenceFromResourceIdentifier } from \"./helpers.ts\";\n\nexport class StateRepository extends AbstractResourceRepository<\"state\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"state\", config);\n\t\tthis.actions = new StateUpdateHandler(config.storage);\n\t\tthis.draftSchema = StateDraftSchema;\n\t}\n\n\tasync create(context: RepositoryContext, draft: StateDraft): Promise<State> {\n\t\tconst transitions = await Promise.all(\n\t\t\t(draft.transitions || []).map((t) =>\n\t\t\t\tgetReferenceFromResourceIdentifier<StateReference>(\n\t\t\t\t\tt,\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tthis._storage,\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\n\t\tconst resource: State = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\t...draft,\n\t\t\tbuiltIn: false,\n\t\t\tinitial: draft.initial || false,\n\t\t\ttransitions,\n\t\t};\n\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n\nclass StateUpdateHandler\n\textends AbstractUpdateHandler\n\timplements UpdateHandlerInterface<State, StateUpdateAction>\n{\n\taddRoles(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<State>,\n\t\taction: StateAddRolesAction,\n\t) {\n\t\tif (!resource.roles) {\n\t\t\tresource.roles = [];\n\t\t}\n\t\tfor (const role of action.roles) {\n\t\t\tif (!resource.roles.includes(role)) {\n\t\t\t\tresource.roles.push(role);\n\t\t\t}\n\t\t}\n\t}\n\n\tchangeInitial(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<State>,\n\t\t{ initial }: StateChangeInitialAction,\n\t) {\n\t\tresource.initial = initial;\n\t}\n\n\tchangeKey(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<State>,\n\t\t{ key }: StateChangeKeyAction,\n\t) {\n\t\tresource.key = key;\n\t}\n\n\tchangeType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<State>,\n\t\taction: StateChangeTypeAction,\n\t) {\n\t\tresource.type = action.type;\n\t}\n\n\tremoveRoles(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<State>,\n\t\taction: StateRemoveRolesAction,\n\t) {\n\t\tresource.roles = resource.roles?.filter(\n\t\t\t(role) => !action.roles.includes(role),\n\t\t);\n\t}\n\n\tsetDescription(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<State>,\n\t\t{ description }: StateSetDescriptionAction,\n\t) {\n\t\tresource.description = description;\n\t}\n\n\tsetName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<State>,\n\t\t{ name }: StateSetNameAction,\n\t) {\n\t\tresource.name = name;\n\t}\n\n\tsetRoles(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<State>,\n\t\t{ roles }: StateSetRolesAction,\n\t) {\n\t\tresource.roles = roles;\n\t}\n\n\tsetTransitions(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<State>,\n\t\t{ transitions }: StateSetTransitionsAction,\n\t) {\n\t\tresource.transitions = transitions?.map(\n\t\t\t(resourceId): StateReference => ({\n\t\t\t\tid: resourceId.id || \"\",\n\t\t\t\ttypeId: \"state\",\n\t\t\t}),\n\t\t);\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tChannelResourceIdentifierSchema,\n\tCustomFieldsDraftSchema,\n\tLocaleSchema,\n\tLocalizedStringSchema,\n\tProductSelectionSettingDraftSchema,\n\tStoreCountrySchema,\n\tStorefrontSchema,\n} from \"./common.ts\";\n\nexport const StoreDraftSchema = z.object({\n\tkey: z.string(),\n\tname: LocalizedStringSchema.nullish(),\n\tlanguages: z.array(LocaleSchema).nullish(),\n\tcountries: z.array(StoreCountrySchema).nullish(),\n\tdistributionChannels: z.array(ChannelResourceIdentifierSchema).nullish(),\n\tsupplyChannels: z.array(ChannelResourceIdentifierSchema).nullish(),\n\tproductSelections: z.array(ProductSelectionSettingDraftSchema).nullish(),\n\tcustom: CustomFieldsDraftSchema.nullish(),\n\tstorefront: StorefrontSchema.nullish(),\n});\n","import type {\n\tChannelReference,\n\tChannelResourceIdentifier,\n\tStore,\n\tStoreDraft,\n\tStoreSetCountriesAction,\n\tStoreSetCustomFieldAction,\n\tStoreSetCustomTypeAction,\n\tStoreSetDistributionChannelsAction,\n\tStoreSetLanguagesAction,\n\tStoreSetNameAction,\n\tStoreUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { StoreDraftSchema } from \"#src/schemas/generated/store.ts\";\nimport { getBaseResourceProperties } from \"../helpers.ts\";\nimport type { AbstractStorage } from \"../storage/abstract.ts\";\nimport type { Writable } from \"../types.ts\";\nimport type { RepositoryContext, UpdateHandlerInterface } from \"./abstract.ts\";\nimport {\n\tAbstractResourceRepository,\n\tAbstractUpdateHandler,\n} from \"./abstract.ts\";\nimport {\n\tcreateCustomFields,\n\tgetReferenceFromResourceIdentifier,\n} from \"./helpers.ts\";\n\nexport class StoreRepository extends AbstractResourceRepository<\"store\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"store\", config);\n\t\tthis.actions = new StoreUpdateHandler(this._storage);\n\t\tthis.draftSchema = StoreDraftSchema;\n\t}\n\n\tasync create(context: RepositoryContext, draft: StoreDraft): Promise<Store> {\n\t\tconst resource: Store = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tkey: draft.key,\n\t\t\tname: draft.name,\n\t\t\tlanguages: draft.languages ?? [],\n\t\t\tcountries: draft.countries ?? [],\n\t\t\tdistributionChannels: await transformChannels(\n\t\t\t\tcontext,\n\t\t\t\tthis._storage,\n\t\t\t\tdraft.distributionChannels,\n\t\t\t),\n\t\t\tsupplyChannels: await transformChannels(\n\t\t\t\tcontext,\n\t\t\t\tthis._storage,\n\t\t\t\tdraft.supplyChannels,\n\t\t\t),\n\t\t\tproductSelections: [],\n\t\t\tcustom: await createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage,\n\t\t\t),\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n\nconst transformChannels = async (\n\tcontext: RepositoryContext,\n\tstorage: AbstractStorage,\n\tchannels?: ChannelResourceIdentifier[],\n) => {\n\tif (!channels) return [];\n\n\treturn Promise.all(\n\t\tchannels.map((ref) =>\n\t\t\tgetReferenceFromResourceIdentifier<ChannelReference>(\n\t\t\t\tref,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tstorage,\n\t\t\t),\n\t\t),\n\t);\n};\n\nclass StoreUpdateHandler\n\textends AbstractUpdateHandler\n\timplements Partial<UpdateHandlerInterface<Store, StoreUpdateAction>>\n{\n\tsetCountries(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Store>,\n\t\t{ countries }: StoreSetCountriesAction,\n\t) {\n\t\tresource.countries = countries ?? [];\n\t}\n\n\tsetCustomField(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Store>,\n\t\t{ name, value }: StoreSetCustomFieldAction,\n\t) {\n\t\tthis._setCustomFieldValues(resource, { name, value });\n\t}\n\n\tasync setCustomType(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Store>,\n\t\t{ type, fields }: StoreSetCustomTypeAction,\n\t) {\n\t\tawait this._setCustomType(context, resource, { type, fields });\n\t}\n\n\tasync setDistributionChannels(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Store>,\n\t\t{ distributionChannels }: StoreSetDistributionChannelsAction,\n\t) {\n\t\tresource.distributionChannels = await transformChannels(\n\t\t\tcontext,\n\t\t\tthis._storage,\n\t\t\tdistributionChannels,\n\t\t);\n\t}\n\n\tsetLanguages(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Store>,\n\t\t{ languages }: StoreSetLanguagesAction,\n\t) {\n\t\tresource.languages = languages ?? [];\n\t}\n\n\tsetName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Store>,\n\t\t{ name }: StoreSetNameAction,\n\t) {\n\t\tresource.name = name;\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tChangeSubscriptionSchema,\n\tDeliveryFormatSchema,\n\tDestinationSchema,\n\tEventSubscriptionSchema,\n\tMessageSubscriptionSchema,\n} from \"./common.ts\";\n\nexport const SubscriptionDraftSchema = z.object({\n\tdestination: DestinationSchema,\n\tkey: z.string().nullish(),\n\tmessages: z.array(MessageSubscriptionSchema).nullish(),\n\tchanges: z.array(ChangeSubscriptionSchema).nullish(),\n\tevents: z.array(EventSubscriptionSchema).nullish(),\n\tformat: DeliveryFormatSchema.nullish(),\n});\n","import type {\n\tInvalidInputError,\n\tSubscription,\n\tSubscriptionDraft,\n\tSubscriptionSetKeyAction,\n\tSubscriptionUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { SubscriptionDraftSchema } from \"#src/schemas/generated/subscription.ts\";\nimport { getBaseResourceProperties } from \"../helpers.ts\";\nimport type { Writable } from \"../types.ts\";\nimport type { RepositoryContext, UpdateHandlerInterface } from \"./abstract.ts\";\nimport {\n\tAbstractResourceRepository,\n\tAbstractUpdateHandler,\n} from \"./abstract.ts\";\n\nexport class SubscriptionRepository extends AbstractResourceRepository<\"subscription\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"subscription\", config);\n\t\tthis.actions = new SubscriptionUpdateHandler(config.storage);\n\t\tthis.draftSchema = SubscriptionDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: SubscriptionDraft,\n\t): Promise<Subscription> {\n\t\t// TODO: We could actually test this here by using the aws sdk. For now\n\t\t// hardcode a failed check when account id is 0000000000\n\t\tif (draft.destination.type === \"SQS\") {\n\t\t\tconst queueURL = new URL(draft.destination.queueUrl);\n\t\t\tconst accountId = queueURL.pathname.split(\"/\")[1];\n\t\t\tif (accountId === \"0000000000\") {\n\t\t\t\tconst dest = draft.destination;\n\t\t\t\tthrow new CommercetoolsError<InvalidInputError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidInput\",\n\t\t\t\t\t\tmessage: `A test message could not be delivered to this destination: SQS ${dest.queueUrl} in ${dest.region} for ${dest.accessKey}. Please make sure your destination is correctly configured.`,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst resource: Subscription = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tchanges: draft.changes || [],\n\t\t\tdestination: draft.destination,\n\t\t\tformat: draft.format || {\n\t\t\t\ttype: \"Platform\",\n\t\t\t},\n\t\t\tkey: draft.key,\n\t\t\tmessages: draft.messages || [],\n\t\t\tstatus: \"Healthy\",\n\t\t\tevents: draft.events || [],\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n\nclass SubscriptionUpdateHandler\n\textends AbstractUpdateHandler\n\timplements\n\t\tPartial<UpdateHandlerInterface<Subscription, SubscriptionUpdateAction>>\n{\n\tsetKey(\n\t\t_context: RepositoryContext,\n\t\tresource: Writable<Subscription>,\n\t\t{ key }: SubscriptionSetKeyAction,\n\t) {\n\t\tresource.key = key;\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport { TaxRateDraftSchema } from \"./common.ts\";\n\nexport const TaxCategoryDraftSchema = z.object({\n\tname: z.string(),\n\tdescription: z.string().nullish(),\n\trates: z.array(TaxRateDraftSchema).nullish(),\n\tkey: z.string().nullish(),\n});\n","import type { TaxRate, TaxRateDraft } from \"@commercetools/platform-sdk\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nexport const taxRateFromTaxRateDraft = (draft: TaxRateDraft): TaxRate => ({\n\t...draft,\n\tid: uuidv4(),\n\tamount: draft.amount || 0,\n});\n","import type {\n\tTaxCategory,\n\tTaxCategoryAddTaxRateAction,\n\tTaxCategoryChangeNameAction,\n\tTaxCategoryRemoveTaxRateAction,\n\tTaxCategoryReplaceTaxRateAction,\n\tTaxCategorySetDescriptionAction,\n\tTaxCategorySetKeyAction,\n\tTaxCategoryUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type { Writable } from \"#src/types.ts\";\nimport type { RepositoryContext } from \"../abstract.ts\";\nimport { AbstractUpdateHandler } from \"../abstract.ts\";\nimport { taxRateFromTaxRateDraft } from \"./helpers.ts\";\n\ntype TaxCategoryUpdateHandlerMethod<T> = (\n\tcontext: RepositoryContext,\n\tresource: Writable<TaxCategory>,\n\taction: T,\n) => void;\n\ntype TaxCategoryUpdateActions = {\n\t[P in TaxCategoryUpdateAction as P[\"action\"]]: TaxCategoryUpdateHandlerMethod<P>;\n};\n\nexport class TaxCategoryUpdateHandler\n\textends AbstractUpdateHandler\n\timplements TaxCategoryUpdateActions\n{\n\taddTaxRate(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<TaxCategory>,\n\t\t{ taxRate }: TaxCategoryAddTaxRateAction,\n\t) {\n\t\tif (resource.rates === undefined) {\n\t\t\tresource.rates = [];\n\t\t}\n\t\tresource.rates.push(taxRateFromTaxRateDraft(taxRate));\n\t}\n\n\tchangeName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<TaxCategory>,\n\t\t{ name }: TaxCategoryChangeNameAction,\n\t) {\n\t\tresource.name = name;\n\t}\n\n\tremoveTaxRate(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<TaxCategory>,\n\t\t{ taxRateId }: TaxCategoryRemoveTaxRateAction,\n\t) {\n\t\tif (resource.rates === undefined) {\n\t\t\tresource.rates = [];\n\t\t}\n\t\tresource.rates = resource.rates.filter(\n\t\t\t(taxRate) => taxRate.id !== taxRateId,\n\t\t);\n\t}\n\n\treplaceTaxRate(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<TaxCategory>,\n\t\t{ taxRateId, taxRate }: TaxCategoryReplaceTaxRateAction,\n\t) {\n\t\tif (resource.rates === undefined) {\n\t\t\tresource.rates = [];\n\t\t}\n\n\t\tconst taxRateObj = taxRateFromTaxRateDraft(taxRate);\n\t\tfor (let i = 0; i < resource.rates.length; i++) {\n\t\t\tconst rate = resource.rates[i];\n\t\t\tif (rate.id === taxRateId) {\n\t\t\t\tresource.rates[i] = taxRateObj;\n\t\t\t}\n\t\t}\n\t}\n\n\tsetDescription(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<TaxCategory>,\n\t\t{ description }: TaxCategorySetDescriptionAction,\n\t) {\n\t\tresource.description = description;\n\t}\n\n\tsetKey(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<TaxCategory>,\n\t\t{ key }: TaxCategorySetKeyAction,\n\t) {\n\t\tresource.key = key;\n\t}\n}\n","import type {\n\tTaxCategory,\n\tTaxCategoryDraft,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { getBaseResourceProperties } from \"#src/helpers.ts\";\nimport { TaxCategoryDraftSchema } from \"#src/schemas/generated/tax-category.ts\";\nimport type { RepositoryContext } from \"../abstract.ts\";\nimport { AbstractResourceRepository } from \"../abstract.ts\";\nimport { TaxCategoryUpdateHandler } from \"./actions.ts\";\nimport { taxRateFromTaxRateDraft } from \"./helpers.ts\";\n\nexport class TaxCategoryRepository extends AbstractResourceRepository<\"tax-category\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"tax-category\", config);\n\t\tthis.actions = new TaxCategoryUpdateHandler(this._storage);\n\t\tthis.draftSchema = TaxCategoryDraftSchema;\n\t}\n\n\tasync create(\n\t\tcontext: RepositoryContext,\n\t\tdraft: TaxCategoryDraft,\n\t): Promise<TaxCategory> {\n\t\tconst resource: TaxCategory = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\t...draft,\n\t\t\trates: draft.rates?.map(taxRateFromTaxRateDraft) || [],\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tFieldDefinitionSchema,\n\tLocalizedStringSchema,\n\tResourceTypeIdSchema,\n} from \"./common.ts\";\n\nexport const TypeDraftSchema = z.object({\n\tkey: z.string(),\n\tname: LocalizedStringSchema,\n\tdescription: LocalizedStringSchema.nullish(),\n\tresourceTypeIds: z.array(ResourceTypeIdSchema),\n\tfieldDefinitions: z.array(FieldDefinitionSchema).nullish(),\n});\n","import { isDeepStrictEqual } from \"node:util\";\nimport type {\n\tFieldDefinition,\n\tInvalidOperationError,\n\tType,\n\tTypeAddEnumValueAction,\n\tTypeAddFieldDefinitionAction,\n\tTypeChangeEnumValueLabelAction,\n\tTypeChangeFieldDefinitionOrderAction,\n\tTypeChangeNameAction,\n\tTypeRemoveFieldDefinitionAction,\n\tTypeSetDescriptionAction,\n\tTypeUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport type { Writable } from \"#src/types.ts\";\nimport type { RepositoryContext } from \"../abstract.ts\";\nimport { AbstractUpdateHandler } from \"../abstract.ts\";\n\ntype TypeUpdateHandlerMethod<T> = (\n\tcontext: RepositoryContext,\n\tresource: Writable<Type>,\n\taction: T,\n) => void;\n\ntype TypeUpdateActions = Partial<{\n\t[P in TypeUpdateAction as P[\"action\"]]: TypeUpdateHandlerMethod<P>;\n}>;\n\nexport class TypeUpdateHandler\n\textends AbstractUpdateHandler\n\timplements TypeUpdateActions\n{\n\taddEnumValue(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Type>,\n\t\t{ fieldName, value }: TypeAddEnumValueAction,\n\t) {\n\t\tresource.fieldDefinitions.forEach((field) => {\n\t\t\tif (field.name === fieldName) {\n\t\t\t\t// TODO, should be done better i suppose\n\t\t\t\tif (field.type.name === \"Enum\") {\n\t\t\t\t\tfield.type.values.push(value);\n\t\t\t\t} else if (\n\t\t\t\t\tfield.type.name === \"Set\" &&\n\t\t\t\t\tfield.type.elementType.name === \"Enum\"\n\t\t\t\t) {\n\t\t\t\t\tfield.type.elementType.values.push(value);\n\t\t\t\t} else {\n\t\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\t\tmessage: \"Type is not a Enum (or Set of Enum)\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t400,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\taddFieldDefinition(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Type>,\n\t\t{ fieldDefinition }: TypeAddFieldDefinitionAction,\n\t) {\n\t\tresource.fieldDefinitions.push(fieldDefinition);\n\t}\n\n\tchangeEnumValueLabel(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Type>,\n\t\t{ fieldName, value }: TypeChangeEnumValueLabelAction,\n\t) {\n\t\tresource.fieldDefinitions.forEach((field) => {\n\t\t\tif (field.name === fieldName) {\n\t\t\t\t// TODO, should be done better i suppose\n\t\t\t\tif (field.type.name === \"Enum\") {\n\t\t\t\t\tfield.type.values.forEach((v) => {\n\t\t\t\t\t\tif (v.key === value.key) {\n\t\t\t\t\t\t\tv.label = value.label;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t} else if (\n\t\t\t\t\tfield.type.name === \"Set\" &&\n\t\t\t\t\tfield.type.elementType.name === \"Enum\"\n\t\t\t\t) {\n\t\t\t\t\tfield.type.elementType.values.forEach((v) => {\n\t\t\t\t\t\tif (v.key === value.key) {\n\t\t\t\t\t\t\tv.label = value.label;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\t\tmessage: \"Type is not a Enum (or Set of Enum)\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t400,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tchangeFieldDefinitionOrder(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Type>,\n\t\t{ fieldNames }: TypeChangeFieldDefinitionOrderAction,\n\t) {\n\t\tconst fields = new Map(\n\t\t\tresource.fieldDefinitions.map((item) => [item.name, item]),\n\t\t);\n\t\tconst result: FieldDefinition[] = [];\n\t\tlet current = resource.fieldDefinitions;\n\n\t\tfieldNames.forEach((fieldName) => {\n\t\t\tconst field = fields.get(fieldName);\n\t\t\tif (field === undefined) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\t\t\tmessage: \"Adding new field definitions is not fully supported yet\",\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tresult.push(field);\n\n\t\t\t// Remove from current items\n\t\t\tcurrent = current.filter((f) => f.name !== fieldName);\n\t\t});\n\n\t\tif (\n\t\t\tisDeepStrictEqual(\n\t\t\t\tfieldNames,\n\t\t\t\tresource.fieldDefinitions.map((item) => item.name),\n\t\t\t)\n\t\t) {\n\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\tcode: \"InvalidOperation\",\n\t\t\t\tmessage: \"'fieldDefinitions' has no changes.\",\n\t\t\t\taction: {\n\t\t\t\t\taction: \"changeFieldDefinitionOrder\",\n\t\t\t\t\tfieldNames: fieldNames,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\tresource.fieldDefinitions = result;\n\t\t// Add fields which were not specified in the order as last items. Not\n\t\t// sure if this follows commercetools\n\t\tresource.fieldDefinitions.push(...current);\n\t}\n\n\tchangeName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Type>,\n\t\t{ name }: TypeChangeNameAction,\n\t) {\n\t\tresource.name = name;\n\t}\n\n\tremoveFieldDefinition(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Type>,\n\t\t{ fieldName }: TypeRemoveFieldDefinitionAction,\n\t) {\n\t\tresource.fieldDefinitions = resource.fieldDefinitions.filter(\n\t\t\t(f) => f.name !== fieldName,\n\t\t);\n\t}\n\n\tsetDescription(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Type>,\n\t\t{ description }: TypeSetDescriptionAction,\n\t) {\n\t\tresource.description = description;\n\t}\n}\n","import type { Type, TypeDraft } from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { getBaseResourceProperties } from \"#src/helpers.ts\";\nimport { TypeDraftSchema } from \"#src/schemas/generated/type.ts\";\nimport type { RepositoryContext } from \"../abstract.ts\";\nimport { AbstractResourceRepository } from \"../abstract.ts\";\nimport { TypeUpdateHandler } from \"./actions.ts\";\n\nexport class TypeRepository extends AbstractResourceRepository<\"type\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"type\", config);\n\t\tthis.actions = new TypeUpdateHandler(config.storage);\n\t\tthis.draftSchema = TypeDraftSchema;\n\t}\n\n\tasync create(context: RepositoryContext, draft: TypeDraft): Promise<Type> {\n\t\tconst resource: Type = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tkey: draft.key,\n\t\t\tname: draft.name,\n\t\t\tresourceTypeIds: draft.resourceTypeIds,\n\t\t\tfieldDefinitions: draft.fieldDefinitions || [],\n\t\t\tdescription: draft.description,\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport { LocationSchema } from \"./common.ts\";\n\nexport const ZoneDraftSchema = z.object({\n\tkey: z.string().nullish(),\n\tname: z.string(),\n\tdescription: z.string().nullish(),\n\tlocations: z.array(LocationSchema).nullish(),\n});\n","import type {\n\tZone,\n\tZoneAddLocationAction,\n\tZoneChangeNameAction,\n\tZoneDraft,\n\tZoneRemoveLocationAction,\n\tZoneSetDescriptionAction,\n\tZoneSetKeyAction,\n\tZoneUpdateAction,\n} from \"@commercetools/platform-sdk\";\nimport type { Config } from \"#src/config.ts\";\nimport { ZoneDraftSchema } from \"#src/schemas/generated/zone.ts\";\nimport { getBaseResourceProperties } from \"../helpers.ts\";\nimport type { Writable } from \"../types.ts\";\nimport type { RepositoryContext, UpdateHandlerInterface } from \"./abstract.ts\";\nimport {\n\tAbstractResourceRepository,\n\tAbstractUpdateHandler,\n} from \"./abstract.ts\";\n\nexport class ZoneRepository extends AbstractResourceRepository<\"zone\"> {\n\tconstructor(config: Config) {\n\t\tsuper(\"zone\", config);\n\t\tthis.actions = new ZoneUpdateHandler(config.storage);\n\t\tthis.draftSchema = ZoneDraftSchema;\n\t}\n\n\tasync create(context: RepositoryContext, draft: ZoneDraft): Promise<Zone> {\n\t\tconst resource: Zone = {\n\t\t\t...getBaseResourceProperties(context.clientId),\n\t\t\tkey: draft.key,\n\t\t\tlocations: draft.locations || [],\n\t\t\tname: draft.name,\n\t\t\tdescription: draft.description,\n\t\t};\n\t\treturn await this.saveNew(context, resource);\n\t}\n}\n\nclass ZoneUpdateHandler\n\textends AbstractUpdateHandler\n\timplements Partial<UpdateHandlerInterface<Zone, ZoneUpdateAction>>\n{\n\taddLocation(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Zone>,\n\t\t{ location }: ZoneAddLocationAction,\n\t) {\n\t\tresource.locations.push(location);\n\t}\n\n\tchangeName(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Zone>,\n\t\t{ name }: ZoneChangeNameAction,\n\t) {\n\t\tresource.name = name;\n\t}\n\n\tremoveLocation(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Zone>,\n\t\t{ location }: ZoneRemoveLocationAction,\n\t) {\n\t\tresource.locations = resource.locations.filter(\n\t\t\t(loc) =>\n\t\t\t\t!(loc.country === location.country && loc.state === location.state),\n\t\t);\n\t}\n\n\tsetDescription(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Zone>,\n\t\t{ description }: ZoneSetDescriptionAction,\n\t) {\n\t\tresource.description = description;\n\t}\n\n\tsetKey(\n\t\tcontext: RepositoryContext,\n\t\tresource: Writable<Zone>,\n\t\t{ key }: ZoneSetKeyAction,\n\t) {\n\t\tresource.key = key;\n\t}\n}\n","import type { Config } from \"#src/config.ts\";\nimport { ProductTailoringRepository } from \"#src/repositories/product-tailoring.ts\";\nimport { ApprovalFlowRepository } from \"./approval-flow.ts\";\nimport { ApprovalRuleRepository } from \"./approval-rule.ts\";\nimport {\n\tAsAssociateApprovalFlowRepository,\n\tAsAssociateApprovalRuleRepository,\n\tAsAssociateBusinessUnitRepository,\n\tAsAssociateCartRepository,\n\tAsAssociateOrderRepository,\n\tAsAssociateQuoteRepository,\n\tAsAssociateQuoteRequestRepository,\n\tAsAssociateShoppingListRepository,\n} from \"./as-associate.ts\";\nimport { AssociateRoleRepository } from \"./associate-role.ts\";\nimport { AttributeGroupRepository } from \"./attribute-group.ts\";\nimport { BusinessUnitRepository } from \"./business-unit.ts\";\nimport { CartRepository } from \"./cart/index.ts\";\nimport { CartDiscountRepository } from \"./cart-discount/index.ts\";\nimport { CategoryRepository } from \"./category/index.ts\";\nimport { ChannelRepository } from \"./channel.ts\";\nimport { CustomObjectRepository } from \"./custom-object.ts\";\nimport { CustomerRepository } from \"./customer/index.ts\";\nimport { CustomerGroupRepository } from \"./customer-group.ts\";\nimport { DiscountCodeRepository } from \"./discount-code/index.ts\";\nimport { DiscountGroupRepository } from \"./discount-group/index.ts\";\nimport { ExtensionRepository } from \"./extension.ts\";\nimport { InventoryEntryRepository } from \"./inventory-entry/index.ts\";\nimport { MyCustomerRepository } from \"./my-customer.ts\";\nimport { MyOrderRepository } from \"./my-order.ts\";\nimport { OrderRepository } from \"./order/index.ts\";\nimport { OrderEditRepository } from \"./order-edit.ts\";\nimport { PaymentRepository } from \"./payment/index.ts\";\nimport { ProductRepository } from \"./product/index.ts\";\nimport { ProductDiscountRepository } from \"./product-discount.ts\";\nimport { ProductProjectionRepository } from \"./product-projection.ts\";\nimport { ProductSelectionRepository } from \"./product-selection.ts\";\nimport { ProductTypeRepository } from \"./product-type.ts\";\nimport { ProjectRepository } from \"./project.ts\";\nimport { QuoteRepository } from \"./quote/index.ts\";\nimport { QuoteRequestRepository } from \"./quote-request/index.ts\";\nimport { StagedQuoteRepository } from \"./quote-staged/index.ts\";\nimport { RecurrencePolicyRepository } from \"./recurrence-policy/index.ts\";\nimport { RecurringOrderRepository } from \"./recurring-order/index.ts\";\nimport { ReviewRepository } from \"./review.ts\";\nimport { ShippingMethodRepository } from \"./shipping-method/index.ts\";\nimport { ShoppingListRepository } from \"./shopping-list/index.ts\";\nimport { StandAlonePriceRepository } from \"./standalone-price.ts\";\nimport { StateRepository } from \"./state.ts\";\nimport { StoreRepository } from \"./store.ts\";\nimport { SubscriptionRepository } from \"./subscription.ts\";\nimport { TaxCategoryRepository } from \"./tax-category/index.ts\";\nimport { TypeRepository } from \"./type/index.ts\";\nimport { ZoneRepository } from \"./zone.ts\";\n\nexport type RepositoryMap = ReturnType<typeof createRepositories>;\n\nexport const createRepositories = (config: Config) => ({\n\t\"as-associate\": {\n\t\t\"approval-flow\": new AsAssociateApprovalFlowRepository(config),\n\t\t\"approval-rule\": new AsAssociateApprovalRuleRepository(config),\n\t\t\"business-unit\": new AsAssociateBusinessUnitRepository(config),\n\t\tcart: new AsAssociateCartRepository(config),\n\t\torder: new AsAssociateOrderRepository(config),\n\t\tquote: new AsAssociateQuoteRepository(config),\n\t\t\"quote-request\": new AsAssociateQuoteRequestRepository(config),\n\t\t\"shopping-list\": new AsAssociateShoppingListRepository(config),\n\t},\n\t\"approval-flow\": new ApprovalFlowRepository(config),\n\t\"approval-rule\": new ApprovalRuleRepository(config),\n\t\"associate-role\": new AssociateRoleRepository(config),\n\t\"attribute-group\": new AttributeGroupRepository(config),\n\t\"business-unit\": new BusinessUnitRepository(config),\n\tcategory: new CategoryRepository(config),\n\tcart: new CartRepository(config),\n\t\"cart-discount\": new CartDiscountRepository(config),\n\tcustomer: new CustomerRepository(config),\n\tchannel: new ChannelRepository(config),\n\t\"customer-group\": new CustomerGroupRepository(config),\n\t\"discount-code\": new DiscountCodeRepository(config),\n\t\"discount-group\": new DiscountGroupRepository(config),\n\textension: new ExtensionRepository(config),\n\t\"inventory-entry\": new InventoryEntryRepository(config),\n\t\"key-value-document\": new CustomObjectRepository(config),\n\torder: new OrderRepository(config),\n\t\"order-edit\": new OrderEditRepository(config),\n\tpayment: new PaymentRepository(config),\n\t\"my-cart\": new CartRepository(config),\n\t\"my-order\": new MyOrderRepository(config),\n\t\"my-customer\": new MyCustomerRepository(config),\n\t\"my-payment\": new PaymentRepository(config),\n\t\"my-shopping-list\": new ShoppingListRepository(config),\n\tproduct: new ProductRepository(config),\n\t\"product-type\": new ProductTypeRepository(config),\n\t\"product-discount\": new ProductDiscountRepository(config),\n\t\"product-projection\": new ProductProjectionRepository(config),\n\t\"product-selection\": new ProductSelectionRepository(config),\n\t\"product-tailoring\": new ProductTailoringRepository(config),\n\tproject: new ProjectRepository(config),\n\t\"recurring-order\": new RecurringOrderRepository(config),\n\t\"recurrence-policy\": new RecurrencePolicyRepository(config),\n\treview: new ReviewRepository(config),\n\tquote: new QuoteRepository(config),\n\t\"quote-request\": new QuoteRequestRepository(config),\n\t\"shipping-method\": new ShippingMethodRepository(config),\n\t\"shopping-list\": new ShoppingListRepository(config),\n\t\"staged-quote\": new StagedQuoteRepository(config),\n\t\"standalone-price\": new StandAlonePriceRepository(config),\n\tstate: new StateRepository(config),\n\tstore: new StoreRepository(config),\n\tsubscription: new SubscriptionRepository(config),\n\t\"tax-category\": new TaxCategoryRepository(config),\n\ttype: new TypeRepository(config),\n\tzone: new ZoneRepository(config),\n});\n","import { z } from \"zod\";\n\nconst UpdateActionSchema = z.looseObject({\n\taction: z.string(),\n});\n\nexport const updateRequestSchema = z.object({\n\tversion: z.number(),\n\tactions: z.array(UpdateActionSchema),\n});\n","import type { InvalidJsonInputError } from \"@commercetools/platform-sdk\";\nimport type { z } from \"zod\";\nimport { CommercetoolsError } from \"./exceptions.ts\";\n\n/**\n * Format a Zod error into a commercetools-style detailedErrorMessage.\n *\n * The real API uses messages like:\n *   \"quantityOnStock: Missing required value\"\n *   \"name: JSON object expected.\"\n *   \"roles: Invalid enum value. Expected one of: 'InventorySupply', ...\"\n *\n * We use the first issue only, matching the real API behaviour of reporting\n * a single detailed message.\n */\nexport function formatDetailedErrorMessage(error: z.ZodError): string {\n\tconst issue = error.issues[0];\n\tif (!issue) return \"Unknown error\";\n\n\tconst path = issue.path.join(\".\");\n\n\t// Missing required field: Zod reports invalid_type with \"received undefined\"\n\tif (\n\t\tissue.code === \"invalid_type\" &&\n\t\tissue.message.includes(\"received undefined\")\n\t) {\n\t\treturn `${path}: Missing required value`;\n\t}\n\n\t// Wrong type (e.g. string received instead of number)\n\tif (issue.code === \"invalid_type\") {\n\t\tconst expected = (issue as any).expected;\n\t\tswitch (expected) {\n\t\t\tcase \"string\":\n\t\t\t\treturn `${path}: JSON String expected.`;\n\t\t\tcase \"number\":\n\t\t\tcase \"integer\":\n\t\t\t\treturn `${path}: JSON Number expected.`;\n\t\t\tcase \"boolean\":\n\t\t\t\treturn `${path}: JSON Boolean expected.`;\n\t\t\tcase \"object\":\n\t\t\t\treturn `${path}: JSON object expected.`;\n\t\t\tcase \"array\":\n\t\t\t\treturn `${path}: JSON Array expected.`;\n\t\t\tdefault:\n\t\t\t\treturn `${path}: Invalid type: expected ${expected}`;\n\t\t}\n\t}\n\n\t// Invalid enum value\n\tif (issue.code === \"invalid_value\") {\n\t\tconst values = (issue as any).values;\n\t\tif (Array.isArray(values)) {\n\t\t\tconst formatted = values.map((v: string) => `'${v}'`).join(\", \");\n\t\t\treturn `${path}: Invalid enum value. Expected one of: ${formatted}`;\n\t\t}\n\t}\n\n\t// Refine errors (e.g. ResourceIdentifier id-or-key check)\n\tif (issue.code === \"custom\") {\n\t\treturn issue.message;\n\t}\n\n\t// Fallback: use Zod's message with path prefix\n\treturn path ? `${path}: ${issue.message}` : issue.message;\n}\n\nexport const validateData = <T>(data: any, schema: z.ZodType) => {\n\tconst result = schema.safeParse(data);\n\tif (result.success) {\n\t\treturn data as T;\n\t}\n\tthrow new CommercetoolsError<InvalidJsonInputError>({\n\t\tcode: \"InvalidJsonInput\",\n\t\tmessage: \"Request body does not contain valid JSON.\",\n\t\tdetailedErrorMessage: formatDetailedErrorMessage(result.error),\n\t});\n};\n\nexport const validateDraft = (data: unknown, schema: z.ZodType): void => {\n\tconst result = schema.safeParse(data);\n\tif (!result.success) {\n\t\tthrow new CommercetoolsError<InvalidJsonInputError>({\n\t\t\tcode: \"InvalidJsonInput\",\n\t\t\tmessage: \"Request body does not contain valid JSON.\",\n\t\t\tdetailedErrorMessage: formatDetailedErrorMessage(result.error),\n\t\t});\n\t}\n};\n","import type {\n\tResourceNotFoundError,\n\tUpdate,\n} from \"@commercetools/platform-sdk\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport type { ParsedQs } from \"qs\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { updateRequestSchema } from \"#src/schemas/update-request.ts\";\nimport { validateData, validateDraft } from \"#src/validate.ts\";\nimport { queryParamsArray } from \"../helpers.ts\";\nimport type {\n\tAbstractResourceRepository,\n\tQueryParams,\n} from \"../repositories/abstract.ts\";\nimport { getRepositoryContext } from \"../repositories/helpers.ts\";\n\nexport default abstract class AbstractService {\n\tpublic abstract repository: AbstractResourceRepository<any>;\n\n\tcreateStatusCode = 201;\n\n\tconstructor(parent: FastifyInstance) {\n\t\tthis.registerRoutes(parent);\n\t}\n\n\tprotected abstract getBasePath(): string;\n\n\textraRoutes(instance: FastifyInstance) {}\n\n\tregisterRoutes(parent: FastifyInstance) {\n\t\tconst basePath = this.getBasePath();\n\t\tparent.register(\n\t\t\t(instance, opts, done) => {\n\t\t\t\tthis.extraRoutes(instance);\n\n\t\t\t\tinstance.get(\"/\", this.get.bind(this));\n\t\t\t\tinstance.get(\"/key=:key\", this.getWithKey.bind(this));\n\t\t\t\tinstance.get(\"/:id\", this.getWithId.bind(this));\n\n\t\t\t\tinstance.delete(\"/key=:key\", this.deleteWithKey.bind(this));\n\t\t\t\tinstance.delete(\"/:id\", this.deleteWithId.bind(this));\n\n\t\t\t\tinstance.post(\"/\", this.post.bind(this));\n\t\t\t\tinstance.post(\"/key=:key\", this.postWithKey.bind(this));\n\t\t\t\tinstance.post(\"/:id\", this.postWithId.bind(this));\n\n\t\t\t\tdone();\n\t\t\t},\n\t\t\t{ prefix: `/${basePath}` },\n\t\t);\n\t}\n\n\tasync get(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tQuerystring: Record<string, any>;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst query = request.query;\n\t\tconst limit = this._parseParam(query.limit);\n\t\tconst offset = this._parseParam(query.offset);\n\t\tconst params: QueryParams = {\n\t\t\texpand: this._parseParam(query.expand),\n\t\t\twhere: this._parseParam(query.where),\n\t\t\tlimit: limit !== undefined ? Number(limit) : undefined,\n\t\t\toffset: offset !== undefined ? Number(offset) : undefined,\n\t\t};\n\n\t\tfor (const key in query) {\n\t\t\tif (key.startsWith(\"var.\")) {\n\t\t\t\tconst items = this._parseParam(query[key]);\n\t\t\t\tif (items) {\n\t\t\t\t\tparams[key] = items.length === 1 ? items[0] : items;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst result = await this.repository.query(\n\t\t\tgetRepositoryContext(request),\n\t\t\tparams,\n\t\t);\n\t\treturn reply.status(200).send(result);\n\t}\n\n\tasync getWithId(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tQuerystring: Record<string, any>;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst params = request.params;\n\t\tconst result = await this._expandWithId(request, params.id);\n\t\tif (!result) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\t\tmessage: `The Resource with ID '${params.id}' was not found.`,\n\t\t\t\t},\n\t\t\t\t404,\n\t\t\t);\n\t\t}\n\t\treturn reply.status(200).send(result);\n\t}\n\n\tasync getWithKey(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tQuerystring: Record<string, any>;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst params = request.params;\n\t\tconst query = request.query;\n\t\tconst result = await this.repository.getByKey(\n\t\t\tgetRepositoryContext(request),\n\t\t\tparams.key,\n\t\t\t{\n\t\t\t\texpand: this._parseParam(query.expand),\n\t\t\t},\n\t\t);\n\t\tif (!result) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\t\tmessage: `The Resource with key '${params.key}' was not found.`,\n\t\t\t\t},\n\t\t\t\t404,\n\t\t\t);\n\t\t}\n\t\treturn reply.status(200).send(result);\n\t}\n\n\tasync deleteWithId(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tQuerystring: Record<string, any>;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst params = request.params;\n\t\tconst query = request.query;\n\t\tconst result = await this.repository.delete(\n\t\t\tgetRepositoryContext(request),\n\t\t\tparams.id,\n\t\t\t{\n\t\t\t\texpand: this._parseParam(query.expand),\n\t\t\t},\n\t\t);\n\t\tif (!result) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\t\tmessage: `The Resource with ID '${params.id}' was not found.`,\n\t\t\t\t},\n\t\t\t\t404,\n\t\t\t);\n\t\t}\n\t\treturn reply.status(200).send(result);\n\t}\n\n\tasync deleteWithKey(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tQuerystring: Record<string, any>;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst params = request.params;\n\t\tconst query = request.query;\n\t\tconst resource = await this.repository.getByKey(\n\t\t\tgetRepositoryContext(request),\n\t\t\tparams.key,\n\t\t);\n\t\tif (!resource) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\t\tmessage: `The Resource with key '${params.key}' was not found.`,\n\t\t\t\t},\n\t\t\t\t404,\n\t\t\t);\n\t\t}\n\n\t\tconst result = await this.repository.delete(\n\t\t\tgetRepositoryContext(request),\n\t\t\tresource.id,\n\t\t\t{\n\t\t\t\texpand: this._parseParam(query.expand),\n\t\t\t},\n\t\t);\n\t\tif (!result) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\t\tmessage: `The Resource with ID '${resource.id}' was not found.`,\n\t\t\t\t},\n\t\t\t\t404,\n\t\t\t);\n\t\t}\n\t\treturn reply.status(200).send(result);\n\t}\n\n\tasync post(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tQuerystring: Record<string, any>;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\t// Validate the draft against the schema when strict mode is enabled\n\t\tif (this.repository.strict && this.repository.draftSchema) {\n\t\t\tvalidateDraft(request.body, this.repository.draftSchema);\n\t\t}\n\n\t\tconst resource = await this.repository.create(\n\t\t\tgetRepositoryContext(request),\n\t\t\trequest.body,\n\t\t);\n\n\t\tconst query = request.query;\n\t\tconst expand = this._parseParam(query.expand);\n\n\t\t// Apply expand on the already-created resource and post-process it\n\t\t// instead of re-fetching from storage via _expandWithId.\n\t\tconst context = getRepositoryContext(request);\n\t\tconst expanded = await this.repository.expand(context, resource, expand);\n\t\tconst result = await this.repository.postProcessResource(\n\t\t\tcontext,\n\t\t\texpanded,\n\t\t\t{ expand },\n\t\t);\n\t\treturn reply.status(this.createStatusCode).send(result);\n\t}\n\n\tasync postWithId(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tQuerystring: Record<string, any>;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst params = request.params;\n\t\tconst updateRequest = validateData<Update>(\n\t\t\trequest.body,\n\t\t\tupdateRequestSchema,\n\t\t);\n\t\tconst resource = await this.repository.get(\n\t\t\tgetRepositoryContext(request),\n\t\t\tparams.id,\n\t\t);\n\t\tif (!resource) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\t\tmessage: `The Resource with ID '${params.id}' was not found.`,\n\t\t\t\t},\n\t\t\t\t404,\n\t\t\t);\n\t\t}\n\n\t\tconst updatedResource = await this.repository.processUpdateActions(\n\t\t\tgetRepositoryContext(request),\n\t\t\tresource,\n\t\t\tupdateRequest.version,\n\t\t\tupdateRequest.actions,\n\t\t);\n\n\t\tconst result = await this._expandWithId(request, updatedResource.id);\n\t\treturn reply.status(200).send(result);\n\t}\n\n\tasync postWithKey(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tQuerystring: Record<string, any>;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst params = request.params;\n\t\tconst updateRequest = validateData<Update>(\n\t\t\trequest.body,\n\t\t\tupdateRequestSchema,\n\t\t);\n\n\t\tconst resource = await this.repository.getByKey(\n\t\t\tgetRepositoryContext(request),\n\t\t\tparams.key,\n\t\t);\n\t\tif (!resource) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\t\tmessage: `The Resource with key '${params.key}' was not found.`,\n\t\t\t\t},\n\t\t\t\t404,\n\t\t\t);\n\t\t}\n\n\t\tconst updatedResource = await this.repository.processUpdateActions(\n\t\t\tgetRepositoryContext(request),\n\t\t\tresource,\n\t\t\tupdateRequest.version,\n\t\t\tupdateRequest.actions,\n\t\t);\n\n\t\tconst result = await this._expandWithId(request, updatedResource.id);\n\t\treturn reply.status(200).send(result);\n\t}\n\n\tprotected async _expandWithId(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tQuerystring: Record<string, any>;\n\t\t}>,\n\t\tresourceId: string,\n\t) {\n\t\tconst query = request.query;\n\t\tconst result = await this.repository.get(\n\t\t\tgetRepositoryContext(request),\n\t\t\tresourceId,\n\t\t\t{\n\t\t\t\texpand: this._parseParam(query.expand),\n\t\t\t},\n\t\t);\n\t\treturn result;\n\t}\n\n\t// No idea what i'm doing\n\tprotected _parseParam(\n\t\tvalue: string | ParsedQs | string[] | ParsedQs[] | undefined,\n\t): string[] | undefined {\n\t\treturn queryParamsArray(value);\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { ApprovalFlowRepository } from \"#src/repositories/approval-flow.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class ApprovalFlowService extends AbstractService {\n\tpublic repository: ApprovalFlowRepository;\n\n\tconstructor(parent: FastifyInstance, repository: ApprovalFlowRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"approval-flows\";\n\t}\n\n\tregisterRoutes(parent: FastifyInstance) {\n\t\tconst basePath = this.getBasePath();\n\t\tparent.register(\n\t\t\t(instance, opts, done) => {\n\t\t\t\tthis.extraRoutes(instance);\n\n\t\t\t\tinstance.get(\"/\", this.get.bind(this));\n\t\t\t\tinstance.get(\"/:id\", this.getWithId.bind(this));\n\n\t\t\t\tinstance.delete(\"/:id\", this.deleteWithId.bind(this));\n\n\t\t\t\tinstance.post(\"/\", this.post.bind(this));\n\t\t\t\tinstance.post(\"/:id\", this.postWithId.bind(this));\n\n\t\t\t\tdone();\n\t\t\t},\n\t\t\t{ prefix: `/${basePath}` },\n\t\t);\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { ApprovalRuleRepository } from \"#src/repositories/approval-rule.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class ApprovalRuleService extends AbstractService {\n\tpublic repository: ApprovalRuleRepository;\n\n\tconstructor(parent: FastifyInstance, repository: ApprovalRuleRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"approval-rules\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { AsAssociateApprovalFlowRepository } from \"#src/repositories/as-associate.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class AsAssociateApprovalFlowService extends AbstractService {\n\tpublic repository: AsAssociateApprovalFlowRepository;\n\n\tconstructor(\n\t\tparent: FastifyInstance,\n\t\trepository: AsAssociateApprovalFlowRepository,\n\t) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"approval-flows\";\n\t}\n\n\tregisterRoutes(parent: FastifyInstance) {\n\t\tconst basePath = this.getBasePath();\n\t\tparent.register(\n\t\t\t(instance, opts, done) => {\n\t\t\t\tthis.extraRoutes(instance);\n\n\t\t\t\tinstance.get(\"/\", this.get.bind(this));\n\t\t\t\tinstance.get(\"/:id\", this.getWithId.bind(this));\n\n\t\t\t\tinstance.post(\"/:id\", this.postWithId.bind(this));\n\n\t\t\t\tdone();\n\t\t\t},\n\t\t\t{ prefix: `/${basePath}` },\n\t\t);\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { AsAssociateApprovalRuleRepository } from \"#src/repositories/as-associate.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class AsAssociateApprovalRuleService extends AbstractService {\n\tpublic repository: AsAssociateApprovalRuleRepository;\n\n\tconstructor(\n\t\tparent: FastifyInstance,\n\t\trepository: AsAssociateApprovalRuleRepository,\n\t) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"approval-rules\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { AsAssociateBusinessUnitRepository } from \"#src/repositories/as-associate.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class AsAssociateBusinessUnitService extends AbstractService {\n\tpublic repository: AsAssociateBusinessUnitRepository;\n\n\tconstructor(\n\t\tparent: FastifyInstance,\n\t\trepository: AsAssociateBusinessUnitRepository,\n\t) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"business-units\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { CartRepository } from \"../repositories/cart/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class AsAssociateCartService extends AbstractService {\n\tpublic repository: CartRepository;\n\n\tconstructor(parent: FastifyInstance, repository: CartRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"carts\";\n\t}\n\n\tregisterRoutes(parent: FastifyInstance) {\n\t\tconst basePath = this.getBasePath();\n\t\tparent.register(\n\t\t\t(instance, opts, done) => {\n\t\t\t\tthis.extraRoutes(instance);\n\n\t\t\t\tinstance.get(\"/\", this.get.bind(this));\n\t\t\t\tinstance.get(\"/:id\", this.getWithId.bind(this));\n\n\t\t\t\tinstance.delete(\"/:id\", this.deleteWithId.bind(this));\n\n\t\t\t\tinstance.post(\"/\", this.post.bind(this));\n\t\t\t\tinstance.post(\"/:id\", this.postWithId.bind(this));\n\n\t\t\t\tdone();\n\t\t\t},\n\t\t\t{ prefix: `/${basePath}` },\n\t\t);\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { MyOrderRepository } from \"../repositories/my-order.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class AsAssociateOrderService extends AbstractService {\n\tpublic repository: MyOrderRepository;\n\n\tconstructor(parent: FastifyInstance, repository: MyOrderRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"orders\";\n\t}\n\n\tregisterRoutes(parent: FastifyInstance) {\n\t\tconst basePath = this.getBasePath();\n\t\tparent.register(\n\t\t\t(instance, opts, done) => {\n\t\t\t\tthis.extraRoutes(instance);\n\n\t\t\t\tinstance.get(\"/\", this.get.bind(this));\n\t\t\t\tinstance.get(\"/:id\", this.getWithId.bind(this));\n\n\t\t\t\tinstance.delete(\"/:id\", this.deleteWithId.bind(this));\n\n\t\t\t\tinstance.post(\"/\", this.post.bind(this));\n\t\t\t\tinstance.post(\"/:id\", this.postWithId.bind(this));\n\n\t\t\t\tdone();\n\t\t\t},\n\t\t\t{ prefix: `/${basePath}` },\n\t\t);\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { AsAssociateQuoteRepository } from \"#src/repositories/as-associate.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class AsAssociateQuoteService extends AbstractService {\n\tpublic repository: AsAssociateQuoteRepository;\n\n\tconstructor(parent: FastifyInstance, repository: AsAssociateQuoteRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"quotes\";\n\t}\n\n\tregisterRoutes(parent: FastifyInstance) {\n\t\tconst basePath = this.getBasePath();\n\t\tparent.register(\n\t\t\t(instance, opts, done) => {\n\t\t\t\tthis.extraRoutes(instance);\n\n\t\t\t\tinstance.get(\"/\", this.get.bind(this));\n\t\t\t\tinstance.get(\"/key=:key\", this.getWithKey.bind(this));\n\t\t\t\tinstance.get(\"/:id\", this.getWithId.bind(this));\n\n\t\t\t\t// An associate reads and updates quotes; quotes are created by the\n\t\t\t\t// seller, so the associate scope has no create or delete route\n\t\t\t\tinstance.post(\"/key=:key\", this.postWithKey.bind(this));\n\t\t\t\tinstance.post(\"/:id\", this.postWithId.bind(this));\n\n\t\t\t\tdone();\n\t\t\t},\n\t\t\t{ prefix: `/${basePath}` },\n\t\t);\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { MyQuoteRequestRepository } from \"#src/repositories/my-quote-request.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class AsAssociateQuoteRequestService extends AbstractService {\n\tpublic repository: MyQuoteRequestRepository;\n\n\tconstructor(parent: FastifyInstance, repository: MyQuoteRequestRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"quote-requests\";\n\t}\n\n\tregisterRoutes(parent: FastifyInstance) {\n\t\tconst basePath = this.getBasePath();\n\t\tparent.register(\n\t\t\t(instance, opts, done) => {\n\t\t\t\tthis.extraRoutes(instance);\n\n\t\t\t\tinstance.get(\"/\", this.get.bind(this));\n\t\t\t\tinstance.get(\"/:id\", this.getWithId.bind(this));\n\n\t\t\t\tinstance.delete(\"/:id\", this.deleteWithId.bind(this));\n\n\t\t\t\tinstance.post(\"/\", this.post.bind(this));\n\t\t\t\tinstance.post(\"/:id\", this.postWithId.bind(this));\n\n\t\t\t\tdone();\n\t\t\t},\n\t\t\t{ prefix: `/${basePath}` },\n\t\t);\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { ShoppingListRepository } from \"#src/repositories/shopping-list/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class AsAssociateShoppingListService extends AbstractService {\n\tpublic repository: ShoppingListRepository;\n\n\tconstructor(parent: FastifyInstance, repository: ShoppingListRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"shopping-lists\";\n\t}\n\n\tregisterRoutes(parent: FastifyInstance) {\n\t\tconst basePath = this.getBasePath();\n\t\tparent.register(\n\t\t\t(instance, opts, done) => {\n\t\t\t\tthis.extraRoutes(instance);\n\n\t\t\t\tinstance.get(\"/\", this.get.bind(this));\n\t\t\t\tinstance.get(\"/:id\", this.getWithId.bind(this));\n\n\t\t\t\tinstance.delete(\"/:id\", this.deleteWithId.bind(this));\n\n\t\t\t\tinstance.post(\"/\", this.post.bind(this));\n\t\t\t\tinstance.post(\"/:id\", this.postWithId.bind(this));\n\n\t\t\t\tdone();\n\t\t\t},\n\t\t\t{ prefix: `/${basePath}` },\n\t\t);\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type {\n\tAsAssociateApprovalFlowRepository,\n\tAsAssociateApprovalRuleRepository,\n\tAsAssociateBusinessUnitRepository,\n\tAsAssociateCartRepository,\n\tAsAssociateOrderRepository,\n\tAsAssociateQuoteRepository,\n\tAsAssociateQuoteRequestRepository,\n\tAsAssociateShoppingListRepository,\n} from \"#src/repositories/as-associate.ts\";\nimport { AsAssociateApprovalFlowService } from \"./as-associate-approval-flow.ts\";\nimport { AsAssociateApprovalRuleService } from \"./as-associate-approval-rule.ts\";\nimport { AsAssociateBusinessUnitService } from \"./as-associate-business-unit.ts\";\nimport { AsAssociateCartService } from \"./as-associate-cart.ts\";\nimport { AsAssociateOrderService } from \"./as-associate-order.ts\";\nimport { AsAssociateQuoteService } from \"./as-associate-quote.ts\";\nimport { AsAssociateQuoteRequestService } from \"./as-associate-quote-request.ts\";\nimport { AsAssociateShoppingListService } from \"./as-associate-shopping-list.ts\";\n\ntype Repositories = {\n\t\"approval-flow\": AsAssociateApprovalFlowRepository;\n\t\"approval-rule\": AsAssociateApprovalRuleRepository;\n\t\"business-unit\": AsAssociateBusinessUnitRepository;\n\tcart: AsAssociateCartRepository;\n\torder: AsAssociateOrderRepository;\n\tquote: AsAssociateQuoteRepository;\n\t\"quote-request\": AsAssociateQuoteRequestRepository;\n\t\"shopping-list\": AsAssociateShoppingListRepository;\n};\n\nexport class AsAssociateService {\n\tsubServices!: {\n\t\t\"approval-flow\": AsAssociateApprovalFlowService;\n\t\t\"approval-rule\": AsAssociateApprovalRuleService;\n\t\t\"business-unit\": AsAssociateBusinessUnitService;\n\t\tcart: AsAssociateCartService;\n\t\torder: AsAssociateOrderService;\n\t\tquote: AsAssociateQuoteService;\n\t\t\"quote-request\": AsAssociateQuoteRequestService;\n\t\t\"shopping-list\": AsAssociateShoppingListService;\n\t};\n\n\tconstructor(parent: FastifyInstance, repositories: Repositories) {\n\t\tparent.register(\n\t\t\t(instance, opts, done) => {\n\t\t\t\tconst businessUnitService = new AsAssociateBusinessUnitService(\n\t\t\t\t\tinstance,\n\t\t\t\t\trepositories[\"business-unit\"],\n\t\t\t\t);\n\n\t\t\t\tinstance.register(\n\t\t\t\t\t(scoped, _opts, scopedDone) => {\n\t\t\t\t\t\tconst order = new AsAssociateOrderService(\n\t\t\t\t\t\t\tscoped,\n\t\t\t\t\t\t\trepositories.order,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst cart = new AsAssociateCartService(scoped, repositories.cart);\n\t\t\t\t\t\tconst quote = new AsAssociateQuoteService(\n\t\t\t\t\t\t\tscoped,\n\t\t\t\t\t\t\trepositories.quote,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst quoteRequest = new AsAssociateQuoteRequestService(\n\t\t\t\t\t\t\tscoped,\n\t\t\t\t\t\t\trepositories[\"quote-request\"],\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst shoppingList = new AsAssociateShoppingListService(\n\t\t\t\t\t\t\tscoped,\n\t\t\t\t\t\t\trepositories[\"shopping-list\"],\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst approvalFlow = new AsAssociateApprovalFlowService(\n\t\t\t\t\t\t\tscoped,\n\t\t\t\t\t\t\trepositories[\"approval-flow\"],\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst approvalRule = new AsAssociateApprovalRuleService(\n\t\t\t\t\t\t\tscoped,\n\t\t\t\t\t\t\trepositories[\"approval-rule\"],\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tthis.subServices = {\n\t\t\t\t\t\t\t\"approval-flow\": approvalFlow,\n\t\t\t\t\t\t\t\"approval-rule\": approvalRule,\n\t\t\t\t\t\t\t\"business-unit\": businessUnitService,\n\t\t\t\t\t\t\torder,\n\t\t\t\t\t\t\tcart,\n\t\t\t\t\t\t\tquote,\n\t\t\t\t\t\t\t\"quote-request\": quoteRequest,\n\t\t\t\t\t\t\t\"shopping-list\": shoppingList,\n\t\t\t\t\t\t};\n\t\t\t\t\t\tscopedDone();\n\t\t\t\t\t},\n\t\t\t\t\t{ prefix: \"/in-business-unit/key=:businessUnitKey\" },\n\t\t\t\t);\n\n\t\t\t\tdone();\n\t\t\t},\n\t\t\t{\n\t\t\t\tprefix: \"/as-associate/:associateId\",\n\t\t\t},\n\t\t);\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { AssociateRoleRepository } from \"../repositories/associate-role.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class AssociateRoleServices extends AbstractService {\n\tpublic repository: AssociateRoleRepository;\n\n\tconstructor(parent: FastifyInstance, repository: AssociateRoleRepository) {\n\t\tsuper(parent);\n\n\t\tthis.repository = repository;\n\t}\n\n\tprotected getBasePath(): string {\n\t\treturn \"associate-roles\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { AttributeGroupRepository } from \"../repositories/attribute-group.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class AttributeGroupService extends AbstractService {\n\tpublic repository: AttributeGroupRepository;\n\n\tconstructor(parent: FastifyInstance, repository: AttributeGroupRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"attribute-groups\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { BusinessUnitRepository } from \"../repositories/business-unit.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class BusinessUnitServices extends AbstractService {\n\tpublic repository: BusinessUnitRepository;\n\n\tconstructor(parent: FastifyInstance, repository: BusinessUnitRepository) {\n\t\tsuper(parent);\n\n\t\tthis.repository = repository;\n\t}\n\n\tprotected getBasePath(): string {\n\t\treturn \"business-units\";\n\t}\n}\n","import type {\n\tCart,\n\tCartDraft,\n\tInvalidInputError,\n\tOrder,\n\tReplicaCartDraft,\n} from \"@commercetools/platform-sdk\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport type { CartRepository } from \"../repositories/cart/index.ts\";\nimport { getRepositoryContext } from \"../repositories/helpers.ts\";\nimport type { OrderRepository } from \"../repositories/order/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class CartService extends AbstractService {\n\tpublic repository: CartRepository;\n\n\tpublic orderRepository: OrderRepository;\n\n\tconstructor(\n\t\tparent: FastifyInstance,\n\t\tcartRepository: CartRepository,\n\t\torderRepository: OrderRepository,\n\t) {\n\t\tsuper(parent);\n\t\tthis.repository = cartRepository;\n\t\tthis.orderRepository = orderRepository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"carts\";\n\t}\n\n\textraRoutes(parent: FastifyInstance) {\n\t\tparent.post(\"/replicate\", this.replicate.bind(this));\n\t}\n\n\tasync replicate(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tBody: ReplicaCartDraft;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst context = getRepositoryContext(request);\n\t\tconst body = request.body;\n\n\t\tconst cartOrOrder: Cart | Order | null =\n\t\t\tbody.reference.typeId === \"order\"\n\t\t\t\t? await this.orderRepository.get(context, body.reference.id)\n\t\t\t\t: await this.repository.get(context, body.reference.id);\n\n\t\tif (!cartOrOrder) {\n\t\t\tthrow new CommercetoolsError<InvalidInputError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidInput\",\n\t\t\t\t\tmessage: `The referenced ${body.reference.typeId} with ID '${body.reference.id}' was not found.`,\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\tconst cartDraft: CartDraft = {\n\t\t\t...cartOrOrder,\n\t\t\tcurrency: cartOrOrder.totalPrice.currencyCode,\n\t\t\tdiscountCodes: [],\n\t\t\tshipping: [], // TODO: cartOrOrder.shipping,\n\t\t\tlineItems: cartOrOrder.lineItems.map((lineItem) => ({\n\t\t\t\t...lineItem,\n\t\t\t\tvariantId: lineItem.variant.id,\n\t\t\t\tsku: lineItem.variant.sku,\n\t\t\t})),\n\t\t};\n\n\t\tconst newCart = await this.repository.create(context, cartDraft);\n\n\t\treturn reply.status(200).send(newCart);\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { CartDiscountRepository } from \"../repositories/cart-discount/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class CartDiscountService extends AbstractService {\n\tpublic repository: CartDiscountRepository;\n\n\tconstructor(parent: FastifyInstance, repository: CartDiscountRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"cart-discounts\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { CategoryRepository } from \"../repositories/category/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class CategoryServices extends AbstractService {\n\tpublic repository: CategoryRepository;\n\n\tconstructor(parent: FastifyInstance, repository: CategoryRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"categories\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { ChannelRepository } from \"../repositories/channel.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class ChannelService extends AbstractService {\n\tpublic repository: ChannelRepository;\n\n\tconstructor(parent: FastifyInstance, repository: ChannelRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"channels\";\n\t}\n}\n","import type {\n\tCustomObjectDraft,\n\tResourceNotFoundError,\n} from \"@commercetools/platform-sdk\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport type { CustomObjectRepository } from \"../repositories/custom-object.ts\";\nimport { getRepositoryContext } from \"../repositories/helpers.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class CustomObjectService extends AbstractService {\n\tpublic repository: CustomObjectRepository;\n\n\tconstructor(parent: FastifyInstance, repository: CustomObjectRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"custom-objects\";\n\t}\n\n\tregisterRoutes(parent: FastifyInstance) {\n\t\tconst basePath = this.getBasePath();\n\t\tparent.register(\n\t\t\t(instance, opts, done) => {\n\t\t\t\t// Custom object specific routes\n\t\t\t\tinstance.get(\n\t\t\t\t\t\"/:container/:key\",\n\t\t\t\t\tthis.getWithContainerAndKey.bind(this),\n\t\t\t\t);\n\t\t\t\tinstance.post(\n\t\t\t\t\t\"/:container/:key\",\n\t\t\t\t\tthis.createWithContainerAndKey.bind(this),\n\t\t\t\t);\n\t\t\t\tinstance.delete(\n\t\t\t\t\t\"/:container/:key\",\n\t\t\t\t\tthis.deleteWithContainerAndKey.bind(this),\n\t\t\t\t);\n\n\t\t\t\t// Standard routes, but use /:container instead of /:id for GET\n\t\t\t\t// to avoid duplicate parametric route conflict in Fastify.\n\t\t\t\t// In Express, /:container was registered first and shadowed /:id.\n\t\t\t\tinstance.get(\"/\", this.get.bind(this));\n\t\t\t\tinstance.get(\"/key=:key\", this.getWithKey.bind(this));\n\t\t\t\tinstance.get(\"/:container\", this.getWithContainer.bind(this));\n\n\t\t\t\tinstance.delete(\"/key=:key\", this.deleteWithKey.bind(this));\n\t\t\t\tinstance.delete(\"/:id\", this.deleteWithId.bind(this));\n\n\t\t\t\tinstance.post(\"/\", this.post.bind(this));\n\t\t\t\tinstance.post(\"/key=:key\", this.postWithKey.bind(this));\n\t\t\t\tinstance.post(\"/:id\", this.postWithId.bind(this));\n\n\t\t\t\tdone();\n\t\t\t},\n\t\t\t{ prefix: `/${basePath}` },\n\t\t);\n\t}\n\n\tasync getWithContainer(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tQuerystring: Record<string, any>;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst params = request.params;\n\t\tconst query = request.query;\n\t\tconst limit = this._parseParam(query.limit);\n\t\tconst offset = this._parseParam(query.offset);\n\n\t\tconst result = await this.repository.queryWithContainer(\n\t\t\tgetRepositoryContext(request),\n\t\t\tparams.container,\n\t\t\t{\n\t\t\t\texpand: this._parseParam(query.expand),\n\t\t\t\twhere: this._parseParam(query.where),\n\t\t\t\tlimit: limit !== undefined ? Number(limit) : undefined,\n\t\t\t\toffset: offset !== undefined ? Number(offset) : undefined,\n\t\t\t},\n\t\t);\n\n\t\treturn reply.status(200).send(result);\n\t}\n\n\tasync getWithContainerAndKey(\n\t\trequest: FastifyRequest<{ Params: Record<string, string> }>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst params = request.params;\n\t\tconst result = await this.repository.getWithContainerAndKey(\n\t\t\tgetRepositoryContext(request),\n\t\t\tparams.container,\n\t\t\tparams.key,\n\t\t);\n\n\t\tif (!result) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\t\tmessage: `The CustomObject with container '${params.container}' and key '${params.key}' was not found.`,\n\t\t\t\t},\n\t\t\t\t404,\n\t\t\t);\n\t\t}\n\t\treturn reply.status(200).send(result);\n\t}\n\n\tasync createWithContainerAndKey(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tBody: CustomObjectDraft;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst params = request.params;\n\t\tconst draft: CustomObjectDraft = {\n\t\t\t...request.body,\n\t\t\tkey: params.key,\n\t\t\tcontainer: params.container,\n\t\t};\n\n\t\tconst result = await this.repository.create(\n\t\t\tgetRepositoryContext(request),\n\t\t\tdraft,\n\t\t);\n\t\treturn reply.status(200).send(result);\n\t}\n\n\tasync deleteWithContainerAndKey(\n\t\trequest: FastifyRequest<{ Params: Record<string, string> }>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst params = request.params;\n\t\tconst current = await this.repository.getWithContainerAndKey(\n\t\t\tgetRepositoryContext(request),\n\t\t\tparams.container,\n\t\t\tparams.key,\n\t\t);\n\n\t\tif (!current) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\t\tmessage: `The CustomObject with container '${params.container}' and key '${params.key}' was not found.`,\n\t\t\t\t},\n\t\t\t\t404,\n\t\t\t);\n\t\t}\n\n\t\tconst result = await this.repository.delete(\n\t\t\tgetRepositoryContext(request),\n\t\t\tcurrent.id,\n\t\t);\n\n\t\treturn reply.status(200).send(result);\n\t}\n}\n","import type {\n\tCustomerCreateEmailToken,\n\tCustomerCreatePasswordResetToken,\n\tCustomerDraft,\n\tCustomerEmailVerify,\n\tCustomerResetPassword,\n\tCustomerSignInResult,\n} from \"@commercetools/platform-sdk\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { validateDraft } from \"#src/validate.ts\";\nimport type { CustomerRepository } from \"../repositories/customer/index.ts\";\nimport { getRepositoryContext } from \"../repositories/helpers.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class CustomerService extends AbstractService {\n\tpublic repository: CustomerRepository;\n\n\tconstructor(parent: FastifyInstance, repository: CustomerRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"customers\";\n\t}\n\n\textraRoutes(parent: FastifyInstance) {\n\t\tparent.post(\"/password-token\", this.passwordResetToken.bind(this));\n\t\tparent.post(\"/password/reset\", this.passwordReset.bind(this));\n\t\tparent.post(\"/email-token\", this.emailToken.bind(this));\n\t\tparent.post(\"/email/confirm\", this.emailTokenConfirm.bind(this));\n\t}\n\n\tasync post(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tQuerystring: Record<string, any>;\n\t\t\tBody: CustomerDraft;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\t// Validate the draft against the schema when strict mode is enabled\n\t\tif (this.repository.strict && this.repository.draftSchema) {\n\t\t\tvalidateDraft(request.body, this.repository.draftSchema);\n\t\t}\n\n\t\tconst resource = await this.repository.create(\n\t\t\tgetRepositoryContext(request),\n\t\t\trequest.body,\n\t\t);\n\t\tconst expanded = await this._expandWithId(request, resource.id);\n\n\t\tconst result: CustomerSignInResult = {\n\t\t\tcustomer: expanded,\n\t\t};\n\t\treturn reply.status(this.createStatusCode).send(result);\n\t}\n\n\tasync passwordResetToken(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tBody: CustomerCreatePasswordResetToken;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst customer = await this.repository.passwordResetToken(\n\t\t\tgetRepositoryContext(request),\n\t\t\trequest.body,\n\t\t);\n\n\t\treturn reply.status(200).send(customer);\n\t}\n\n\tasync passwordReset(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tBody: CustomerResetPassword;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst customer = await this.repository.passwordReset(\n\t\t\tgetRepositoryContext(request),\n\t\t\trequest.body,\n\t\t);\n\n\t\treturn reply.status(200).send(customer);\n\t}\n\n\tasync emailToken(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tBody: CustomerCreateEmailToken;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst body = request.body;\n\t\tconst id = body.id;\n\t\tconst token = await this.repository.emailToken(\n\t\t\tgetRepositoryContext(request),\n\t\t\tid,\n\t\t);\n\t\treturn reply.status(200).send(token);\n\t}\n\n\tasync emailTokenConfirm(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tBody: CustomerEmailVerify;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst customer = await this.repository.emailTokenConfirm(\n\t\t\tgetRepositoryContext(request),\n\t\t\trequest.body,\n\t\t);\n\n\t\treturn reply.status(200).send(customer);\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { CustomerGroupRepository } from \"../repositories/customer-group.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class CustomerGroupService extends AbstractService {\n\tpublic repository: CustomerGroupRepository;\n\n\tconstructor(parent: FastifyInstance, repository: CustomerGroupRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"customer-groups\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { DiscountCodeRepository } from \"../repositories/discount-code/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class DiscountCodeService extends AbstractService {\n\tpublic repository: DiscountCodeRepository;\n\n\tconstructor(parent: FastifyInstance, repository: DiscountCodeRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"discount-codes\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { DiscountGroupRepository } from \"../repositories/discount-group/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class DiscountGroupService extends AbstractService {\n\tpublic repository: DiscountGroupRepository;\n\n\tconstructor(parent: FastifyInstance, repository: DiscountGroupRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"discount-groups\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { ExtensionRepository } from \"../repositories/extension.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class ExtensionServices extends AbstractService {\n\tpublic repository: ExtensionRepository;\n\n\tconstructor(parent: FastifyInstance, repository: ExtensionRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"extensions\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { InventoryEntryRepository } from \"../repositories/inventory-entry/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class InventoryEntryService extends AbstractService {\n\tpublic repository: InventoryEntryRepository;\n\n\tconstructor(parent: FastifyInstance, repository: InventoryEntryRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"inventory\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { BusinessUnitRepository } from \"#src/repositories/business-unit.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class MyBusinessUnitService extends AbstractService {\n\tpublic repository: BusinessUnitRepository;\n\n\tconstructor(parent: FastifyInstance, repository: BusinessUnitRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"me\";\n\t}\n\n\tregisterRoutes(parent: FastifyInstance) {\n\t\t// Overwrite this function to be able to handle /me/business-units path.\n\t\tconst basePath = this.getBasePath();\n\t\tparent.register(\n\t\t\t(instance, opts, done) => {\n\t\t\t\tthis.extraRoutes(instance);\n\n\t\t\t\tinstance.get(\"/business-units\", this.get.bind(this));\n\t\t\t\tinstance.get(\"/business-units/key=:key\", this.getWithKey.bind(this));\n\t\t\t\tinstance.get(\"/business-units/:id\", this.getWithId.bind(this));\n\n\t\t\t\tinstance.delete(\n\t\t\t\t\t\"/business-units/key=:key\",\n\t\t\t\t\tthis.deleteWithKey.bind(this),\n\t\t\t\t);\n\t\t\t\tinstance.delete(\"/business-units/:id\", this.deleteWithId.bind(this));\n\n\t\t\t\tinstance.post(\"/business-units\", this.post.bind(this));\n\t\t\t\tinstance.post(\"/business-units/key=:key\", this.postWithKey.bind(this));\n\t\t\t\tinstance.post(\"/business-units/:id\", this.postWithId.bind(this));\n\n\t\t\t\tdone();\n\t\t\t},\n\t\t\t{ prefix: `/${basePath}` },\n\t\t);\n\t}\n}\n","import type { ResourceNotFoundError } from \"@commercetools/platform-sdk\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport type { CartRepository } from \"../repositories/cart/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class MyCartService extends AbstractService {\n\tpublic repository: CartRepository;\n\n\tconstructor(parent: FastifyInstance, repository: CartRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"me\";\n\t}\n\n\tregisterRoutes(parent: FastifyInstance) {\n\t\t// Overwrite this function to be able to handle /me/active-cart path.\n\t\tconst basePath = this.getBasePath();\n\t\tparent.register(\n\t\t\t(instance, opts, done) => {\n\t\t\t\tthis.extraRoutes(instance);\n\n\t\t\t\tinstance.get(\"/active-cart\", this.activeCart.bind(this));\n\t\t\t\tinstance.get(\"/carts\", this.get.bind(this));\n\t\t\t\tinstance.get(\"/carts/:id\", this.getWithId.bind(this));\n\n\t\t\t\tinstance.delete(\"/carts/:id\", this.deleteWithId.bind(this));\n\n\t\t\t\tinstance.post(\"/carts\", this.post.bind(this));\n\t\t\t\tinstance.post(\"/carts/:id\", this.postWithId.bind(this));\n\n\t\t\t\tdone();\n\t\t\t},\n\t\t\t{ prefix: `/${basePath}` },\n\t\t);\n\t}\n\n\tasync activeCart(\n\t\trequest: FastifyRequest<{ Params: Record<string, string> }>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst params = request.params;\n\t\tconst resource = await this.repository.getActiveCart(params.projectKey);\n\t\tif (!resource) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\t\tmessage: \"No active cart exists.\",\n\t\t\t\t},\n\t\t\t\t404,\n\t\t\t);\n\t\t}\n\t\treturn reply.status(200).send(resource);\n\t}\n}\n","import type {\n\tMyCustomerChangePassword,\n\tMyCustomerDraft,\n\tMyCustomerEmailVerify,\n\tMyCustomerResetPassword,\n\tMyCustomerSignin,\n\tResourceNotFoundError,\n\tUpdate,\n} from \"@commercetools/platform-sdk\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { updateRequestSchema } from \"#src/schemas/update-request.ts\";\nimport { validateData } from \"#src/validate.ts\";\nimport { hashPassword } from \"../lib/password.ts\";\nimport { getRepositoryContext } from \"../repositories/helpers.ts\";\nimport type { MyCustomerRepository } from \"../repositories/my-customer.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class MyCustomerService extends AbstractService {\n\tpublic repository: MyCustomerRepository;\n\n\tconstructor(parent: FastifyInstance, repository: MyCustomerRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"me\";\n\t}\n\n\tregisterRoutes(parent: FastifyInstance) {\n\t\t// Overwrite this function to be able to handle /me path.\n\t\tconst basePath = this.getBasePath();\n\t\tparent.register(\n\t\t\t(instance, opts, done) => {\n\t\t\t\tthis.extraRoutes(instance);\n\n\t\t\t\tinstance.get(\"\", this.getMe.bind(this));\n\t\t\t\tinstance.post(\"\", this.updateMe.bind(this));\n\t\t\t\tinstance.delete(\"\", this.deleteMe.bind(this));\n\n\t\t\t\tinstance.post(\"/signup\", this.signUp.bind(this));\n\n\t\t\t\tinstance.post(\"/login\", this.signIn.bind(this));\n\t\t\t\tinstance.post(\"/password\", this.changePassword.bind(this));\n\t\t\t\tinstance.post(\"/password/reset\", this.resetPassword.bind(this));\n\t\t\t\tinstance.post(\"/email/confirm\", this.emailConfirm.bind(this));\n\n\t\t\t\tdone();\n\t\t\t},\n\t\t\t{ prefix: `/${basePath}` },\n\t\t);\n\t}\n\n\tasync getMe(\n\t\trequest: FastifyRequest<{ Params: Record<string, string> }>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst resource = await this.repository.getMe(getRepositoryContext(request));\n\t\tif (!resource) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\t\tmessage: \"The Resource was not found.\",\n\t\t\t\t},\n\t\t\t\t404,\n\t\t\t);\n\t\t}\n\t\treturn reply.status(200).send(resource);\n\t}\n\n\tasync updateMe(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tQuerystring: Record<string, any>;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst resource = await this.repository.getMe(getRepositoryContext(request));\n\n\t\tif (!resource) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\t\tmessage: \"The Resource was not found.\",\n\t\t\t\t},\n\t\t\t\t404,\n\t\t\t);\n\t\t}\n\t\tconst updateRequest = validateData<Update>(\n\t\t\trequest.body,\n\t\t\tupdateRequestSchema,\n\t\t);\n\t\tconst updatedResource = await this.repository.processUpdateActions(\n\t\t\tgetRepositoryContext(request),\n\t\t\tresource,\n\t\t\tupdateRequest.version,\n\t\t\tupdateRequest.actions,\n\t\t);\n\n\t\tconst result = await this._expandWithId(request, updatedResource.id);\n\t\treturn reply.status(200).send(result);\n\t}\n\n\tasync deleteMe(\n\t\trequest: FastifyRequest<{ Params: Record<string, string> }>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst resource = await this.repository.deleteMe(\n\t\t\tgetRepositoryContext(request),\n\t\t);\n\t\tif (!resource) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\t\tmessage: \"The Resource was not found.\",\n\t\t\t\t},\n\t\t\t\t404,\n\t\t\t);\n\t\t}\n\n\t\treturn reply.status(200).send(resource);\n\t}\n\n\tasync signUp(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tQuerystring: Record<string, any>;\n\t\t\tBody: MyCustomerDraft;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst draft = request.body;\n\t\tconst resource = await this.repository.create(\n\t\t\tgetRepositoryContext(request),\n\t\t\tdraft,\n\t\t);\n\t\tconst result = await this._expandWithId(request, resource.id);\n\t\treturn reply.status(this.createStatusCode).send({ customer: result });\n\t}\n\n\tasync changePassword(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tBody: MyCustomerChangePassword;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst customer = await this.repository.changePassword(\n\t\t\tgetRepositoryContext(request),\n\t\t\trequest.body,\n\t\t);\n\n\t\treturn reply.status(200).send(customer);\n\t}\n\n\tasync resetPassword(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tBody: MyCustomerResetPassword;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst customer = await this.repository.passwordReset(\n\t\t\tgetRepositoryContext(request),\n\t\t\trequest.body,\n\t\t);\n\n\t\treturn reply.status(200).send(customer);\n\t}\n\n\tasync emailConfirm(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tBody: MyCustomerEmailVerify;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst customer = await this.repository.confirmEmail(\n\t\t\tgetRepositoryContext(request),\n\t\t\trequest.body,\n\t\t);\n\n\t\treturn reply.status(200).send(customer);\n\t}\n\n\tasync signIn(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tBody: MyCustomerSignin;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst body = request.body;\n\t\tconst { email, password } = body;\n\t\tconst encodedPassword = hashPassword(password);\n\n\t\tconst result = await this.repository.query(getRepositoryContext(request), {\n\t\t\twhere: [`email = \"${email}\"`, `password = \"${encodedPassword}\"`],\n\t\t});\n\n\t\tif (result.count === 0) {\n\t\t\tthrow new CommercetoolsError<any>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidCredentials\",\n\t\t\t\t\tmessage: \"Account with the given credentials not found.\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\treturn reply.status(200).send({ customer: result.results[0] });\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\n\nexport const MyOrderFromQuoteDraftSchema = z.object({\n\tid: z.string(),\n\tversion: z.number().int(),\n\tquoteStateToAccepted: z.boolean().nullish(),\n});\n","import type { MyOrderFromQuoteDraft } from \"@commercetools/platform-sdk\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { MyOrderFromQuoteDraftSchema } from \"#src/schemas/generated/my-order-from-quote.ts\";\nimport { validateDraft } from \"#src/validate.ts\";\nimport { getRepositoryContext } from \"../repositories/helpers.ts\";\nimport type { MyOrderRepository } from \"../repositories/my-order.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class MyOrderService extends AbstractService {\n\tpublic repository: MyOrderRepository;\n\n\tconstructor(parent: FastifyInstance, repository: MyOrderRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"me\";\n\t}\n\n\tregisterRoutes(parent: FastifyInstance) {\n\t\t// Overwrite this function to be able to handle /me/active-cart path.\n\t\tconst basePath = this.getBasePath();\n\t\tparent.register(\n\t\t\t(instance, opts, done) => {\n\t\t\t\tthis.extraRoutes(instance);\n\n\t\t\t\tinstance.get(\"/orders\", this.get.bind(this));\n\t\t\t\tinstance.get(\"/orders/:id\", this.getWithId.bind(this));\n\n\t\t\t\tinstance.delete(\"/orders/:id\", this.deleteWithId.bind(this));\n\n\t\t\t\tinstance.post(\"/orders/quotes\", this.createFromQuote.bind(this));\n\t\t\t\tinstance.post(\"/orders\", this.post.bind(this));\n\t\t\t\tinstance.post(\"/orders/:id\", this.postWithId.bind(this));\n\n\t\t\t\tdone();\n\t\t\t},\n\t\t\t{ prefix: `/${basePath}` },\n\t\t);\n\t}\n\n\tasync createFromQuote(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tBody: MyOrderFromQuoteDraft;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tif (this.repository.strict) {\n\t\t\tvalidateDraft(request.body, MyOrderFromQuoteDraftSchema);\n\t\t}\n\n\t\tconst { id, version, quoteStateToAccepted } = request.body;\n\t\tconst resource = await this.repository.createFromQuote(\n\t\t\tgetRepositoryContext(request),\n\t\t\t{\n\t\t\t\tquote: { typeId: \"quote\", id },\n\t\t\t\tversion,\n\t\t\t\tquoteStateToAccepted,\n\t\t\t},\n\t\t);\n\t\treturn reply.status(this.createStatusCode).send(resource);\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { PaymentRepository } from \"../repositories/payment/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class MyPaymentService extends AbstractService {\n\tpublic repository: PaymentRepository;\n\n\tconstructor(parent: FastifyInstance, repository: PaymentRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"me/payments\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { ShoppingListRepository } from \"../repositories/shopping-list/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class MyShoppingListService extends AbstractService {\n\tpublic repository: ShoppingListRepository;\n\n\tconstructor(parent: FastifyInstance, repository: ShoppingListRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"me/shopping-lists\";\n\t}\n}\n","// This file is auto-generated by scripts/generate-schemas.ts\n// Do not edit manually.\n\nimport { z } from \"zod\";\nimport {\n\tOrderStateSchema,\n\tPaymentStateSchema,\n\tQuoteResourceIdentifierSchema,\n\tShipmentStateSchema,\n\tStateResourceIdentifierSchema,\n} from \"./common.ts\";\n\nexport const OrderFromQuoteDraftSchema = z.object({\n\tquote: QuoteResourceIdentifierSchema,\n\tversion: z.number().int(),\n\tquoteStateToAccepted: z.boolean().nullish(),\n\torderNumber: z.string().nullish(),\n\tpaymentState: PaymentStateSchema.nullish(),\n\tshipmentState: ShipmentStateSchema.nullish(),\n\torderState: OrderStateSchema.nullish(),\n\tstate: StateResourceIdentifierSchema.nullish(),\n});\n","import type {\n\tOrderFromQuoteDraft,\n\tOrderImportDraft,\n\tOrderSearchRequest,\n\tResourceNotFoundError,\n} from \"@commercetools/platform-sdk\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { OrderFromQuoteDraftSchema } from \"#src/schemas/generated/order-from-quote.ts\";\nimport { validateDraft } from \"#src/validate.ts\";\nimport { getRepositoryContext } from \"../repositories/helpers.ts\";\nimport type { OrderRepository } from \"../repositories/order/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class OrderService extends AbstractService {\n\tpublic repository: OrderRepository;\n\n\tconstructor(parent: FastifyInstance, repository: OrderRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"orders\";\n\t}\n\n\textraRoutes(instance: FastifyInstance) {\n\t\tinstance.post(\"/quotes\", this.createFromQuote.bind(this));\n\t\tinstance.post(\"/import\", this.import.bind(this));\n\t\tinstance.post(\"/search\", this.search.bind(this));\n\t\tinstance.get(\n\t\t\t\"/order-number=:orderNumber\",\n\t\t\tthis.getWithOrderNumber.bind(this),\n\t\t);\n\t}\n\n\tasync createFromQuote(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tBody: OrderFromQuoteDraft;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tif (this.repository.strict) {\n\t\t\tvalidateDraft(request.body, OrderFromQuoteDraftSchema);\n\t\t}\n\n\t\tconst resource = await this.repository.createFromQuote(\n\t\t\tgetRepositoryContext(request),\n\t\t\trequest.body,\n\t\t);\n\t\treturn reply.status(this.createStatusCode).send(resource);\n\t}\n\n\tasync import(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tBody: OrderImportDraft;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst importDraft = request.body;\n\t\tconst resource = await this.repository.import(\n\t\t\tgetRepositoryContext(request),\n\t\t\timportDraft,\n\t\t);\n\t\treturn reply.status(200).send(resource);\n\t}\n\n\tasync getWithOrderNumber(\n\t\trequest: FastifyRequest<{ Params: Record<string, string> }>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst params = request.params;\n\t\tconst orderNumber = params.orderNumber;\n\t\tconst resource = await this.repository.getWithOrderNumber(\n\t\t\tgetRepositoryContext(request),\n\t\t\torderNumber,\n\n\t\t\t// @ts-expect-error\n\t\t\trequest.query,\n\t\t);\n\t\tif (resource) {\n\t\t\treturn reply.status(200).send(resource);\n\t\t}\n\t\tthrow new CommercetoolsError<ResourceNotFoundError>(\n\t\t\t{\n\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\tmessage: `The Resource with key '${orderNumber}' was not found.`,\n\t\t\t},\n\t\t\t404,\n\t\t);\n\t}\n\n\tasync search(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tBody: OrderSearchRequest;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst resource = await this.repository.search(\n\t\t\tgetRepositoryContext(request),\n\t\t\trequest.body,\n\t\t);\n\t\treturn reply.status(200).send(resource);\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { PaymentRepository } from \"../repositories/payment/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class PaymentService extends AbstractService {\n\tpublic repository: PaymentRepository;\n\n\tconstructor(parent: FastifyInstance, repository: PaymentRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"payments\";\n\t}\n}\n","import type { ProductSearchRequest } from \"@commercetools/platform-sdk\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { getRepositoryContext } from \"#src/repositories/helpers.ts\";\nimport type { ProductRepository } from \"../repositories/product/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class ProductService extends AbstractService {\n\tpublic repository: ProductRepository;\n\n\tconstructor(parent: FastifyInstance, repository: ProductRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"products\";\n\t}\n\n\textraRoutes(instance: FastifyInstance) {\n\t\tinstance.post(\"/search\", this.search.bind(this));\n\t}\n\n\tasync search(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tBody: ProductSearchRequest;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst searchBody = request.body;\n\t\tconst resource = await this.repository.search(\n\t\t\tgetRepositoryContext(request),\n\t\t\tsearchBody,\n\t\t);\n\t\treturn reply.status(200).send(resource);\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { ProductDiscountRepository } from \"../repositories/product-discount.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class ProductDiscountService extends AbstractService {\n\tpublic repository: ProductDiscountRepository;\n\n\tconstructor(parent: FastifyInstance, repository: ProductDiscountRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"product-discounts\";\n\t}\n}\n","import type { InvalidInputError } from \"@commercetools/platform-sdk\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { queryParamsArray, queryParamsValue } from \"../helpers.ts\";\nimport { getRepositoryContext } from \"../repositories/helpers.ts\";\nimport type {\n\tProductProjectionQueryParams,\n\tProductProjectionRepository,\n} from \"./../repositories/product-projection.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class ProductProjectionService extends AbstractService {\n\tpublic repository: ProductProjectionRepository;\n\n\tconstructor(\n\t\tparent: FastifyInstance,\n\t\trepository: ProductProjectionRepository,\n\t) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"product-projections\";\n\t}\n\n\textraRoutes(instance: FastifyInstance) {\n\t\tinstance.get(\"/search\", this.search.bind(this));\n\t\tinstance.get(\"/suggest\", this.suggest.bind(this));\n\t}\n\n\tasync get(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tQuerystring: Record<string, any>;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst query = request.query;\n\t\tconst limit = this._parseParam(query.limit);\n\t\tconst offset = this._parseParam(query.offset);\n\n\t\tconst result = await this.repository.query(getRepositoryContext(request), {\n\t\t\t...query,\n\t\t\texpand: this._parseParam(query.expand),\n\t\t\twhere: this._parseParam(query.where),\n\t\t\tlimit: limit !== undefined ? Number(limit) : undefined,\n\t\t\toffset: offset !== undefined ? Number(offset) : undefined,\n\t\t});\n\t\treturn reply.status(200).send(result);\n\t}\n\n\tasync suggest(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tQuerystring: Record<string, any>;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst query = request.query;\n\t\tconst searchKeywords: Record<string, string> = {};\n\t\tfor (const key in query) {\n\t\t\tif (key.startsWith(\"searchKeywords.\")) {\n\t\t\t\tconst value = queryParamsValue(query[key]);\n\t\t\t\tif (value !== undefined) {\n\t\t\t\t\tsearchKeywords[key.substring(\"searchKeywords.\".length)] = value;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (Object.keys(searchKeywords).length === 0) {\n\t\t\tthrow new CommercetoolsError<InvalidInputError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidInput\",\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t\"Required parameter 'searchKeywords.{language}' is missing or invalid.\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\tconst limit = queryParamsValue(query.limit);\n\t\tconst fuzzyLevel = queryParamsValue(query.fuzzyLevel);\n\t\tconst resource = await this.repository.suggest(\n\t\t\tgetRepositoryContext(request),\n\t\t\t{\n\t\t\t\tsearchKeywords,\n\t\t\t\tstaged: queryParamsValue(query.staged) === \"true\",\n\t\t\t\tfuzzy: queryParamsValue(query.fuzzy) === \"true\",\n\t\t\t\tfuzzyLevel: fuzzyLevel !== undefined ? Number(fuzzyLevel) : undefined,\n\t\t\t\tlimit: limit !== undefined ? Number(limit) : undefined,\n\t\t\t},\n\t\t);\n\t\treturn reply.status(200).send(resource);\n\t}\n\n\tasync search(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tQuerystring: Record<string, any>;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst query = request.query;\n\t\tconst searchParams: ProductProjectionQueryParams = {\n\t\t\tfilter: queryParamsArray(query.filter),\n\t\t\t\"filter.query\": queryParamsArray(query[\"filter.query\"]),\n\t\t\tfacet: queryParamsArray(query.facet),\n\t\t\texpand: queryParamsArray(query.expand),\n\t\t\tstaged: queryParamsValue(query.staged) === \"true\",\n\t\t\tlocaleProjection: queryParamsValue(query.localeProjection),\n\t\t\tstoreProjection: queryParamsValue(query.storeProjection),\n\t\t\tpriceChannel: queryParamsValue(query.priceChannel),\n\t\t\tpriceCountry: queryParamsValue(query.priceCountry),\n\t\t\tpriceCurrency: queryParamsValue(query.priceCurrency),\n\t\t\tpriceCustomerGroup: queryParamsValue(query.priceCustomerGroup),\n\t\t\toffset: query.offset ? Number(queryParamsValue(query.offset)) : undefined,\n\t\t\tlimit: query.limit ? Number(queryParamsValue(query.limit)) : undefined,\n\t\t};\n\t\tconst resource = await this.repository.search(\n\t\t\tgetRepositoryContext(request),\n\t\t\tsearchParams,\n\t\t);\n\t\treturn reply.status(200).send(resource);\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { ProductSelectionRepository } from \"../repositories/product-selection.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class ProductSelectionService extends AbstractService {\n\tpublic repository: ProductSelectionRepository;\n\n\tconstructor(parent: FastifyInstance, repository: ProductSelectionRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"product-selections\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { ProductTypeRepository } from \"../repositories/product-type.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class ProductTypeService extends AbstractService {\n\tpublic repository: ProductTypeRepository;\n\n\tconstructor(parent: FastifyInstance, repository: ProductTypeRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"product-types\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { QuoteRepository } from \"#src/repositories/quote/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class QuoteService extends AbstractService {\n\tpublic repository: QuoteRepository;\n\n\tconstructor(parent: FastifyInstance, repository: QuoteRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"quotes\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { QuoteRequestRepository } from \"#src/repositories/quote-request/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class QuoteRequestService extends AbstractService {\n\tpublic repository: QuoteRequestRepository;\n\n\tconstructor(parent: FastifyInstance, repository: QuoteRequestRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"quote-requests\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { StagedQuoteRepository } from \"#src/repositories/quote-staged/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class StagedQuoteService extends AbstractService {\n\tpublic repository: StagedQuoteRepository;\n\n\tconstructor(parent: FastifyInstance, repository: StagedQuoteRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"staged-quotes\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { RecurrencePolicyRepository } from \"../repositories/recurrence-policy/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class RecurrencePolicyService extends AbstractService {\n\tpublic repository: RecurrencePolicyRepository;\n\n\tconstructor(parent: FastifyInstance, repository: RecurrencePolicyRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"recurrence-policies\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { RecurringOrderRepository } from \"../repositories/recurring-order/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class RecurringOrderService extends AbstractService {\n\tpublic repository: RecurringOrderRepository;\n\n\tconstructor(parent: FastifyInstance, repository: RecurringOrderRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"recurring-orders\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { ReviewRepository } from \"../repositories/review.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class ReviewService extends AbstractService {\n\tpublic repository: ReviewRepository;\n\n\tconstructor(parent: FastifyInstance, repository: ReviewRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"reviews\";\n\t}\n}\n","import type { InvalidInputError } from \"@commercetools/platform-sdk\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { queryParamsValue } from \"../helpers.ts\";\nimport { getRepositoryContext } from \"../repositories/helpers.ts\";\nimport type { ShippingMethodRepository } from \"../repositories/shipping-method/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class ShippingMethodService extends AbstractService {\n\tpublic repository: ShippingMethodRepository;\n\n\tconstructor(parent: FastifyInstance, repository: ShippingMethodRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"shipping-methods\";\n\t}\n\n\textraRoutes(parent: FastifyInstance) {\n\t\tparent.get(\"/matching-cart\", this.matchingCart.bind(this));\n\t}\n\n\tasync matchingCart(\n\t\trequest: FastifyRequest<{\n\t\t\tParams: Record<string, string>;\n\t\t\tQuerystring: Record<string, any>;\n\t\t}>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst query = request.query;\n\t\tconst cartId = queryParamsValue(query.cartId);\n\t\tif (!cartId) {\n\t\t\tthrow new CommercetoolsError<InvalidInputError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"InvalidInput\",\n\t\t\t\t\tmessage: \"Missing required parameter: cartId.\",\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tconst result = await this.repository.matchingCart(\n\t\t\tgetRepositoryContext(request),\n\t\t\tcartId,\n\t\t\t{\n\t\t\t\texpand: this._parseParam(query.expand),\n\t\t\t},\n\t\t);\n\t\treturn reply.status(200).send(result);\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { ShoppingListRepository } from \"../repositories/shopping-list/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class ShoppingListService extends AbstractService {\n\tpublic repository: ShoppingListRepository;\n\n\tconstructor(parent: FastifyInstance, repository: ShoppingListRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"shopping-lists\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { StandAlonePriceRepository } from \"../repositories/standalone-price.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class StandAlonePriceService extends AbstractService {\n\tpublic repository: StandAlonePriceRepository;\n\n\tconstructor(parent: FastifyInstance, repository: StandAlonePriceRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"standalone-prices\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { StateRepository } from \"../repositories/state.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class StateService extends AbstractService {\n\tpublic repository: StateRepository;\n\n\tconstructor(parent: FastifyInstance, repository: StateRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"states\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { StoreRepository } from \"../repositories/store.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class StoreService extends AbstractService {\n\tpublic repository: StoreRepository;\n\n\tconstructor(parent: FastifyInstance, repository: StoreRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"stores\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { SubscriptionRepository } from \"../repositories/subscription.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class SubscriptionService extends AbstractService {\n\tpublic repository: SubscriptionRepository;\n\n\tconstructor(parent: FastifyInstance, repository: SubscriptionRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"subscriptions\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { TaxCategoryRepository } from \"../repositories/tax-category/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class TaxCategoryService extends AbstractService {\n\tpublic repository: TaxCategoryRepository;\n\n\tconstructor(parent: FastifyInstance, repository: TaxCategoryRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"tax-categories\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { TypeRepository } from \"../repositories/type/index.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class TypeService extends AbstractService {\n\tpublic repository: TypeRepository;\n\n\tconstructor(parent: FastifyInstance, repository: TypeRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"types\";\n\t}\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { ZoneRepository } from \"../repositories/zone.ts\";\nimport AbstractService from \"./abstract.ts\";\n\nexport class ZoneService extends AbstractService {\n\tpublic repository: ZoneRepository;\n\n\tconstructor(parent: FastifyInstance, repository: ZoneRepository) {\n\t\tsuper(parent);\n\t\tthis.repository = repository;\n\t}\n\n\tgetBasePath() {\n\t\treturn \"zones\";\n\t}\n}\n","import type { createRepositories } from \"../repositories/index.ts\";\nimport { ApprovalFlowService } from \"./approval-flow.ts\";\nimport { ApprovalRuleService } from \"./approval-rule.ts\";\nimport { AsAssociateService } from \"./as-associate.ts\";\nimport { AssociateRoleServices } from \"./associate-roles.ts\";\nimport { AttributeGroupService } from \"./attribute-group.ts\";\nimport { BusinessUnitServices } from \"./business-units.ts\";\nimport { CartService } from \"./cart.ts\";\nimport { CartDiscountService } from \"./cart-discount.ts\";\nimport { CategoryServices } from \"./category.ts\";\nimport { ChannelService } from \"./channel.ts\";\nimport { CustomObjectService } from \"./custom-object.ts\";\nimport { CustomerService } from \"./customer.ts\";\nimport { CustomerGroupService } from \"./customer-group.ts\";\nimport { DiscountCodeService } from \"./discount-code.ts\";\nimport { DiscountGroupService } from \"./discount-group.ts\";\nimport { ExtensionServices } from \"./extension.ts\";\nimport { InventoryEntryService } from \"./inventory-entry.ts\";\nimport { MyBusinessUnitService } from \"./my-business-unit.ts\";\nimport { MyCartService } from \"./my-cart.ts\";\nimport { MyCustomerService } from \"./my-customer.ts\";\nimport { MyOrderService } from \"./my-order.ts\";\nimport { MyPaymentService } from \"./my-payment.ts\";\nimport { MyShoppingListService } from \"./my-shopping-list.ts\";\nimport { OrderService } from \"./order.ts\";\nimport { PaymentService } from \"./payment.ts\";\nimport { ProductService } from \"./product.ts\";\nimport { ProductDiscountService } from \"./product-discount.ts\";\nimport { ProductProjectionService } from \"./product-projection.ts\";\nimport { ProductSelectionService } from \"./product-selection.ts\";\nimport { ProductTypeService } from \"./product-type.ts\";\nimport { QuoteService } from \"./quote.ts\";\nimport { QuoteRequestService } from \"./quote-request.ts\";\nimport { StagedQuoteService } from \"./quote-staged.ts\";\nimport { RecurrencePolicyService } from \"./recurrence-policy.ts\";\nimport { RecurringOrderService } from \"./recurring-order.ts\";\nimport { ReviewService } from \"./reviews.ts\";\nimport { ShippingMethodService } from \"./shipping-method.ts\";\nimport { ShoppingListService } from \"./shopping-list.ts\";\nimport { StandAlonePriceService } from \"./standalone-price.ts\";\nimport { StateService } from \"./state.ts\";\nimport { StoreService } from \"./store.ts\";\nimport { SubscriptionService } from \"./subscription.ts\";\nimport { TaxCategoryService } from \"./tax-category.ts\";\nimport { TypeService } from \"./type.ts\";\nimport { ZoneService } from \"./zone.ts\";\n\ntype ServiceFactory = (\n\trouter: any,\n\trepos: ReturnType<typeof createRepositories>,\n) => unknown;\n\nconst serviceFactories = {\n\t\"approval-flow\": (router, repos) =>\n\t\tnew ApprovalFlowService(router, repos[\"approval-flow\"]),\n\t\"approval-rule\": (router, repos) =>\n\t\tnew ApprovalRuleService(router, repos[\"approval-rule\"]),\n\t\"associate-role\": (router, repos) =>\n\t\tnew AssociateRoleServices(router, repos[\"associate-role\"]),\n\t\"as-associate\": (router, repos) =>\n\t\tnew AsAssociateService(router, repos[\"as-associate\"]),\n\t\"business-unit\": (router, repos) =>\n\t\tnew BusinessUnitServices(router, repos[\"business-unit\"]),\n\tcategory: (router, repos) => new CategoryServices(router, repos.category),\n\tcart: (router, repos) => new CartService(router, repos.cart, repos.order),\n\t\"cart-discount\": (router, repos) =>\n\t\tnew CartDiscountService(router, repos[\"cart-discount\"]),\n\tcustomer: (router, repos) => new CustomerService(router, repos.customer),\n\tchannel: (router, repos) => new ChannelService(router, repos.channel),\n\t\"customer-group\": (router, repos) =>\n\t\tnew CustomerGroupService(router, repos[\"customer-group\"]),\n\t\"discount-code\": (router, repos) =>\n\t\tnew DiscountCodeService(router, repos[\"discount-code\"]),\n\t\"discount-group\": (router, repos) =>\n\t\tnew DiscountGroupService(router, repos[\"discount-group\"]),\n\textension: (router, repos) => new ExtensionServices(router, repos.extension),\n\t\"inventory-entry\": (router, repos) =>\n\t\tnew InventoryEntryService(router, repos[\"inventory-entry\"]),\n\t\"key-value-document\": (router, repos) =>\n\t\tnew CustomObjectService(router, repos[\"key-value-document\"]),\n\torder: (router, repos) => new OrderService(router, repos.order),\n\tpayment: (router, repos) => new PaymentService(router, repos.payment),\n\t\"standalone-price\": (router, repos) =>\n\t\tnew StandAlonePriceService(router, repos[\"standalone-price\"]),\n\t\"my-cart\": (router, repos) => new MyCartService(router, repos[\"my-cart\"]),\n\t\"my-order\": (router, repos) => new MyOrderService(router, repos[\"my-order\"]),\n\t\"my-customer\": (router, repos) =>\n\t\tnew MyCustomerService(router, repos[\"my-customer\"]),\n\t\"my-business-unit\": (router, repos) =>\n\t\tnew MyBusinessUnitService(router, repos[\"business-unit\"]),\n\t\"my-payment\": (router, repos) =>\n\t\tnew MyPaymentService(router, repos[\"my-payment\"]),\n\t\"my-shopping-list\": (router, repos) =>\n\t\tnew MyShoppingListService(router, repos[\"my-shopping-list\"]),\n\t\"shipping-method\": (router, repos) =>\n\t\tnew ShippingMethodService(router, repos[\"shipping-method\"]),\n\t\"product-type\": (router, repos) =>\n\t\tnew ProductTypeService(router, repos[\"product-type\"]),\n\tproduct: (router, repos) => new ProductService(router, repos.product),\n\t\"product-discount\": (router, repos) =>\n\t\tnew ProductDiscountService(router, repos[\"product-discount\"]),\n\t\"product-projection\": (router, repos) =>\n\t\tnew ProductProjectionService(router, repos[\"product-projection\"]),\n\t\"product-selection\": (router, repos) =>\n\t\tnew ProductSelectionService(router, repos[\"product-selection\"]),\n\tquotes: (router, repos) => new QuoteService(router, repos.quote),\n\t\"quote-request\": (router, repos) =>\n\t\tnew QuoteRequestService(router, repos[\"quote-request\"]),\n\t\"recurrence-policy\": (router, repos) =>\n\t\tnew RecurrencePolicyService(router, repos[\"recurrence-policy\"]),\n\t\"recurring-order\": (router, repos) =>\n\t\tnew RecurringOrderService(router, repos[\"recurring-order\"]),\n\treviews: (router, repos) => new ReviewService(router, repos.review),\n\t\"shopping-list\": (router, repos) =>\n\t\tnew ShoppingListService(router, repos[\"shopping-list\"]),\n\t\"staged-quote\": (router, repos) =>\n\t\tnew StagedQuoteService(router, repos[\"staged-quote\"]),\n\tstate: (router, repos) => new StateService(router, repos.state),\n\tstore: (router, repos) => new StoreService(router, repos.store),\n\tsubscription: (router, repos) =>\n\t\tnew SubscriptionService(router, repos.subscription),\n\t\"tax-category\": (router, repos) =>\n\t\tnew TaxCategoryService(router, repos[\"tax-category\"]),\n\t\"attribute-group\": (router, repos) =>\n\t\tnew AttributeGroupService(router, repos[\"attribute-group\"]),\n\ttype: (router, repos) => new TypeService(router, repos.type),\n\tzone: (router, repos) => new ZoneService(router, repos.zone),\n} satisfies Record<string, ServiceFactory>;\n\nexport type ServiceKey = keyof typeof serviceFactories;\n\n/**\n * Services mounted under `/{projectKey}/in-store/key={storeKey}`.\n *\n * commercetools documents in-store endpoints for a subset of resources only;\n * anything else under that prefix is a 404 on the real API. Mounting every\n * service there would make the mock accept requests that production rejects.\n *\n * `my-customer` is included because it also serves the in-store `/login` and\n * `/me/*` customer endpoints.\n */\nexport const IN_STORE_SERVICES: readonly ServiceKey[] = [\n\t\"business-unit\",\n\t\"cart\",\n\t\"cart-discount\",\n\t\"customer\",\n\t\"discount-code\",\n\t\"my-cart\",\n\t\"my-customer\",\n\t\"my-order\",\n\t\"my-shopping-list\",\n\t\"order\",\n\t\"product\",\n\t\"product-projection\",\n\t\"quote-request\",\n\t\"quotes\",\n\t\"shipping-method\",\n\t\"shopping-list\",\n\t\"staged-quote\",\n];\n\nexport const createServices = (\n\trouter: any,\n\trepos: ReturnType<typeof createRepositories>,\n\tkeys: readonly ServiceKey[] = Object.keys(serviceFactories) as ServiceKey[],\n): void => {\n\tfor (const key of keys) {\n\t\tserviceFactories[key](router, repos);\n\t}\n};\n","import type {\n\tResourceNotFoundError,\n\tUpdate,\n} from \"@commercetools/platform-sdk\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { updateRequestSchema } from \"#src/schemas/update-request.ts\";\nimport { validateData } from \"#src/validate.ts\";\nimport { getRepositoryContext } from \"../repositories/helpers.ts\";\nimport type { ProjectRepository } from \"../repositories/project.ts\";\n\nexport class ProjectService {\n\tpublic repository: ProjectRepository;\n\n\tconstructor(parent: FastifyInstance, repository: ProjectRepository) {\n\t\tthis.repository = repository;\n\t\tthis.registerRoutes(parent);\n\t}\n\n\tregisterRoutes(parent: FastifyInstance) {\n\t\tparent.get(\"\", this.get.bind(this));\n\t\tparent.post(\"\", this.post.bind(this));\n\t}\n\n\tasync get(\n\t\trequest: FastifyRequest<{ Params: Record<string, string> }>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst project = await this.repository.get(getRepositoryContext(request));\n\t\treturn reply.status(200).send(project);\n\t}\n\n\tasync post(\n\t\trequest: FastifyRequest<{ Params: Record<string, string> }>,\n\t\treply: FastifyReply,\n\t) {\n\t\tconst updateRequest = validateData<Update>(\n\t\t\trequest.body,\n\t\t\tupdateRequestSchema,\n\t\t);\n\t\tconst project = await this.repository.get(getRepositoryContext(request));\n\n\t\tif (!project) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>(\n\t\t\t\t{\n\t\t\t\t\tcode: \"ResourceNotFound\",\n\t\t\t\t\tmessage: \"The Resource was not found.\",\n\t\t\t\t},\n\t\t\t\t404,\n\t\t\t);\n\t\t}\n\n\t\tconst updatedResource = await this.repository.processUpdateActions(\n\t\t\tgetRepositoryContext(request),\n\t\t\tproject,\n\t\t\tupdateRequest.version,\n\t\t\tupdateRequest.actions,\n\t\t);\n\n\t\treturn reply.status(200).send(updatedResource);\n\t}\n}\n","import { cloneObject } from \"../helpers.ts\";\n\n/**\n * A Map wrapper that deep-clones values on insertion and retrieval.\n *\n * This ensures that the stored data is fully isolated from external\n * mutations: callers cannot accidentally corrupt the store by modifying\n * an object after inserting it, and retrieved objects are independent\n * copies that can be freely mutated without affecting the store.\n */\nexport class StorageMap<K, V> {\n\tprivate _map: Map<K, V>;\n\n\tconstructor() {\n\t\tthis._map = new Map();\n\t}\n\n\tget size(): number {\n\t\treturn this._map.size;\n\t}\n\n\tset(key: K, value: V): this {\n\t\tthis._map.set(key, cloneObject(value));\n\t\treturn this;\n\t}\n\n\tget(key: K): V | undefined {\n\t\tconst value = this._map.get(key);\n\t\tif (value === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn cloneObject(value);\n\t}\n\n\thas(key: K): boolean {\n\t\treturn this._map.has(key);\n\t}\n\n\tdelete(key: K): boolean {\n\t\treturn this._map.delete(key);\n\t}\n\n\tclear(): void {\n\t\tthis._map.clear();\n\t}\n\n\t/**\n\t * Returns cloned values. Each value is a deep copy.\n\t */\n\tvalues(): IterableIterator<V> {\n\t\tconst inner = this._map.values();\n\n\t\treturn (function* () {\n\t\t\tfor (const value of inner) {\n\t\t\t\tyield cloneObject(value);\n\t\t\t}\n\t\t})() as IterableIterator<V>;\n\t}\n\n\t/**\n\t * Returns cloned entries. Each value is a deep copy, keys are returned as-is.\n\t */\n\tentries(): IterableIterator<[K, V]> {\n\t\tconst inner = this._map.entries();\n\t\treturn (function* () {\n\t\t\tfor (const [key, value] of inner) {\n\t\t\t\tyield [key, cloneObject(value)] as [K, V];\n\t\t\t}\n\t\t})() as IterableIterator<[K, V]>;\n\t}\n\n\t[Symbol.iterator](): IterableIterator<[K, V]> {\n\t\treturn this.entries();\n\t}\n}\n","import type {\n\tApprovalFlow,\n\tApprovalRule,\n\tAssociateRole,\n\tAttributeGroup,\n\tBusinessUnit,\n\tCart,\n\tCartDiscount,\n\tCategory,\n\tChannel,\n\tCustomer,\n\tCustomerGroup,\n\tCustomObject,\n\tDiscountCode,\n\tDiscountGroup,\n\tExtension,\n\tInvalidInputError,\n\tInventoryEntry,\n\tOrder,\n\tPayment,\n\tProduct,\n\tProductDiscount,\n\tProductProjection,\n\tProductTailoring,\n\tProductType,\n\tProject,\n\tQuote,\n\tQuoteRequest,\n\tRecurrencePolicy,\n\tRecurringOrder,\n\tShippingMethod,\n\tShoppingList,\n\tStagedQuote,\n\tState,\n\tStore,\n\tSubscription,\n\tTaxCategory,\n\tType,\n\tZone,\n} from \"@commercetools/platform-sdk\";\nimport { CommercetoolsError } from \"#src/exceptions.ts\";\nimport { cloneObject } from \"../helpers.ts\";\nimport { parseQueryExpression } from \"../lib/predicateParser.ts\";\nimport { applySort } from \"../lib/sortParser.ts\";\nimport type {\n\tPagedQueryResponseMap,\n\tResourceMap,\n\tResourceType,\n} from \"../types.ts\";\nimport type { GetParams, ProjectStorage, QueryParams } from \"./abstract.ts\";\nimport { AbstractStorage } from \"./abstract.ts\";\nimport { StorageMap } from \"./storage-map.ts\";\n\nexport class InMemoryStorage extends AbstractStorage {\n\tprotected resources: {\n\t\t[projectKey: string]: ProjectStorage;\n\t} = {};\n\n\tprotected projects: {\n\t\t[projectKey: string]: Project;\n\t} = {};\n\n\t// Secondary index for custom objects: projectKey -> \"container\\0key\" -> resource id\n\tprivate _customObjectIndex: Map<string, Map<string, string>> = new Map();\n\n\tasync addProject(projectKey: string): Promise<Project> {\n\t\tif (!this.projects[projectKey]) {\n\t\t\tthis.projects[projectKey] = {\n\t\t\t\tkey: projectKey,\n\t\t\t\tname: \"\",\n\t\t\t\tcountries: [],\n\t\t\t\tcurrencies: [],\n\t\t\t\tlanguages: [],\n\t\t\t\tcreatedAt: \"2018-10-04T11:32:12.603Z\",\n\t\t\t\ttrialUntil: \"2018-12\",\n\t\t\t\tcarts: {\n\t\t\t\t\tcountryTaxRateFallbackEnabled: false,\n\t\t\t\t\tdeleteDaysAfterLastModification: 90,\n\t\t\t\t\tpriceRoundingMode: \"HalfEven\",\n\t\t\t\t\ttaxRoundingMode: \"HalfEven\",\n\t\t\t\t},\n\t\t\t\tshoppingLists: {\n\t\t\t\t\tdeleteDaysAfterLastModification: 360,\n\t\t\t\t},\n\t\t\t\tmessages: { enabled: false, deleteDaysAfterCreation: 15 },\n\t\t\t\tinventory: { releaseExpiredReservations: false },\n\t\t\t\tshippingRateInputType: undefined,\n\t\t\t\texternalOAuth: undefined,\n\t\t\t\tsearchIndexing: {\n\t\t\t\t\tproducts: {\n\t\t\t\t\t\tstatus: \"Deactivated\",\n\t\t\t\t\t},\n\t\t\t\t\tproductsSearch: {\n\t\t\t\t\t\tstatus: \"Deactivated\",\n\t\t\t\t\t},\n\t\t\t\t\torders: {\n\t\t\t\t\t\tstatus: \"Deactivated\",\n\t\t\t\t\t},\n\t\t\t\t\tcustomers: {\n\t\t\t\t\t\tstatus: \"Deactivated\",\n\t\t\t\t\t},\n\t\t\t\t\tbusinessUnits: {\n\t\t\t\t\t\tstatus: \"Deactivated\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tdiscounts: {\n\t\t\t\t\tdiscountCombinationMode: \"Stacking\",\n\t\t\t\t},\n\t\t\t\tversion: 1,\n\t\t\t};\n\t\t}\n\t\treturn this.projects[projectKey];\n\t}\n\n\tasync saveProject(project: Project): Promise<Project> {\n\t\tthis.projects[project.key] = cloneObject(project);\n\t\treturn project;\n\t}\n\n\tasync getProject(projectKey: string): Promise<Project> {\n\t\tawait this.addProject(projectKey);\n\t\treturn cloneObject(this.projects[projectKey]);\n\t}\n\n\tprivate async forProjectKey(projectKey: string): Promise<ProjectStorage> {\n\t\tawait this.addProject(projectKey);\n\n\t\tlet projectStorage = this.resources[projectKey];\n\t\tif (!projectStorage) {\n\t\t\tprojectStorage = this.resources[projectKey] = {\n\t\t\t\t\"approval-flow\": new StorageMap<string, ApprovalFlow>(),\n\t\t\t\t\"approval-rule\": new StorageMap<string, ApprovalRule>(),\n\t\t\t\t\"associate-role\": new StorageMap<string, AssociateRole>(),\n\t\t\t\t\"attribute-group\": new StorageMap<string, AttributeGroup>(),\n\t\t\t\t\"business-unit\": new StorageMap<string, BusinessUnit>(),\n\t\t\t\tcart: new StorageMap<string, Cart>(),\n\t\t\t\t\"cart-discount\": new StorageMap<string, CartDiscount>(),\n\t\t\t\tcategory: new StorageMap<string, Category>(),\n\t\t\t\tchannel: new StorageMap<string, Channel>(),\n\t\t\t\tcustomer: new StorageMap<string, Customer>(),\n\t\t\t\t\"customer-group\": new StorageMap<string, CustomerGroup>(),\n\t\t\t\t\"discount-code\": new StorageMap<string, DiscountCode>(),\n\t\t\t\t\"discount-group\": new StorageMap<string, DiscountGroup>(),\n\t\t\t\textension: new StorageMap<string, Extension>(),\n\t\t\t\t\"inventory-entry\": new StorageMap<string, InventoryEntry>(),\n\t\t\t\t\"key-value-document\": new StorageMap<string, CustomObject>(),\n\t\t\t\torder: new StorageMap<string, Order>(),\n\t\t\t\t\"order-edit\": new StorageMap<string, any>(),\n\t\t\t\tpayment: new StorageMap<string, Payment>(),\n\t\t\t\tproduct: new StorageMap<string, Product>(),\n\t\t\t\tquote: new StorageMap<string, Quote>(),\n\t\t\t\t\"quote-request\": new StorageMap<string, QuoteRequest>(),\n\t\t\t\t\"product-discount\": new StorageMap<string, ProductDiscount>(),\n\t\t\t\t\"product-selection\": new StorageMap<string, any>(),\n\t\t\t\t\"product-type\": new StorageMap<string, ProductType>(),\n\t\t\t\t\"product-projection\": new StorageMap<string, ProductProjection>(),\n\t\t\t\t\"product-tailoring\": new StorageMap<string, ProductTailoring>(),\n\t\t\t\t\"recurrence-policy\": new StorageMap<string, RecurrencePolicy>(),\n\t\t\t\t\"recurring-order\": new StorageMap<string, RecurringOrder>(),\n\t\t\t\treview: new StorageMap<string, any>(),\n\t\t\t\t\"shipping-method\": new StorageMap<string, ShippingMethod>(),\n\t\t\t\t\"staged-quote\": new StorageMap<string, StagedQuote>(),\n\t\t\t\tstate: new StorageMap<string, State>(),\n\t\t\t\tstore: new StorageMap<string, Store>(),\n\t\t\t\t\"shopping-list\": new StorageMap<string, ShoppingList>(),\n\t\t\t\t\"standalone-price\": new StorageMap<string, any>(),\n\t\t\t\tsubscription: new StorageMap<string, Subscription>(),\n\t\t\t\t\"tax-category\": new StorageMap<string, TaxCategory>(),\n\t\t\t\ttype: new StorageMap<string, Type>(),\n\t\t\t\tzone: new StorageMap<string, Zone>(),\n\t\t\t};\n\t\t}\n\t\treturn projectStorage;\n\t}\n\n\tasync clear(): Promise<void> {\n\t\tfor (const [, projectStorage] of Object.entries(this.resources)) {\n\t\t\tfor (const [, value] of Object.entries(projectStorage)) {\n\t\t\t\tvalue?.clear();\n\t\t\t}\n\t\t}\n\t\tthis._customObjectIndex.clear();\n\t}\n\n\tasync all<RT extends ResourceType>(\n\t\tprojectKey: string,\n\t\ttypeId: RT,\n\t): Promise<ResourceMap[RT][]> {\n\t\tconst projectStorage = await this.forProjectKey(projectKey);\n\t\tconst store = projectStorage[typeId];\n\t\tif (store) {\n\t\t\t// StorageMap.values() already returns cloned values\n\t\t\treturn Array.from(store.values()) as ResourceMap[RT][];\n\t\t}\n\t\treturn [];\n\t}\n\n\tasync count(projectKey: string, typeId: ResourceType): Promise<number> {\n\t\tconst projectStorage = await this.forProjectKey(projectKey);\n\t\tconst store = projectStorage[typeId];\n\t\treturn store ? store.size : 0;\n\t}\n\n\tasync add<RT extends ResourceType>(\n\t\tprojectKey: string,\n\t\ttypeId: RT,\n\t\tobj: ResourceMap[RT],\n\t\tparams: GetParams = {},\n\t): Promise<ResourceMap[RT]> {\n\t\tconst store = await this.forProjectKey(projectKey);\n\t\t// StorageMap.set() clones the value before storing\n\t\tstore[typeId]?.set(obj.id, obj);\n\n\t\t// Maintain secondary index for custom objects\n\t\tif (typeId === \"key-value-document\") {\n\t\t\tconst co = obj as unknown as CustomObject;\n\t\t\tlet projectIndex = this._customObjectIndex.get(projectKey);\n\t\t\tif (!projectIndex) {\n\t\t\t\tprojectIndex = new Map();\n\t\t\t\tthis._customObjectIndex.set(projectKey, projectIndex);\n\t\t\t}\n\t\t\tprojectIndex.set(`${co.container}\\0${co.key}`, co.id);\n\t\t}\n\n\t\t// StorageMap.get() returns a clone, so we get a fresh copy for expand\n\t\tconst clone = store[typeId]?.get(obj.id) as ResourceMap[RT];\n\t\treturn this.expand(projectKey, clone, params.expand);\n\t}\n\n\tasync get<RT extends ResourceType>(\n\t\tprojectKey: string,\n\t\ttypeId: RT,\n\t\tid: string,\n\t\tparams: GetParams = {},\n\t): Promise<ResourceMap[RT] | null> {\n\t\tconst projectStorage = await this.forProjectKey(projectKey);\n\t\t// StorageMap.get() already returns a clone\n\t\tconst resource = projectStorage[typeId]?.get(id);\n\t\tif (resource) {\n\t\t\tconst expanded = await this.expand(projectKey, resource, params.expand);\n\t\t\treturn expanded as ResourceMap[RT];\n\t\t}\n\t\treturn null;\n\t}\n\n\tasync getByKey<RT extends ResourceType>(\n\t\tprojectKey: string,\n\t\ttypeId: RT,\n\t\tkey: string,\n\t\tparams: GetParams = {},\n\t): Promise<ResourceMap[RT] | null> {\n\t\tconst store = await this.forProjectKey(projectKey);\n\t\tif (!store) {\n\t\t\tthrow new Error(\"No type\");\n\t\t}\n\t\tconst resourceStore = store[typeId];\n\n\t\t// StorageMap.values() already returns cloned values\n\t\tconst resources: any[] = Array.from(resourceStore.values());\n\t\tconst resource = resources.find((e) => e.key === key);\n\t\tif (resource) {\n\t\t\tconst expanded = await this.expand(projectKey, resource, params.expand);\n\t\t\treturn expanded as ResourceMap[RT];\n\t\t}\n\t\treturn null;\n\t}\n\n\tasync delete<RT extends ResourceType>(\n\t\tprojectKey: string,\n\t\ttypeId: RT,\n\t\tid: string,\n\t\tparams: GetParams = {},\n\t): Promise<ResourceMap[RT] | null> {\n\t\tconst resource = await this.get(projectKey, typeId, id);\n\n\t\tif (resource) {\n\t\t\tconst projectStorage = await this.forProjectKey(projectKey);\n\t\t\tprojectStorage[typeId]?.delete(id);\n\n\t\t\t// Remove from secondary index for custom objects\n\t\t\tif (typeId === \"key-value-document\") {\n\t\t\t\tconst co = resource as unknown as CustomObject;\n\t\t\t\tthis._customObjectIndex\n\t\t\t\t\t.get(projectKey)\n\t\t\t\t\t?.delete(`${co.container}\\0${co.key}`);\n\t\t\t}\n\n\t\t\treturn this.expand(projectKey, resource, params.expand);\n\t\t}\n\t\treturn resource;\n\t}\n\n\tasync getByContainerAndKey(\n\t\tprojectKey: string,\n\t\tcontainer: string,\n\t\tkey: string,\n\t): Promise<CustomObject | null> {\n\t\tconst projectIndex = this._customObjectIndex.get(projectKey);\n\t\tif (!projectIndex) {\n\t\t\treturn null;\n\t\t}\n\t\tconst id = projectIndex.get(`${container}\\0${key}`);\n\t\tif (!id) {\n\t\t\treturn null;\n\t\t}\n\t\tconst resource = await this.get(projectKey, \"key-value-document\", id);\n\t\treturn resource as CustomObject | null;\n\t}\n\n\tasync query<RT extends ResourceType>(\n\t\tprojectKey: string,\n\t\ttypeId: RT,\n\t\tparams: QueryParams,\n\t): Promise<PagedQueryResponseMap[RT]> {\n\t\tconst projectStorage = await this.forProjectKey(projectKey);\n\t\tconst store = projectStorage[typeId];\n\t\tif (!store) {\n\t\t\tthrow new Error(\"No type\");\n\t\t}\n\n\t\t// all() already returns cloned values via StorageMap\n\t\tlet resources = await this.all<RT>(projectKey, typeId);\n\n\t\t// Apply predicates\n\t\tif (params.where) {\n\t\t\t// Get all key-value pairs starting with 'var.' to pass as variables, removing\n\t\t\t// the 'var.' prefix.\n\t\t\tconst vars = Object.fromEntries(\n\t\t\t\tObject.entries(params)\n\t\t\t\t\t.filter(([key]) => key.startsWith(\"var.\"))\n\t\t\t\t\t.map(([key, value]) => [key.slice(4), value]),\n\t\t\t);\n\n\t\t\ttry {\n\t\t\t\tconst filterFunc = parseQueryExpression(params.where);\n\t\t\t\tresources = resources.filter((resource) => filterFunc(resource, vars));\n\t\t\t} catch (err) {\n\t\t\t\tthrow new CommercetoolsError<InvalidInputError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"InvalidInput\",\n\t\t\t\t\t\tmessage: (err as any).message,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Apply sorting before paging: a cursor-based pager (`where id > \"...\"`\n\t\t// with `sort id asc`) depends on a deterministic order.\n\t\tresources = applySort(resources, params.sort);\n\n\t\t// Get the total before slicing the array\n\t\tconst totalResources = resources.length;\n\n\t\t// Apply offset, limit\n\t\tconst offset = params.offset || 0;\n\t\tconst limit = params.limit || 20;\n\t\tresources = resources.slice(offset, offset + limit);\n\n\t\t// Expand the resources\n\t\tif (params.expand !== undefined) {\n\t\t\tresources = await Promise.all(\n\t\t\t\tresources.map((resource) =>\n\t\t\t\t\tthis.expand(projectKey, resource, params.expand),\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\n\t\treturn {\n\t\t\tcount: resources.length,\n\t\t\ttotal: totalResources,\n\t\t\toffset: offset,\n\t\t\tlimit: limit,\n\t\t\t// Resources are already clones from StorageMap\n\t\t\tresults: resources,\n\t\t} as PagedQueryResponseMap[RT];\n\t}\n}\n","import Fastify, { type FastifyBaseLogger, type FastifyInstance } from \"fastify\";\nimport { type AnyHandler, HttpResponse, http } from \"msw\";\nimport type { SetupServer } from \"msw/node\";\nimport qs from \"qs\";\nimport type { Config } from \"./config.ts\";\nimport { DEFAULT_API_HOSTNAME, DEFAULT_AUTH_HOSTNAME } from \"./constants.ts\";\nimport { CommercetoolsError } from \"./exceptions.ts\";\nimport { mapHeaderType } from \"./helpers.ts\";\nimport { copyHeaders } from \"./lib/proxy.ts\";\nimport { OAuth2Server } from \"./oauth/server.ts\";\nimport { ProjectAPI } from \"./projectAPI.ts\";\nimport type { RepositoryMap } from \"./repositories/index.ts\";\nimport { createRepositories } from \"./repositories/index.ts\";\nimport type { ProjectRepository } from \"./repositories/project.ts\";\nimport { createServices, IN_STORE_SERVICES } from \"./services/index.ts\";\nimport { ProjectService } from \"./services/project.ts\";\nimport type { AbstractStorage } from \"./storage/index.ts\";\nimport { InMemoryStorage } from \"./storage/index.ts\";\n\nexport type CommercetoolsMockOptions = {\n\tvalidateCredentials: boolean;\n\tenableAuthentication: boolean;\n\tdefaultProjectKey: string | undefined;\n\tapiHost: RegExp | string;\n\tauthHost: RegExp | string;\n\tsilent: boolean;\n\tstrict: boolean;\n\tstorage: AbstractStorage | undefined;\n\tlogger: FastifyBaseLogger | undefined;\n};\n\nconst DEFAULT_OPTIONS: CommercetoolsMockOptions = {\n\tenableAuthentication: false,\n\tvalidateCredentials: false,\n\tdefaultProjectKey: undefined,\n\tapiHost: DEFAULT_API_HOSTNAME,\n\tauthHost: DEFAULT_AUTH_HOSTNAME,\n\tsilent: true,\n\tstrict: false,\n\tstorage: undefined,\n\tlogger: undefined,\n};\n\nconst _globalListeners: SetupServer[] = [];\n\nexport class CommercetoolsMock {\n\tpublic app: FastifyInstance;\n\n\tpublic options: CommercetoolsMockOptions;\n\n\tprivate _storage: AbstractStorage;\n\n\tprivate _oauth2: OAuth2Server;\n\n\tprivate _mswServer: SetupServer | undefined = undefined;\n\n\tprivate _repositories: RepositoryMap | null;\n\n\t// biome-ignore lint: lint/correctness/noUnusedPrivateClassMembers\n\tprivate _projectService: ProjectService | undefined;\n\n\tconstructor(options: Partial<CommercetoolsMockOptions> = {}) {\n\t\tthis.options = { ...DEFAULT_OPTIONS, ...options };\n\t\tthis._repositories = null;\n\t\tthis._projectService = undefined;\n\n\t\tthis._storage = this.options.storage ?? new InMemoryStorage();\n\t\tthis._oauth2 = new OAuth2Server({\n\t\t\tenabled: this.options.enableAuthentication,\n\t\t\tvalidate: this.options.validateCredentials,\n\t\t});\n\n\t\tthis.app = this.createApp();\n\t}\n\n\tget server() {\n\t\treturn this.app.server;\n\t}\n\n\tasync clear() {\n\t\tawait this._storage.clear();\n\t}\n\n\tproject(projectKey?: string) {\n\t\tif (!projectKey && !this.options.defaultProjectKey) {\n\t\t\tthrow new Error(\"No projectKey passed and no default set\");\n\t\t}\n\n\t\tif (this._repositories === null) {\n\t\t\tthrow new Error(\"repositories not initialized yet\");\n\t\t}\n\n\t\tconst config: Config = {\n\t\t\tstrict: this.options.strict,\n\t\t\tstorage: this._storage,\n\t\t};\n\n\t\treturn new ProjectAPI(\n\t\t\tprojectKey || this.options.defaultProjectKey!,\n\t\t\tthis._repositories,\n\t\t\tconfig,\n\t\t);\n\t}\n\n\tauthStore() {\n\t\treturn this._oauth2.store;\n\t}\n\n\tasync runServer(port = 3000) {\n\t\tawait this.app.listen({ port, host: \"0.0.0.0\" });\n\t}\n\n\tprivate createApp(): FastifyInstance {\n\t\tconst config: Config = {\n\t\t\tstrict: this.options.strict,\n\t\t\tstorage: this._storage,\n\t\t};\n\t\tthis._repositories = createRepositories(config);\n\t\tthis._oauth2.setCustomerRepository(this._repositories.customer);\n\n\t\tconst loggerConfig = this.options.logger\n\t\t\t? { loggerInstance: this.options.logger }\n\t\t\t: { logger: !this.options.silent ? { level: \"info\" as const } : false };\n\n\t\tconst app = Fastify({\n\t\t\t// Set limit to 16mb, this is the maximum size allowed by the commercetools API: https://docs.commercetools.com/api/limits\n\t\t\tbodyLimit: 16 * 1024 * 1024,\n\t\t\t...loggerConfig,\n\t\t\trouterOptions: {\n\t\t\t\tquerystringParser: (str) => qs.parse(str),\n\t\t\t},\n\t\t});\n\n\t\t// Override the default JSON parser to accept empty bodies. This is\n\t\t// needed because some HTTP clients (e.g. commercetools SDKs) send\n\t\t// DELETE requests with a Content-Type: application/json header but\n\t\t// without a body. Fastify 5 rejects these by default.\n\t\tapp.addContentTypeParser(\n\t\t\t\"application/json\",\n\t\t\t{ parseAs: \"string\" },\n\t\t\t(_req, body, done) => {\n\t\t\t\tif (!body || (typeof body === \"string\" && body.trim() === \"\")) {\n\t\t\t\t\tdone(null, undefined);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tdone(null, JSON.parse(body as string));\n\t\t\t\t} catch (err) {\n\t\t\t\t\tdone(err as Error, undefined);\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\n\t\t// Register OAuth routes\n\t\tapp.register(this._oauth2.createPlugin(), { prefix: \"/oauth\" });\n\n\t\t// Register project routes\n\t\tconst repositories = this._repositories;\n\t\tconst oauth2 = this._oauth2;\n\t\tconst enableAuth = this.options.enableAuthentication;\n\n\t\tconst projectPlugin = async (instance: FastifyInstance) => {\n\t\t\tif (enableAuth) {\n\t\t\t\tinstance.addHook(\"preHandler\", oauth2.createMiddleware());\n\t\t\t}\n\t\t\tcreateServices(instance, repositories);\n\t\t\tnew ProjectService(instance, repositories.project as ProjectRepository);\n\t\t};\n\n\t\t// Only the resources commercetools documents under\n\t\t// /{projectKey}/in-store/key={storeKey} are mounted there; the rest 404,\n\t\t// as they do on the real API.\n\t\tconst inStorePlugin = async (instance: FastifyInstance) => {\n\t\t\tif (enableAuth) {\n\t\t\t\tinstance.addHook(\"preHandler\", oauth2.createMiddleware());\n\t\t\t}\n\t\t\tcreateServices(instance, repositories, IN_STORE_SERVICES);\n\t\t};\n\n\t\tapp.register(projectPlugin, { prefix: \"/:projectKey\" });\n\t\tapp.register(inStorePlugin, {\n\t\t\tprefix: \"/:projectKey/in-store/key=:storeKey\",\n\t\t});\n\n\t\t// Error handler\n\t\tapp.setErrorHandler((error, request, reply) => {\n\t\t\tif (error instanceof CommercetoolsError) {\n\t\t\t\tconst responseBody =\n\t\t\t\t\terror.errors?.length > 0\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tstatusCode: error.statusCode,\n\t\t\t\t\t\t\t\tmessage: error.message,\n\t\t\t\t\t\t\t\terrors: error.errors,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tstatusCode: error.statusCode,\n\t\t\t\t\t\t\t\tmessage: error.message,\n\t\t\t\t\t\t\t\terrors: [error.info],\n\t\t\t\t\t\t\t};\n\n\t\t\t\trequest.log.error(\n\t\t\t\t\t{ statusCode: error.statusCode, err: error },\n\t\t\t\t\t`${request.method} ${request.url} - ${error.statusCode}: ${error.message}`,\n\t\t\t\t);\n\n\t\t\t\treturn reply.status(error.statusCode).send(responseBody);\n\t\t\t}\n\n\t\t\trequest.log.error(\n\t\t\t\t{ statusCode: 500, err: error },\n\t\t\t\t`${request.method} ${request.url} - 500: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\n\t\t\treturn reply.status(500).send({\n\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t});\n\t\t});\n\n\t\treturn app;\n\t}\n\n\t// registerHandlers is an alternative way to work with commercetools-mock, it\n\t// allows you to manage msw server yourself and register the handlers needed\n\t// for commercetools-mock to work.\n\tpublic registerHandlers(server: SetupServer): void {\n\t\tconst handlers = this.getHandlers();\n\t\tserver.use(...handlers);\n\t}\n\n\tpublic getHandlers(): AnyHandler[] {\n\t\tconst app = this.app;\n\t\treturn [\n\t\t\thttp.post(`${this.options.authHost}/oauth/*`, async ({ request }) => {\n\t\t\t\tconst body = await request.text();\n\t\t\t\tconst url = new URL(request.url);\n\t\t\t\tconst headers = copyHeaders(request.headers);\n\n\t\t\t\tconst res = await app.inject({\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\turl: `${url.pathname}?${url.searchParams.toString()}`,\n\t\t\t\t\tbody,\n\t\t\t\t\theaders,\n\t\t\t\t});\n\t\t\t\treturn new HttpResponse(res.body, {\n\t\t\t\t\tstatus: res.statusCode,\n\t\t\t\t\theaders: mapHeaderType(res.headers),\n\t\t\t\t});\n\t\t\t}),\n\t\t\thttp.head(`${this.options.apiHost}/*`, async ({ request }) => {\n\t\t\t\tconst body = await request.text();\n\t\t\t\tconst url = new URL(request.url);\n\t\t\t\tconst headers = copyHeaders(request.headers);\n\n\t\t\t\tconst res = await app.inject({\n\t\t\t\t\tmethod: \"GET\",\n\t\t\t\t\turl: `${url.pathname}?${url.searchParams.toString()}`,\n\t\t\t\t\tbody,\n\t\t\t\t\theaders,\n\t\t\t\t});\n\n\t\t\t\tif (res.statusCode === 200) {\n\t\t\t\t\tconst parsedBody = JSON.parse(res.body);\n\t\t\t\t\tconst resultCount =\n\t\t\t\t\t\t\"count\" in parsedBody\n\t\t\t\t\t\t\t? parsedBody.count\n\t\t\t\t\t\t\t: Object.keys(parsedBody).length;\n\n\t\t\t\t\treturn new HttpResponse(null, {\n\t\t\t\t\t\tstatus: resultCount > 0 ? 200 : 404,\n\t\t\t\t\t\theaders: mapHeaderType(res.headers),\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn new HttpResponse(null, {\n\t\t\t\t\tstatus: res.statusCode,\n\t\t\t\t\theaders: mapHeaderType(res.headers),\n\t\t\t\t});\n\t\t\t}),\n\t\t\thttp.get(`${this.options.apiHost}/*`, async ({ request }) => {\n\t\t\t\tconst body = await request.text();\n\t\t\t\tconst url = new URL(request.url);\n\t\t\t\tconst headers = copyHeaders(request.headers);\n\n\t\t\t\tconst res = await app.inject({\n\t\t\t\t\tmethod: \"GET\",\n\t\t\t\t\turl: `${url.pathname}?${url.searchParams.toString()}`,\n\t\t\t\t\tbody,\n\t\t\t\t\theaders,\n\t\t\t\t});\n\t\t\t\treturn new HttpResponse(res.body, {\n\t\t\t\t\tstatus: res.statusCode,\n\t\t\t\t\theaders: mapHeaderType(res.headers),\n\t\t\t\t});\n\t\t\t}),\n\t\t\thttp.post(`${this.options.apiHost}/*`, async ({ request }) => {\n\t\t\t\tconst body = await request.text();\n\t\t\t\tconst url = new URL(request.url);\n\t\t\t\tconst headers = copyHeaders(request.headers);\n\n\t\t\t\tconst res = await app.inject({\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\turl: `${url.pathname}?${url.searchParams.toString()}`,\n\t\t\t\t\tbody,\n\t\t\t\t\theaders,\n\t\t\t\t});\n\t\t\t\treturn new HttpResponse(res.body, {\n\t\t\t\t\tstatus: res.statusCode,\n\t\t\t\t\theaders: mapHeaderType(res.headers),\n\t\t\t\t});\n\t\t\t}),\n\t\t\thttp.delete(`${this.options.apiHost}/*`, async ({ request }) => {\n\t\t\t\tconst body = await request.text();\n\t\t\t\tconst url = new URL(request.url);\n\t\t\t\tconst headers = copyHeaders(request.headers);\n\n\t\t\t\tconst res = await app.inject({\n\t\t\t\t\tmethod: \"DELETE\",\n\t\t\t\t\turl: `${url.pathname}?${url.searchParams.toString()}`,\n\t\t\t\t\tbody,\n\t\t\t\t\theaders,\n\t\t\t\t});\n\t\t\t\treturn new HttpResponse(res.body, {\n\t\t\t\t\tstatus: res.statusCode,\n\t\t\t\t\theaders: mapHeaderType(res.headers),\n\t\t\t\t});\n\t\t\t}),\n\t\t];\n\t}\n\n\tpublic mswServer() {\n\t\treturn this._mswServer;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,MAAa,uBAAuB;AACpC,MAAa,wBAAwB;;;ACDrC,MAAa,eAAe,YAAqB;CAChD,MAAM,eAAe;EAAC;EAAU;EAAQ;EAAiB;CAAc;CACvE,MAAM,SAAiC,CAAC;CAExC,KAAK,MAAM,CAAC,KAAK,UAAU,QAAQ,QAAQ,GAC1C,IAAI,aAAa,SAAS,IAAI,YAAY,CAAC,GAC1C,OAAO,OAAO;CAIhB,OAAO;AACR;;;ACRA,MAAM,iBAAiB;AACvB,MAAM,sBAAsB;AAO5B,MAAa,gBAAgB,kBAC5B,OAAO,KAAK,aAAa,CAAC,CAAC,SAAS,QAAQ;AAE7C,MAAa,4BAA4B,UAAoB,cAC5D,OAAO,KACN,GAAG,SAAS,GAAG,GAAG,eAAe,GAAG,UAAU,QAAQ,GACvD,CAAC,CAAC,SAAS,QAAQ;AAEpB,MAAa,0BAA0B,aACtC,OAAO,KAAK,GAAG,SAAS,GAAG,GAAG,oBAAoB,GAAGA,GAAO,GAAG,CAAC,CAAC,SAChE,QACD;AAED,MAAa,8BAA8B,UAAkB;CAE5D,MAAM,CAAC,YAAY,QAAQ,QADb,OAAO,KAAK,OAAO,QAAQ,CAAC,CAAC,SAAS,OAAO,CAAC,CAAC,MAAM,GAC5B;CAEvC,IAAI,WAAW,gBACd;CAID,IAAI,OAAO,SAAS,MAAM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AAQ,CAAC;AAEpE,MAAa,sBAAsB,EAAE,KAAK;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;AAED,MAAa,sBAAsB,EAAE,KAAK,CACzC,8BACA,QACD,CAAC;AAED,MAAa,0CAA0C,EAAE,KAAK;CAC7D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;AAED,MAAa,yCAAyC,EAAE,KAAK;CAC5D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;AAED,MAAa,wCAAwC,EAAE,KAAK,CAC3D,YACA,YACD,CAAC;AAED,MAAa,kBAAkB,EAAE,KAAK;CACrC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;AAED,MAAa,uBAAuB,EAAE,KAAK;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;AAED,MAAa,0BAA0B,EAAE,KAAK,CAAC,cAAc,WAAW,CAAC;AAEzE,MAAa,oBAAoB,EAAE,OAAO;AAE1C,MAAa,qBAAqB,EAAE,OAAO;AAE3C,MAAa,eAAe,EAAE,OAAO;AAErC,MAAa,+BAA+B,EAC1C,OAAO;CACP,QAAQ;CACR,IAAI,EAAE,OAAO,CAAC,CAAC,QAAQ;CACvB,KAAK,EAAE,OAAO,CAAC,CAAC,QAAQ;AAC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