@labdigital/commercetools-mock 2.41.1 → 2.42.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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,24 +3304,29 @@ 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;
3307
+ var AssociateRoleUpdateHandler = class extends AbstractUpdateHandler {
3308
+ addPermission(context, resource, { permission }) {
3309
+ if (!resource.permissions) {
3310
+ resource.permissions = [permission];
3311
+ } else {
3312
+ resource.permissions.push(permission);
3313
+ }
3466
3314
  }
3467
- changeKey(context, resource, { key }) {
3468
- resource.key = key;
3315
+ changeBuyerAssignable(context, resource, { buyerAssignable }) {
3316
+ resource.buyerAssignable = buyerAssignable;
3469
3317
  }
3470
- changeName(context, resource, { name }) {
3471
- resource.name = name;
3318
+ removePermission(context, resource, { permission }) {
3319
+ if (!resource.permissions) {
3320
+ return;
3321
+ }
3322
+ resource.permissions = resource.permissions.filter((p) => {
3323
+ p !== permission;
3324
+ });
3472
3325
  }
3473
- setAddress(context, resource, { address }) {
3474
- resource.address = createAddress(
3475
- address,
3476
- context.projectKey,
3477
- this._storage
3478
- );
3326
+ setBuyerAssignable(context, resource, { buyerAssignable }) {
3327
+ resource.buyerAssignable = buyerAssignable;
3479
3328
  }
3480
- setCustomField(context, resource, { name, value }) {
3329
+ setCustomFields(context, resource, { name, value }) {
3481
3330
  if (!resource.custom) {
3482
3331
  return;
3483
3332
  }
@@ -3498,245 +3347,185 @@ var ChannelUpdateHandler = class extends AbstractUpdateHandler {
3498
3347
  resource.custom = void 0;
3499
3348
  }
3500
3349
  }
3501
- setGeoLocation(context, resource, { geoLocation }) {
3502
- resource.geoLocation = geoLocation;
3350
+ setName(context, resource, { name }) {
3351
+ resource.name = name;
3352
+ }
3353
+ setPermissions(context, resource, { permissions }) {
3354
+ resource.permissions = permissions || [];
3503
3355
  }
3504
3356
  };
3505
3357
 
3506
- // src/repositories/custom-object.ts
3507
- var CustomObjectRepository = class extends AbstractResourceRepository {
3358
+ // src/repositories/attribute-group.ts
3359
+ var AttributeGroupRepository = class extends AbstractResourceRepository {
3508
3360
  constructor(storage) {
3509
- super("key-value-document", storage);
3361
+ super("attribute-group", storage);
3362
+ this.actions = new AttributeGroupUpdateHandler(this._storage);
3510
3363
  }
3511
3364
  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;
3531
- } 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
- }
3365
+ const resource = {
3366
+ ...getBaseResourceProperties(),
3367
+ name: draft.name,
3368
+ description: draft.description,
3369
+ key: draft.key,
3370
+ attributes: draft.attributes
3371
+ };
3372
+ return this.saveNew(context, resource);
3373
+ }
3374
+ };
3375
+ var AttributeGroupUpdateHandler = class extends AbstractUpdateHandler {
3376
+ changeName(_context, resource, { name }) {
3377
+ resource.name = name;
3551
3378
  }
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
- );
3379
+ setAttributes(_context, resource, { attributes }) {
3380
+ resource.attributes = attributes;
3557
3381
  }
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;
3382
+ setDescription(_context, resource, { description }) {
3383
+ resource.description = description;
3384
+ }
3385
+ setKey(_context, resource, { key }) {
3386
+ resource.key = key;
3571
3387
  }
3572
3388
  };
3573
3389
 
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
- });
3390
+ // src/repositories/business-unit.ts
3391
+ var BusinessUnitRepository = class extends AbstractResourceRepository {
3392
+ constructor(storage) {
3393
+ super("business-unit", storage);
3394
+ this.actions = new BusinessUnitUpdateHandler(this._storage);
3582
3395
  }
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);
3396
+ create(context, draft) {
3397
+ const addresses = draft.addresses?.map((address) => ({
3398
+ ...address,
3399
+ id: generateRandomString(5)
3400
+ })) ?? [];
3401
+ const defaultBillingAddressId = addresses.length > 0 && draft.defaultBillingAddress !== void 0 ? addresses[draft.defaultBillingAddress].id : void 0;
3402
+ const defaultShippingAddressId = addresses.length > 0 && draft.defaultShippingAddress !== void 0 ? addresses[draft.defaultShippingAddress].id : void 0;
3403
+ const shippingAddressIds = draft.shippingAddresses?.map(
3404
+ (i) => addresses[i].id
3405
+ );
3406
+ const billingAddressIds = draft.billingAddresses?.map(
3407
+ (i) => addresses[i].id
3408
+ );
3409
+ const resource = {
3410
+ ...getBaseResourceProperties(),
3411
+ key: draft.key,
3412
+ status: draft.status,
3413
+ stores: draft.stores?.map(
3414
+ (s) => getStoreKeyReference(s, context.projectKey, this._storage)
3415
+ ),
3416
+ storeMode: draft.storeMode,
3417
+ name: draft.name,
3418
+ contactEmail: draft.contactEmail,
3419
+ addresses,
3420
+ custom: createCustomFields(
3421
+ draft.custom,
3422
+ context.projectKey,
3423
+ this._storage
3424
+ ),
3425
+ shippingAddressIds,
3426
+ billingAddressIds,
3427
+ defaultShippingAddressId,
3428
+ defaultBillingAddressId,
3429
+ associateMode: draft.associateMode,
3430
+ approvalRuleMode: draft.approvalRuleMode,
3431
+ associates: draft.associates?.map(
3432
+ (a) => createAssociate(a, context.projectKey, this._storage)
3433
+ ) ?? []
3434
+ };
3435
+ if (this._isDivisionDraft(draft)) {
3436
+ const division = {
3437
+ ...resource,
3438
+ parentUnit: getBusinessUnitKeyReference(
3439
+ draft.parentUnit,
3440
+ context.projectKey,
3441
+ this._storage
3442
+ )
3443
+ };
3444
+ this.saveNew(context, division);
3445
+ return division;
3446
+ } else if (this._isCompanyDraft(draft)) {
3447
+ const company = resource;
3448
+ this.saveNew(context, company);
3449
+ return company;
3591
3450
  }
3451
+ throw new Error("Invalid business unit type");
3592
3452
  }
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);
3601
- }
3602
- return resource;
3453
+ _isCompanyDraft(draft) {
3454
+ return draft.unitType === "Company";
3603
3455
  }
