UNPKG

@valantic/spartacus-mock

Version:

This project offers you the possibility to mock the OCC Endpoints of your Composable Storefront (Spartacus). It uses the Mock Service Worker to mock the API calls.

1,270 lines (1,235 loc) 207 kB
import { HttpResponse, http, passthrough } from 'msw'; import { setupWorker } from 'msw/browser'; import { defaultOccUserProfileConfig } from '@spartacus/user/profile/occ'; import { faker } from '@faker-js/faker'; import { Occ } from '@spartacus/core'; const occCartConfig = { backend: { occ: { // cannot extend from defaultOccCartConfig as it is not exported endpoints: { carts: 'users/${userId}/carts?fields=carts(DEFAULT,potentialProductPromotions,appliedProductPromotions,potentialOrderPromotions,appliedOrderPromotions,entries(totalPrice(formattedValue),product(images(FULL),stock(FULL)),basePrice(formattedValue,value),updateable),totalPrice(formattedValue),totalItems,totalPriceWithTax(formattedValue),totalDiscounts(value,formattedValue),subTotal(formattedValue),deliveryItemsQuantity,deliveryCost(formattedValue),totalTax(formattedValue, value),pickupItemsQuantity,net,appliedVouchers,productDiscounts(formattedValue),user,saveTime,name,description)', cart: 'users/${userId}/carts/${cartId}?fields=DEFAULT,potentialProductPromotions,appliedProductPromotions,potentialOrderPromotions,appliedOrderPromotions,entries(totalPrice(formattedValue),product(images(FULL),stock(FULL)),basePrice(formattedValue,value),updateable),totalPrice(formattedValue),totalItems,totalPriceWithTax(formattedValue),totalDiscounts(value,formattedValue),subTotal(formattedValue),deliveryItemsQuantity,deliveryCost(formattedValue),totalTax(formattedValue, value),pickupItemsQuantity,net,appliedVouchers,productDiscounts(formattedValue),user,saveTime,name,description', createCart: 'users/${userId}/carts?fields=DEFAULT,potentialProductPromotions,appliedProductPromotions,potentialOrderPromotions,appliedOrderPromotions,entries(totalPrice(formattedValue),product(images(FULL),stock(FULL)),basePrice(formattedValue,value),updateable),totalPrice(formattedValue),totalItems,totalPriceWithTax(formattedValue),totalDiscounts(value,formattedValue),subTotal(formattedValue),deliveryItemsQuantity,deliveryCost(formattedValue),totalTax(formattedValue, value),pickupItemsQuantity,net,appliedVouchers,productDiscounts(formattedValue),user', addEntries: 'users/${userId}/carts/${cartId}/entries', updateEntries: 'users/${userId}/carts/${cartId}/entries/${entryNumber}', removeEntries: 'users/${userId}/carts/${cartId}/entries/${entryNumber}', addEmail: 'users/${userId}/carts/${cartId}/email', deleteCart: 'users/${userId}/carts/${cartId}', cartVoucher: 'users/${userId}/carts/${cartId}/vouchers', saveCart: '/users/${userId}/carts/${cartId}/save?saveCartName=${saveCartName}&saveCartDescription=${saveCartDescription}', validate: 'users/${userId}/carts/${cartId}/validate?fields=DEFAULT', }, }, }, }; const occCheckoutConfig = { backend: { occ: { // cannot extend from defaultOccCheckoutConfig as it is not exported endpoints: { setDeliveryAddress: 'users/${userId}/carts/${cartId}/addresses/delivery', cardTypes: 'cardtypes', createDeliveryAddress: 'users/${userId}/carts/${cartId}/addresses/delivery', removeDeliveryAddress: 'users/${userId}/carts/${cartId}/addresses/delivery', deliveryMode: 'users/${userId}/carts/${cartId}/deliverymode', setDeliveryMode: 'users/${userId}/carts/${cartId}/deliverymode', clearDeliveryMode: 'users/${userId}/carts/${cartId}/deliverymode', deliveryModes: 'users/${userId}/carts/${cartId}/deliverymodes', setCartPaymentDetails: 'users/${userId}/carts/${cartId}/paymentdetails', paymentProviderSubInfo: 'users/${userId}/carts/${cartId}/payment/sop/request?responseUrl=sampleUrl', createPaymentDetails: 'users/${userId}/carts/${cartId}/payment/sop/response', getCheckoutDetails: 'users/${userId}/carts/${cartId}?fields=deliveryAddress(FULL),deliveryMode(FULL),paymentInfo(FULL)', }, }, }, }; const occOrderConfig = { backend: { occ: { // cannot extend from defaultOccCartConfig as it is not exported endpoints: { orderHistory: 'users/${userId}/orders', orderDetail: 'users/${userId}/orders/${orderId}?fields=FULL', consignmentTracking: 'users/${userId}/orders/${orderCode}/consignments/${consignmentCode}/tracking', cancelOrder: 'users/${userId}/orders/${orderId}/cancellation', returnOrder: 'users/${userId}/orderReturns?fields=BASIC,returnEntries(BASIC,refundAmount(formattedValue),orderEntry(basePrice(formattedValue),product(name,code,baseOptions,images(DEFAULT,galleryIndex)))),deliveryCost(formattedValue),totalPrice(formattedValue),subTotal(formattedValue)', orderReturns: 'users/${userId}/orderReturns?fields=BASIC', orderReturnDetail: 'users/${userId}/orderReturns/${returnRequestCode}?fields=BASIC,returnEntries(BASIC,refundAmount(formattedValue),orderEntry(basePrice(formattedValue),product(name,code,baseOptions,images(DEFAULT,galleryIndex)))),deliveryCost(formattedValue),totalPrice(formattedValue),subTotal(formattedValue)', cancelReturn: 'users/${userId}/orderReturns/${returnRequestCode}', /* eslint-enable */ /** scheduled replenishment endpoints start */ replenishmentOrderDetails: 'users/${userId}/replenishmentOrders/${replenishmentOrderCode}?fields=FULL,costCenter(FULL),purchaseOrderNumber,paymentType,user', replenishmentOrderDetailsHistory: 'users/${userId}/replenishmentOrders/${replenishmentOrderCode}/orders', cancelReplenishmentOrder: 'users/${userId}/replenishmentOrders/${replenishmentOrderCode}?fields=FULL,costCenter(FULL),purchaseOrderNumber,paymentType,user', replenishmentOrderHistory: 'users/${userId}/replenishmentOrders?fields=FULL,replenishmentOrders(FULL, purchaseOrderNumber)', /** scheduled replenishment endpoints end */ /** placing an order endpoints start **/ placeOrder: 'users/${userId}/orders?fields=FULL', /** placing an order endpoints end **/ }, }, }, }; const occSavedCartConfig = { backend: { occ: { endpoints: { savedCarts: 'users/${userId}/carts?savedCartsOnly=true&fields=carts(DEFAULT,potentialProductPromotions,appliedProductPromotions,potentialOrderPromotions,appliedOrderPromotions,entries(totalPrice(formattedValue),product(images(FULL),stock(FULL)),basePrice(formattedValue,value),updateable),totalPrice(formattedValue),totalItems,totalPriceWithTax(formattedValue),totalDiscounts(value,formattedValue),subTotal(formattedValue),deliveryItemsQuantity,deliveryCost(formattedValue),totalTax(formattedValue, value),pickupItemsQuantity,net,appliedVouchers,productDiscounts(formattedValue),saveTime,user,name,description)', savedCart: 'users/${userId}/carts/${cartId}/savedcart', restoreSavedCart: 'users/${userId}/carts/${cartId}/restoresavedcart', cloneSavedCart: 'users/${userId}/carts/${cartId}/clonesavedcart?name=${saveCartName}', }, }, }, }; const occStoreFinderConfig = { backend: { occ: { endpoints: { store: 'stores/${storeId}?fields=FULL', stores: 'stores?fields=stores(name,displayName,formattedDistance,openingHours(weekDayOpeningList(FULL),specialDayOpeningList(FULL)),geoPoint(latitude,longitude),address(line1,line2,town,region(FULL),postalCode,phone,country,email), features),pagination(DEFAULT),sorts(DEFAULT)', storescounts: 'stores/storescounts', }, }, }, }; const occUserConfig = { backend: { occ: { // cannot extend from defaultOccCartConfig as it is not exported endpoints: { paymentDetailsAll: 'users/${userId}/paymentdetails', paymentDetail: 'users/${userId}/paymentdetails/${paymentDetailId}', anonymousConsentTemplates: 'users/anonymous/consenttemplates', consentTemplates: 'users/${userId}/consenttemplates', consents: 'users/${userId}/consents', consentDetail: 'users/${userId}/consents/${consentId}', addresses: 'users/${userId}/addresses', addressDetail: 'users/${userId}/addresses/${addressId}', addressVerification: 'users/${userId}/addresses/verification', customerCoupons: 'users/${userId}/customercoupons', claimCoupon: 'users/${userId}/customercoupons/${couponCode}/claim', couponNotification: 'users/${userId}/customercoupons/${couponCode}/notification', notificationPreference: 'users/${userId}/notificationpreferences', productInterests: 'users/${userId}/productinterests', getProductInterests: 'users/${userId}/productinterests?fields=sorts,pagination,results(productInterestEntry,product(code))', }, }, }, }; /** * TODO use endpoints from default configs after SAP exports them, see https://github.com/SAP/spartacus/issues/17442 * * defaultOccCartConfig * defaultOccCheckoutConfig * defaultOccOrderConfig * defaultOccAccountSummaryConfig * defaultOccStoreFinderConfig * defaultOccUserAccountConfig * defaultOccUserProfileConfig * defaultOccProductConfig * defaultOccSiteContextConfig * defaultOccUserConfig */ const i18nEndpoint = 'i18n/${language}/${namespace}'; const cartEndpoints = occCartConfig.backend.occ.endpoints; const checkoutEndpoints = occCheckoutConfig.backend.occ.endpoints; const orderEndpoints = occOrderConfig.backend.occ.endpoints; const savedCartEndpoints = occSavedCartConfig.backend?.occ?.endpoints; const userEndpoints = occUserConfig.backend?.occ?.endpoints; const userProfileEndpoints = defaultOccUserProfileConfig.backend?.occ?.endpoints; const storeFinderEndpoints = occStoreFinderConfig.backend.occ.endpoints; /** * Returns the default routes for Spartacus Mock Server * @param environment */ function getDefaultRoutes(environment) { const occEndpoint = `${environment.backend.occ?.baseUrl}${environment.backend.occ?.prefix}`; // TODO Take all endpoints from the defaultXxx configs above return { /** * General Calls *************************************************************************************************** */ /** * Route for the baseSites call being done by spartacus on application startup */ baseSites: `${occEndpoint}basesites`, /** * Route for the languages call being done by spartacus on application startup */ languages: `${occEndpoint}:baseSiteId/languages`, /** * Route for the currencies call being done by spartacus on application startup */ currencies: `${occEndpoint}:baseSiteId/currencies`, /** * Route for the titles call being done by spartacus when showing the address form */ titles: `${occEndpoint}:baseSiteId/titles`, /** * Route for the countries call being done by spartacus when showing the address form */ countries: `${occEndpoint}:baseSiteId/countries`, /** * Route for the regions call being done by spartacus when showing the address form */ regions: `${occEndpoint}:baseSiteId/countries/:isocode/regions`, /** * Route for the i18n call to load the translations from the backend when having i18n lazy loading activated * Url is defined as <occ-base-url>/<occ-prefix>/i18n/${language}/${namespace} and can be overridden via * option i18nEndpoint of the spartacus-mock options */ i18n: `${occEndpoint}:baseSiteId/${i18nEndpoint .split('?')[0] .replace('${language}', ':language') .replace('${namespace}', ':namespace')}`, /** * User related calls ********************************************************************************************** */ /** * Route for the login call to the authorizationserver */ authLogin: '*/authorizationserver/oauth/token', /** * Route for the logout call to the authorizationserver */ authRevoke: '*/authorizationserver/oauth/revoke', /** * Route for the users call to create a new user during registration */ users: `${occEndpoint}:baseSiteId/users`, /** * Route for the user call to get the user details after login */ user: `${occEndpoint}:baseSiteId/users/:user`, /** * Route for the call to get the user details * call somehow needed and done without baseSite sometimes */ userTemp: `${occEndpoint}users/:user`, /** * Route for the call to get the consent templates for the current user */ consentTemplates: `${occEndpoint}:baseSiteId/users/:user/consenttemplates`, /** * Route for the call to get the consent templates for the current user */ anonymousConsentTemplates: `${occEndpoint}:baseSiteId/users/:user/consenttemplates`, /** * Route for the call to get the notification preferences for the current user */ notificationPreferences: `${occEndpoint}:baseSiteId/users/:user/notificationpreferences`, /** * Route for the call to get the product interests for the current user */ productInterests: `${occEndpoint}:baseSiteId/users/:user/productinterests`, /** * Route for the call to get the customer coupons for the current user */ customerCoupons: `${occEndpoint}:baseSiteId/users/:user/customercoupons`, /** * Route for the call to get the addresses for the current user */ addresses: `${occEndpoint}:baseSiteId/users/:user/addresses`, /** * Route for the call to get the payment details for the current user */ payments: `${occEndpoint}:baseSiteId/users/:user/paymentDetails`, /** * Route for the call to get execute the address verification for the current user */ addressVerification: `${occEndpoint}:baseSiteId/users/:user/addresses/verification`, /** * CMS Calls ******************************************************************************************************* */ /** * Route for the call to get the page data (basic page data & slots with components) for the current page */ pages: `${occEndpoint}:baseSiteId/cms/pages`, /** * Route for the call to get the component data (spartacus does this call with aggregated component Uid's) */ components: `${occEndpoint}:baseSiteId/cms/components`, /** * Product Calls *************************************************************************************************** */ /** * Route for the call to get the product references for the current product (works on product detail page) */ productReferences: `${occEndpoint}:baseSiteId/products/:productCode/references`, /** * Route for the call to get the product references for the current product (works on product detail page) */ productReviews: `${occEndpoint}:baseSiteId/products/:productCode/reviews`, /** * Route for the call to search for products and return a productSearchPage Object */ productSearch: `${occEndpoint}:baseSiteId/products/search`, /** * Route for the call to search for text based product suggestions */ searchSuggestions: `${occEndpoint}:baseSiteId/products/suggestions`, /** * Route for the call to load the product details */ product: `${occEndpoint}:baseSiteId/products/:productCode`, /** * Cart Calls ****************************************************************************************************** */ /** * Route for the call to load the carts for a user. The returned array can contain multiple (normal, wishlist, selective) carts. */ carts: `${occEndpoint}:baseSiteId/${cartEndpoints.carts.split('?')[0]}`.replace('${userId}', ':userId'), /** * Route for the call to load the cart data for a certain cartId */ cart: `${occEndpoint}:baseSiteId/${cartEndpoints.cart.split('?')[0]}` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId'), /** * Route for the call to add an entry to cart */ addEntries: `${occEndpoint}:baseSiteId/${cartEndpoints.addEntries.split('?')[0]}` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId'), /** * Route for the call to update an entry in the cart */ updateEntries: `${occEndpoint}:baseSiteId/${cartEndpoints.updateEntries.split('?')[0]}` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId') .replace('${entryNumber}', ':entryNumber'), /** * Route for the call to remove an entry from the cart */ removeEntries: `${occEndpoint}:baseSiteId/${cartEndpoints.removeEntries.split('?')[0]}` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId') .replace('${entryNumber}', ':entryNumber'), /** * Route for the call to delete a cart */ deleteCart: `${occEndpoint}:baseSiteId/${cartEndpoints.deleteCart.split('?')[0]}` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId'), /** * Route for the call to set an email on the cart (needed for guest checkout) */ addEmail: `${occEndpoint}:baseSiteId/${cartEndpoints.addEmail.split('?')[0]}` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId'), /** * Route for the call to add a voucher on the cart */ cartVoucher: `${occEndpoint}:baseSiteId/${cartEndpoints.cartVoucher.split('?')[0]}` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId'), /** * Route for the call to remove a voucher from the cart */ cartVoucherRemove: `${occEndpoint}:baseSiteId/${cartEndpoints.cartVoucher.split('?')[0]}/:voucherCode` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId'), /** * Route for the call to validate the cart */ validate: `${occEndpoint}:baseSiteId/${cartEndpoints.validate.split('?')[0]}` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId'), /** * Route for the call to save a cart as wishlist cart for user logging in and not having a wishlist cart yet */ saveCart: `${occEndpoint}:baseSiteId${cartEndpoints.saveCart.split('?')[0]}` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId'), // Note: The saveCart endpoint from the Spartacus Core starts with a "/" /** * Checkout Calls ************************************************************************************************** */ /** * Route for the call to set a delivery address on the cart during checkout */ setDeliveryAddress: `${occEndpoint}:baseSiteId/${checkoutEndpoints.setDeliveryAddress.split('?')[0]}` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId'), /** * Route for the call to create a new delivery address on the cart during checkout */ createDeliveryAddress: `${occEndpoint}:baseSiteId/${checkoutEndpoints.createDeliveryAddress.split('?')[0]}` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId'), /** * Route for the call to remove a delivery address on the cart during checkout */ removeDeliveryAddress: `${occEndpoint}:baseSiteId/${checkoutEndpoints.removeDeliveryAddress.split('?')[0]}` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId'), /** * Route for the call to set a delivery mode on the cart during checkout */ deliveryMode: `${occEndpoint}:baseSiteId/${checkoutEndpoints.deliveryMode.split('?')[0]}` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId'), /** * Route for the call to get all available delivery modes */ deliveryModes: `${occEndpoint}:baseSiteId/${checkoutEndpoints.deliveryModes.split('?')[0]}` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId'), /** * Route for the call to get all available card types for payment */ cardTypes: `${occEndpoint}:baseSiteId/${checkoutEndpoints.cardTypes.split('?')[0]}` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId'), /** * Route for the call to get the payment provider sub info when using an integrated payment provider (default spartacus) */ paymentProviderSubInfo: `${occEndpoint}:baseSiteId/${checkoutEndpoints.paymentProviderSubInfo.split('?')[0]}` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId'), /** * Route for the call to create a new payment method */ createPaymentDetails: `${occEndpoint}:baseSiteId/${checkoutEndpoints.createPaymentDetails.split('?')[0]}` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId'), /** * Route for the call to set an existing payment method on the cart */ setCartPaymentDetails: `${occEndpoint}:baseSiteId/${checkoutEndpoints.setCartPaymentDetails.split('?')[0]}` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId'), /** * Route for the call to get the mock sop payment response (html page) */ sopMockProcess: `${environment.backend.occ?.baseUrl}/acceleratorservices/sop-mock/process`, /** * Order Calls ***************************************************************************************************** */ /** * Route for the call to place the order */ placeOrder: `${occEndpoint}:baseSiteId/${orderEndpoints.placeOrder.split('?')[0]}`.replace('${userId}', ':userId'), /** * Route for the call to load the orders for a user */ orderHistory: `${occEndpoint}:baseSiteId/${orderEndpoints.orderHistory.split('?')[0]}`.replace('${userId}', ':userId'), /** * Route for the call to load the order details for an order */ orderDetail: `${occEndpoint}:baseSiteId/${orderEndpoints.orderDetail.split('?')[0]}` .replace('${userId}', ':userId') .replace('${orderId}', ':orderId'), /** * Route for the call to cancel an order */ cancelOrder: `${occEndpoint}:baseSiteId/${orderEndpoints.cancelOrder.split('?')[0]}` .replace('${userId}', ':userId') .replace('${orderId}', ':orderId'), /** * Route for the call to return an order */ returnOrder: `${occEndpoint}:baseSiteId/${orderEndpoints.returnOrder.split('?')[0]}` .replace('${userId}', ':userId') .replace('${orderId}', ':orderId'), /** * Route for the call to load the order returns */ orderReturns: `${occEndpoint}:baseSiteId/${orderEndpoints.orderReturns.split('?')[0]}`.replace('${userId}', ':userId'), /** * Route for the call to load the the order return details */ orderReturnDetail: `${occEndpoint}:baseSiteId/${orderEndpoints.orderReturnDetail.split('?')[0]}` .replace('${userId}', ':userId') .replace('${returnRequestCode}', ':returnRequestCode'), /** * Route for the call to cancel an order return */ cancelReturn: `${occEndpoint}:baseSiteId/${orderEndpoints.cancelReturn.split('?')[0]}` .replace('${userId}', ':userId') .replace('${returnRequestCode}', ':returnRequestCode'), /** * Account Calls *************************************************************************************************** */ /** * Route for the call to restore a saved cart */ restoreSavedCart: `${occEndpoint}:baseSideId/${savedCartEndpoints?.restoreSavedCart}` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId'), /** * Route for the call to clone a saved cart */ cloneSavedCart: `${occEndpoint}:baseSideId/${(savedCartEndpoints?.cloneSavedCart).split('?')}` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId'), /** * Route for the call to get a saved cart */ savedCart: `${occEndpoint}:baseSideId/${savedCartEndpoints?.savedCart}` .replace('${userId}', ':userId') .replace('${cartId}', ':cartId'), /** * Route for the call to change / delete an address */ addressDetail: `${occEndpoint}:baseSideId/${userEndpoints?.addressDetail}` .replace('${userId}', ':userId') .replace('${addressId}', ':addressId'), /** * Route for the call to delete an payment type */ paymentDetail: `${occEndpoint}:baseSiteId/${userEndpoints?.paymentDetail}` .replace('${userId}', ':userId') .replace('${paymentDetailId}', ':paymentDetailId'), /** * Route for the call to update the user password */ userUpdatePassword: `${occEndpoint}:baseSiteId/${userProfileEndpoints?.userUpdatePassword}`.replace('${userId}', ':userId'), /** * Route for the call to update the user id (email) */ userUpdateLoginId: `${occEndpoint}:baseSiteId/${userProfileEndpoints?.userUpdateLoginId}`.replace('${userId}', ':userId'), /** * Route for the call to delete a previously given consent */ consentDetail: `${occEndpoint}:baseSiteId/${userEndpoints?.consentDetail}` .replace('${userId}', ':userId') .replace('${consentId}', ':consentId'), /** * Route for the call to get all consents of a user */ consents: `${occEndpoint}:baseSiteId/${userEndpoints?.consents}`.replace('${userId}', ':userId'), /** * Route for the call to get all consents of a user */ anonymousConsents: `${occEndpoint}:baseSiteId/${(userEndpoints?.anonymousConsentTemplates).split('?')[0]}}`, /** * Route for the call to get the notification preferences of a user */ notificationPreference: `${occEndpoint}:baseSiteId/${userEndpoints?.notificationPreference}`.replace('${userId}', ':userId'), /** * Store Finder **************************************************************************************************** */ /** * Route for the call to get the number of stores */ storescounts: `${occEndpoint}:baseSiteId/${storeFinderEndpoints.storescounts.split('?')[0]}`, /** * Route for the call to get the stores */ stores: `${occEndpoint}:baseSiteId/${storeFinderEndpoints.stores.split('?')[0]}`, /** * Route for the call to get the store details */ store: `${occEndpoint}:baseSiteId/${storeFinderEndpoints.store.split('?')[0]}`.replace('${storeId}', ':storeId'), }; } const createCountry = (additionalData) => { return { isocode: 'CH', name: 'Schweiz', ...additionalData, }; }; const countryList = () => { return { countries: [ createCountry({ isocode: 'CH', name: 'Switzerland', }), createCountry({ isocode: 'DE', name: 'Germany', }), createCountry({ isocode: 'FR', name: 'France', }), createCountry({ isocode: 'IT', name: 'Italy', }), ], }; }; const createCurrency = (additionalData) => { return { active: true, isocode: 'USD', name: 'US Dollar', symbol: '$', ...additionalData, }; }; const currencyList = () => { return { currencies: [ createCurrency(), createCurrency({ isocode: 'EUR', name: 'Euro', symbol: '€', }), createCurrency({ isocode: 'CHF', name: 'Schweizer Franken', symbol: 'CHF', }), ], }; }; const createPagination = (additionalData) => { return { count: 10, page: 1, totalCount: 10, totalPages: 1, ...additionalData, }; }; const createPaginationModel = (additionalData) => { const totalResults = faker.number.int({ min: 1, max: 999 }); const pageSize = 12; return { currentPage: 1, pageSize, sort: '', totalPages: totalResults / pageSize + 1, totalResults, ...additionalData, }; }; const createRegion = (additionalData) => { return { countryIso: 'CH', isocode: 'SG', isocodeShort: 'SG', name: 'St. Gallen', ...additionalData, }; }; const regionList = () => { return { regions: [ createRegion(), createRegion({ isocode: 'ZH', isocodeShort: 'ZH', name: 'Zürich', }), createRegion({ isocode: 'BE', isocodeShort: 'BE', name: 'Bern', }), createRegion({ isocode: 'TG', isocodeShort: 'TG', name: 'Thurgau', }), ], }; }; const createSort = (additionalData) => { return { asc: true, code: 'name', ...additionalData, }; }; const createSortModel = (additionalData) => { return { code: 'name', name: 'Name', selected: false, ...additionalData, }; }; const createTitle = (additionalData) => { return { code: 'mr', name: 'Mr', ...additionalData, }; }; const titleList = () => { return { titles: [ createTitle({ code: 'mr', name: 'Mr.', }), createTitle({ code: 'mrs', name: 'Mrs.', }), createTitle({ code: 'div', name: 'Divers', }), ], }; }; const createAddress = (additionalData) => { const firstName = faker.person.firstName(); const lastName = faker.person.lastName(); return { id: faker.string.uuid(), title: 'Mr.', titleCode: 'mr', email: faker.internet.email({ firstName, lastName }), firstName, lastName, companyName: faker.company.name(), line1: faker.location.streetAddress(), line2: '', postalCode: faker.location.zipCode('####'), town: faker.location.city(), country: createCountry(), region: createRegion(), cellphone: faker.phone.number(), defaultAddress: false, shippingAddress: true, formattedAddress: '', phone: faker.phone.number(), visibleInAddressBook: true, ...additionalData, }; }; const addressList = () => { return { addresses: [ createAddress({ shippingAddress: true, }), createAddress({ shippingAddress: false, }), ], }; }; const createCustomerCoupon = (additionalData) => { return { couponId: faker.string.numeric(6), name: 'Free Delivery Coupon', startDate: faker.date.past().toDateString(), endDate: faker.date.future().toDateString(), status: 'Effective', description: faker.lorem.sentences(2), notificationOn: false, allProductsApplicable: true, ...additionalData, }; }; const customerCouponSearchResult = (additionalData) => { return { coupons: [createCustomerCoupon()], pagination: createPagination(), sorts: [ createSort({ code: 'startdata', }), ], ...additionalData, }; }; const createNotificationPreference = (additionalData) => { return { channel: 'EMAIL', enabled: true, value: faker.internet.email(), visible: true, ...additionalData, }; }; const notificationPreferenceList = () => { return { preferences: [ createNotificationPreference(), createNotificationPreference({ channel: 'SITE_MESSAGE', enabled: false, visible: true, value: '', }), ], }; }; const DEFAULT_PAYMENT_ID = '8796126183466'; const createCardType = (additionalData) => { return { code: 'maestro', name: 'Maestro', ...additionalData, }; }; const createPaymentDetails = (additionalData) => { return { accountHolderName: faker.person.fullName(), billingAddress: createAddress({ shippingAddress: false }), cardNumber: `************${faker.string.numeric(4)}`, cardType: createCardType(), defaultPayment: false, expiryMonth: faker.number.int({ min: 1, max: 12 }).toString(), expiryYear: faker.number.int({ min: 2030, max: 2050 }).toString(), id: faker.string.numeric(9), saved: true, subscriptionId: faker.string.uuid(), ...additionalData, }; }; const paymentDetailsList = () => { return { payments: [ createPaymentDetails({ defaultPayment: true, id: DEFAULT_PAYMENT_ID, }), createPaymentDetails({ cardType: createCardType({ code: 'visa', name: 'Visa', }), }), createPaymentDetails({ cardType: createCardType({ code: 'amex', name: 'American Express', }), }), createPaymentDetails({ cardType: createCardType({ code: 'diners', name: "Diner's Club", }), }), ], }; }; const createPrice = (additionalData, modifier) => { const valueMin = Number.isInteger(modifier?.valueMin) ? modifier?.valueMin : faker.number.int({ min: 1, max: 9999 }); const valueMax = Number.isInteger(modifier?.valueMax) ? modifier?.valueMax : faker.number.int({ min: valueMin, max: 9999 }); const value = faker.number.int({ min: valueMin, max: valueMax }); return { currencyIso: 'CHF', formattedValue: faker.commerce.price({ min: valueMin, max: valueMax, dec: 2, symbol: 'CHF' }), maxQuantity: undefined, minQuantity: undefined, priceType: Occ.PriceType.BUY, value, ...additionalData, }; }; const createPriceRange = (additionalData) => { const minPrice = faker.number.int({ min: 1, max: 999 }); const maxPrice = faker.number.int({ min: minPrice, max: 9999 }); return { minPrice: createPrice({ value: minPrice, formattedValue: faker.commerce.price({ min: minPrice, max: minPrice, dec: 2, symbol: 'CHF' }), }), maxPrice: createPrice({ value: maxPrice, formattedValue: faker.commerce.price({ min: maxPrice, max: maxPrice, dec: 2, symbol: 'CHF' }), }), ...additionalData, }; }; const createDeliveryMode = (additionalData) => { return { code: faker.string.uuid(), name: faker.lorem.words(3), description: faker.lorem.sentences(1), deliveryCost: createPrice(), ...additionalData, }; }; const image = (additionalData, modifier) => { return { altText: faker.lorem.words(5), format: 'picture', galleryIndex: undefined, imageType: Occ.ImageType.PRIMARY, url: `https://picsum.photos/${modifier?.width || 1200}/${modifier?.height || 1200}.webp?random=${faker.number.int(999)}`, ...additionalData, }; }; const createPromotionOrderEntryConsumed = (additionalData) => { return { adjustedUnitPrice: faker.number.int({ min: 1, max: 50 }), code: faker.string.numeric(6), orderEntryNumber: 1, quantity: 1, ...additionalData, }; }; const createPromotionResult = (additionalData) => { return { consumedEntries: [createPromotionOrderEntryConsumed()], description: faker.lorem.words(4), promotion: createPromotion(), ...additionalData, }; }; const createPromotionRestriction = (additionalData) => { return { description: faker.lorem.sentences(3), restrictionType: '', ...additionalData, }; }; const createPromotion = (additionalData) => { return { code: faker.string.uuid(), couldFireMessages: [], description: faker.lorem.sentences(3), enabled: true, endDate: faker.date.future(), firedMessages: [], priority: 1, productBanner: image(), promotionGroup: '', promotionType: '', restrictions: [createPromotionRestriction()], startDate: faker.date.past(), title: faker.lorem.words(5), ...additionalData, }; }; const LOCAL_STORAGE_KEY = 'spartacus⚿⚿mock-data'; const createVoucher = (additionalData) => { return { code: faker.string.uuid(), currency: createCurrency(), description: faker.lorem.paragraphs(1), freeShipping: faker.datatype.boolean(), name: faker.lorem.words(4), value: 0, valueFormatted: 'USD 0.00', valueString: '0', voucherCode: faker.string.numeric(10), ...additionalData, }; }; const addVoucher = (voucherId) => { let mockData = JSON.parse(window.localStorage.getItem(LOCAL_STORAGE_KEY) || '{}'); mockData.activeVouchers.push({ code: voucherId, voucherCode: voucherId, }); window.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(mockData)); }; const deleteVoucher = (voucherCode) => { let mockData = JSON.parse(window.localStorage.getItem(LOCAL_STORAGE_KEY) || '{}'); mockData = { ...mockData, activeVouchers: mockData.activeVouchers.filter((voucher) => { return voucher.code !== voucherCode; }), }; window.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(mockData)); }; const createProductStock = (additionalData) => { return { stockLevel: faker.number.int({ min: 1, max: 9999 }), stockLevelStatus: 'inStock', ...additionalData, }; }; const createFutureStock = (additionalData) => { const date = faker.date.future(); return { date, formattedDate: date.toDateString(), stock: createProductStock(), ...additionalData, }; }; const createVariantOptionQualifier = () => { return { image: undefined, name: `${faker.commerce.productName()} - ${faker.commerce.productMaterial()}`, qualifier: faker.commerce.productMaterial(), value: faker.commerce.productMaterial(), }; }; const createVariantOption = (additionalData) => { return { code: `VAR_${faker.string.numeric(6)}`, priceData: createPrice(), stock: createProductStock(), url: faker.internet.url(), variantOptionQualifiers: [ createVariantOptionQualifier(), createVariantOptionQualifier(), createVariantOptionQualifier(), ], ...additionalData, }; }; const createBaseOption = (additionalData) => { return { options: [createVariantOption()], selected: createVariantOption(), variantType: '', ...additionalData, }; }; const createProductCategory = (additionalData) => { return { code: faker.string.uuid(), name: faker.commerce.department(), image: undefined, url: faker.internet.url(), ...additionalData, }; }; const createFeatureValue = () => { return { value: faker.string.numeric(2), }; }; const createFeatureUnit = (additionalData) => { return { name: faker.science.unit().name, symbol: faker.science.unit().symbol, unitType: faker.string.numeric(2), ...additionalData, }; }; const createFeature = (additionalData) => { return { code: faker.string.numeric(4), comparable: true, featureUnit: createFeatureUnit(), featureValues: [createFeatureValue()], name: faker.science.unit().name, range: false, ...additionalData, }; }; const createProductClassification = (additionalData) => { return { code: faker.string.numeric(4), features: new Array(faker.number.int(10)).fill(null).map(() => createFeature()), name: faker.commerce.productName(), ...additionalData, }; }; const createProductReference = (additionalData) => { return { description: faker.commerce.productDescription(), preselected: false, quantity: faker.number.int({ min: 1, max: 99 }), referenceType: 'ACCESSORIES', target: createBaseProduct(), ...additionalData, }; }; const productReferenceList = (modifier) => { return { references: [ createProductReference({ referenceType: modifier?.referenceType || 'ACCESSORIES' }), createProductReference({ referenceType: modifier?.referenceType || 'ACCESSORIES' }), createProductReference({ referenceType: modifier?.referenceType || 'ACCESSORIES' }), ], }; }; const createLanguage = (additionalData) => { return { active: true, isocode: 'en', name: 'English', nativeName: 'English', ...additionalData, }; }; const languageList = () => { return { languages: [ createLanguage(), createLanguage({ isocode: 'de', name: 'German', nativeName: 'Deutsch', }), createLanguage({ isocode: 'it', name: 'Italian', nativeName: 'Italiano', }), createLanguage({ isocode: 'fr', name: 'French', nativeName: 'Francais', }), ], }; }; const createUser = (additionalData) => { const firstName = faker.person.firstName(); const lastName = faker.person.lastName(); return { currency: createCurrency(), customerId: faker.string.numeric(6), deactivationDate: faker.date.future(), defaultAddress: createAddress(), displayUid: faker.internet.email({ firstName, lastName }), firstName, language: createLanguage(), lastName, name: faker.person.fullName({ firstName, lastName }), title: 'Mr.', titleCode: 'mr', uid: faker.string.uuid(), ...additionalData, }; }; const createReview = (additionalData) => { return { alias: faker.person.fullName(), comment: faker.lorem.paragraphs(faker.number.int({ min: 1, max: 5 })), date: faker.date.past(), headline: faker.lorem.words(faker.number.int({ min: 2, max: 5 })), id: faker.string.numeric(10), principal: createUser(), rating: faker.number.int({ min: 1, max: 5 }), ...additionalData, }; }; const reviewList = () => { return { reviews: new Array(faker.number.int({ min: 1, max: 10 })).fill(null).map(() => createReview()), }; }; const activeTabItems = [ 'ProductDetailsTabComponent', 'ProductSpecsTabComponent', 'ProductReviewsTabComponent', 'deliveryTab', ]; /** * Gets a Base Set of Product Data */ const createBaseProduct = (additionalData) => { return { code: faker.string.numeric(6), name: faker.commerce.productName(), images: [ // PRIMARY image({ format: 'hires' }, { width: 3500, height: 3500 }), image({ format: 'product' }, { width: 675, height: 675 }), image({ format: 'thumbnail' }, { width: 180, height: 180 }), image({ format: 'cartIcon' }, { width: 180, height: 180 }), // GALLERY image({ format: 'zoom', imageType: Occ.ImageType.GALLERY, galleryIndex: 1 }, { width: 1200, height: 1200, }), image({ format: 'product', imageType: Occ.ImageType.GALLERY, galleryIndex: 1 }, { width: 480, height: 480, }), image({ format: 'thumbnail', imageType: Occ.ImageType.GALLERY, galleryIndex: 1 }, { width: 180, height: 180, }), image({ format: 'zoom', imageType: Occ.ImageType.GALLERY, galleryIndex: 2 }, { width: 1200, height: 1200, }), image({ format: 'product', imageType: Occ.ImageType.GALLERY, galleryIndex: 2 }, { width: 480, height: 480, }), image({ format: 'thumbnail', imageType: Occ.ImageType.GALLERY, galleryIndex: 2 }, { width: 180, height: 180, }), image({ format: 'zoom', imageType: Occ.ImageType.GALLERY, galleryIndex: 3 }, { width: 1200, height: 1200, }), image({ format: 'product', imageType: Occ.ImageType.GALLERY, galleryIndex: 3 }, { width: 480, height: 480, }), image({ format: 'thumbnail', imageType: Occ.ImageType.GALLERY, galleryIndex: 3 }, { width: 180, height: 180, }), ], baseProduct: `BASE_${faker.string.numeric(6)}`, price: createPrice(), purchasable: true, url: faker.internet.url(), stock: createProductStock(), ...additionalData, }; }; /** * Gets a Full Set of Product Data */ const createFullProduct = (additionalData) => { return { ...createBaseProduct(), availableForPickup: true, averageRating: faker.number.float({ min: 1, max: 5, multipleOf: 0.1 }), baseOptions: [createBaseOption()], categories: [createProductCategory(), createProductCategory(), createProductCategory()], classifications: [createProductClassification(), createProductClassification(), createProductClassification()], description: faker.commerce.productDescription(), futureStocks: [createFutureStock()], manufacturer: faker.company.name(), multidimensional: false, numberOfReviews: faker.number.int({ min: 0, max: 999 }), potentialPromotions: [createPromotion()], priceRange: createPriceRange(), productReferences: [ createProductReference({ referenceType: 'ACCESSORIES' }), createProductReference({ referenceType: 'SIMILAR' }), ], reviews: reviewList().reviews, summary: faker.lorem.sentences(5), variantMatrix: [], variantOptions: [createVariantOption(), createVariantOption(), createVariantOption()], variantType: '', volumePrices: [ createPrice({ minQuantity: 10 }), createPrice({ minQuantity: 100 }), createPrice({ minQuantity: 1000 }), ], volumePricesFlag: false, ...additionalData, }; }; const createProductInterestEntry = (additionalData) => { return { interestType: Occ.NotificationType.BACK_IN_STOCK, dateAdded: faker.date.past().toDateString(), expirationDate: faker.date.future().toDateString(), ...additionalData, }; }; const createProductInterestEntryRelation = (additionalData) => { return { product: createFullProduct(), productInterestEntry: [createProductInterestEntry()], ...additionalData, }; }; const productInterestSearchResult = (additionalData) => { return { pagination: createPagination(), results: [createProductInterestEntryRelation()], sorts: [createSort()], ...additionalData, }; }; const createAuthToken = () => { return { access_token: faker.string.uuid(),