@labdigital/commercetools-mock 2.41.0 → 2.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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
- } else {
3339
- resource.custom.fields[name] = value;
3340
- }
3341
- }
3342
- setCustomType(context, resource, { type, fields }) {
3343
- if (type) {
3344
- resource.custom = createCustomFields(
3345
- { type, fields },
3346
- context.projectKey,
3347
- this._storage
3348
- );
3349
3212
  } else {
3350
- resource.custom = void 0;
3213
+ throw new Error("No product found");
3351
3214
  }
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);
3380
- }
3381
- create(context, draft) {
3382
- const resource = {
3215
+ const lineItem = {
3383
3216
  ...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
3217
  custom: createCustomFields(
3409
3218
  draft.custom,
3410
3219
  context.projectKey,
3411
3220
  this._storage
3412
- )
3413
- };
3414
- return this.saveNew(context, resource);
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;
3415
3242
  }
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(
3243
+ customLineItemFromImportDraft(context, draft) {
3244
+ const lineItem = {
3245
+ ...getBaseResourceProperties(),
3246
+ custom: createCustomFields(
3247
+ draft.custom,
3425
3248
  context.projectKey,
3426
- node.parent
3427
- );
3428
- ancestors.push({
3429
- typeId: "category",
3430
- id: node.id,
3431
- obj: addExpand ? node : void 0
3432
- });
3249
+ this._storage
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: []
3261
+ };
3262
+ return lineItem;
3263
+ }
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
  }
@@ -3487,632 +3336,814 @@ var ChannelUpdateHandler = class extends AbstractUpdateHandler {
3487
3336
  resource.custom.fields[name] = value;
3488
3337
  }
3489
3338
  }
3490
- setCustomType(context, resource, { type, fields }) {
3491
- if (type) {
3492
- resource.custom = createCustomFields(
3493
- { type, fields },
3494
- context.projectKey,
3495
- this._storage
3496
- );
3497
- } else {
3498
- resource.custom = void 0;
3499
- }
3339
+ setName(context, resource, { name }) {
3340
+ resource.name = name;
3500
3341
  }
3501
- setGeoLocation(context, resource, { geoLocation }) {
3502
- resource.geoLocation = geoLocation;
3342
+ setPermissions(context, resource, { permissions }) {
3343
+ resource.permissions = permissions || [];
3503
3344
  }
3504
3345
  };
3505
3346
 
3506
- // src/repositories/custom-object.ts
3507
- var CustomObjectRepository = class extends AbstractResourceRepository {
3347
+ // src/repositories/attribute-group.ts
3348
+ var AttributeGroupRepository = class extends AbstractResourceRepository {
3508
3349
  constructor(storage) {
3509
- super("key-value-document", storage);
3350
+ super("attribute-group", storage);
3351
+ this.actions = new AttributeGroupUpdateHandler(this._storage);
3510
3352
  }
3511
3353
  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
- }
3551
- }
3552
- getWithContainerAndKey(context, container, key) {
3553
- const items = this._storage.all(context.projectKey, this.getTypeId());
3554
- return items.find(
3555
- (item) => item.container === container && item.key === key
3556
- );
3557
- }
3558
- queryWithContainer(context, container, params = {}) {
3559
- const whereClause = params.where || [];
3560
- whereClause.push(`container="${container}"`);
3561
- const result = this._storage.query(context.projectKey, this.getTypeId(), {
3562
- ...params,
3563
- where: whereClause
3564
- });
3565
- result.results = result.results.map(
3566
- (r) => this.postProcessResource(context, r, {
3567
- expand: params.expand
3568
- })
3569
- );
3570
- return result;
3354
+ const resource = {
3355
+ ...getBaseResourceProperties(),
3356
+ name: draft.name,
3357
+ description: draft.description,
3358
+ key: draft.key,
3359
+ attributes: draft.attributes
3360
+ };
3361
+ return this.saveNew(context, resource);
3571
3362
  }
3572
3363
  };
