@labdigital/commercetools-mock 2.41.1 → 2.42.1

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
  }
3378
- }
3379
- setCustomType(context, resource, { type, fields }) {
3380
- if (type) {
3381
- resource.custom = createCustomFields(
3382
- { type, fields },
3252
+ const lineItem = {
3253
+ ...getBaseResourceProperties(),
3254
+ custom: createCustomFields(
3255
+ draft.custom,
3383
3256
  context.projectKey,
3384
3257
  this._storage
3385
- );
3386
- } else {
3387
- resource.custom = void 0;
3388
- }
3389
- }
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
- };
3411
-
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);
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;
3417
3279
  }
3418
- create(context, draft) {
3419
- const resource = {
3280
+ customLineItemFromImportDraft(context, draft) {
3281
+ const lineItem = {
3420
3282
  ...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
3283
  custom: createCustomFields(
3446
3284
  draft.custom,
3447
3285
  context.projectKey,
3448
3286
  this._storage
3449
- )
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: []
3450
3298
  };
3451
- return this.saveNew(context, resource);
3299
+ return lineItem;
3452
3300
  }
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
- });
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];
3470
3308
  }
3471
- resource.ancestors = ancestors;
3472
- return resource;
3309
+ if (result.count > 1) {
3310
+ throw new Error("Duplicate order numbers");
3311
+ }
3312
+ return;
3473
3313
  }
3474
3314
  };
3475
3315
 
3476
- // src/repositories/channel.ts
3477
- var ChannelRepository = class extends AbstractResourceRepository {
3316
+ // src/repositories/as-associate.ts
3317
+ var AsAssociateOrderRepository = class extends OrderRepository {
3318
+ };
3319
+ var AsAssociateCartRepository = class extends CartRepository {
3320
+ };
3321
+
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
  }
@@ -3535,566 +3384,539 @@ var ChannelUpdateHandler = class extends AbstractUpdateHandler {
3535
3384
  resource.custom = void 0;
3536
3385
  }
3537
3386
  }
3538
- setGeoLocation(context, resource, { geoLocation }) {
3539
- resource.geoLocation = geoLocation;
3387
+ setName(context, resource, { name }) {
3388
+ resource.name = name;
3389
+ }
3390
+ setPermissions(context, resource, { permissions }) {
3391
+ resource.permissions = permissions || [];
3540
3392
  }
3541
3393
  };
3542
3394
 
3543
- // src/repositories/custom-object.ts
3544
- var CustomObjectRepository = class extends AbstractResourceRepository {
3395
+ // src/repositories/attribute-group.ts
3396
+ var AttributeGroupRepository = class extends AbstractResourceRepository {
3545
3397
  constructor(storage) {
3546
- super("key-value-document", storage);
3398
+ super("attribute-group", storage);
3399
+ this.actions = new AttributeGroupUpdateHandler(this._storage);
3547
3400
  }
3548
3401
  create(context, draft) {
3549
- const current = this.getWithContainerAndKey(
3550
- context,
3551
- draft.container,
3552
- draft.key
3402
+ const resource = {
3403
+ ...getBaseResourceProperties(),
3404
+ name: draft.name,
3405
+ description: draft.description,
3406
+ key: draft.key,
3407
+ attributes: draft.attributes
3408
+ };
3409
+ return this.saveNew(context, resource);
3410
+ }
3411
+ };
3412
+ var AttributeGroupUpdateHandler = class extends AbstractUpdateHandler {
3413
+ changeName(_context, resource, { name }) {
3414
+ resource.name = name;
3415
+ }
3416
+ setAttributes(_context, resource, { attributes }) {
3417
+ resource.attributes = attributes;
3418
+ }
3419
+ setDescription(_context, resource, { description }) {
3420
+ resource.description = description;
3421
+ }
3422
+ setKey(_context, resource, { key }) {
3423
+ resource.key = key;
3424
+ }
3425
+ };
3426
+
3427
+ // src/repositories/business-unit.ts
3428
+ var BusinessUnitRepository = class extends AbstractResourceRepository {
3429
+ constructor(storage) {
3430
+ super("business-unit", storage);
3431
+ this.actions = new BusinessUnitUpdateHandler(this._storage);
3432
+ }
3433
+ create(context, draft) {
3434
+ const addresses = draft.addresses?.map((address) => ({
3435
+ ...address,
3436
+ id: generateRandomString(5)
3437
+ })) ?? [];
3438
+ const defaultBillingAddressId = addresses.length > 0 && draft.defaultBillingAddress !== void 0 ? addresses[draft.defaultBillingAddress].id : void 0;
3439
+ const defaultShippingAddressId = addresses.length > 0 && draft.defaultShippingAddress !== void 0 ? addresses[draft.defaultShippingAddress].id : void 0;
3440
+ const shippingAddressIds = draft.shippingAddresses?.map(
3441
+ (i) => addresses[i].id
3553
3442
  );
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
3443
+ const billingAddressIds = draft.billingAddresses?.map(
3444
+ (i) => addresses[i].id
3445
+ );
3446
+ const resource = {
3447
+ ...getBaseResourceProperties(),
3448
+ key: draft.key,
3449
+ status: draft.status,
3450
+ stores: draft.stores?.map(
3451
+ (s) => getStoreKeyReference(s, context.projectKey, this._storage)
3452
+ ),
3453
+ storeMode: draft.storeMode,
3454
+ name: draft.name,
3455
+ contactEmail: draft.contactEmail,
3456
+ addresses,
3457
+ custom: createCustomFields(
3458
+ draft.custom,
3459
+ context.projectKey,
3460
+ this._storage
3461
+ ),
3462
+ shippingAddressIds,
3463
+ billingAddressIds,
3464
+ defaultShippingAddressId,
3465
+ defaultBillingAddressId,
3466
+ associateMode: draft.associateMode,
3467
+ approvalRuleMode: draft.approvalRuleMode,
3468
+ associates: draft.associates?.map(
3469
+ (a) => createAssociate(a, context.projectKey, this._storage)
3470
+ ) ?? []
3471
+ };
3472
+ if (this._isDivisionDraft(draft)) {
3473
+ const division = {
3474
+ ...resource,
3475
+ parentUnit: getBusinessUnitKeyReference(
3476
+ draft.parentUnit,
3477
+ context.projectKey,
3478
+ this._storage
3479
+ )
3584
3480
  };
3585
- this.saveNew(context, resource);
3586
- return resource;
3481
+ this.saveNew(context, division);
3482
+ return division;
3483
+ } else if (this._isCompanyDraft(draft)) {
3484
+ const company = resource;
3485
+ this.saveNew(context, company);
3486
+ return company;
3587
3487
  }
3488
+ throw new Error("Invalid business unit type");
3588
3489
  }
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
- );
3490
+ _isCompanyDraft(draft) {
3491
+ return draft.unitType === "Company";
3594
3492
  }
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;
3493
+ _isDivisionDraft(draft) {
3494
+ return draft.unitType === "Division";
3608
3495
  }
3609
3496
  };
3610
-
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);
3497
+ var BusinessUnitUpdateHandler = class extends AbstractUpdateHandler {
3498
+ addAddress(context, resource, { address }) {
3499
+ const newAddress = createAddress(
3500
+ address,
3501
+ context.projectKey,
3502
+ this._storage
3503
+ );
3504
+ if (newAddress) {
3505
+ resource.addresses.push(newAddress);
3628
3506
  }
3629
3507
  }
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);
3508
+ addAssociate(context, resource, { associate }) {
3509
+ const newAssociate = createAssociate(
3510
+ associate,
3511
+ context.projectKey,
3512
+ this._storage
3513
+ );
3514
+ if (newAssociate) {
3515
+ resource.associates.push(newAssociate);
3638
3516
  }
3639
- return resource;
3640
- }
3641
- addStore(context, resource, action) {
3642
- throw new Error("Method not implemented.");
3643
3517
  }
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
3518
+ addStore(context, resource, { store }) {
3519
+ const newStore = getStoreKeyReference(
3520
+ store,
3521
+ context.projectKey,
3522
+ this._storage
3649
3523
  );
3524
+ if (newStore) {
3525
+ if (!resource.stores) {
3526
+ resource.stores = [];
3527
+ }
3528
+ resource.stores.push(newStore);
3529
+ }
3530
+ }
3531
+ changeAddress(context, resource, { address }) {
3650
3532
  const newAddress = createAddress(
3651
3533
  address,
3652
3534
  context.projectKey,
3653
3535
  this._storage
3654
3536
  );
3655
3537
  if (newAddress) {
3656
- resource.addresses[oldAddressIndex] = {
3657
- id: addressId,
3658
- ...newAddress
3659
- };
3538
+ resource.addresses.push(newAddress);
3660
3539
  }
3661
3540
  }
