@labdigital/commercetools-mock 2.41.0 → 2.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -36,7 +36,7 @@ __export(src_exports, {
36
36
  module.exports = __toCommonJS(src_exports);
37
37
 
38
38
  // src/ctMock.ts
39
- var import_express7 = __toESM(require("express"), 1);
39
+ var import_express10 = __toESM(require("express"), 1);
40
40
  var import_light_my_request = __toESM(require("light-my-request"), 1);
41
41
  var import_morgan = __toESM(require("morgan"), 1);
42
42
  var import_msw = require("msw");
@@ -1972,6 +1972,9 @@ var ProductTailoringUpdateHandler = class extends AbstractUpdateHandler {
1972
1972
  }
1973
1973
  };
1974
1974
 
1975
+ // src/repositories/cart/index.ts
1976
+ var import_uuid6 = require("uuid");
1977
+
1975
1978
  // src/repositories/helpers.ts
1976
1979
  var import_decimal = require("decimal.js/decimal");
1977
1980
  var import_uuid4 = require("uuid");
@@ -2201,248 +2204,6 @@ var getBusinessUnitKeyReference = (id, projectKey, storage) => {
2201
2204
  };
2202
2205
  };
2203
2206
 
2204
- // src/repositories/associate-role.ts
2205
- var AssociateRoleRepository = class extends AbstractResourceRepository {
2206
- constructor(storage) {
2207
- super("associate-role", storage);
2208
- this.actions = new AssociateRoleUpdateHandler(this._storage);
2209
- }
2210
- create(context, draft) {
2211
- const resource = {
2212
- ...getBaseResourceProperties(),
2213
- key: draft.key,
2214
- name: draft.name,
2215
- buyerAssignable: draft.buyerAssignable || false,
2216
- permissions: draft.permissions || [],
2217
- custom: createCustomFields(
2218
- draft.custom,
2219
- context.projectKey,
2220
- this._storage
2221
- )
2222
- };
2223
- return this.saveNew(context, resource);
2224
- }
2225
- };
2226
- var AssociateRoleUpdateHandler = class extends AbstractUpdateHandler {
2227
- addPermission(context, resource, { permission }) {
2228
- if (!resource.permissions) {
2229
- resource.permissions = [permission];
2230
- } else {
2231
- resource.permissions.push(permission);
2232
- }
2233
- }
2234
- changeBuyerAssignable(context, resource, { buyerAssignable }) {
2235
- resource.buyerAssignable = buyerAssignable;
2236
- }
2237
- removePermission(context, resource, { permission }) {
2238
- if (!resource.permissions) {
2239
- return;
2240
- }
2241
- resource.permissions = resource.permissions.filter((p) => {
2242
- p !== permission;
2243
- });
2244
- }
2245
- setBuyerAssignable(context, resource, { buyerAssignable }) {
2246
- resource.buyerAssignable = buyerAssignable;
2247
- }
2248
- setCustomFields(context, resource, { name, value }) {
2249
- if (!resource.custom) {
2250
- return;
2251
- }
2252
- if (value === null) {
2253
- delete resource.custom.fields[name];
2254
- } else {
2255
- resource.custom.fields[name] = value;
2256
- }
2257
- }
2258
- setName(context, resource, { name }) {
2259
- resource.name = name;
2260
- }
2261
- setPermissions(context, resource, { permissions }) {
2262
- resource.permissions = permissions || [];
2263
- }
2264
- };
2265
-
2266
- // src/repositories/attribute-group.ts
2267
- var AttributeGroupRepository = class extends AbstractResourceRepository {
2268
- constructor(storage) {
2269
- super("attribute-group", storage);
2270
- this.actions = new AttributeGroupUpdateHandler(this._storage);
2271
- }
2272
- create(context, draft) {
2273
- const resource = {
2274
- ...getBaseResourceProperties(),
2275
- name: draft.name,
2276
- description: draft.description,
2277
- key: draft.key,
2278
- attributes: draft.attributes
2279
- };
2280
- return this.saveNew(context, resource);
2281
- }
2282
- };
2283
- var AttributeGroupUpdateHandler = class extends AbstractUpdateHandler {
2284
- changeName(_context, resource, { name }) {
2285
- resource.name = name;
2286
- }
2287
- setAttributes(_context, resource, { attributes }) {
2288
- resource.attributes = attributes;
2289
- }
2290
- setDescription(_context, resource, { description }) {
2291
- resource.description = description;
2292
- }
2293
- setKey(_context, resource, { key }) {
2294
- resource.key = key;
2295
- }
2296
- };
2297
-
2298
- // src/repositories/business-unit.ts
2299
- var BusinessUnitRepository = class extends AbstractResourceRepository {
2300
- constructor(storage) {
2301
- super("business-unit", storage);
2302
- this.actions = new BusinessUnitUpdateHandler(this._storage);
2303
- }
2304
- create(context, draft) {
2305
- const addresses = draft.addresses?.map((address) => ({
2306
- ...address,
2307
- id: generateRandomString(5)
2308
- })) ?? [];
2309
- const defaultBillingAddressId = addresses.length > 0 && draft.defaultBillingAddress !== void 0 ? addresses[draft.defaultBillingAddress].id : void 0;
2310
- const defaultShippingAddressId = addresses.length > 0 && draft.defaultShippingAddress !== void 0 ? addresses[draft.defaultShippingAddress].id : void 0;
2311
- const shippingAddressIds = draft.shippingAddresses?.map(
2312
- (i) => addresses[i].id
2313
- );
2314
- const billingAddressIds = draft.billingAddresses?.map(
2315
- (i) => addresses[i].id
2316
- );
2317
- const resource = {
2318
- ...getBaseResourceProperties(),
2319
- key: draft.key,
2320
- status: draft.status,
2321
- stores: draft.stores?.map(
2322
- (s) => getStoreKeyReference(s, context.projectKey, this._storage)
2323
- ),
2324
- storeMode: draft.storeMode,
2325
- name: draft.name,
2326
- contactEmail: draft.contactEmail,
2327
- addresses,
2328
- custom: createCustomFields(
2329
- draft.custom,
2330
- context.projectKey,
2331
- this._storage
2332
- ),
2333
- shippingAddressIds,
2334
- billingAddressIds,
2335
- defaultShippingAddressId,
2336
- defaultBillingAddressId,
2337
- associateMode: draft.associateMode,
2338
- approvalRuleMode: draft.approvalRuleMode,
2339
- associates: draft.associates?.map(
2340
- (a) => createAssociate(a, context.projectKey, this._storage)
2341
- )
2342
- };
2343
- if (this._isDivisionDraft(draft)) {
2344
- const division = {
2345
- ...resource,
2346
- parentUnit: getBusinessUnitKeyReference(
2347
- draft.parentUnit,
2348
- context.projectKey,
2349
- this._storage
2350
- )
2351
- };
2352
- this.saveNew(context, division);
2353
- return division;
2354
- } else if (this._isCompanyDraft(draft)) {
2355
- const company = resource;
2356
- this.saveNew(context, company);
2357
- return company;
2358
- }
2359
- throw new Error("Invalid business unit type");
2360
- }
2361
- _isCompanyDraft(draft) {
2362
- return draft.unitType === "Company";
2363
- }
2364
- _isDivisionDraft(draft) {
2365
- return draft.unitType === "Division";
2366
- }
2367
- };
2368
- var BusinessUnitUpdateHandler = class extends AbstractUpdateHandler {
2369
- addAddress(context, resource, { address }) {
2370
- const newAddress = createAddress(
2371
- address,
2372
- context.projectKey,
2373
- this._storage
2374
- );
2375
- if (newAddress) {
2376
- resource.addresses.push(newAddress);
2377
- }
2378
- }
2379
- addAssociate(context, resource, { associate }) {
2380
- const newAssociate = createAssociate(
2381
- associate,
2382
- context.projectKey,
2383
- this._storage
2384
- );
2385
- if (newAssociate) {
2386
- resource.associates.push(newAssociate);
2387
- }
2388
- }
2389
- addStore(context, resource, { store }) {
2390
- const newStore = getStoreKeyReference(
2391
- store,
2392
- context.projectKey,
2393
- this._storage
2394
- );
2395
- if (newStore) {
2396
- if (!resource.stores) {
2397
- resource.stores = [];
2398
- }
2399
- resource.stores.push(newStore);
2400
- }
2401
- }
2402
- changeAddress(context, resource, { address }) {
2403
- const newAddress = createAddress(
2404
- address,
2405
- context.projectKey,
2406
- this._storage
2407
- );
2408
- if (newAddress) {
2409
- resource.addresses.push(newAddress);
2410
- }
2411
- }
2412
- changeApprovalRuleMode(context, resource, { approvalRuleMode }) {
2413
- resource.approvalRuleMode = approvalRuleMode;
2414
- }
2415
- changeAssociateMode(context, resource, { associateMode }) {
2416
- resource.associateMode = associateMode;
2417
- }
2418
- changeName(context, resource, { name }) {
2419
- resource.name = name;
2420
- }
2421
- changeParentUnit(context, resource, { parentUnit }) {
2422
- resource.parentUnit = getBusinessUnitKeyReference(
2423
- parentUnit,
2424
- context.projectKey,
2425
- this._storage
2426
- );
2427
- }
2428
- changeStatus(context, resource, { status }) {
2429
- resource.status = status;
2430
- }
2431
- setAssociates(context, resource, { associates }) {
2432
- const newAssociates = associates.map((a) => createAssociate(a, context.projectKey, this._storage)).filter((a) => a !== void 0);
2433
- resource.associates = newAssociates || void 0;
2434
- }
2435
- setContactEmail(context, resource, { contactEmail }) {
2436
- resource.contactEmail = contactEmail;
2437
- }
2438
- setStoreMode(context, resource, { storeMode }) {
2439
- resource.storeMode = storeMode;
2440
- }
2441
- };
2442
-
2443
- // src/repositories/cart/index.ts
2444
- var import_uuid6 = require("uuid");
2445
-
2446
2207
  // src/repositories/cart/actions.ts
2447
2208
  var import_decimal2 = require("decimal.js/decimal");
2448
2209
  var import_uuid5 = require("uuid");
@@ -3151,36 +2912,87 @@ var CartRepository = class extends AbstractResourceRepository {
3151
2912
  };
3152
2913
  };
3153
2914
 
