All files / src sfcc.js

62.22% Statements 168/270
51.33% Branches 77/150
61.95% Functions 70/113
69.79% Lines 164/235

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090                      1x 247x 47x     1x                   1x           5x           5x                       1x         150x                                 1x         487x                               1x       177x                             1x             85x                                       1x       280x                                 1x       25x     280x                           1x                   5x   25x   85x                               1x         20x                             1x       35x                           1x                               5x                                       1x       7x               1x                       1x                         1x       1x         2x         1x 1x             1x     1x 1x 1x 1x 1x             1x                             25x                     25x             1x 1x     1x 1x     1x 1x                                         1x   1x 1x               1x 1x   1x   1x   1x 1x               1x 1x   1x   1x 1x               1x 1x   1x 1x   1x   1x 1x                                                                                                                                       6x 6x   6x         6x   6x 5x   1x                                                                                                                                                               1x 1x   1x     1x   1x 1x               3x                                                                 5x                                                                                                                                     5x       5x 5x 5x       5x   5x   5x 5x   5x 5x 5x 5x 5x 5x 5x   5x                                         1x             1x             3x 3x       3x       3x 2x                   7x             2x 2x       2x       2x 1x   1x               3x   3x 3x       3x       3x   3x                             5x             5x 5x   5x           5x           5x 5x                         5x             1x   1x 1x                   5x 5x                                       2x 2x                         4x 2x     2x 2x 2x   2x     2x         2x 2x       4x               1x 1x 1x             1x 1x         1x                             46x                                     47x         47x               47x 12x     47x                         38x            
/* * *  *  * *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  * */
/* Copyright (c) 2018 Mobify Research & Development Inc. All rights reserved. */
/* * *  *  * *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  * */
/** @module sfcc */
 
 
import ShopApi from 'commercecloud-ocapi-client'
import btoa from 'btoa'
import * as errors from './errors'
 
 
const clean = (obj) => {
    Object.keys(obj).forEach((key) => (obj[key] === null || obj[key] === undefined) && delete obj[key])
    return obj
}
 
const filterAttributeDictionary = {
    categoryId: 'cgid'
}
 
/**
 * This function will take product search request as we use them in the commerce-integrations
 * and output them into a format usable by the specific connector (ocapi).
 *
 * @private
 */
const transformProductSearchRequest = ({
    query,
    count,
    start,
    sort,
    filters = {}
}) => ({
    count,
    q: query,
    sort,
    start,
    refine: Object.keys(filters)
        .map((key) => `${filterAttributeDictionary[key] || key}=${filters[key]}`)
})
 
/**
* Takes a OCAPI Image object and parses it into a commerce-integrations
* Image type.
 *
 * @param {Object} data a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/Image.html|Image} document
 *
 * @return {module:types.Image}.
 */
/* eslint-disable camelcase */
const parseImage = ({
    alt,
    dis_base_link,
    link,
    title
}) => ({
    alt,
    description: alt,
    src: dis_base_link || link,
    title
})
/* eslint-enable camelcase */
 
/**
 * Takes a OCAPI VariationAttributeValue object and parses it into a commerce-integrations
 * ProductSearchResult type.
 *
 * @param {Object} data a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/VariationAttributeValue.html|VariationAttributeValue} document
 * @return {module:types.VariationPropertyValue}
 * @private
 */
 /* eslint-disable camelcase */
const parseVariationPropertyValue = ({
    image,
    image_swatch,
    name,
    value
}) => ({
    name,
    value,
    mainImage: image ? parseImage(image) : undefined,
    swatchImage: image_swatch ? parseImage(image_swatch) : undefined
})
/* eslint-enable camelcase */
 
/**
 * Takes a OCAPI VariationAttribute object and parses it into a commerce-integrations
 * VariationProperty type.
 *
 * @param {Object} data a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/VariationAttribute.html|VariationAttribute} document
 * @return {module:types.VariationProperty}
 * @private
 */
const parseVariationProperty = ({
    id,
    name,
    values = []
}) => ({
    id,
    label: name,
    values: values.map(parseVariationPropertyValue)
})
 