3662
- changeEmail(_context, resource, { email }) {
3663
- resource.email = email;
3541
+ changeApprovalRuleMode(context, resource, { approvalRuleMode }) {
3542
+ resource.approvalRuleMode = approvalRuleMode;
3664
3543
  }
3665
- removeAddress(context, resource, action) {
3666
- const address = this._findAddress(
3667
- resource,
3668
- action.addressId,
3669
- action.addressKey,
3670
- true
3671
- );
3672
- (0, import_node_assert.default)(address?.id);
3673
- resource.addresses = resource.addresses.filter((a) => a.id !== address.id);
3544
+ changeAssociateMode(context, resource, { associateMode }) {
3545
+ resource.associateMode = associateMode;
3674
3546
  }
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
3685
- );
3686
- if (resource.defaultBillingAddressId === address.id) {
3687
- resource.defaultBillingAddressId = void 0;
3688
- }
3547
+ changeName(context, resource, { name }) {
3548
+ resource.name = name;
3689
3549
  }
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
3550
+ changeParentUnit(context, resource, { parentUnit }) {
3551
+ resource.parentUnit = getBusinessUnitKeyReference(
3552
+ parentUnit,
3553
+ context.projectKey,
3554
+ this._storage
3700
3555
  );
3701
- if (resource.defaultShippingAddressId === address.id) {
3702
- resource.defaultShippingAddressId = void 0;
3703
- }
3704
3556
  }
3705
- removeStore(context, resource, action) {
3706
- throw new Error("Method not implemented.");
3557
+ changeStatus(context, resource, { status }) {
3558
+ resource.status = status;
3707
3559
  }
3708
- setAddressCustomField(context, resource, action) {
3709
- throw new Error("Method not implemented.");
3560
+ setAssociates(context, resource, { associates }) {
3561
+ const newAssociates = associates.map((a) => createAssociate(a, context.projectKey, this._storage)).filter((a) => a !== void 0);
3562
+ resource.associates = newAssociates || void 0;
3710
3563
  }
3711
- setAddressCustomType(context, resource, action) {
3712
- throw new Error("Method not implemented.");
3564
+ setContactEmail(context, resource, { contactEmail }) {
3565
+ resource.contactEmail = contactEmail;
3713
3566
  }
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
3567
+ setCustomType(context, resource, { type, fields }) {
3568
+ if (type) {
3569
+ resource.custom = createCustomFields(
3570
+ { type, fields },
3571
+ context.projectKey,
3572
+ this._storage
3722
3573
  );
3574
+ } else {
3575
+ resource.custom = void 0;
3723
3576
  }
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
3740
- );
3741
3577
  }
3742
- setCompanyName(_context, resource, { companyName }) {
3743
- resource.companyName = companyName;
3578
+ setStoreMode(context, resource, { storeMode }) {
3579
+ resource.storeMode = storeMode;
3744
3580
  }
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
- };
3581
+ };
3582
+
3583
+ // src/repositories/cart-discount/actions.ts
3584
+ var CartDiscountUpdateHandler = class extends AbstractUpdateHandler {
3585
+ changeIsActive(context, resource, { isActive }) {
3586
+ resource.isActive = isActive;
3763
3587
  }
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;
3588
+ changeSortOrder(context, resource, { sortOrder }) {
3589
+ resource.sortOrder = sortOrder;
3771
3590
  }
3772
- setCustomField(_context, resource, { name, value }) {
3591
+ changeTarget(context, resource, { target }) {
3592
+ resource.target = target;
3593
+ }
3594
+ setCustomField(context, resource, { name, value }) {
3773
3595
  if (!resource.custom) {
3774
- throw new Error("Resource has no custom field");
3596
+ return;
3597
+ }
3598
+ if (value === null) {
3599
+ if (name in resource.custom.fields) {
3600
+ delete resource.custom.fields[name];
3601
+ } else {
3602
+ throw new CommercetoolsError(
3603
+ {
3604
+ code: "InvalidOperation",
3605
+ message: "Cannot remove custom field " + name + " because it does not exist."
3606
+ },
3607
+ 400
3608
+ );
3609
+ }
3610
+ } else {
3611
+ resource.custom.fields[name] = value;
3775
3612
  }
3776
- resource.custom.fields[name] = value;
3777
3613
  }
3778
3614
  setCustomType(context, resource, { type, fields }) {
3779
- if (type) {
3780
- resource.custom = createCustomFields(
3781
- { type, fields },
3615
+ if (!type) {
3616
+ resource.custom = void 0;
3617
+ } else {
3618
+ const resolvedType = this._storage.getByResourceIdentifier(
3782
3619
  context.projectKey,
3783
- this._storage
3620
+ type
3784
3621
  );
3785
- } else {
3786
- resource.custom = void 0;
3622
+ if (!resolvedType) {
3623
+ throw new Error(`Type ${type} not found`);
3624
+ }
3625
+ resource.custom = {
3626
+ type: {
3627
+ typeId: "type",
3628
+ id: resolvedType.id
3629
+ },
3630
+ fields: fields || {}
3631
+ };
3787
3632
  }
3788
3633
  }
3789
- setDateOfBirth(context, resource, action) {
3790
- resource.dateOfBirth = action.dateOfBirth;
3634
+ setDescription(context, resource, { description }) {
3635
+ resource.description = description;
3791
3636
  }
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
- }
3637
+ setKey(context, resource, { key }) {
3638
+ resource.key = key;
3807
3639
  }
3808
- setDefaultShippingAddress(context, resource, action) {
3809
- const address = this._findAddress(
3810
- resource,
3811
- action.addressId,
3812
- action.addressKey,
3813
- true
3640
+ setStores(context, resource, { stores }) {
3641
+ resource.stores = stores?.map(
3642
+ (s) => getStoreKeyReference(s, context.projectKey, this._storage)
3814
3643
  );
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
3644
  }
3824
- setExternalId(_context, resource, { externalId }) {
3825
- resource.externalId = externalId;
3645
+ setValidFrom(context, resource, { validFrom }) {
3646
+ resource.validFrom = validFrom;
3826
3647
  }
3827
- setFirstName(_context, resource, { firstName }) {
3828
- resource.firstName = firstName;
3648
+ setValidFromAndUntil(context, resource, { validFrom, validUntil }) {
3649
+ resource.validFrom = validFrom;
3650
+ resource.validUntil = validUntil;
3829
3651
  }
3830
- setKey(_context, resource, { key }) {
3831
- resource.key = key;
3652
+ setValidUntil(context, resource, { validUntil }) {
3653
+ resource.validUntil = validUntil;
3832
3654
  }
3833
- setLastName(_context, resource, { lastName }) {
3834
- resource.lastName = lastName;
3655
+ };
3656
+
3657
+ // src/repositories/cart-discount/index.ts
3658
+ var CartDiscountRepository = class extends AbstractResourceRepository {
3659
+ constructor(storage) {
3660
+ super("cart-discount", storage);
3661
+ this.actions = new CartDiscountUpdateHandler(storage);
3835
3662
  }
3836
- setLocale(_context, resource, { locale }) {
3837
- resource.locale = locale;
3663
+ create(context, draft) {
3664
+ const resource = {
3665
+ ...getBaseResourceProperties(),
3666
+ key: draft.key,
3667
+ description: draft.description,
3668
+ cartPredicate: draft.cartPredicate,
3669
+ isActive: draft.isActive || false,
3670
+ name: draft.name,
3671
+ stores: draft.stores?.map(
3672
+ (s) => getStoreKeyReference(s, context.projectKey, this._storage)
3673
+ ) ?? [],
3674
+ references: [],
3675
+ target: draft.target,
3676
+ requiresDiscountCode: draft.requiresDiscountCode || false,
3677
+ sortOrder: draft.sortOrder,
3678
+ stackingMode: draft.stackingMode || "Stacking",
3679
+ validFrom: draft.validFrom,
3680
+ validUntil: draft.validUntil,
3681
+ value: this.transformValueDraft(draft.value),
3682
+ custom: createCustomFields(
3683
+ draft.custom,
3684
+ context.projectKey,
3685
+ this._storage
3686
+ )
3687
+ };
3688
+ return this.saveNew(context, resource);
3838
3689
  }
3839
- setMiddleName(context, resource, action) {
3840
- resource.middleName = action.middleName;
3690
+ transformValueDraft(value) {
3691
+ switch (value.type) {
3692
+ case "absolute": {
3693
+ return {
3694
+ type: "absolute",
3695
+ money: value.money.map(createTypedMoney)
3696
+ };
3697
+ }
3698
+ case "fixed": {
3699
+ return {
3700
+ type: "fixed",
3701
+ money: value.money.map(createTypedMoney)
3702
+ };
3703
+ }
3704
+ case "giftLineItem": {
3705
+ return {
3706
+ ...value
3707
+ };
3708
+ }
3709
+ case "relative": {
3710
+ return {
3711
+ ...value
3712
+ };
3713
+ }
3714
+ }
3715
+ return value;
3841
3716
  }
3842
- setSalutation(_context, resource, { salutation }) {
3843
- resource.salutation = salutation;
3717
+ };
3718
+
3719
+ // src/repositories/category/index.ts
3720
+ var import_uuid8 = require("uuid");
3721
+
3722
+ // src/repositories/category/actions.ts
3723
+ var import_uuid7 = require("uuid");
3724
+ var CategoryUpdateHandler = class extends AbstractUpdateHandler {
3725
+ addAsset(context, resource, { asset }) {
3726
+ if (!resource.assets) {
3727
+ resource.assets = [this.assetFromAssetDraft(asset, context)];
3728
+ } else {
3729
+ resource.assets.push(this.assetFromAssetDraft(asset, context));
3730
+ }
3844
3731
  }
3845
- setStores(context, resource, action) {
3846
- throw new Error("Method not implemented.");
3732
+ changeAssetName(context, resource, { assetId, assetKey, name }) {
3733
+ resource.assets?.forEach((asset) => {
3734
+ if (assetId && assetId === asset.id) {
3735
+ asset.name = name;
3736
+ }
3737
+ if (assetKey && assetKey === asset.key) {
3738
+ asset.name = name;
3739
+ }
3740
+ });
3847
3741
  }
3848
- setTitle(context, resource, action) {
3849
- resource.title = action.title;
3742
+ changeName(context, resource, { name }) {
3743
+ resource.name = name;
3850
3744
  }
3851
- setVatId(_context, resource, { vatId }) {
3852
- resource.vatId = vatId;
3745
+ changeParent(context, resource, { parent }) {
3746
+ const category = this._storage.getByResourceIdentifier(
3747
+ context.projectKey,
3748
+ parent
3749
+ );
3750
+ if (!category) {
3751
+ throw new Error("No category found for reference");
3752
+ }
3753
+ resource.parent = {
3754
+ typeId: "category",
3755
+ id: category.id
3756
+ };
3853
3757
  }
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;
3758
+ changeSlug(context, resource, { slug }) {
3759
+ resource.slug = slug;
3760
+ }
3761
+ removeAsset(context, resource, { assetId, assetKey }) {
3762
+ if (!resource.assets) {
3763
+ return;
3867
3764
  }
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
- );
3765
+ if (assetId) {
3766
+ resource.assets = resource.assets.filter(function(obj) {
3767
+ return obj.id !== assetId;
3768
+ });
3769
+ return;
3770
+ }
3771
+ if (assetKey) {
3772
+ resource.assets = resource.assets.filter(function(obj) {
3773
+ return obj.key !== assetKey;
3774
+ });
3775
+ return;
3776
+ }
3777
+ }
3778
+ setAssetDescription(context, resource, { assetId, assetKey, description }) {
3779
+ resource.assets?.forEach((asset) => {
3780
+ if (assetId && assetId === asset.id) {
3781
+ asset.description = description;
3782
+ }
3783
+ if (assetKey && assetKey === asset.key) {
3784
+ asset.description = description;
3785
+ }
3786
+ });
3787
+ }
3788
+ setAssetSources(context, resource, { assetId, assetKey, sources }) {
3789
+ resource.assets?.forEach((asset) => {
3790
+ if (assetId && assetId === asset.id) {
3791
+ asset.sources = sources;
3878
3792
  }
3879
- return address;
3793
+ if (assetKey && assetKey === asset.key) {
3794
+ asset.sources = sources;
3795
+ }
3796
+ });
3797
+ }
3798
+ setCustomField(context, resource, { name, value }) {
3799
+ if (!resource.custom) {
3800
+ return;
3880
3801
  }
3881
- if (required) {
3882
- throw new CommercetoolsError(
3883
- {
3884
- code: "InvalidOperation",
3885
- message: "One of address 'addressId' or 'addressKey' is required."
3886
- },
3887
- 400
3802
+ if (value === null) {
3803
+ delete resource.custom.fields[name];
3804
+ } else {
3805
+ resource.custom.fields[name] = value;
3806
+ }
3807
+ }
3808
+ setCustomType(context, resource, { type, fields }) {
3809
+ if (type) {
3810
+ resource.custom = createCustomFields(
3811
+ { type, fields },
3812
+ context.projectKey,
3813
+ this._storage
3888
3814
  );
3815
+ } else {
3816
+ resource.custom = void 0;
3889
3817
  }
3890
3818
  }
3819
+ setDescription(context, resource, { description }) {
3820
+ resource.description = description;
3821
+ }
3822
+ setKey(context, resource, { key }) {
3823
+ resource.key = key;
3824
+ }
3825
+ setMetaDescription(context, resource, { metaDescription }) {
3826
+ resource.metaDescription = metaDescription;
3827
+ }
3828
+ setMetaKeywords(context, resource, { metaKeywords }) {
3829
+ resource.metaKeywords = metaKeywords;
3830
+ }
3831
+ setMetaTitle(context, resource, { metaTitle }) {
3832
+ resource.metaTitle = metaTitle;
3833
+ }
3834
+ assetFromAssetDraft = (draft, context) => ({
3835
+ ...draft,
3836
+ id: (0, import_uuid7.v4)(),
3837
+ custom: createCustomFields(draft.custom, context.projectKey, this._storage)
3838
+ });
3891
3839
  };
3892
3840
 
3893
- // src/repositories/customer/index.ts
3894
- var CustomerRepository = class extends AbstractResourceRepository {
3841
+ // src/repositories/category/index.ts
3842
+ var CategoryRepository = class extends AbstractResourceRepository {
3895
3843
  constructor(storage) {
3896
- super("customer", storage);
3897
- this.actions = new CustomerUpdateHandler(storage);
3844
+ super("category", storage);
3845
+ this.actions = new CategoryUpdateHandler(this._storage);
3898
3846
  }
3899
3847
  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
- storesForCustomer = this.storeReferenceToStoreKeyReference(
3953
- draft.stores,
3954
- context.projectKey
3955
- );
3956
- }
3957
3848
  const resource = {
3958
3849
  ...getBaseResourceProperties(),
3959
3850
  key: draft.key,
3960
- authenticationMode: draft.authenticationMode || "Password",
3961
- firstName: draft.firstName,
3962
- lastName: draft.lastName,
3963
- middleName: draft.middleName,
3964
- title: draft.title,
3965
- dateOfBirth: draft.dateOfBirth,
3966
- companyName: draft.companyName,
3967
- email: draft.email.toLowerCase(),
3968
- lowercaseEmail: draft.email.toLowerCase(),
3969
- password: draft.password ? hashPassword(draft.password) : void 0,
3970
- isEmailVerified: draft.isEmailVerified || false,
3971
- addresses,
3972
- customerNumber: draft.customerNumber,
3973
- externalId: draft.externalId,
3974
- defaultBillingAddressId,
3975
- defaultShippingAddressId,
3976
- shippingAddressIds,
3977
- billingAddressIds,
3851
+ name: draft.name,
3852
+ slug: draft.slug,
3853
+ description: draft.description,
3854
+ metaDescription: draft.metaDescription,
3855
+ metaKeywords: draft.metaKeywords,
3856
+ orderHint: draft.orderHint || "",
3857
+ externalId: draft.externalId || "",
3858
+ parent: draft.parent ? { typeId: "category", id: draft.parent.id } : void 0,
3859
+ ancestors: [],
3860
+ // Resolved at runtime
3861
+ assets: draft.assets?.map((d) => ({
3862
+ id: (0, import_uuid8.v4)(),
3863
+ name: d.name,
3864
+ description: d.description,
3865
+ sources: d.sources,
3866
+ tags: d.tags,
3867
+ key: d.key,
3868
+ custom: createCustomFields(
3869
+ draft.custom,
3870
+ context.projectKey,
3871
+ this._storage
3872
+ )
3873
+ })) || [],
3978
3874
  custom: createCustomFields(
3979
3875
  draft.custom,
3980
3876
  context.projectKey,
3981
3877
  this._storage
3982
- ),
3983
- stores: storesForCustomer
3878
+ )
3984
3879
  };
3985
3880
  return this.saveNew(context, resource);
3986
3881
  }
3987
- saveUpdate(context, version, resource) {
3988
- const updatedResource = {
3989
- ...resource,
3990
- lowercaseEmail: resource.email.toLowerCase()
3991
- };
3992
- return super.saveUpdate(context, version, updatedResource);
3993
- }
3994
- passwordResetToken(context, request) {
3995
- const results = this._storage.query(context.projectKey, this.getTypeId(), {
3996
- where: [`email="${request.email.toLocaleLowerCase()}"`]
3997
- });
3998
- if (results.count === 0) {
3999
- throw new CommercetoolsError({
4000
- code: "ResourceNotFound",
4001
- message: `The Customer with ID '${request.email}' was not found.`
4002
- });
4003
- }
4004
- const ttlMinutes = request.ttlMinutes ?? 34560;
4005
- const expiresAt = new Date((/* @__PURE__ */ new Date()).getTime() + ttlMinutes * 60 * 1e3);
4006
- const customer = results.results[0];
4007
- const rest = getBaseResourceProperties();
4008
- const token = createPasswordResetToken(customer, expiresAt);
4009
- return {
4010
- id: rest.id,
4011
- createdAt: rest.createdAt,
4012
- lastModifiedAt: rest.lastModifiedAt,
4013
- customerId: customer.id,
4014
- expiresAt: expiresAt.toISOString(),
4015
- value: token
4016
- };
4017
- }
4018
- passwordReset(context, resetPassword) {
4019
- const { newPassword, tokenValue } = resetPassword;
4020
- const customerId = validatePasswordResetToken(tokenValue);
4021
- if (!customerId) {
4022
- throw new CommercetoolsError({
4023
- code: "ResourceNotFound",
4024
- message: `The Customer with ID 'Token(${tokenValue})' was not found.`
4025
- });
4026
- }
4027
- const customer = this._storage.get(
4028
- context.projectKey,
4029
- "customer",
4030
- customerId
3882
+ postProcessResource(context, resource, params) {
3883
+ let node = resource;
3884
+ const ancestors = [];
3885
+ const expandClauses = params?.expand?.map(parseExpandClause) ?? [];
3886
+ const addExpand = expandClauses?.find(
3887
+ (c) => c.element === "ancestors" && c.index === "*"
4031
3888
  );
4032
- if (!customer) {
4033
- throw new CommercetoolsError({
4034
- code: "ResourceNotFound",
4035
- message: `The Customer with ID 'Token(${tokenValue})' was not found.`
4036
- });
4037
- }
4038
- customer.password = hashPassword(newPassword);
4039
- customer.version += 1;
4040
- this._storage.add(context.projectKey, "customer", customer);
4041
- return customer;
4042
- }
4043
- verifyEmailToken(context, id) {
4044
- const results = this._storage.query(context.projectKey, this.getTypeId(), {
4045
- where: [`id="${id.toLocaleLowerCase()}"`]
4046
- });
4047
- if (results.count === 0) {
4048
- throw new CommercetoolsError({
4049
- code: "ResourceNotFound",
4050
- message: `The Customer with ID '${id}' was not found.`
4051
- });
4052
- }
4053
- const expiresAt = new Date(Date.now() + 30 * 60);
4054
- const customer = results.results[0];
4055
- const rest = getBaseResourceProperties();
4056
- const token = createEmailVerifyToken(customer);
4057
- return {
4058
- id: rest.id,
4059
- createdAt: rest.createdAt,
4060
- lastModifiedAt: rest.lastModifiedAt,
4061
- customerId: customer.id,
4062
- expiresAt: expiresAt.toISOString(),
4063
- value: token
4064
- };
4065
- }
4066
- storeReferenceToStoreKeyReference(draftStores, projectKey) {
4067
- const storeIds = draftStores.map((storeReference) => storeReference.id).filter(Boolean);
4068
- let stores = [];
4069
- if (storeIds.length > 0) {
4070
- stores = this._storage.query(projectKey, "store", {
4071
- where: storeIds.map((id) => `id="${id}"`)
4072
- }).results;
4073
- if (storeIds.length !== stores.length) {
4074
- throw new CommercetoolsError({
4075
- code: "ResourceNotFound",
4076
- message: `Store with ID '${storeIds.find((id) => !stores.some((store) => store.id === id))}' was not found.`
4077
- });
4078
- }
3889
+ while (node.parent) {
3890
+ node = this._storage.getByResourceIdentifier(
3891
+ context.projectKey,
3892
+ node.parent
3893
+ );
3894
+ ancestors.push({
3895
+ typeId: "category",
3896
+ id: node.id,
3897
+ obj: addExpand ? node : void 0
3898
+ });
4079
3899
  }
4080
- return draftStores.map((storeReference) => ({
4081
- typeId: "store",
4082
- key: storeReference.key ?? stores.find((store) => store.id === storeReference.id)?.key
4083
- }));
3900
+ resource.ancestors = ancestors;
3901
+ return resource;
4084
3902
  }
4085
3903
  };
4086
3904
 
4087
- // src/repositories/customer-group.ts
4088
- var CustomerGroupRepository = class extends AbstractResourceRepository {
3905
+ // src/repositories/channel.ts
3906
+ var ChannelRepository = class extends AbstractResourceRepository {
4089
3907
  constructor(storage) {
4090
- super("customer-group", storage);
4091
- this.actions = new CustomerGroupUpdateHandler(storage);
3908
+ super("channel", storage);
3909
+ this.actions = new ChannelUpdateHandler(this._storage);
4092
3910
  }
4093
3911
  create(context, draft) {
4094
3912
  const resource = {
4095
3913
  ...getBaseResourceProperties(),
4096
3914
  key: draft.key,
4097
- name: draft.groupName,
3915
+ name: draft.name,
3916
+ description: draft.description,
3917
+ roles: draft.roles || [],
3918
+ geoLocation: draft.geoLocation,
3919
+ address: createAddress(draft.address, context.projectKey, this._storage),
4098
3920
  custom: createCustomFields(
4099
3921
  draft.custom,
4100
3922
  context.projectKey,
@@ -4104,61 +3926,283 @@ var CustomerGroupRepository = class extends AbstractResourceRepository {
4104
3926
  return this.saveNew(context, resource);
4105
3927
  }
4106
3928
  };
4107
- var CustomerGroupUpdateHandler = class extends AbstractUpdateHandler {
3929
+ var ChannelUpdateHandler = class extends AbstractUpdateHandler {
3930
+ changeDescription(context, resource, { description }) {
3931
+ resource.description = description;
3932
+ }
3933
+ changeKey(context, resource, { key }) {
3934
+ resource.key = key;
3935
+ }
4108
3936
  changeName(context, resource, { name }) {
4109
3937
  resource.name = name;
4110
3938
  }
3939
+ setAddress(context, resource, { address }) {
3940
+ resource.address = createAddress(
3941
+ address,
3942
+ context.projectKey,
3943
+ this._storage
3944
+ );
3945
+ }
4111
3946
  setCustomField(context, resource, { name, value }) {
4112
3947
  if (!resource.custom) {
4113
3948
  return;
4114
3949
  }
4115
- if (value === null) {
4116
- delete resource.custom.fields[name];
4117
- } else {
4118
- resource.custom.fields[name] = value;
4119
- }
3950
+ if (value === null) {
3951
+ delete resource.custom.fields[name];
3952
+ } else {
3953
+ resource.custom.fields[name] = value;
3954
+ }
3955
+ }
3956
+ setCustomType(context, resource, { type, fields }) {
3957
+ if (type) {
3958
+ resource.custom = createCustomFields(
3959
+ { type, fields },
3960
+ context.projectKey,
3961
+ this._storage
3962
+ );
3963
+ } else {
3964
+ resource.custom = void 0;
3965
+ }
3966
+ }
3967
+ setGeoLocation(context, resource, { geoLocation }) {
3968
+ resource.geoLocation = geoLocation;
3969
+ }
3970
+ };
3971
+
3972
+ // src/repositories/custom-object.ts
3973
+ var CustomObjectRepository = class extends AbstractResourceRepository {
3974
+ constructor(storage) {
3975
+ super("key-value-document", storage);
3976
+ }
3977
+ create(context, draft) {
3978
+ const current = this.getWithContainerAndKey(
3979
+ context,
3980
+ draft.container,
3981
+ draft.key
3982
+ );
3983
+ if (current) {
3984
+ if (draft.version) {
3985
+ checkConcurrentModification(current.version, draft.version, current.id);
3986
+ } else {
3987
+ draft.version = current.version;
3988
+ }
3989
+ if (draft.value !== current.value) {
3990
+ const updated = cloneObject(current);
3991
+ updated.value = draft.value;
3992
+ updated.version += 1;
3993
+ this.saveUpdate(context, draft.version, updated);
3994
+ return updated;
3995
+ }
3996
+ return current;
3997
+ } else {
3998
+ if (draft.version) {
3999
+ throw new CommercetoolsError(
4000
+ {
4001
+ code: "InvalidOperation",
4002
+ message: "version on create must be 0"
4003
+ },
4004
+ 400
4005
+ );
4006
+ }
4007
+ const baseProperties = getBaseResourceProperties();
4008
+ const resource = {
4009
+ ...baseProperties,
4010
+ container: draft.container,
4011
+ key: draft.key,
4012
+ value: draft.value
4013
+ };
4014
+ this.saveNew(context, resource);
4015
+ return resource;
4016
+ }
4017
+ }
4018
+ getWithContainerAndKey(context, container, key) {
4019
+ const items = this._storage.all(context.projectKey, this.getTypeId());
4020
+ return items.find(
4021
+ (item) => item.container === container && item.key === key
4022
+ );
4023
+ }
4024
+ queryWithContainer(context, container, params = {}) {
4025
+ const whereClause = params.where || [];
4026
+ whereClause.push(`container="${container}"`);
4027
+ const result = this._storage.query(context.projectKey, this.getTypeId(), {
4028
+ ...params,
4029
+ where: whereClause
4030
+ });
4031
+ result.results = result.results.map(
4032
+ (r) => this.postProcessResource(context, r, {
4033
+ expand: params.expand
4034
+ })
4035
+ );
4036
+ return result;
4037
+ }
4038
+ };
4039
+
4040
+ // src/repositories/customer/actions.ts
4041
+ var import_node_assert = __toESM(require("assert"), 1);
4042
+ var CustomerUpdateHandler = class extends AbstractUpdateHandler {
4043
+ addAddress(_context, resource, { address }) {
4044
+ resource.addresses.push({
4045
+ ...address,
4046
+ id: address.id ?? generateRandomString(5)
4047
+ });
4048
+ }
4049
+ addBillingAddressId(_context, resource, { addressId, addressKey }) {
4050
+ const address = this._findAddress(resource, addressId, addressKey, true);
4051
+ (0, import_node_assert.default)(address?.id);
4052
+ if (resource.billingAddressIds === void 0) {
4053
+ resource.billingAddressIds = [];
4054
+ }
4055
+ if (!resource.billingAddressIds.includes(address.id)) {
4056
+ resource.billingAddressIds.push(address.id);
4057
+ }
4058
+ }
4059
+ addShippingAddressId(_context, resource, { addressId, addressKey }) {
4060
+ const address = this._findAddress(resource, addressId, addressKey, true);
4061
+ (0, import_node_assert.default)(address?.id);
4062
+ if (resource.shippingAddressIds === void 0) {
4063
+ resource.shippingAddressIds = [];
4064
+ }
4065
+ if (!resource.shippingAddressIds.includes(address.id)) {
4066
+ resource.shippingAddressIds.push(address.id);
4067
+ }
4068
+ return resource;
4069
+ }
4070
+ addStore(context, resource, action) {
4071
+ throw new Error("Method not implemented.");
4072
+ }
4073
+ changeAddress(context, resource, { addressId, addressKey, address }) {
4074
+ const current = this._findAddress(resource, addressId, addressKey, true);
4075
+ (0, import_node_assert.default)(current?.id);
4076
+ const oldAddressIndex = resource.addresses.findIndex(
4077
+ (a) => a.id === current.id
4078
+ );
4079
+ const newAddress = createAddress(
4080
+ address,
4081
+ context.projectKey,
4082
+ this._storage
4083
+ );
4084
+ if (newAddress) {
4085
+ resource.addresses[oldAddressIndex] = {
4086
+ id: addressId,
4087
+ ...newAddress
4088
+ };
4089
+ }
4090
+ }
4091
+ changeEmail(_context, resource, { email }) {
4092
+ resource.email = email;
4093
+ }
4094
+ removeAddress(context, resource, action) {
4095
+ const address = this._findAddress(
4096
+ resource,
4097
+ action.addressId,
4098
+ action.addressKey,
4099
+ true
4100
+ );
4101
+ (0, import_node_assert.default)(address?.id);
4102
+ resource.addresses = resource.addresses.filter((a) => a.id !== address.id);
4103
+ }
4104
+ removeBillingAddressId(context, resource, action) {
4105
+ const address = this._findAddress(
4106
+ resource,
4107
+ action.addressId,
4108
+ action.addressKey,
4109
+ true
4110
+ );
4111
+ (0, import_node_assert.default)(address?.id);
4112
+ resource.billingAddressIds = resource.billingAddressIds?.filter(
4113
+ (id) => id !== address.id
4114
+ );
4115
+ if (resource.defaultBillingAddressId === address.id) {
4116
+ resource.defaultBillingAddressId = void 0;
4117
+ }
4118
+ }
4119
+ removeShippingAddressId(context, resource, action) {
4120
+ const address = this._findAddress(
4121
+ resource,
4122
+ action.addressId,
4123
+ action.addressKey,
4124
+ true
4125
+ );
4126
+ (0, import_node_assert.default)(address?.id);
4127
+ resource.shippingAddressIds = resource.shippingAddressIds?.filter(
4128
+ (id) => id !== address.id
4129
+ );
4130
+ if (resource.defaultShippingAddressId === address.id) {
4131
+ resource.defaultShippingAddressId = void 0;
4132
+ }
4133
+ }
4134
+ removeStore(context, resource, action) {
4135
+ throw new Error("Method not implemented.");
4136
+ }
4137
+ setAddressCustomField(context, resource, action) {
4138
+ throw new Error("Method not implemented.");
4139
+ }
4140
+ setAddressCustomType(context, resource, action) {
4141
+ throw new Error("Method not implemented.");
4142
+ }
4143
+ setAuthenticationMode(_context, resource, { authMode, password }) {
4144
+ if (resource.authenticationMode === authMode) {
4145
+ throw new CommercetoolsError(
4146
+ {
4147
+ code: "InvalidInput",
4148
+ message: `The customer is already using the '${resource.authenticationMode}' authentication mode.`
4149
+ },
4150
+ 400
4151
+ );
4152
+ }
4153
+ resource.authenticationMode = authMode;
4154
+ if (authMode === "ExternalAuth") {
4155
+ delete resource.password;
4156
+ return;
4157
+ }
4158
+ if (authMode === "Password") {
4159
+ resource.password = password ? hashPassword(password) : void 0;
4160
+ return;
4161
+ }
4162
+ throw new CommercetoolsError(
4163
+ {
4164
+ code: "InvalidJsonInput",
4165
+ message: "Request body does not contain valid JSON.",
4166
+ detailedErrorMessage: `actions -> authMode: Invalid enum value: '${authMode}'. Expected one of: 'Password','ExternalAuth'`
4167
+ },
4168
+ 400
4169
+ );
4120
4170
  }
4121
- setCustomType(context, resource, { type, fields }) {
4122
- if (type) {
4123
- resource.custom = createCustomFields(
4124
- { type, fields },
4125
- context.projectKey,
4126
- this._storage
4171
+ setCompanyName(_context, resource, { companyName }) {
4172
+ resource.companyName = companyName;
4173
+ }
4174
+ setCustomerGroup(context, resource, action) {
4175
+ if (!action.customerGroup) {
4176
+ throw new CommercetoolsError(
4177
+ {
4178
+ code: "InvalidOperation",
4179
+ message: "CustomerGroup is required."
4180
+ },
4181
+ 400
4127
4182
  );
4128
- } else {
4129
- resource.custom = void 0;
4130
4183
  }
4131
- }
4132
- setKey(context, resource, { key }) {
4133
- resource.key = key;
4134
- }
4135
- };
4136
-
4137
- // src/repositories/discount-code/actions.ts
4138
- var DiscountCodeUpdateHandler = class extends AbstractUpdateHandler {
4139
- changeCartDiscounts(context, resource, { cartDiscounts }) {
4140
- resource.cartDiscounts = cartDiscounts.map(
4141
- (obj) => ({
4142
- typeId: "cart-discount",
4143
- id: obj.id
4144
- })
4184
+ const group = this._storage.getByResourceIdentifier(
4185
+ context.projectKey,
4186
+ action.customerGroup
4145
4187
  );
4188
+ resource.customerGroup = {
4189
+ typeId: "customer-group",
4190
+ id: group.id
4191
+ };
4146
4192
  }
4147
- changeIsActive(context, resource, { isActive }) {
4148
- resource.isActive = isActive;
4149
- }
4150
- setCartPredicate(context, resource, { cartPredicate }) {
4151
- resource.cartPredicate = cartPredicate;
4193
+ setCustomerNumber(_context, resource, { customerNumber }) {
4194
+ if (resource.customerNumber) {
4195
+ throw new Error(
4196
+ "A Customer number already exists and cannot be set again."
4197
+ );
4198
+ }
4199
+ resource.customerNumber = customerNumber;
4152
4200
  }
4153
- setCustomField(context, resource, { name, value }) {
4201
+ setCustomField(_context, resource, { name, value }) {
4154
4202
  if (!resource.custom) {
4155
- return;
4156
- }
4157
- if (value === null) {
4158
- delete resource.custom.fields[name];
4159
- } else {
4160
- resource.custom.fields[name] = value;
4203
+ throw new Error("Resource has no custom field");
4161
4204
  }
4205
+ resource.custom.fields[name] = value;
4162
4206
  }
4163
4207
  setCustomType(context, resource, { type, fields }) {
4164
4208
  if (type) {
@@ -4171,683 +4215,665 @@ var DiscountCodeUpdateHandler = class extends AbstractUpdateHandler {
4171
4215
  resource.custom = void 0;
4172
4216
  }
4173
4217
  }
4174
- setDescription(context, resource, { description }) {
4175
- resource.description = description;
4176
- }
4177
- setMaxApplications(context, resource, { maxApplications }) {
4178
- resource.maxApplications = maxApplications;
4179
- }
4180
- setMaxApplicationsPerCustomer(context, resource, {
4181
- maxApplicationsPerCustomer
4182
- }) {
4183
- resource.maxApplicationsPerCustomer = maxApplicationsPerCustomer;
4184
- }
4185
- setName(context, resource, { name }) {
4186
- resource.name = name;
4187
- }
4188
- setValidFrom(context, resource, { validFrom }) {
4189
- resource.validFrom = validFrom;
4190
- }
4191
- setValidFromAndUntil(context, resource, { validFrom, validUntil }) {
4192
- resource.validFrom = validFrom;
4193
- resource.validUntil = validUntil;
4194
- }
4195
- setValidUntil(context, resource, { validUntil }) {
4196
- resource.validUntil = validUntil;
4197
- }
4198
- };
4199
-
4200
- // src/repositories/discount-code/index.ts
4201
- var DiscountCodeRepository = class extends AbstractResourceRepository {
4202
- constructor(storage) {
4203
- super("discount-code", storage);
4204
- this.actions = new DiscountCodeUpdateHandler(storage);
4218
+ setDateOfBirth(context, resource, action) {
4219
+ resource.dateOfBirth = action.dateOfBirth;
4205
4220
  }
4206
- create(context, draft) {
4207
- const resource = {
4208
- ...getBaseResourceProperties(),
4209
- applicationVersion: 1,
4210
- cartDiscounts: draft.cartDiscounts.map(
4211
- (obj) => ({
4212
- typeId: "cart-discount",
4213
- id: obj.id
4214
- })
4215
- ),
4216
- cartPredicate: draft.cartPredicate,
4217
- code: draft.code,
4218
- description: draft.description,
4219
- groups: draft.groups || [],
4220
- isActive: draft.isActive || true,
4221
- name: draft.name,
4222
- references: [],
4223
- validFrom: draft.validFrom,
4224
- validUntil: draft.validUntil,
4225
- maxApplications: draft.maxApplications,
4226
- maxApplicationsPerCustomer: draft.maxApplicationsPerCustomer,
4227
- custom: createCustomFields(
4228
- draft.custom,
4229
- context.projectKey,
4230
- this._storage
4231
- )
4232
- };
4233
- return this.saveNew(context, resource);
4221
+ setDefaultBillingAddress(context, resource, action) {
4222
+ const address = this._findAddress(
4223
+ resource,
4224
+ action.addressId,
4225
+ action.addressKey,
4226
+ true
4227
+ );
4228
+ (0, import_node_assert.default)(address?.id);
4229
+ resource.defaultBillingAddressId = address.id;
4230
+ if (resource.billingAddressIds === void 0) {
4231
+ resource.billingAddressIds = [];
4232
+ }
4233
+ if (!resource.billingAddressIds.includes(address.id)) {
4234
+ resource.billingAddressIds.push(address.id);
4235
+ }
4234
4236
  }
4235
- };
4236
-
4237
- // src/lib/masking.ts
4238
- var maskSecretValue = (resource, path) => {
4239
- const parts = path.split(".");
4240
- const clone = cloneObject(resource);
4241
- let val = clone;
4242
- const target = parts.pop();
4243
- for (let i = 0; i < parts.length; i++) {
4244
- const part = parts[i];
4245
- val = val[part];
4246
- if (val === void 0) {
4247
- return resource;
4237
+ setDefaultShippingAddress(context, resource, action) {
4238
+ const address = this._findAddress(
4239
+ resource,
4240
+ action.addressId,
4241
+ action.addressKey,
4242
+ true
4243
+ );
4244
+ (0, import_node_assert.default)(address?.id);
4245
+ resource.defaultShippingAddressId = address.id;
4246
+ if (resource.shippingAddressIds === void 0) {
4247
+ resource.shippingAddressIds = [];
4248
+ }
4249
+ if (!resource.shippingAddressIds.includes(address.id)) {
4250
+ resource.shippingAddressIds.push(address.id);
4248
4251
  }
4249
4252
  }
4250
- if (val && target && val[target]) {
4251
- val[target] = "****";
4253
+ setExternalId(_context, resource, { externalId }) {
4254
+ resource.externalId = externalId;
4252
4255
  }
4253
- return clone;
4254
- };
4255
-
4256
- // src/repositories/extension.ts
4257
- var ExtensionRepository = class extends AbstractResourceRepository {
4258
- constructor(storage) {
4259
- super("extension", storage);
4260
- this.actions = new ExtensionUpdateHandler(storage);
4256
+ setFirstName(_context, resource, { firstName }) {
4257
+ resource.firstName = firstName;
4261
4258
  }
4262
- create(context, draft) {
4263
- const resource = {
4264
- ...getBaseResourceProperties(),
4265
- key: draft.key,
4266
- timeoutInMs: draft.timeoutInMs,
4267
- destination: draft.destination,
4268
- triggers: draft.triggers
4269
- };
4270
- return this.saveNew(context, resource);
4259
+ setKey(_context, resource, { key }) {
4260
+ resource.key = key;
4271
4261
  }
4272
- postProcessResource(context, resource) {
4273
- if (resource) {
4274
- const extension = resource;
4275
- if (extension.destination.type === "HTTP" && extension.destination.authentication?.type === "AuthorizationHeader") {
4276
- return maskSecretValue(
4277
- extension,
4278
- "destination.authentication.headerValue"
4279
- );
4280
- } else if (extension.destination.type === "AWSLambda") {
4281
- return maskSecretValue(resource, "destination.accessSecret");
4282
- }
4283
- }
4284
- return resource;
4262
+ setLastName(_context, resource, { lastName }) {
4263
+ resource.lastName = lastName;
4285
4264
  }
4286
- };
4287
- var ExtensionUpdateHandler = class extends AbstractUpdateHandler {
4288
- changeDestination(context, resource, action) {
4289
- resource.destination = action.destination;
4265
+ setLocale(_context, resource, { locale }) {
4266
+ resource.locale = locale;
4290
4267
  }
4291
- changeTriggers(context, resource, action) {
4292
- resource.triggers = action.triggers;
4268
+ setMiddleName(context, resource, action) {
4269
+ resource.middleName = action.middleName;
4293
4270
  }
4294
- setKey(context, resource, action) {
4295
- resource.key = action.key;
4271
+ setSalutation(_context, resource, { salutation }) {
4272
+ resource.salutation = salutation;
4296
4273
  }
4297
- setTimeoutInMs(context, resource, action) {
4298
- resource.timeoutInMs = action.timeoutInMs;
4274
+ setStores(context, resource, action) {
4275
+ throw new Error("Method not implemented.");
4299
4276
  }
4300
- };
4301
-
4302
- // src/repositories/inventory-entry/actions.ts
4303
- var InventoryEntryUpdateHandler = class extends AbstractUpdateHandler {
4304
- changeQuantity(context, resource, { quantity }) {
4305
- resource.quantityOnStock = quantity;
4306
- resource.availableQuantity = quantity;
4277
+ setTitle(context, resource, action) {
4278
+ resource.title = action.title;
4307
4279
  }
4308
- setCustomField(context, resource, { name, value }) {
4309
- if (!resource.custom) {
4310
- throw new Error("Resource has no custom field");
4280
+ setVatId(_context, resource, { vatId }) {
4281
+ resource.vatId = vatId;
4282
+ }
4283
+ _findAddress(resource, addressId, addressKey, required = false) {
4284
+ if (addressKey) {
4285
+ const address = resource.addresses.find((a) => a.key === addressKey);
4286
+ if (!address) {
4287
+ throw new CommercetoolsError(
4288
+ {
4289
+ code: "InvalidOperation",
4290
+ message: `Customer does not contain an address with the key ${addressKey}.`
4291
+ },
4292
+ 400
4293
+ );
4294
+ }
4295
+ return address;
4311
4296
  }
4312
- resource.custom.fields[name] = value;
4313
- }
4314
- setCustomType(context, resource, { type, fields }) {
4315
- if (!type) {
4316
- resource.custom = void 0;
4317
- } else {
4318
- const resolvedType = this._storage.getByResourceIdentifier(
4319
- context.projectKey,
4320
- type
4321
- );
4322
- if (!resolvedType) {
4323
- throw new Error(`Type ${type} not found`);
4297
+ if (addressId) {
4298
+ const address = resource.addresses.find((a) => a.id === addressId);
4299
+ if (!address) {
4300
+ throw new CommercetoolsError(
4301
+ {
4302
+ code: "InvalidOperation",
4303
+ message: `Customer does not contain an address with the id ${addressId}.`
4304
+ },
4305
+ 400
4306
+ );
4324
4307
  }
4325
- resource.custom = {
4326
- type: {
4327
- typeId: "type",
4328
- id: resolvedType.id
4308
+ return address;
4309
+ }
4310
+ if (required) {
4311
+ throw new CommercetoolsError(
4312
+ {
4313
+ code: "InvalidOperation",
4314
+ message: "One of address 'addressId' or 'addressKey' is required."
4329
4315
  },
4330
- fields: fields || {}
4331
- };
4316
+ 400
4317
+ );
4332
4318
  }
4333
4319
  }
4334
- setExpectedDelivery(context, resource, { expectedDelivery }) {
4335
- resource.expectedDelivery = new Date(expectedDelivery).toISOString();
4336
- }
4337
- setRestockableInDays(context, resource, { restockableInDays }) {
4338
- resource.restockableInDays = restockableInDays;
4339
- }
4340
4320
  };
4341
4321
 
4342
- // src/repositories/inventory-entry/index.ts
4343
- var InventoryEntryRepository = class extends AbstractResourceRepository {
4322
+ // src/repositories/customer/index.ts
4323
+ var CustomerRepository = class extends AbstractResourceRepository {
4344
4324
  constructor(storage) {
4345
- super("inventory-entry", storage);
4346
- this.actions = new InventoryEntryUpdateHandler(storage);
4325
+ super("customer", storage);
4326
+ this.actions = new CustomerUpdateHandler(storage);
4347
4327
  }
4348
4328
  create(context, draft) {
4329
+ const results = this._storage.query(context.projectKey, this.getTypeId(), {
4330
+ where: [`lowercaseEmail="${draft.email.toLowerCase()}"`]
4331
+ });
4332
+ if (results.count > 0) {
4333
+ throw new CommercetoolsError({
4334
+ code: "CustomerAlreadyExists",
4335
+ statusCode: 400,
4336
+ message: "There is already an existing customer with the provided email.",
4337
+ errors: [
4338
+ {
4339
+ code: "DuplicateField",
4340
+ message: `Customer with email '${draft.email}' already exists.`,
4341
+ duplicateValue: draft.email,
4342
+ field: "email"
4343
+ }
4344
+ ]
4345
+ });
4346
+ }
4347
+ const addresses = draft.addresses?.map((address) => ({
4348
+ ...address,
4349
+ id: generateRandomString(5)
4350
+ })) ?? [];
4351
+ const lookupAdressId = (addresses2, addressId) => {
4352
+ if (addressId < addresses2.length) {
4353
+ const id = addresses2[addressId].id;
4354
+ if (!id) {
4355
+ throw new Error("Address ID is missing");
4356
+ }
4357
+ return id;
4358
+ }
4359
+ throw new CommercetoolsError({
4360
+ code: "InvalidInput",
4361
+ message: `Address with ID '${addressId}' not found.`,
4362
+ errors: [
4363
+ {
4364
+ code: "InvalidInput",
4365
+ message: `Address with ID '${addressId}' not found.`,
4366
+ field: "addressId"
4367
+ }
4368
+ ]
4369
+ });
4370
+ };
4371
+ const defaultBillingAddressId = draft.defaultBillingAddress !== void 0 ? lookupAdressId(addresses, draft.defaultBillingAddress) : void 0;
4372
+ const defaultShippingAddressId = draft.defaultShippingAddress !== void 0 ? lookupAdressId(addresses, draft.defaultShippingAddress) : void 0;
4373
+ const shippingAddressIds = draft.shippingAddresses?.map(
4374
+ (addressId) => lookupAdressId(addresses, addressId)
4375
+ ) ?? [];
4376
+ const billingAddressIds = draft.billingAddresses?.map(
4377
+ (addressId) => lookupAdressId(addresses, addressId)
4378
+ ) ?? [];
4379
+ let storesForCustomer = [];
4380
+ if (draft.stores && draft.stores.length > 0) {
4381
+ storesForCustomer = this.storeReferenceToStoreKeyReference(
4382
+ draft.stores,
4383
+ context.projectKey
4384
+ );
4385
+ }
4349
4386
  const resource = {
4350
4387
  ...getBaseResourceProperties(),
4351
- sku: draft.sku,
4352
- quantityOnStock: draft.quantityOnStock,
4353
- availableQuantity: draft.quantityOnStock,
4354
- expectedDelivery: draft.expectedDelivery,
4355
- restockableInDays: draft.restockableInDays,
4356
- supplyChannel: {
4357
- ...draft.supplyChannel,
4358
- typeId: "channel",
4359
- id: draft.supplyChannel?.id ?? ""
4360
- },
4388
+ key: draft.key,
4389
+ authenticationMode: draft.authenticationMode || "Password",
4390
+ firstName: draft.firstName,
4391
+ lastName: draft.lastName,
4392
+ middleName: draft.middleName,
4393
+ title: draft.title,
4394
+ dateOfBirth: draft.dateOfBirth,
4395
+ companyName: draft.companyName,
4396
+ email: draft.email.toLowerCase(),
4397
+ lowercaseEmail: draft.email.toLowerCase(),
4398
+ password: draft.password ? hashPassword(draft.password) : void 0,
4399
+ isEmailVerified: draft.isEmailVerified || false,
4400
+ addresses,
4401
+ customerNumber: draft.customerNumber,
4402
+ externalId: draft.externalId,
4403
+ defaultBillingAddressId,
4404
+ defaultShippingAddressId,
4405
+ shippingAddressIds,
4406
+ billingAddressIds,
4361
4407
  custom: createCustomFields(
4362
4408
  draft.custom,
4363
4409
  context.projectKey,
4364
4410
  this._storage
4365
- )
4411
+ ),
4412
+ stores: storesForCustomer
4366
4413
  };
4367
4414
  return this.saveNew(context, resource);
4368
4415
  }
4369
- };
4370
-
4371
- // src/repositories/my-customer.ts
4372
- var MyCustomerRepository = class extends CustomerRepository {
4373
- changePassword(context, changePassword) {
4374
- const { currentPassword, newPassword } = changePassword;
4375
- const encodedPassword = hashPassword(currentPassword);
4376
- const result = this._storage.query(context.projectKey, "customer", {
4377
- where: [`password = "${encodedPassword}"`]
4378
- });
4379
- if (result.count === 0) {
4380
- throw new CommercetoolsError({
4381
- code: "InvalidCurrentPassword",
4382
- message: "Account with the given credentials not found."
4383
- });
4384
- }
4385
- const customer = result.results[0];
4386
- if (customer.password !== hashPassword(currentPassword)) {
4387
- throw new CommercetoolsError({
4388
- code: "InvalidCurrentPassword",
4389
- message: "The current password is invalid."
4390
- });
4391
- }
4392
- customer.password = hashPassword(newPassword);
4393
- customer.version += 1;
4394
- this._storage.add(context.projectKey, "customer", customer);
4395
- return customer;
4416
+ saveUpdate(context, version, resource) {
4417
+ const updatedResource = {
4418
+ ...resource,
4419
+ lowercaseEmail: resource.email.toLowerCase()
4420
+ };
4421
+ return super.saveUpdate(context, version, updatedResource);
4396
4422
  }
4397
- confirmEmail(context, resetPassword) {
4398
- const { tokenValue } = resetPassword;
4399
- const customerId = validateEmailVerifyToken(tokenValue);
4400
- if (!customerId) {
4401
- throw new CommercetoolsError({
4402
- code: "ResourceNotFound",
4403
- message: `The Customer with ID 'Token(${tokenValue})' was not found.`
4404
- });
4405
- }
4406
- const customer = this._storage.get(
4407
- context.projectKey,
4408
- "customer",
4409
- customerId
4410
- );
4411
- if (!customer) {
4423
+ passwordResetToken(context, request) {
4424
+ const results = this._storage.query(context.projectKey, this.getTypeId(), {
4425
+ where: [`email="${request.email.toLocaleLowerCase()}"`]
4426
+ });
4427
+ if (results.count === 0) {
4412
4428
  throw new CommercetoolsError({
4413
4429
  code: "ResourceNotFound",
4414
- message: `The Customer with ID 'Token(${tokenValue})' was not found.`
4430
+ message: `The Customer with ID '${request.email}' was not found.`
4415
4431
  });
4416
4432
  }
4417
- customer.isEmailVerified = true;
4418
- customer.version += 1;
4419
- this._storage.add(context.projectKey, "customer", customer);
4420
- return customer;
4421
- }
4422
- deleteMe(context) {
4423
- const results = this._storage.query(
4424
- context.projectKey,
4425
- this.getTypeId(),
4426
- {}
4427
- );
4428
- if (results.count > 0) {
4429
- return this.delete(context, results.results[0].id);
4430
- }
4431
- return;
4432
- }
4433
- getMe(context) {
4434
- const results = this._storage.query(
4435
- context.projectKey,
4436
- this.getTypeId(),
4437
- {}
4438
- );
4439
- if (results.count > 0) {
4440
- return results.results[0];
4441
- }
4442
- return;
4433
+ const ttlMinutes = request.ttlMinutes ?? 34560;
4434
+ const expiresAt = new Date((/* @__PURE__ */ new Date()).getTime() + ttlMinutes * 60 * 1e3);
4435
+ const customer = results.results[0];
4436
+ const rest = getBaseResourceProperties();
4437
+ const token = createPasswordResetToken(customer, expiresAt);
4438
+ return {
4439
+ id: rest.id,
4440
+ createdAt: rest.createdAt,
4441
+ lastModifiedAt: rest.lastModifiedAt,
4442
+ customerId: customer.id,
4443
+ expiresAt: expiresAt.toISOString(),
4444
+ value: token
4445
+ };
4443
4446
  }
4444
- };
4445
-
4446
- // src/repositories/my-order.ts
4447
- var import_assert3 = __toESM(require("assert"), 1);
4448
-
4449
- // src/repositories/order/index.ts
4450
- var import_assert2 = __toESM(require("assert"), 1);
4451
-
4452
- // src/repositories/order/actions.ts
4453
- var OrderUpdateHandler = class extends AbstractUpdateHandler {
4454
- addPayment(context, resource, { payment }) {
4455
- const resolvedPayment = this._storage.getByResourceIdentifier(
4447
+ passwordReset(context, resetPassword) {
4448
+ const { newPassword, tokenValue } = resetPassword;
4449
+ const customerId = validatePasswordResetToken(tokenValue);
4450
+ if (!customerId) {
4451
+ throw new CommercetoolsError({
4452
+ code: "ResourceNotFound",
4453
+ message: `The Customer with ID 'Token(${tokenValue})' was not found.`
4454
+ });
4455
+ }
4456
+ const customer = this._storage.get(
4456
4457
  context.projectKey,
4457
- payment
4458
+ "customer",
4459
+ customerId
4458
4460
  );
4459
- if (!resolvedPayment) {
4460
- throw new Error(`Payment ${payment.id} not found`);
4461
- }
4462
- if (!resource.paymentInfo) {
4463
- resource.paymentInfo = {
4464
- payments: []
4465
- };
4461
+ if (!customer) {
4462
+ throw new CommercetoolsError({
4463
+ code: "ResourceNotFound",
4464
+ message: `The Customer with ID 'Token(${tokenValue})' was not found.`
4465
+ });
4466
4466
  }
4467
- resource.paymentInfo.payments.push({
4468
- typeId: "payment",
4469
- id: payment.id
4470
- });
4467
+ customer.password = hashPassword(newPassword);
4468
+ customer.version += 1;
4469
+ this._storage.add(context.projectKey, "customer", customer);
4470
+ return customer;
4471
4471
  }
4472
- addReturnInfo(context, resource, info) {
4473
- if (!resource.returnInfo) {
4474
- resource.returnInfo = [];
4472
+ verifyEmailToken(context, id) {
4473
+ const results = this._storage.query(context.projectKey, this.getTypeId(), {
4474
+ where: [`id="${id.toLocaleLowerCase()}"`]
4475
+ });
4476
+ if (results.count === 0) {
4477
+ throw new CommercetoolsError({
4478
+ code: "ResourceNotFound",
4479
+ message: `The Customer with ID '${id}' was not found.`
4480
+ });
4475
4481
  }
4476
- const resolved = {
4477
- items: info.items.map((item) => {
4478
- const common = {
4479
- ...getBaseResourceProperties(),
4480
- quantity: item.quantity,
4481
- paymentState: "Initial",
4482
- shipmentState: "Initial",
4483
- comment: item.comment
4484
- };
4485
- if (item.customLineItemId) {
4486
- return {
4487
- ...common,
4488
- type: "CustomLineItemReturnItem",
4489
- customLineItemId: item.customLineItemId
4490
- };
4491
- }
4492
- return {
4493
- ...common,
4494
- type: "LineItemReturnItem",
4495
- lineItemId: item.customLineItemId || item.lineItemId
4496
- };
4497
- }),
4498
- returnTrackingId: info.returnTrackingId,
4499
- returnDate: info.returnDate
4482
+ const expiresAt = new Date(Date.now() + 30 * 60);
4483
+ const customer = results.results[0];
4484
+ const rest = getBaseResourceProperties();
4485
+ const token = createEmailVerifyToken(customer);
4486
+ return {
4487
+ id: rest.id,
4488
+ createdAt: rest.createdAt,
4489
+ lastModifiedAt: rest.lastModifiedAt,
4490
+ customerId: customer.id,
4491
+ expiresAt: expiresAt.toISOString(),
4492
+ value: token
4500
4493
  };
4501
- resource.returnInfo.push(resolved);
4502
4494
  }
4503
- changeOrderState(context, resource, { orderState }) {
4504
- resource.orderState = orderState;
4505
- }
4506
- changePaymentState(context, resource, { paymentState }) {
4507
- resource.paymentState = paymentState;
4508
- }
4509
- changeShipmentState(context, resource, { shipmentState }) {
4510
- resource.shipmentState = shipmentState;
4495
+ storeReferenceToStoreKeyReference(draftStores, projectKey) {
4496
+ const storeIds = draftStores.map((storeReference) => storeReference.id).filter(Boolean);
4497
+ let stores = [];
4498
+ if (storeIds.length > 0) {
4499
+ stores = this._storage.query(projectKey, "store", {
4500
+ where: storeIds.map((id) => `id="${id}"`)
4501
+ }).results;
4502
+ if (storeIds.length !== stores.length) {
4503
+ throw new CommercetoolsError({
4504
+ code: "ResourceNotFound",
4505
+ message: `Store with ID '${storeIds.find((id) => !stores.some((store) => store.id === id))}' was not found.`
4506
+ });
4507
+ }
4508
+ }
4509
+ return draftStores.map((storeReference) => ({
4510
+ typeId: "store",
4511
+ key: storeReference.key ?? stores.find((store) => store.id === storeReference.id)?.key
4512
+ }));
4511
4513
  }
4512
- setBillingAddress(context, resource, { address }) {
4513
- resource.billingAddress = createAddress(
4514
- address,
4515
- context.projectKey,
4516
- this._storage
4517
- );
4514
+ };
4515
+
4516
+ // src/repositories/customer-group.ts
4517
+ var CustomerGroupRepository = class extends AbstractResourceRepository {
4518
+ constructor(storage) {
4519
+ super("customer-group", storage);
4520
+ this.actions = new CustomerGroupUpdateHandler(storage);
4518
4521
  }
4519
- setCustomerEmail(context, resource, { email }) {
4520
- resource.customerEmail = email;
4522
+ create(context, draft) {
4523
+ const resource = {
4524
+ ...getBaseResourceProperties(),
4525
+ key: draft.key,
4526
+ name: draft.groupName,
4527
+ custom: createCustomFields(
4528
+ draft.custom,
4529
+ context.projectKey,
4530
+ this._storage
4531
+ )
4532
+ };
4533
+ return this.saveNew(context, resource);
4521
4534
  }
4522
- setCustomerId(context, resource, { customerId }) {
4523
- resource.customerId = customerId;
4535
+ };
4536
+ var CustomerGroupUpdateHandler = class extends AbstractUpdateHandler {
4537
+ changeName(context, resource, { name }) {
4538
+ resource.name = name;
4524
4539
  }
4525
4540
  setCustomField(context, resource, { name, value }) {
4526
4541
  if (!resource.custom) {
4527
- throw new Error("Resource has no custom field");
4542
+ return;
4543
+ }
4544
+ if (value === null) {
4545
+ delete resource.custom.fields[name];
4546
+ } else {
4547
+ resource.custom.fields[name] = value;
4528
4548
  }
4529
- resource.custom.fields[name] = value;
4530
4549
  }
4531
4550
  setCustomType(context, resource, { type, fields }) {
4532
- if (!type) {
4533
- resource.custom = void 0;
4534
- } else {
4535
- const resolvedType = this._storage.getByResourceIdentifier(
4551
+ if (type) {
4552
+ resource.custom = createCustomFields(
4553
+ { type, fields },
4536
4554
  context.projectKey,
4537
- type
4555
+ this._storage
4538
4556
  );
4539
- if (!resolvedType) {
4540
- throw new Error(`Type ${type} not found`);
4541
- }
4542
- resource.custom = {
4543
- type: {
4544
- typeId: "type",
4545
- id: resolvedType.id
4546
- },
4547
- fields: fields || {}
4548
- };
4549
- }
4550
- }
4551
- setDeliveryCustomField(context, resource, { deliveryId, name, value }) {
4552
- if (!resource.shippingInfo) {
4553
- throw new Error("Resource has no shipping info");
4554
- }
4555
- for (const delivery of resource.shippingInfo.deliveries || []) {
4556
- if (delivery.id === deliveryId && delivery.custom?.fields) {
4557
- delivery.custom.fields[name] = value;
4558
- }
4559
- }
4560
- }
4561
- setLocale(context, resource, { locale }) {
4562
- resource.locale = locale;
4563
- }
4564
- setOrderNumber(context, resource, { orderNumber }) {
4565
- resource.orderNumber = orderNumber;
4566
- }
4567
- setParcelCustomField(context, resource, { parcelId, name, value }) {
4568
- if (!resource.shippingInfo) {
4569
- throw new Error("Resource has no shipping info");
4570
- }
4571
- for (const delivery of resource.shippingInfo.deliveries || []) {
4572
- for (const parcel of delivery.parcels || []) {
4573
- if (parcel.id === parcelId && parcel.custom?.fields) {
4574
- parcel.custom.fields[name] = value;
4575
- }
4576
- }
4557
+ } else {
4558
+ resource.custom = void 0;
4577
4559
  }
4578
4560
  }
4579
- setPurchaseOrderNumber(context, resource, { purchaseOrderNumber }) {
4580
- resource.purchaseOrderNumber = purchaseOrderNumber;
4581
- }
4582
- setShippingAddress(context, resource, { address }) {
4583
- resource.shippingAddress = createAddress(
4584
- address,
4585
- context.projectKey,
4586
- this._storage
4587
- );
4561
+ setKey(context, resource, { key }) {
4562
+ resource.key = key;
4588
4563
  }
4589
- setStore(context, resource, { store }) {
4590
- if (!store) return;
4591
- const resolvedType = this._storage.getByResourceIdentifier(
4592
- context.projectKey,
4593
- store
4564
+ };
4565
+
4566
+ // src/repositories/discount-code/actions.ts
4567
+ var DiscountCodeUpdateHandler = class extends AbstractUpdateHandler {
4568
+ changeCartDiscounts(context, resource, { cartDiscounts }) {
4569
+ resource.cartDiscounts = cartDiscounts.map(
4570
+ (obj) => ({
4571
+ typeId: "cart-discount",
4572
+ id: obj.id
4573
+ })
4594
4574
  );
4595
- if (!resolvedType) {
4596
- throw new Error(`No store found with key=${store.key}`);
4597
- }
4598
- const storeReference = resolvedType;
4599
- resource.store = {
4600
- typeId: "store",
4601
- key: storeReference.key
4602
- };
4603
4575
  }
4604
- transitionState(context, resource, { state }) {
4605
- const resolvedType = this._storage.getByResourceIdentifier(
4606
- context.projectKey,
4607
- state
4608
- );
4609
- if (!resolvedType) {
4610
- throw new Error(
4611
- `No state found with key=${state.key} or id=${state.key}`
4612
- );
4613
- }
4614
- resource.state = {
4615
- typeId: "state",
4616
- id: resolvedType.id,
4617
- obj: { ...resolvedType, key: state.key ?? "" }
4618
- };
4576
+ changeIsActive(context, resource, { isActive }) {
4577
+ resource.isActive = isActive;
4619
4578
  }
4620
- updateSyncInfo(context, resource, { channel, externalId, syncedAt }) {
4621
- if (!channel) return;
4622
- const resolvedType = this._storage.getByResourceIdentifier(
4623
- context.projectKey,
4624
- channel
4625
- );
4626
- if (!resolvedType) {
4627
- throw new Error(`Channel ${channel} not found`);
4579
+ setCartPredicate(context, resource, { cartPredicate }) {
4580
+ resource.cartPredicate = cartPredicate;
4581
+ }
4582
+ setCustomField(context, resource, { name, value }) {
4583
+ if (!resource.custom) {
4584
+ return;
4628
4585
  }
4629
- const syncData = {
4630
- channel: {
4631
- typeId: "channel",
4632
- id: resolvedType.id
4633
- },
4634
- externalId,
4635
- syncedAt: syncedAt ?? (/* @__PURE__ */ new Date()).toISOString()
4636
- };
4637
- if (!resource.syncInfo?.length) {
4638
- resource.syncInfo = [syncData];
4586
+ if (value === null) {
4587
+ delete resource.custom.fields[name];
4639
4588
  } else {
4640
- const lastSyncInfo = resource.syncInfo[resource.syncInfo.length - 1];
4641
- if (lastSyncInfo.channel.id !== syncData.channel.id || lastSyncInfo.externalId !== syncData.externalId) {
4642
- resource.syncInfo.push(syncData);
4643
- }
4589
+ resource.custom.fields[name] = value;
4590
+ }
4591
+ }
4592
+ setCustomType(context, resource, { type, fields }) {
4593
+ if (type) {
4594
+ resource.custom = createCustomFields(
4595
+ { type, fields },
4596
+ context.projectKey,
4597
+ this._storage
4598
+ );
4599
+ } else {
4600
+ resource.custom = void 0;
4644
4601
  }
4645
4602
  }
4603
+ setDescription(context, resource, { description }) {
4604
+ resource.description = description;
4605
+ }
4606
+ setMaxApplications(context, resource, { maxApplications }) {
4607
+ resource.maxApplications = maxApplications;
4608
+ }
4609
+ setMaxApplicationsPerCustomer(context, resource, {
4610
+ maxApplicationsPerCustomer
4611
+ }) {
4612
+ resource.maxApplicationsPerCustomer = maxApplicationsPerCustomer;
4613
+ }
4614
+ setName(context, resource, { name }) {
4615
+ resource.name = name;
4616
+ }
4617
+ setValidFrom(context, resource, { validFrom }) {
4618
+ resource.validFrom = validFrom;
4619
+ }
4620
+ setValidFromAndUntil(context, resource, { validFrom, validUntil }) {
4621
+ resource.validFrom = validFrom;
4622
+ resource.validUntil = validUntil;
4623
+ }
4624
+ setValidUntil(context, resource, { validUntil }) {
4625
+ resource.validUntil = validUntil;
4626
+ }
4646
4627
  };
4647
4628
 
4648
- // src/repositories/order/index.ts
4649
- var OrderRepository = class extends AbstractResourceRepository {
4629
+ // src/repositories/discount-code/index.ts
4630
+ var DiscountCodeRepository = class extends AbstractResourceRepository {
4650
4631
  constructor(storage) {
4651
- super("order", storage);
4652
- this.actions = new OrderUpdateHandler(storage);
4632
+ super("discount-code", storage);
4633
+ this.actions = new DiscountCodeUpdateHandler(storage);
4653
4634
  }
4654
4635
  create(context, draft) {
4655
- (0, import_assert2.default)(draft.cart, "draft.cart is missing");
4656
- return this.createFromCart(
4657
- context,
4658
- {
4659
- id: draft.cart.id,
4660
- typeId: "cart"
4661
- },
4662
- draft.orderNumber
4663
- );
4664
- }
4665
- createFromCart(context, cartReference, orderNumber) {
4666
- const cart = this._storage.getByResourceIdentifier(
4667
- context.projectKey,
4668
- cartReference
4669
- );
4670
- if (!cart) {
4671
- throw new Error("Cannot find cart");
4672
- }
4673
- const resource = {
4674
- ...getBaseResourceProperties(),
4675
- anonymousId: cart.anonymousId,
4676
- billingAddress: cart.billingAddress,
4677
- cart: cartReference,
4678
- country: cart.country,
4679
- custom: cart.custom,
4680
- customerEmail: cart.customerEmail,
4681
- customerGroup: cart.customerGroup,
4682
- customerId: cart.customerId,
4683
- customLineItems: [],
4684
- directDiscounts: cart.directDiscounts,
4685
- discountCodes: cart.discountCodes,
4686
- discountOnTotalPrice: cart.discountOnTotalPrice,
4687
- lastMessageSequenceNumber: 0,
4688
- lineItems: cart.lineItems,
4689
- locale: cart.locale,
4690
- orderNumber: orderNumber ?? generateRandomString(10),
4691
- orderState: "Open",
4692
- origin: "Customer",
4693
- paymentInfo: cart.paymentInfo,
4694
- refusedGifts: [],
4695
- shipping: cart.shipping,
4696
- shippingAddress: cart.shippingAddress,
4697
- shippingMode: cart.shippingMode,
4698
- syncInfo: [],
4699
- taxCalculationMode: cart.taxCalculationMode,
4700
- taxedPrice: cart.taxedPrice,
4701
- taxedShippingPrice: cart.taxedShippingPrice,
4702
- taxMode: cart.taxMode,
4703
- taxRoundingMode: cart.taxRoundingMode,
4704
- totalPrice: cart.totalPrice,
4705
- store: cart.store
4706
- };
4707
- return this.saveNew(context, resource);
4708
- }
4709
- import(context, draft) {
4710
- (0, import_assert2.default)(this, "OrderRepository not valid");
4711
4636
  const resource = {
4712
4637
  ...getBaseResourceProperties(),
4713
- billingAddress: createAddress(
4714
- draft.billingAddress,
4715
- context.projectKey,
4716
- this._storage
4717
- ),
4718
- shippingAddress: createAddress(
4719
- draft.shippingAddress,
4720
- context.projectKey,
4721
- this._storage
4638
+ applicationVersion: 1,
4639
+ cartDiscounts: draft.cartDiscounts.map(
4640
+ (obj) => ({
4641
+ typeId: "cart-discount",
4642
+ id: obj.id
4643
+ })
4722
4644
  ),
4645
+ cartPredicate: draft.cartPredicate,
4646
+ code: draft.code,
4647
+ description: draft.description,
4648
+ groups: draft.groups || [],
4649
+ isActive: draft.isActive || true,
4650
+ name: draft.name,
4651
+ references: [],
4652
+ validFrom: draft.validFrom,
4653
+ validUntil: draft.validUntil,
4654
+ maxApplications: draft.maxApplications,
4655
+ maxApplicationsPerCustomer: draft.maxApplicationsPerCustomer,
4723
4656
  custom: createCustomFields(
4724
4657
  draft.custom,
4725
4658
  context.projectKey,
4726
4659
  this._storage
4727
- ),
4728
- customerEmail: draft.customerEmail,
4729
- lastMessageSequenceNumber: 0,
4730
- orderNumber: draft.orderNumber,
4731
- orderState: draft.orderState || "Open",
4732
- origin: draft.origin || "Customer",
4733
- paymentState: draft.paymentState,
4734
- refusedGifts: [],
4735
- shippingMode: "Single",
4736
- shipping: [],
4737
- store: resolveStoreReference(
4738
- draft.store,
4739
- context.projectKey,
4740
- this._storage
4741
- ),
4742
- syncInfo: [],
4743
- lineItems: draft.lineItems?.map(
4744
- (item) => this.lineItemFromImportDraft.bind(this)(context, item)
4745
- ) || [],
4746
- customLineItems: draft.customLineItems?.map(
4747
- (item) => this.customLineItemFromImportDraft.bind(this)(context, item)
4748
- ) || [],
4749
- totalPrice: createCentPrecisionMoney(draft.totalPrice)
4660
+ )
4750
4661
  };
4751
4662
  return this.saveNew(context, resource);
4752
4663
  }
4753
- lineItemFromImportDraft(context, draft) {
4754
- let product;
4755
- let variant;
4756
- if (draft.variant.sku) {
4757
- variant = {
4758
- id: 0,
4759
- sku: draft.variant.sku
4760
- };
4761
- const items = this._storage.query(context.projectKey, "product", {
4762
- where: [
4763
- `masterData(current(masterVariant(sku="${draft.variant.sku}"))) or masterData(current(variants(sku="${draft.variant.sku}")))`
4764
- ]
4765
- });
4766
- if (items.count !== 1) {
4767
- throw new CommercetoolsError({
4768
- code: "General",
4769
- message: `A product containing a variant with SKU '${draft.variant.sku}' not found.`
4770
- });
4771
- }
4772
- product = items.results[0];
4773
- if (product.masterData.current.masterVariant.sku === draft.variant.sku) {
4774
- variant = product.masterData.current.masterVariant;
4775
- } else {
4776
- variant = product.masterData.current.variants.find(
4777
- (v) => v.sku === draft.variant.sku
4664
+ };
4665
+
4666
+ // src/lib/masking.ts
4667
+ var maskSecretValue = (resource, path) => {
4668
+ const parts = path.split(".");
4669
+ const clone = cloneObject(resource);
4670
+ let val = clone;
4671
+ const target = parts.pop();
4672
+ for (let i = 0; i < parts.length; i++) {
4673
+ const part = parts[i];
4674
+ val = val[part];
4675
+ if (val === void 0) {
4676
+ return resource;
4677
+ }
4678
+ }
4679
+ if (val && target && val[target]) {
4680
+ val[target] = "****";
4681
+ }
4682
+ return clone;
4683
+ };
4684
+
4685
+ // src/repositories/extension.ts
4686
+ var ExtensionRepository = class extends AbstractResourceRepository {
4687
+ constructor(storage) {
4688
+ super("extension", storage);
4689
+ this.actions = new ExtensionUpdateHandler(storage);
4690
+ }
4691
+ create(context, draft) {
4692
+ const resource = {
4693
+ ...getBaseResourceProperties(),
4694
+ key: draft.key,
4695
+ timeoutInMs: draft.timeoutInMs,
4696
+ destination: draft.destination,
4697
+ triggers: draft.triggers
4698
+ };
4699
+ return this.saveNew(context, resource);
4700
+ }
4701
+ postProcessResource(context, resource) {
4702
+ if (resource) {
4703
+ const extension = resource;
4704
+ if (extension.destination.type === "HTTP" && extension.destination.authentication?.type === "AuthorizationHeader") {
4705
+ return maskSecretValue(
4706
+ extension,
4707
+ "destination.authentication.headerValue"
4778
4708
  );
4709
+ } else if (extension.destination.type === "AWSLambda") {
4710
+ return maskSecretValue(resource, "destination.accessSecret");
4779
4711
  }
4780
- if (!variant) {
4781
- throw new Error("Internal state error");
4782
- }
4783
- } else {
4784
- throw new Error("No product found");
4785
4712
  }
4786
- const lineItem = {
4787
- ...getBaseResourceProperties(),
4788
- custom: createCustomFields(
4789
- draft.custom,
4713
+ return resource;
4714
+ }
4715
+ };
4716
+ var ExtensionUpdateHandler = class extends AbstractUpdateHandler {
4717
+ changeDestination(context, resource, action) {
4718
+ resource.destination = action.destination;
4719
+ }
4720
+ changeTriggers(context, resource, action) {
4721
+ resource.triggers = action.triggers;
4722
+ }
4723
+ setKey(context, resource, action) {
4724
+ resource.key = action.key;
4725
+ }
4726
+ setTimeoutInMs(context, resource, action) {
4727
+ resource.timeoutInMs = action.timeoutInMs;
4728
+ }
4729
+ };
4730
+
4731
+ // src/repositories/inventory-entry/actions.ts
4732
+ var InventoryEntryUpdateHandler = class extends AbstractUpdateHandler {
4733
+ changeQuantity(context, resource, { quantity }) {
4734
+ resource.quantityOnStock = quantity;
4735
+ resource.availableQuantity = quantity;
4736
+ }
4737
+ setCustomField(context, resource, { name, value }) {
4738
+ if (!resource.custom) {
4739
+ throw new Error("Resource has no custom field");
4740
+ }
4741
+ resource.custom.fields[name] = value;
4742
+ }
4743
+ setCustomType(context, resource, { type, fields }) {
4744
+ if (!type) {
4745
+ resource.custom = void 0;
4746
+ } else {
4747
+ const resolvedType = this._storage.getByResourceIdentifier(
4790
4748
  context.projectKey,
4791
- this._storage
4792
- ),
4793
- discountedPricePerQuantity: [],
4794
- lineItemMode: "Standard",
4795
- name: draft.name,
4796
- price: createPrice(draft.price),
4797
- priceMode: "Platform",
4798
- productId: product.id,
4799
- productType: product.productType,
4800
- quantity: draft.quantity,
4801
- state: draft.state || [],
4802
- taxRate: draft.taxRate,
4803
- taxedPricePortions: [],
4804
- perMethodTaxRate: [],
4805
- totalPrice: createCentPrecisionMoney(draft.price.value),
4806
- variant: {
4807
- id: variant.id,
4808
- sku: variant.sku,
4809
- price: createPrice(draft.price)
4749
+ type
4750
+ );
4751
+ if (!resolvedType) {
4752
+ throw new Error(`Type ${type} not found`);
4810
4753
  }
4811
- };
4812
- return lineItem;
4754
+ resource.custom = {
4755
+ type: {
4756
+ typeId: "type",
4757
+ id: resolvedType.id
4758
+ },
4759
+ fields: fields || {}
4760
+ };
4761
+ }
4813
4762
  }
4814
- customLineItemFromImportDraft(context, draft) {
4815
- const lineItem = {
4763
+ setExpectedDelivery(context, resource, { expectedDelivery }) {
4764
+ resource.expectedDelivery = new Date(expectedDelivery).toISOString();
4765
+ }
4766
+ setRestockableInDays(context, resource, { restockableInDays }) {
4767
+ resource.restockableInDays = restockableInDays;
4768
+ }
4769
+ };
4770
+
4771
+ // src/repositories/inventory-entry/index.ts
4772
+ var InventoryEntryRepository = class extends AbstractResourceRepository {
4773
+ constructor(storage) {
4774
+ super("inventory-entry", storage);
4775
+ this.actions = new InventoryEntryUpdateHandler(storage);
4776
+ }
4777
+ create(context, draft) {
4778
+ const resource = {
4816
4779
  ...getBaseResourceProperties(),
4780
+ sku: draft.sku,
4781
+ quantityOnStock: draft.quantityOnStock,
4782
+ availableQuantity: draft.quantityOnStock,
4783
+ expectedDelivery: draft.expectedDelivery,
4784
+ restockableInDays: draft.restockableInDays,
4785
+ supplyChannel: {
4786
+ ...draft.supplyChannel,
4787
+ typeId: "channel",
4788
+ id: draft.supplyChannel?.id ?? ""
4789
+ },
4817
4790
  custom: createCustomFields(
4818
4791
  draft.custom,
4819
4792
  context.projectKey,
4820
4793
  this._storage
4821
- ),
4822
- discountedPricePerQuantity: [],
4823
- money: createTypedMoney(draft.money),
4824
- name: draft.name,
4825
- quantity: draft.quantity ?? 0,
4826
- perMethodTaxRate: [],
4827
- priceMode: draft.priceMode ?? "Standard",
4828
- slug: draft.slug,
4829
- state: [],
4830
- totalPrice: createCentPrecisionMoney(draft.money),
4831
- taxedPricePortions: []
4794
+ )
4832
4795
  };
4833
- return lineItem;
4796
+ return this.saveNew(context, resource);
4834
4797
  }
4835
- getWithOrderNumber(context, orderNumber, params = {}) {
4836
- const result = this._storage.query(context.projectKey, this.getTypeId(), {
4837
- ...params,
4838
- where: [`orderNumber="${orderNumber}"`]
4798
+ };
4799
+
4800
+ // src/repositories/my-customer.ts
4801
+ var MyCustomerRepository = class extends CustomerRepository {
4802
+ changePassword(context, changePassword) {
4803
+ const { currentPassword, newPassword } = changePassword;
4804
+ const encodedPassword = hashPassword(currentPassword);
4805
+ const result = this._storage.query(context.projectKey, "customer", {
4806
+ where: [`password = "${encodedPassword}"`]
4839
4807
  });
4840
- if (result.count === 1) {
4841
- return result.results[0];
4808
+ if (result.count === 0) {
4809
+ throw new CommercetoolsError({
4810
+ code: "InvalidCurrentPassword",
4811
+ message: "Account with the given credentials not found."
4812
+ });
4842
4813
  }
4843
- if (result.count > 1) {
4844
- throw new Error("Duplicate order numbers");
4814
+ const customer = result.results[0];
4815
+ if (customer.password !== hashPassword(currentPassword)) {
4816
+ throw new CommercetoolsError({
4817
+ code: "InvalidCurrentPassword",
4818
+ message: "The current password is invalid."
4819
+ });
4820
+ }
4821
+ customer.password = hashPassword(newPassword);
4822
+ customer.version += 1;
4823
+ this._storage.add(context.projectKey, "customer", customer);
4824
+ return customer;
4825
+ }
4826
+ confirmEmail(context, resetPassword) {
4827
+ const { tokenValue } = resetPassword;
4828
+ const customerId = validateEmailVerifyToken(tokenValue);
4829
+ if (!customerId) {
4830
+ throw new CommercetoolsError({
4831
+ code: "ResourceNotFound",
4832
+ message: `The Customer with ID 'Token(${tokenValue})' was not found.`
4833
+ });
4834
+ }
4835
+ const customer = this._storage.get(
4836
+ context.projectKey,
4837
+ "customer",
4838
+ customerId
4839
+ );
4840
+ if (!customer) {
4841
+ throw new CommercetoolsError({
4842
+ code: "ResourceNotFound",
4843
+ message: `The Customer with ID 'Token(${tokenValue})' was not found.`
4844
+ });
4845
+ }
4846
+ customer.isEmailVerified = true;
4847
+ customer.version += 1;
4848
+ this._storage.add(context.projectKey, "customer", customer);
4849
+ return customer;
4850
+ }
4851
+ deleteMe(context) {
4852
+ const results = this._storage.query(
4853
+ context.projectKey,
4854
+ this.getTypeId(),
4855
+ {}
4856
+ );
4857
+ if (results.count > 0) {
4858
+ return this.delete(context, results.results[0].id);
4859
+ }
4860
+ return;
4861
+ }
4862
+ getMe(context) {
4863
+ const results = this._storage.query(
4864
+ context.projectKey,
4865
+ this.getTypeId(),
4866
+ {}
4867
+ );
4868
+ if (results.count > 0) {
4869
+ return results.results[0];
4845
4870
  }
4846
4871
  return;
4847
4872
  }
4848
4873
  };
4849
4874
 
4850
4875
  // src/repositories/my-order.ts
4876
+ var import_assert3 = __toESM(require("assert"), 1);
4851
4877
  var MyOrderRepository = class extends OrderRepository {
4852
4878
  create(context, draft) {
4853
4879
  (0, import_assert3.default)(draft.id, "draft.id is missing");
@@ -6863,6 +6889,17 @@ var ProductSelectionUpdateHandler = class extends AbstractUpdateHandler {
6863
6889
  changeName(context, resource, { name }) {
6864
6890
  resource.name = name;
6865
6891
  }
6892
+ setCustomType(context, resource, { type, fields }) {
6893
+ if (type) {
6894
+ resource.custom = createCustomFields(
6895
+ { type, fields },
6896
+ context.projectKey,
6897
+ this._storage
6898
+ );
6899
+ } else {
6900
+ resource.custom = void 0;
6901
+ }
6902
+ }
6866
6903
  };
6867
6904
 
6868
6905
  // src/repositories/product-type.ts
@@ -8005,6 +8042,10 @@ var ZoneUpdateHandler = class extends AbstractUpdateHandler {
8005
8042
 
8006
8043
  // src/repositories/index.ts
8007
8044
  var createRepositories = (storage) => ({
8045
+ "as-associate": {
8046
+ cart: new AsAssociateCartRepository(storage),
8047
+ order: new AsAssociateOrderRepository(storage)
8048
+ },
8008
8049
  "associate-role": new AssociateRoleRepository(storage),
8009
8050
  "attribute-group": new AttributeGroupRepository(storage),
8010
8051
  "business-unit": new BusinessUnitRepository(storage),
@@ -8048,6 +8089,12 @@ var createRepositories = (storage) => ({
8048
8089
  "zone": new ZoneRepository(storage)
8049
8090
  });
8050
8091
 
8092
+ // src/services/as-associate.ts
8093
+ var import_express5 = require("express");
8094
+
8095
+ // src/services/as-associate-cart.ts
8096
+ var import_express3 = require("express");
8097
+
8051
8098
  // src/services/abstract.ts
8052
8099
  var import_express2 = require("express");
8053
8100
 
@@ -8237,6 +8284,70 @@ var AbstractService = class {
8237
8284
  }
8238
8285
  };
8239
8286
 
8287
+ // src/services/as-associate-cart.ts
8288
+ var AsAssociateCartService = class extends AbstractService {
8289
+ repository;
8290
+ constructor(parent, repository) {
8291
+ super(parent);
8292
+ this.repository = repository;
8293
+ }
8294
+ getBasePath() {
8295
+ return "carts";
8296
+ }
8297
+ registerRoutes(parent) {
8298
+ const basePath = this.getBasePath();
8299
+ const router = (0, import_express3.Router)({ mergeParams: true });
8300
+ this.extraRoutes(router);
8301
+ router.get("/", this.get.bind(this));
8302
+ router.get("/:id", this.getWithId.bind(this));
8303
+ router.delete("/:id", this.deleteWithId.bind(this));
8304
+ router.post("/", this.post.bind(this));
8305
+ router.post("/:id", this.postWithId.bind(this));
8306
+ parent.use(`/${basePath}`, router);
8307
+ }
8308
+ };
8309
+
8310
+ // src/services/as-associate-order.ts
8311
+ var import_express4 = require("express");
8312
+ var AsAssociateOrderService = class extends AbstractService {
8313
+ repository;
8314
+ constructor(parent, repository) {
8315
+ super(parent);
8316
+ this.repository = repository;
8317
+ }
8318
+ getBasePath() {
8319
+ return "orders";
8320
+ }
8321
+ registerRoutes(parent) {
8322
+ const basePath = this.getBasePath();
8323
+ const router = (0, import_express4.Router)({ mergeParams: true });
8324
+ this.extraRoutes(router);
8325
+ router.get("/", this.get.bind(this));
8326
+ router.get("/:id", this.getWithId.bind(this));
8327
+ router.delete("/:id", this.deleteWithId.bind(this));
8328
+ router.post("/", this.post.bind(this));
8329
+ router.post("/:id", this.postWithId.bind(this));
8330
+ parent.use(`/${basePath}`, router);
8331
+ }
8332
+ };
8333
+
8334
+ // src/services/as-associate.ts
8335
+ var AsAssociateService = class {
8336
+ router;
8337
+ subServices;
8338
+ constructor(parent, repositories) {
8339
+ this.router = (0, import_express5.Router)({ mergeParams: true });
8340
+ this.subServices = {
8341
+ order: new AsAssociateOrderService(this.router, repositories.order),
8342
+ cart: new AsAssociateCartService(this.router, repositories.cart)
8343
+ };
8344
+ parent.use(
8345
+ "/as-associate/:associateId/in-business-unit/key=:businessUnitId",
8346
+ this.router
8347
+ );
8348
+ }
8349
+ };
8350
+
8240
8351
  // src/services/associate-roles.ts
8241
8352
  var AssociateRoleServices = class extends AbstractService {
8242
8353
  repository;
@@ -8518,7 +8629,7 @@ var InventoryEntryService = class extends AbstractService {
8518
8629
  };
8519
8630
 
8520
8631
  // src/services/my-business-unit.ts
8521
- var import_express3 = require("express");
8632
+ var import_express6 = require("express");
8522
8633
  var MyBusinessUnitService = class extends AbstractService {
8523
8634
  repository;
8524
8635
  constructor(parent, repository) {
@@ -8530,7 +8641,7 @@ var MyBusinessUnitService = class extends AbstractService {
8530
8641
  }
8531
8642
  registerRoutes(parent) {
8532
8643
  const basePath = this.getBasePath();
8533
- const router = (0, import_express3.Router)({ mergeParams: true });
8644
+ const router = (0, import_express6.Router)({ mergeParams: true });
8534
8645
  this.extraRoutes(router);
8535
8646
  router.get("/business-units/", this.get.bind(this));
8536
8647
  parent.use(`/${basePath}`, router);
@@ -8538,7 +8649,7 @@ var MyBusinessUnitService = class extends AbstractService {
8538
8649
  };
8539
8650
 
8540
8651
  // src/services/my-cart.ts
8541
- var import_express4 = require("express");
8652
+ var import_express7 = require("express");
8542
8653
  var MyCartService = class extends AbstractService {
8543
8654
  repository;
8544
8655
  constructor(parent, repository) {
@@ -8550,7 +8661,7 @@ var MyCartService = class extends AbstractService {
8550
8661
  }
8551
8662
  registerRoutes(parent) {
8552
8663
  const basePath = this.getBasePath();
8553
- const router = (0, import_express4.Router)({ mergeParams: true });
8664
+ const router = (0, import_express7.Router)({ mergeParams: true });
8554
8665
  this.extraRoutes(router);
8555
8666
  router.get("/active-cart", this.activeCart.bind(this));
8556
8667
  router.get("/carts/", this.get.bind(this));
@@ -8570,7 +8681,7 @@ var MyCartService = class extends AbstractService {
8570
8681
  };
8571
8682
 
8572
8683
  // src/services/my-customer.ts
8573
- var import_express5 = require("express");
8684
+ var import_express8 = require("express");
8574
8685
  var MyCustomerService = class extends AbstractService {
8575
8686
  repository;
8576
8687
  constructor(parent, repository) {
@@ -8582,7 +8693,7 @@ var MyCustomerService = class extends AbstractService {
8582
8693
  }
8583
8694
  registerRoutes(parent) {
8584
8695
  const basePath = this.getBasePath();
8585
- const router = (0, import_express5.Router)({ mergeParams: true });
8696
+ const router = (0, import_express8.Router)({ mergeParams: true });
8586
8697
  this.extraRoutes(router);
8587
8698
  router.get("", this.getMe.bind(this));
8588
8699
  router.post("", this.updateMe.bind(this));
@@ -8678,7 +8789,7 @@ var MyCustomerService = class extends AbstractService {
8678
8789
  };
8679
8790
 
8680
8791
  // src/services/my-order.ts
8681
- var import_express6 = require("express");
8792
+ var import_express9 = require("express");
8682
8793
  var MyOrderService = class extends AbstractService {
8683
8794
  repository;
8684
8795
  constructor(parent, repository) {
@@ -8690,7 +8801,7 @@ var MyOrderService = class extends AbstractService {
8690
8801
  }
8691
8802
  registerRoutes(parent) {
8692
8803
  const basePath = this.getBasePath();
8693
- const router = (0, import_express6.Router)({ mergeParams: true });
8804
+ const router = (0, import_express9.Router)({ mergeParams: true });
8694
8805
  this.extraRoutes(router);
8695
8806
  router.get("/orders/", this.get.bind(this));
8696
8807
  router.get("/orders/:id", this.getWithId.bind(this));
@@ -9026,6 +9137,7 @@ var ZoneService = class extends AbstractService {
9026
9137
  // src/services/index.ts
9027
9138
  var createServices = (router, repos) => ({
9028
9139
  "associate-role": new AssociateRoleServices(router, repos["associate-role"]),
9140
+ "as-associate": new AsAssociateService(router, repos["as-associate"]),
9029
9141
  "business-unit": new BusinessUnitServices(router, repos["business-unit"]),
9030
9142
  "category": new CategoryServices(router, repos["category"]),
9031
9143
  "cart": new CartService(router, repos["cart"], repos["order"]),
@@ -9140,12 +9252,10 @@ var CommercetoolsMock = class {
9140
9252
  _storage;
9141
9253
  _oauth2;
9142
9254
  _mswServer = void 0;
9143
- _services;
9144
9255
  _repositories;
9145
9256
  _projectService;
9146
9257
  constructor(options = {}) {
9147
9258
  this.options = { ...DEFAULT_OPTIONS, ...options };
9148
- this._services = null;
9149
9259
  this._repositories = null;
9150
9260
  this._projectService = void 0;
9151
9261
  this._storage = new InMemoryStorage();
@@ -9197,9 +9307,9 @@ var CommercetoolsMock = class {
9197
9307
  createApp(options) {
9198
9308
  this._repositories = createRepositories(this._storage);
9199
9309
  this._oauth2.setCustomerRepository(this._repositories.customer);
9200
- const app = (0, import_express7.default)();
9201
- const projectRouter = import_express7.default.Router({ mergeParams: true });
9202
- projectRouter.use(import_express7.default.json());
9310
+ const app = (0, import_express10.default)();
9311
+ const projectRouter = import_express10.default.Router({ mergeParams: true });
9312
+ projectRouter.use(import_express10.default.json());
9203
9313
  if (!options?.silent) {
9204
9314
  app.use((0, import_morgan.default)("tiny"));
9205
9315
  }
@@ -9215,7 +9325,7 @@ var CommercetoolsMock = class {
9215
9325
  app.use("/:projectKey", projectRouter);
9216
9326
  app.use("/:projectKey/in-store/key=:storeKey", projectRouter);
9217
9327
  }
9218
- this._services = createServices(projectRouter, this._repositories);
9328
+ createServices(projectRouter, this._repositories);
9219
9329
  this._projectService = new ProjectService(
9220
9330
  projectRouter,
9221
9331
  this._repositories.project