3154
- // src/repositories/cart-discount/actions.ts
3155
- var CartDiscountUpdateHandler = class extends AbstractUpdateHandler {
3156
- changeIsActive(context, resource, { isActive }) {
3157
- resource.isActive = isActive;
3158
- }
3159
- changeSortOrder(context, resource, { sortOrder }) {
3160
- resource.sortOrder = sortOrder;
3161
- }
3162
- changeTarget(context, resource, { target }) {
3163
- resource.target = target;
3164
- }
2915
+ // src/repositories/order/index.ts
2916
+ var import_assert2 = __toESM(require("assert"), 1);
2917
+
2918
+ // src/repositories/order/actions.ts
2919
+ var OrderUpdateHandler = class extends AbstractUpdateHandler {
2920
+ addPayment(context, resource, { payment }) {
2921
+ const resolvedPayment = this._storage.getByResourceIdentifier(
2922
+ context.projectKey,
2923
+ payment
2924
+ );
2925
+ if (!resolvedPayment) {
2926
+ throw new Error(`Payment ${payment.id} not found`);
2927
+ }
2928
+ if (!resource.paymentInfo) {
2929
+ resource.paymentInfo = {
2930
+ payments: []
2931
+ };
2932
+ }
2933
+ resource.paymentInfo.payments.push({
2934
+ typeId: "payment",
2935
+ id: payment.id
2936
+ });
2937
+ }
2938
+ addReturnInfo(context, resource, info) {
2939
+ if (!resource.returnInfo) {
2940
+ resource.returnInfo = [];
2941
+ }
2942
+ const resolved = {
2943
+ items: info.items.map((item) => {
2944
+ const common = {
2945
+ ...getBaseResourceProperties(),
2946
+ quantity: item.quantity,
2947
+ paymentState: "Initial",
2948
+ shipmentState: "Initial",
2949
+ comment: item.comment
2950
+ };
2951
+ if (item.customLineItemId) {
2952
+ return {
2953
+ ...common,
2954
+ type: "CustomLineItemReturnItem",
2955
+ customLineItemId: item.customLineItemId
2956
+ };
2957
+ }
2958
+ return {
2959
+ ...common,
2960
+ type: "LineItemReturnItem",
2961
+ lineItemId: item.customLineItemId || item.lineItemId
2962
+ };
2963
+ }),
2964
+ returnTrackingId: info.returnTrackingId,
2965
+ returnDate: info.returnDate
2966
+ };
2967
+ resource.returnInfo.push(resolved);
2968
+ }
2969
+ changeOrderState(context, resource, { orderState }) {
2970
+ resource.orderState = orderState;
2971
+ }
2972
+ changePaymentState(context, resource, { paymentState }) {
2973
+ resource.paymentState = paymentState;
2974
+ }
2975
+ changeShipmentState(context, resource, { shipmentState }) {
2976
+ resource.shipmentState = shipmentState;
2977
+ }
2978
+ setBillingAddress(context, resource, { address }) {
2979
+ resource.billingAddress = createAddress(
2980
+ address,
2981
+ context.projectKey,
2982
+ this._storage
2983
+ );
2984
+ }
2985
+ setCustomerEmail(context, resource, { email }) {
2986
+ resource.customerEmail = email;
2987
+ }
2988
+ setCustomerId(context, resource, { customerId }) {
2989
+ resource.customerId = customerId;
2990
+ }
3165
2991
  setCustomField(context, resource, { name, value }) {
3166
2992
  if (!resource.custom) {
3167
- return;
3168
- }
3169
- if (value === null) {
3170
- if (name in resource.custom.fields) {
3171
- delete resource.custom.fields[name];
3172
- } else {
3173
- throw new CommercetoolsError(
3174
- {
3175
- code: "InvalidOperation",
3176
- message: "Cannot remove custom field " + name + " because it does not exist."
3177
- },
3178
- 400
3179
- );
3180
- }
3181
- } else {
3182
- resource.custom.fields[name] = value;
2993
+ throw new Error("Resource has no custom field");
3183
2994
  }
2995
+ resource.custom.fields[name] = value;
3184
2996
  }
3185
2997
  setCustomType(context, resource, { type, fields }) {
3186
2998
  if (!type) {
@@ -3202,292 +3014,324 @@ var CartDiscountUpdateHandler = class extends AbstractUpdateHandler {
3202
3014
  };
3203
3015
  }
3204
3016
  }
3205
- setDescription(context, resource, { description }) {
3206
- resource.description = description;
3017
+ setDeliveryCustomField(context, resource, { deliveryId, name, value }) {
3018
+ if (!resource.shippingInfo) {
3019
+ throw new Error("Resource has no shipping info");
3020
+ }
3021
+ for (const delivery of resource.shippingInfo.deliveries || []) {
3022
+ if (delivery.id === deliveryId && delivery.custom?.fields) {
3023
+ delivery.custom.fields[name] = value;
3024
+ }
3025
+ }
3207
3026
  }
3208
- setKey(context, resource, { key }) {
3209
- resource.key = key;
3027
+ setLocale(context, resource, { locale }) {
3028
+ resource.locale = locale;
3210
3029
  }
3211
- setStores(context, resource, { stores }) {
3212
- resource.stores = stores?.map(
3213
- (s) => getStoreKeyReference(s, context.projectKey, this._storage)
3214
- );
3030
+ setOrderNumber(context, resource, { orderNumber }) {
3031
+ resource.orderNumber = orderNumber;
3215
3032
  }
3216
- setValidFrom(context, resource, { validFrom }) {
3217
- resource.validFrom = validFrom;
3033
+ setParcelCustomField(context, resource, { parcelId, name, value }) {
3034
+ if (!resource.shippingInfo) {
3035
+ throw new Error("Resource has no shipping info");
3036
+ }
3037
+ for (const delivery of resource.shippingInfo.deliveries || []) {
3038
+ for (const parcel of delivery.parcels || []) {
3039
+ if (parcel.id === parcelId && parcel.custom?.fields) {
3040
+ parcel.custom.fields[name] = value;
3041
+ }
3042
+ }
3043
+ }
3218
3044
  }
3219
- setValidFromAndUntil(context, resource, { validFrom, validUntil }) {
3220
- resource.validFrom = validFrom;
3221
- resource.validUntil = validUntil;
3045
+ setPurchaseOrderNumber(context, resource, { purchaseOrderNumber }) {
3046
+ resource.purchaseOrderNumber = purchaseOrderNumber;
3222
3047
  }
3223
- setValidUntil(context, resource, { validUntil }) {
3224
- resource.validUntil = validUntil;
3048
+ setShippingAddress(context, resource, { address }) {
3049
+ resource.shippingAddress = createAddress(
3050
+ address,
3051
+ context.projectKey,
3052
+ this._storage
3053
+ );
3225
3054
  }
3226
- };
3227
-
3228
- // src/repositories/cart-discount/index.ts
3229
- var CartDiscountRepository = class extends AbstractResourceRepository {
3230
- constructor(storage) {
3231
- super("cart-discount", storage);
3232
- this.actions = new CartDiscountUpdateHandler(storage);
3055
+ setStore(context, resource, { store }) {
3056
+ if (!store) return;
3057
+ const resolvedType = this._storage.getByResourceIdentifier(
3058
+ context.projectKey,
3059
+ store
3060
+ );
3061
+ if (!resolvedType) {
3062
+ throw new Error(`No store found with key=${store.key}`);
3063
+ }
3064
+ const storeReference = resolvedType;
3065
+ resource.store = {
3066
+ typeId: "store",
3067
+ key: storeReference.key
3068
+ };
3233
3069
  }
3234
- create(context, draft) {
3235
- const resource = {
3236
- ...getBaseResourceProperties(),
3237
- key: draft.key,
3238
- description: draft.description,
3239
- cartPredicate: draft.cartPredicate,
3240
- isActive: draft.isActive || false,
3241
- name: draft.name,
3242
- stores: draft.stores?.map(
3243
- (s) => getStoreKeyReference(s, context.projectKey, this._storage)
3244
- ) ?? [],
3245
- references: [],
3246
- target: draft.target,
3247
- requiresDiscountCode: draft.requiresDiscountCode || false,
3248
- sortOrder: draft.sortOrder,
3249
- stackingMode: draft.stackingMode || "Stacking",
3250
- validFrom: draft.validFrom,
3251
- validUntil: draft.validUntil,
3252
- value: this.transformValueDraft(draft.value),
3253
- custom: createCustomFields(
3254
- draft.custom,
3255
- context.projectKey,
3256
- this._storage
3257
- )
3070
+ transitionState(context, resource, { state }) {
3071
+ const resolvedType = this._storage.getByResourceIdentifier(
3072
+ context.projectKey,
3073
+ state
3074
+ );
3075
+ if (!resolvedType) {
3076
+ throw new Error(
3077
+ `No state found with key=${state.key} or id=${state.key}`
3078
+ );
3079
+ }
3080
+ resource.state = {
3081
+ typeId: "state",
3082
+ id: resolvedType.id,
3083
+ obj: { ...resolvedType, key: state.key ?? "" }
3258
3084
  };
3259
- return this.saveNew(context, resource);
3260
3085
  }
3261
- transformValueDraft(value) {
3262
- switch (value.type) {
3263
- case "absolute": {
3264
- return {
3265
- type: "absolute",
3266
- money: value.money.map(createTypedMoney)
3267
- };
3268
- }
3269
- case "fixed": {
3270
- return {
3271
- type: "fixed",
3272
- money: value.money.map(createTypedMoney)
3273
- };
3274
- }
3275
- case "giftLineItem": {
3276
- return {
3277
- ...value
3278
- };
3279
- }
3280
- case "relative": {
3281
- return {
3282
- ...value
3283
- };
3086
+ updateSyncInfo(context, resource, { channel, externalId, syncedAt }) {
3087
+ if (!channel) return;
3088
+ const resolvedType = this._storage.getByResourceIdentifier(
3089
+ context.projectKey,
3090
+ channel
3091
+ );
3092
+ if (!resolvedType) {
3093
+ throw new Error(`Channel ${channel} not found`);
3094
+ }
3095
+ const syncData = {
3096
+ channel: {
3097
+ typeId: "channel",
3098
+ id: resolvedType.id
3099
+ },
3100
+ externalId,
3101
+ syncedAt: syncedAt ?? (/* @__PURE__ */ new Date()).toISOString()
3102
+ };
3103
+ if (!resource.syncInfo?.length) {
3104
+ resource.syncInfo = [syncData];
3105
+ } else {
3106
+ const lastSyncInfo = resource.syncInfo[resource.syncInfo.length - 1];
3107
+ if (lastSyncInfo.channel.id !== syncData.channel.id || lastSyncInfo.externalId !== syncData.externalId) {
3108
+ resource.syncInfo.push(syncData);
3284
3109
  }
3285
3110
  }
3286
- return value;
3287
3111
  }
3288
3112
  };
3289
3113
 
3290
- // src/repositories/category/index.ts
3291
- var import_uuid8 = require("uuid");
3292
-
3293
- // src/repositories/category/actions.ts
3294
- var import_uuid7 = require("uuid");
3295
- var CategoryUpdateHandler = class extends AbstractUpdateHandler {
3296
- addAsset(context, resource, { asset }) {
3297
- if (!resource.assets) {
3298
- resource.assets = [this.assetFromAssetDraft(asset, context)];
3299
- } else {
3300
- resource.assets.push(this.assetFromAssetDraft(asset, context));
3301
- }
3302
- }
3303
- changeAssetName(context, resource, { assetId, assetKey, name }) {
3304
- resource.assets?.forEach((asset) => {
3305
- if (assetId && assetId === asset.id) {
3306
- asset.name = name;
3307
- }
3308
- if (assetKey && assetKey === asset.key) {
3309
- asset.name = name;
3310
- }
3311
- });
3114
+ // src/repositories/order/index.ts
3115
+ var OrderRepository = class extends AbstractResourceRepository {
3116
+ constructor(storage) {
3117
+ super("order", storage);
3118
+ this.actions = new OrderUpdateHandler(storage);
3312
3119
  }
3313
- changeName(context, resource, { name }) {
3314
- resource.name = name;
3120
+ create(context, draft) {
3121
+ (0, import_assert2.default)(draft.cart, "draft.cart is missing");
3122
+ return this.createFromCart(
3123
+ context,
3124
+ {
3125
+ id: draft.cart.id,
3126
+ typeId: "cart"
3127
+ },
3128
+ draft.orderNumber
3129
+ );
3315
3130
  }
3316
- changeParent(context, resource, { parent }) {
3317
- const category = this._storage.getByResourceIdentifier(
3131
+ createFromCart(context, cartReference, orderNumber) {
3132
+ const cart = this._storage.getByResourceIdentifier(
3318
3133
  context.projectKey,
3319
- parent
3134
+ cartReference
3320
3135
  );
3321
- if (!category) {
3322
- throw new Error("No category found for reference");
3136
+ if (!cart) {
3137
+ throw new Error("Cannot find cart");
3323
3138
  }
3324
- resource.parent = {
3325
- typeId: "category",
3326
- id: category.id
3139
+ const resource = {
3140
+ ...getBaseResourceProperties(),
3141
+ anonymousId: cart.anonymousId,
3142
+ billingAddress: cart.billingAddress,
3143
+ cart: cartReference,
3144
+ country: cart.country,
3145
+ custom: cart.custom,
3146
+ customerEmail: cart.customerEmail,
3147
+ customerGroup: cart.customerGroup,
3148
+ customerId: cart.customerId,
3149
+ customLineItems: [],
3150
+ directDiscounts: cart.directDiscounts,
3151
+ discountCodes: cart.discountCodes,
3152
+ discountOnTotalPrice: cart.discountOnTotalPrice,
3153
+ lastMessageSequenceNumber: 0,
3154
+ lineItems: cart.lineItems,
3155
+ locale: cart.locale,
3156
+ orderNumber: orderNumber ?? generateRandomString(10),
3157
+ orderState: "Open",
3158
+ origin: "Customer",
3159
+ paymentInfo: cart.paymentInfo,
3160
+ refusedGifts: [],
3161
+ shipping: cart.shipping,
3162
+ shippingAddress: cart.shippingAddress,
3163
+ shippingMode: cart.shippingMode,
3164
+ syncInfo: [],
3165
+ taxCalculationMode: cart.taxCalculationMode,
3166
+ taxedPrice: cart.taxedPrice,
3167
+ taxedShippingPrice: cart.taxedShippingPrice,
3168
+ taxMode: cart.taxMode,
3169
+ taxRoundingMode: cart.taxRoundingMode,
3170
+ totalPrice: cart.totalPrice,
3171
+ store: cart.store
3327
3172
  };
3173
+ return this.saveNew(context, resource);
3328
3174
  }
3329
- changeSlug(context, resource, { slug }) {
3330
- resource.slug = slug;
3175
+ import(context, draft) {
3176
+ (0, import_assert2.default)(this, "OrderRepository not valid");
3177
+ const resource = {
3178
+ ...getBaseResourceProperties(),
3179
+ billingAddress: createAddress(
3180
+ draft.billingAddress,
3181
+ context.projectKey,
3182
+ this._storage
3183
+ ),
3184
+ shippingAddress: createAddress(
3185
+ draft.shippingAddress,
3186
+ context.projectKey,
3187
+ this._storage
3188
+ ),
3189
+ custom: createCustomFields(
3190
+ draft.custom,
3191
+ context.projectKey,
3192
+ this._storage
3193
+ ),
3194
+ customerEmail: draft.customerEmail,
3195
+ lastMessageSequenceNumber: 0,
3196
+ orderNumber: draft.orderNumber,
3197
+ orderState: draft.orderState || "Open",
3198
+ origin: draft.origin || "Customer",
3199
+ paymentState: draft.paymentState,
3200
+ refusedGifts: [],
3201
+ shippingMode: "Single",
3202
+ shipping: [],
3203
+ store: resolveStoreReference(
3204
+ draft.store,
3205
+ context.projectKey,
3206
+ this._storage
3207
+ ),
3208
+ syncInfo: [],
3209
+ lineItems: draft.lineItems?.map(
3210
+ (item) => this.lineItemFromImportDraft.bind(this)(context, item)
3211
+ ) || [],
3212
+ customLineItems: draft.customLineItems?.map(
3213
+ (item) => this.customLineItemFromImportDraft.bind(this)(context, item)
3214
+ ) || [],
3215
+ totalPrice: createCentPrecisionMoney(draft.totalPrice)
3216
+ };
3217
+ return this.saveNew(context, resource);
3331
3218
  }
3332
- removeAsset(context, resource, { assetId, assetKey }) {
3333
- if (!resource.assets) {
3334
- return;
3335
- }
3336
- if (assetId) {
3337
- resource.assets = resource.assets.filter(function(obj) {
3338
- return obj.id !== assetId;
3339
- });
3340
- return;
3341
- }
3342
- if (assetKey) {
3343
- resource.assets = resource.assets.filter(function(obj) {
3344
- return obj.key !== assetKey;
3219
+ lineItemFromImportDraft(context, draft) {
3220
+ let product;
3221
+ let variant;
3222
+ if (draft.variant.sku) {
3223
+ variant = {
3224
+ id: 0,
3225
+ sku: draft.variant.sku
3226
+ };
3227
+ const items = this._storage.query(context.projectKey, "product", {
3228
+ where: [
3229
+ `masterData(current(masterVariant(sku="${draft.variant.sku}"))) or masterData(current(variants(sku="${draft.variant.sku}")))`
3230
+ ]
3345
3231
  });
3346
- return;
3347
- }
3348
- }
3349
- setAssetDescription(context, resource, { assetId, assetKey, description }) {
3350
- resource.assets?.forEach((asset) => {
3351
- if (assetId && assetId === asset.id) {
3352
- asset.description = description;
3353
- }
3354
- if (assetKey && assetKey === asset.key) {
3355
- asset.description = description;
3232
+ if (items.count !== 1) {
3233
+ throw new CommercetoolsError({
3234
+ code: "General",
3235
+ message: `A product containing a variant with SKU '${draft.variant.sku}' not found.`
3236
+ });
3356
3237
  }
3357
- });
3358
- }
3359
- setAssetSources(context, resource, { assetId, assetKey, sources }) {
3360
- resource.assets?.forEach((asset) => {
3361
- if (assetId && assetId === asset.id) {
3362
- asset.sources = sources;
3238
+ product = items.results[0];
3239
+ if (product.masterData.current.masterVariant.sku === draft.variant.sku) {
3240
+ variant = product.masterData.current.masterVariant;
3241
+ } else {
3242
+ variant = product.masterData.current.variants.find(
3243
+ (v) => v.sku === draft.variant.sku
3244
+ );
3363
3245
  }
3364
- if (assetKey && assetKey === asset.key) {
3365
- asset.sources = sources;
3246
+ if (!variant) {
3247
+ throw new Error("Internal state error");
3366
3248
  }
3367
- });
3368
- }
3369
- setCustomField(context, resource, { name, value }) {
3370
- if (!resource.custom) {
3371
- return;
3372
- }
3373
- if (value === null) {
3374
- delete resource.custom.fields[name];
3375
3249
  } else {
3376
- resource.custom.fields[name] = value;
3250
+ throw new Error("No product found");
3377
3251
  }
3252
+ const lineItem = {
3253
+ ...getBaseResourceProperties(),
3254
+ custom: createCustomFields(
3255
+ draft.custom,
3256
+ context.projectKey,
3257
+ this._storage
3258
+ ),
3259
+ discountedPricePerQuantity: [],
3260
+ lineItemMode: "Standard",
3261
+ name: draft.name,
3262
+ price: createPrice(draft.price),
3263
+ priceMode: "Platform",
3264
+ productId: product.id,
3265
+ productType: product.productType,
3266
+ quantity: draft.quantity,
3267
+ state: draft.state || [],
3268
+ taxRate: draft.taxRate,
3269
+ taxedPricePortions: [],
3270
+ perMethodTaxRate: [],
3271
+ totalPrice: createCentPrecisionMoney(draft.price.value),
3272
+ variant: {
3273
+ id: variant.id,
3274
+ sku: variant.sku,
3275
+ price: createPrice(draft.price)
3276
+ }
3277
+ };
3278
+ return lineItem;
3378
3279
  }
3379
- setCustomType(context, resource, { type, fields }) {
3380
- if (type) {
3381
- resource.custom = createCustomFields(
3382
- { type, fields },
3280
+ customLineItemFromImportDraft(context, draft) {
3281
+ const lineItem = {
3282
+ ...getBaseResourceProperties(),
3283
+ custom: createCustomFields(
3284
+ draft.custom,
3383
3285
  context.projectKey,
3384
3286
  this._storage
3385
- );
3386
- } else {
3387
- resource.custom = void 0;
3287
+ ),
3288
+ discountedPricePerQuantity: [],
3289
+ money: createTypedMoney(draft.money),
3290
+ name: draft.name,
3291
+ quantity: draft.quantity ?? 0,
3292
+ perMethodTaxRate: [],
3293
+ priceMode: draft.priceMode ?? "Standard",
3294
+ slug: draft.slug,
3295
+ state: [],
3296
+ totalPrice: createCentPrecisionMoney(draft.money),
3297
+ taxedPricePortions: []
3298
+ };
3299
+ return lineItem;
3300
+ }
3301
+ getWithOrderNumber(context, orderNumber, params = {}) {
3302
+ const result = this._storage.query(context.projectKey, this.getTypeId(), {
3303
+ ...params,
3304
+ where: [`orderNumber="${orderNumber}"`]
3305
+ });
3306
+ if (result.count === 1) {
3307
+ return result.results[0];
3308
+ }
3309
+ if (result.count > 1) {
3310
+ throw new Error("Duplicate order numbers");
3388
3311
  }
3312
+ return;
3389
3313
  }
3390
- setDescription(context, resource, { description }) {
3391
- resource.description = description;
3392
- }
3393
- setKey(context, resource, { key }) {
3394
- resource.key = key;
3395
- }
3396
- setMetaDescription(context, resource, { metaDescription }) {
3397
- resource.metaDescription = metaDescription;
3398
- }
3399
- setMetaKeywords(context, resource, { metaKeywords }) {
3400
- resource.metaKeywords = metaKeywords;
3401
- }
3402
- setMetaTitle(context, resource, { metaTitle }) {
3403
- resource.metaTitle = metaTitle;
3404
- }
3405
- assetFromAssetDraft = (draft, context) => ({
3406
- ...draft,
3407
- id: (0, import_uuid7.v4)(),
3408
- custom: createCustomFields(draft.custom, context.projectKey, this._storage)
3409
- });
3410
3314
  };
3411
3315
 
3412
- // src/repositories/category/index.ts
3413
- var CategoryRepository = class extends AbstractResourceRepository {
3414
- constructor(storage) {
3415
- super("category", storage);
3416
- this.actions = new CategoryUpdateHandler(this._storage);
3417
- }
3418
- create(context, draft) {
3419
- const resource = {
3420
- ...getBaseResourceProperties(),
3421
- key: draft.key,
3422
- name: draft.name,
3423
- slug: draft.slug,
3424
- description: draft.description,
3425
- metaDescription: draft.metaDescription,
3426
- metaKeywords: draft.metaKeywords,
3427
- orderHint: draft.orderHint || "",
3428
- externalId: draft.externalId || "",
3429
- parent: draft.parent ? { typeId: "category", id: draft.parent.id } : void 0,
3430
- ancestors: [],
3431
- // Resolved at runtime
3432
- assets: draft.assets?.map((d) => ({
3433
- id: (0, import_uuid8.v4)(),
3434
- name: d.name,
3435
- description: d.description,
3436
- sources: d.sources,
3437
- tags: d.tags,
3438
- key: d.key,
3439
- custom: createCustomFields(
3440
- draft.custom,
3441
- context.projectKey,
3442
- this._storage
3443
- )
3444
- })) || [],
3445
- custom: createCustomFields(
3446
- draft.custom,
3447
- context.projectKey,
3448
- this._storage
3449
- )
3450
- };
3451
- return this.saveNew(context, resource);
3452
- }
3453
- postProcessResource(context, resource, params) {
3454
- let node = resource;
3455
- const ancestors = [];
3456
- const expandClauses = params?.expand?.map(parseExpandClause) ?? [];
3457
- const addExpand = expandClauses?.find(
3458
- (c) => c.element === "ancestors" && c.index === "*"
3459
- );
3460
- while (node.parent) {
3461
- node = this._storage.getByResourceIdentifier(
3462
- context.projectKey,
3463
- node.parent
3464
- );
3465
- ancestors.push({
3466
- typeId: "category",
3467
- id: node.id,
3468
- obj: addExpand ? node : void 0
3469
- });
3470
- }
3471
- resource.ancestors = ancestors;
3472
- return resource;
3473
- }
3316
+ // src/repositories/as-associate.ts
3317
+ var AsAssociateOrderRepository = class extends OrderRepository {
3318
+ };
3319
+ var AsAssociateCartRepository = class extends CartRepository {
3474
3320
  };
3475
3321
 
3476
- // src/repositories/channel.ts
3477
- var ChannelRepository = class extends AbstractResourceRepository {
3322
+ // src/repositories/associate-role.ts
3323
+ var AssociateRoleRepository = class extends AbstractResourceRepository {
3478
3324
  constructor(storage) {
3479
- super("channel", storage);
3480
- this.actions = new ChannelUpdateHandler(this._storage);
3325
+ super("associate-role", storage);
3326
+ this.actions = new AssociateRoleUpdateHandler(this._storage);
3481
3327
  }
3482
3328
  create(context, draft) {
3483
3329
  const resource = {
3484
3330
  ...getBaseResourceProperties(),
3485
3331
  key: draft.key,
3486
3332
  name: draft.name,
3487
- description: draft.description,
3488
- roles: draft.roles || [],
3489
- geoLocation: draft.geoLocation,
3490
- address: createAddress(draft.address, context.projectKey, this._storage),
3333
+ buyerAssignable: draft.buyerAssignable || false,
3334
+ permissions: draft.permissions || [],
3491
3335
  custom: createCustomFields(
3492
3336
  draft.custom,
3493
3337
  context.projectKey,
@@ -3497,24 +3341,29 @@ var ChannelRepository = class extends AbstractResourceRepository {
3497
3341
  return this.saveNew(context, resource);
3498
3342
  }
3499
3343
  };
3500
- var ChannelUpdateHandler = class extends AbstractUpdateHandler {
3501
- changeDescription(context, resource, { description }) {
3502
- resource.description = description;
3344
+ var AssociateRoleUpdateHandler = class extends AbstractUpdateHandler {
3345
+ addPermission(context, resource, { permission }) {
3346
+ if (!resource.permissions) {
3347
+ resource.permissions = [permission];
3348
+ } else {
3349
+ resource.permissions.push(permission);
3350
+ }
3503
3351
  }
3504
- changeKey(context, resource, { key }) {
3505
- resource.key = key;
3352
+ changeBuyerAssignable(context, resource, { buyerAssignable }) {
3353
+ resource.buyerAssignable = buyerAssignable;
3506
3354
  }
3507
- changeName(context, resource, { name }) {
3508
- resource.name = name;
3355
+ removePermission(context, resource, { permission }) {
3356
+ if (!resource.permissions) {
3357
+ return;
3358
+ }
3359
+ resource.permissions = resource.permissions.filter((p) => {
3360
+ p !== permission;
3361
+ });
3509
3362
  }
3510
- setAddress(context, resource, { address }) {
3511
- resource.address = createAddress(
3512
- address,
3513
- context.projectKey,
3514
- this._storage
3515
- );
3363
+ setBuyerAssignable(context, resource, { buyerAssignable }) {
3364
+ resource.buyerAssignable = buyerAssignable;
3516
3365
  }
3517
- setCustomField(context, resource, { name, value }) {
3366
+ setCustomFields(context, resource, { name, value }) {
3518
3367
  if (!resource.custom) {
3519
3368
  return;
3520
3369
  }
@@ -3524,632 +3373,814 @@ var ChannelUpdateHandler = class extends AbstractUpdateHandler {
3524
3373
  resource.custom.fields[name] = value;
3525
3374
  }
3526
3375
  }
3527
- setCustomType(context, resource, { type, fields }) {
3528
- if (type) {
3529
- resource.custom = createCustomFields(
3530
- { type, fields },
3531
- context.projectKey,
3532
- this._storage
3533
- );
3534
- } else {
3535
- resource.custom = void 0;
3536
- }
3376
+ setName(context, resource, { name }) {
3377
+ resource.name = name;
3537
3378
  }
3538
- setGeoLocation(context, resource, { geoLocation }) {
3539
- resource.geoLocation = geoLocation;
3379
+ setPermissions(context, resource, { permissions }) {
3380
+ resource.permissions = permissions || [];
3540
3381
  }
3541
3382
  };
3542
3383
 
3543
- // src/repositories/custom-object.ts
3544
- var CustomObjectRepository = class extends AbstractResourceRepository {
3384
+ // src/repositories/attribute-group.ts
3385
+ var AttributeGroupRepository = class extends AbstractResourceRepository {
3545
3386
  constructor(storage) {
3546
- super("key-value-document", storage);
3387
+ super("attribute-group", storage);
3388
+ this.actions = new AttributeGroupUpdateHandler(this._storage);
3547
3389
  }
3548
3390
  create(context, draft) {
3549
- const current = this.getWithContainerAndKey(
3550
- context,
3551
- draft.container,
3552
- draft.key
3553
- );
3554
- if (current) {
3555
- if (draft.version) {
3556
- checkConcurrentModification(current.version, draft.version, current.id);
3557
- } else {
3558
- draft.version = current.version;
3559
- }
3560
- if (draft.value !== current.value) {
3561
- const updated = cloneObject(current);
3562
- updated.value = draft.value;
3563
- updated.version += 1;
3564
- this.saveUpdate(context, draft.version, updated);
3565
- return updated;
3566
- }
3567
- return current;
3568
- } else {
3569
- if (draft.version) {
3570
- throw new CommercetoolsError(
3571
- {
3572
- code: "InvalidOperation",
3573
- message: "version on create must be 0"
3574
- },
3575
- 400
3576
- );
3577
- }
3578
- const baseProperties = getBaseResourceProperties();
3579
- const resource = {
3580
- ...baseProperties,
3581
- container: draft.container,
3582
- key: draft.key,
3583
- value: draft.value
3584
- };
3585
- this.saveNew(context, resource);
3586
- return resource;
3587
- }
3391
+ const resource = {
3392
+ ...getBaseResourceProperties(),
3393
+ name: draft.name,
3394
+ description: draft.description,
3395
+ key: draft.key,
3396
+ attributes: draft.attributes
3397
+ };
3398
+ return this.saveNew(context, resource);
3588
3399
  }
3589
- getWithContainerAndKey(context, container, key) {
3590
- const items = this._storage.all(context.projectKey, this.getTypeId());
3591
- return items.find(
3592
- (item) => item.container === container && item.key === key
3593
- );
3400
+ };
3401
+ var AttributeGroupUpdateHandler = class extends AbstractUpdateHandler {
3402
+ changeName(_context, resource, { name }) {
3403
+ resource.name = name;
3594
3404
  }
3595
- queryWithContainer(context, container, params = {}) {
3596
- const whereClause = params.where || [];
3597
- whereClause.push(`container="${container}"`);
3598
- const result = this._storage.query(context.projectKey, this.getTypeId(), {
3599
- ...params,
3600
- where: whereClause
3601
- });
3602
- result.results = result.results.map(
3603
- (r) => this.postProcessResource(context, r, {
3604
- expand: params.expand
3605
- })
3606
- );
3607
- return result;
3405
+ setAttributes(_context, resource, { attributes }) {
3406
+ resource.attributes = attributes;
3407
+ }
3408
+ setDescription(_context, resource, { description }) {
3409
+ resource.description = description;
3410
+ }
3411
+ setKey(_context, resource, { key }) {
3412
+ resource.key = key;
3608
3413
  }
3609
3414
  };
3610
3415
 
3611
- // src/repositories/customer/actions.ts
3612
- var import_node_assert = __toESM(require("assert"), 1);
3613
- var CustomerUpdateHandler = class extends AbstractUpdateHandler {
3614
- addAddress(_context, resource, { address }) {
3615
- resource.addresses.push({
3616
- ...address,
3617
- id: address.id ?? generateRandomString(5)
3618
- });
3619
- }
3620
- addBillingAddressId(_context, resource, { addressId, addressKey }) {
3621
- const address = this._findAddress(resource, addressId, addressKey, true);
3622
- (0, import_node_assert.default)(address?.id);
3623
- if (resource.billingAddressIds === void 0) {
3624
- resource.billingAddressIds = [];
3625
- }
3626
- if (!resource.billingAddressIds.includes(address.id)) {
3627
- resource.billingAddressIds.push(address.id);
3628
- }
3416
+ // src/repositories/business-unit.ts
3417
+ var BusinessUnitRepository = class extends AbstractResourceRepository {
3418
+ constructor(storage) {
3419
+ super("business-unit", storage);
3420
+ this.actions = new BusinessUnitUpdateHandler(this._storage);
3629
3421
  }
3630
- addShippingAddressId(_context, resource, { addressId, addressKey }) {
3631
- const address = this._findAddress(resource, addressId, addressKey, true);
3632
- (0, import_node_assert.default)(address?.id);
3633
- if (resource.shippingAddressIds === void 0) {
3634
- resource.shippingAddressIds = [];
3635
- }
3636
- if (!resource.shippingAddressIds.includes(address.id)) {
3637
- resource.shippingAddressIds.push(address.id);
3422
+ create(context, draft) {
3423
+ const addresses = draft.addresses?.map((address) => ({
3424
+ ...address,
3425
+ id: generateRandomString(5)
3426
+ })) ?? [];
3427
+ const defaultBillingAddressId = addresses.length > 0 && draft.defaultBillingAddress !== void 0 ? addresses[draft.defaultBillingAddress].id : void 0;
3428
+ const defaultShippingAddressId = addresses.length > 0 && draft.defaultShippingAddress !== void 0 ? addresses[draft.defaultShippingAddress].id : void 0;
3429
+ const shippingAddressIds = draft.shippingAddresses?.map(
3430
+ (i) => addresses[i].id
3431
+ );
3432
+ const billingAddressIds = draft.billingAddresses?.map(
3433
+ (i) => addresses[i].id
3434
+ );
3435
+ const resource = {
3436
+ ...getBaseResourceProperties(),
3437
+ key: draft.key,
3438
+ status: draft.status,
3439
+ stores: draft.stores?.map(
3440
+ (s) => getStoreKeyReference(s, context.projectKey, this._storage)
3441
+ ),
3442
+ storeMode: draft.storeMode,
3443
+ name: draft.name,
3444
+ contactEmail: draft.contactEmail,
3445
+ addresses,
3446
+ custom: createCustomFields(
3447
+ draft.custom,
3448
+ context.projectKey,
3449
+ this._storage
3450
+ ),
3451
+ shippingAddressIds,
3452
+ billingAddressIds,
3453
+ defaultShippingAddressId,
3454
+ defaultBillingAddressId,
3455
+ associateMode: draft.associateMode,
3456
+ approvalRuleMode: draft.approvalRuleMode,
3457
+ associates: draft.associates?.map(
3458
+ (a) => createAssociate(a, context.projectKey, this._storage)
3459
+ ) ?? []
3460
+ };
3461
+ if (this._isDivisionDraft(draft)) {
3462
+ const division = {
3463
+ ...resource,
3464
+ parentUnit: getBusinessUnitKeyReference(
3465
+ draft.parentUnit,
3466
+ context.projectKey,
3467
+ this._storage
3468
+ )
3469
+ };
3470
+ this.saveNew(context, division);
3471
+ return division;
3472
+ } else if (this._isCompanyDraft(draft)) {
3473
+ const company = resource;
3474
+ this.saveNew(context, company);
3475
+ return company;
3638
3476
  }
3639
- return resource;
3477
+ throw new Error("Invalid business unit type");
3640
3478
  }
3641
- addStore(context, resource, action) {
3642
- throw new Error("Method not implemented.");
3479
+ _isCompanyDraft(draft) {
3480
+ return draft.unitType === "Company";
3643
3481
  }
3644
- changeAddress(context, resource, { addressId, addressKey, address }) {
3645
- const current = this._findAddress(resource, addressId, addressKey, true);
3646
- (0, import_node_assert.default)(current?.id);
3647
- const oldAddressIndex = resource.addresses.findIndex(
3648
- (a) => a.id === current.id
3649
- );
3482
+ _isDivisionDraft(draft) {
3483
+ return draft.unitType === "Division";
3484
+ }
3485
+ };
3486
+ var BusinessUnitUpdateHandler = class extends AbstractUpdateHandler {
3487
+ addAddress(context, resource, { address }) {
3650
3488
  const newAddress = createAddress(
3651
3489
  address,
3652
3490
  context.projectKey,
3653
3491
  this._storage
3654
3492
  );
3655
3493
  if (newAddress) {
3656
- resource.addresses[oldAddressIndex] = {
3657
- id: addressId,
3658
- ...newAddress
3659
- };
3494
+ resource.addresses.push(newAddress);
3660
3495
  }
3661
3496
  }
3662
- changeEmail(_context, resource, { email }) {
3663
- resource.email = email;
3664
- }
3665
- removeAddress(context, resource, action) {
3666
- const address = this._findAddress(
3667
- resource,
3668
- action.addressId,
3669
- action.addressKey,
3670
- true
3497
+ addAssociate(context, resource, { associate }) {
3498
+ const newAssociate = createAssociate(
3499
+ associate,
3500
+ context.projectKey,
3501
+ this._storage
3671
3502
  );
3672
- (0, import_node_assert.default)(address?.id);
3673
- resource.addresses = resource.addresses.filter((a) => a.id !== address.id);
3503
+ if (newAssociate) {
3504
+ resource.associates.push(newAssociate);
3505
+ }
3674
3506
  }
3675
- removeBillingAddressId(context, resource, action) {
3676
- const address = this._findAddress(
3677
- resource,
3678
- action.addressId,
3679
- action.addressKey,
3680
- true
3681
- );
3682
- (0, import_node_assert.default)(address?.id);
3683
- resource.billingAddressIds = resource.billingAddressIds?.filter(
3684
- (id) => id !== address.id
3507
+ addStore(context, resource, { store }) {
3508
+ const newStore = getStoreKeyReference(
3509
+ store,
3510
+ context.projectKey,
3511
+ this._storage
3685
3512
  );
3686
- if (resource.defaultBillingAddressId === address.id) {
3687
- resource.defaultBillingAddressId = void 0;
3513
+ if (newStore) {
3514
+ if (!resource.stores) {
3515
+ resource.stores = [];
3516
+ }
3517
+ resource.stores.push(newStore);
3688
3518
  }
3689
3519
  }
3690
- removeShippingAddressId(context, resource, action) {
3691
- const address = this._findAddress(
3692
- resource,
3693
- action.addressId,
3694
- action.addressKey,
3695
- true
3696
- );
3697
- (0, import_node_assert.default)(address?.id);
3698
- resource.shippingAddressIds = resource.shippingAddressIds?.filter(
3699
- (id) => id !== address.id
3520
+ changeAddress(context, resource, { address }) {
3521
+ const newAddress = createAddress(
3522
+ address,
3523
+ context.projectKey,
3524
+ this._storage
3700
3525
  );
3701
- if (resource.defaultShippingAddressId === address.id) {
3702
- resource.defaultShippingAddressId = void 0;
3526
+ if (newAddress) {
3527
+ resource.addresses.push(newAddress);
3703
3528
  }
3704
3529
  }
3705
- removeStore(context, resource, action) {
3706
- throw new Error("Method not implemented.");
3530
+ changeApprovalRuleMode(context, resource, { approvalRuleMode }) {
3531
+ resource.approvalRuleMode = approvalRuleMode;
3707
3532
  }
3708
- setAddressCustomField(context, resource, action) {
3709
- throw new Error("Method not implemented.");
3533
+ changeAssociateMode(context, resource, { associateMode }) {
3534
+ resource.associateMode = associateMode;
3710
3535
  }
3711
- setAddressCustomType(context, resource, action) {
3712
- throw new Error("Method not implemented.");
3536
+ changeName(context, resource, { name }) {
3537
+ resource.name = name;
3713
3538
  }
3714
- setAuthenticationMode(_context, resource, { authMode, password }) {
3715
- if (resource.authenticationMode === authMode) {
3716
- throw new CommercetoolsError(
3717
- {
3718
- code: "InvalidInput",
3719
- message: `The customer is already using the '${resource.authenticationMode}' authentication mode.`
3720
- },
3721
- 400
3722
- );
3723
- }
3724
- resource.authenticationMode = authMode;
3725
- if (authMode === "ExternalAuth") {
3726
- delete resource.password;
3727
- return;
3728
- }
3729
- if (authMode === "Password") {
3730
- resource.password = password ? hashPassword(password) : void 0;
3731
- return;
3732
- }
3733
- throw new CommercetoolsError(
3734
- {
3735
- code: "InvalidJsonInput",
3736
- message: "Request body does not contain valid JSON.",
3737
- detailedErrorMessage: `actions -> authMode: Invalid enum value: '${authMode}'. Expected one of: 'Password','ExternalAuth'`
3738
- },
3739
- 400
3539
+ changeParentUnit(context, resource, { parentUnit }) {
3540
+ resource.parentUnit = getBusinessUnitKeyReference(
3541
+ parentUnit,
3542
+ context.projectKey,
3543
+ this._storage
3740
3544
  );
3741
3545
  }
3742
- setCompanyName(_context, resource, { companyName }) {
3743
- resource.companyName = companyName;
3546
+ changeStatus(context, resource, { status }) {
3547
+ resource.status = status;
3744
3548
  }
3745
- setCustomerGroup(context, resource, action) {
3746
- if (!action.customerGroup) {
3747
- throw new CommercetoolsError(
3748
- {
3749
- code: "InvalidOperation",
3750
- message: "CustomerGroup is required."
3751
- },
3752
- 400
3753
- );
3754
- }
3755
- const group = this._storage.getByResourceIdentifier(
3756
- context.projectKey,
3757
- action.customerGroup
3758
- );
3759
- resource.customerGroup = {
3760
- typeId: "customer-group",
3761
- id: group.id
3762
- };
3549
+ setAssociates(context, resource, { associates }) {
3550
+ const newAssociates = associates.map((a) => createAssociate(a, context.projectKey, this._storage)).filter((a) => a !== void 0);
3551
+ resource.associates = newAssociates || void 0;
3763
3552
  }
3764
- setCustomerNumber(_context, resource, { customerNumber }) {
3765
- if (resource.customerNumber) {
3766
- throw new Error(
3767
- "A Customer number already exists and cannot be set again."
3768
- );
3769
- }
3770
- resource.customerNumber = customerNumber;
3553
+ setContactEmail(context, resource, { contactEmail }) {
3554
+ resource.contactEmail = contactEmail;
3771
3555
  }
3772
- setCustomField(_context, resource, { name, value }) {
3556
+ setStoreMode(context, resource, { storeMode }) {
3557
+ resource.storeMode = storeMode;
3558
+ }
3559
+ };
3560
+
3561
+ // src/repositories/cart-discount/actions.ts
3562
+ var CartDiscountUpdateHandler = class extends AbstractUpdateHandler {
3563
+ changeIsActive(context, resource, { isActive }) {
3564
+ resource.isActive = isActive;
3565
+ }
3566
+ changeSortOrder(context, resource, { sortOrder }) {
3567
+ resource.sortOrder = sortOrder;
3568
+ }
3569
+ changeTarget(context, resource, { target }) {
3570
+ resource.target = target;
3571
+ }
3572
+ setCustomField(context, resource, { name, value }) {
3773
3573
  if (!resource.custom) {
3774
- throw new Error("Resource has no custom field");
3574
+ return;
3575
+ }
3576
+ if (value === null) {
3577
+ if (name in resource.custom.fields) {
3578
+ delete resource.custom.fields[name];
3579
+ } else {
3580
+ throw new CommercetoolsError(
3581
+ {
3582
+ code: "InvalidOperation",
3583
+ message: "Cannot remove custom field " + name + " because it does not exist."
3584
+ },
3585
+ 400
3586
+ );
3587
+ }
3588
+ } else {
3589
+ resource.custom.fields[name] = value;
3775
3590
  }
3776
- resource.custom.fields[name] = value;
3777
3591
  }
3778
3592
  setCustomType(context, resource, { type, fields }) {
3779
- if (type) {
3780
- resource.custom = createCustomFields(
3781
- { type, fields },
3782
- context.projectKey,
3783
- this._storage
3784
- );
3785
- } else {
3593
+ if (!type) {
3786
3594
  resource.custom = void 0;
3595
+ } else {
3596
+ const resolvedType = this._storage.getByResourceIdentifier(
3597
+ context.projectKey,
3598
+ type
3599
+ );
3600
+ if (!resolvedType) {
3601
+ throw new Error(`Type ${type} not found`);
3602
+ }
3603
+ resource.custom = {
3604
+ type: {
3605
+ typeId: "type",
3606
+ id: resolvedType.id
3607
+ },
3608
+ fields: fields || {}
3609
+ };
3787
3610
  }
3788
3611
  }
3789
- setDateOfBirth(context, resource, action) {
3790
- resource.dateOfBirth = action.dateOfBirth;
3791
- }
3792
- setDefaultBillingAddress(context, resource, action) {
3793
- const address = this._findAddress(
3794
- resource,
3795
- action.addressId,
3796
- action.addressKey,
3797
- true
3798
- );
3799
- (0, import_node_assert.default)(address?.id);
3800
- resource.defaultBillingAddressId = address.id;
3801
- if (resource.billingAddressIds === void 0) {
3802
- resource.billingAddressIds = [];
3803
- }
3804
- if (!resource.billingAddressIds.includes(address.id)) {
3805
- resource.billingAddressIds.push(address.id);
3806
- }
3807
- }
3808
- setDefaultShippingAddress(context, resource, action) {
3809
- const address = this._findAddress(
3810
- resource,
3811
- action.addressId,
3812
- action.addressKey,
3813
- true
3814
- );
3815
- (0, import_node_assert.default)(address?.id);
3816
- resource.defaultShippingAddressId = address.id;
3817
- if (resource.shippingAddressIds === void 0) {
3818
- resource.shippingAddressIds = [];
3819
- }
3820
- if (!resource.shippingAddressIds.includes(address.id)) {
3821
- resource.shippingAddressIds.push(address.id);
3822
- }
3823
- }
3824
- setExternalId(_context, resource, { externalId }) {
3825
- resource.externalId = externalId;
3826
- }
3827
- setFirstName(_context, resource, { firstName }) {
3828
- resource.firstName = firstName;
3612
+ setDescription(context, resource, { description }) {
3613
+ resource.description = description;
3829
3614
  }
3830
- setKey(_context, resource, { key }) {
3615
+ setKey(context, resource, { key }) {
3831
3616
  resource.key = key;
3832
3617
  }
3833
- setLastName(_context, resource, { lastName }) {
3834
- resource.lastName = lastName;
3835
- }
3836
- setLocale(_context, resource, { locale }) {
3837
- resource.locale = locale;
3838
- }
3839
- setMiddleName(context, resource, action) {
3840
- resource.middleName = action.middleName;
3841
- }
3842
- setSalutation(_context, resource, { salutation }) {
3843
- resource.salutation = salutation;
3844
- }
3845
- setStores(context, resource, action) {
3846
- throw new Error("Method not implemented.");
3618
+ setStores(context, resource, { stores }) {
3619
+ resource.stores = stores?.map(
3620
+ (s) => getStoreKeyReference(s, context.projectKey, this._storage)
3621
+ );
3847
3622
  }
3848
- setTitle(context, resource, action) {
3849
- resource.title = action.title;
3623
+ setValidFrom(context, resource, { validFrom }) {
3624
+ resource.validFrom = validFrom;
3850
3625
  }
3851
- setVatId(_context, resource, { vatId }) {
3852
- resource.vatId = vatId;
3626
+ setValidFromAndUntil(context, resource, { validFrom, validUntil }) {
3627
+ resource.validFrom = validFrom;
3628
+ resource.validUntil = validUntil;
3853
3629
  }
3854
- _findAddress(resource, addressId, addressKey, required = false) {
3855
- if (addressKey) {
3856
- const address = resource.addresses.find((a) => a.key === addressKey);
3857
- if (!address) {
3858
- throw new CommercetoolsError(
3859
- {
3860
- code: "InvalidOperation",
3861
- message: `Customer does not contain an address with the key ${addressKey}.`
3862
- },
3863
- 400
3864
- );
3865
- }
3866
- return address;
3867
- }
3868
- if (addressId) {
3869
- const address = resource.addresses.find((a) => a.id === addressId);
3870
- if (!address) {
3871
- throw new CommercetoolsError(
3872
- {
3873
- code: "InvalidOperation",
3874
- message: `Customer does not contain an address with the id ${addressId}.`
3875
- },
3876
- 400
3877
- );
3878
- }
3879
- return address;
3880
- }
3881
- if (required) {
3882
- throw new CommercetoolsError(
3883
- {
3884
- code: "InvalidOperation",
3885
- message: "One of address 'addressId' or 'addressKey' is required."
3886
- },
3887
- 400
3888
- );
3889
- }
3630
+ setValidUntil(context, resource, { validUntil }) {
3631
+ resource.validUntil = validUntil;
3890
3632
  }
3891
3633
  };
3892
3634
 
3893
- // src/repositories/customer/index.ts
3894
- var CustomerRepository = class extends AbstractResourceRepository {
3635
+ // src/repositories/cart-discount/index.ts
3636
+ var CartDiscountRepository = class extends AbstractResourceRepository {
3895
3637
  constructor(storage) {
3896
- super("customer", storage);
3897
- this.actions = new CustomerUpdateHandler(storage);
3638
+ super("cart-discount", storage);
3639
+ this.actions = new CartDiscountUpdateHandler(storage);
3898
3640
  }
3899
3641
  create(context, draft) {
3900
- const results = this._storage.query(context.projectKey, this.getTypeId(), {
3901
- where: [`lowercaseEmail="${draft.email.toLowerCase()}"`]
3902
- });
3903
- if (results.count > 0) {
3904
- throw new CommercetoolsError({
3905
- code: "CustomerAlreadyExists",
3906
- statusCode: 400,
3907
- message: "There is already an existing customer with the provided email.",
3908
- errors: [
3909
- {
3910
- code: "DuplicateField",
3911
- message: `Customer with email '${draft.email}' already exists.`,
3912
- duplicateValue: draft.email,
3913
- field: "email"
3914
- }
3915
- ]
3916
- });
3917
- }
3918
- const addresses = draft.addresses?.map((address) => ({
3919
- ...address,
3920
- id: generateRandomString(5)
3921
- })) ?? [];
3922
- const lookupAdressId = (addresses2, addressId) => {
3923
- if (addressId < addresses2.length) {
3924
- const id = addresses2[addressId].id;
3925
- if (!id) {
3926
- throw new Error("Address ID is missing");
3927
- }
3928
- return id;
3929
- }
3930
- throw new CommercetoolsError({
3931
- code: "InvalidInput",
3932
- message: `Address with ID '${addressId}' not found.`,
3933
- errors: [
3934
- {
3935
- code: "InvalidInput",
3936
- message: `Address with ID '${addressId}' not found.`,
3937
- field: "addressId"
3938
- }
3939
- ]
3940
- });
3941
- };
3942
- const defaultBillingAddressId = draft.defaultBillingAddress !== void 0 ? lookupAdressId(addresses, draft.defaultBillingAddress) : void 0;
3943
- const defaultShippingAddressId = draft.defaultShippingAddress !== void 0 ? lookupAdressId(addresses, draft.defaultShippingAddress) : void 0;
3944
- const shippingAddressIds = draft.shippingAddresses?.map(
3945
- (addressId) => lookupAdressId(addresses, addressId)
3946
- ) ?? [];
3947
- const billingAddressIds = draft.billingAddresses?.map(
3948
- (addressId) => lookupAdressId(addresses, addressId)
3949
- ) ?? [];
3950
- let storesForCustomer = [];
3951
- if (draft.stores && draft.stores.length > 0) {
3952
- const storeIds = draft.stores.map((storeReference) => storeReference.id).filter(Boolean);
3953
- const stores = this._storage.query(context.projectKey, "store", {
3954
- where: storeIds.map((id) => `id="${id}"`)
3955
- }).results;
3956
- if (storeIds.length !== stores.length) {
3957
- throw new CommercetoolsError({
3958
- code: "ResourceNotFound",
3959
- message: `Store with ID '${storeIds.find((id) => !stores.some((store) => store.id === id))}' was not found.`
3960
- });
3961
- }
3962
- storesForCustomer = draft.stores.map((storeReference) => ({
3963
- typeId: "store",
3964
- key: storeReference.key ?? stores.find((store) => store.id === storeReference.id)?.key
3965
- }));
3966
- }
3967
3642
  const resource = {
3968
3643
  ...getBaseResourceProperties(),
3969
3644
  key: draft.key,
3970
- authenticationMode: draft.authenticationMode || "Password",
3971
- firstName: draft.firstName,
3972
- lastName: draft.lastName,
3973
- middleName: draft.middleName,
3974
- title: draft.title,
3975
- dateOfBirth: draft.dateOfBirth,
3976
- companyName: draft.companyName,
3977
- email: draft.email.toLowerCase(),
3978
- lowercaseEmail: draft.email.toLowerCase(),
3979
- password: draft.password ? hashPassword(draft.password) : void 0,
3980
- isEmailVerified: draft.isEmailVerified || false,
3981
- addresses,
3982
- customerNumber: draft.customerNumber,
3983
- externalId: draft.externalId,
3984
- defaultBillingAddressId,
3985
- defaultShippingAddressId,
3986
- shippingAddressIds,
3987
- billingAddressIds,
3645
+ description: draft.description,
3646
+ cartPredicate: draft.cartPredicate,
3647
+ isActive: draft.isActive || false,
3648
+ name: draft.name,
3649
+ stores: draft.stores?.map(
3650
+ (s) => getStoreKeyReference(s, context.projectKey, this._storage)
3651
+ ) ?? [],
3652
+ references: [],
3653
+ target: draft.target,
3654
+ requiresDiscountCode: draft.requiresDiscountCode || false,
3655
+ sortOrder: draft.sortOrder,
3656
+ stackingMode: draft.stackingMode || "Stacking",
3657
+ validFrom: draft.validFrom,
3658
+ validUntil: draft.validUntil,
3659
+ value: this.transformValueDraft(draft.value),
3988
3660
  custom: createCustomFields(
3989
3661
  draft.custom,
3990
3662
  context.projectKey,
3991
3663
  this._storage
3992
- ),
3993
- stores: storesForCustomer
3664
+ )
3994
3665
  };
3995
3666
  return this.saveNew(context, resource);
3996
3667
  }
3997
- saveUpdate(context, version, resource) {
3998
- const updatedResource = {
3999
- ...resource,
4000
- lowercaseEmail: resource.email.toLowerCase()
4001
- };
4002
- return super.saveUpdate(context, version, updatedResource);
4003
- }
4004
- passwordResetToken(context, request) {
4005
- const results = this._storage.query(context.projectKey, this.getTypeId(), {
4006
- where: [`email="${request.email.toLocaleLowerCase()}"`]
4007
- });
4008
- if (results.count === 0) {
4009
- throw new CommercetoolsError({
4010
- code: "ResourceNotFound",
4011
- message: `The Customer with ID '${request.email}' was not found.`
4012
- });
4013
- }
4014
- const ttlMinutes = request.ttlMinutes ?? 34560;
4015
- const expiresAt = new Date((/* @__PURE__ */ new Date()).getTime() + ttlMinutes * 60 * 1e3);
4016
- const customer = results.results[0];
4017
- const rest = getBaseResourceProperties();
4018
- const token = createPasswordResetToken(customer, expiresAt);
4019
- return {
4020
- id: rest.id,
4021
- createdAt: rest.createdAt,
4022
- lastModifiedAt: rest.lastModifiedAt,
4023
- customerId: customer.id,
4024
- expiresAt: expiresAt.toISOString(),
4025
- value: token
4026
- };
3668
+ transformValueDraft(value) {
3669
+ switch (value.type) {
3670
+ case "absolute": {
3671
+ return {
3672
+ type: "absolute",
3673
+ money: value.money.map(createTypedMoney)
3674
+ };
3675
+ }
3676
+ case "fixed": {
3677
+ return {
3678
+ type: "fixed",
3679
+ money: value.money.map(createTypedMoney)
3680
+ };
3681
+ }
3682
+ case "giftLineItem": {
3683
+ return {
3684
+ ...value
3685
+ };
3686
+ }
3687
+ case "relative": {
3688
+ return {
3689
+ ...value
3690
+ };
3691
+ }
3692
+ }
3693
+ return value;
4027
3694
  }
4028
- passwordReset(context, resetPassword) {
4029
- const { newPassword, tokenValue } = resetPassword;
4030
- const customerId = validatePasswordResetToken(tokenValue);
4031
- if (!customerId) {
4032
- throw new CommercetoolsError({
4033
- code: "ResourceNotFound",
4034
- message: `The Customer with ID 'Token(${tokenValue})' was not found.`
4035
- });
3695
+ };
3696
+
3697
+ // src/repositories/category/index.ts
3698
+ var import_uuid8 = require("uuid");
3699
+
3700
+ // src/repositories/category/actions.ts
3701
+ var import_uuid7 = require("uuid");
3702
+ var CategoryUpdateHandler = class extends AbstractUpdateHandler {
3703
+ addAsset(context, resource, { asset }) {
3704
+ if (!resource.assets) {
3705
+ resource.assets = [this.assetFromAssetDraft(asset, context)];
3706
+ } else {
3707
+ resource.assets.push(this.assetFromAssetDraft(asset, context));
4036
3708
  }
4037
- const customer = this._storage.get(
3709
+ }
3710
+ changeAssetName(context, resource, { assetId, assetKey, name }) {
3711
+ resource.assets?.forEach((asset) => {
3712
+ if (assetId && assetId === asset.id) {
3713
+ asset.name = name;
3714
+ }
3715
+ if (assetKey && assetKey === asset.key) {
3716
+ asset.name = name;
3717
+ }
3718
+ });
3719
+ }
3720
+ changeName(context, resource, { name }) {
3721
+ resource.name = name;
3722
+ }
3723
+ changeParent(context, resource, { parent }) {
3724
+ const category = this._storage.getByResourceIdentifier(
4038
3725
  context.projectKey,
4039
- "customer",
4040
- customerId
3726
+ parent
4041
3727
  );
4042
- if (!customer) {
4043
- throw new CommercetoolsError({
4044
- code: "ResourceNotFound",
4045
- message: `The Customer with ID 'Token(${tokenValue})' was not found.`
3728
+ if (!category) {
3729
+ throw new Error("No category found for reference");
3730
+ }
3731
+ resource.parent = {
3732
+ typeId: "category",
3733
+ id: category.id
3734
+ };
3735
+ }
3736
+ changeSlug(context, resource, { slug }) {
3737
+ resource.slug = slug;
3738
+ }
3739
+ removeAsset(context, resource, { assetId, assetKey }) {
3740
+ if (!resource.assets) {
3741
+ return;
3742
+ }
3743
+ if (assetId) {
3744
+ resource.assets = resource.assets.filter(function(obj) {
3745
+ return obj.id !== assetId;
4046
3746
  });
3747
+ return;
3748
+ }
3749
+ if (assetKey) {
3750
+ resource.assets = resource.assets.filter(function(obj) {
3751
+ return obj.key !== assetKey;
3752
+ });
3753
+ return;
4047
3754
  }
4048
- customer.password = hashPassword(newPassword);
4049
- customer.version += 1;
4050
- this._storage.add(context.projectKey, "customer", customer);
4051
- return customer;
4052
3755
  }
4053
- verifyEmailToken(context, id) {
4054
- const results = this._storage.query(context.projectKey, this.getTypeId(), {
4055
- where: [`id="${id.toLocaleLowerCase()}"`]
3756
+ setAssetDescription(context, resource, { assetId, assetKey, description }) {
3757
+ resource.assets?.forEach((asset) => {
3758
+ if (assetId && assetId === asset.id) {
3759
+ asset.description = description;
3760
+ }
3761
+ if (assetKey && assetKey === asset.key) {
3762
+ asset.description = description;
3763
+ }
4056
3764
  });
4057
- if (results.count === 0) {
4058
- throw new CommercetoolsError({
4059
- code: "ResourceNotFound",
4060
- message: `The Customer with ID '${id}' was not found.`
3765
+ }
3766
+ setAssetSources(context, resource, { assetId, assetKey, sources }) {
3767
+ resource.assets?.forEach((asset) => {
3768
+ if (assetId && assetId === asset.id) {
3769
+ asset.sources = sources;
3770
+ }
3771
+ if (assetKey && assetKey === asset.key) {
3772
+ asset.sources = sources;
3773
+ }
3774
+ });
3775
+ }
3776
+ setCustomField(context, resource, { name, value }) {
3777
+ if (!resource.custom) {
3778
+ return;
3779
+ }
3780
+ if (value === null) {
3781
+ delete resource.custom.fields[name];
3782
+ } else {
3783
+ resource.custom.fields[name] = value;
3784
+ }
3785
+ }
3786
+ setCustomType(context, resource, { type, fields }) {
3787
+ if (type) {
3788
+ resource.custom = createCustomFields(
3789
+ { type, fields },
3790
+ context.projectKey,
3791
+ this._storage
3792
+ );
3793
+ } else {
3794
+ resource.custom = void 0;
3795
+ }
3796
+ }
3797
+ setDescription(context, resource, { description }) {
3798
+ resource.description = description;
3799
+ }
3800
+ setKey(context, resource, { key }) {
3801
+ resource.key = key;
3802
+ }
3803
+ setMetaDescription(context, resource, { metaDescription }) {
3804
+ resource.metaDescription = metaDescription;
3805
+ }
3806
+ setMetaKeywords(context, resource, { metaKeywords }) {
3807
+ resource.metaKeywords = metaKeywords;
3808
+ }
3809
+ setMetaTitle(context, resource, { metaTitle }) {
3810
+ resource.metaTitle = metaTitle;
3811
+ }
3812
+ assetFromAssetDraft = (draft, context) => ({
3813
+ ...draft,
3814
+ id: (0, import_uuid7.v4)(),
3815
+ custom: createCustomFields(draft.custom, context.projectKey, this._storage)
3816
+ });
3817
+ };
3818
+
3819
+ // src/repositories/category/index.ts
3820
+ var CategoryRepository = class extends AbstractResourceRepository {
3821
+ constructor(storage) {
3822
+ super("category", storage);
3823
+ this.actions = new CategoryUpdateHandler(this._storage);
3824
+ }
3825
+ create(context, draft) {
3826
+ const resource = {
3827
+ ...getBaseResourceProperties(),
3828
+ key: draft.key,
3829
+ name: draft.name,
3830
+ slug: draft.slug,
3831
+ description: draft.description,
3832
+ metaDescription: draft.metaDescription,
3833
+ metaKeywords: draft.metaKeywords,
3834
+ orderHint: draft.orderHint || "",
3835
+ externalId: draft.externalId || "",
3836
+ parent: draft.parent ? { typeId: "category", id: draft.parent.id } : void 0,
3837
+ ancestors: [],
3838
+ // Resolved at runtime
3839
+ assets: draft.assets?.map((d) => ({
3840
+ id: (0, import_uuid8.v4)(),
3841
+ name: d.name,
3842
+ description: d.description,
3843
+ sources: d.sources,
3844
+ tags: d.tags,
3845
+ key: d.key,
3846
+ custom: createCustomFields(
3847
+ draft.custom,
3848
+ context.projectKey,
3849
+ this._storage
3850
+ )
3851
+ })) || [],
3852
+ custom: createCustomFields(
3853
+ draft.custom,
3854
+ context.projectKey,
3855
+ this._storage
3856
+ )
3857
+ };
3858
+ return this.saveNew(context, resource);
3859
+ }
3860
+ postProcessResource(context, resource, params) {
3861
+ let node = resource;
3862
+ const ancestors = [];
3863
+ const expandClauses = params?.expand?.map(parseExpandClause) ?? [];
3864
+ const addExpand = expandClauses?.find(
3865
+ (c) => c.element === "ancestors" && c.index === "*"
3866
+ );
3867
+ while (node.parent) {
3868
+ node = this._storage.getByResourceIdentifier(
3869
+ context.projectKey,
3870
+ node.parent
3871
+ );
3872
+ ancestors.push({
3873
+ typeId: "category",
3874
+ id: node.id,
3875
+ obj: addExpand ? node : void 0
4061
3876
  });
4062
3877
  }
4063
- const expiresAt = new Date(Date.now() + 30 * 60);
4064
- const customer = results.results[0];
4065
- const rest = getBaseResourceProperties();
4066
- const token = createEmailVerifyToken(customer);
4067
- return {
4068
- id: rest.id,
4069
- createdAt: rest.createdAt,
4070
- lastModifiedAt: rest.lastModifiedAt,
4071
- customerId: customer.id,
4072
- expiresAt: expiresAt.toISOString(),
4073
- value: token
3878
+ resource.ancestors = ancestors;
3879
+ return resource;
3880
+ }
3881
+ };
3882
+
3883
+ // src/repositories/channel.ts
3884
+ var ChannelRepository = class extends AbstractResourceRepository {
3885
+ constructor(storage) {
3886
+ super("channel", storage);
3887
+ this.actions = new ChannelUpdateHandler(this._storage);
3888
+ }
3889
+ create(context, draft) {
3890
+ const resource = {
3891
+ ...getBaseResourceProperties(),
3892
+ key: draft.key,
3893
+ name: draft.name,
3894
+ description: draft.description,
3895
+ roles: draft.roles || [],
3896
+ geoLocation: draft.geoLocation,
3897
+ address: createAddress(draft.address, context.projectKey, this._storage),
3898
+ custom: createCustomFields(
3899
+ draft.custom,
3900
+ context.projectKey,
3901
+ this._storage
3902
+ )
4074
3903
  };
3904
+ return this.saveNew(context, resource);
3905
+ }
3906
+ };
3907
+ var ChannelUpdateHandler = class extends AbstractUpdateHandler {
3908
+ changeDescription(context, resource, { description }) {
3909
+ resource.description = description;
3910
+ }
3911
+ changeKey(context, resource, { key }) {
3912
+ resource.key = key;
3913
+ }
3914
+ changeName(context, resource, { name }) {
3915
+ resource.name = name;
3916
+ }
3917
+ setAddress(context, resource, { address }) {
3918
+ resource.address = createAddress(
3919
+ address,
3920
+ context.projectKey,
3921
+ this._storage
3922
+ );
3923
+ }
3924
+ setCustomField(context, resource, { name, value }) {
3925
+ if (!resource.custom) {
3926
+ return;
3927
+ }
3928
+ if (value === null) {
3929
+ delete resource.custom.fields[name];
3930
+ } else {
3931
+ resource.custom.fields[name] = value;
3932
+ }
3933
+ }
3934
+ setCustomType(context, resource, { type, fields }) {
3935
+ if (type) {
3936
+ resource.custom = createCustomFields(
3937
+ { type, fields },
3938
+ context.projectKey,
3939
+ this._storage
3940
+ );
3941
+ } else {
3942
+ resource.custom = void 0;
3943
+ }
3944
+ }
3945
+ setGeoLocation(context, resource, { geoLocation }) {
3946
+ resource.geoLocation = geoLocation;
3947
+ }
3948
+ };
3949
+
3950
+ // src/repositories/custom-object.ts
3951
+ var CustomObjectRepository = class extends AbstractResourceRepository {
3952
+ constructor(storage) {
3953
+ super("key-value-document", storage);
3954
+ }
3955
+ create(context, draft) {
3956
+ const current = this.getWithContainerAndKey(
3957
+ context,
3958
+ draft.container,
3959
+ draft.key
3960
+ );
3961
+ if (current) {
3962
+ if (draft.version) {
3963
+ checkConcurrentModification(current.version, draft.version, current.id);
3964
+ } else {
3965
+ draft.version = current.version;
3966
+ }
3967
+ if (draft.value !== current.value) {
3968
+ const updated = cloneObject(current);
3969
+ updated.value = draft.value;
3970
+ updated.version += 1;
3971
+ this.saveUpdate(context, draft.version, updated);
3972
+ return updated;
3973
+ }
3974
+ return current;
3975
+ } else {
3976
+ if (draft.version) {
3977
+ throw new CommercetoolsError(
3978
+ {
3979
+ code: "InvalidOperation",
3980
+ message: "version on create must be 0"
3981
+ },
3982
+ 400
3983
+ );
3984
+ }
3985
+ const baseProperties = getBaseResourceProperties();
3986
+ const resource = {
3987
+ ...baseProperties,
3988
+ container: draft.container,
3989
+ key: draft.key,
3990
+ value: draft.value
3991
+ };
3992
+ this.saveNew(context, resource);
3993
+ return resource;
3994
+ }
3995
+ }
3996
+ getWithContainerAndKey(context, container, key) {
3997
+ const items = this._storage.all(context.projectKey, this.getTypeId());
3998
+ return items.find(
3999
+ (item) => item.container === container && item.key === key
4000
+ );
4001
+ }
4002
+ queryWithContainer(context, container, params = {}) {
4003
+ const whereClause = params.where || [];
4004
+ whereClause.push(`container="${container}"`);
4005
+ const result = this._storage.query(context.projectKey, this.getTypeId(), {
4006
+ ...params,
4007
+ where: whereClause
4008
+ });
4009
+ result.results = result.results.map(
4010
+ (r) => this.postProcessResource(context, r, {
4011
+ expand: params.expand
4012
+ })
4013
+ );
4014
+ return result;
4015
+ }
4016
+ };
4017
+
4018
+ // src/repositories/customer/actions.ts
4019
+ var import_node_assert = __toESM(require("assert"), 1);
4020
+ var CustomerUpdateHandler = class extends AbstractUpdateHandler {
4021
+ addAddress(_context, resource, { address }) {
4022
+ resource.addresses.push({
4023
+ ...address,
4024
+ id: address.id ?? generateRandomString(5)
4025
+ });
4026
+ }
4027
+ addBillingAddressId(_context, resource, { addressId, addressKey }) {
4028
+ const address = this._findAddress(resource, addressId, addressKey, true);
4029
+ (0, import_node_assert.default)(address?.id);
4030
+ if (resource.billingAddressIds === void 0) {
4031
+ resource.billingAddressIds = [];
4032
+ }
4033
+ if (!resource.billingAddressIds.includes(address.id)) {
4034
+ resource.billingAddressIds.push(address.id);
4035
+ }
4036
+ }
4037
+ addShippingAddressId(_context, resource, { addressId, addressKey }) {
4038
+ const address = this._findAddress(resource, addressId, addressKey, true);
4039
+ (0, import_node_assert.default)(address?.id);
4040
+ if (resource.shippingAddressIds === void 0) {
4041
+ resource.shippingAddressIds = [];
4042
+ }
4043
+ if (!resource.shippingAddressIds.includes(address.id)) {
4044
+ resource.shippingAddressIds.push(address.id);
4045
+ }
4046
+ return resource;
4047
+ }
4048
+ addStore(context, resource, action) {
4049
+ throw new Error("Method not implemented.");
4050
+ }
4051
+ changeAddress(context, resource, { addressId, addressKey, address }) {
4052
+ const current = this._findAddress(resource, addressId, addressKey, true);
4053
+ (0, import_node_assert.default)(current?.id);
4054
+ const oldAddressIndex = resource.addresses.findIndex(
4055
+ (a) => a.id === current.id
4056
+ );
4057
+ const newAddress = createAddress(
4058
+ address,
4059
+ context.projectKey,
4060
+ this._storage
4061
+ );
4062
+ if (newAddress) {
4063
+ resource.addresses[oldAddressIndex] = {
4064
+ id: addressId,
4065
+ ...newAddress
4066
+ };
4067
+ }
4068
+ }
4069
+ changeEmail(_context, resource, { email }) {
4070
+ resource.email = email;
4071
+ }
4072
+ removeAddress(context, resource, action) {
4073
+ const address = this._findAddress(
4074
+ resource,
4075
+ action.addressId,
4076
+ action.addressKey,
4077
+ true
4078
+ );
4079
+ (0, import_node_assert.default)(address?.id);
4080
+ resource.addresses = resource.addresses.filter((a) => a.id !== address.id);
4081
+ }
4082
+ removeBillingAddressId(context, resource, action) {
4083
+ const address = this._findAddress(
4084
+ resource,
4085
+ action.addressId,
4086
+ action.addressKey,
4087
+ true
4088
+ );
4089
+ (0, import_node_assert.default)(address?.id);
4090
+ resource.billingAddressIds = resource.billingAddressIds?.filter(
4091
+ (id) => id !== address.id
4092
+ );
4093
+ if (resource.defaultBillingAddressId === address.id) {
4094
+ resource.defaultBillingAddressId = void 0;
4095
+ }
4096
+ }
4097
+ removeShippingAddressId(context, resource, action) {
4098
+ const address = this._findAddress(
4099
+ resource,
4100
+ action.addressId,
4101
+ action.addressKey,
4102
+ true
4103
+ );
4104
+ (0, import_node_assert.default)(address?.id);
4105
+ resource.shippingAddressIds = resource.shippingAddressIds?.filter(
4106
+ (id) => id !== address.id
4107
+ );
4108
+ if (resource.defaultShippingAddressId === address.id) {
4109
+ resource.defaultShippingAddressId = void 0;
4110
+ }
4075
4111
  }
4076
- };
4077
-
4078
- // src/repositories/customer-group.ts
4079
- var CustomerGroupRepository = class extends AbstractResourceRepository {
4080
- constructor(storage) {
4081
- super("customer-group", storage);
4082
- this.actions = new CustomerGroupUpdateHandler(storage);
4112
+ removeStore(context, resource, action) {
4113
+ throw new Error("Method not implemented.");
4083
4114
  }
4084
- create(context, draft) {
4085
- const resource = {
4086
- ...getBaseResourceProperties(),
4087
- key: draft.key,
4088
- name: draft.groupName,
4089
- custom: createCustomFields(
4090
- draft.custom,
4091
- context.projectKey,
4092
- this._storage
4093
- )
4094
- };
4095
- return this.saveNew(context, resource);
4115
+ setAddressCustomField(context, resource, action) {
4116
+ throw new Error("Method not implemented.");
4096
4117
  }
4097
- };
4098
- var CustomerGroupUpdateHandler = class extends AbstractUpdateHandler {
4099
- changeName(context, resource, { name }) {
4100
- resource.name = name;
4118
+ setAddressCustomType(context, resource, action) {
4119
+ throw new Error("Method not implemented.");
4101
4120
  }
4102
- setCustomField(context, resource, { name, value }) {
4103
- if (!resource.custom) {
4121
+ setAuthenticationMode(_context, resource, { authMode, password }) {
4122
+ if (resource.authenticationMode === authMode) {
4123
+ throw new CommercetoolsError(
4124
+ {
4125
+ code: "InvalidInput",
4126
+ message: `The customer is already using the '${resource.authenticationMode}' authentication mode.`
4127
+ },
4128
+ 400
4129
+ );
4130
+ }
4131
+ resource.authenticationMode = authMode;
4132
+ if (authMode === "ExternalAuth") {
4133
+ delete resource.password;
4104
4134
  return;
4105
4135
  }
4106
- if (value === null) {
4107
- delete resource.custom.fields[name];
4108
- } else {
4109
- resource.custom.fields[name] = value;
4136
+ if (authMode === "Password") {
4137
+ resource.password = password ? hashPassword(password) : void 0;
4138
+ return;
4110
4139
  }
4140
+ throw new CommercetoolsError(
4141
+ {
4142
+ code: "InvalidJsonInput",
4143
+ message: "Request body does not contain valid JSON.",
4144
+ detailedErrorMessage: `actions -> authMode: Invalid enum value: '${authMode}'. Expected one of: 'Password','ExternalAuth'`
4145
+ },
4146
+ 400
4147
+ );
4111
4148
  }
4112
- setCustomType(context, resource, { type, fields }) {
4113
- if (type) {
4114
- resource.custom = createCustomFields(
4115
- { type, fields },
4116
- context.projectKey,
4117
- this._storage
4149
+ setCompanyName(_context, resource, { companyName }) {
4150
+ resource.companyName = companyName;
4151
+ }
4152
+ setCustomerGroup(context, resource, action) {
4153
+ if (!action.customerGroup) {
4154
+ throw new CommercetoolsError(
4155
+ {
4156
+ code: "InvalidOperation",
4157
+ message: "CustomerGroup is required."
4158
+ },
4159
+ 400
4118
4160
  );
4119
- } else {
4120
- resource.custom = void 0;
4121
4161
  }
4122
- }
4123
- setKey(context, resource, { key }) {
4124
- resource.key = key;
4125
- }
4126
- };
4127
-
4128
- // src/repositories/discount-code/actions.ts
4129
- var DiscountCodeUpdateHandler = class extends AbstractUpdateHandler {
4130
- changeCartDiscounts(context, resource, { cartDiscounts }) {
4131
- resource.cartDiscounts = cartDiscounts.map(
4132
- (obj) => ({
4133
- typeId: "cart-discount",
4134
- id: obj.id
4135
- })
4162
+ const group = this._storage.getByResourceIdentifier(
4163
+ context.projectKey,
4164
+ action.customerGroup
4136
4165
  );
4166
+ resource.customerGroup = {
4167
+ typeId: "customer-group",
4168
+ id: group.id
4169
+ };
4137
4170
  }
4138
- changeIsActive(context, resource, { isActive }) {
4139
- resource.isActive = isActive;
4140
- }
4141
- setCartPredicate(context, resource, { cartPredicate }) {
4142
- resource.cartPredicate = cartPredicate;
4171
+ setCustomerNumber(_context, resource, { customerNumber }) {
4172
+ if (resource.customerNumber) {
4173
+ throw new Error(
4174
+ "A Customer number already exists and cannot be set again."
4175
+ );
4176
+ }
4177
+ resource.customerNumber = customerNumber;
4143
4178
  }
4144
- setCustomField(context, resource, { name, value }) {
4179
+ setCustomField(_context, resource, { name, value }) {
4145
4180
  if (!resource.custom) {
4146
- return;
4147
- }
4148
- if (value === null) {
4149
- delete resource.custom.fields[name];
4150
- } else {
4151
- resource.custom.fields[name] = value;
4181
+ throw new Error("Resource has no custom field");
4152
4182
  }
4183
+ resource.custom.fields[name] = value;
4153
4184
  }
4154
4185
  setCustomType(context, resource, { type, fields }) {
4155
4186
  if (type) {
@@ -4162,232 +4193,238 @@ var DiscountCodeUpdateHandler = class extends AbstractUpdateHandler {
4162
4193
  resource.custom = void 0;
4163
4194
  }
4164
4195
  }
4165
- setDescription(context, resource, { description }) {
4166
- resource.description = description;
4167
- }
4168
- setMaxApplications(context, resource, { maxApplications }) {
4169
- resource.maxApplications = maxApplications;
4170
- }
4171
- setMaxApplicationsPerCustomer(context, resource, {
4172
- maxApplicationsPerCustomer
4173
- }) {
4174
- resource.maxApplicationsPerCustomer = maxApplicationsPerCustomer;
4175
- }
4176
- setName(context, resource, { name }) {
4177
- resource.name = name;
4178
- }
4179
- setValidFrom(context, resource, { validFrom }) {
4180
- resource.validFrom = validFrom;
4181
- }
4182
- setValidFromAndUntil(context, resource, { validFrom, validUntil }) {
4183
- resource.validFrom = validFrom;
4184
- resource.validUntil = validUntil;
4185
- }
4186
- setValidUntil(context, resource, { validUntil }) {
4187
- resource.validUntil = validUntil;
4188
- }
4189
- };
4190
-
4191
- // src/repositories/discount-code/index.ts
4192
- var DiscountCodeRepository = class extends AbstractResourceRepository {
4193
- constructor(storage) {
4194
- super("discount-code", storage);
4195
- this.actions = new DiscountCodeUpdateHandler(storage);
4196
- }
4197
- create(context, draft) {
4198
- const resource = {
4199
- ...getBaseResourceProperties(),
4200
- applicationVersion: 1,
4201
- cartDiscounts: draft.cartDiscounts.map(
4202
- (obj) => ({
4203
- typeId: "cart-discount",
4204
- id: obj.id
4205
- })
4206
- ),
4207
- cartPredicate: draft.cartPredicate,
4208
- code: draft.code,
4209
- description: draft.description,
4210
- groups: draft.groups || [],
4211
- isActive: draft.isActive || true,
4212
- name: draft.name,
4213
- references: [],
4214
- validFrom: draft.validFrom,
4215
- validUntil: draft.validUntil,
4216
- maxApplications: draft.maxApplications,
4217
- maxApplicationsPerCustomer: draft.maxApplicationsPerCustomer,
4218
- custom: createCustomFields(
4219
- draft.custom,
4220
- context.projectKey,
4221
- this._storage
4222
- )
4223
- };
4224
- return this.saveNew(context, resource);
4196
+ setDateOfBirth(context, resource, action) {
4197
+ resource.dateOfBirth = action.dateOfBirth;
4225
4198
  }
4226
- };
4227
-
4228
- // src/lib/masking.ts
4229
- var maskSecretValue = (resource, path) => {
4230
- const parts = path.split(".");
4231
- const clone = cloneObject(resource);
4232
- let val = clone;
4233
- const target = parts.pop();
4234
- for (let i = 0; i < parts.length; i++) {
4235
- const part = parts[i];
4236
- val = val[part];
4237
- if (val === void 0) {
4238
- return resource;
4199
+ setDefaultBillingAddress(context, resource, action) {
4200
+ const address = this._findAddress(
4201
+ resource,
4202
+ action.addressId,
4203
+ action.addressKey,
4204
+ true
4205
+ );
4206
+ (0, import_node_assert.default)(address?.id);
4207
+ resource.defaultBillingAddressId = address.id;
4208
+ if (resource.billingAddressIds === void 0) {
4209
+ resource.billingAddressIds = [];
4210
+ }
4211
+ if (!resource.billingAddressIds.includes(address.id)) {
4212
+ resource.billingAddressIds.push(address.id);
4239
4213
  }
4240
4214
  }
4241
- if (val && target && val[target]) {
4242
- val[target] = "****";
4243
- }
4244
- return clone;
4245
- };
4246
-
4247
- // src/repositories/extension.ts
4248
- var ExtensionRepository = class extends AbstractResourceRepository {
4249
- constructor(storage) {
4250
- super("extension", storage);
4251
- this.actions = new ExtensionUpdateHandler(storage);
4252
- }
4253
- create(context, draft) {
4254
- const resource = {
4255
- ...getBaseResourceProperties(),
4256
- key: draft.key,
4257
- timeoutInMs: draft.timeoutInMs,
4258
- destination: draft.destination,
4259
- triggers: draft.triggers
4260
- };
4261
- return this.saveNew(context, resource);
4262
- }
4263
- postProcessResource(context, resource) {
4264
- if (resource) {
4265
- const extension = resource;
4266
- if (extension.destination.type === "HTTP" && extension.destination.authentication?.type === "AuthorizationHeader") {
4267
- return maskSecretValue(
4268
- extension,
4269
- "destination.authentication.headerValue"
4270
- );
4271
- } else if (extension.destination.type === "AWSLambda") {
4272
- return maskSecretValue(resource, "destination.accessSecret");
4273
- }
4215
+ setDefaultShippingAddress(context, resource, action) {
4216
+ const address = this._findAddress(
4217
+ resource,
4218
+ action.addressId,
4219
+ action.addressKey,
4220
+ true
4221
+ );
4222
+ (0, import_node_assert.default)(address?.id);
4223
+ resource.defaultShippingAddressId = address.id;
4224
+ if (resource.shippingAddressIds === void 0) {
4225
+ resource.shippingAddressIds = [];
4226
+ }
4227
+ if (!resource.shippingAddressIds.includes(address.id)) {
4228
+ resource.shippingAddressIds.push(address.id);
4274
4229
  }
4275
- return resource;
4276
4230
  }
4277
- };
4278
- var ExtensionUpdateHandler = class extends AbstractUpdateHandler {
4279
- changeDestination(context, resource, action) {
4280
- resource.destination = action.destination;
4231
+ setExternalId(_context, resource, { externalId }) {
4232
+ resource.externalId = externalId;
4281
4233
  }
4282
- changeTriggers(context, resource, action) {
4283
- resource.triggers = action.triggers;
4234
+ setFirstName(_context, resource, { firstName }) {
4235
+ resource.firstName = firstName;
4284
4236
  }
4285
- setKey(context, resource, action) {
4286
- resource.key = action.key;
4237
+ setKey(_context, resource, { key }) {
4238
+ resource.key = key;
4287
4239
  }
4288
- setTimeoutInMs(context, resource, action) {
4289
- resource.timeoutInMs = action.timeoutInMs;
4240
+ setLastName(_context, resource, { lastName }) {
4241
+ resource.lastName = lastName;
4290
4242
  }
4291
- };
4292
-
4293
- // src/repositories/inventory-entry/actions.ts
4294
- var InventoryEntryUpdateHandler = class extends AbstractUpdateHandler {
4295
- changeQuantity(context, resource, { quantity }) {
4296
- resource.quantityOnStock = quantity;
4297
- resource.availableQuantity = quantity;
4243
+ setLocale(_context, resource, { locale }) {
4244
+ resource.locale = locale;
4298
4245
  }
4299
- setCustomField(context, resource, { name, value }) {
4300
- if (!resource.custom) {
4301
- throw new Error("Resource has no custom field");
4302
- }
4303
- resource.custom.fields[name] = value;
4246
+ setMiddleName(context, resource, action) {
4247
+ resource.middleName = action.middleName;
4304
4248
  }
4305
- setCustomType(context, resource, { type, fields }) {
4306
- if (!type) {
4307
- resource.custom = void 0;
4308
- } else {
4309
- const resolvedType = this._storage.getByResourceIdentifier(
4310
- context.projectKey,
4311
- type
4312
- );
4313
- if (!resolvedType) {
4314
- throw new Error(`Type ${type} not found`);
4249
+ setSalutation(_context, resource, { salutation }) {
4250
+ resource.salutation = salutation;
4251
+ }
4252
+ setStores(context, resource, action) {
4253
+ throw new Error("Method not implemented.");
4254
+ }
4255
+ setTitle(context, resource, action) {
4256
+ resource.title = action.title;
4257
+ }
4258
+ setVatId(_context, resource, { vatId }) {
4259
+ resource.vatId = vatId;
4260
+ }
4261
+ _findAddress(resource, addressId, addressKey, required = false) {
4262
+ if (addressKey) {
4263
+ const address = resource.addresses.find((a) => a.key === addressKey);
4264
+ if (!address) {
4265
+ throw new CommercetoolsError(
4266
+ {
4267
+ code: "InvalidOperation",
4268
+ message: `Customer does not contain an address with the key ${addressKey}.`
4269
+ },
4270
+ 400
4271
+ );
4315
4272
  }
4316
- resource.custom = {
4317
- type: {
4318
- typeId: "type",
4319
- id: resolvedType.id
4273
+ return address;
4274
+ }
4275
+ if (addressId) {
4276
+ const address = resource.addresses.find((a) => a.id === addressId);
4277
+ if (!address) {
4278
+ throw new CommercetoolsError(
4279
+ {
4280
+ code: "InvalidOperation",
4281
+ message: `Customer does not contain an address with the id ${addressId}.`
4282
+ },
4283
+ 400
4284
+ );
4285
+ }
4286
+ return address;
4287
+ }
4288
+ if (required) {
4289
+ throw new CommercetoolsError(
4290
+ {
4291
+ code: "InvalidOperation",
4292
+ message: "One of address 'addressId' or 'addressKey' is required."
4320
4293
  },
4321
- fields: fields || {}
4322
- };
4294
+ 400
4295
+ );
4323
4296
  }
4324
4297
  }
4325
- setExpectedDelivery(context, resource, { expectedDelivery }) {
4326
- resource.expectedDelivery = new Date(expectedDelivery).toISOString();
4327
- }
4328
- setRestockableInDays(context, resource, { restockableInDays }) {
4329
- resource.restockableInDays = restockableInDays;
4330
- }
4331
4298
  };
4332
4299
 
4333
- // src/repositories/inventory-entry/index.ts
4334
- var InventoryEntryRepository = class extends AbstractResourceRepository {
4300
+ // src/repositories/customer/index.ts
4301
+ var CustomerRepository = class extends AbstractResourceRepository {
4335
4302
  constructor(storage) {
4336
- super("inventory-entry", storage);
4337
- this.actions = new InventoryEntryUpdateHandler(storage);
4303
+ super("customer", storage);
4304
+ this.actions = new CustomerUpdateHandler(storage);
4338
4305
  }
4339
4306
  create(context, draft) {
4307
+ const results = this._storage.query(context.projectKey, this.getTypeId(), {
4308
+ where: [`lowercaseEmail="${draft.email.toLowerCase()}"`]
4309
+ });
4310
+ if (results.count > 0) {
4311
+ throw new CommercetoolsError({
4312
+ code: "CustomerAlreadyExists",
4313
+ statusCode: 400,
4314
+ message: "There is already an existing customer with the provided email.",
4315
+ errors: [
4316
+ {
4317
+ code: "DuplicateField",
4318
+ message: `Customer with email '${draft.email}' already exists.`,
4319
+ duplicateValue: draft.email,
4320
+ field: "email"
4321
+ }
4322
+ ]
4323
+ });
4324
+ }
4325
+ const addresses = draft.addresses?.map((address) => ({
4326
+ ...address,
4327
+ id: generateRandomString(5)
4328
+ })) ?? [];
4329
+ const lookupAdressId = (addresses2, addressId) => {
4330
+ if (addressId < addresses2.length) {
4331
+ const id = addresses2[addressId].id;
4332
+ if (!id) {
4333
+ throw new Error("Address ID is missing");
4334
+ }
4335
+ return id;
4336
+ }
4337
+ throw new CommercetoolsError({
4338
+ code: "InvalidInput",
4339
+ message: `Address with ID '${addressId}' not found.`,
4340
+ errors: [
4341
+ {
4342
+ code: "InvalidInput",
4343
+ message: `Address with ID '${addressId}' not found.`,
4344
+ field: "addressId"
4345
+ }
4346
+ ]
4347
+ });
4348
+ };
4349
+ const defaultBillingAddressId = draft.defaultBillingAddress !== void 0 ? lookupAdressId(addresses, draft.defaultBillingAddress) : void 0;
4350
+ const defaultShippingAddressId = draft.defaultShippingAddress !== void 0 ? lookupAdressId(addresses, draft.defaultShippingAddress) : void 0;
4351
+ const shippingAddressIds = draft.shippingAddresses?.map(
4352
+ (addressId) => lookupAdressId(addresses, addressId)
4353
+ ) ?? [];
4354
+ const billingAddressIds = draft.billingAddresses?.map(
4355
+ (addressId) => lookupAdressId(addresses, addressId)
4356
+ ) ?? [];
4357
+ let storesForCustomer = [];
4358
+ if (draft.stores && draft.stores.length > 0) {
4359
+ storesForCustomer = this.storeReferenceToStoreKeyReference(
4360
+ draft.stores,
4361
+ context.projectKey
4362
+ );
4363
+ }
4340
4364
  const resource = {
4341
4365
  ...getBaseResourceProperties(),
4342
- sku: draft.sku,
4343
- quantityOnStock: draft.quantityOnStock,
4344
- availableQuantity: draft.quantityOnStock,
4345
- expectedDelivery: draft.expectedDelivery,
4346
- restockableInDays: draft.restockableInDays,
4347
- supplyChannel: {
4348
- ...draft.supplyChannel,
4349
- typeId: "channel",
4350
- id: draft.supplyChannel?.id ?? ""
4351
- },
4366
+ key: draft.key,
4367
+ authenticationMode: draft.authenticationMode || "Password",
4368
+ firstName: draft.firstName,
4369
+ lastName: draft.lastName,
4370
+ middleName: draft.middleName,
4371
+ title: draft.title,
4372
+ dateOfBirth: draft.dateOfBirth,
4373
+ companyName: draft.companyName,
4374
+ email: draft.email.toLowerCase(),
4375
+ lowercaseEmail: draft.email.toLowerCase(),
4376
+ password: draft.password ? hashPassword(draft.password) : void 0,
4377
+ isEmailVerified: draft.isEmailVerified || false,
4378
+ addresses,
4379
+ customerNumber: draft.customerNumber,
4380
+ externalId: draft.externalId,
4381
+ defaultBillingAddressId,
4382
+ defaultShippingAddressId,
4383
+ shippingAddressIds,
4384
+ billingAddressIds,
4352
4385
  custom: createCustomFields(
4353
4386
  draft.custom,
4354
4387
  context.projectKey,
4355
4388
  this._storage
4356
- )
4389
+ ),
4390
+ stores: storesForCustomer
4357
4391
  };
4358
4392
  return this.saveNew(context, resource);
4359
4393
  }
4360
- };
4361
-
4362
- // src/repositories/my-customer.ts
4363
- var MyCustomerRepository = class extends CustomerRepository {
4364
- changePassword(context, changePassword) {
4365
- const { currentPassword, newPassword } = changePassword;
4366
- const encodedPassword = hashPassword(currentPassword);
4367
- const result = this._storage.query(context.projectKey, "customer", {
4368
- where: [`password = "${encodedPassword}"`]
4394
+ saveUpdate(context, version, resource) {
4395
+ const updatedResource = {
4396
+ ...resource,
4397
+ lowercaseEmail: resource.email.toLowerCase()
4398
+ };
4399
+ return super.saveUpdate(context, version, updatedResource);
4400
+ }
4401
+ passwordResetToken(context, request) {
4402
+ const results = this._storage.query(context.projectKey, this.getTypeId(), {
4403
+ where: [`email="${request.email.toLocaleLowerCase()}"`]
4369
4404
  });
4370
- if (result.count === 0) {
4371
- throw new CommercetoolsError({
4372
- code: "InvalidCurrentPassword",
4373
- message: "Account with the given credentials not found."
4374
- });
4375
- }
4376
- const customer = result.results[0];
4377
- if (customer.password !== hashPassword(currentPassword)) {
4405
+ if (results.count === 0) {
4378
4406
  throw new CommercetoolsError({
4379
- code: "InvalidCurrentPassword",
4380
- message: "The current password is invalid."
4407
+ code: "ResourceNotFound",
4408
+ message: `The Customer with ID '${request.email}' was not found.`
4381
4409
  });
4382
4410
  }
4383
- customer.password = hashPassword(newPassword);
4384
- customer.version += 1;
4385
- this._storage.add(context.projectKey, "customer", customer);
4386
- return customer;
4411
+ const ttlMinutes = request.ttlMinutes ?? 34560;
4412
+ const expiresAt = new Date((/* @__PURE__ */ new Date()).getTime() + ttlMinutes * 60 * 1e3);
4413
+ const customer = results.results[0];
4414
+ const rest = getBaseResourceProperties();
4415
+ const token = createPasswordResetToken(customer, expiresAt);
4416
+ return {
4417
+ id: rest.id,
4418
+ createdAt: rest.createdAt,
4419
+ lastModifiedAt: rest.lastModifiedAt,
4420
+ customerId: customer.id,
4421
+ expiresAt: expiresAt.toISOString(),
4422
+ value: token
4423
+ };
4387
4424
  }
4388
- confirmEmail(context, resetPassword) {
4389
- const { tokenValue } = resetPassword;
4390
- const customerId = validateEmailVerifyToken(tokenValue);
4425
+ passwordReset(context, resetPassword) {
4426
+ const { newPassword, tokenValue } = resetPassword;
4427
+ const customerId = validatePasswordResetToken(tokenValue);
4391
4428
  if (!customerId) {
4392
4429
  throw new CommercetoolsError({
4393
4430
  code: "ResourceNotFound",
@@ -4405,440 +4442,416 @@ var MyCustomerRepository = class extends CustomerRepository {
4405
4442
  message: `The Customer with ID 'Token(${tokenValue})' was not found.`
4406
4443
  });
4407
4444
  }
4408
- customer.isEmailVerified = true;
4445
+ customer.password = hashPassword(newPassword);
4409
4446
  customer.version += 1;
4410
4447
  this._storage.add(context.projectKey, "customer", customer);
4411
4448
  return customer;
4412
4449
  }
4413
- deleteMe(context) {
4414
- const results = this._storage.query(
4415
- context.projectKey,
4416
- this.getTypeId(),
4417
- {}
4418
- );
4419
- if (results.count > 0) {
4420
- return this.delete(context, results.results[0].id);
4450
+ verifyEmailToken(context, id) {
4451
+ const results = this._storage.query(context.projectKey, this.getTypeId(), {
4452
+ where: [`id="${id.toLocaleLowerCase()}"`]
4453
+ });
4454
+ if (results.count === 0) {
4455
+ throw new CommercetoolsError({
4456
+ code: "ResourceNotFound",
4457
+ message: `The Customer with ID '${id}' was not found.`
4458
+ });
4421
4459
  }
4422
- return;
4460
+ const expiresAt = new Date(Date.now() + 30 * 60);
4461
+ const customer = results.results[0];
4462
+ const rest = getBaseResourceProperties();
4463
+ const token = createEmailVerifyToken(customer);
4464
+ return {
4465
+ id: rest.id,
4466
+ createdAt: rest.createdAt,
4467
+ lastModifiedAt: rest.lastModifiedAt,
4468
+ customerId: customer.id,
4469
+ expiresAt: expiresAt.toISOString(),
4470
+ value: token
4471
+ };
4423
4472
  }
4424
- getMe(context) {
4425
- const results = this._storage.query(
4426
- context.projectKey,
4427
- this.getTypeId(),
4428
- {}
4429
- );
4430
- if (results.count > 0) {
4431
- return results.results[0];
4473
+ storeReferenceToStoreKeyReference(draftStores, projectKey) {
4474
+ const storeIds = draftStores.map((storeReference) => storeReference.id).filter(Boolean);
4475
+ let stores = [];
4476
+ if (storeIds.length > 0) {
4477
+ stores = this._storage.query(projectKey, "store", {
4478
+ where: storeIds.map((id) => `id="${id}"`)
4479
+ }).results;
4480
+ if (storeIds.length !== stores.length) {
4481
+ throw new CommercetoolsError({
4482
+ code: "ResourceNotFound",
4483
+ message: `Store with ID '${storeIds.find((id) => !stores.some((store) => store.id === id))}' was not found.`
4484
+ });
4485
+ }
4432
4486
  }
4433
- return;
4487
+ return draftStores.map((storeReference) => ({
4488
+ typeId: "store",
4489
+ key: storeReference.key ?? stores.find((store) => store.id === storeReference.id)?.key
4490
+ }));
4434
4491
  }
4435
4492
  };
4436
4493
 
4437
- // src/repositories/my-order.ts
4438
- var import_assert3 = __toESM(require("assert"), 1);
4439
-
4440
- // src/repositories/order/index.ts
4441
- var import_assert2 = __toESM(require("assert"), 1);
4442
-
4443
- // src/repositories/order/actions.ts
4444
- var OrderUpdateHandler = class extends AbstractUpdateHandler {
4445
- addPayment(context, resource, { payment }) {
4446
- const resolvedPayment = this._storage.getByResourceIdentifier(
4447
- context.projectKey,
4448
- payment
4449
- );
4450
- if (!resolvedPayment) {
4451
- throw new Error(`Payment ${payment.id} not found`);
4452
- }
4453
- if (!resource.paymentInfo) {
4454
- resource.paymentInfo = {
4455
- payments: []
4456
- };
4457
- }
4458
- resource.paymentInfo.payments.push({
4459
- typeId: "payment",
4460
- id: payment.id
4461
- });
4494
+ // src/repositories/customer-group.ts
4495
+ var CustomerGroupRepository = class extends AbstractResourceRepository {
4496
+ constructor(storage) {
4497
+ super("customer-group", storage);
4498
+ this.actions = new CustomerGroupUpdateHandler(storage);
4462
4499
  }
4463
- addReturnInfo(context, resource, info) {
4464
- if (!resource.returnInfo) {
4465
- resource.returnInfo = [];
4466
- }
4467
- const resolved = {
4468
- items: info.items.map((item) => {
4469
- const common = {
4470
- ...getBaseResourceProperties(),
4471
- quantity: item.quantity,
4472
- paymentState: "Initial",
4473
- shipmentState: "Initial",
4474
- comment: item.comment
4475
- };
4476
- if (item.customLineItemId) {
4477
- return {
4478
- ...common,
4479
- type: "CustomLineItemReturnItem",
4480
- customLineItemId: item.customLineItemId
4481
- };
4482
- }
4483
- return {
4484
- ...common,
4485
- type: "LineItemReturnItem",
4486
- lineItemId: item.customLineItemId || item.lineItemId
4487
- };
4488
- }),
4489
- returnTrackingId: info.returnTrackingId,
4490
- returnDate: info.returnDate
4500
+ create(context, draft) {
4501
+ const resource = {
4502
+ ...getBaseResourceProperties(),
4503
+ key: draft.key,
4504
+ name: draft.groupName,
4505
+ custom: createCustomFields(
4506
+ draft.custom,
4507
+ context.projectKey,
4508
+ this._storage
4509
+ )
4491
4510
  };
4492
- resource.returnInfo.push(resolved);
4493
- }
4494
- changeOrderState(context, resource, { orderState }) {
4495
- resource.orderState = orderState;
4496
- }
4497
- changePaymentState(context, resource, { paymentState }) {
4498
- resource.paymentState = paymentState;
4499
- }
4500
- changeShipmentState(context, resource, { shipmentState }) {
4501
- resource.shipmentState = shipmentState;
4502
- }
4503
- setBillingAddress(context, resource, { address }) {
4504
- resource.billingAddress = createAddress(
4505
- address,
4506
- context.projectKey,
4507
- this._storage
4508
- );
4509
- }
4510
- setCustomerEmail(context, resource, { email }) {
4511
- resource.customerEmail = email;
4511
+ return this.saveNew(context, resource);
4512
4512
  }
4513
- setCustomerId(context, resource, { customerId }) {
4514
- resource.customerId = customerId;
4513
+ };
4514
+ var CustomerGroupUpdateHandler = class extends AbstractUpdateHandler {
4515
+ changeName(context, resource, { name }) {
4516
+ resource.name = name;
4515
4517
  }
4516
4518
  setCustomField(context, resource, { name, value }) {
4517
4519
  if (!resource.custom) {
4518
- throw new Error("Resource has no custom field");
4520
+ return;
4521
+ }
4522
+ if (value === null) {
4523
+ delete resource.custom.fields[name];
4524
+ } else {
4525
+ resource.custom.fields[name] = value;
4519
4526
  }
4520
- resource.custom.fields[name] = value;
4521
4527
  }
4522
4528
  setCustomType(context, resource, { type, fields }) {
4523
- if (!type) {
4524
- resource.custom = void 0;
4525
- } else {
4526
- const resolvedType = this._storage.getByResourceIdentifier(
4529
+ if (type) {
4530
+ resource.custom = createCustomFields(
4531
+ { type, fields },
4527
4532
  context.projectKey,
4528
- type
4533
+ this._storage
4529
4534
  );
4530
- if (!resolvedType) {
4531
- throw new Error(`Type ${type} not found`);
4532
- }
4533
- resource.custom = {
4534
- type: {
4535
- typeId: "type",
4536
- id: resolvedType.id
4537
- },
4538
- fields: fields || {}
4539
- };
4540
- }
4541
- }
4542
- setDeliveryCustomField(context, resource, { deliveryId, name, value }) {
4543
- if (!resource.shippingInfo) {
4544
- throw new Error("Resource has no shipping info");
4545
- }
4546
- for (const delivery of resource.shippingInfo.deliveries || []) {
4547
- if (delivery.id === deliveryId && delivery.custom?.fields) {
4548
- delivery.custom.fields[name] = value;
4549
- }
4550
- }
4551
- }
4552
- setLocale(context, resource, { locale }) {
4553
- resource.locale = locale;
4554
- }
4555
- setOrderNumber(context, resource, { orderNumber }) {
4556
- resource.orderNumber = orderNumber;
4557
- }
4558
- setParcelCustomField(context, resource, { parcelId, name, value }) {
4559
- if (!resource.shippingInfo) {
4560
- throw new Error("Resource has no shipping info");
4561
- }
4562
- for (const delivery of resource.shippingInfo.deliveries || []) {
4563
- for (const parcel of delivery.parcels || []) {
4564
- if (parcel.id === parcelId && parcel.custom?.fields) {
4565
- parcel.custom.fields[name] = value;
4566
- }
4567
- }
4568
- }
4569
- }
4570
- setPurchaseOrderNumber(context, resource, { purchaseOrderNumber }) {
4571
- resource.purchaseOrderNumber = purchaseOrderNumber;
4572
- }
4573
- setShippingAddress(context, resource, { address }) {
4574
- resource.shippingAddress = createAddress(
4575
- address,
4576
- context.projectKey,
4577
- this._storage
4578
- );
4579
- }
4580
- setStore(context, resource, { store }) {
4581
- if (!store) return;
4582
- const resolvedType = this._storage.getByResourceIdentifier(
4583
- context.projectKey,
4584
- store
4585
- );
4586
- if (!resolvedType) {
4587
- throw new Error(`No store found with key=${store.key}`);
4535
+ } else {
4536
+ resource.custom = void 0;
4588
4537
  }
4589
- const storeReference = resolvedType;
4590
- resource.store = {
4591
- typeId: "store",
4592
- key: storeReference.key
4593
- };
4594
4538
  }
4595
- transitionState(context, resource, { state }) {
4596
- const resolvedType = this._storage.getByResourceIdentifier(
4597
- context.projectKey,
4598
- state
4599
- );
4600
- if (!resolvedType) {
4601
- throw new Error(
4602
- `No state found with key=${state.key} or id=${state.key}`
4603
- );
4604
- }
4605
- resource.state = {
4606
- typeId: "state",
4607
- id: resolvedType.id,
4608
- obj: { ...resolvedType, key: state.key ?? "" }
4609
- };
4539
+ setKey(context, resource, { key }) {
4540
+ resource.key = key;
4610
4541
  }
4611
- updateSyncInfo(context, resource, { channel, externalId, syncedAt }) {
4612
- if (!channel) return;
4613
- const resolvedType = this._storage.getByResourceIdentifier(
4614
- context.projectKey,
4615
- channel
4542
+ };
4543
+
4544
+ // src/repositories/discount-code/actions.ts
4545
+ var DiscountCodeUpdateHandler = class extends AbstractUpdateHandler {
4546
+ changeCartDiscounts(context, resource, { cartDiscounts }) {
4547
+ resource.cartDiscounts = cartDiscounts.map(
4548
+ (obj) => ({
4549
+ typeId: "cart-discount",
4550
+ id: obj.id
4551
+ })
4616
4552
  );
4617
- if (!resolvedType) {
4618
- throw new Error(`Channel ${channel} not found`);
4553
+ }
4554
+ changeIsActive(context, resource, { isActive }) {
4555
+ resource.isActive = isActive;
4556
+ }
4557
+ setCartPredicate(context, resource, { cartPredicate }) {
4558
+ resource.cartPredicate = cartPredicate;
4559
+ }
4560
+ setCustomField(context, resource, { name, value }) {
4561
+ if (!resource.custom) {
4562
+ return;
4619
4563
  }
4620
- const syncData = {
4621
- channel: {
4622
- typeId: "channel",
4623
- id: resolvedType.id
4624
- },
4625
- externalId,
4626
- syncedAt: syncedAt ?? (/* @__PURE__ */ new Date()).toISOString()
4627
- };
4628
- if (!resource.syncInfo?.length) {
4629
- resource.syncInfo = [syncData];
4564
+ if (value === null) {
4565
+ delete resource.custom.fields[name];
4630
4566
  } else {
4631
- const lastSyncInfo = resource.syncInfo[resource.syncInfo.length - 1];
4632
- if (lastSyncInfo.channel.id !== syncData.channel.id || lastSyncInfo.externalId !== syncData.externalId) {
4633
- resource.syncInfo.push(syncData);
4634
- }
4567
+ resource.custom.fields[name] = value;
4568
+ }
4569
+ }
4570
+ setCustomType(context, resource, { type, fields }) {
4571
+ if (type) {
4572
+ resource.custom = createCustomFields(
4573
+ { type, fields },
4574
+ context.projectKey,
4575
+ this._storage
4576
+ );
4577
+ } else {
4578
+ resource.custom = void 0;
4635
4579
  }
4636
4580
  }
4581
+ setDescription(context, resource, { description }) {
4582
+ resource.description = description;
4583
+ }
4584
+ setMaxApplications(context, resource, { maxApplications }) {
4585
+ resource.maxApplications = maxApplications;
4586
+ }
4587
+ setMaxApplicationsPerCustomer(context, resource, {
4588
+ maxApplicationsPerCustomer
4589
+ }) {
4590
+ resource.maxApplicationsPerCustomer = maxApplicationsPerCustomer;
4591
+ }
4592
+ setName(context, resource, { name }) {
4593
+ resource.name = name;
4594
+ }
4595
+ setValidFrom(context, resource, { validFrom }) {
4596
+ resource.validFrom = validFrom;
4597
+ }
4598
+ setValidFromAndUntil(context, resource, { validFrom, validUntil }) {
4599
+ resource.validFrom = validFrom;
4600
+ resource.validUntil = validUntil;
4601
+ }
4602
+ setValidUntil(context, resource, { validUntil }) {
4603
+ resource.validUntil = validUntil;
4604
+ }
4637
4605
  };
4638
4606
 
4639
- // src/repositories/order/index.ts
4640
- var OrderRepository = class extends AbstractResourceRepository {
4607
+ // src/repositories/discount-code/index.ts
4608
+ var DiscountCodeRepository = class extends AbstractResourceRepository {
4641
4609
  constructor(storage) {
4642
- super("order", storage);
4643
- this.actions = new OrderUpdateHandler(storage);
4610
+ super("discount-code", storage);
4611
+ this.actions = new DiscountCodeUpdateHandler(storage);
4644
4612
  }
4645
4613
  create(context, draft) {
4646
- (0, import_assert2.default)(draft.cart, "draft.cart is missing");
4647
- return this.createFromCart(
4648
- context,
4649
- {
4650
- id: draft.cart.id,
4651
- typeId: "cart"
4652
- },
4653
- draft.orderNumber
4654
- );
4655
- }
4656
- createFromCart(context, cartReference, orderNumber) {
4657
- const cart = this._storage.getByResourceIdentifier(
4658
- context.projectKey,
4659
- cartReference
4660
- );
4661
- if (!cart) {
4662
- throw new Error("Cannot find cart");
4663
- }
4664
- const resource = {
4665
- ...getBaseResourceProperties(),
4666
- anonymousId: cart.anonymousId,
4667
- billingAddress: cart.billingAddress,
4668
- cart: cartReference,
4669
- country: cart.country,
4670
- custom: cart.custom,
4671
- customerEmail: cart.customerEmail,
4672
- customerGroup: cart.customerGroup,
4673
- customerId: cart.customerId,
4674
- customLineItems: [],
4675
- directDiscounts: cart.directDiscounts,
4676
- discountCodes: cart.discountCodes,
4677
- discountOnTotalPrice: cart.discountOnTotalPrice,
4678
- lastMessageSequenceNumber: 0,
4679
- lineItems: cart.lineItems,
4680
- locale: cart.locale,
4681
- orderNumber: orderNumber ?? generateRandomString(10),
4682
- orderState: "Open",
4683
- origin: "Customer",
4684
- paymentInfo: cart.paymentInfo,
4685
- refusedGifts: [],
4686
- shipping: cart.shipping,
4687
- shippingAddress: cart.shippingAddress,
4688
- shippingMode: cart.shippingMode,
4689
- syncInfo: [],
4690
- taxCalculationMode: cart.taxCalculationMode,
4691
- taxedPrice: cart.taxedPrice,
4692
- taxedShippingPrice: cart.taxedShippingPrice,
4693
- taxMode: cart.taxMode,
4694
- taxRoundingMode: cart.taxRoundingMode,
4695
- totalPrice: cart.totalPrice,
4696
- store: cart.store
4697
- };
4698
- return this.saveNew(context, resource);
4699
- }
4700
- import(context, draft) {
4701
- (0, import_assert2.default)(this, "OrderRepository not valid");
4702
4614
  const resource = {
4703
4615
  ...getBaseResourceProperties(),
4704
- billingAddress: createAddress(
4705
- draft.billingAddress,
4706
- context.projectKey,
4707
- this._storage
4708
- ),
4709
- shippingAddress: createAddress(
4710
- draft.shippingAddress,
4711
- context.projectKey,
4712
- this._storage
4616
+ applicationVersion: 1,
4617
+ cartDiscounts: draft.cartDiscounts.map(
4618
+ (obj) => ({
4619
+ typeId: "cart-discount",
4620
+ id: obj.id
4621
+ })
4713
4622
  ),
4623
+ cartPredicate: draft.cartPredicate,
4624
+ code: draft.code,
4625
+ description: draft.description,
4626
+ groups: draft.groups || [],
4627
+ isActive: draft.isActive || true,
4628
+ name: draft.name,
4629
+ references: [],
4630
+ validFrom: draft.validFrom,
4631
+ validUntil: draft.validUntil,
4632
+ maxApplications: draft.maxApplications,
4633
+ maxApplicationsPerCustomer: draft.maxApplicationsPerCustomer,
4714
4634
  custom: createCustomFields(
4715
4635
  draft.custom,
4716
4636
  context.projectKey,
4717
4637
  this._storage
4718
- ),
4719
- customerEmail: draft.customerEmail,
4720
- lastMessageSequenceNumber: 0,
4721
- orderNumber: draft.orderNumber,
4722
- orderState: draft.orderState || "Open",
4723
- origin: draft.origin || "Customer",
4724
- paymentState: draft.paymentState,
4725
- refusedGifts: [],
4726
- shippingMode: "Single",
4727
- shipping: [],
4728
- store: resolveStoreReference(
4729
- draft.store,
4730
- context.projectKey,
4731
- this._storage
4732
- ),
4733
- syncInfo: [],
4734
- lineItems: draft.lineItems?.map(
4735
- (item) => this.lineItemFromImportDraft.bind(this)(context, item)
4736
- ) || [],
4737
- customLineItems: draft.customLineItems?.map(
4738
- (item) => this.customLineItemFromImportDraft.bind(this)(context, item)
4739
- ) || [],
4740
- totalPrice: createCentPrecisionMoney(draft.totalPrice)
4638
+ )
4741
4639
  };
4742
4640
  return this.saveNew(context, resource);
4743
4641
  }
4744
- lineItemFromImportDraft(context, draft) {
4745
- let product;
4746
- let variant;
4747
- if (draft.variant.sku) {
4748
- variant = {
4749
- id: 0,
4750
- sku: draft.variant.sku
4751
- };
4752
- const items = this._storage.query(context.projectKey, "product", {
4753
- where: [
4754
- `masterData(current(masterVariant(sku="${draft.variant.sku}"))) or masterData(current(variants(sku="${draft.variant.sku}")))`
4755
- ]
4756
- });
4757
- if (items.count !== 1) {
4758
- throw new CommercetoolsError({
4759
- code: "General",
4760
- message: `A product containing a variant with SKU '${draft.variant.sku}' not found.`
4761
- });
4762
- }
4763
- product = items.results[0];
4764
- if (product.masterData.current.masterVariant.sku === draft.variant.sku) {
4765
- variant = product.masterData.current.masterVariant;
4766
- } else {
4767
- variant = product.masterData.current.variants.find(
4768
- (v) => v.sku === draft.variant.sku
4642
+ };
4643
+
4644
+ // src/lib/masking.ts
4645
+ var maskSecretValue = (resource, path) => {
4646
+ const parts = path.split(".");
4647
+ const clone = cloneObject(resource);
4648
+ let val = clone;
4649
+ const target = parts.pop();
4650
+ for (let i = 0; i < parts.length; i++) {
4651
+ const part = parts[i];
4652
+ val = val[part];
4653
+ if (val === void 0) {
4654
+ return resource;
4655
+ }
4656
+ }
4657
+ if (val && target && val[target]) {
4658
+ val[target] = "****";
4659
+ }
4660
+ return clone;
4661
+ };
4662
+
4663
+ // src/repositories/extension.ts
4664
+ var ExtensionRepository = class extends AbstractResourceRepository {
4665
+ constructor(storage) {
4666
+ super("extension", storage);
4667
+ this.actions = new ExtensionUpdateHandler(storage);
4668
+ }
4669
+ create(context, draft) {
4670
+ const resource = {
4671
+ ...getBaseResourceProperties(),
4672
+ key: draft.key,
4673
+ timeoutInMs: draft.timeoutInMs,
4674
+ destination: draft.destination,
4675
+ triggers: draft.triggers
4676
+ };
4677
+ return this.saveNew(context, resource);
4678
+ }
4679
+ postProcessResource(context, resource) {
4680
+ if (resource) {
4681
+ const extension = resource;
4682
+ if (extension.destination.type === "HTTP" && extension.destination.authentication?.type === "AuthorizationHeader") {
4683
+ return maskSecretValue(
4684
+ extension,
4685
+ "destination.authentication.headerValue"
4769
4686
  );
4687
+ } else if (extension.destination.type === "AWSLambda") {
4688
+ return maskSecretValue(resource, "destination.accessSecret");
4770
4689
  }
4771
- if (!variant) {
4772
- throw new Error("Internal state error");
4773
- }
4774
- } else {
4775
- throw new Error("No product found");
4776
4690
  }
4777
- const lineItem = {
4778
- ...getBaseResourceProperties(),
4779
- custom: createCustomFields(
4780
- draft.custom,
4691
+ return resource;
4692
+ }
4693
+ };
4694
+ var ExtensionUpdateHandler = class extends AbstractUpdateHandler {
4695
+ changeDestination(context, resource, action) {
4696
+ resource.destination = action.destination;
4697
+ }
4698
+ changeTriggers(context, resource, action) {
4699
+ resource.triggers = action.triggers;
4700
+ }
4701
+ setKey(context, resource, action) {
4702
+ resource.key = action.key;
4703
+ }
4704
+ setTimeoutInMs(context, resource, action) {
4705
+ resource.timeoutInMs = action.timeoutInMs;
4706
+ }
4707
+ };
4708
+
4709
+ // src/repositories/inventory-entry/actions.ts
4710
+ var InventoryEntryUpdateHandler = class extends AbstractUpdateHandler {
4711
+ changeQuantity(context, resource, { quantity }) {
4712
+ resource.quantityOnStock = quantity;
4713
+ resource.availableQuantity = quantity;
4714
+ }
4715
+ setCustomField(context, resource, { name, value }) {
4716
+ if (!resource.custom) {
4717
+ throw new Error("Resource has no custom field");
4718
+ }
4719
+ resource.custom.fields[name] = value;
4720
+ }
4721
+ setCustomType(context, resource, { type, fields }) {
4722
+ if (!type) {
4723
+ resource.custom = void 0;
4724
+ } else {
4725
+ const resolvedType = this._storage.getByResourceIdentifier(
4781
4726
  context.projectKey,
4782
- this._storage
4783
- ),
4784
- discountedPricePerQuantity: [],
4785
- lineItemMode: "Standard",
4786
- name: draft.name,
4787
- price: createPrice(draft.price),
4788
- priceMode: "Platform",
4789
- productId: product.id,
4790
- productType: product.productType,
4791
- quantity: draft.quantity,
4792
- state: draft.state || [],
4793
- taxRate: draft.taxRate,
4794
- taxedPricePortions: [],
4795
- perMethodTaxRate: [],
4796
- totalPrice: createCentPrecisionMoney(draft.price.value),
4797
- variant: {
4798
- id: variant.id,
4799
- sku: variant.sku,
4800
- price: createPrice(draft.price)
4727
+ type
4728
+ );
4729
+ if (!resolvedType) {
4730
+ throw new Error(`Type ${type} not found`);
4801
4731
  }
4802
- };
4803
- return lineItem;
4732
+ resource.custom = {
4733
+ type: {
4734
+ typeId: "type",
4735
+ id: resolvedType.id
4736
+ },
4737
+ fields: fields || {}
4738
+ };
4739
+ }
4804
4740
  }
4805
- customLineItemFromImportDraft(context, draft) {
4806
- const lineItem = {
4741
+ setExpectedDelivery(context, resource, { expectedDelivery }) {
4742
+ resource.expectedDelivery = new Date(expectedDelivery).toISOString();
4743
+ }
4744
+ setRestockableInDays(context, resource, { restockableInDays }) {
4745
+ resource.restockableInDays = restockableInDays;
4746
+ }
4747
+ };
4748
+
4749
+ // src/repositories/inventory-entry/index.ts
4750
+ var InventoryEntryRepository = class extends AbstractResourceRepository {
4751
+ constructor(storage) {
4752
+ super("inventory-entry", storage);
4753
+ this.actions = new InventoryEntryUpdateHandler(storage);
4754
+ }
4755
+ create(context, draft) {
4756
+ const resource = {
4807
4757
  ...getBaseResourceProperties(),
4758
+ sku: draft.sku,
4759
+ quantityOnStock: draft.quantityOnStock,
4760
+ availableQuantity: draft.quantityOnStock,
4761
+ expectedDelivery: draft.expectedDelivery,
4762
+ restockableInDays: draft.restockableInDays,
4763
+ supplyChannel: {
4764
+ ...draft.supplyChannel,
4765
+ typeId: "channel",
4766
+ id: draft.supplyChannel?.id ?? ""
4767
+ },
4808
4768
  custom: createCustomFields(
4809
4769
  draft.custom,
4810
4770
  context.projectKey,
4811
4771
  this._storage
4812
- ),
4813
- discountedPricePerQuantity: [],
4814
- money: createTypedMoney(draft.money),
4815
- name: draft.name,
4816
- quantity: draft.quantity ?? 0,
4817
- perMethodTaxRate: [],
4818
- priceMode: draft.priceMode ?? "Standard",
4819
- slug: draft.slug,
4820
- state: [],
4821
- totalPrice: createCentPrecisionMoney(draft.money),
4822
- taxedPricePortions: []
4772
+ )
4823
4773
  };
4824
- return lineItem;
4774
+ return this.saveNew(context, resource);
4825
4775
  }
4826
- getWithOrderNumber(context, orderNumber, params = {}) {
4827
- const result = this._storage.query(context.projectKey, this.getTypeId(), {
4828
- ...params,
4829
- where: [`orderNumber="${orderNumber}"`]
4776
+ };
4777
+
4778
+ // src/repositories/my-customer.ts
4779
+ var MyCustomerRepository = class extends CustomerRepository {
4780
+ changePassword(context, changePassword) {
4781
+ const { currentPassword, newPassword } = changePassword;
4782
+ const encodedPassword = hashPassword(currentPassword);
4783
+ const result = this._storage.query(context.projectKey, "customer", {
4784
+ where: [`password = "${encodedPassword}"`]
4830
4785
  });
4831
- if (result.count === 1) {
4832
- return result.results[0];
4786
+ if (result.count === 0) {
4787
+ throw new CommercetoolsError({
4788
+ code: "InvalidCurrentPassword",
4789
+ message: "Account with the given credentials not found."
4790
+ });
4833
4791
  }
4834
- if (result.count > 1) {
4835
- throw new Error("Duplicate order numbers");
4792
+ const customer = result.results[0];
4793
+ if (customer.password !== hashPassword(currentPassword)) {
4794
+ throw new CommercetoolsError({
4795
+ code: "InvalidCurrentPassword",
4796
+ message: "The current password is invalid."
4797
+ });
4798
+ }
4799
+ customer.password = hashPassword(newPassword);
4800
+ customer.version += 1;
4801
+ this._storage.add(context.projectKey, "customer", customer);
4802
+ return customer;
4803
+ }
4804
+ confirmEmail(context, resetPassword) {
4805
+ const { tokenValue } = resetPassword;
4806
+ const customerId = validateEmailVerifyToken(tokenValue);
4807
+ if (!customerId) {
4808
+ throw new CommercetoolsError({
4809
+ code: "ResourceNotFound",
4810
+ message: `The Customer with ID 'Token(${tokenValue})' was not found.`
4811
+ });
4812
+ }
4813
+ const customer = this._storage.get(
4814
+ context.projectKey,
4815
+ "customer",
4816
+ customerId
4817
+ );
4818
+ if (!customer) {
4819
+ throw new CommercetoolsError({
4820
+ code: "ResourceNotFound",
4821
+ message: `The Customer with ID 'Token(${tokenValue})' was not found.`
4822
+ });
4823
+ }
4824
+ customer.isEmailVerified = true;
4825
+ customer.version += 1;
4826
+ this._storage.add(context.projectKey, "customer", customer);
4827
+ return customer;
4828
+ }
4829
+ deleteMe(context) {
4830
+ const results = this._storage.query(
4831
+ context.projectKey,
4832
+ this.getTypeId(),
4833
+ {}
4834
+ );
4835
+ if (results.count > 0) {
4836
+ return this.delete(context, results.results[0].id);
4837
+ }
4838
+ return;
4839
+ }
4840
+ getMe(context) {
4841
+ const results = this._storage.query(
4842
+ context.projectKey,
4843
+ this.getTypeId(),
4844
+ {}
4845
+ );
4846
+ if (results.count > 0) {
4847
+ return results.results[0];
4836
4848
  }
4837
4849
  return;
4838
4850
  }
4839
4851
  };
4840
4852
 
4841
4853
  // src/repositories/my-order.ts
4854
+ var import_assert3 = __toESM(require("assert"), 1);
4842
4855
  var MyOrderRepository = class extends OrderRepository {
4843
4856
  create(context, draft) {
4844
4857
  (0, import_assert3.default)(draft.id, "draft.id is missing");
@@ -7996,6 +8009,10 @@ var ZoneUpdateHandler = class extends AbstractUpdateHandler {
7996
8009
 
7997
8010
  // src/repositories/index.ts
7998
8011
  var createRepositories = (storage) => ({
8012
+ "as-associate": {
8013
+ cart: new AsAssociateCartRepository(storage),
8014
+ order: new AsAssociateOrderRepository(storage)
8015
+ },
7999
8016
  "associate-role": new AssociateRoleRepository(storage),
8000
8017
  "attribute-group": new AttributeGroupRepository(storage),
8001
8018
  "business-unit": new BusinessUnitRepository(storage),
@@ -8039,6 +8056,12 @@ var createRepositories = (storage) => ({
8039
8056
  "zone": new ZoneRepository(storage)
8040
8057
  });
8041
8058
 
8059
+ // src/services/as-associate.ts
8060
+ var import_express5 = require("express");
8061
+
8062
+ // src/services/as-associate-cart.ts
8063
+ var import_express3 = require("express");
8064
+
8042
8065
  // src/services/abstract.ts
8043
8066
  var import_express2 = require("express");
8044
8067
 
@@ -8228,6 +8251,70 @@ var AbstractService = class {
8228
8251
  }
8229
8252
  };
8230
8253
 
8254
+ // src/services/as-associate-cart.ts
8255
+ var AsAssociateCartService = class extends AbstractService {
8256
+ repository;
8257
+ constructor(parent, repository) {
8258
+ super(parent);
8259
+ this.repository = repository;
8260
+ }
8261
+ getBasePath() {
8262
+ return "carts";
8263
+ }
8264
+ registerRoutes(parent) {
8265
+ const basePath = this.getBasePath();
8266
+ const router = (0, import_express3.Router)({ mergeParams: true });
8267
+ this.extraRoutes(router);
8268
+ router.get("/", this.get.bind(this));
8269
+ router.get("/:id", this.getWithId.bind(this));
8270
+ router.delete("/:id", this.deleteWithId.bind(this));
8271
+ router.post("/", this.post.bind(this));
8272
+ router.post("/:id", this.postWithId.bind(this));
8273
+ parent.use(`/${basePath}`, router);
8274
+ }
8275
+ };
8276
+
8277
+ // src/services/as-associate-order.ts
8278
+ var import_express4 = require("express");
8279
+ var AsAssociateOrderService = class extends AbstractService {
8280
+ repository;
8281
+ constructor(parent, repository) {
8282
+ super(parent);
8283
+ this.repository = repository;
8284
+ }
8285
+ getBasePath() {
8286
+ return "orders";
8287
+ }
8288
+ registerRoutes(parent) {
8289
+ const basePath = this.getBasePath();
8290
+ const router = (0, import_express4.Router)({ mergeParams: true });
8291
+ this.extraRoutes(router);
8292
+ router.get("/", this.get.bind(this));
8293
+ router.get("/:id", this.getWithId.bind(this));
8294
+ router.delete("/:id", this.deleteWithId.bind(this));
8295
+ router.post("/", this.post.bind(this));
8296
+ router.post("/:id", this.postWithId.bind(this));
8297
+ parent.use(`/${basePath}`, router);
8298
+ }
8299
+ };
8300
+
8301
+ // src/services/as-associate.ts
8302
+ var AsAssociateService = class {
8303
+ router;
8304
+ subServices;
8305
+ constructor(parent, repositories) {
8306
+ this.router = (0, import_express5.Router)({ mergeParams: true });
8307
+ this.subServices = {
8308
+ order: new AsAssociateOrderService(this.router, repositories.order),
8309
+ cart: new AsAssociateCartService(this.router, repositories.cart)
8310
+ };
8311
+ parent.use(
8312
+ "/as-associate/:associateId/in-business-unit/key=:businessUnitId",
8313
+ this.router
8314
+ );
8315
+ }
8316
+ };
8317
+
8231
8318
  // src/services/associate-roles.ts
8232
8319
  var AssociateRoleServices = class extends AbstractService {
8233
8320
  repository;
@@ -8509,7 +8596,7 @@ var InventoryEntryService = class extends AbstractService {
8509
8596
  };
8510
8597
 
8511
8598
  // src/services/my-business-unit.ts
8512
- var import_express3 = require("express");
8599
+ var import_express6 = require("express");
8513
8600
  var MyBusinessUnitService = class extends AbstractService {
8514
8601
  repository;
8515
8602
  constructor(parent, repository) {
@@ -8521,7 +8608,7 @@ var MyBusinessUnitService = class extends AbstractService {
8521
8608
  }
8522
8609
  registerRoutes(parent) {
8523
8610
  const basePath = this.getBasePath();
8524
- const router = (0, import_express3.Router)({ mergeParams: true });
8611
+ const router = (0, import_express6.Router)({ mergeParams: true });
8525
8612
  this.extraRoutes(router);
8526
8613
  router.get("/business-units/", this.get.bind(this));
8527
8614
  parent.use(`/${basePath}`, router);
@@ -8529,7 +8616,7 @@ var MyBusinessUnitService = class extends AbstractService {
8529
8616
  };
8530
8617
 
8531
8618
  // src/services/my-cart.ts
8532
- var import_express4 = require("express");
8619
+ var import_express7 = require("express");
8533
8620
  var MyCartService = class extends AbstractService {
8534
8621
  repository;
8535
8622
  constructor(parent, repository) {
@@ -8541,7 +8628,7 @@ var MyCartService = class extends AbstractService {
8541
8628
  }
8542
8629
  registerRoutes(parent) {
8543
8630
  const basePath = this.getBasePath();
8544
- const router = (0, import_express4.Router)({ mergeParams: true });
8631
+ const router = (0, import_express7.Router)({ mergeParams: true });
8545
8632
  this.extraRoutes(router);
8546
8633
  router.get("/active-cart", this.activeCart.bind(this));
8547
8634
  router.get("/carts/", this.get.bind(this));
@@ -8561,7 +8648,7 @@ var MyCartService = class extends AbstractService {
8561
8648
  };
8562
8649
 
8563
8650
  // src/services/my-customer.ts
8564
- var import_express5 = require("express");
8651
+ var import_express8 = require("express");
8565
8652
  var MyCustomerService = class extends AbstractService {
8566
8653
  repository;
8567
8654
  constructor(parent, repository) {
@@ -8573,7 +8660,7 @@ var MyCustomerService = class extends AbstractService {
8573
8660
  }
8574
8661
  registerRoutes(parent) {
8575
8662
  const basePath = this.getBasePath();
8576
- const router = (0, import_express5.Router)({ mergeParams: true });
8663
+ const router = (0, import_express8.Router)({ mergeParams: true });
8577
8664
  this.extraRoutes(router);
8578
8665
  router.get("", this.getMe.bind(this));
8579
8666
  router.post("", this.updateMe.bind(this));
@@ -8669,7 +8756,7 @@ var MyCustomerService = class extends AbstractService {
8669
8756
  };
8670
8757
 
8671
8758
  // src/services/my-order.ts
8672
- var import_express6 = require("express");
8759
+ var import_express9 = require("express");
8673
8760
  var MyOrderService = class extends AbstractService {
8674
8761
  repository;
8675
8762
  constructor(parent, repository) {
@@ -8681,7 +8768,7 @@ var MyOrderService = class extends AbstractService {
8681
8768
  }
8682
8769
  registerRoutes(parent) {
8683
8770
  const basePath = this.getBasePath();
8684
- const router = (0, import_express6.Router)({ mergeParams: true });
8771
+ const router = (0, import_express9.Router)({ mergeParams: true });
8685
8772
  this.extraRoutes(router);
8686
8773
  router.get("/orders/", this.get.bind(this));
8687
8774
  router.get("/orders/:id", this.getWithId.bind(this));
@@ -9017,6 +9104,7 @@ var ZoneService = class extends AbstractService {
9017
9104
  // src/services/index.ts
9018
9105
  var createServices = (router, repos) => ({
9019
9106
  "associate-role": new AssociateRoleServices(router, repos["associate-role"]),
9107
+ "as-associate": new AsAssociateService(router, repos["as-associate"]),
9020
9108
  "business-unit": new BusinessUnitServices(router, repos["business-unit"]),
9021
9109
  "category": new CategoryServices(router, repos["category"]),
9022
9110
  "cart": new CartService(router, repos["cart"], repos["order"]),
@@ -9131,12 +9219,10 @@ var CommercetoolsMock = class {
9131
9219
  _storage;
9132
9220
  _oauth2;
9133
9221
  _mswServer = void 0;
9134
- _services;
9135
9222
  _repositories;
9136
9223
  _projectService;
9137
9224
  constructor(options = {}) {
9138
9225
  this.options = { ...DEFAULT_OPTIONS, ...options };
9139
- this._services = null;
9140
9226
  this._repositories = null;
9141
9227
  this._projectService = void 0;
9142
9228
  this._storage = new InMemoryStorage();
@@ -9188,9 +9274,9 @@ var CommercetoolsMock = class {
9188
9274
  createApp(options) {
9189
9275
  this._repositories = createRepositories(this._storage);
9190
9276
  this._oauth2.setCustomerRepository(this._repositories.customer);
9191
- const app = (0, import_express7.default)();
9192
- const projectRouter = import_express7.default.Router({ mergeParams: true });
9193
- projectRouter.use(import_express7.default.json());
9277
+ const app = (0, import_express10.default)();
9278
+ const projectRouter = import_express10.default.Router({ mergeParams: true });
9279
+ projectRouter.use(import_express10.default.json());
9194
9280
  if (!options?.silent) {
9195
9281
  app.use((0, import_morgan.default)("tiny"));
9196
9282
  }
@@ -9206,7 +9292,7 @@ var CommercetoolsMock = class {
9206
9292
  app.use("/:projectKey", projectRouter);
9207
9293
  app.use("/:projectKey/in-store/key=:storeKey", projectRouter);
9208
9294
  }
9209
- this._services = createServices(projectRouter, this._repositories);
9295
+ createServices(projectRouter, this._repositories);
9210
9296
  this._projectService = new ProjectService(
9211
9297
  projectRouter,
9212
9298
  this._repositories.project