/**
 * Takes a OCAPI ProductSearchHit object and parses it into a commerce-integrations
 * ProductSearchResult type.
 *
 * @param {Object} data a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/ProductSearchHit.html|ProductSearchHit} document
 *
 * @returns {module:types.ProductSearchResult}.
 */
/* eslint-disable camelcase */
const parseProductSearchResult = ({
    product_id,
    product_name,
    image,
    orderable,
    price,
    variation_attributes
}) => ({
    available: orderable,
    productId: product_id,
    productName: product_name,
    price,
    defaultImage: image ? parseImage(image) : undefined,
    variationProperties: variation_attributes ? variation_attributes.map(parseVariationProperty) : [],
})
/* eslint-enable camelcase */
 
/**
 * Takes a OCAPI ProductSearchRefinementValue object and parses it into a commerce-integrations
 * FilterValue type.
 *
 * @param {Object} data a OCAPI
 * {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/ProductSearchRefinementValue.html|ProductSearchRefinementValue} document
 *
 * @returns {module:types.FilterValue}.
 */
/* eslint-disable camelcase */
const parseFilterValue = ({
    hit_count,
    label,
    value
}) => ({
    count: hit_count,
    label,
    value
})
/* eslint-enable camelcase */
 
/**
 * Takes a OCAPI ProductSearchRefinement object and parses it into a commerce-integrations
 * Filter type.
 *
 * @param {Object} data a OCAPI
 * {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/ProductSearchRefinement.html|ProductSearchRefinement} document // eslint-disable-line
 *
 * @returns {module:types.Filter}.
 */
/* eslint-disable camelcase */
const parseFilters = ({
    label,
    attribute_id,
    values
}) => ({
    propertyId: attribute_id,
    label,
    values: values ? values.map((value) => parseFilterValue(value)) : undefined
})
/* eslint-enable camelcase */
 
/**
 * Takes a OCAPI ProductSearchResult object and parses it into a commerce-integrations
 * ProductSearch type.
 *
 * @param {Object} data a OCAPI
 * {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/ProductSearchResult.html?cp=0_12_5_96|ProductSearchResult} document // eslint-disable-line
 *
 * @returns {module:types.ProductSearch}
 */
/* eslint-disable camelcase */
const parseProductSearch = ({
    count,
    hits = [],
    query,
    refinements = [],
    selected_sorting_option,
    selected_refinements,
    sorting_options,
    start,
    total,
}) => ({
    count,
    filters: refinements.map((refinement) => parseFilters(refinement)),
    query,
    results: hits.map((hit) => parseProductSearchResult(hit)),
    selectedFilters: selected_refinements,
    selectedSortingOption: selected_sorting_option,
    sortingOptions: sorting_options,
    start,
    total
})
/* eslint-enable camelcase */
 
/**
 * Takes a OCAPI Variant object and parses it into a commerce-integrations Variation type.
 * @param {Object} data a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/Variant.html|Variant} document
 *
 * @returns {Promise<module:types.Variation>}
 */
/* eslint-disable camelcase */
const parseVariation = ({
    product_id,
    price,
    orderable,
    variation_values
}) => ({
    id: product_id,
    price,
    orderable,
    values: variation_values
})
/* eslint-enable camelcase */
 
/**
 * Takes a OCAPI ImageGroup object and parses it into a commerce-integrations ImageSet type.
 * @param {Object} data a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/ImageGroup.html|ImageGroup} document
 *
 * @returns {Promise<module:types.ImageSet>}
 */
/* eslint-disable camelcase */
const parseImageSet = ({
    images,
    view_type,
    variation_attributes
}) => ({
    images: images.map(parseImage),
    variationProperties: variation_attributes && variation_attributes.map(parseVariationProperty),
    sizeType: view_type
})
/* eslint-enable camelcase */
 
/**
 * Takes a OCAPI Product object and parses it into a commerce-integrations Product type.
 * @param {Object} data a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/Product.html|Product} document
 *
 * @returns {Promise<module:types.Product>}
 */