3604
- addStore(context, resource, action) {
3605
- throw new Error("Method not implemented.");
3456
+ _isDivisionDraft(draft) {
3457
+ return draft.unitType === "Division";
3606
3458
  }
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
- );
3459
+ };
3460
+ var BusinessUnitUpdateHandler = class extends AbstractUpdateHandler {
3461
+ addAddress(context, resource, { address }) {
3613
3462
  const newAddress = createAddress(
3614
3463
  address,
3615
3464
  context.projectKey,
3616
3465
  this._storage
3617
3466
  );
3618
3467
  if (newAddress) {
3619
- resource.addresses[oldAddressIndex] = {
3620
- id: addressId,
3621
- ...newAddress
3622
- };
3468
+ resource.addresses.push(newAddress);
3623
3469
  }
3624
3470
  }
3625
- changeEmail(_context, resource, { email }) {
3626
- resource.email = email;
3627
- }
3628
- removeAddress(context, resource, action) {
3629
- const address = this._findAddress(
3630
- resource,
3631
- action.addressId,
3632
- action.addressKey,
3633
- true
3471
+ addAssociate(context, resource, { associate }) {
3472
+ const newAssociate = createAssociate(
3473
+ associate,
3474
+ context.projectKey,
3475
+ this._storage
3634
3476
  );
3635
- assert2(address?.id);
3636
- resource.addresses = resource.addresses.filter((a) => a.id !== address.id);
3477
+ if (newAssociate) {
3478
+ resource.associates.push(newAssociate);
3479
+ }
3637
3480
  }
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
3481
+ addStore(context, resource, { store }) {
3482
+ const newStore = getStoreKeyReference(
3483
+ store,
3484
+ context.projectKey,
3485
+ this._storage
3648
3486
  );
3649
- if (resource.defaultBillingAddressId === address.id) {
3650
- resource.defaultBillingAddressId = void 0;
3487
+ if (newStore) {
3488
+ if (!resource.stores) {
3489
+ resource.stores = [];
3490
+ }
3491
+ resource.stores.push(newStore);
3651
3492
  }
3652
3493
  }
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
3494
+ changeAddress(context, resource, { address }) {
3495
+ const newAddress = createAddress(
3496
+ address,
3497
+ context.projectKey,
3498
+ this._storage
3663
3499
  );
3664
- if (resource.defaultShippingAddressId === address.id) {
3665
- resource.defaultShippingAddressId = void 0;
3500
+ if (newAddress) {
3501
+ resource.addresses.push(newAddress);
3666
3502
  }
3667
3503
  }
3668
- removeStore(context, resource, action) {
3669
- throw new Error("Method not implemented.");
3670
- }
3671
- setAddressCustomField(context, resource, action) {
3672
- throw new Error("Method not implemented.");
3673
- }
3674
- setAddressCustomType(context, resource, action) {
3675
- throw new Error("Method not implemented.");
3504
+ changeApprovalRuleMode(context, resource, { approvalRuleMode }) {
3505
+ resource.approvalRuleMode = approvalRuleMode;
3676
3506
  }
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
- );
3507
+ changeAssociateMode(context, resource, { associateMode }) {
3508
+ resource.associateMode = associateMode;
3704
3509
  }
3705
- setCompanyName(_context, resource, { companyName }) {
3706
- resource.companyName = companyName;
3510
+ changeName(context, resource, { name }) {
3511
+ resource.name = name;
3707
3512
  }
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(
3513
+ changeParentUnit(context, resource, { parentUnit }) {
3514
+ resource.parentUnit = getBusinessUnitKeyReference(
3515
+ parentUnit,
3719
3516
  context.projectKey,
3720
- action.customerGroup
3517
+ this._storage
3721
3518
  );
3722
- resource.customerGroup = {
3723
- typeId: "customer-group",
3724
- id: group.id
3725
- };
3726
3519
  }
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
- );
3732
- }
3733
- resource.customerNumber = customerNumber;
3520
+ changeStatus(context, resource, { status }) {
3521
+ resource.status = status;
3734
3522
  }
3735
- setCustomField(_context, resource, { name, value }) {
3736
- if (!resource.custom) {
3737
- throw new Error("Resource has no custom field");
3738
- }
3739
- resource.custom.fields[name] = value;
3523
+ setAssociates(context, resource, { associates }) {
3524
+ const newAssociates = associates.map((a) => createAssociate(a, context.projectKey, this._storage)).filter((a) => a !== void 0);
3525
+ resource.associates = newAssociates || void 0;
3526
+ }
3527
+ setContactEmail(context, resource, { contactEmail }) {
3528
+ resource.contactEmail = contactEmail;
3740
3529
  }
3741
3530
  setCustomType(context, resource, { type, fields }) {
3742
3531
  if (type) {
@@ -3749,315 +3538,348 @@ var CustomerUpdateHandler = class extends AbstractUpdateHandler {
3749
3538
  resource.custom = void 0;
3750
3539
  }
3751
3540
  }
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
3761
- );
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);
3769
- }
3770
- }
3771
- setDefaultShippingAddress(context, resource, action) {
3772
- const address = this._findAddress(
3773
- resource,
3774
- action.addressId,
3775
- action.addressKey,
3776
- true
3777
- );
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);
3785
- }
3786
- }
3787
- setExternalId(_context, resource, { externalId }) {
3788
- resource.externalId = externalId;
3789
- }
3790
- setFirstName(_context, resource, { firstName }) {
3791
- resource.firstName = firstName;
3792
- }
3793
- setKey(_context, resource, { key }) {
3794
- resource.key = key;
3795
- }
3796
- setLastName(_context, resource, { lastName }) {
3797
- resource.lastName = lastName;
3798
- }
3799
- setLocale(_context, resource, { locale }) {
3800
- resource.locale = locale;
3801
- }
3802
- setMiddleName(context, resource, action) {
3803
- resource.middleName = action.middleName;
3804
- }
3805
- setSalutation(_context, resource, { salutation }) {
3806
- resource.salutation = salutation;
3541
+ setStoreMode(context, resource, { storeMode }) {
3542
+ resource.storeMode = storeMode;
3807
3543
  }
3808
- setStores(context, resource, action) {
3809
- throw new Error("Method not implemented.");
3544
+ };
3545
+
3546
+ // src/repositories/cart-discount/actions.ts
3547
+ var CartDiscountUpdateHandler = class extends AbstractUpdateHandler {
3548
+ changeIsActive(context, resource, { isActive }) {
3549
+ resource.isActive = isActive;
3810
3550
  }
3811
- setTitle(context, resource, action) {
3812
- resource.title = action.title;
3551
+ changeSortOrder(context, resource, { sortOrder }) {
3552
+ resource.sortOrder = sortOrder;
3813
3553
  }
3814
- setVatId(_context, resource, { vatId }) {
3815
- resource.vatId = vatId;
3554
+ changeTarget(context, resource, { target }) {
3555
+ resource.target = target;
3816
3556
  }
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;
3557
+ setCustomField(context, resource, { name, value }) {
3558
+ if (!resource.custom) {
3559
+ return;
3830
3560
  }
3831
- if (addressId) {
3832
- const address = resource.addresses.find((a) => a.id === addressId);
3833
- if (!address) {
3561
+ if (value === null) {
3562
+ if (name in resource.custom.fields) {
3563
+ delete resource.custom.fields[name];
3564
+ } else {
3834
3565
  throw new CommercetoolsError(
3835
3566
  {
3836
3567
  code: "InvalidOperation",
3837
- message: `Customer does not contain an address with the id ${addressId}.`
3568
+ message: "Cannot remove custom field " + name + " because it does not exist."
3838
3569
  },
3839
3570
  400
3840
3571
  );
3841
3572
  }
3842
- return address;
3573
+ } else {
3574
+ resource.custom.fields[name] = value;
3843
3575
  }
3844
- if (required) {
3845
- throw new CommercetoolsError(
3846
- {
3847
- code: "InvalidOperation",
3848
- message: "One of address 'addressId' or 'addressKey' is required."
3849
- },
3850
- 400
3576
+ }
3577
+ setCustomType(context, resource, { type, fields }) {
3578
+ if (!type) {
3579
+ resource.custom = void 0;
3580
+ } else {
3581
+ const resolvedType = this._storage.getByResourceIdentifier(
3582
+ context.projectKey,
3583
+ type
3851
3584
  );
3585
+ if (!resolvedType) {
3586
+ throw new Error(`Type ${type} not found`);
3587
+ }
3588
+ resource.custom = {
3589
+ type: {
3590
+ typeId: "type",
3591
+ id: resolvedType.id
3592
+ },
3593
+ fields: fields || {}
3594
+ };
3852
3595
  }
3853
3596
  }
3597
+ setDescription(context, resource, { description }) {
3598
+ resource.description = description;
3599
+ }
3600
+ setKey(context, resource, { key }) {
3601
+ resource.key = key;
3602
+ }
3603
+ setStores(context, resource, { stores }) {
3604
+ resource.stores = stores?.map(
3605
+ (s) => getStoreKeyReference(s, context.projectKey, this._storage)
3606
+ );
3607
+ }
3608
+ setValidFrom(context, resource, { validFrom }) {
3609
+ resource.validFrom = validFrom;
3610
+ }
3611
+ setValidFromAndUntil(context, resource, { validFrom, validUntil }) {
3612
+ resource.validFrom = validFrom;
3613
+ resource.validUntil = validUntil;
3614
+ }
3615
+ setValidUntil(context, resource, { validUntil }) {
3616
+ resource.validUntil = validUntil;
3617
+ }
3854
3618
  };
3855
3619
 
3856
- // src/repositories/customer/index.ts
3857
- var CustomerRepository = class extends AbstractResourceRepository {
3620
+ // src/repositories/cart-discount/index.ts
3621
+ var CartDiscountRepository = class extends AbstractResourceRepository {
3858
3622
  constructor(storage) {
3859
- super("customer", storage);
3860
- this.actions = new CustomerUpdateHandler(storage);
3623
+ super("cart-discount", storage);
3624
+ this.actions = new CartDiscountUpdateHandler(storage);
3861
3625
  }
3862
3626
  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
3627
  const resource = {
3921
3628
  ...getBaseResourceProperties(),
3922
3629
  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,
3630
+ description: draft.description,
3631
+ cartPredicate: draft.cartPredicate,
3632
+ isActive: draft.isActive || false,
3633
+ name: draft.name,
3634
+ stores: draft.stores?.map(
3635
+ (s) => getStoreKeyReference(s, context.projectKey, this._storage)
3636
+ ) ?? [],
3637
+ references: [],
3638
+ target: draft.target,
3639
+ requiresDiscountCode: draft.requiresDiscountCode || false,
3640
+ sortOrder: draft.sortOrder,
3641
+ stackingMode: draft.stackingMode || "Stacking",
3642
+ validFrom: draft.validFrom,
3643
+ validUntil: draft.validUntil,
3644
+ value: this.transformValueDraft(draft.value),
3941
3645
  custom: createCustomFields(
3942
3646
  draft.custom,
3943
3647
  context.projectKey,
3944
3648
  this._storage
3945
- ),
3946
- stores: storesForCustomer
3649
+ )
3947
3650
  };
3948
3651
  return this.saveNew(context, resource);
3949
3652
  }
3950
- saveUpdate(context, version, resource) {
3951
- const updatedResource = {
3952
- ...resource,
3953
- lowercaseEmail: resource.email.toLowerCase()
3954
- };
3955
- return super.saveUpdate(context, version, updatedResource);
3653
+ transformValueDraft(value) {
3654
+ switch (value.type) {
3655
+ case "absolute": {
3656
+ return {
3657
+ type: "absolute",
3658
+ money: value.money.map(createTypedMoney)
3659
+ };
3660
+ }
3661
+ case "fixed": {
3662
+ return {
3663
+ type: "fixed",
3664
+ money: value.money.map(createTypedMoney)
3665
+ };
3666
+ }
3667
+ case "giftLineItem": {
3668
+ return {
3669
+ ...value
3670
+ };
3671
+ }
3672
+ case "relative": {
3673
+ return {
3674
+ ...value
3675
+ };
3676
+ }
3677
+ }
3678
+ return value;
3956
3679
  }
3957
- passwordResetToken(context, request) {
3958
- const results = this._storage.query(context.projectKey, this.getTypeId(), {
3959
- where: [`email="${request.email.toLocaleLowerCase()}"`]
3680
+ };
3681
+
3682
+ // src/repositories/category/index.ts
3683
+ import { v4 as uuidv48 } from "uuid";
3684
+
3685
+ // src/repositories/category/actions.ts
3686
+ import { v4 as uuidv47 } from "uuid";
3687
+ var CategoryUpdateHandler = class extends AbstractUpdateHandler {
3688
+ addAsset(context, resource, { asset }) {
3689
+ if (!resource.assets) {
3690
+ resource.assets = [this.assetFromAssetDraft(asset, context)];
3691
+ } else {
3692
+ resource.assets.push(this.assetFromAssetDraft(asset, context));
3693
+ }
3694
+ }
3695
+ changeAssetName(context, resource, { assetId, assetKey, name }) {
3696
+ resource.assets?.forEach((asset) => {
3697
+ if (assetId && assetId === asset.id) {
3698
+ asset.name = name;
3699
+ }
3700
+ if (assetKey && assetKey === asset.key) {
3701
+ asset.name = name;
3702
+ }
3960
3703
  });
3961
- if (results.count === 0) {
3962
- throw new CommercetoolsError({
3963
- code: "ResourceNotFound",
3964
- message: `The Customer with ID '${request.email}' was not found.`
3965
- });
3704
+ }
3705
+ changeName(context, resource, { name }) {
3706
+ resource.name = name;
3707
+ }
3708
+ changeParent(context, resource, { parent }) {
3709
+ const category = this._storage.getByResourceIdentifier(
3710
+ context.projectKey,
3711
+ parent
3712
+ );
3713
+ if (!category) {
3714
+ throw new Error("No category found for reference");
3966
3715
  }
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
3716
+ resource.parent = {
3717
+ typeId: "category",
3718
+ id: category.id
3979
3719
  };
3980
3720
  }
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.`
3721
+ changeSlug(context, resource, { slug }) {
3722
+ resource.slug = slug;
3723
+ }
3724
+ removeAsset(context, resource, { assetId, assetKey }) {
3725
+ if (!resource.assets) {
3726
+ return;
3727
+ }
3728
+ if (assetId) {
3729
+ resource.assets = resource.assets.filter(function(obj) {
3730
+ return obj.id !== assetId;
3988
3731
  });
3732
+ return;
3989
3733
  }
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.`
3734
+ if (assetKey) {
3735
+ resource.assets = resource.assets.filter(function(obj) {
3736
+ return obj.key !== assetKey;
3999
3737
  });
3738
+ return;
4000
3739
  }
4001
- customer.password = hashPassword(newPassword);
4002
- customer.version += 1;
4003
- this._storage.add(context.projectKey, "customer", customer);
4004
- return customer;
4005
3740
  }
4006
- verifyEmailToken(context, id) {
4007
- const results = this._storage.query(context.projectKey, this.getTypeId(), {
4008
- where: [`id="${id.toLocaleLowerCase()}"`]
3741
+ setAssetDescription(context, resource, { assetId, assetKey, description }) {
3742
+ resource.assets?.forEach((asset) => {
3743
+ if (assetId && assetId === asset.id) {
3744
+ asset.description = description;
3745
+ }
3746
+ if (assetKey && assetKey === asset.key) {
3747
+ asset.description = description;
3748
+ }
4009
3749
  });
4010
- if (results.count === 0) {
4011
- throw new CommercetoolsError({
4012
- code: "ResourceNotFound",
4013
- message: `The Customer with ID '${id}' was not found.`
4014
- });
4015
- }
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
4027
- };
4028
3750
  }
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
- });
3751
+ setAssetSources(context, resource, { assetId, assetKey, sources }) {
3752
+ resource.assets?.forEach((asset) => {
3753
+ if (assetId && assetId === asset.id) {
3754
+ asset.sources = sources;
4041
3755
  }
3756
+ if (assetKey && assetKey === asset.key) {
3757
+ asset.sources = sources;
3758
+ }
3759
+ });
3760
+ }
3761
+ setCustomField(context, resource, { name, value }) {
3762
+ if (!resource.custom) {
3763
+ return;
3764
+ }
3765
+ if (value === null) {
3766
+ delete resource.custom.fields[name];
3767
+ } else {
3768
+ resource.custom.fields[name] = value;
3769
+ }
3770
+ }
3771
+ setCustomType(context, resource, { type, fields }) {
3772
+ if (type) {
3773
+ resource.custom = createCustomFields(
3774
+ { type, fields },
3775
+ context.projectKey,
3776
+ this._storage
3777
+ );
3778
+ } else {
3779
+ resource.custom = void 0;
3780
+ }
3781
+ }
3782
+ setDescription(context, resource, { description }) {
3783
+ resource.description = description;
3784
+ }
3785
+ setKey(context, resource, { key }) {
3786
+ resource.key = key;
3787
+ }
3788
+ setMetaDescription(context, resource, { metaDescription }) {
3789
+ resource.metaDescription = metaDescription;
3790
+ }
3791
+ setMetaKeywords(context, resource, { metaKeywords }) {
3792
+ resource.metaKeywords = metaKeywords;
3793
+ }
3794
+ setMetaTitle(context, resource, { metaTitle }) {
3795
+ resource.metaTitle = metaTitle;
3796
+ }
3797
+ assetFromAssetDraft = (draft, context) => ({
3798
+ ...draft,
3799
+ id: uuidv47(),
3800
+ custom: createCustomFields(draft.custom, context.projectKey, this._storage)
3801
+ });
3802
+ };
3803
+
3804
+ // src/repositories/category/index.ts
3805
+ var CategoryRepository = class extends AbstractResourceRepository {
3806
+ constructor(storage) {
3807
+ super("category", storage);
3808
+ this.actions = new CategoryUpdateHandler(this._storage);
3809
+ }
3810
+ create(context, draft) {
3811
+ const resource = {
3812
+ ...getBaseResourceProperties(),
3813
+ key: draft.key,
3814
+ name: draft.name,
3815
+ slug: draft.slug,
3816
+ description: draft.description,
3817
+ metaDescription: draft.metaDescription,
3818
+ metaKeywords: draft.metaKeywords,
3819
+ orderHint: draft.orderHint || "",
3820
+ externalId: draft.externalId || "",
3821
+ parent: draft.parent ? { typeId: "category", id: draft.parent.id } : void 0,
3822
+ ancestors: [],
3823
+ // Resolved at runtime
3824
+ assets: draft.assets?.map((d) => ({
3825
+ id: uuidv48(),
3826
+ name: d.name,
3827
+ description: d.description,
3828
+ sources: d.sources,
3829
+ tags: d.tags,
3830
+ key: d.key,
3831
+ custom: createCustomFields(
3832
+ draft.custom,
3833
+ context.projectKey,
3834
+ this._storage
3835
+ )
3836
+ })) || [],
3837
+ custom: createCustomFields(
3838
+ draft.custom,
3839
+ context.projectKey,
3840
+ this._storage
3841
+ )
3842
+ };
3843
+ return this.saveNew(context, resource);
3844
+ }
3845
+ postProcessResource(context, resource, params) {
3846
+ let node = resource;
3847
+ const ancestors = [];
3848
+ const expandClauses = params?.expand?.map(parseExpandClause) ?? [];
3849
+ const addExpand = expandClauses?.find(
3850
+ (c) => c.element === "ancestors" && c.index === "*"
3851
+ );
3852
+ while (node.parent) {
3853
+ node = this._storage.getByResourceIdentifier(
3854
+ context.projectKey,
3855
+ node.parent
3856
+ );
3857
+ ancestors.push({
3858
+ typeId: "category",
3859
+ id: node.id,
3860
+ obj: addExpand ? node : void 0
3861
+ });
4042
3862
  }
4043
- return draftStores.map((storeReference) => ({
4044
- typeId: "store",
4045
- key: storeReference.key ?? stores.find((store) => store.id === storeReference.id)?.key
4046
- }));
3863
+ resource.ancestors = ancestors;
3864
+ return resource;
4047
3865
  }
4048
3866
  };
4049
3867
 
4050
- // src/repositories/customer-group.ts
4051
- var CustomerGroupRepository = class extends AbstractResourceRepository {
3868
+ // src/repositories/channel.ts
3869
+ var ChannelRepository = class extends AbstractResourceRepository {
4052
3870
  constructor(storage) {
4053
- super("customer-group", storage);
4054
- this.actions = new CustomerGroupUpdateHandler(storage);
3871
+ super("channel", storage);
3872
+ this.actions = new ChannelUpdateHandler(this._storage);
4055
3873
  }
4056
3874
  create(context, draft) {
4057
3875
  const resource = {
4058
3876
  ...getBaseResourceProperties(),
4059
3877
  key: draft.key,
4060
- name: draft.groupName,
3878
+ name: draft.name,
3879
+ description: draft.description,
3880
+ roles: draft.roles || [],
3881
+ geoLocation: draft.geoLocation,
3882
+ address: createAddress(draft.address, context.projectKey, this._storage),
4061
3883
  custom: createCustomFields(
4062
3884
  draft.custom,
4063
3885
  context.projectKey,
@@ -4067,61 +3889,283 @@ var CustomerGroupRepository = class extends AbstractResourceRepository {
4067
3889
  return this.saveNew(context, resource);
4068
3890
  }
4069
3891
  };
4070
- var CustomerGroupUpdateHandler = class extends AbstractUpdateHandler {
3892
+ var ChannelUpdateHandler = class extends AbstractUpdateHandler {
3893
+ changeDescription(context, resource, { description }) {
3894
+ resource.description = description;
3895
+ }
3896
+ changeKey(context, resource, { key }) {
3897
+ resource.key = key;
3898
+ }
4071
3899
  changeName(context, resource, { name }) {
4072
3900
  resource.name = name;
4073
3901
  }
3902
+ setAddress(context, resource, { address }) {
3903
+ resource.address = createAddress(
3904
+ address,
3905
+ context.projectKey,
3906
+ this._storage
3907
+ );
3908
+ }
4074
3909
  setCustomField(context, resource, { name, value }) {
4075
3910
  if (!resource.custom) {
4076
3911
  return;
4077
3912
  }
4078
- if (value === null) {
4079
- delete resource.custom.fields[name];
4080
- } else {
4081
- resource.custom.fields[name] = value;
3913
+ if (value === null) {
3914
+ delete resource.custom.fields[name];
3915
+ } else {
3916
+ resource.custom.fields[name] = value;
3917
+ }
3918
+ }
3919
+ setCustomType(context, resource, { type, fields }) {
3920
+ if (type) {
3921
+ resource.custom = createCustomFields(
3922
+ { type, fields },
3923
+ context.projectKey,
3924
+ this._storage
3925
+ );
3926
+ } else {
3927
+ resource.custom = void 0;
3928
+ }
3929
+ }
3930
+ setGeoLocation(context, resource, { geoLocation }) {
3931
+ resource.geoLocation = geoLocation;
3932
+ }
3933
+ };
3934
+
3935
+ // src/repositories/custom-object.ts
3936
+ var CustomObjectRepository = class extends AbstractResourceRepository {
3937
+ constructor(storage) {
3938
+ super("key-value-document", storage);
3939
+ }
3940
+ create(context, draft) {
3941
+ const current = this.getWithContainerAndKey(
3942
+ context,
3943
+ draft.container,
3944
+ draft.key
3945
+ );
3946
+ if (current) {
3947
+ if (draft.version) {
3948
+ checkConcurrentModification(current.version, draft.version, current.id);
3949
+ } else {
3950
+ draft.version = current.version;
3951
+ }
3952
+ if (draft.value !== current.value) {
3953
+ const updated = cloneObject(current);
3954
+ updated.value = draft.value;
3955
+ updated.version += 1;
3956
+ this.saveUpdate(context, draft.version, updated);
3957
+ return updated;
3958
+ }
3959
+ return current;
3960
+ } else {
3961
+ if (draft.version) {
3962
+ throw new CommercetoolsError(
3963
+ {
3964
+ code: "InvalidOperation",
3965
+ message: "version on create must be 0"
3966
+ },
3967
+ 400
3968
+ );
3969
+ }
3970
+ const baseProperties = getBaseResourceProperties();
3971
+ const resource = {
3972
+ ...baseProperties,
3973
+ container: draft.container,
3974
+ key: draft.key,
3975
+ value: draft.value
3976
+ };
3977
+ this.saveNew(context, resource);
3978
+ return resource;
3979
+ }
3980
+ }
3981
+ getWithContainerAndKey(context, container, key) {
3982
+ const items = this._storage.all(context.projectKey, this.getTypeId());
3983
+ return items.find(
3984
+ (item) => item.container === container && item.key === key
3985
+ );
3986
+ }
3987
+ queryWithContainer(context, container, params = {}) {
3988
+ const whereClause = params.where || [];
3989
+ whereClause.push(`container="${container}"`);
3990
+ const result = this._storage.query(context.projectKey, this.getTypeId(), {
3991
+ ...params,
3992
+ where: whereClause
3993
+ });
3994
+ result.results = result.results.map(
3995
+ (r) => this.postProcessResource(context, r, {
3996
+ expand: params.expand
3997
+ })
3998
+ );
3999
+ return result;
4000
+ }
4001
+ };
4002
+
4003
+ // src/repositories/customer/actions.ts
4004
+ import assert3 from "node:assert";
4005
+ var CustomerUpdateHandler = class extends AbstractUpdateHandler {
4006
+ addAddress(_context, resource, { address }) {
4007
+ resource.addresses.push({
4008
+ ...address,
4009
+ id: address.id ?? generateRandomString(5)
4010
+ });
4011
+ }
4012
+ addBillingAddressId(_context, resource, { addressId, addressKey }) {
4013
+ const address = this._findAddress(resource, addressId, addressKey, true);
4014
+ assert3(address?.id);
4015
+ if (resource.billingAddressIds === void 0) {
4016
+ resource.billingAddressIds = [];
4017
+ }
4018
+ if (!resource.billingAddressIds.includes(address.id)) {
4019
+ resource.billingAddressIds.push(address.id);
4020
+ }
4021
+ }
4022
+ addShippingAddressId(_context, resource, { addressId, addressKey }) {
4023
+ const address = this._findAddress(resource, addressId, addressKey, true);
4024
+ assert3(address?.id);
4025
+ if (resource.shippingAddressIds === void 0) {
4026
+ resource.shippingAddressIds = [];
4027
+ }
4028
+ if (!resource.shippingAddressIds.includes(address.id)) {
4029
+ resource.shippingAddressIds.push(address.id);
4030
+ }
4031
+ return resource;
4032
+ }
4033
+ addStore(context, resource, action) {
4034
+ throw new Error("Method not implemented.");
4035
+ }
4036
+ changeAddress(context, resource, { addressId, addressKey, address }) {
4037
+ const current = this._findAddress(resource, addressId, addressKey, true);
4038
+ assert3(current?.id);
4039
+ const oldAddressIndex = resource.addresses.findIndex(
4040
+ (a) => a.id === current.id
4041
+ );
4042
+ const newAddress = createAddress(
4043
+ address,
4044
+ context.projectKey,
4045
+ this._storage
4046
+ );
4047
+ if (newAddress) {
4048
+ resource.addresses[oldAddressIndex] = {
4049
+ id: addressId,
4050
+ ...newAddress
4051
+ };
4052
+ }
4053
+ }
4054
+ changeEmail(_context, resource, { email }) {
4055
+ resource.email = email;
4056
+ }
4057
+ removeAddress(context, resource, action) {
4058
+ const address = this._findAddress(
4059
+ resource,
4060
+ action.addressId,
4061
+ action.addressKey,
4062
+ true
4063
+ );
4064
+ assert3(address?.id);
4065
+ resource.addresses = resource.addresses.filter((a) => a.id !== address.id);
4066
+ }
4067
+ removeBillingAddressId(context, resource, action) {
4068
+ const address = this._findAddress(
4069
+ resource,
4070
+ action.addressId,
4071
+ action.addressKey,
4072
+ true
4073
+ );
4074
+ assert3(address?.id);
4075
+ resource.billingAddressIds = resource.billingAddressIds?.filter(
4076
+ (id) => id !== address.id
4077
+ );
4078
+ if (resource.defaultBillingAddressId === address.id) {
4079
+ resource.defaultBillingAddressId = void 0;
4080
+ }
4081
+ }
4082
+ removeShippingAddressId(context, resource, action) {
4083
+ const address = this._findAddress(
4084
+ resource,
4085
+ action.addressId,
4086
+ action.addressKey,
4087
+ true
4088
+ );
4089
+ assert3(address?.id);
4090
+ resource.shippingAddressIds = resource.shippingAddressIds?.filter(
4091
+ (id) => id !== address.id
4092
+ );
4093
+ if (resource.defaultShippingAddressId === address.id) {
4094
+ resource.defaultShippingAddressId = void 0;
4095
+ }
4096
+ }
4097
+ removeStore(context, resource, action) {
4098
+ throw new Error("Method not implemented.");
4099
+ }
4100
+ setAddressCustomField(context, resource, action) {
4101
+ throw new Error("Method not implemented.");
4102
+ }
4103
+ setAddressCustomType(context, resource, action) {
4104
+ throw new Error("Method not implemented.");
4105
+ }
4106
+ setAuthenticationMode(_context, resource, { authMode, password }) {
4107
+ if (resource.authenticationMode === authMode) {
4108
+ throw new CommercetoolsError(
4109
+ {
4110
+ code: "InvalidInput",
4111
+ message: `The customer is already using the '${resource.authenticationMode}' authentication mode.`
4112
+ },
4113
+ 400
4114
+ );
4115
+ }
4116
+ resource.authenticationMode = authMode;
4117
+ if (authMode === "ExternalAuth") {
4118
+ delete resource.password;
4119
+ return;
4120
+ }
4121
+ if (authMode === "Password") {
4122
+ resource.password = password ? hashPassword(password) : void 0;
4123
+ return;
4082
4124
  }
4125
+ throw new CommercetoolsError(
4126
+ {
4127
+ code: "InvalidJsonInput",
4128
+ message: "Request body does not contain valid JSON.",
4129
+ detailedErrorMessage: `actions -> authMode: Invalid enum value: '${authMode}'. Expected one of: 'Password','ExternalAuth'`
4130
+ },
4131
+ 400
4132
+ );
4083
4133
  }
4084
- setCustomType(context, resource, { type, fields }) {
4085
- if (type) {
4086
- resource.custom = createCustomFields(
4087
- { type, fields },
4088
- context.projectKey,
4089
- this._storage
4134
+ setCompanyName(_context, resource, { companyName }) {
4135
+ resource.companyName = companyName;
4136
+ }
4137
+ setCustomerGroup(context, resource, action) {
4138
+ if (!action.customerGroup) {
4139
+ throw new CommercetoolsError(
4140
+ {
4141
+ code: "InvalidOperation",
4142
+ message: "CustomerGroup is required."
4143
+ },
4144
+ 400
4090
4145
  );
4091
- } else {
4092
- resource.custom = void 0;
4093
4146
  }
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
- })
4147
+ const group = this._storage.getByResourceIdentifier(
4148
+ context.projectKey,
4149
+ action.customerGroup
4108
4150
  );
4151
+ resource.customerGroup = {
4152
+ typeId: "customer-group",
4153
+ id: group.id
4154
+ };
4109
4155
  }
4110
- changeIsActive(context, resource, { isActive }) {
4111
- resource.isActive = isActive;
4112
- }
4113
- setCartPredicate(context, resource, { cartPredicate }) {
4114
- resource.cartPredicate = cartPredicate;
4156
+ setCustomerNumber(_context, resource, { customerNumber }) {
4157
+ if (resource.customerNumber) {
4158
+ throw new Error(
4159
+ "A Customer number already exists and cannot be set again."
4160
+ );
4161
+ }
4162
+ resource.customerNumber = customerNumber;
4115
4163
  }
4116
- setCustomField(context, resource, { name, value }) {
4164
+ setCustomField(_context, resource, { name, value }) {
4117
4165
  if (!resource.custom) {
4118
- return;
4119
- }
4120
- if (value === null) {
4121
- delete resource.custom.fields[name];
4122
- } else {
4123
- resource.custom.fields[name] = value;
4166
+ throw new Error("Resource has no custom field");
4124
4167
  }
4168
+ resource.custom.fields[name] = value;
4125
4169
  }
4126
4170
  setCustomType(context, resource, { type, fields }) {
4127
4171
  if (type) {
@@ -4134,683 +4178,665 @@ var DiscountCodeUpdateHandler = class extends AbstractUpdateHandler {
4134
4178
  resource.custom = void 0;
4135
4179
  }
4136
4180
  }
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);
4181
+ setDateOfBirth(context, resource, action) {
4182
+ resource.dateOfBirth = action.dateOfBirth;
4168
4183
  }
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);
4184
+ setDefaultBillingAddress(context, resource, action) {
4185
+ const address = this._findAddress(
4186
+ resource,
4187
+ action.addressId,
4188
+ action.addressKey,
4189
+ true
4190
+ );
4191
+ assert3(address?.id);
4192
+ resource.defaultBillingAddressId = address.id;
4193
+ if (resource.billingAddressIds === void 0) {
4194
+ resource.billingAddressIds = [];
4195
+ }
4196
+ if (!resource.billingAddressIds.includes(address.id)) {
4197
+ resource.billingAddressIds.push(address.id);
4198
+ }
4197
4199
  }
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;
4200
+ setDefaultShippingAddress(context, resource, action) {
4201
+ const address = this._findAddress(
4202
+ resource,
4203
+ action.addressId,
4204
+ action.addressKey,
4205
+ true
4206
+ );
4207
+ assert3(address?.id);
4208
+ resource.defaultShippingAddressId = address.id;
4209
+ if (resource.shippingAddressIds === void 0) {
4210
+ resource.shippingAddressIds = [];
4211
+ }
4212
+ if (!resource.shippingAddressIds.includes(address.id)) {
4213
+ resource.shippingAddressIds.push(address.id);
4211
4214
  }
4212
4215
  }
4213
- if (val && target && val[target]) {
4214
- val[target] = "****";
4216
+ setExternalId(_context, resource, { externalId }) {
4217
+ resource.externalId = externalId;
4215
4218
  }
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);
4219
+ setFirstName(_context, resource, { firstName }) {
4220
+ resource.firstName = firstName;
4224
4221
  }
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);
4222
+ setKey(_context, resource, { key }) {
4223
+ resource.key = key;
4234
4224
  }
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;
4225
+ setLastName(_context, resource, { lastName }) {
4226
+ resource.lastName = lastName;
4248
4227
  }
4249
- };
4250
- var ExtensionUpdateHandler = class extends AbstractUpdateHandler {
4251
- changeDestination(context, resource, action) {
4252
- resource.destination = action.destination;
4228
+ setLocale(_context, resource, { locale }) {
4229
+ resource.locale = locale;
4253
4230
  }
4254
- changeTriggers(context, resource, action) {
4255
- resource.triggers = action.triggers;
4231
+ setMiddleName(context, resource, action) {
4232
+ resource.middleName = action.middleName;
4256
4233
  }
4257
- setKey(context, resource, action) {
4258
- resource.key = action.key;
4234
+ setSalutation(_context, resource, { salutation }) {
4235
+ resource.salutation = salutation;
4259
4236
  }
4260
- setTimeoutInMs(context, resource, action) {
4261
- resource.timeoutInMs = action.timeoutInMs;
4237
+ setStores(context, resource, action) {
4238
+ throw new Error("Method not implemented.");
4262
4239
  }
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;
4240
+ setTitle(context, resource, action) {
4241
+ resource.title = action.title;
4270
4242
  }
4271
- setCustomField(context, resource, { name, value }) {
4272
- if (!resource.custom) {
4273
- throw new Error("Resource has no custom field");
4243
+ setVatId(_context, resource, { vatId }) {
4244
+ resource.vatId = vatId;
4245
+ }
4246
+ _findAddress(resource, addressId, addressKey, required = false) {
4247
+ if (addressKey) {
4248
+ const address = resource.addresses.find((a) => a.key === addressKey);
4249
+ if (!address) {
4250
+ throw new CommercetoolsError(
4251
+ {
4252
+ code: "InvalidOperation",
4253
+ message: `Customer does not contain an address with the key ${addressKey}.`
4254
+ },
4255
+ 400
4256
+ );
4257
+ }
4258
+ return address;
4274
4259
  }
4275
- resource.custom.fields[name] = value;
4276
- }
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`);
4260
+ if (addressId) {
4261
+ const address = resource.addresses.find((a) => a.id === addressId);
4262
+ if (!address) {
4263
+ throw new CommercetoolsError(
4264
+ {
4265
+ code: "InvalidOperation",
4266
+ message: `Customer does not contain an address with the id ${addressId}.`
4267
+ },
4268
+ 400
4269
+ );
4287
4270
  }
4288
- resource.custom = {
4289
- type: {
4290
- typeId: "type",
4291
- id: resolvedType.id
4271
+ return address;
4272
+ }
4273
+ if (required) {
4274
+ throw new CommercetoolsError(
4275
+ {
4276
+ code: "InvalidOperation",
4277
+ message: "One of address 'addressId' or 'addressKey' is required."
4292
4278
  },
4293
- fields: fields || {}
4294
- };
4279
+ 400
4280
+ );
4295
4281
  }
4296
4282
  }
4297
- setExpectedDelivery(context, resource, { expectedDelivery }) {
4298
- resource.expectedDelivery = new Date(expectedDelivery).toISOString();
4299
- }
4300
- setRestockableInDays(context, resource, { restockableInDays }) {
4301
- resource.restockableInDays = restockableInDays;
4302
- }
4303
4283
  };
4304
4284
 
4305
- // src/repositories/inventory-entry/index.ts
4306
- var InventoryEntryRepository = class extends AbstractResourceRepository {
4285
+ // src/repositories/customer/index.ts
4286
+ var CustomerRepository = class extends AbstractResourceRepository {
4307
4287
  constructor(storage) {
4308
- super("inventory-entry", storage);
4309
- this.actions = new InventoryEntryUpdateHandler(storage);
4288
+ super("customer", storage);
4289
+ this.actions = new CustomerUpdateHandler(storage);
4310
4290
  }
4311
4291
  create(context, draft) {
4292
+ const results = this._storage.query(context.projectKey, this.getTypeId(), {
4293
+ where: [`lowercaseEmail="${draft.email.toLowerCase()}"`]
4294
+ });
4295
+ if (results.count > 0) {
4296
+ throw new CommercetoolsError({
4297
+ code: "CustomerAlreadyExists",
4298
+ statusCode: 400,
4299
+ message: "There is already an existing customer with the provided email.",
4300
+ errors: [
4301
+ {
4302
+ code: "DuplicateField",
4303
+ message: `Customer with email '${draft.email}' already exists.`,
4304
+ duplicateValue: draft.email,
4305
+ field: "email"
4306
+ }
4307
+ ]
4308
+ });
4309
+ }
4310
+ const addresses = draft.addresses?.map((address) => ({
4311
+ ...address,
4312
+ id: generateRandomString(5)
4313
+ })) ?? [];
4314
+ const lookupAdressId = (addresses2, addressId) => {
4315
+ if (addressId < addresses2.length) {
4316
+ const id = addresses2[addressId].id;
4317
+ if (!id) {
4318
+ throw new Error("Address ID is missing");
4319
+ }
4320
+ return id;
4321
+ }
4322
+ throw new CommercetoolsError({
4323
+ code: "InvalidInput",
4324
+ message: `Address with ID '${addressId}' not found.`,
4325
+ errors: [
4326
+ {
4327
+ code: "InvalidInput",
4328
+ message: `Address with ID '${addressId}' not found.`,
4329
+ field: "addressId"
4330
+ }
4331
+ ]
4332
+ });
4333
+ };
4334
+ const defaultBillingAddressId = draft.defaultBillingAddress !== void 0 ? lookupAdressId(addresses, draft.defaultBillingAddress) : void 0;
4335
+ const defaultShippingAddressId = draft.defaultShippingAddress !== void 0 ? lookupAdressId(addresses, draft.defaultShippingAddress) : void 0;
4336
+ const shippingAddressIds = draft.shippingAddresses?.map(
4337
+ (addressId) => lookupAdressId(addresses, addressId)
4338
+ ) ?? [];
4339
+ const billingAddressIds = draft.billingAddresses?.map(
4340
+ (addressId) => lookupAdressId(addresses, addressId)
4341
+ ) ?? [];
4342
+ let storesForCustomer = [];
4343
+ if (draft.stores && draft.stores.length > 0) {
4344
+ storesForCustomer = this.storeReferenceToStoreKeyReference(
4345
+ draft.stores,
4346
+ context.projectKey
4347
+ );
4348
+ }
4312
4349
  const resource = {
4313
4350
  ...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
- },
4351
+ key: draft.key,
4352
+ authenticationMode: draft.authenticationMode || "Password",
4353
+ firstName: draft.firstName,
4354
+ lastName: draft.lastName,
4355
+ middleName: draft.middleName,
4356
+ title: draft.title,
4357
+ dateOfBirth: draft.dateOfBirth,
4358
+ companyName: draft.companyName,
4359
+ email: draft.email.toLowerCase(),
4360
+ lowercaseEmail: draft.email.toLowerCase(),
4361
+ password: draft.password ? hashPassword(draft.password) : void 0,
4362
+ isEmailVerified: draft.isEmailVerified || false,
4363
+ addresses,
4364
+ customerNumber: draft.customerNumber,
4365
+ externalId: draft.externalId,
4366
+ defaultBillingAddressId,
4367
+ defaultShippingAddressId,
4368
+ shippingAddressIds,
4369
+ billingAddressIds,
4324
4370
  custom: createCustomFields(
4325
4371
  draft.custom,
4326
4372
  context.projectKey,
4327
4373
  this._storage
4328
- )
4374
+ ),
4375
+ stores: storesForCustomer
4329
4376
  };
4330
4377
  return this.saveNew(context, resource);
4331
4378
  }
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;
4379
+ saveUpdate(context, version, resource) {
4380
+ const updatedResource = {
4381
+ ...resource,
4382
+ lowercaseEmail: resource.email.toLowerCase()
4383
+ };
4384
+ return super.saveUpdate(context, version, updatedResource);
4359
4385
  }
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) {
4386
+ passwordResetToken(context, request) {
4387
+ const results = this._storage.query(context.projectKey, this.getTypeId(), {
4388
+ where: [`email="${request.email.toLocaleLowerCase()}"`]
4389
+ });
4390
+ if (results.count === 0) {
4375
4391
  throw new CommercetoolsError({
4376
4392
  code: "ResourceNotFound",
4377
- message: `The Customer with ID 'Token(${tokenValue})' was not found.`
4393
+ message: `The Customer with ID '${request.email}' was not found.`
4378
4394
  });
4379
4395
  }
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;
4395
- }
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];
4404
- }
4405
- return;
4396
+ const ttlMinutes = request.ttlMinutes ?? 34560;
4397
+ const expiresAt = new Date((/* @__PURE__ */ new Date()).getTime() + ttlMinutes * 60 * 1e3);
4398
+ const customer = results.results[0];
4399
+ const rest = getBaseResourceProperties();
4400
+ const token = createPasswordResetToken(customer, expiresAt);
4401
+ return {
4402
+ id: rest.id,
4403
+ createdAt: rest.createdAt,
4404
+ lastModifiedAt: rest.lastModifiedAt,
4405
+ customerId: customer.id,
4406
+ expiresAt: expiresAt.toISOString(),
4407
+ value: token
4408
+ };
4406
4409
  }
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(
4410
+ passwordReset(context, resetPassword) {
4411
+ const { newPassword, tokenValue } = resetPassword;
4412
+ const customerId = validatePasswordResetToken(tokenValue);
4413
+ if (!customerId) {
4414
+ throw new CommercetoolsError({
4415
+ code: "ResourceNotFound",
4416
+ message: `The Customer with ID 'Token(${tokenValue})' was not found.`
4417
+ });
4418
+ }
4419
+ const customer = this._storage.get(
4419
4420
  context.projectKey,
4420
- payment
4421
+ "customer",
4422
+ customerId
4421
4423
  );
4422
- if (!resolvedPayment) {
4423
- throw new Error(`Payment ${payment.id} not found`);
4424
- }
4425
- if (!resource.paymentInfo) {
4426
- resource.paymentInfo = {
4427
- payments: []
4428
- };
4424
+ if (!customer) {
4425
+ throw new CommercetoolsError({
4426
+ code: "ResourceNotFound",
4427
+ message: `The Customer with ID 'Token(${tokenValue})' was not found.`
4428
+ });
4429
4429
  }
4430
- resource.paymentInfo.payments.push({
4431
- typeId: "payment",
4432
- id: payment.id
4433
- });
4430
+ customer.password = hashPassword(newPassword);
4431
+ customer.version += 1;
4432
+ this._storage.add(context.projectKey, "customer", customer);
4433
+ return customer;
4434
4434
  }
4435
- addReturnInfo(context, resource, info) {
4436
- if (!resource.returnInfo) {
4437
- resource.returnInfo = [];
4435
+ verifyEmailToken(context, id) {
4436
+ const results = this._storage.query(context.projectKey, this.getTypeId(), {
4437
+ where: [`id="${id.toLocaleLowerCase()}"`]
4438
+ });
4439
+ if (results.count === 0) {
4440
+ throw new CommercetoolsError({
4441
+ code: "ResourceNotFound",
4442
+ message: `The Customer with ID '${id}' was not found.`
4443
+ });
4438
4444
  }
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
4445
+ const expiresAt = new Date(Date.now() + 30 * 60);
4446
+ const customer = results.results[0];
4447
+ const rest = getBaseResourceProperties();
4448
+ const token = createEmailVerifyToken(customer);
4449
+ return {
4450
+ id: rest.id,
4451
+ createdAt: rest.createdAt,
4452
+ lastModifiedAt: rest.lastModifiedAt,
4453
+ customerId: customer.id,
4454
+ expiresAt: expiresAt.toISOString(),
4455
+ value: token
4463
4456
  };
4464
- resource.returnInfo.push(resolved);
4465
4457
  }
4466
- changeOrderState(context, resource, { orderState }) {
4467
- resource.orderState = orderState;
4468
- }
4469
- changePaymentState(context, resource, { paymentState }) {
4470
- resource.paymentState = paymentState;
4471
- }
4472
- changeShipmentState(context, resource, { shipmentState }) {
4473
- resource.shipmentState = shipmentState;
4458
+ storeReferenceToStoreKeyReference(draftStores, projectKey) {
4459
+ const storeIds = draftStores.map((storeReference) => storeReference.id).filter(Boolean);
4460
+ let stores = [];
4461
+ if (storeIds.length > 0) {
4462
+ stores = this._storage.query(projectKey, "store", {
4463
+ where: storeIds.map((id) => `id="${id}"`)
4464
+ }).results;
4465
+ if (storeIds.length !== stores.length) {
4466
+ throw new CommercetoolsError({
4467
+ code: "ResourceNotFound",
4468
+ message: `Store with ID '${storeIds.find((id) => !stores.some((store) => store.id === id))}' was not found.`
4469
+ });
4470
+ }
4471
+ }
4472
+ return draftStores.map((storeReference) => ({
4473
+ typeId: "store",
4474
+ key: storeReference.key ?? stores.find((store) => store.id === storeReference.id)?.key
4475
+ }));
4474
4476
  }
4475
- setBillingAddress(context, resource, { address }) {
4476
- resource.billingAddress = createAddress(
4477
- address,
4478
- context.projectKey,
4479
- this._storage
4480
- );
4477
+ };
4478
+
4479
+ // src/repositories/customer-group.ts
4480
+ var CustomerGroupRepository = class extends AbstractResourceRepository {
4481
+ constructor(storage) {
4482
+ super("customer-group", storage);
4483
+ this.actions = new CustomerGroupUpdateHandler(storage);
4481
4484
  }
4482
- setCustomerEmail(context, resource, { email }) {
4483
- resource.customerEmail = email;
4485
+ create(context, draft) {
4486
+ const resource = {
4487
+ ...getBaseResourceProperties(),
4488
+ key: draft.key,
4489
+ name: draft.groupName,
4490
+ custom: createCustomFields(
4491
+ draft.custom,
4492
+ context.projectKey,
4493
+ this._storage
4494
+ )
4495
+ };
4496
+ return this.saveNew(context, resource);
4484
4497
  }
4485
- setCustomerId(context, resource, { customerId }) {
4486
- resource.customerId = customerId;
4498
+ };
4499
+ var CustomerGroupUpdateHandler = class extends AbstractUpdateHandler {
4500
+ changeName(context, resource, { name }) {
4501
+ resource.name = name;
4487
4502
  }
4488
4503
  setCustomField(context, resource, { name, value }) {
4489
4504
  if (!resource.custom) {
4490
- throw new Error("Resource has no custom field");
4505
+ return;
4506
+ }
4507
+ if (value === null) {
4508
+ delete resource.custom.fields[name];
4509
+ } else {
4510
+ resource.custom.fields[name] = value;
4491
4511
  }
4492
- resource.custom.fields[name] = value;
4493
4512
  }
4494
4513
  setCustomType(context, resource, { type, fields }) {
4495
- if (!type) {
4496
- resource.custom = void 0;
4497
- } else {
4498
- const resolvedType = this._storage.getByResourceIdentifier(
4514
+ if (type) {
4515
+ resource.custom = createCustomFields(
4516
+ { type, fields },
4499
4517
  context.projectKey,
4500
- type
4518
+ this._storage
4501
4519
  );
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
- }
4520
+ } else {
4521
+ resource.custom = void 0;
4540
4522
  }
4541
4523
  }
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}`);
4560
- }
4561
- const storeReference = resolvedType;
4562
- resource.store = {
4563
- typeId: "store",
4564
- key: storeReference.key
4565
- };
4524
+ setKey(context, resource, { key }) {
4525
+ resource.key = key;
4566
4526
  }
4567
- transitionState(context, resource, { state }) {
4568
- const resolvedType = this._storage.getByResourceIdentifier(
4569
- context.projectKey,
4570
- state
4527
+ };
4528
+
4529
+ // src/repositories/discount-code/actions.ts
4530
+ var DiscountCodeUpdateHandler = class extends AbstractUpdateHandler {
4531
+ changeCartDiscounts(context, resource, { cartDiscounts }) {
4532
+ resource.cartDiscounts = cartDiscounts.map(
4533
+ (obj) => ({
4534
+ typeId: "cart-discount",
4535
+ id: obj.id
4536
+ })
4571
4537
  );
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
- };
4582
4538
  }
4583
- updateSyncInfo(context, resource, { channel, externalId, syncedAt }) {
4584
- if (!channel) return;
4585
- const resolvedType = this._storage.getByResourceIdentifier(
4586
- context.projectKey,
4587
- channel
4588
- );
4589
- if (!resolvedType) {
4590
- throw new Error(`Channel ${channel} not found`);
4539
+ changeIsActive(context, resource, { isActive }) {
4540
+ resource.isActive = isActive;
4541
+ }
4542
+ setCartPredicate(context, resource, { cartPredicate }) {
4543
+ resource.cartPredicate = cartPredicate;
4544
+ }
4545
+ setCustomField(context, resource, { name, value }) {
4546
+ if (!resource.custom) {
4547
+ return;
4591
4548
  }
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];
4549
+ if (value === null) {
4550
+ delete resource.custom.fields[name];
4602
4551
  } 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
- }
4552
+ resource.custom.fields[name] = value;
4553
+ }
4554
+ }
4555
+ setCustomType(context, resource, { type, fields }) {
4556
+ if (type) {
4557
+ resource.custom = createCustomFields(
4558
+ { type, fields },
4559
+ context.projectKey,
4560
+ this._storage
4561
+ );
4562
+ } else {
4563
+ resource.custom = void 0;
4607
4564
  }
4608
4565
  }
4566
+ setDescription(context, resource, { description }) {
4567
+ resource.description = description;
4568
+ }
4569
+ setMaxApplications(context, resource, { maxApplications }) {
4570
+ resource.maxApplications = maxApplications;
4571
+ }
4572
+ setMaxApplicationsPerCustomer(context, resource, {
4573
+ maxApplicationsPerCustomer
4574
+ }) {
4575
+ resource.maxApplicationsPerCustomer = maxApplicationsPerCustomer;
4576
+ }
4577
+ setName(context, resource, { name }) {
4578
+ resource.name = name;
4579
+ }
4580
+ setValidFrom(context, resource, { validFrom }) {
4581
+ resource.validFrom = validFrom;
4582
+ }
4583
+ setValidFromAndUntil(context, resource, { validFrom, validUntil }) {
4584
+ resource.validFrom = validFrom;
4585
+ resource.validUntil = validUntil;
4586
+ }
4587
+ setValidUntil(context, resource, { validUntil }) {
4588
+ resource.validUntil = validUntil;
4589
+ }
4609
4590
  };
4610
4591
 
4611
- // src/repositories/order/index.ts
4612
- var OrderRepository = class extends AbstractResourceRepository {
4592
+ // src/repositories/discount-code/index.ts
4593
+ var DiscountCodeRepository = class extends AbstractResourceRepository {
4613
4594
  constructor(storage) {
4614
- super("order", storage);
4615
- this.actions = new OrderUpdateHandler(storage);
4595
+ super("discount-code", storage);
4596
+ this.actions = new DiscountCodeUpdateHandler(storage);
4616
4597
  }
4617
4598
  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
4599
  const resource = {
4675
4600
  ...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
4601
+ applicationVersion: 1,
4602
+ cartDiscounts: draft.cartDiscounts.map(
4603
+ (obj) => ({
4604
+ typeId: "cart-discount",
4605
+ id: obj.id
4606
+ })
4685
4607
  ),
4608
+ cartPredicate: draft.cartPredicate,
4609
+ code: draft.code,
4610
+ description: draft.description,
4611
+ groups: draft.groups || [],
4612
+ isActive: draft.isActive || true,
4613
+ name: draft.name,
4614
+ references: [],
4615
+ validFrom: draft.validFrom,
4616
+ validUntil: draft.validUntil,
4617
+ maxApplications: draft.maxApplications,
4618
+ maxApplicationsPerCustomer: draft.maxApplicationsPerCustomer,
4686
4619
  custom: createCustomFields(
4687
4620
  draft.custom,
4688
4621
  context.projectKey,
4689
4622
  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)
4623
+ )
4713
4624
  };
4714
4625
  return this.saveNew(context, resource);
4715
4626
  }
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
4627
+ };
4628
+
4629
+ // src/lib/masking.ts
4630
+ var maskSecretValue = (resource, path) => {
4631
+ const parts = path.split(".");
4632
+ const clone = cloneObject(resource);
4633
+ let val = clone;
4634
+ const target = parts.pop();
4635
+ for (let i = 0; i < parts.length; i++) {
4636
+ const part = parts[i];
4637
+ val = val[part];
4638
+ if (val === void 0) {
4639
+ return resource;
4640
+ }
4641
+ }
4642
+ if (val && target && val[target]) {
4643
+ val[target] = "****";
4644
+ }
4645
+ return clone;
4646
+ };
4647
+
4648
+ // src/repositories/extension.ts
4649
+ var ExtensionRepository = class extends AbstractResourceRepository {
4650
+ constructor(storage) {
4651
+ super("extension", storage);
4652
+ this.actions = new ExtensionUpdateHandler(storage);
4653
+ }
4654
+ create(context, draft) {
4655
+ const resource = {
4656
+ ...getBaseResourceProperties(),
4657
+ key: draft.key,
4658
+ timeoutInMs: draft.timeoutInMs,
4659
+ destination: draft.destination,
4660
+ triggers: draft.triggers
4661
+ };
4662
+ return this.saveNew(context, resource);
4663
+ }
4664
+ postProcessResource(context, resource) {
4665
+ if (resource) {
4666
+ const extension = resource;
4667
+ if (extension.destination.type === "HTTP" && extension.destination.authentication?.type === "AuthorizationHeader") {
4668
+ return maskSecretValue(
4669
+ extension,
4670
+ "destination.authentication.headerValue"
4741
4671
  );
4672
+ } else if (extension.destination.type === "AWSLambda") {
4673
+ return maskSecretValue(resource, "destination.accessSecret");
4742
4674
  }
4743
- if (!variant) {
4744
- throw new Error("Internal state error");
4745
- }
4746
- } else {
4747
- throw new Error("No product found");
4748
4675
  }
4749
- const lineItem = {
4750
- ...getBaseResourceProperties(),
4751
- custom: createCustomFields(
4752
- draft.custom,
4676
+ return resource;
4677
+ }
4678
+ };
4679
+ var ExtensionUpdateHandler = class extends AbstractUpdateHandler {
4680
+ changeDestination(context, resource, action) {
4681
+ resource.destination = action.destination;
4682
+ }
4683
+ changeTriggers(context, resource, action) {
4684
+ resource.triggers = action.triggers;
4685
+ }
4686
+ setKey(context, resource, action) {
4687
+ resource.key = action.key;
4688
+ }
4689
+ setTimeoutInMs(context, resource, action) {
4690
+ resource.timeoutInMs = action.timeoutInMs;
4691
+ }
4692
+ };
4693
+
4694
+ // src/repositories/inventory-entry/actions.ts
4695
+ var InventoryEntryUpdateHandler = class extends AbstractUpdateHandler {
4696
+ changeQuantity(context, resource, { quantity }) {
4697
+ resource.quantityOnStock = quantity;
4698
+ resource.availableQuantity = quantity;
4699
+ }
4700
+ setCustomField(context, resource, { name, value }) {
4701
+ if (!resource.custom) {
4702
+ throw new Error("Resource has no custom field");
4703
+ }
4704
+ resource.custom.fields[name] = value;
4705
+ }
4706
+ setCustomType(context, resource, { type, fields }) {
4707
+ if (!type) {
4708
+ resource.custom = void 0;
4709
+ } else {
4710
+ const resolvedType = this._storage.getByResourceIdentifier(
4753
4711
  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)
4712
+ type
4713
+ );
4714
+ if (!resolvedType) {
4715
+ throw new Error(`Type ${type} not found`);
4773
4716
  }
4774
- };
4775
- return lineItem;
4717
+ resource.custom = {
4718
+ type: {
4719
+ typeId: "type",
4720
+ id: resolvedType.id
4721
+ },
4722
+ fields: fields || {}
4723
+ };
4724
+ }
4776
4725
  }
4777
- customLineItemFromImportDraft(context, draft) {
4778
- const lineItem = {
4726
+ setExpectedDelivery(context, resource, { expectedDelivery }) {
4727
+ resource.expectedDelivery = new Date(expectedDelivery).toISOString();
4728
+ }
4729
+ setRestockableInDays(context, resource, { restockableInDays }) {
4730
+ resource.restockableInDays = restockableInDays;
4731
+ }
4732
+ };
4733
+
4734
+ // src/repositories/inventory-entry/index.ts
4735
+ var InventoryEntryRepository = class extends AbstractResourceRepository {
4736
+ constructor(storage) {
4737
+ super("inventory-entry", storage);
4738
+ this.actions = new InventoryEntryUpdateHandler(storage);
4739
+ }
4740
+ create(context, draft) {
4741
+ const resource = {
4779
4742
  ...getBaseResourceProperties(),
4743
+ sku: draft.sku,
4744
+ quantityOnStock: draft.quantityOnStock,
4745
+ availableQuantity: draft.quantityOnStock,
4746
+ expectedDelivery: draft.expectedDelivery,
4747
+ restockableInDays: draft.restockableInDays,
4748
+ supplyChannel: {
4749
+ ...draft.supplyChannel,
4750
+ typeId: "channel",
4751
+ id: draft.supplyChannel?.id ?? ""
4752
+ },
4780
4753
  custom: createCustomFields(
4781
4754
  draft.custom,
4782
4755
  context.projectKey,
4783
4756
  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: []
4757
+ )
4795
4758
  };
4796
- return lineItem;
4759
+ return this.saveNew(context, resource);
4797
4760
  }
4798
- getWithOrderNumber(context, orderNumber, params = {}) {
4799
- const result = this._storage.query(context.projectKey, this.getTypeId(), {
4800
- ...params,
4801
- where: [`orderNumber="${orderNumber}"`]
4761
+ };
4762
+
4763
+ // src/repositories/my-customer.ts
4764
+ var MyCustomerRepository = class extends CustomerRepository {
4765
+ changePassword(context, changePassword) {
4766
+ const { currentPassword, newPassword } = changePassword;
4767
+ const encodedPassword = hashPassword(currentPassword);
4768
+ const result = this._storage.query(context.projectKey, "customer", {
4769
+ where: [`password = "${encodedPassword}"`]
4802
4770
  });
4803
- if (result.count === 1) {
4804
- return result.results[0];
4771
+ if (result.count === 0) {
4772
+ throw new CommercetoolsError({
4773
+ code: "InvalidCurrentPassword",
4774
+ message: "Account with the given credentials not found."
4775
+ });
4805
4776
  }
4806
- if (result.count > 1) {
4807
- throw new Error("Duplicate order numbers");
4777
+ const customer = result.results[0];
4778
+ if (customer.password !== hashPassword(currentPassword)) {
4779
+ throw new CommercetoolsError({
4780
+ code: "InvalidCurrentPassword",
4781
+ message: "The current password is invalid."
4782
+ });
4783
+ }
4784
+ customer.password = hashPassword(newPassword);
4785
+ customer.version += 1;
4786
+ this._storage.add(context.projectKey, "customer", customer);
4787
+ return customer;
4788
+ }
4789
+ confirmEmail(context, resetPassword) {
4790
+ const { tokenValue } = resetPassword;
4791
+ const customerId = validateEmailVerifyToken(tokenValue);
4792
+ if (!customerId) {
4793
+ throw new CommercetoolsError({
4794
+ code: "ResourceNotFound",
4795
+ message: `The Customer with ID 'Token(${tokenValue})' was not found.`
4796
+ });
4797
+ }
4798
+ const customer = this._storage.get(
4799
+ context.projectKey,
4800
+ "customer",
4801
+ customerId
4802
+ );
4803
+ if (!customer) {
4804
+ throw new CommercetoolsError({
4805
+ code: "ResourceNotFound",
4806
+ message: `The Customer with ID 'Token(${tokenValue})' was not found.`
4807
+ });
4808
+ }
4809
+ customer.isEmailVerified = true;
4810
+ customer.version += 1;
4811
+ this._storage.add(context.projectKey, "customer", customer);
4812
+ return customer;
4813
+ }
4814
+ deleteMe(context) {
4815
+ const results = this._storage.query(
4816
+ context.projectKey,
4817
+ this.getTypeId(),
4818
+ {}
4819
+ );
4820
+ if (results.count > 0) {
4821
+ return this.delete(context, results.results[0].id);
4822
+ }
4823
+ return;
4824
+ }
4825
+ getMe(context) {
4826
+ const results = this._storage.query(
4827
+ context.projectKey,
4828
+ this.getTypeId(),
4829
+ {}
4830
+ );
4831
+ if (results.count > 0) {
4832
+ return results.results[0];
4808
4833
  }
4809
4834
  return;
4810
4835
  }
4811
4836
  };
4812
4837
 
4813
4838
  // src/repositories/my-order.ts
4839
+ import assert4 from "assert";
4814
4840
  var MyOrderRepository = class extends OrderRepository {
4815
4841
  create(context, draft) {
4816
4842
  assert4(draft.id, "draft.id is missing");
@@ -6826,6 +6852,17 @@ var ProductSelectionUpdateHandler = class extends AbstractUpdateHandler {
6826
6852
  changeName(context, resource, { name }) {
6827
6853
  resource.name = name;
6828
6854
  }
6855
+ setCustomType(context, resource, { type, fields }) {
6856
+ if (type) {
6857
+ resource.custom = createCustomFields(
6858
+ { type, fields },
6859
+ context.projectKey,
6860
+ this._storage
6861
+ );
6862
+ } else {
6863
+ resource.custom = void 0;
6864
+ }
6865
+ }
6829
6866
  };
6830
6867
 
6831
6868
  // src/repositories/product-type.ts
@@ -7968,6 +8005,10 @@ var ZoneUpdateHandler = class extends AbstractUpdateHandler {
7968
8005
 
7969
8006
  // src/repositories/index.ts
7970
8007
  var createRepositories = (storage) => ({
8008
+ "as-associate": {
8009
+ cart: new AsAssociateCartRepository(storage),
8010
+ order: new AsAssociateOrderRepository(storage)
8011
+ },
7971
8012
  "associate-role": new AssociateRoleRepository(storage),
7972
8013
  "attribute-group": new AttributeGroupRepository(storage),
7973
8014
  "business-unit": new BusinessUnitRepository(storage),
@@ -8011,6 +8052,12 @@ var createRepositories = (storage) => ({
8011
8052
  "zone": new ZoneRepository(storage)
8012
8053
  });
8013
8054
 
8055
+ // src/services/as-associate.ts
8056
+ import { Router as Router4 } from "express";
8057
+
8058
+ // src/services/as-associate-cart.ts
8059
+ import { Router as Router2 } from "express";
8060
+
8014
8061
  // src/services/abstract.ts
8015
8062
  import { Router } from "express";
8016
8063
 
@@ -8200,6 +8247,70 @@ var AbstractService = class {
8200
8247
  }
8201
8248
  };
8202
8249
 
8250
+ // src/services/as-associate-cart.ts
8251
+ var AsAssociateCartService = class extends AbstractService {
8252
+ repository;
8253
+ constructor(parent, repository) {
8254
+ super(parent);
8255
+ this.repository = repository;
8256
+ }
8257
+ getBasePath() {
8258
+ return "carts";
8259
+ }
8260
+ registerRoutes(parent) {
8261
+ const basePath = this.getBasePath();
8262
+ const router = Router2({ mergeParams: true });
8263
+ this.extraRoutes(router);
8264
+ router.get("/", this.get.bind(this));
8265
+ router.get("/:id", this.getWithId.bind(this));
8266
+ router.delete("/:id", this.deleteWithId.bind(this));
8267
+ router.post("/", this.post.bind(this));
8268
+ router.post("/:id", this.postWithId.bind(this));
8269
+ parent.use(`/${basePath}`, router);
8270
+ }
8271
+ };
8272
+
8273
+ // src/services/as-associate-order.ts
8274
+ import { Router as Router3 } from "express";
8275
+ var AsAssociateOrderService = class extends AbstractService {
8276
+ repository;
8277
+ constructor(parent, repository) {
8278
+ super(parent);
8279
+ this.repository = repository;
8280
+ }
8281
+ getBasePath() {
8282
+ return "orders";
8283
+ }
8284
+ registerRoutes(parent) {
8285
+ const basePath = this.getBasePath();
8286
+ const router = Router3({ mergeParams: true });
8287
+ this.extraRoutes(router);
8288
+ router.get("/", this.get.bind(this));
8289
+ router.get("/:id", this.getWithId.bind(this));
8290
+ router.delete("/:id", this.deleteWithId.bind(this));
8291
+ router.post("/", this.post.bind(this));
8292
+ router.post("/:id", this.postWithId.bind(this));
8293
+ parent.use(`/${basePath}`, router);
8294
+ }
8295
+ };
8296
+
8297
+ // src/services/as-associate.ts
8298
+ var AsAssociateService = class {
8299
+ router;
8300
+ subServices;
8301
+ constructor(parent, repositories) {
8302
+ this.router = Router4({ mergeParams: true });
8303
+ this.subServices = {
8304
+ order: new AsAssociateOrderService(this.router, repositories.order),
8305
+ cart: new AsAssociateCartService(this.router, repositories.cart)
8306
+ };
8307
+ parent.use(
8308
+ "/as-associate/:associateId/in-business-unit/key=:businessUnitId",
8309
+ this.router
8310
+ );
8311
+ }
8312
+ };
8313
+
8203
8314
  // src/services/associate-roles.ts
8204
8315
  var AssociateRoleServices = class extends AbstractService {
8205
8316
  repository;
@@ -8481,7 +8592,7 @@ var InventoryEntryService = class extends AbstractService {
8481
8592
  };
8482
8593
 
8483
8594
  // src/services/my-business-unit.ts
8484
- import { Router as Router2 } from "express";
8595
+ import { Router as Router5 } from "express";
8485
8596
  var MyBusinessUnitService = class extends AbstractService {
8486
8597
  repository;
8487
8598
  constructor(parent, repository) {
@@ -8493,7 +8604,7 @@ var MyBusinessUnitService = class extends AbstractService {
8493
8604
  }
8494
8605
  registerRoutes(parent) {
8495
8606
  const basePath = this.getBasePath();
8496
- const router = Router2({ mergeParams: true });
8607
+ const router = Router5({ mergeParams: true });
8497
8608
  this.extraRoutes(router);
8498
8609
  router.get("/business-units/", this.get.bind(this));
8499
8610
  parent.use(`/${basePath}`, router);
@@ -8501,7 +8612,7 @@ var MyBusinessUnitService = class extends AbstractService {
8501
8612
  };
8502
8613
 
8503
8614
  // src/services/my-cart.ts
8504
- import { Router as Router3 } from "express";
8615
+ import { Router as Router6 } from "express";
8505
8616
  var MyCartService = class extends AbstractService {
8506
8617
  repository;
8507
8618
  constructor(parent, repository) {
@@ -8513,7 +8624,7 @@ var MyCartService = class extends AbstractService {
8513
8624
  }
8514
8625
  registerRoutes(parent) {
8515
8626
  const basePath = this.getBasePath();
8516
- const router = Router3({ mergeParams: true });
8627
+ const router = Router6({ mergeParams: true });
8517
8628
  this.extraRoutes(router);
8518
8629
  router.get("/active-cart", this.activeCart.bind(this));
8519
8630
  router.get("/carts/", this.get.bind(this));
@@ -8533,7 +8644,7 @@ var MyCartService = class extends AbstractService {
8533
8644
  };
8534
8645
 
8535
8646
  // src/services/my-customer.ts
8536
- import { Router as Router4 } from "express";
8647
+ import { Router as Router7 } from "express";
8537
8648
  var MyCustomerService = class extends AbstractService {
8538
8649
  repository;
8539
8650
  constructor(parent, repository) {
@@ -8545,7 +8656,7 @@ var MyCustomerService = class extends AbstractService {
8545
8656
  }
8546
8657
  registerRoutes(parent) {
8547
8658
  const basePath = this.getBasePath();
8548
- const router = Router4({ mergeParams: true });
8659
+ const router = Router7({ mergeParams: true });
8549
8660
  this.extraRoutes(router);
8550
8661
  router.get("", this.getMe.bind(this));
8551
8662
  router.post("", this.updateMe.bind(this));
@@ -8641,7 +8752,7 @@ var MyCustomerService = class extends AbstractService {
8641
8752
  };
8642
8753
 
8643
8754
  // src/services/my-order.ts
8644
- import { Router as Router5 } from "express";
8755
+ import { Router as Router8 } from "express";
8645
8756
  var MyOrderService = class extends AbstractService {
8646
8757
  repository;
8647
8758
  constructor(parent, repository) {
@@ -8653,7 +8764,7 @@ var MyOrderService = class extends AbstractService {
8653
8764
  }
8654
8765
  registerRoutes(parent) {
8655
8766
  const basePath = this.getBasePath();
8656
- const router = Router5({ mergeParams: true });
8767
+ const router = Router8({ mergeParams: true });
8657
8768
  this.extraRoutes(router);
8658
8769
  router.get("/orders/", this.get.bind(this));
8659
8770
  router.get("/orders/:id", this.getWithId.bind(this));
@@ -8989,6 +9100,7 @@ var ZoneService = class extends AbstractService {
8989
9100
  // src/services/index.ts
8990
9101
  var createServices = (router, repos) => ({
8991
9102
  "associate-role": new AssociateRoleServices(router, repos["associate-role"]),
9103
+ "as-associate": new AsAssociateService(router, repos["as-associate"]),
8992
9104
  "business-unit": new BusinessUnitServices(router, repos["business-unit"]),
8993
9105
  "category": new CategoryServices(router, repos["category"]),
8994
9106
  "cart": new CartService(router, repos["cart"], repos["order"]),
@@ -9103,12 +9215,10 @@ var CommercetoolsMock = class {
9103
9215
  _storage;
9104
9216
  _oauth2;
9105
9217
  _mswServer = void 0;
9106
- _services;
9107
9218
  _repositories;
9108
9219
  _projectService;
9109
9220
  constructor(options = {}) {
9110
9221
  this.options = { ...DEFAULT_OPTIONS, ...options };
9111
- this._services = null;
9112
9222
  this._repositories = null;
9113
9223
  this._projectService = void 0;
9114
9224
  this._storage = new InMemoryStorage();
@@ -9178,7 +9288,7 @@ var CommercetoolsMock = class {
9178
9288
  app.use("/:projectKey", projectRouter);
9179
9289
  app.use("/:projectKey/in-store/key=:storeKey", projectRouter);
9180
9290
  }
9181
- this._services = createServices(projectRouter, this._repositories);
9291
+ createServices(projectRouter, this._repositories);
9182
9292
  this._projectService = new ProjectService(
9183
9293
  projectRouter,
9184
9294
  this._repositories.project