3573
-
3574
- // src/repositories/customer/actions.ts
3575
- import assert2 from "node:assert";
3576
- var CustomerUpdateHandler = class extends AbstractUpdateHandler {
3577
- addAddress(_context, resource, { address }) {
3578
- resource.addresses.push({
3579
- ...address,
3580
- id: address.id ?? generateRandomString(5)
3581
- });
3364
+ var AttributeGroupUpdateHandler = class extends AbstractUpdateHandler {
3365
+ changeName(_context, resource, { name }) {
3366
+ resource.name = name;
3582
3367
  }
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);
3591
- }
3368
+ setAttributes(_context, resource, { attributes }) {
3369
+ resource.attributes = attributes;
3592
3370
  }
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;
3371
+ setDescription(_context, resource, { description }) {
3372
+ resource.description = description;
3603
3373
  }
3604
- addStore(context, resource, action) {
3605
- throw new Error("Method not implemented.");
3374
+ setKey(_context, resource, { key }) {
3375
+ resource.key = key;
3606
3376
  }
3607
- changeAddress(context, resource, { addressId, addressKey, address }) {
3608
- const current = this._findAddress(resource, addressId, addressKey, true);
3609
- assert2(current?.id);
3610
- const oldAddressIndex = resource.addresses.findIndex(
3611
- (a) => a.id === current.id
3612
- );
3613
- const newAddress = createAddress(
3614
- address,
3615
- context.projectKey,
3616
- this._storage
3377
+ };
3378
+
3379
+ // src/repositories/business-unit.ts
3380
+ var BusinessUnitRepository = class extends AbstractResourceRepository {
3381
+ constructor(storage) {
3382
+ super("business-unit", storage);
3383
+ this.actions = new BusinessUnitUpdateHandler(this._storage);
3384
+ }
3385
+ create(context, draft) {
3386
+ const addresses = draft.addresses?.map((address) => ({
3387
+ ...address,
3388
+ id: generateRandomString(5)
3389
+ })) ?? [];
3390
+ const defaultBillingAddressId = addresses.length > 0 && draft.defaultBillingAddress !== void 0 ? addresses[draft.defaultBillingAddress].id : void 0;
3391
+ const defaultShippingAddressId = addresses.length > 0 && draft.defaultShippingAddress !== void 0 ? addresses[draft.defaultShippingAddress].id : void 0;
3392
+ const shippingAddressIds = draft.shippingAddresses?.map(
3393
+ (i) => addresses[i].id
3617
3394
  );
3618
- if (newAddress) {
3619
- resource.addresses[oldAddressIndex] = {
3620
- id: addressId,
3621
- ...newAddress
3395
+ const billingAddressIds = draft.billingAddresses?.map(
3396
+ (i) => addresses[i].id
3397
+ );
3398
+ const resource = {
3399
+ ...getBaseResourceProperties(),
3400
+ key: draft.key,
3401
+ status: draft.status,
3402
+ stores: draft.stores?.map(
3403
+ (s) => getStoreKeyReference(s, context.projectKey, this._storage)
3404
+ ),
3405
+ storeMode: draft.storeMode,
3406
+ name: draft.name,
3407
+ contactEmail: draft.contactEmail,
3408
+ addresses,
3409
+ custom: createCustomFields(
3410
+ draft.custom,
3411
+ context.projectKey,
3412
+ this._storage
3413
+ ),
3414
+ shippingAddressIds,
3415
+ billingAddressIds,
3416
+ defaultShippingAddressId,
3417
+ defaultBillingAddressId,
3418
+ associateMode: draft.associateMode,
3419
+ approvalRuleMode: draft.approvalRuleMode,
3420
+ associates: draft.associates?.map(
3421
+ (a) => createAssociate(a, context.projectKey, this._storage)
3422
+ ) ?? []
3423
+ };
3424
+ if (this._isDivisionDraft(draft)) {
3425
+ const division = {
3426
+ ...resource,
3427
+ parentUnit: getBusinessUnitKeyReference(
3428
+ draft.parentUnit,
3429
+ context.projectKey,
3430
+ this._storage
3431
+ )
3622
3432
  };
3433
+ this.saveNew(context, division);
3434
+ return division;
3435
+ } else if (this._isCompanyDraft(draft)) {
3436
+ const company = resource;
3437
+ this.saveNew(context, company);
3438
+ return company;
3623
3439
  }
3440
+ throw new Error("Invalid business unit type");
3624
3441
  }
3625
- changeEmail(_context, resource, { email }) {
3626
- resource.email = email;
3442
+ _isCompanyDraft(draft) {
3443
+ return draft.unitType === "Company";
3627
3444
  }
3628
- removeAddress(context, resource, action) {
3629
- const address = this._findAddress(
3630
- resource,
3631
- action.addressId,
3632
- action.addressKey,
3633
- true
3634
- );
3635
- assert2(address?.id);
3636
- resource.addresses = resource.addresses.filter((a) => a.id !== address.id);
3445
+ _isDivisionDraft(draft) {
3446
+ return draft.unitType === "Division";
3637
3447
  }
3638
- removeBillingAddressId(context, resource, action) {
3639
- const address = this._findAddress(
3640
- resource,
3641
- action.addressId,
3642
- action.addressKey,
3643
- true
3448
+ };
3449
+ var BusinessUnitUpdateHandler = class extends AbstractUpdateHandler {
3450
+ addAddress(context, resource, { address }) {
3451
+ const newAddress = createAddress(
3452
+ address,
3453
+ context.projectKey,
3454
+ this._storage
3644
3455
  );
3645
- assert2(address?.id);
3646
- resource.billingAddressIds = resource.billingAddressIds?.filter(
3647
- (id) => id !== address.id
3456
+ if (newAddress) {
3457
+ resource.addresses.push(newAddress);
3458
+ }
3459
+ }
3460
+ addAssociate(context, resource, { associate }) {
3461
+ const newAssociate = createAssociate(
3462
+ associate,
3463
+ context.projectKey,
3464
+ this._storage
3648
3465
  );
3649
- if (resource.defaultBillingAddressId === address.id) {
3650
- resource.defaultBillingAddressId = void 0;
3466
+ if (newAssociate) {
3467
+ resource.associates.push(newAssociate);
3651
3468
  }
3652
3469
  }
3653
- removeShippingAddressId(context, resource, action) {
3654
- const address = this._findAddress(
3655
- resource,
3656
- action.addressId,
3657
- action.addressKey,
3658
- true
3470
+ addStore(context, resource, { store }) {
3471
+ const newStore = getStoreKeyReference(
3472
+ store,
3473
+ context.projectKey,
3474
+ this._storage
3659
3475
  );
3660
- assert2(address?.id);
3661
- resource.shippingAddressIds = resource.shippingAddressIds?.filter(
3662
- (id) => id !== address.id
3476
+ if (newStore) {
3477
+ if (!resource.stores) {
3478
+ resource.stores = [];
3479
+ }
3480
+ resource.stores.push(newStore);
3481
+ }
3482
+ }
3483
+ changeAddress(context, resource, { address }) {
3484
+ const newAddress = createAddress(
3485
+ address,
3486
+ context.projectKey,
3487
+ this._storage
3663
3488
  );
3664
- if (resource.defaultShippingAddressId === address.id) {
3665
- resource.defaultShippingAddressId = void 0;
3489
+ if (newAddress) {
3490
+ resource.addresses.push(newAddress);
3666
3491
  }
3667
3492
  }
3668
- removeStore(context, resource, action) {
3669
- throw new Error("Method not implemented.");
3493
+ changeApprovalRuleMode(context, resource, { approvalRuleMode }) {
3494
+ resource.approvalRuleMode = approvalRuleMode;
3670
3495
  }
3671
- setAddressCustomField(context, resource, action) {
3672
- throw new Error("Method not implemented.");
3496
+ changeAssociateMode(context, resource, { associateMode }) {
3497
+ resource.associateMode = associateMode;
3673
3498
  }
3674
- setAddressCustomType(context, resource, action) {
3675
- throw new Error("Method not implemented.");
3499
+ changeName(context, resource, { name }) {
3500
+ resource.name = name;
3676
3501
  }
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
3502
+ changeParentUnit(context, resource, { parentUnit }) {
3503
+ resource.parentUnit = getBusinessUnitKeyReference(
3504
+ parentUnit,
3505
+ context.projectKey,
3506
+ this._storage
3703
3507
  );
3704
3508
  }
3705
- setCompanyName(_context, resource, { companyName }) {
3706
- resource.companyName = companyName;
3509
+ changeStatus(context, resource, { status }) {
3510
+ resource.status = status;
3707
3511
  }
3708
- setCustomerGroup(context, resource, action) {
3709
- if (!action.customerGroup) {
3710
- throw new CommercetoolsError(
3711
- {
3712
- code: "InvalidOperation",
3713
- message: "CustomerGroup is required."
3714
- },
3715
- 400
3716
- );
3717
- }
3718
- const group = this._storage.getByResourceIdentifier(
3719
- context.projectKey,
3720
- action.customerGroup
3721
- );
3722
- resource.customerGroup = {
3723
- typeId: "customer-group",
3724
- id: group.id
3725
- };
3512
+ setAssociates(context, resource, { associates }) {
3513
+ const newAssociates = associates.map((a) => createAssociate(a, context.projectKey, this._storage)).filter((a) => a !== void 0);
3514
+ resource.associates = newAssociates || void 0;
3726
3515
  }
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;
3516
+ setContactEmail(context, resource, { contactEmail }) {
3517
+ resource.contactEmail = contactEmail;
3734
3518
  }
3735
- setCustomField(_context, resource, { name, value }) {
3519
+ setStoreMode(context, resource, { storeMode }) {
3520
+ resource.storeMode = storeMode;
3521
+ }
3522
+ };
3523
+
3524
+ // src/repositories/cart-discount/actions.ts
3525
+ var CartDiscountUpdateHandler = class extends AbstractUpdateHandler {
3526
+ changeIsActive(context, resource, { isActive }) {
3527
+ resource.isActive = isActive;
3528
+ }
3529
+ changeSortOrder(context, resource, { sortOrder }) {
3530
+ resource.sortOrder = sortOrder;
3531
+ }
3532
+ changeTarget(context, resource, { target }) {
3533
+ resource.target = target;
3534
+ }
3535
+ setCustomField(context, resource, { name, value }) {
3736
3536
  if (!resource.custom) {
3737
- throw new Error("Resource has no custom field");
3537
+ return;
3738
3538
  }
3739
- resource.custom.fields[name] = value;
3740
- }
3741
- setCustomType(context, resource, { type, fields }) {
3742
- if (type) {
3743
- resource.custom = createCustomFields(
3744
- { type, fields },
3745
- context.projectKey,
3746
- this._storage
3747
- );
3539
+ if (value === null) {
3540
+ if (name in resource.custom.fields) {
3541
+ delete resource.custom.fields[name];
3542
+ } else {
3543
+ throw new CommercetoolsError(
3544
+ {
3545
+ code: "InvalidOperation",
3546
+ message: "Cannot remove custom field " + name + " because it does not exist."
3547
+ },
3548
+ 400
3549
+ );
3550
+ }
3748
3551
  } else {
3749
- resource.custom = void 0;
3552
+ resource.custom.fields[name] = value;
3750
3553
  }
3751
3554
  }
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);
3555
+ setCustomType(context, resource, { type, fields }) {
3556
+ if (!type) {
3557
+ resource.custom = void 0;
3558
+ } else {
3559
+ const resolvedType = this._storage.getByResourceIdentifier(
3560
+ context.projectKey,
3561
+ type
3562
+ );
3563
+ if (!resolvedType) {
3564
+ throw new Error(`Type ${type} not found`);
3565
+ }
3566
+ resource.custom = {
3567
+ type: {
3568
+ typeId: "type",
3569
+ id: resolvedType.id
3570
+ },
3571
+ fields: fields || {}
3572
+ };
3785
3573
  }
3786
3574
  }
3787
- setExternalId(_context, resource, { externalId }) {
3788
- resource.externalId = externalId;
3789
- }
3790
- setFirstName(_context, resource, { firstName }) {
3791
- resource.firstName = firstName;
3575
+ setDescription(context, resource, { description }) {
3576
+ resource.description = description;
3792
3577
  }
3793
- setKey(_context, resource, { key }) {
3578
+ setKey(context, resource, { key }) {
3794
3579
  resource.key = key;
3795
3580
  }
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;
3807
- }
3808
- setStores(context, resource, action) {
3809
- throw new Error("Method not implemented.");
3581
+ setStores(context, resource, { stores }) {
3582
+ resource.stores = stores?.map(
3583
+ (s) => getStoreKeyReference(s, context.projectKey, this._storage)
3584
+ );
3810
3585
  }
3811
- setTitle(context, resource, action) {
3812
- resource.title = action.title;
3586
+ setValidFrom(context, resource, { validFrom }) {
3587
+ resource.validFrom = validFrom;
3813
3588
  }
3814
- setVatId(_context, resource, { vatId }) {
3815
- resource.vatId = vatId;
3589
+ setValidFromAndUntil(context, resource, { validFrom, validUntil }) {
3590
+ resource.validFrom = validFrom;
3591
+ resource.validUntil = validUntil;
3816
3592
  }
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;
3830
- }
3831
- if (addressId) {
3832
- const address = resource.addresses.find((a) => a.id === addressId);
3833
- if (!address) {
3834
- throw new CommercetoolsError(
3835
- {
3836
- code: "InvalidOperation",
3837
- message: `Customer does not contain an address with the id ${addressId}.`
3838
- },
3839
- 400
3840
- );
3841
- }
3842
- return address;
3843
- }
3844
- if (required) {
3845
- throw new CommercetoolsError(
3846
- {
3847
- code: "InvalidOperation",
3848
- message: "One of address 'addressId' or 'addressKey' is required."
3849
- },
3850
- 400
3851
- );
3852
- }
3593
+ setValidUntil(context, resource, { validUntil }) {
3594
+ resource.validUntil = validUntil;
3853
3595
  }
3854
3596
  };
3855
3597
 
3856
- // src/repositories/customer/index.ts
3857
- var CustomerRepository = class extends AbstractResourceRepository {
3598
+ // src/repositories/cart-discount/index.ts
3599
+ var CartDiscountRepository = class extends AbstractResourceRepository {
3858
3600
  constructor(storage) {
3859
- super("customer", storage);
3860
- this.actions = new CustomerUpdateHandler(storage);
3601
+ super("cart-discount", storage);
3602
+ this.actions = new CartDiscountUpdateHandler(storage);
3861
3603
  }
3862
3604
  create(context, draft) {
3863
- const results = this._storage.query(context.projectKey, this.getTypeId(), {
3864
- where: [`lowercaseEmail="${draft.email.toLowerCase()}"`]
3865
- });
3866
- if (results.count > 0) {
3867
- throw new CommercetoolsError({
3868
- code: "CustomerAlreadyExists",
3869
- statusCode: 400,
3870
- message: "There is already an existing customer with the provided email.",
3871
- errors: [
3872
- {
3873
- code: "DuplicateField",
3874
- message: `Customer with email '${draft.email}' already exists.`,
3875
- duplicateValue: draft.email,
3876
- field: "email"
3877
- }
3878
- ]
3879
- });
3880
- }
3881
- const addresses = draft.addresses?.map((address) => ({
3882
- ...address,
3883
- id: generateRandomString(5)
3884
- })) ?? [];
3885
- const lookupAdressId = (addresses2, addressId) => {
3886
- if (addressId < addresses2.length) {
3887
- const id = addresses2[addressId].id;
3888
- if (!id) {
3889
- throw new Error("Address ID is missing");
3890
- }
3891
- return id;
3892
- }
3893
- throw new CommercetoolsError({
3894
- code: "InvalidInput",
3895
- message: `Address with ID '${addressId}' not found.`,
3896
- errors: [
3897
- {
3898
- code: "InvalidInput",
3899
- message: `Address with ID '${addressId}' not found.`,
3900
- field: "addressId"
3901
- }
3902
- ]
3903
- });
3904
- };
3905
- const defaultBillingAddressId = draft.defaultBillingAddress !== void 0 ? lookupAdressId(addresses, draft.defaultBillingAddress) : void 0;
3906
- const defaultShippingAddressId = draft.defaultShippingAddress !== void 0 ? lookupAdressId(addresses, draft.defaultShippingAddress) : void 0;
3907
- const shippingAddressIds = draft.shippingAddresses?.map(
3908
- (addressId) => lookupAdressId(addresses, addressId)
3909
- ) ?? [];
3910
- const billingAddressIds = draft.billingAddresses?.map(
3911
- (addressId) => lookupAdressId(addresses, addressId)
3912
- ) ?? [];
3913
- let storesForCustomer = [];
3914
- if (draft.stores && draft.stores.length > 0) {
3915
- const storeIds = draft.stores.map((storeReference) => storeReference.id).filter(Boolean);
3916
- const stores = this._storage.query(context.projectKey, "store", {
3917
- where: storeIds.map((id) => `id="${id}"`)
3918
- }).results;
3919
- if (storeIds.length !== stores.length) {
3920
- throw new CommercetoolsError({
3921
- code: "ResourceNotFound",
3922
- message: `Store with ID '${storeIds.find((id) => !stores.some((store) => store.id === id))}' was not found.`
3923
- });
3924
- }
3925
- storesForCustomer = draft.stores.map((storeReference) => ({
3926
- typeId: "store",
3927
- key: storeReference.key ?? stores.find((store) => store.id === storeReference.id)?.key
3928
- }));
3929
- }
3930
3605
  const resource = {
3931
3606
  ...getBaseResourceProperties(),
3932
3607
  key: draft.key,
3933
- authenticationMode: draft.authenticationMode || "Password",
3934
- firstName: draft.firstName,
3935
- lastName: draft.lastName,
3936
- middleName: draft.middleName,
3937
- title: draft.title,
3938
- dateOfBirth: draft.dateOfBirth,
3939
- companyName: draft.companyName,
3940
- email: draft.email.toLowerCase(),
3941
- lowercaseEmail: draft.email.toLowerCase(),
3942
- password: draft.password ? hashPassword(draft.password) : void 0,
3943
- isEmailVerified: draft.isEmailVerified || false,
3944
- addresses,
3945
- customerNumber: draft.customerNumber,
3946
- externalId: draft.externalId,
3947
- defaultBillingAddressId,
3948
- defaultShippingAddressId,
3949
- shippingAddressIds,
3950
- billingAddressIds,
3608
+ description: draft.description,
3609
+ cartPredicate: draft.cartPredicate,
3610
+ isActive: draft.isActive || false,
3611
+ name: draft.name,
3612
+ stores: draft.stores?.map(
3613
+ (s) => getStoreKeyReference(s, context.projectKey, this._storage)
3614
+ ) ?? [],
3615
+ references: [],
3616
+ target: draft.target,
3617
+ requiresDiscountCode: draft.requiresDiscountCode || false,
3618
+ sortOrder: draft.sortOrder,
3619
+ stackingMode: draft.stackingMode || "Stacking",
3620
+ validFrom: draft.validFrom,
3621
+ validUntil: draft.validUntil,
3622
+ value: this.transformValueDraft(draft.value),
3951
3623
  custom: createCustomFields(
3952
3624
  draft.custom,
3953
3625
  context.projectKey,
3954
3626
  this._storage
3955
- ),
3956
- stores: storesForCustomer
3627
+ )
3957
3628
  };
3958
3629
  return this.saveNew(context, resource);
3959
3630
  }
3960
- saveUpdate(context, version, resource) {
3961
- const updatedResource = {
3962
- ...resource,
3963
- lowercaseEmail: resource.email.toLowerCase()
3964
- };
3965
- return super.saveUpdate(context, version, updatedResource);
3966
- }
3967
- passwordResetToken(context, request) {
3968
- const results = this._storage.query(context.projectKey, this.getTypeId(), {
3969
- where: [`email="${request.email.toLocaleLowerCase()}"`]
3970
- });
3971
- if (results.count === 0) {
3972
- throw new CommercetoolsError({
3973
- code: "ResourceNotFound",
3974
- message: `The Customer with ID '${request.email}' was not found.`
3975
- });
3976
- }
3977
- const ttlMinutes = request.ttlMinutes ?? 34560;
3978
- const expiresAt = new Date((/* @__PURE__ */ new Date()).getTime() + ttlMinutes * 60 * 1e3);
3979
- const customer = results.results[0];
3980
- const rest = getBaseResourceProperties();
3981
- const token = createPasswordResetToken(customer, expiresAt);
3982
- return {
3983
- id: rest.id,
3984
- createdAt: rest.createdAt,
3985
- lastModifiedAt: rest.lastModifiedAt,
3986
- customerId: customer.id,
3987
- expiresAt: expiresAt.toISOString(),
3988
- value: token
3989
- };
3631
+ transformValueDraft(value) {
3632
+ switch (value.type) {
3633
+ case "absolute": {
3634
+ return {
3635
+ type: "absolute",
3636
+ money: value.money.map(createTypedMoney)
3637
+ };
3638
+ }
3639
+ case "fixed": {
3640
+ return {
3641
+ type: "fixed",
3642
+ money: value.money.map(createTypedMoney)
3643
+ };
3644
+ }
3645
+ case "giftLineItem": {
3646
+ return {
3647
+ ...value
3648
+ };
3649
+ }
3650
+ case "relative": {
3651
+ return {
3652
+ ...value
3653
+ };
3654
+ }
3655
+ }
3656
+ return value;
3990
3657
  }
3991
- passwordReset(context, resetPassword) {
3992
- const { newPassword, tokenValue } = resetPassword;
3993
- const customerId = validatePasswordResetToken(tokenValue);
3994
- if (!customerId) {
3995
- throw new CommercetoolsError({
3996
- code: "ResourceNotFound",
3997
- message: `The Customer with ID 'Token(${tokenValue})' was not found.`
3998
- });
3658
+ };
3659
+
3660
+ // src/repositories/category/index.ts
3661
+ import { v4 as uuidv48 } from "uuid";
3662
+
3663
+ // src/repositories/category/actions.ts
3664
+ import { v4 as uuidv47 } from "uuid";
3665
+ var CategoryUpdateHandler = class extends AbstractUpdateHandler {
3666
+ addAsset(context, resource, { asset }) {
3667
+ if (!resource.assets) {
3668
+ resource.assets = [this.assetFromAssetDraft(asset, context)];
3669
+ } else {
3670
+ resource.assets.push(this.assetFromAssetDraft(asset, context));
3999
3671
  }
4000
- const customer = this._storage.get(
3672
+ }
3673
+ changeAssetName(context, resource, { assetId, assetKey, name }) {
3674
+ resource.assets?.forEach((asset) => {
3675
+ if (assetId && assetId === asset.id) {
3676
+ asset.name = name;
3677
+ }
3678
+ if (assetKey && assetKey === asset.key) {
3679
+ asset.name = name;
3680
+ }
3681
+ });
3682
+ }
3683
+ changeName(context, resource, { name }) {
3684
+ resource.name = name;
3685
+ }
3686
+ changeParent(context, resource, { parent }) {
3687
+ const category = this._storage.getByResourceIdentifier(
4001
3688
  context.projectKey,
4002
- "customer",
4003
- customerId
3689
+ parent
4004
3690
  );
4005
- if (!customer) {
4006
- throw new CommercetoolsError({
4007
- code: "ResourceNotFound",
4008
- message: `The Customer with ID 'Token(${tokenValue})' was not found.`
3691
+ if (!category) {
3692
+ throw new Error("No category found for reference");
3693
+ }
3694
+ resource.parent = {
3695
+ typeId: "category",
3696
+ id: category.id
3697
+ };
3698
+ }
3699
+ changeSlug(context, resource, { slug }) {
3700
+ resource.slug = slug;
3701
+ }
3702
+ removeAsset(context, resource, { assetId, assetKey }) {
3703
+ if (!resource.assets) {
3704
+ return;
3705
+ }
3706
+ if (assetId) {
3707
+ resource.assets = resource.assets.filter(function(obj) {
3708
+ return obj.id !== assetId;
4009
3709
  });
3710
+ return;
3711
+ }
3712
+ if (assetKey) {
3713
+ resource.assets = resource.assets.filter(function(obj) {
3714
+ return obj.key !== assetKey;
3715
+ });
3716
+ return;
4010
3717
  }
4011
- customer.password = hashPassword(newPassword);
4012
- customer.version += 1;
4013
- this._storage.add(context.projectKey, "customer", customer);
4014
- return customer;
4015
3718
  }
4016
- verifyEmailToken(context, id) {
4017
- const results = this._storage.query(context.projectKey, this.getTypeId(), {
4018
- where: [`id="${id.toLocaleLowerCase()}"`]
3719
+ setAssetDescription(context, resource, { assetId, assetKey, description }) {
3720
+ resource.assets?.forEach((asset) => {
3721
+ if (assetId && assetId === asset.id) {
3722
+ asset.description = description;
3723
+ }
3724
+ if (assetKey && assetKey === asset.key) {
3725
+ asset.description = description;
3726
+ }
4019
3727
  });
4020
- if (results.count === 0) {
4021
- throw new CommercetoolsError({
4022
- code: "ResourceNotFound",
4023
- message: `The Customer with ID '${id}' was not found.`
3728
+ }
3729
+ setAssetSources(context, resource, { assetId, assetKey, sources }) {
3730
+ resource.assets?.forEach((asset) => {
3731
+ if (assetId && assetId === asset.id) {
3732
+ asset.sources = sources;
3733
+ }
3734
+ if (assetKey && assetKey === asset.key) {
3735
+ asset.sources = sources;
3736
+ }
3737
+ });
3738
+ }
3739
+ setCustomField(context, resource, { name, value }) {
3740
+ if (!resource.custom) {
3741
+ return;
3742
+ }
3743
+ if (value === null) {
3744
+ delete resource.custom.fields[name];
3745
+ } else {
3746
+ resource.custom.fields[name] = value;
3747
+ }
3748
+ }
3749
+ setCustomType(context, resource, { type, fields }) {
3750
+ if (type) {
3751
+ resource.custom = createCustomFields(
3752
+ { type, fields },
3753
+ context.projectKey,
3754
+ this._storage
3755
+ );
3756
+ } else {
3757
+ resource.custom = void 0;
3758
+ }
3759
+ }
3760
+ setDescription(context, resource, { description }) {
3761
+ resource.description = description;
3762
+ }
3763
+ setKey(context, resource, { key }) {
3764
+ resource.key = key;
3765
+ }
3766
+ setMetaDescription(context, resource, { metaDescription }) {
3767
+ resource.metaDescription = metaDescription;
3768
+ }
3769
+ setMetaKeywords(context, resource, { metaKeywords }) {
3770
+ resource.metaKeywords = metaKeywords;
3771
+ }
3772
+ setMetaTitle(context, resource, { metaTitle }) {
3773
+ resource.metaTitle = metaTitle;
3774
+ }
3775
+ assetFromAssetDraft = (draft, context) => ({
3776
+ ...draft,
3777
+ id: uuidv47(),
3778
+ custom: createCustomFields(draft.custom, context.projectKey, this._storage)
3779
+ });
3780
+ };
3781
+
3782
+ // src/repositories/category/index.ts
3783
+ var CategoryRepository = class extends AbstractResourceRepository {
3784
+ constructor(storage) {
3785
+ super("category", storage);
3786
+ this.actions = new CategoryUpdateHandler(this._storage);
3787
+ }
3788
+ create(context, draft) {
3789
+ const resource = {
3790
+ ...getBaseResourceProperties(),
3791
+ key: draft.key,
3792
+ name: draft.name,
3793
+ slug: draft.slug,
3794
+ description: draft.description,
3795
+ metaDescription: draft.metaDescription,
3796
+ metaKeywords: draft.metaKeywords,
3797
+ orderHint: draft.orderHint || "",
3798
+ externalId: draft.externalId || "",
3799
+ parent: draft.parent ? { typeId: "category", id: draft.parent.id } : void 0,
3800
+ ancestors: [],
3801
+ // Resolved at runtime
3802
+ assets: draft.assets?.map((d) => ({
3803
+ id: uuidv48(),
3804
+ name: d.name,
3805
+ description: d.description,
3806
+ sources: d.sources,
3807
+ tags: d.tags,
3808
+ key: d.key,
3809
+ custom: createCustomFields(
3810
+ draft.custom,
3811
+ context.projectKey,
3812
+ this._storage
3813
+ )
3814
+ })) || [],
3815
+ custom: createCustomFields(
3816
+ draft.custom,
3817
+ context.projectKey,
3818
+ this._storage
3819
+ )
3820
+ };
3821
+ return this.saveNew(context, resource);
3822
+ }
3823
+ postProcessResource(context, resource, params) {
3824
+ let node = resource;
3825
+ const ancestors = [];
3826
+ const expandClauses = params?.expand?.map(parseExpandClause) ?? [];
3827
+ const addExpand = expandClauses?.find(
3828
+ (c) => c.element === "ancestors" && c.index === "*"
3829
+ );
3830
+ while (node.parent) {
3831
+ node = this._storage.getByResourceIdentifier(
3832
+ context.projectKey,
3833
+ node.parent
3834
+ );
3835
+ ancestors.push({
3836
+ typeId: "category",
3837
+ id: node.id,
3838
+ obj: addExpand ? node : void 0
4024
3839
  });
4025
3840
  }
4026
- const expiresAt = new Date(Date.now() + 30 * 60);
4027
- const customer = results.results[0];
4028
- const rest = getBaseResourceProperties();
4029
- const token = createEmailVerifyToken(customer);
4030
- return {
4031
- id: rest.id,
4032
- createdAt: rest.createdAt,
4033
- lastModifiedAt: rest.lastModifiedAt,
4034
- customerId: customer.id,
4035
- expiresAt: expiresAt.toISOString(),
4036
- value: token
3841
+ resource.ancestors = ancestors;
3842
+ return resource;
3843
+ }
3844
+ };
3845
+
3846
+ // src/repositories/channel.ts
3847
+ var ChannelRepository = class extends AbstractResourceRepository {
3848
+ constructor(storage) {
3849
+ super("channel", storage);
3850
+ this.actions = new ChannelUpdateHandler(this._storage);
3851
+ }
3852
+ create(context, draft) {
3853
+ const resource = {
3854
+ ...getBaseResourceProperties(),
3855
+ key: draft.key,
3856
+ name: draft.name,
3857
+ description: draft.description,
3858
+ roles: draft.roles || [],
3859
+ geoLocation: draft.geoLocation,
3860
+ address: createAddress(draft.address, context.projectKey, this._storage),
3861
+ custom: createCustomFields(
3862
+ draft.custom,
3863
+ context.projectKey,
3864
+ this._storage
3865
+ )
4037
3866
  };
3867
+ return this.saveNew(context, resource);
3868
+ }
3869
+ };
3870
+ var ChannelUpdateHandler = class extends AbstractUpdateHandler {
3871
+ changeDescription(context, resource, { description }) {
3872
+ resource.description = description;
3873
+ }
3874
+ changeKey(context, resource, { key }) {
3875
+ resource.key = key;
3876
+ }
3877
+ changeName(context, resource, { name }) {
3878
+ resource.name = name;
3879
+ }
3880
+ setAddress(context, resource, { address }) {
3881
+ resource.address = createAddress(
3882
+ address,
3883
+ context.projectKey,
3884
+ this._storage
3885
+ );
3886
+ }
3887
+ setCustomField(context, resource, { name, value }) {
3888
+ if (!resource.custom) {
3889
+ return;
3890
+ }
3891
+ if (value === null) {
3892
+ delete resource.custom.fields[name];
3893
+ } else {
3894
+ resource.custom.fields[name] = value;
3895
+ }
3896
+ }
3897
+ setCustomType(context, resource, { type, fields }) {
3898
+ if (type) {
3899
+ resource.custom = createCustomFields(
3900
+ { type, fields },
3901
+ context.projectKey,
3902
+ this._storage
3903
+ );
3904
+ } else {
3905
+ resource.custom = void 0;
3906
+ }
3907
+ }
3908
+ setGeoLocation(context, resource, { geoLocation }) {
3909
+ resource.geoLocation = geoLocation;
3910
+ }
3911
+ };
3912
+
3913
+ // src/repositories/custom-object.ts
3914
+ var CustomObjectRepository = class extends AbstractResourceRepository {
3915
+ constructor(storage) {
3916
+ super("key-value-document", storage);
3917
+ }
3918
+ create(context, draft) {
3919
+ const current = this.getWithContainerAndKey(
3920
+ context,
3921
+ draft.container,
3922
+ draft.key
3923
+ );
3924
+ if (current) {
3925
+ if (draft.version) {
3926
+ checkConcurrentModification(current.version, draft.version, current.id);
3927
+ } else {
3928
+ draft.version = current.version;
3929
+ }
3930
+ if (draft.value !== current.value) {
3931
+ const updated = cloneObject(current);
3932
+ updated.value = draft.value;
3933
+ updated.version += 1;
3934
+ this.saveUpdate(context, draft.version, updated);
3935
+ return updated;
3936
+ }
3937
+ return current;
3938
+ } else {
3939
+ if (draft.version) {
3940
+ throw new CommercetoolsError(
3941
+ {
3942
+ code: "InvalidOperation",
3943
+ message: "version on create must be 0"
3944
+ },
3945
+ 400
3946
+ );
3947
+ }
3948
+ const baseProperties = getBaseResourceProperties();
3949
+ const resource = {
3950
+ ...baseProperties,
3951
+ container: draft.container,
3952
+ key: draft.key,
3953
+ value: draft.value
3954
+ };
3955
+ this.saveNew(context, resource);
3956
+ return resource;
3957
+ }
3958
+ }
3959
+ getWithContainerAndKey(context, container, key) {
3960
+ const items = this._storage.all(context.projectKey, this.getTypeId());
3961
+ return items.find(
3962
+ (item) => item.container === container && item.key === key
3963
+ );
3964
+ }
3965
+ queryWithContainer(context, container, params = {}) {
3966
+ const whereClause = params.where || [];
3967
+ whereClause.push(`container="${container}"`);
3968
+ const result = this._storage.query(context.projectKey, this.getTypeId(), {
3969
+ ...params,
3970
+ where: whereClause
3971
+ });
3972
+ result.results = result.results.map(
3973
+ (r) => this.postProcessResource(context, r, {
3974
+ expand: params.expand
3975
+ })
3976
+ );
3977
+ return result;
3978
+ }
3979
+ };
3980
+
3981
+ // src/repositories/customer/actions.ts
3982
+ import assert3 from "node:assert";
3983
+ var CustomerUpdateHandler = class extends AbstractUpdateHandler {
3984
+ addAddress(_context, resource, { address }) {
3985
+ resource.addresses.push({
3986
+ ...address,
3987
+ id: address.id ?? generateRandomString(5)
3988
+ });
3989
+ }
3990
+ addBillingAddressId(_context, resource, { addressId, addressKey }) {
3991
+ const address = this._findAddress(resource, addressId, addressKey, true);
3992
+ assert3(address?.id);
3993
+ if (resource.billingAddressIds === void 0) {
3994
+ resource.billingAddressIds = [];
3995
+ }
3996
+ if (!resource.billingAddressIds.includes(address.id)) {
3997
+ resource.billingAddressIds.push(address.id);
3998
+ }
3999
+ }
4000
+ addShippingAddressId(_context, resource, { addressId, addressKey }) {
4001
+ const address = this._findAddress(resource, addressId, addressKey, true);
4002
+ assert3(address?.id);
4003
+ if (resource.shippingAddressIds === void 0) {
4004
+ resource.shippingAddressIds = [];
4005
+ }
4006
+ if (!resource.shippingAddressIds.includes(address.id)) {
4007
+ resource.shippingAddressIds.push(address.id);
4008
+ }
4009
+ return resource;
4010
+ }
4011
+ addStore(context, resource, action) {
4012
+ throw new Error("Method not implemented.");
4013
+ }
4014
+ changeAddress(context, resource, { addressId, addressKey, address }) {
4015
+ const current = this._findAddress(resource, addressId, addressKey, true);
4016
+ assert3(current?.id);
4017
+ const oldAddressIndex = resource.addresses.findIndex(
4018
+ (a) => a.id === current.id
4019
+ );
4020
+ const newAddress = createAddress(
4021
+ address,
4022
+ context.projectKey,
4023
+ this._storage
4024
+ );
4025
+ if (newAddress) {
4026
+ resource.addresses[oldAddressIndex] = {
4027
+ id: addressId,
4028
+ ...newAddress
4029
+ };
4030
+ }
4031
+ }
4032
+ changeEmail(_context, resource, { email }) {
4033
+ resource.email = email;
4034
+ }
4035
+ removeAddress(context, resource, action) {
4036
+ const address = this._findAddress(
4037
+ resource,
4038
+ action.addressId,
4039
+ action.addressKey,
4040
+ true
4041
+ );
4042
+ assert3(address?.id);
4043
+ resource.addresses = resource.addresses.filter((a) => a.id !== address.id);
4044
+ }
4045
+ removeBillingAddressId(context, resource, action) {
4046
+ const address = this._findAddress(
4047
+ resource,
4048
+ action.addressId,
4049
+ action.addressKey,
4050
+ true
4051
+ );
4052
+ assert3(address?.id);
4053
+ resource.billingAddressIds = resource.billingAddressIds?.filter(
4054
+ (id) => id !== address.id
4055
+ );
4056
+ if (resource.defaultBillingAddressId === address.id) {
4057
+ resource.defaultBillingAddressId = void 0;
4058
+ }
4059
+ }
4060
+ removeShippingAddressId(context, resource, action) {
4061
+ const address = this._findAddress(
4062
+ resource,
4063
+ action.addressId,
4064
+ action.addressKey,
4065
+ true
4066
+ );
4067
+ assert3(address?.id);
4068
+ resource.shippingAddressIds = resource.shippingAddressIds?.filter(
4069
+ (id) => id !== address.id
4070
+ );
4071
+ if (resource.defaultShippingAddressId === address.id) {
4072
+ resource.defaultShippingAddressId = void 0;
4073
+ }
4038
4074
  }
4039
- };
4040
-
4041
- // src/repositories/customer-group.ts
4042
- var CustomerGroupRepository = class extends AbstractResourceRepository {
4043
- constructor(storage) {
4044
- super("customer-group", storage);
4045
- this.actions = new CustomerGroupUpdateHandler(storage);
4075
+ removeStore(context, resource, action) {
4076
+ throw new Error("Method not implemented.");
4046
4077
  }
4047
- create(context, draft) {
4048
- const resource = {
4049
- ...getBaseResourceProperties(),
4050
- key: draft.key,
4051
- name: draft.groupName,
4052
- custom: createCustomFields(
4053
- draft.custom,
4054
- context.projectKey,
4055
- this._storage
4056
- )
4057
- };
4058
- return this.saveNew(context, resource);
4078
+ setAddressCustomField(context, resource, action) {
4079
+ throw new Error("Method not implemented.");
4059
4080
  }
4060
- };
4061
- var CustomerGroupUpdateHandler = class extends AbstractUpdateHandler {
4062
- changeName(context, resource, { name }) {
4063
- resource.name = name;
4081
+ setAddressCustomType(context, resource, action) {
4082
+ throw new Error("Method not implemented.");
4064
4083
  }
4065
- setCustomField(context, resource, { name, value }) {
4066
- if (!resource.custom) {
4084
+ setAuthenticationMode(_context, resource, { authMode, password }) {
4085
+ if (resource.authenticationMode === authMode) {
4086
+ throw new CommercetoolsError(
4087
+ {
4088
+ code: "InvalidInput",
4089
+ message: `The customer is already using the '${resource.authenticationMode}' authentication mode.`
4090
+ },
4091
+ 400
4092
+ );
4093
+ }
4094
+ resource.authenticationMode = authMode;
4095
+ if (authMode === "ExternalAuth") {
4096
+ delete resource.password;
4067
4097
  return;
4068
4098
  }
4069
- if (value === null) {
4070
- delete resource.custom.fields[name];
4071
- } else {
4072
- resource.custom.fields[name] = value;
4099
+ if (authMode === "Password") {
4100
+ resource.password = password ? hashPassword(password) : void 0;
4101
+ return;
4073
4102
  }
4103
+ throw new CommercetoolsError(
4104
+ {
4105
+ code: "InvalidJsonInput",
4106
+ message: "Request body does not contain valid JSON.",
4107
+ detailedErrorMessage: `actions -> authMode: Invalid enum value: '${authMode}'. Expected one of: 'Password','ExternalAuth'`
4108
+ },
4109
+ 400
4110
+ );
4074
4111
  }
4075
- setCustomType(context, resource, { type, fields }) {
4076
- if (type) {
4077
- resource.custom = createCustomFields(
4078
- { type, fields },
4079
- context.projectKey,
4080
- this._storage
4112
+ setCompanyName(_context, resource, { companyName }) {
4113
+ resource.companyName = companyName;
4114
+ }
4115
+ setCustomerGroup(context, resource, action) {
4116
+ if (!action.customerGroup) {
4117
+ throw new CommercetoolsError(
4118
+ {
4119
+ code: "InvalidOperation",
4120
+ message: "CustomerGroup is required."
4121
+ },
4122
+ 400
4081
4123
  );
4082
- } else {
4083
- resource.custom = void 0;
4084
4124
  }
4085
- }
4086
- setKey(context, resource, { key }) {
4087
- resource.key = key;
4088
- }
4089
- };
4090
-
4091
- // src/repositories/discount-code/actions.ts
4092
- var DiscountCodeUpdateHandler = class extends AbstractUpdateHandler {
4093
- changeCartDiscounts(context, resource, { cartDiscounts }) {
4094
- resource.cartDiscounts = cartDiscounts.map(
4095
- (obj) => ({
4096
- typeId: "cart-discount",
4097
- id: obj.id
4098
- })
4125
+ const group = this._storage.getByResourceIdentifier(
4126
+ context.projectKey,
4127
+ action.customerGroup
4099
4128
  );
4129
+ resource.customerGroup = {
4130
+ typeId: "customer-group",
4131
+ id: group.id
4132
+ };
4100
4133
  }
4101
- changeIsActive(context, resource, { isActive }) {
4102
- resource.isActive = isActive;
4103
- }
4104
- setCartPredicate(context, resource, { cartPredicate }) {
4105
- resource.cartPredicate = cartPredicate;
4134
+ setCustomerNumber(_context, resource, { customerNumber }) {
4135
+ if (resource.customerNumber) {
4136
+ throw new Error(
4137
+ "A Customer number already exists and cannot be set again."
4138
+ );
4139
+ }
4140
+ resource.customerNumber = customerNumber;
4106
4141
  }
4107
- setCustomField(context, resource, { name, value }) {
4142
+ setCustomField(_context, resource, { name, value }) {
4108
4143
  if (!resource.custom) {
4109
- return;
4110
- }
4111
- if (value === null) {
4112
- delete resource.custom.fields[name];
4113
- } else {
4114
- resource.custom.fields[name] = value;
4144
+ throw new Error("Resource has no custom field");
4115
4145
  }
4146
+ resource.custom.fields[name] = value;
4116
4147
  }
4117
4148
  setCustomType(context, resource, { type, fields }) {
4118
4149
  if (type) {
@@ -4125,232 +4156,238 @@ var DiscountCodeUpdateHandler = class extends AbstractUpdateHandler {
4125
4156
  resource.custom = void 0;
4126
4157
  }
4127
4158
  }
4128
- setDescription(context, resource, { description }) {
4129
- resource.description = description;
4130
- }
4131
- setMaxApplications(context, resource, { maxApplications }) {
4132
- resource.maxApplications = maxApplications;
4133
- }
4134
- setMaxApplicationsPerCustomer(context, resource, {
4135
- maxApplicationsPerCustomer
4136
- }) {
4137
- resource.maxApplicationsPerCustomer = maxApplicationsPerCustomer;
4138
- }
4139
- setName(context, resource, { name }) {
4140
- resource.name = name;
4141
- }
4142
- setValidFrom(context, resource, { validFrom }) {
4143
- resource.validFrom = validFrom;
4144
- }
4145
- setValidFromAndUntil(context, resource, { validFrom, validUntil }) {
4146
- resource.validFrom = validFrom;
4147
- resource.validUntil = validUntil;
4148
- }
4149
- setValidUntil(context, resource, { validUntil }) {
4150
- resource.validUntil = validUntil;
4151
- }
4152
- };
4153
-
4154
- // src/repositories/discount-code/index.ts
4155
- var DiscountCodeRepository = class extends AbstractResourceRepository {
4156
- constructor(storage) {
4157
- super("discount-code", storage);
4158
- this.actions = new DiscountCodeUpdateHandler(storage);
4159
- }
4160
- create(context, draft) {
4161
- const resource = {
4162
- ...getBaseResourceProperties(),
4163
- applicationVersion: 1,
4164
- cartDiscounts: draft.cartDiscounts.map(
4165
- (obj) => ({
4166
- typeId: "cart-discount",
4167
- id: obj.id
4168
- })
4169
- ),
4170
- cartPredicate: draft.cartPredicate,
4171
- code: draft.code,
4172
- description: draft.description,
4173
- groups: draft.groups || [],
4174
- isActive: draft.isActive || true,
4175
- name: draft.name,
4176
- references: [],
4177
- validFrom: draft.validFrom,
4178
- validUntil: draft.validUntil,
4179
- maxApplications: draft.maxApplications,
4180
- maxApplicationsPerCustomer: draft.maxApplicationsPerCustomer,
4181
- custom: createCustomFields(
4182
- draft.custom,
4183
- context.projectKey,
4184
- this._storage
4185
- )
4186
- };
4187
- return this.saveNew(context, resource);
4159
+ setDateOfBirth(context, resource, action) {
4160
+ resource.dateOfBirth = action.dateOfBirth;
4188
4161
  }
4189
- };
4190
-
4191
- // src/lib/masking.ts
4192
- var maskSecretValue = (resource, path) => {
4193
- const parts = path.split(".");
4194
- const clone = cloneObject(resource);
4195
- let val = clone;
4196
- const target = parts.pop();
4197
- for (let i = 0; i < parts.length; i++) {
4198
- const part = parts[i];
4199
- val = val[part];
4200
- if (val === void 0) {
4201
- return resource;
4162
+ setDefaultBillingAddress(context, resource, action) {
4163
+ const address = this._findAddress(
4164
+ resource,
4165
+ action.addressId,
4166
+ action.addressKey,
4167
+ true
4168
+ );
4169
+ assert3(address?.id);
4170
+ resource.defaultBillingAddressId = address.id;
4171
+ if (resource.billingAddressIds === void 0) {
4172
+ resource.billingAddressIds = [];
4173
+ }
4174
+ if (!resource.billingAddressIds.includes(address.id)) {
4175
+ resource.billingAddressIds.push(address.id);
4202
4176
  }
4203
4177
  }
4204
- if (val && target && val[target]) {
4205
- val[target] = "****";
4206
- }
4207
- return clone;
4208
- };
4209
-
4210
- // src/repositories/extension.ts
4211
- var ExtensionRepository = class extends AbstractResourceRepository {
4212
- constructor(storage) {
4213
- super("extension", storage);
4214
- this.actions = new ExtensionUpdateHandler(storage);
4215
- }
4216
- create(context, draft) {
4217
- const resource = {
4218
- ...getBaseResourceProperties(),
4219
- key: draft.key,
4220
- timeoutInMs: draft.timeoutInMs,
4221
- destination: draft.destination,
4222
- triggers: draft.triggers
4223
- };
4224
- return this.saveNew(context, resource);
4225
- }
4226
- postProcessResource(context, resource) {
4227
- if (resource) {
4228
- const extension = resource;
4229
- if (extension.destination.type === "HTTP" && extension.destination.authentication?.type === "AuthorizationHeader") {
4230
- return maskSecretValue(
4231
- extension,
4232
- "destination.authentication.headerValue"
4233
- );
4234
- } else if (extension.destination.type === "AWSLambda") {
4235
- return maskSecretValue(resource, "destination.accessSecret");
4236
- }
4178
+ setDefaultShippingAddress(context, resource, action) {
4179
+ const address = this._findAddress(
4180
+ resource,
4181
+ action.addressId,
4182
+ action.addressKey,
4183
+ true
4184
+ );
4185
+ assert3(address?.id);
4186
+ resource.defaultShippingAddressId = address.id;
4187
+ if (resource.shippingAddressIds === void 0) {
4188
+ resource.shippingAddressIds = [];
4189
+ }
4190
+ if (!resource.shippingAddressIds.includes(address.id)) {
4191
+ resource.shippingAddressIds.push(address.id);
4237
4192
  }
4238
- return resource;
4239
4193
  }
4240
- };
4241
- var ExtensionUpdateHandler = class extends AbstractUpdateHandler {
4242
- changeDestination(context, resource, action) {
4243
- resource.destination = action.destination;
4194
+ setExternalId(_context, resource, { externalId }) {
4195
+ resource.externalId = externalId;
4244
4196
  }
4245
- changeTriggers(context, resource, action) {
4246
- resource.triggers = action.triggers;
4197
+ setFirstName(_context, resource, { firstName }) {
4198
+ resource.firstName = firstName;
4247
4199
  }
4248
- setKey(context, resource, action) {
4249
- resource.key = action.key;
4200
+ setKey(_context, resource, { key }) {
4201
+ resource.key = key;
4250
4202
  }
4251
- setTimeoutInMs(context, resource, action) {
4252
- resource.timeoutInMs = action.timeoutInMs;
4203
+ setLastName(_context, resource, { lastName }) {
4204
+ resource.lastName = lastName;
4253
4205
  }
4254
- };
4255
-
4256
- // src/repositories/inventory-entry/actions.ts
4257
- var InventoryEntryUpdateHandler = class extends AbstractUpdateHandler {
4258
- changeQuantity(context, resource, { quantity }) {
4259
- resource.quantityOnStock = quantity;
4260
- resource.availableQuantity = quantity;
4206
+ setLocale(_context, resource, { locale }) {
4207
+ resource.locale = locale;
4261
4208
  }
4262
- setCustomField(context, resource, { name, value }) {
4263
- if (!resource.custom) {
4264
- throw new Error("Resource has no custom field");
4265
- }
4266
- resource.custom.fields[name] = value;
4209
+ setMiddleName(context, resource, action) {
4210
+ resource.middleName = action.middleName;
4267
4211
  }
4268
- setCustomType(context, resource, { type, fields }) {
4269
- if (!type) {
4270
- resource.custom = void 0;
4271
- } else {
4272
- const resolvedType = this._storage.getByResourceIdentifier(
4273
- context.projectKey,
4274
- type
4275
- );
4276
- if (!resolvedType) {
4277
- throw new Error(`Type ${type} not found`);
4212
+ setSalutation(_context, resource, { salutation }) {
4213
+ resource.salutation = salutation;
4214
+ }
4215
+ setStores(context, resource, action) {
4216
+ throw new Error("Method not implemented.");
4217
+ }
4218
+ setTitle(context, resource, action) {
4219
+ resource.title = action.title;
4220
+ }
4221
+ setVatId(_context, resource, { vatId }) {
4222
+ resource.vatId = vatId;
4223
+ }
4224
+ _findAddress(resource, addressId, addressKey, required = false) {
4225
+ if (addressKey) {
4226
+ const address = resource.addresses.find((a) => a.key === addressKey);
4227
+ if (!address) {
4228
+ throw new CommercetoolsError(
4229
+ {
4230
+ code: "InvalidOperation",
4231
+ message: `Customer does not contain an address with the key ${addressKey}.`
4232
+ },
4233
+ 400
4234
+ );
4278
4235
  }
4279
- resource.custom = {
4280
- type: {
4281
- typeId: "type",
4282
- id: resolvedType.id
4236
+ return address;
4237
+ }
4238
+ if (addressId) {
4239
+ const address = resource.addresses.find((a) => a.id === addressId);
4240
+ if (!address) {
4241
+ throw new CommercetoolsError(
4242
+ {
4243
+ code: "InvalidOperation",
4244
+ message: `Customer does not contain an address with the id ${addressId}.`
4245
+ },
4246
+ 400
4247
+ );
4248
+ }
4249
+ return address;
4250
+ }
4251
+ if (required) {
4252
+ throw new CommercetoolsError(
4253
+ {
4254
+ code: "InvalidOperation",
4255
+ message: "One of address 'addressId' or 'addressKey' is required."
4283
4256
  },
4284
- fields: fields || {}
4285
- };
4257
+ 400
4258
+ );
4286
4259
  }
4287
4260
  }
4288
- setExpectedDelivery(context, resource, { expectedDelivery }) {
4289
- resource.expectedDelivery = new Date(expectedDelivery).toISOString();
4290
- }
4291
- setRestockableInDays(context, resource, { restockableInDays }) {
4292
- resource.restockableInDays = restockableInDays;
4293
- }
4294
4261
  };
4295
4262
 
4296
- // src/repositories/inventory-entry/index.ts
4297
- var InventoryEntryRepository = class extends AbstractResourceRepository {
4263
+ // src/repositories/customer/index.ts
4264
+ var CustomerRepository = class extends AbstractResourceRepository {
4298
4265
  constructor(storage) {
4299
- super("inventory-entry", storage);
4300
- this.actions = new InventoryEntryUpdateHandler(storage);
4266
+ super("customer", storage);
4267
+ this.actions = new CustomerUpdateHandler(storage);
4301
4268
  }
4302
4269
  create(context, draft) {
4270
+ const results = this._storage.query(context.projectKey, this.getTypeId(), {
4271
+ where: [`lowercaseEmail="${draft.email.toLowerCase()}"`]
4272
+ });
4273
+ if (results.count > 0) {
4274
+ throw new CommercetoolsError({
4275
+ code: "CustomerAlreadyExists",
4276
+ statusCode: 400,
4277
+ message: "There is already an existing customer with the provided email.",
4278
+ errors: [
4279
+ {
4280
+ code: "DuplicateField",
4281
+ message: `Customer with email '${draft.email}' already exists.`,
4282
+ duplicateValue: draft.email,
4283
+ field: "email"
4284
+ }
4285
+ ]
4286
+ });
4287
+ }
4288
+ const addresses = draft.addresses?.map((address) => ({
4289
+ ...address,
4290
+ id: generateRandomString(5)
4291
+ })) ?? [];
4292
+ const lookupAdressId = (addresses2, addressId) => {
4293
+ if (addressId < addresses2.length) {
4294
+ const id = addresses2[addressId].id;
4295
+ if (!id) {
4296
+ throw new Error("Address ID is missing");
4297
+ }
4298
+ return id;
4299
+ }
4300
+ throw new CommercetoolsError({
4301
+ code: "InvalidInput",
4302
+ message: `Address with ID '${addressId}' not found.`,
4303
+ errors: [
4304
+ {
4305
+ code: "InvalidInput",
4306
+ message: `Address with ID '${addressId}' not found.`,
4307
+ field: "addressId"
4308
+ }
4309
+ ]
4310
+ });
4311
+ };
4312
+ const defaultBillingAddressId = draft.defaultBillingAddress !== void 0 ? lookupAdressId(addresses, draft.defaultBillingAddress) : void 0;
4313
+ const defaultShippingAddressId = draft.defaultShippingAddress !== void 0 ? lookupAdressId(addresses, draft.defaultShippingAddress) : void 0;
4314
+ const shippingAddressIds = draft.shippingAddresses?.map(
4315
+ (addressId) => lookupAdressId(addresses, addressId)
4316
+ ) ?? [];
4317
+ const billingAddressIds = draft.billingAddresses?.map(
4318
+ (addressId) => lookupAdressId(addresses, addressId)
4319
+ ) ?? [];
4320
+ let storesForCustomer = [];
4321
+ if (draft.stores && draft.stores.length > 0) {
4322
+ storesForCustomer = this.storeReferenceToStoreKeyReference(
4323
+ draft.stores,
4324
+ context.projectKey
4325
+ );
4326
+ }
4303
4327
  const resource = {
4304
4328
  ...getBaseResourceProperties(),
4305
- sku: draft.sku,
4306
- quantityOnStock: draft.quantityOnStock,
4307
- availableQuantity: draft.quantityOnStock,
4308
- expectedDelivery: draft.expectedDelivery,
4309
- restockableInDays: draft.restockableInDays,
4310
- supplyChannel: {
4311
- ...draft.supplyChannel,
4312
- typeId: "channel",
4313
- id: draft.supplyChannel?.id ?? ""
4314
- },
4329
+ key: draft.key,
4330
+ authenticationMode: draft.authenticationMode || "Password",
4331
+ firstName: draft.firstName,
4332
+ lastName: draft.lastName,
4333
+ middleName: draft.middleName,
4334
+ title: draft.title,
4335
+ dateOfBirth: draft.dateOfBirth,
4336
+ companyName: draft.companyName,
4337
+ email: draft.email.toLowerCase(),
4338
+ lowercaseEmail: draft.email.toLowerCase(),
4339
+ password: draft.password ? hashPassword(draft.password) : void 0,
4340
+ isEmailVerified: draft.isEmailVerified || false,
4341
+ addresses,
4342
+ customerNumber: draft.customerNumber,
4343
+ externalId: draft.externalId,
4344
+ defaultBillingAddressId,
4345
+ defaultShippingAddressId,
4346
+ shippingAddressIds,
4347
+ billingAddressIds,
4315
4348
  custom: createCustomFields(
4316
4349
  draft.custom,
4317
4350
  context.projectKey,
4318
4351
  this._storage
4319
- )
4352
+ ),
4353
+ stores: storesForCustomer
4320
4354
  };
4321
4355
  return this.saveNew(context, resource);
4322
4356
  }
4323
- };
4324
-
4325
- // src/repositories/my-customer.ts
4326
- var MyCustomerRepository = class extends CustomerRepository {
4327
- changePassword(context, changePassword) {
4328
- const { currentPassword, newPassword } = changePassword;
4329
- const encodedPassword = hashPassword(currentPassword);
4330
- const result = this._storage.query(context.projectKey, "customer", {
4331
- where: [`password = "${encodedPassword}"`]
4357
+ saveUpdate(context, version, resource) {
4358
+ const updatedResource = {
4359
+ ...resource,
4360
+ lowercaseEmail: resource.email.toLowerCase()
4361
+ };
4362
+ return super.saveUpdate(context, version, updatedResource);
4363
+ }
4364
+ passwordResetToken(context, request) {
4365
+ const results = this._storage.query(context.projectKey, this.getTypeId(), {
4366
+ where: [`email="${request.email.toLocaleLowerCase()}"`]
4332
4367
  });
4333
- if (result.count === 0) {
4334
- throw new CommercetoolsError({
4335
- code: "InvalidCurrentPassword",
4336
- message: "Account with the given credentials not found."
4337
- });
4338
- }
4339
- const customer = result.results[0];
4340
- if (customer.password !== hashPassword(currentPassword)) {
4368
+ if (results.count === 0) {
4341
4369
  throw new CommercetoolsError({
4342
- code: "InvalidCurrentPassword",
4343
- message: "The current password is invalid."
4370
+ code: "ResourceNotFound",
4371
+ message: `The Customer with ID '${request.email}' was not found.`
4344
4372
  });
4345
4373
  }
4346
- customer.password = hashPassword(newPassword);
4347
- customer.version += 1;
4348
- this._storage.add(context.projectKey, "customer", customer);
4349
- return customer;
4350
- }
4351
- confirmEmail(context, resetPassword) {
4352
- const { tokenValue } = resetPassword;
4353
- const customerId = validateEmailVerifyToken(tokenValue);
4374
+ const ttlMinutes = request.ttlMinutes ?? 34560;
4375
+ const expiresAt = new Date((/* @__PURE__ */ new Date()).getTime() + ttlMinutes * 60 * 1e3);
4376
+ const customer = results.results[0];
4377
+ const rest = getBaseResourceProperties();
4378
+ const token = createPasswordResetToken(customer, expiresAt);
4379
+ return {
4380
+ id: rest.id,
4381
+ createdAt: rest.createdAt,
4382
+ lastModifiedAt: rest.lastModifiedAt,
4383
+ customerId: customer.id,
4384
+ expiresAt: expiresAt.toISOString(),
4385
+ value: token
4386
+ };
4387
+ }
4388
+ passwordReset(context, resetPassword) {
4389
+ const { newPassword, tokenValue } = resetPassword;
4390
+ const customerId = validatePasswordResetToken(tokenValue);
4354
4391
  if (!customerId) {
4355
4392
  throw new CommercetoolsError({
4356
4393
  code: "ResourceNotFound",
@@ -4368,440 +4405,416 @@ var MyCustomerRepository = class extends CustomerRepository {
4368
4405
  message: `The Customer with ID 'Token(${tokenValue})' was not found.`
4369
4406
  });
4370
4407
  }
4371
- customer.isEmailVerified = true;
4408
+ customer.password = hashPassword(newPassword);
4372
4409
  customer.version += 1;
4373
4410
  this._storage.add(context.projectKey, "customer", customer);
4374
4411
  return customer;
4375
4412
  }
4376
- deleteMe(context) {
4377
- const results = this._storage.query(
4378
- context.projectKey,
4379
- this.getTypeId(),
4380
- {}
4381
- );
4382
- if (results.count > 0) {
4383
- return this.delete(context, results.results[0].id);
4413
+ verifyEmailToken(context, id) {
4414
+ const results = this._storage.query(context.projectKey, this.getTypeId(), {
4415
+ where: [`id="${id.toLocaleLowerCase()}"`]
4416
+ });
4417
+ if (results.count === 0) {
4418
+ throw new CommercetoolsError({
4419
+ code: "ResourceNotFound",
4420
+ message: `The Customer with ID '${id}' was not found.`
4421
+ });
4384
4422
  }
4385
- return;
4423
+ const expiresAt = new Date(Date.now() + 30 * 60);
4424
+ const customer = results.results[0];
4425
+ const rest = getBaseResourceProperties();
4426
+ const token = createEmailVerifyToken(customer);
4427
+ return {
4428
+ id: rest.id,
4429
+ createdAt: rest.createdAt,
4430
+ lastModifiedAt: rest.lastModifiedAt,
4431
+ customerId: customer.id,
4432
+ expiresAt: expiresAt.toISOString(),
4433
+ value: token
4434
+ };
4386
4435
  }
4387
- getMe(context) {
4388
- const results = this._storage.query(
4389
- context.projectKey,
4390
- this.getTypeId(),
4391
- {}
4392
- );
4393
- if (results.count > 0) {
4394
- return results.results[0];
4436
+ storeReferenceToStoreKeyReference(draftStores, projectKey) {
4437
+ const storeIds = draftStores.map((storeReference) => storeReference.id).filter(Boolean);
4438
+ let stores = [];
4439
+ if (storeIds.length > 0) {
4440
+ stores = this._storage.query(projectKey, "store", {
4441
+ where: storeIds.map((id) => `id="${id}"`)
4442
+ }).results;
4443
+ if (storeIds.length !== stores.length) {
4444
+ throw new CommercetoolsError({
4445
+ code: "ResourceNotFound",
4446
+ message: `Store with ID '${storeIds.find((id) => !stores.some((store) => store.id === id))}' was not found.`
4447
+ });
4448
+ }
4395
4449
  }
4396
- return;
4450
+ return draftStores.map((storeReference) => ({
4451
+ typeId: "store",
4452
+ key: storeReference.key ?? stores.find((store) => store.id === storeReference.id)?.key
4453
+ }));
4397
4454
  }
4398
4455
  };
4399
4456
 
4400
- // src/repositories/my-order.ts
4401
- import assert4 from "assert";
4402
-
4403
- // src/repositories/order/index.ts
4404
- import assert3 from "assert";
4405
-
4406
- // src/repositories/order/actions.ts
4407
- var OrderUpdateHandler = class extends AbstractUpdateHandler {
4408
- addPayment(context, resource, { payment }) {
4409
- const resolvedPayment = this._storage.getByResourceIdentifier(
4410
- context.projectKey,
4411
- payment
4412
- );
4413
- if (!resolvedPayment) {
4414
- throw new Error(`Payment ${payment.id} not found`);
4415
- }
4416
- if (!resource.paymentInfo) {
4417
- resource.paymentInfo = {
4418
- payments: []
4419
- };
4420
- }
4421
- resource.paymentInfo.payments.push({
4422
- typeId: "payment",
4423
- id: payment.id
4424
- });
4457
+ // src/repositories/customer-group.ts
4458
+ var CustomerGroupRepository = class extends AbstractResourceRepository {
4459
+ constructor(storage) {
4460
+ super("customer-group", storage);
4461
+ this.actions = new CustomerGroupUpdateHandler(storage);
4425
4462
  }
4426
- addReturnInfo(context, resource, info) {
4427
- if (!resource.returnInfo) {
4428
- resource.returnInfo = [];
4429
- }
4430
- const resolved = {
4431
- items: info.items.map((item) => {
4432
- const common = {
4433
- ...getBaseResourceProperties(),
4434
- quantity: item.quantity,
4435
- paymentState: "Initial",
4436
- shipmentState: "Initial",
4437
- comment: item.comment
4438
- };
4439
- if (item.customLineItemId) {
4440
- return {
4441
- ...common,
4442
- type: "CustomLineItemReturnItem",
4443
- customLineItemId: item.customLineItemId
4444
- };
4445
- }
4446
- return {
4447
- ...common,
4448
- type: "LineItemReturnItem",
4449
- lineItemId: item.customLineItemId || item.lineItemId
4450
- };
4451
- }),
4452
- returnTrackingId: info.returnTrackingId,
4453
- returnDate: info.returnDate
4463
+ create(context, draft) {
4464
+ const resource = {
4465
+ ...getBaseResourceProperties(),
4466
+ key: draft.key,
4467
+ name: draft.groupName,
4468
+ custom: createCustomFields(
4469
+ draft.custom,
4470
+ context.projectKey,
4471
+ this._storage
4472
+ )
4454
4473
  };
4455
- resource.returnInfo.push(resolved);
4456
- }
4457
- changeOrderState(context, resource, { orderState }) {
4458
- resource.orderState = orderState;
4459
- }
4460
- changePaymentState(context, resource, { paymentState }) {
4461
- resource.paymentState = paymentState;
4462
- }
4463
- changeShipmentState(context, resource, { shipmentState }) {
4464
- resource.shipmentState = shipmentState;
4465
- }
4466
- setBillingAddress(context, resource, { address }) {
4467
- resource.billingAddress = createAddress(
4468
- address,
4469
- context.projectKey,
4470
- this._storage
4471
- );
4472
- }
4473
- setCustomerEmail(context, resource, { email }) {
4474
- resource.customerEmail = email;
4474
+ return this.saveNew(context, resource);
4475
4475
  }
4476
- setCustomerId(context, resource, { customerId }) {
4477
- resource.customerId = customerId;
4476
+ };
4477
+ var CustomerGroupUpdateHandler = class extends AbstractUpdateHandler {
4478
+ changeName(context, resource, { name }) {
4479
+ resource.name = name;
4478
4480
  }
4479
4481
  setCustomField(context, resource, { name, value }) {
4480
4482
  if (!resource.custom) {
4481
- throw new Error("Resource has no custom field");
4483
+ return;
4484
+ }
4485
+ if (value === null) {
4486
+ delete resource.custom.fields[name];
4487
+ } else {
4488
+ resource.custom.fields[name] = value;
4482
4489
  }
4483
- resource.custom.fields[name] = value;
4484
4490
  }
4485
4491
  setCustomType(context, resource, { type, fields }) {
4486
- if (!type) {
4487
- resource.custom = void 0;
4488
- } else {
4489
- const resolvedType = this._storage.getByResourceIdentifier(
4492
+ if (type) {
4493
+ resource.custom = createCustomFields(
4494
+ { type, fields },
4490
4495
  context.projectKey,
4491
- type
4496
+ this._storage
4492
4497
  );
4493
- if (!resolvedType) {
4494
- throw new Error(`Type ${type} not found`);
4495
- }
4496
- resource.custom = {
4497
- type: {
4498
- typeId: "type",
4499
- id: resolvedType.id
4500
- },
4501
- fields: fields || {}
4502
- };
4503
- }
4504
- }
4505
- setDeliveryCustomField(context, resource, { deliveryId, name, value }) {
4506
- if (!resource.shippingInfo) {
4507
- throw new Error("Resource has no shipping info");
4508
- }
4509
- for (const delivery of resource.shippingInfo.deliveries || []) {
4510
- if (delivery.id === deliveryId && delivery.custom?.fields) {
4511
- delivery.custom.fields[name] = value;
4512
- }
4513
- }
4514
- }
4515
- setLocale(context, resource, { locale }) {
4516
- resource.locale = locale;
4517
- }
4518
- setOrderNumber(context, resource, { orderNumber }) {
4519
- resource.orderNumber = orderNumber;
4520
- }
4521
- setParcelCustomField(context, resource, { parcelId, name, value }) {
4522
- if (!resource.shippingInfo) {
4523
- throw new Error("Resource has no shipping info");
4524
- }
4525
- for (const delivery of resource.shippingInfo.deliveries || []) {
4526
- for (const parcel of delivery.parcels || []) {
4527
- if (parcel.id === parcelId && parcel.custom?.fields) {
4528
- parcel.custom.fields[name] = value;
4529
- }
4530
- }
4531
- }
4532
- }
4533
- setPurchaseOrderNumber(context, resource, { purchaseOrderNumber }) {
4534
- resource.purchaseOrderNumber = purchaseOrderNumber;
4535
- }
4536
- setShippingAddress(context, resource, { address }) {
4537
- resource.shippingAddress = createAddress(
4538
- address,
4539
- context.projectKey,
4540
- this._storage
4541
- );
4542
- }
4543
- setStore(context, resource, { store }) {
4544
- if (!store) return;
4545
- const resolvedType = this._storage.getByResourceIdentifier(
4546
- context.projectKey,
4547
- store
4548
- );
4549
- if (!resolvedType) {
4550
- throw new Error(`No store found with key=${store.key}`);
4498
+ } else {
4499
+ resource.custom = void 0;
4551
4500
  }
4552
- const storeReference = resolvedType;
4553
- resource.store = {
4554
- typeId: "store",
4555
- key: storeReference.key
4556
- };
4557
4501
  }
4558
- transitionState(context, resource, { state }) {
4559
- const resolvedType = this._storage.getByResourceIdentifier(
4560
- context.projectKey,
4561
- state
4562
- );
4563
- if (!resolvedType) {
4564
- throw new Error(
4565
- `No state found with key=${state.key} or id=${state.key}`
4566
- );
4567
- }
4568
- resource.state = {
4569
- typeId: "state",
4570
- id: resolvedType.id,
4571
- obj: { ...resolvedType, key: state.key ?? "" }
4572
- };
4502
+ setKey(context, resource, { key }) {
4503
+ resource.key = key;
4573
4504
  }
4574
- updateSyncInfo(context, resource, { channel, externalId, syncedAt }) {
4575
- if (!channel) return;
4576
- const resolvedType = this._storage.getByResourceIdentifier(
4577
- context.projectKey,
4578
- channel
4505
+ };
4506
+
4507
+ // src/repositories/discount-code/actions.ts
4508
+ var DiscountCodeUpdateHandler = class extends AbstractUpdateHandler {
4509
+ changeCartDiscounts(context, resource, { cartDiscounts }) {
4510
+ resource.cartDiscounts = cartDiscounts.map(
4511
+ (obj) => ({
4512
+ typeId: "cart-discount",
4513
+ id: obj.id
4514
+ })
4579
4515
  );
4580
- if (!resolvedType) {
4581
- throw new Error(`Channel ${channel} not found`);
4516
+ }
4517
+ changeIsActive(context, resource, { isActive }) {
4518
+ resource.isActive = isActive;
4519
+ }
4520
+ setCartPredicate(context, resource, { cartPredicate }) {
4521
+ resource.cartPredicate = cartPredicate;
4522
+ }
4523
+ setCustomField(context, resource, { name, value }) {
4524
+ if (!resource.custom) {
4525
+ return;
4582
4526
  }
4583
- const syncData = {
4584
- channel: {
4585
- typeId: "channel",
4586
- id: resolvedType.id
4587
- },
4588
- externalId,
4589
- syncedAt: syncedAt ?? (/* @__PURE__ */ new Date()).toISOString()
4590
- };
4591
- if (!resource.syncInfo?.length) {
4592
- resource.syncInfo = [syncData];
4527
+ if (value === null) {
4528
+ delete resource.custom.fields[name];
4593
4529
  } else {
4594
- const lastSyncInfo = resource.syncInfo[resource.syncInfo.length - 1];
4595
- if (lastSyncInfo.channel.id !== syncData.channel.id || lastSyncInfo.externalId !== syncData.externalId) {
4596
- resource.syncInfo.push(syncData);
4597
- }
4530
+ resource.custom.fields[name] = value;
4531
+ }
4532
+ }
4533
+ setCustomType(context, resource, { type, fields }) {
4534
+ if (type) {
4535
+ resource.custom = createCustomFields(
4536
+ { type, fields },
4537
+ context.projectKey,
4538
+ this._storage
4539
+ );
4540
+ } else {
4541
+ resource.custom = void 0;
4598
4542
  }
4599
4543
  }
4544
+ setDescription(context, resource, { description }) {
4545
+ resource.description = description;
4546
+ }
4547
+ setMaxApplications(context, resource, { maxApplications }) {
4548
+ resource.maxApplications = maxApplications;
4549
+ }
4550
+ setMaxApplicationsPerCustomer(context, resource, {
4551
+ maxApplicationsPerCustomer
4552
+ }) {
4553
+ resource.maxApplicationsPerCustomer = maxApplicationsPerCustomer;
4554
+ }
4555
+ setName(context, resource, { name }) {
4556
+ resource.name = name;
4557
+ }
4558
+ setValidFrom(context, resource, { validFrom }) {
4559
+ resource.validFrom = validFrom;
4560
+ }
4561
+ setValidFromAndUntil(context, resource, { validFrom, validUntil }) {
4562
+ resource.validFrom = validFrom;
4563
+ resource.validUntil = validUntil;
4564
+ }
4565
+ setValidUntil(context, resource, { validUntil }) {
4566
+ resource.validUntil = validUntil;
4567
+ }
4600
4568
  };
4601
4569
 
4602
- // src/repositories/order/index.ts
4603
- var OrderRepository = class extends AbstractResourceRepository {
4570
+ // src/repositories/discount-code/index.ts
4571
+ var DiscountCodeRepository = class extends AbstractResourceRepository {
4604
4572
  constructor(storage) {
4605
- super("order", storage);
4606
- this.actions = new OrderUpdateHandler(storage);
4573
+ super("discount-code", storage);
4574
+ this.actions = new DiscountCodeUpdateHandler(storage);
4607
4575
  }
4608
4576
  create(context, draft) {
4609
- assert3(draft.cart, "draft.cart is missing");
4610
- return this.createFromCart(
4611
- context,
4612
- {
4613
- id: draft.cart.id,
4614
- typeId: "cart"
4615
- },
4616
- draft.orderNumber
4617
- );
4618
- }
4619
- createFromCart(context, cartReference, orderNumber) {
4620
- const cart = this._storage.getByResourceIdentifier(
4621
- context.projectKey,
4622
- cartReference
4623
- );
4624
- if (!cart) {
4625
- throw new Error("Cannot find cart");
4626
- }
4627
- const resource = {
4628
- ...getBaseResourceProperties(),
4629
- anonymousId: cart.anonymousId,
4630
- billingAddress: cart.billingAddress,
4631
- cart: cartReference,
4632
- country: cart.country,
4633
- custom: cart.custom,
4634
- customerEmail: cart.customerEmail,
4635
- customerGroup: cart.customerGroup,
4636
- customerId: cart.customerId,
4637
- customLineItems: [],
4638
- directDiscounts: cart.directDiscounts,
4639
- discountCodes: cart.discountCodes,
4640
- discountOnTotalPrice: cart.discountOnTotalPrice,
4641
- lastMessageSequenceNumber: 0,
4642
- lineItems: cart.lineItems,
4643
- locale: cart.locale,
4644
- orderNumber: orderNumber ?? generateRandomString(10),
4645
- orderState: "Open",
4646
- origin: "Customer",
4647
- paymentInfo: cart.paymentInfo,
4648
- refusedGifts: [],
4649
- shipping: cart.shipping,
4650
- shippingAddress: cart.shippingAddress,
4651
- shippingMode: cart.shippingMode,
4652
- syncInfo: [],
4653
- taxCalculationMode: cart.taxCalculationMode,
4654
- taxedPrice: cart.taxedPrice,
4655
- taxedShippingPrice: cart.taxedShippingPrice,
4656
- taxMode: cart.taxMode,
4657
- taxRoundingMode: cart.taxRoundingMode,
4658
- totalPrice: cart.totalPrice,
4659
- store: cart.store
4660
- };
4661
- return this.saveNew(context, resource);
4662
- }
4663
- import(context, draft) {
4664
- assert3(this, "OrderRepository not valid");
4665
4577
  const resource = {
4666
4578
  ...getBaseResourceProperties(),
4667
- billingAddress: createAddress(
4668
- draft.billingAddress,
4669
- context.projectKey,
4670
- this._storage
4671
- ),
4672
- shippingAddress: createAddress(
4673
- draft.shippingAddress,
4674
- context.projectKey,
4675
- this._storage
4579
+ applicationVersion: 1,
4580
+ cartDiscounts: draft.cartDiscounts.map(
4581
+ (obj) => ({
4582
+ typeId: "cart-discount",
4583
+ id: obj.id
4584
+ })
4676
4585
  ),
4586
+ cartPredicate: draft.cartPredicate,
4587
+ code: draft.code,
4588
+ description: draft.description,
4589
+ groups: draft.groups || [],
4590
+ isActive: draft.isActive || true,
4591
+ name: draft.name,
4592
+ references: [],
4593
+ validFrom: draft.validFrom,
4594
+ validUntil: draft.validUntil,
4595
+ maxApplications: draft.maxApplications,
4596
+ maxApplicationsPerCustomer: draft.maxApplicationsPerCustomer,
4677
4597
  custom: createCustomFields(
4678
4598
  draft.custom,
4679
4599
  context.projectKey,
4680
4600
  this._storage
4681
- ),
4682
- customerEmail: draft.customerEmail,
4683
- lastMessageSequenceNumber: 0,
4684
- orderNumber: draft.orderNumber,
4685
- orderState: draft.orderState || "Open",
4686
- origin: draft.origin || "Customer",
4687
- paymentState: draft.paymentState,
4688
- refusedGifts: [],
4689
- shippingMode: "Single",
4690
- shipping: [],
4691
- store: resolveStoreReference(
4692
- draft.store,
4693
- context.projectKey,
4694
- this._storage
4695
- ),
4696
- syncInfo: [],
4697
- lineItems: draft.lineItems?.map(
4698
- (item) => this.lineItemFromImportDraft.bind(this)(context, item)
4699
- ) || [],
4700
- customLineItems: draft.customLineItems?.map(
4701
- (item) => this.customLineItemFromImportDraft.bind(this)(context, item)
4702
- ) || [],
4703
- totalPrice: createCentPrecisionMoney(draft.totalPrice)
4601
+ )
4704
4602
  };
4705
4603
  return this.saveNew(context, resource);
4706
4604
  }
4707
- lineItemFromImportDraft(context, draft) {
4708
- let product;
4709
- let variant;
4710
- if (draft.variant.sku) {
4711
- variant = {
4712
- id: 0,
4713
- sku: draft.variant.sku
4714
- };
4715
- const items = this._storage.query(context.projectKey, "product", {
4716
- where: [
4717
- `masterData(current(masterVariant(sku="${draft.variant.sku}"))) or masterData(current(variants(sku="${draft.variant.sku}")))`
4718
- ]
4719
- });
4720
- if (items.count !== 1) {
4721
- throw new CommercetoolsError({
4722
- code: "General",
4723
- message: `A product containing a variant with SKU '${draft.variant.sku}' not found.`
4724
- });
4725
- }
4726
- product = items.results[0];
4727
- if (product.masterData.current.masterVariant.sku === draft.variant.sku) {
4728
- variant = product.masterData.current.masterVariant;
4729
- } else {
4730
- variant = product.masterData.current.variants.find(
4731
- (v) => v.sku === draft.variant.sku
4605
+ };
4606
+
4607
+ // src/lib/masking.ts
4608
+ var maskSecretValue = (resource, path) => {
4609
+ const parts = path.split(".");
4610
+ const clone = cloneObject(resource);
4611
+ let val = clone;
4612
+ const target = parts.pop();
4613
+ for (let i = 0; i < parts.length; i++) {
4614
+ const part = parts[i];
4615
+ val = val[part];
4616
+ if (val === void 0) {
4617
+ return resource;
4618
+ }
4619
+ }
4620
+ if (val && target && val[target]) {
4621
+ val[target] = "****";
4622
+ }
4623
+ return clone;
4624
+ };
4625
+
4626
+ // src/repositories/extension.ts
4627
+ var ExtensionRepository = class extends AbstractResourceRepository {
4628
+ constructor(storage) {
4629
+ super("extension", storage);
4630
+ this.actions = new ExtensionUpdateHandler(storage);
4631
+ }
4632
+ create(context, draft) {
4633
+ const resource = {
4634
+ ...getBaseResourceProperties(),
4635
+ key: draft.key,
4636
+ timeoutInMs: draft.timeoutInMs,
4637
+ destination: draft.destination,
4638
+ triggers: draft.triggers
4639
+ };
4640
+ return this.saveNew(context, resource);
4641
+ }
4642
+ postProcessResource(context, resource) {
4643
+ if (resource) {
4644
+ const extension = resource;
4645
+ if (extension.destination.type === "HTTP" && extension.destination.authentication?.type === "AuthorizationHeader") {
4646
+ return maskSecretValue(
4647
+ extension,
4648
+ "destination.authentication.headerValue"
4732
4649
  );
4650
+ } else if (extension.destination.type === "AWSLambda") {
4651
+ return maskSecretValue(resource, "destination.accessSecret");
4733
4652
  }
4734
- if (!variant) {
4735
- throw new Error("Internal state error");
4736
- }
4737
- } else {
4738
- throw new Error("No product found");
4739
4653
  }
4740
- const lineItem = {
4741
- ...getBaseResourceProperties(),
4742
- custom: createCustomFields(
4743
- draft.custom,
4654
+ return resource;
4655
+ }
4656
+ };
4657
+ var ExtensionUpdateHandler = class extends AbstractUpdateHandler {
4658
+ changeDestination(context, resource, action) {
4659
+ resource.destination = action.destination;
4660
+ }
4661
+ changeTriggers(context, resource, action) {
4662
+ resource.triggers = action.triggers;
4663
+ }
4664
+ setKey(context, resource, action) {
4665
+ resource.key = action.key;
4666
+ }
4667
+ setTimeoutInMs(context, resource, action) {
4668
+ resource.timeoutInMs = action.timeoutInMs;
4669
+ }
4670
+ };
4671
+
4672
+ // src/repositories/inventory-entry/actions.ts
4673
+ var InventoryEntryUpdateHandler = class extends AbstractUpdateHandler {
4674
+ changeQuantity(context, resource, { quantity }) {
4675
+ resource.quantityOnStock = quantity;
4676
+ resource.availableQuantity = quantity;
4677
+ }
4678
+ setCustomField(context, resource, { name, value }) {
4679
+ if (!resource.custom) {
4680
+ throw new Error("Resource has no custom field");
4681
+ }
4682
+ resource.custom.fields[name] = value;
4683
+ }
4684
+ setCustomType(context, resource, { type, fields }) {
4685
+ if (!type) {
4686
+ resource.custom = void 0;
4687
+ } else {
4688
+ const resolvedType = this._storage.getByResourceIdentifier(
4744
4689
  context.projectKey,
4745
- this._storage
4746
- ),
4747
- discountedPricePerQuantity: [],
4748
- lineItemMode: "Standard",
4749
- name: draft.name,
4750
- price: createPrice(draft.price),
4751
- priceMode: "Platform",
4752
- productId: product.id,
4753
- productType: product.productType,
4754
- quantity: draft.quantity,
4755
- state: draft.state || [],
4756
- taxRate: draft.taxRate,
4757
- taxedPricePortions: [],
4758
- perMethodTaxRate: [],
4759
- totalPrice: createCentPrecisionMoney(draft.price.value),
4760
- variant: {
4761
- id: variant.id,
4762
- sku: variant.sku,
4763
- price: createPrice(draft.price)
4690
+ type
4691
+ );
4692
+ if (!resolvedType) {
4693
+ throw new Error(`Type ${type} not found`);
4764
4694
  }
4765
- };
4766
- return lineItem;
4695
+ resource.custom = {
4696
+ type: {
4697
+ typeId: "type",
4698
+ id: resolvedType.id
4699
+ },
4700
+ fields: fields || {}
4701
+ };
4702
+ }
4767
4703
  }
4768
- customLineItemFromImportDraft(context, draft) {
4769
- const lineItem = {
4704
+ setExpectedDelivery(context, resource, { expectedDelivery }) {
4705
+ resource.expectedDelivery = new Date(expectedDelivery).toISOString();
4706
+ }
4707
+ setRestockableInDays(context, resource, { restockableInDays }) {
4708
+ resource.restockableInDays = restockableInDays;
4709
+ }
4710
+ };
4711
+
4712
+ // src/repositories/inventory-entry/index.ts
4713
+ var InventoryEntryRepository = class extends AbstractResourceRepository {
4714
+ constructor(storage) {
4715
+ super("inventory-entry", storage);
4716
+ this.actions = new InventoryEntryUpdateHandler(storage);
4717
+ }
4718
+ create(context, draft) {
4719
+ const resource = {
4770
4720
  ...getBaseResourceProperties(),
4721
+ sku: draft.sku,
4722
+ quantityOnStock: draft.quantityOnStock,
4723
+ availableQuantity: draft.quantityOnStock,
4724
+ expectedDelivery: draft.expectedDelivery,
4725
+ restockableInDays: draft.restockableInDays,
4726
+ supplyChannel: {
4727
+ ...draft.supplyChannel,
4728
+ typeId: "channel",
4729
+ id: draft.supplyChannel?.id ?? ""
4730
+ },
4771
4731
  custom: createCustomFields(
4772
4732
  draft.custom,
4773
4733
  context.projectKey,
4774
4734
  this._storage
4775
- ),
4776
- discountedPricePerQuantity: [],
4777
- money: createTypedMoney(draft.money),
4778
- name: draft.name,
4779
- quantity: draft.quantity ?? 0,
4780
- perMethodTaxRate: [],
4781
- priceMode: draft.priceMode ?? "Standard",
4782
- slug: draft.slug,
4783
- state: [],
4784
- totalPrice: createCentPrecisionMoney(draft.money),
4785
- taxedPricePortions: []
4735
+ )
4786
4736
  };
4787
- return lineItem;
4737
+ return this.saveNew(context, resource);
4788
4738
  }
4789
- getWithOrderNumber(context, orderNumber, params = {}) {
4790
- const result = this._storage.query(context.projectKey, this.getTypeId(), {
4791
- ...params,
4792
- where: [`orderNumber="${orderNumber}"`]
4739
+ };
4740
+
4741
+ // src/repositories/my-customer.ts
4742
+ var MyCustomerRepository = class extends CustomerRepository {
4743
+ changePassword(context, changePassword) {
4744
+ const { currentPassword, newPassword } = changePassword;
4745
+ const encodedPassword = hashPassword(currentPassword);
4746
+ const result = this._storage.query(context.projectKey, "customer", {
4747
+ where: [`password = "${encodedPassword}"`]
4793
4748
  });
4794
- if (result.count === 1) {
4795
- return result.results[0];
4749
+ if (result.count === 0) {
4750
+ throw new CommercetoolsError({
4751
+ code: "InvalidCurrentPassword",
4752
+ message: "Account with the given credentials not found."
4753
+ });
4796
4754
  }
4797
- if (result.count > 1) {
4798
- throw new Error("Duplicate order numbers");
4755
+ const customer = result.results[0];
4756
+ if (customer.password !== hashPassword(currentPassword)) {
4757
+ throw new CommercetoolsError({
4758
+ code: "InvalidCurrentPassword",
4759
+ message: "The current password is invalid."
4760
+ });
4761
+ }
4762
+ customer.password = hashPassword(newPassword);
4763
+ customer.version += 1;
4764
+ this._storage.add(context.projectKey, "customer", customer);
4765
+ return customer;
4766
+ }
4767
+ confirmEmail(context, resetPassword) {
4768
+ const { tokenValue } = resetPassword;
4769
+ const customerId = validateEmailVerifyToken(tokenValue);
4770
+ if (!customerId) {
4771
+ throw new CommercetoolsError({
4772
+ code: "ResourceNotFound",
4773
+ message: `The Customer with ID 'Token(${tokenValue})' was not found.`
4774
+ });
4775
+ }
4776
+ const customer = this._storage.get(
4777
+ context.projectKey,
4778
+ "customer",
4779
+ customerId
4780
+ );
4781
+ if (!customer) {
4782
+ throw new CommercetoolsError({
4783
+ code: "ResourceNotFound",
4784
+ message: `The Customer with ID 'Token(${tokenValue})' was not found.`
4785
+ });
4786
+ }
4787
+ customer.isEmailVerified = true;
4788
+ customer.version += 1;
4789
+ this._storage.add(context.projectKey, "customer", customer);
4790
+ return customer;
4791
+ }
4792
+ deleteMe(context) {
4793
+ const results = this._storage.query(
4794
+ context.projectKey,
4795
+ this.getTypeId(),
4796
+ {}
4797
+ );
4798
+ if (results.count > 0) {
4799
+ return this.delete(context, results.results[0].id);
4800
+ }
4801
+ return;
4802
+ }
4803
+ getMe(context) {
4804
+ const results = this._storage.query(
4805
+ context.projectKey,
4806
+ this.getTypeId(),
4807
+ {}
4808
+ );
4809
+ if (results.count > 0) {
4810
+ return results.results[0];
4799
4811
  }
4800
4812
  return;
4801
4813
  }
4802
4814
  };
4803
4815
 
4804
4816
  // src/repositories/my-order.ts
4817
+ import assert4 from "assert";
4805
4818
  var MyOrderRepository = class extends OrderRepository {
4806
4819
  create(context, draft) {
4807
4820
  assert4(draft.id, "draft.id is missing");
@@ -7959,6 +7972,10 @@ var ZoneUpdateHandler = class extends AbstractUpdateHandler {
7959
7972
 
7960
7973
  // src/repositories/index.ts
7961
7974
  var createRepositories = (storage) => ({
7975
+ "as-associate": {
7976
+ cart: new AsAssociateCartRepository(storage),
7977
+ order: new AsAssociateOrderRepository(storage)
7978
+ },
7962
7979
  "associate-role": new AssociateRoleRepository(storage),
7963
7980
  "attribute-group": new AttributeGroupRepository(storage),
7964
7981
  "business-unit": new BusinessUnitRepository(storage),
@@ -8002,6 +8019,12 @@ var createRepositories = (storage) => ({
8002
8019
  "zone": new ZoneRepository(storage)
8003
8020
  });
8004
8021
 
8022
+ // src/services/as-associate.ts
8023
+ import { Router as Router4 } from "express";
8024
+
8025
+ // src/services/as-associate-cart.ts
8026
+ import { Router as Router2 } from "express";
8027
+
8005
8028
  // src/services/abstract.ts
8006
8029
  import { Router } from "express";
8007
8030
 
@@ -8191,6 +8214,70 @@ var AbstractService = class {
8191
8214
  }
8192
8215
  };
8193
8216
 
8217
+ // src/services/as-associate-cart.ts
8218
+ var AsAssociateCartService = class extends AbstractService {
8219
+ repository;
8220
+ constructor(parent, repository) {
8221
+ super(parent);
8222
+ this.repository = repository;
8223
+ }
8224
+ getBasePath() {
8225
+ return "carts";
8226
+ }
8227
+ registerRoutes(parent) {
8228
+ const basePath = this.getBasePath();
8229
+ const router = Router2({ mergeParams: true });
8230
+ this.extraRoutes(router);
8231
+ router.get("/", this.get.bind(this));
8232
+ router.get("/:id", this.getWithId.bind(this));
8233
+ router.delete("/:id", this.deleteWithId.bind(this));
8234
+ router.post("/", this.post.bind(this));
8235
+ router.post("/:id", this.postWithId.bind(this));
8236
+ parent.use(`/${basePath}`, router);
8237
+ }
8238
+ };
8239
+
8240
+ // src/services/as-associate-order.ts
8241
+ import { Router as Router3 } from "express";
8242
+ var AsAssociateOrderService = class extends AbstractService {
8243
+ repository;
8244
+ constructor(parent, repository) {
8245
+ super(parent);
8246
+ this.repository = repository;
8247
+ }
8248
+ getBasePath() {
8249
+ return "orders";
8250
+ }
8251
+ registerRoutes(parent) {
8252
+ const basePath = this.getBasePath();
8253
+ const router = Router3({ mergeParams: true });
8254
+ this.extraRoutes(router);
8255
+ router.get("/", this.get.bind(this));
8256
+ router.get("/:id", this.getWithId.bind(this));
8257
+ router.delete("/:id", this.deleteWithId.bind(this));
8258
+ router.post("/", this.post.bind(this));
8259
+ router.post("/:id", this.postWithId.bind(this));
8260
+ parent.use(`/${basePath}`, router);
8261
+ }
8262
+ };
8263
+
8264
+ // src/services/as-associate.ts
8265
+ var AsAssociateService = class {
8266
+ router;
8267
+ subServices;
8268
+ constructor(parent, repositories) {
8269
+ this.router = Router4({ mergeParams: true });
8270
+ this.subServices = {
8271
+ order: new AsAssociateOrderService(this.router, repositories.order),
8272
+ cart: new AsAssociateCartService(this.router, repositories.cart)
8273
+ };
8274
+ parent.use(
8275
+ "/as-associate/:associateId/in-business-unit/key=:businessUnitId",
8276
+ this.router
8277
+ );
8278
+ }
8279
+ };
8280
+
8194
8281
  // src/services/associate-roles.ts
8195
8282
  var AssociateRoleServices = class extends AbstractService {
8196
8283
  repository;
@@ -8472,7 +8559,7 @@ var InventoryEntryService = class extends AbstractService {
8472
8559
  };
8473
8560
 
8474
8561
  // src/services/my-business-unit.ts
8475
- import { Router as Router2 } from "express";
8562
+ import { Router as Router5 } from "express";
8476
8563
  var MyBusinessUnitService = class extends AbstractService {
8477
8564
  repository;
8478
8565
  constructor(parent, repository) {
@@ -8484,7 +8571,7 @@ var MyBusinessUnitService = class extends AbstractService {
8484
8571
  }
8485
8572
  registerRoutes(parent) {
8486
8573
  const basePath = this.getBasePath();
8487
- const router = Router2({ mergeParams: true });
8574
+ const router = Router5({ mergeParams: true });
8488
8575
  this.extraRoutes(router);
8489
8576
  router.get("/business-units/", this.get.bind(this));
8490
8577
  parent.use(`/${basePath}`, router);
@@ -8492,7 +8579,7 @@ var MyBusinessUnitService = class extends AbstractService {
8492
8579
  };
8493
8580
 
8494
8581
  // src/services/my-cart.ts
8495
- import { Router as Router3 } from "express";
8582
+ import { Router as Router6 } from "express";
8496
8583
  var MyCartService = class extends AbstractService {
8497
8584
  repository;
8498
8585
  constructor(parent, repository) {
@@ -8504,7 +8591,7 @@ var MyCartService = class extends AbstractService {
8504
8591
  }
8505
8592
  registerRoutes(parent) {
8506
8593
  const basePath = this.getBasePath();
8507
- const router = Router3({ mergeParams: true });
8594
+ const router = Router6({ mergeParams: true });
8508
8595
  this.extraRoutes(router);
8509
8596
  router.get("/active-cart", this.activeCart.bind(this));
8510
8597
  router.get("/carts/", this.get.bind(this));
@@ -8524,7 +8611,7 @@ var MyCartService = class extends AbstractService {
8524
8611
  };
8525
8612
 
8526
8613
  // src/services/my-customer.ts
8527
- import { Router as Router4 } from "express";
8614
+ import { Router as Router7 } from "express";
8528
8615
  var MyCustomerService = class extends AbstractService {
8529
8616
  repository;
8530
8617
  constructor(parent, repository) {
@@ -8536,7 +8623,7 @@ var MyCustomerService = class extends AbstractService {
8536
8623
  }
8537
8624
  registerRoutes(parent) {
8538
8625
  const basePath = this.getBasePath();
8539
- const router = Router4({ mergeParams: true });
8626
+ const router = Router7({ mergeParams: true });
8540
8627
  this.extraRoutes(router);
8541
8628
  router.get("", this.getMe.bind(this));
8542
8629
  router.post("", this.updateMe.bind(this));
@@ -8632,7 +8719,7 @@ var MyCustomerService = class extends AbstractService {
8632
8719
  };
8633
8720
 
8634
8721
  // src/services/my-order.ts
8635
- import { Router as Router5 } from "express";
8722
+ import { Router as Router8 } from "express";
8636
8723
  var MyOrderService = class extends AbstractService {
8637
8724
  repository;
8638
8725
  constructor(parent, repository) {
@@ -8644,7 +8731,7 @@ var MyOrderService = class extends AbstractService {
8644
8731
  }
8645
8732
  registerRoutes(parent) {
8646
8733
  const basePath = this.getBasePath();
8647
- const router = Router5({ mergeParams: true });
8734
+ const router = Router8({ mergeParams: true });
8648
8735
  this.extraRoutes(router);
8649
8736
  router.get("/orders/", this.get.bind(this));
8650
8737
  router.get("/orders/:id", this.getWithId.bind(this));
@@ -8980,6 +9067,7 @@ var ZoneService = class extends AbstractService {
8980
9067
  // src/services/index.ts
8981
9068
  var createServices = (router, repos) => ({
8982
9069
  "associate-role": new AssociateRoleServices(router, repos["associate-role"]),
9070
+ "as-associate": new AsAssociateService(router, repos["as-associate"]),
8983
9071
  "business-unit": new BusinessUnitServices(router, repos["business-unit"]),
8984
9072
  "category": new CategoryServices(router, repos["category"]),
8985
9073
  "cart": new CartService(router, repos["cart"], repos["order"]),
@@ -9094,12 +9182,10 @@ var CommercetoolsMock = class {
9094
9182
  _storage;
9095
9183
  _oauth2;
9096
9184
  _mswServer = void 0;
9097
- _services;
9098
9185
  _repositories;
9099
9186
  _projectService;
9100
9187
  constructor(options = {}) {
9101
9188
  this.options = { ...DEFAULT_OPTIONS, ...options };
9102
- this._services = null;
9103
9189
  this._repositories = null;
9104
9190
  this._projectService = void 0;
9105
9191
  this._storage = new InMemoryStorage();
@@ -9169,7 +9255,7 @@ var CommercetoolsMock = class {
9169
9255
  app.use("/:projectKey", projectRouter);
9170
9256
  app.use("/:projectKey/in-store/key=:storeKey", projectRouter);
9171
9257
  }
9172
- this._services = createServices(projectRouter, this._repositories);
9258
+ createServices(projectRouter, this._repositories);
9173
9259
  this._projectService = new ProjectService(
9174
9260
  projectRouter,
9175
9261
  this._repositories.project