/* eslint-disable camelcase */
const parseProduct = ({
    id,
    image_groups = [],
    name,
    long_description,
    primary_category_id,
    brand,
    min_order_quantity,
    step_quantity,
    upc,
    unit,
    price,
    prices,
    variants = [],
    variation_attributes = [],
    variation_values = {}
}) => ({
    id,
    name,
    imageSets: image_groups.map(parseImageSet),
    description: long_description,
    categoryId: primary_category_id,
    brand,
    minimumOrderQuantity: min_order_quantity,
    stepQuantity: step_quantity,
    upc,
    unit,
    price,
    prices,
    variations: variants.map(parseVariation),
    variationProperties: variation_attributes.map(parseVariationProperty),
    variationValues: variation_values
})
/* eslint-enable camelcase */
 
/* eslint-disable camelcase */
const parseCustomer = ({
    customer_id,
    first_name,
    last_name, email
}) => ({
    id: customer_id,
    firstName: first_name,
    lastName: last_name,
    email
})
/* eslint-enable camelcase */
 
const transformOrderAddress = (shippingAddress) => ({
    first_name: shippingAddress.firstName,
    last_name: shippingAddress.lastName,
    phone: shippingAddress.phone,
    address1: shippingAddress.addressLine1,
    address2: shippingAddress.addressLine2,
    country_code: shippingAddress.countryCode,
    state_code: shippingAddress.stateCode,
    city: shippingAddress.city,
    postal_code: shippingAddress.postalCode,
})
 
const transformPayment = (payment) => ({
    amount: payment.amount,
    payment_card: {
        issue_number: payment.paymentDetails.number,
        security_code: payment.paymentDetails.ccv,
        holder: payment.paymentDetails.holderName,
        card_type: payment.paymentDetails.type,
        expiration_month: payment.paymentDetails.expiryMonth,
        expiration_year: payment.paymentDetails.expiryYear
    },
    payment_method_id: payment.methodId
})
 
const transformShippingMethod = (shippingMethod) => ({
    id: shippingMethod.id
})
 
const transformCustomerInformation = (customerInformation) => ({
    customer_id: customerInformation.customerId,
    email: customerInformation.email
})
 
const transformCartItem = (cartItem) => ({
    product_id: cartItem.productId,
    quantity: cartItem.quantity
})
 
const transformCart = (cart) => {
    const transformedCart = {}
    const {
        billingAddress,
        customerInformation,
        items,
        payments,
        shippingAddress
    } = cart
 
    // Transform our mobify api schema to salesforce ocapi schema
    Iif (billingAddress) { transformedCart.billing_address = transformOrderAddress(billingAddress) }
    Iif (customerInformation) { transformedCart.customer_info = transformCustomerInformation(customerInformation) }
    Iif (items) { transformedCart.product_items = items.map(transformCartItem) }
    Iif (payments) { transformedCart.payment_instruments = payments.map(transformPayment) }
    Iif (shippingAddress) {
        transformedCart.shipments = [{
            shipment_id: 'me',
            shipping_address: transformOrderAddress(shippingAddress)
        }]
    }
 
    return transformedCart
}
 
/**
 * A connector for the Salesforce Commerce Cloud API.
 *
 * @implements {module:interfaces.CommerceConnector}
 * @implements {module:interfaces.ParserHooks}
 */
export class SalesforceConnector {
 
    /**
     * @param client {ShopApi.ApiClient}
     */
    constructor(client) {
        this.client = client
    }
 
    /**
     * Given a configuration in the form of a plain object, this method returns
     * a new SalesforceConnector instance.
     *
     * @param {Object} config {@link https://github.com/mobify/commercecloud-ocapi-client/blob/develop/src/ApiClient.js#L44}
     * @returns {module:sfcc.SalesforceConnector} The new SalesforceConnector instance.
     */
    static fromConfig(config) {
        return new this.prototype.constructor(new ShopApi.ApiClient(config))
    }
 
    /**
     * @inheritDoc
     */
    createCart(oldCart) {
        const api = new ShopApi.BasketsApi(this.client)
        const options = {}
 
        // Append the cart to the body.
        Eif (oldCart) {
            options.body = transformCart(oldCart)
        }
 
        return api.postBaskets(options)
            .then((data) => this.parseCart(data))
            .catch(() => { throw new errors.ServerError('Could Not Create Cart') })
    }
 
