@labdigital/commercetools-mock 2.41.1 → 2.42.0

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