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