    /**
     * @inheritDoc
     */
    getCart(cartId) {
        if (!cartId) { throw new errors.InvalidArgumentError(`Parameter 'cartId' is required`) }
 
        const api = new ShopApi.BasketsApi(this.client)
 
        return api.getBasketsByID(cartId)
            .then((data) => this.parseCart(data))
            .catch(() => { throw new errors.NotFoundError('Cart Not Found') })
    }
 
    /**
     * @inheritDoc
     */
    deleteCart(cartId) {
        Iif (!cartId) { throw new errors.InvalidArgumentError(`Parameter 'cartId' is required`) }
 
        const api = new ShopApi.BasketsApi(this.client)
        return api.deleteBasketsByID(cartId)
            .catch(() => { throw new errors.ServerError('Could Not Delete Cart') })
    }
 
    /**
     * @inheritDoc
     */
    addCartItem(cart, cartItem) {
        Iif (!cart) { throw new errors.InvalidArgumentError(`Parameter 'cart' is required`) }
        Iif (!cartItem) { throw new errors.InvalidArgumentError(`Parameter 'cartItem' is required`) }
 
        const api = new ShopApi.BasketsApi(this.client)
 
        cartItem = transformCartItem(cartItem) // eslint-disable-line no-undef
 
        return api.postBasketsByIDItems(cart.id, [cartItem])
            .then((data) => this.parseCart(data))
            .catch(() => { throw new errors.ServerError('Could Not Add Cart Item') })
    }
 
    /**
     * @inheritDoc
     */
    removeCartItem(cart, cartItemId) {
        Iif (!cart) { throw new errors.InvalidArgumentError(`Parameter 'cart' is required`) }
        Iif (!cartItemId) { throw new errors.InvalidArgumentError(`Parameter 'cartItemId' is required`) }
 
        const api = new ShopApi.BasketsApi(this.client)
 
        return api.deleteBasketsByIDItemsByID(cart.id, cartItemId)
            .then((data) => this.parseCart(data))
            .catch(() => { throw new errors.ServerError('Could Not Remove Cart') })
    }
 
    /**
     * @inheritDoc
     */
    updateCartItem(cart, cartItem) {
        Iif (!cart) { throw new errors.InvalidArgumentError(`Parameter 'cart' is required`) }
        Iif (!cartItem) { throw new errors.InvalidArgumentError(`Parameter 'cartItem' is required`) }
 
        const api = new ShopApi.BasketsApi(this.client)
        const cartItemId = cartItem.id
 
        cartItem = transformCartItem(cartItem) // eslint-disable-line no-undef
 
        return api.patchBasketsByIDItemsByID(cart.id, cartItemId, cartItem)
            .then((data) => this.parseCart(data))
            .catch(() => { throw new errors.ServerError('Could Not Update Cart') })
    }
 
    /**
     * @inheritDoc
     */
    setShippingAddress(cart, shippingAddress) {
        if (!cart) { throw new errors.InvalidArgumentError(`Parameter 'cart' is required`) }
        if (!shippingAddress) { throw new errors.InvalidArgumentError(`Parameter 'shippingAddress' is required`) }
 
        const api = new ShopApi.BasketsApi(this.client)
 
        // Transform Mobify schema into OCAPI schema
        shippingAddress = transformOrderAddress(shippingAddress) // eslint-disable-line no-undef
 
        return api.putBasketsByIDShipmentsByIDShippingAddress(cart.id, 'me', shippingAddress)
            .then((data) => this.parseCart(data))
            .catch(() => { throw new errors.ServerError('Could Not Set Shipping Address') })
    }
 
    /**
     * @inheritDoc
     */
    setBillingAddress(cart, billingAddress) {
        if (!cart) { throw new errors.InvalidArgumentError(`Parameter 'cart' is required`) }
        if (!billingAddress) { throw new errors.InvalidArgumentError(`Parameter 'billingAddress' is required`) }
 
        const api = new ShopApi.BasketsApi(this.client)
 
        // Transform Mobify schema into OCAPI schema
        billingAddress = transformOrderAddress(billingAddress) // eslint-disable-line no-undef
 
        return api.putBasketsByIDBillingAddress(cart.id, {body: billingAddress})
            .then((data) => this.parseCart(data))
            .catch(() => { throw new errors.ServerError('Could Not Set Billing Address') })
    }
 
    /**
     * @inheritDoc
     */
    setPayment(cart, payment) {
        if (!cart) { throw new errors.InvalidArgumentError(`Parameter 'cart' is required`) }
        if (!payment) { throw new errors.InvalidArgumentError(`Parameter 'payment' is required`) }
 
        const api = new ShopApi.BasketsApi(this.client)
 
        // Only allow one payment of a given type. If there is already a type in the cart,
        // then get it's id so we can `patch` it.
        const {payments = []} = cart
        const oldPayment = payments.find(({methodId}) => (methodId === payment.methodId))
 
        // Transform Mobify schema into OCAPI schema
        payment = transformPayment(payment) // eslint-disable-line no-undef
 
        const request = !oldPayment ?
            api.postBasketsByIDPaymentInstruments(cart.id, payment) :
            api.patchBasketsByIDPaymentInstrumentsByID(cart.id, oldPayment.id, payment)
 
        return request
            .then((data) => this.parseCart(data))
            .catch(() => { throw new errors.ServerError('Could Not Add Payment') })
    }
 
    /**
     * @inheritDoc
     */
    login(username, password) {
        const type = (username && password) ? 'credentials' : 'guest'
        const api = new ShopApi.CustomersApi(this.client)
 
        const authParam = type === 'credentials' ?
            {authorization: `Basic ${btoa(`${username}:${password}`)}`} :
            undefined
 
        // Clear authorization from previous login
        delete api.apiClient.defaultHeaders.authorization
 
        return api.postCustomersAuth({type}, authParam)
            .then((data) => this.parseCustomer(data))
            .catch(() => {
                throw new errors.ForbiddenError('Login error.')
            })
    }
 
    /**
     * @inheritDoc
     */
    logout() {
        const api = new ShopApi.CustomersApi(this.client)
        return api.deleteCustomersAuth()
            .then(() => {
                // Clear authorization from current login
                delete api.apiClient.defaultHeaders.authorization
                return undefined
            })
            .catch(() => {
                throw new errors.ServerError('Logout error.')
            })
    }
 
    /**
     * @inheritDoc
     */
    getShippingMethods(cart) {
        if (!cart) { throw new errors.InvalidArgumentError(`Parameter 'cart' is required`) }
 
        const api = new ShopApi.BasketsApi(this.client)
 
        return api.getBasketsByIDShipmentsByIDShippingMethods(cart.id, 'me')
            .then(({applicable_shipping_methods = []}) => (applicable_shipping_methods.map(this.parseShippingMethod))) // eslint-disable-line camelcase
            .catch(() => { throw new errors.ServerError('Could Not Get Shipping Methods') })
    }
 
    /**
     * @inheritDoc
     */
    refreshSession() {
        const api = new ShopApi.CustomersApi(this.client)
 
        return api.postCustomersAuth({type: 'refresh'})
            .then((data) => this.parseCustomer(data))
            .catch(() => {
                throw new errors.ForbiddenError('Unable to refresh session.')
            })
    }
 
    /**
     * @inheritDoc
     */
    getPaymentMethods(cart) {
        if (!cart) { throw new errors.InvalidArgumentError(`Parameter 'cart' is required`) }
 
        const api = new ShopApi.BasketsApi(this.client)
 
        return api.getBasketsByIDPaymentMethods(cart.id, 'me')
            .then(({applicable_payment_methods = []}) => (applicable_payment_methods.map(this.parsePaymentMethod))) // eslint-disable-line camelcase
            .catch(() => { throw new errors.ServerError('Could Not Get Payment Methods') })
    }
 
    /**
     * @inheritDoc
     */
    setShippingMethod(cart, shippingMethod) {
        if (!cart) { throw new errors.InvalidArgumentError(`Parameter 'cart' is required`) }
        if (!shippingMethod) { throw new errors.InvalidArgumentError(`Parameter 'shippingMethod' is required`) }
 
        const api = new ShopApi.BasketsApi(this.client)
 
        // Transform Mobify schema into OCAPI schema
        shippingMethod = transformShippingMethod(shippingMethod) // eslint-disable-line no-undef
 
        return api.putBasketsByIDShipmentsByIDShippingMethod(cart.id, 'me', shippingMethod)
            .then((data) => this.parseCart(data))
            .catch(() => { throw new errors.ServerError('Could Not Set Shipping Method') })
    }
 
    /**
     * @inheritDoc
     */
    setCustomerInformation(cart, customerInformation) {
        Iif (!cart) { throw new errors.InvalidArgumentError(`Parameter 'cart' is required`) }
        Iif (!customerInformation) { throw new errors.InvalidArgumentError(`Parameter 'customerInformation' is required`) }
 
        const api = new ShopApi.BasketsApi(this.client)
 
        // Transform Mobify schema into OCAPI schema
        customerInformation = transformCustomerInformation(customerInformation) // eslint-disable-line no-undef
 
        return api.putBasketsByIDCustomer(cart.id, customerInformation)
            .then((data) => this.parseCart(data))
            .catch(() => { throw new errors.ServerError('Could Not Set Customer Information') })
    }
 
    /**
     * Parse a cart item
     */
    parseCartItem(data) {
        return {
            id: data.item_id,
            baseItemPrice: data.base_price,
            baseLinePrice: data.base_price * data.quantity,
            productId: data.product_id,
            productName: data.product_name,
            quantity: data.quantity,
            itemPrice: data.price_after_order_discount / data.quantity,
            linePrice: data.price_after_order_discount
        }
    }
 
    /**
     * Parse an order address
     */
    parseOrderAddress(data) {
        return {
            firstName: data.first_name,
            lastName: data.last_name,
            phone: data.phone,
            addressLine1: data.address1,
            addressLine2: data.address2,
            city: data.city,
            countryCode: data.country_code,
            stateCode: data.state_code,
            postalCode: data.postal_code
        }
    }
 
    /**
     * Parse customer information
     */
    parseCustomerInformation(data) {
        return {
            customerId: data.customer_id,
            email: data.email
        }
    }
 
    /**
     * Parse a shipping method
     */
    parseShippingMethod(data) {
        return {
            id: data.id,
            cost: data.price,
            label: `${data.name} - ${data.description}`
        }
    }
 
    /**
     * Parse a payment method
     */
    parsePaymentMethod(data) {
        const {cards} = data
        const method = {
            id: data.id,
            name: data.name
        }
 
        if (cards) {
            method.types = cards.map((card) => ({
                id: card.card_type,
                name: card.name
            }))
        }
 
        return method
    }
 
    /**
     * Parse a payment.
     */
    parsePayment(data) {
        return {
            id: data.payment_instrument_id,
            amount: data.amount,
            methodId: data.payment_method_id,
            paymentDetails: {
                type: data.payment_card.card_type,
                expiryMonth: data.payment_card.expiration_month,
                expiryYear: data.payment_card.expiration_year,
                holderName: data.payment_card.holder,
                number: data.payment_card.issue_number,
                maskedNumber: data.payment_card.masked_number
            }
        }
    }
 
    /**
    * Parse a cart
    */
    parseCart(data) {
        /* eslint-disable camelcase */
        const {
            billing_address,
            shipments = [],
            payment_instruments = [],
            product_items = [],
            customer_info
        } = data
        let shippingAddress
        let selectedShippingMethodId
 
        const shipment = shipments.length ? shipments[0] : undefined
        Eif (shipment) {
            shippingAddress = shipment.shipping_address ?
                this.parseOrderAddress(shipment.shipping_address) :
                undefined
 
            selectedShippingMethodId = shipment.shipping_method ? shipment.shipping_method.id : undefined
        }
        const billingAddress = billing_address ? this.parseOrderAddress(billing_address) : undefined
 
        const payments = payment_instruments.length ? payment_instruments.map(this.parsePayment) : []
        const items = product_items.length ? product_items.map(this.parseCartItem) : []
 
        const id = data.basket_id
        const customerInformation = customer_info ? this.parseCustomerInformation(customer_info) : undefined
        const subtotal = data.product_sub_total
        const discounts = (data.order_price_adjustments || []).reduce((acc, curr) => (acc + curr.price), 0)
        const shipping = data.shipping_total
        const tax = data.tax_total || data.merchandize_total_tax
        const total = data.order_total || data.product_total
 
        return {
            id,
            discounts,
            billingAddress,
            customerInformation,
            items,
            payments,
            shippingAddress,
            selectedShippingMethodId,
            shipping,
            subtotal,
            tax,
            total
        }
        /* eslint-enable camelcase */
    }
 
    /**
    * @inheritDoc
    */
    getDefaultHeaders() {
        return Object.assign({}, this.client.defaultHeaders)
    }
 
    /**
    * @inheritDoc
    */
    setDefaultHeaders(headers) {
        this.client.defaultHeaders = Object.assign({}, headers)
    }
 
    /**
    * @inheritDoc
    */
    getCustomer(id, opts) {
        const api = new ShopApi.CustomersApi(this.client)
        const defaultOptions = {
            expand: ['addresses', 'paymentinstruments'],
            allImages: true
        }
        const options = {
            ...defaultOptions,
            ...opts
        }
        return api.getCustomersByID(id, options)
            .then((data) => this.parseCustomer(data))
    }
 
    /**
    * Takes a OCAPI Customer object and parses it into a commerce-integrations Customer type.
    * @param {Object} data a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/Customer.html|Customer} document
    *
    * @returns {Promise<module:types.Customer>}
    */
    parseCustomer(data) {
       return parseCustomer(data)
   }
 
    /**
     * @inheritDoc
     */
     getProduct(id, opts = {}) {
         const api = new ShopApi.ProductsApi(this.client)
         const defaultOptions = {
             expand: ['availability', 'prices', 'variations', 'images'],
             allImages: true
         }
         const options = {
             ...defaultOptions,
             ...opts
         }
         return api.getProductsByID(id, options)
            .then((data) => this.parseProduct(data))
            .catch(() => {
                throw new errors.NotFoundError('Product Not Found')
            })
    }
 
    /**
     * @inheritDoc
     */
    getProducts(ids, opts = {}) {
        Iif (!ids || ids.length <= 0) { throw new Error('Please specify list of product ids to get.') }
 
        const api = new ShopApi.ProductsApi(this.client)
        const defaultOptions = {
            expand: ['availability', 'prices', 'variations', 'images'],
            allImages: true
        }
        const options = {
            ...defaultOptions,
            ...opts
        }
        return api.getProductsByIDs(ids, options)
            .then(({count, data = [], total}) => {
                return {
                    count,
                    data: data.map(this.parseProduct),
                    total
                }
            })
    }
 
    /**
     * Takes a OCAPI Product object and parses it into a commerce-integrations Product type.
     * @param {Object} data a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/Product.html|Product} document
     *
     * @returns {Promise<module:types.Product>}
     */
    parseProduct(data) {
        return parseProduct(data)
    }
 
    /**
     * @inheritDoc
     */
    searchProducts(productSearchRequest, opts = {}) {
        let searchRequest = transformProductSearchRequest(productSearchRequest)
        const api = new ShopApi.ProductSearchApi(this.client)
 
        const defaultOptions = {
            expand: ['availability', 'prices', 'variations', 'images']
        }
 
        // Assign options to new object. This allows the user to override
        // and defaults we set.
        searchRequest = {
            ...searchRequest,
            ...defaultOptions,
            ...opts
        }
 
        return api.getProductSearch(searchRequest)
            .then((data) => this.parseSearchProducts(data, searchRequest))
    }
 
    /**
     * Takes a OCAPI ProductSearchResult object and parses it into a commerce-integrations
     * ProductSearch type.
     *
     * @param {Object} data a OCAPI
     * {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/ProductSearchResult.html?cp=0_12_5_96|ProductSearchResult} document
     *
     * @returns {Promise<module:types.ProductSearch>}
     */
    parseSearchProducts(data, searchParams) {
        return parseProductSearch(data, searchParams)
    }
 
    /**
     * @inheritDoc
     */
    getStore(id) {
        const api = new ShopApi.StoresApi(this.client)
 
        return api.getStoresByID(id)
            .then((data) => this.parseGetStore(data))
    }
 
    /**
     * Takes a OCAPI Store object and parses it into a commerce-integrations Store type.
     * @param {Object} data a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/Store.html|Store} document
     *
     * @returns {Promise<module:types.Store>}
     */
    parseGetStore(data) {
        const d = data
        return {
            addressLine1: d.address1,
            addressLine2: d.address2,
            city: d.city,
            country: d.country_code,
            email: d.email,
            id: d.id,
            name: d.name,
            phone: d.phone ? d.phone.replace(new RegExp('[(]|[)]|[.]|[ ]|[-]|[#]|[x]', 'g'), '') : undefined,
            postalCode: d.postal_code,
            hours: d.store_hours,
            images: d.image ? {src: d.image, alt: d.name} : undefined
        }
    }
 
    /**
     * This function will take product search request as we use them in the commerce-integrations
     * and output them into a format usable by the specific connector (ocapi).
     */
    transformSearchStoreParams(searchParams) {
        const sp = searchParams
        return {
            count: sp.count > 0 ? sp.count : 20,
            start: sp.start > 0 ? sp.start : 0,
            distanceUnit: 'km', // only 'mi' and 'km' supported
            latitude: sp.latlon.latitude,
            longitude: sp.latlon.longitude
        }
    }
 
    /**
     * @inheritDoc
     */
    searchStores(storeSearchRequest, opts = {}) { // eslint-disable-line no-unused-vars
        if (isNaN(storeSearchRequest.latlon.latitude) || isNaN(storeSearchRequest.latlon.longitude)) {
            throw new Error('Provide Latitude and Longitude coordinates')
        }
 
        const api = new ShopApi.StoresApi(this.client)
        const searchRequest = this.transformSearchStoreParams(storeSearchRequest)
        return api.getStores(searchRequest)
            .then((data) => {
                Iif (!data.data) {
                    throw new Error('No stores found')
                }
                return this.parseSearchStores(data)
            })
    }
 
    parseSearchStores(data) {
        const d = data
        return {
            count: d.count,
            start: d.start,
            total: d.total,
            stores: d.data ? d.data.map((store) => this.parseGetStore(store)) : undefined
        }
    }
 
    /**
     * @inheritDoc
     */
    getCategory(id, options = {}) {
        const api = new ShopApi.CategoriesApi(this.client)
        return api.getCategoriesByID(id, options)
            .then((data) => this.parseCategory(data))
    }
 
    /**
     * @inheritDoc
     */
    getCategories(ids, options = {}) {
        const api = new ShopApi.CategoriesApi(this.client)
        return api.getCategoriesByIDs(ids, options)
            .then(({
                data,
                count,
                total
            }) => ({
                categories: this.parseCategories(data),
                count,
                total
            }))
    }
 
    /**
     * Takes an array of OCAPI Category objects and parses it into an
     * commerce-integrations Category type.
     * @param {Object[]} categories an array of OCAPI {@link https://mobify.github.io/commercecloud-ocapi-client/module-models_Category.html|Category} document
     *
     * @returns {Array<module:types.Category>}
     */
    parseCategories(categories) {
        return categories.map((c) => this.parseCategory(c))
    }
 
    /**
     * Takes a OCAPI Category objects and parses it into an
     * commerce-integrations Category type.
     * @param {Object[]} categories an OCAPI {@link https://mobify.github.io/commercecloud-ocapi-client/module-models_Category.html|Category} document
     *
     * @returns {module:types.Category}
     */
    /* eslint-disable camelcase */
    parseCategory({
        id,
        name,
        page_description,
        categories: subCategories,
        image: backgroundImage,
        thumbnail: thumbnailImage
    }) {
        const imageAttributes = {
            alt: name,
            description: page_description,
            title: name
        }
        const category = {
            id,
            name,
            description: page_description,
            thumbnailImage: thumbnailImage && this.parseImage(thumbnailImage, imageAttributes),
            backgroundImage: backgroundImage && this.parseImage(backgroundImage, imageAttributes)
        }
 
        if (subCategories) {
            category.categories = this.parseCategories(subCategories)
        }
 
        return clean(category)
    }
    /* eslint-enable camelcase */
 
    /**
     * Takes an image url and its attributes and return an
     * commerce-integrations Image type.
     * @param {string} imageUrl
     * @param {Object} attributes additional attributes of an image
     *
     * @returns {Promise<module:types.Image>}
     */
    parseImage(imageUrl, attributes) {
        return {
            ...attributes,
            src: imageUrl
        }
    }
}