All files / src hybris.js

85.6% Statements 309/361
72.38% Branches 207/286
84.87% Functions 129/152
91.82% Lines 292/318

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 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197              68x                     26x 26x 26x 26x                               9x 9x 9x         9x 5x             9x       9x         9x 9x                     1x         1x 1x             2x 2x   2x 2x             2x       2x         2x 2x                                                             67x                   1x             12x 12x 12x             12x 12x                       5x 5x   5x 5x                 5x 5x       5x                           530x   530x                       35x   35x   35x     35x                             5x   5x 5x 530x   5x       5x   5x 5x     5x 70x                                 5x 5x   30x                       3x 3x 3x             2x   1x   2x   1x                                 324x   324x   324x                             324x         324x 324x     324x             10x   10x 10x           10x           10x 10x 20x   15x       15x   15x         10x         5x   5x   58x   21x 5x   5x     5x 5x 5x 10x           5x   5x           5x               3x   8x   3x   8x 3x                               21x 21x   42x                 63x   522x 153x                                                             5x 5x 21x     5x   21x     5x 42x   74x     63x 2844x   63x 621x   63x 621x   63x   181x   53x 16x               10x                       63x     5x   21x         42x 42x       21x         5x                                     1x 1x   1x                     18x   18x 126x         18x                   18x 18x 18x           49x             30x             2x 2x 2x 2x                           4x 2x     2x 2x 2x   2x 1x   1x         1x     1x 1x 1x 1x 1x 1x       1x         1x       17x         33x               33x 33x             4x 4x 4x   4x 1x                 3x   4x                   9x 9x   9x 6x 3x             3x   3x 3x             17x 17x     17x 17x   17x                                                     6x 6x   6x                               2x                     6x 6x                                     8x 8x                                         2x     14x               8x                                                                   5x                         5x 5x                                   3x 3x   3x   3x   3x 3x 3x               2x 2x   2x   2x 2x 2x               2x 2x   2x   2x 2x 2x 2x                     6x 6x   6x   6x       6x 2x     4x   4x   4x         4x   1x     3x 3x     4x                     2x 2x   2x 2x   2x   1x 1x   1x             2x   2x   2x 2x             2x 2x   2x 2x   2x 2x                             5x 5x   5x   5x       5x 2x 2x     3x     3x 1x   1x 1x           2x 1x       1x   1x 1x 1x                       3x 3x   3x 1x     2x     2x   2x       2x 1x       1x   1x     1x     2x   2x 2x                           2x 2x 2x        
/** @module hybris */
 
import * as hybris from 'hybris-occ-client'
import * as errors from './errors'
import superagent from 'superagent'
 
 
const clone = (x) => JSON.parse(JSON.stringify(x))
 
/**
 * A connector for the Hybris API.
 *
 * @implements {module:interfaces.CommerceConnector}
 * @implements {module:interfaces.ParserHooks}
 */
export class HybrisConnector {
 
    constructor({client, catalogId, catalogVersionId, authentication}) {
        this.client = client
        this.catalogId = catalogId
        this.catalogVersionId = catalogVersionId
        this.authentication = authentication
    }
 
    static fromConfig(config) {
        return new this.prototype.constructor({
            client: new hybris.ApiClient(config.clientConfig),
            catalogId: config.catalogId,
            catalogVersionId: config.catalogVersionId,
            authentication: config.authentication
        })
    }
 
    /**
     * @inheritDoc
     */
    login(username, password) {
        const isRegisteredUser = username && password
        const auth = this.authentication
        const body = {
            client_id: auth.clientId,
            client_secret: auth.clientSecret,
            grant_type: 'client_credentials'
        }
        if (isRegisteredUser) {
            Object.assign(body, {
                grant_type: 'password',
                username,
                password
            })
        }
 
        return superagent.post(auth.authorizationUrl)
            .set('Content-Type', 'application/x-www-form-urlencoded')
            .send(body)
            .then((res) => {
                const updatedAuth = {
                    accessToken: res.body.access_token,
                    expiresIn: res.body.expires_in,
                    refreshToken: res.body.refresh_token
                }
                Object.assign(this.client.authentications.auth, updatedAuth)
                return isRegisteredUser ? this.getCustomer('current') : this.getCustomer('anonymous')
            })
            .catch(() => {
                throw new errors.ForbiddenError('Login failed')
            })
    }
 
    /**
     * @inheritDoc
     */
    logout() {
        const invalidatedAuth = {
            accessToken: undefined,
            expiresIn: undefined,
            refreshToken: undefined
        }
        Object.assign(this.client.authentications.auth, invalidatedAuth)
        return Promise.resolve(undefined)
    }
 
    /**
     * @inheritDoc
     */
    refreshSession() {
        const refreshToken = this.client.authentications.auth.refreshToken
        const grantType = refreshToken ? 'refresh_token' : 'client_credentials'
 
        const auth = this.authentication
        const body = {
            client_id: auth.clientId,
            client_secret: auth.clientSecret,
            grant_type: grantType,
            refresh_token: refreshToken
        }
 
        return superagent.post(auth.authorizationUrl)
            .set('Content-Type', 'application/x-www-form-urlencoded')
            .send(body)
            .then((res) => {
                const newAuth = {
                    accessToken: res.body.access_token,
                    expiresIn: res.body.expires_in,
                    refreshToken: res.body.refresh_token
                }
                Object.assign(this.client.authentications.auth, newAuth)
                return (refreshToken ?
                    this.getCustomer('current') :
                    this.getCustomer('anonymous')
                )
            })
            .catch(() => {
                throw new errors.ForbiddenError('Failed To Refresh Session')
            })
    }
 
    /**
     * @inheritDoc
     */
     getDefaultHeaders() {
         return Object.assign({}, this.client.defaultHeaders)
     }
 
    /**
    * @inheritDoc
    */
    setDefaultHeaders(headers) {
        this.client.defaultHeaders = Object.assign({}, headers)
    }
 
    /**
     * Get current authentications object, which can be used to
     * save/restore auth state, eg. for server-side usage.
     *
     * @return {Object}
     */
    getAuthentications() {
        return clone(this.client.authentications)
    }
 
    /**
     * Set the current authentications object, as returned from getAuthentications.
     * Use to save/restore auth state, eg. for server-side usage.
     *
     * @param {Object} authentications
     */
    setAuthentications(authentications) {
        this.client.authentications = clone(authentications)
    }
 
    /**
     * @inheritDoc
     */
    getCustomer(id, opts = {}) {
        const api = new hybris.UsersApi(this.client)
        return api.getUser(id, {fields: 'FULL', ...opts})
            .then((res) => this.parseCustomer(res))
    }
 
    /**
     * @inheritDoc
     */
    parseCustomer(data) {
        const d = data
        return {
            id: d.uid === 'anonymous' ? 'anonymous' : 'current',
            firstName: d.firstName,
            lastName: d.lastName,
            email: d.defaultAddress ? d.defaultAddress.email : undefined
        }
    }
 
    /**
     * @inheritDoc
     */
    searchProducts(query, opts = {}) {
        const searchRequest = this.transformSearchParams(query)
        const api = new hybris.ProductsApi(this.client)
 
        return api.getProductSearch(searchRequest, opts)
            .then((data) => this.parseSearchProducts(data, query))
    }
 
    transformSearchParams(params) {
        const {
            count = 20,
            start = 0,
            sort = 'relevance',
            filters
        } = params
        return {
            query: [].concat(...[
                ['', sort],
                Object.keys(filters)
                    .filter((key) => !['categoryId', 'query'].includes(key))
                    .filter((key) => Boolean(filters[key]))
                    .map((key) => `${key}:${filters[key]}`),
                [`allCategories:${filters.categoryId}`],
            ]).join(':'),
            pageSize: count,
            currentPage: start / count,
            sort,
            fields: 'FULL'
        }
    }
 
    parseFilterValue({count, name, query}) {
        // Parse query string to get filter value.
        const value = query.query.value.split(':').slice(-1)[0]
 
        return {
            count,
            label: name,
            value
        }
    }
 
    parseFilter({name, values}) {
        // Get the filter identifier from the first values query string. There should
        // always be a value or else the filter wouldn't be listed, but to be sure
        // return undefiend if there isn't one.
        let filterId
        const firstValue = values[0]
 
        Eif (firstValue) {
            // Parse query string to get filter identifier.
            filterId = firstValue.query.query.value.split(':').slice(-2)[0]
        }
 
        return {
            id: filterId,
            label: name,
            values: values.map(this.parseFilterValue.bind(this))
        }
    }
 
    parseSearchProducts(data) {
        const {
            products = [],
            sorts = [],
            pagination,
            currentQuery,
            facets = [],
            breadcrumbs = [],
        } = data
 
        const getFilterCrumbs = () => {
            const selectedFilterVals = ([].concat(
                ...facets.map((filter) => filter.values.filter((f) => f.selected))))
 
            const selectedBreadcrumbs = ([].concat(
                ...selectedFilterVals.map(
                    (fv) => breadcrumbs.filter((bc) => bc.facetValueName === fv.name))))
 
            const allCatsCrumb = breadcrumbs.find((bc) => bc.facetCode === 'allCategories')
 
            allCatsCrumb && selectedBreadcrumbs.push(allCatsCrumb)
            return selectedBreadcrumbs
        }
 
        return {
            results: products.map(({stock = {}, images = [], ...product}) => ({
                available: stock.stockLevelStatus === 'inStock',
                productId: product.code,
                productName: product.name,
                link: product.url,
                defaultImage: images[0] && {
                    alt: product.name,
                    src: images[0].url
                },
                price: product.price.value
            })),
            query: currentQuery.query.value || '',
            count: pagination.pageSize,
            start: pagination.currentPage * pagination.pageSize,
            total: pagination.totalResults,
            filters: facets.map(this.parseFilter.bind(this)),
            selectedFilters: getFilterCrumbs().reduce((obj, curr) => {
                obj[curr.facetCode] = curr.facetValueCode
                return obj
            }, {}),
            sortingOptions: sorts.map(({code, name}) => ({
                id: code,
                label: name
            })),
            selectedSortingOption: pagination.sort
        }
    }
 
    /**
     * @inheritDoc
     */
    getCategory(id, options = {}) {
        const api = new hybris.CatalogsApi(this.client)
        return api.getCategory(this.catalogId, this.catalogVersionId, id, options)
            .then((data) => this.parseCategory(data))
    }
 
    /**
     * @inheritDoc
     */
    getCategories(ids, options = {}) {
        const getCategoryPromises = ids.map((id) => this.getCategory(id, options).catch(() => null))
 
        return Promise.all(getCategoryPromises)
            .then((categories) => {
                const validCategories = categories.filter((category) => !!category)
 
                return {
                    data: validCategories,
                    count: Object.keys(categories).length,
                    total: ids.length
                }
            })
    }
 
    /**
     * 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/hybris-occ-client/module-models_CategoryHierarchy.html|Category} document
     *
     * @returns {Promise<module:types.Category>}
     */
    /* eslint-disable camelcase */
    parseCategories(categories) {
        const parsedCategories = []
 
        categories.forEach((category) => parsedCategories.push(this.parseCategory(category)))
 
        return parsedCategories
    }
 
    /**
     * Takes an OCAPI Category objects and parses it into an
     * commerce-integrations Category type.
     * @param {Object[]} categories an OCAPI {@link https://mobify.github.io/hybris-occ-client/module-models_CategoryHierarchy.html|Category} document
     *
     * @returns {Promise<module:types.Category>}
     */
    parseCategory({
        id,
        name,
        subcategories
    }) {
        const category = {
            id,
            name
        }
 
        Eif (subcategories) {
            category.categories = this.parseCategories(subcategories)
        }
 
        return category
    }
 
    /**
     * @inheritDoc
     */
    getProduct(id, opts = {}) {
        let options = {}
 
        const api = new hybris.ProductsApi(this.client)
        const defaultOptions = {
            fields: 'FULL'
        }
 
        // Assign options to new object. This allows the user to override
        // the defaults we set.
        options = {
            ...defaultOptions,
            ...opts
        }
 
        // Get the base product by creating a promise chain recursively.
        const productCache = []
        const getBaseProduct = (id, options) => (
            api.getProduct(id, options)
                .then((product) => {
                    const {baseProduct} = product
 
                    // Maintain a cache of all products requested in this command.
                    // It will be used lated to de-dup any fetches.
                    productCache.push(product)
 
                    return baseProduct ?
                        getBaseProduct(baseProduct, options) : product
                })
        )
 
        return getBaseProduct(id, options)
            .then((baseProduct) => {
 
                // Overwrite the base product id with the id we initiality requested so it's parsed
                // out correctly later on.
                baseProduct.code = id
 
                return Promise.all(baseProduct.variantOptions.map((variantOption) => {
                    // Search product cache and return products already fetched.
                    const cachedProduct = productCache.find(({code}) => code === variantOption.code)
 
                    return cachedProduct || api.getProduct(variantOption.code, options)
                })).then((variations) => ({baseProduct, variations}))
            })
            .then(({baseProduct, variations}) => this.parseProduct(baseProduct, variations))
            .then((parsedProduct) => {
                // Get the variation values from the first product requested.
                const {baseOptions = []} = productCache[0]
                const {selected = {}} = baseOptions[0]
                const {variantOptionQualifiers = []} = selected
                const variationValues = variantOptionQualifiers.reduce((acc, {qualifier, value}) => ({
                    ...acc,
                    [qualifier]: value
                }), {})
 
                // Set the products values.
                parsedProduct.variationValues = variationValues
 
                return parsedProduct
            })
            .catch(() => {
                // TODO: Lets come up with a formal way of handling errors with it's
                // own time and things like that. We'll need to map the OCAPI errors,
                // to our own here.
                throw new Error('Product Not Found')
            })
    }
 
    /**
     * @inheritDoc
     */
    getProducts(ids, opts = {}) {
        Iif (!ids || ids.length <= 0) { throw new Error('Please specify list of product ids to get.') }
 
        const getProductPromises = ids.map((id) => this.getProduct(id, opts).catch(() => null))
 
        return Promise.all(getProductPromises)
            .then((products) => {
                const validProducts = products.filter((product) => !!product)
                return {
                    count: validProducts.length,
                    data: validProducts,
                    total: validProducts.length
                }
            })
    }
 
    /**
     * 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 */
    parseImageSets(variation) {
        const {images, variantOptions} = variation
        const {variantOptionQualifiers} = variantOptions[0]
 
        const variationProperties = variantOptionQualifiers.map(({qualifier, name, value}) => ({
            id: qualifier,
            lable: name,
            values: [{
                name: value,
                value
            }]
        }))
 
        return ['zoom', 'product', 'thumbnail'].map((type) => ({
            images: images
                .filter((image) => image.format === type)
                .map(({altText, url}) => ({
                    alt: altText,
                    description: altText,
                    src: url,
                    title: altText
                })),
            variationProperties,
            type
        }))
    }
    /* eslint-enable camelcase */
 
    /**
     * Takes a OCC Product object and parses it into a commerce-integrations Product type.
     * @param {Object} data a OCC product document
     *
     * @returns {Promise<module:types/Product>}
     */
    /* eslint-disable camelcase */
    parseProduct({
        code,
        name,
        description,
        categories,
        price,
        // images,
        variantOptions
    }, variations = []) {
 
        // Parse all the image sets. We'll use these in our return value as well
        // as for parsing property value images.
        let allImageSets = []
        variations.forEach((variation) => {
            allImageSets = [...allImageSets, ...this.parseImageSets(variation)]
        })
 
        const allVariantOptions = [
            ...variantOptions,
            ...variations.reduce((acc, {variantOptions}) => [...acc, ...variantOptions], [])
        ]
 
        const variationProperties = allVariantOptions
            .reduce((acc, variantOption) => ([...acc, ...variantOption.variantOptionQualifiers]), [])
            .reduce((acc, {qualifier, name, value}) => {
                const variationProperty = acc.find((variationOptionQualifier) => variationOptionQualifier.id === qualifier)
 
                // Lets get the first image of the correct type from the image sets.
                const variationImageSets = allImageSets
                    .filter(({variationProperties}) => (variationProperties.find(({id, values}) => (id === qualifier && values[0].value === value))))
 
                const filteredProductImageSets = variationImageSets
                    .filter(({type}) => (type === 'product'))
 
                const filteredThumbnailImageSets = variationImageSets
                    .filter(({type}) => (type === 'thumbnail'))
 
                if (variationProperty) {
 
                    const isNew = !variationProperty.values.find((v) => v.value === value)
 
                    if (isNew) {
                        variationProperty.values.push({
                            name: value,
                            value,
                            mainImage: filteredProductImageSets.length && filteredProductImageSets[0].images[0],
                            swatchImage: filteredThumbnailImageSets.length && filteredThumbnailImageSets[0].images[0],
                        })
                    }
                } else {
                    acc.push({
                        id: qualifier,
                        label: name,
                        values: [{
                            name: qualifier,
                            value,
                            mainImage: filteredProductImageSets.length && filteredProductImageSets[0].images[0],
                            swatchImage: filteredThumbnailImageSets.length && filteredThumbnailImageSets[0].images[0],
                        }]
                    })
                }
 
                return acc
            }, [])
 
        const allVariations = variations
            .map(({variantOptions}) => (
                variantOptions.map(({code, priceData, stock, variantOptionQualifiers}) => ({
                    id: code,
                    price: priceData.value,
                    orderable: stock.stockLevelStatus === 'inStock',
                    values: variantOptionQualifiers.reduce((acc, curr) => {
                        acc[curr.qualifier] = curr.value
                        return acc
                    }, {})
                }))
            ))
            .reduce((acc, curr) => ([
                ...acc,
                ...curr
            ]), [])
 
        return {
            id: code,
            name,
            imageSets: allImageSets,
            description,
            categoryId: categories.length ? categories.pop().code : undefined,
            minimumOrderQuantity: 1,
            stepQuantity: 1,
            price: price.value,
            variations: allVariations,
            variationProperties
        }
    }
    /* eslint-enable camelcase */
 
    /**
     * @inheritDoc
     */
    getStore(id) {
        const api = new hybris.StoresApi(this.client)
        return api.getStore(id, {fields: 'FULL'})
        .then((data) => {
            return this.parseGetStore({...data, id})
        })
    }
 
    /**
     * Takes a OCCAPI WeekdayOpeningDay object and parses it into a commerce-integrations Store.hours type.
     * @param {Object} hours a OCCAPI {@link https://help.hybris.com/6.7.0/api/ycommercewebservices/index.html#_weekdayopeningdaywsdto|WeekdayOpneningDay} document
     *
     * @returns {Promise<module:types.Store.hours>}
     */
    parseOpeningHours(hours) {
        const parsedHours = {}
 
        hours.forEach((h) => {
            parsedHours[h.weekDay] = {
                openingTime: h.openingTime ? h.openingTime.formattedHour : undefined,
                closingTime: h.closingTime ? h.closingTime.formattedHour : undefined
            }
        })
        return parsedHours
    }
 
    /**
     * Takes a OCCAPI PointOfService object and parses it into a commerce-integrations Store type.
     * @param {Object} data a OCCAPI {@link https://help.hybris.com/6.7.0/api/ycommercewebservices/index.html#_pointofservicewsdto|PointOfService} document
     *
     * @returns {Promise<module:types.Store>}
     */
    parseGetStore(data) {
        const d = data
        const address = d.address
        return {
            addressLine1: address ? address.line1 : undefined,
            addressLine2: address ? address.line2 : undefined,
            city: address ? address.town : undefined,
            country: address && address.country ? address.country.isocode : undefined,
            description: d.description,
            features: d.features ? d.features.entry.map((feature) => feature.value) : undefined,
            email: address ? address.email : undefined,
            name: d.name,
            phone: address && address.phone ? address.phone.replace(new RegExp('[(]|[)]|[.]|[ ]|[-]|[#]|[x]', 'g'), '') : undefined,
            postalCode: address ? address.postalCode : undefined,
            hours: this.parseOpeningHours(d.openingHours.weekDayOpeningList),
            images: d.storeImages ? d.storeImages.map((image) => {
                return {src: image.url, alt: d.name}
            }) : undefined,
            id: d.id
        }
    }
 
    transformSearchStoreParams(searchParams) {
        const sp = searchParams
        const count = sp.count > 0 ? sp.count : 20
        const start = sp.start > 0 ? sp.start : 0
        return {
            pageSize: count.toString(),
            currentPage: start.toString(),
            sort: 'relevance',
            latitude: !isNaN(sp.latlon.latitude) ? sp.latlon.latitude.toString() : undefined,
            longitude: !isNaN(sp.latlon.longitude) ? sp.latlon.longitude.toString() : undefined,
            fields: 'FULL'
        }
    }
 
    /**
     * @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 hybris.StoresApi(this.client)
        const searchRequest = this.transformSearchStoreParams(storeSearchRequest)
            return api.getStores(searchRequest)
                .then((data) => {
                    if (data.stores.length <= 0) {
                        throw new Error('No stores found')
                    }
                    return this.parseSearchStores(data)
                })
    }
 
    parseSearchStores(data) {
        const d = data
 
        let count
        const start = d.pagination.currentPage
        const total = d.pagination.totalResults
        const pageSize = d.pagination.pageSize
        const totalPages = d.pagination.totalPages
        Eif (totalPages === start + 1) { // on last page
            Iif (total > pageSize) {
                const remainder = total % pageSize
                count = (remainder !== 0) ? remainder : pageSize
            } else {
                count = total
            }
        } else { // middle pages
            count = pageSize
        }
        return {
            count,
            start,
            total,
            stores: d.stores.length > 0 ? d.stores.map((store) => this.parseGetStore({...store, id: store.name})) : undefined
        }
    }
 
    isLoggedIn() {
        return this.getAuthentications().auth !== undefined
    }
 
    /**
     * Returns customer id 'current' if a refresh token is set in the auth
     * Otherwise, returns customer id 'anonymous'
     */
    getCustomerIdFromAuth() {
        Iif (!this.isLoggedIn()) { throw new errors.NotAuthenticatedError() }
        return this.getAuthentications().auth.refreshToken === undefined ? 'anonymous' : 'current'
    }
 
    /**
     * @inheritDoc
     */
    createCart(oldCart, opts = {}) {
        const api = new hybris.UsersApi(this.client)
        const customerId = this.getCustomerIdFromAuth()
        return api.postCart(customerId, {fields: 'FULL', ...opts})
            .then((newCart) => {
                if (customerId === 'current' && oldCart !== undefined) {
                    return api.postCart(customerId, { // postCart will merge and delete the old cart
                            fields: 'FULL',
                            toMergeCartGuid: newCart.guid,
                            oldCartId: oldCart.id
                    })
                    .catch(() => {
                        throw new errors.ServerError('Could not merge old cart')
                    })
                }
                return newCart
            })
            .then((cart) => this.parseCart(cart))
            .catch(() => {
                throw new errors.ServerError('Could not create cart')
            })
    }
 
    /**
     * @inheritDoc
     */
    getCart(cartId, opts = {}) {
        const api = new hybris.UsersApi(this.client)
        Iif (!cartId) { throw new errors.InvalidArgumentError(`Parameter 'cartId' is required`) }
 
        return api.getCart(this.getCustomerIdFromAuth(), cartId, {fields: 'FULL', ...opts})
            .then((data) => this.parseCart(data))
            .catch(() => { throw new errors.ServerError('Could not get cart') })
    }
 
    /**
     * @inheritDoc
     */
    deleteCart(cartId, opts = {}) { // eslint-disable-line no-unused-vars
        Iif (!cartId) { throw new errors.InvalidArgumentError(`Parameter 'cartId' is required`) }
 
        const api = new hybris.UsersApi(this.client)
        return api.deleteCart(this.getCustomerIdFromAuth(), cartId)
            .catch(() => { throw new errors.ServerError('Could not delete cart') })
    }
    /**
     * @inheritDoc
     */
    parseCart(data) {
        const d = data
        Iif (!d.guid && !d.code) {
            throw new Error('Error parsing cart')
        }
        const customerId = this.getCustomerIdFromAuth()
        const cartId = customerId === 'anonymous' ? d.guid : d.code
 
        return {
            id: cartId,
            customerInfo: {
                id: customerId,
                email: d.email
            },
            items: d.entries ? d.entries.map(this.parseCartItem) : [],
            shippingAddress: d.deliveryAddress ? this.parseOrderAddress(d.deliveryAddress) : undefined,
            billingAddress: d.paymentInfo && d.paymentInfo.billingAddress ?
                                this.parseOrderAddress(d.paymentInfo.billingAddress)
                                : undefined,
            shippingMethods: [],
            paymentMethods: [],
            selectedShippingMethodId: d.deliveryMode ? d.deliveryMode.code : undefined,
            payments: d.paymentInfo ? [this.parsePayment({...d.paymentInfo, amount: d.totalPriceWithTax.value})] : [],
            subtotal: d.subTotal ? d.subTotal.value : 0,
            shipping: d.deliveryCost ? d.deliveryCost.value : 0,
            discounts: d.totalDiscounts ? d.totalDiscounts.value : 0,
            tax: d.totalTax ? d.totalTax.value : 0,
            total: d.totalPriceWithTax ? d.totalPriceWithTax.value : 0
        }
    }
 
    /**
     * @inheritDoc
     */
    parseCartItem(data) {
        const d = data
        const quantity = d.quantity || 0
 
        return {
            id: `${d.entryNumber}`,
            productId: d.product ? d.product.code : undefined,
            productName: d.product ? d.product.name : undefined,
            quantity,
            baseItemPrice: d.basePrice ? d.basePrice.value : 0,
            baseLinePrice: d.basePrice ? d.basePrice.value * quantity : 0,
            itemPrice: d.totalPrice && (quantity !== 0) ? d.totalPrice.value / quantity : 0,
            linePrice: d.totalPrice ? d.totalPrice.value : 0
        }
    }
 
    /**
     * @inheritDoc
     */
    parseShippingMethod(data) {
        return {
            id: data.code,
            name: data.name,
            cost: data.deliveryCost || 0
        }
    }
 
    /**
     * @inheritDoc
     */
    parseOrderAddress(data) {
        const d = data
        return {
            id: d.id,
            titleCode: d.titleCode,
            firstName: d.firstName,
            lastName: d.lastName,
            phone: d.phone,
            addressLine1: d.line1,
            addressLine2: d.line2,
            countryCode: d.country ? d.country.isocode : undefined,
            stateCode: d.region ? d.region.isocode : undefined,
            city: d.town,
            postalCode: d.postalCode,
        }
    }
 
    /**
     * @inheritDoc
     */
    parsePayment(data) {
        const d = data
        return {
            id: d.id,
            amount: d.amount, // amount is always cart total for now.
            methodId: 'CREDIT_CARD', // only 1 type of payment method, we'll call it 'CREDIT_CARD'
            details: {
                type: d.cardType.code,
                holderName: d.accountHolderName,
                number: undefined, // to add/update payment, provide full number.
                username: undefined,
                maskedNumber: d.cardNumber, // hybris will give back masked number.
                expiryMonth: parseInt(d.expiryMonth),
                expiryYear: parseInt(d.expiryYear),
                ccv: undefined // hybris doesnt have ccv?
            }
        }
    }
 
    /**
     * @inheritDoc
     */
    parsePaymentMethod(data) {
        return {
            id: data.id,
            name: data.name,
            types: data.types.map((types) => ({id: types.code, name: types.name}))
        }
    }
 
    /**
     * Transform an orderAddress into hybris' models: billingAddress or shippingAddress
     */
    transformOrderAddress(orderAddress) {
        return {
            country: {
                isocode: orderAddress.countryCode
            },
            firstName: orderAddress.firstName,
            lastName: orderAddress.lastName,
            id: orderAddress.id,
            line1: orderAddress.addressLine1,
            line2: orderAddress.addressLine2,
            phone: orderAddress.phone,
            postalCode: orderAddress.postalCode,
            region: {
                isocode: orderAddress.stateCode,
            },
            titleCode: orderAddress.titleCode,
            town: orderAddress.city,
        }
    }
 
    /**
     * Transform a shippingMethod into hybris' model deliveryMethod.
     */
    transformShippingMethod(shippingMethod) {
        return {
            code: shippingMethod.id,
            name: shippingMethod.name,
            deliveryCost: shippingMethod.cost
        }
    }
 
    /**
     * Transform a cartItem into hybris' model OrderEntryOCC.
     */
    transformCartItem(cartItem) {
        return {
            product: {
                code: cartItem.productId
            },
            quantity: cartItem.quantity
        }
    }
 
 
    /**
     * Transform a payment into hybris' model paymentDetail.
     */
    transformPayment(payment, billingAddress) {
        const details = payment.details
        return {
            id: payment.id,
            accountHolderName: details ? details.holderName : undefined,
            billingAddress: this.transformOrderAddress(billingAddress),
            cardNumber: details ? details.number : undefined,
            cardType: {
                code: details ? details.type : undefined
            },
            expiryMonth: details ? details.expiryMonth : undefined,
            expiryYear: details ? details.expiryYear : undefined,
            subscriptionId: details ? details.username : undefined
        }
    }
 
    /**
     * @inheritDoc
     */
    addCartItem(cart, cartItem, opts = {}) {
        Iif (!cart) { throw new errors.InvalidArgumentError(`Parameter 'cart' is required`) }
        Iif (!cartItem) { throw new errors.InvalidArgumentError(`Parameter 'cartItem' is required`) }
 
        const api = new hybris.UsersApi(this.client)
 
        const entryOrder = this.transformCartItem(cartItem, opts)
 
        return api.postCartEntries(cart.customerInfo.id, cart.id, entryOrder, {...opts, fields: 'FULL'})
            .then(() => api.getCart(cart.customerInfo.id, cart.id, {...opts, fields: 'FULL'}))
            .then((data) => this.parseCart({...data, email: cart.customerInfo.email}))
            .catch(() => { throw new errors.ServerError('Could not add item to cart') })
    }
 
    /**
     * @inheritDoc
     */
    removeCartItem(cart, cartItemId, opts = {}) {
        Iif (!cart) { throw new errors.InvalidArgumentError(`Parameter 'cart' is required`) }
        Iif (!cartItemId) { throw new errors.InvalidArgumentError(`Parameter 'cartItemId' is required`) }
 
        const api = new hybris.UsersApi(this.client)
 
        return api.deleteCartEntry(cart.customerInfo.id, cart.id, cartItemId)
            .then(() => api.getCart(cart.customerInfo.id, cart.id, {...opts, fields: 'FULL'}))
            .then((data) => this.parseCart({...data, email: cart.customerInfo.email}))
            .catch(() => { throw new errors.ServerError('Could not delete cart item') })
    }
 
    /**
     * @inheritDoc
     */
    updateCartItem(cart, cartItem, opts = {}) {
        Iif (!cart) { throw new errors.InvalidArgumentError(`Parameter 'cart' is required`) }
        Iif (!cartItem) { throw new errors.InvalidArgumentError(`Parameter 'cartItem' is required`) }
 
        const api = new hybris.UsersApi(this.client)
 
        const entryOrder = this.transformCartItem(cartItem, opts)
        return api.patchCartEntry(cart.customerInfo.id, cart.id, cartItem.id, entryOrder, {fields: 'FULL'})
            .then(() => api.getCart(cart.customerInfo.id, cart.id, {fields: 'FULL'}))
            .then((data) => this.parseCart({...data, email: cart.customerInfo.email}))
            .catch(() => { throw new errors.ServerError('Could not update cart item') })
    }
 
    /**
     * @inheritDoc
     * Need to set a billing address before setting a payment.
     * Must call setCustomerInformation() to add an email before setting payment for an anonymous user.
     * cart.paymentDetails.number will be returned as undefined and set as a masked number in cart.paymentDetails.maskedNumber.
     */
    setPayment(cart, payment, opts = {}) {
        Iif (!cart) { throw new errors.InvalidArgumentError(`Parameter 'cart' is required`) }
        Iif (!payment) { throw new errors.InvalidArgumentError(`Parameter 'payment' is required`) }
 
        const api = new hybris.UsersApi(this.client)
 
        Iif (cart.customerInfo.id === 'anonymous' && cart.customerInfo.email === undefined) {
            throw new errors.InvalidArgumentError('Please set email for guest user cart')
        }
 
        if (!cart.billingAddress) {
            throw new errors.InvalidArgumentError('Please set billing address first')
        }
 
        const isMissingFields = !payment.details.type || !payment.details.expiryMonth || !payment.details.expiryYear || !payment.details.holderName || !payment.details.number
 
        Iif (isMissingFields) { throw new errors.InvalidArgumentError('Missing hybris required fields') }
 
        const paymentDetails = this.transformPayment(payment, cart.billingAddress)
 
        // If the customer is a registered user and a payment already exists on the cart,
        // then the payment is has also been added to the user account. So, update the
        // corresponding payment on the user account to see the reflected changes on the cart.
        const apiCommand = cart.payments.length > 0 && cart.customerInfo.id === 'current' ?
            api.putPaymentDetail(cart.customerInfo.id, cart.payments[0].id, paymentDetails)
                .then(() => this.getCart(cart.id))
            : api.postCartPaymentDetail(cart.customerInfo.id, cart.id, paymentDetails, {...opts, fields: 'FULL'})
                .then((data) => {
                    cart.payments[0] = this.parsePayment({...data, amount: cart.total})
                    return cart
                })
 
        return apiCommand
            .catch(() => {
                throw new errors.ServerError('Could not set payment')
            })
    }
 
    /**
     * @inheritDoc
     * Email can be set for a guest user but not a registered user.
     */
    setCustomerInformation(cart, customerInfo, opts = {}) {
        Iif (!cart) { throw new errors.InvalidArgumentError(`Parameter 'cart' is required`) }
        Iif (!customerInfo) { throw new errors.InvalidArgumentError(`Parameter 'customerInformation' is required`) }
 
        const api = new hybris.UsersApi(this.client)
        const customerId = cart.customerInfo.id
 
        return api.putCartEmail(customerId, cart.id, {...opts, email: customerInfo.email})
            .then(() => {
                cart.customerInfo = {...customerInfo, id: customerId}
                return cart
            })
            .catch(() => { throw new errors.ServerError('Could not set customer information') })
    }
 
    /**
     * @inheritDoc
     */
    getShippingMethods(cart, opts = {}) {
        Iif (!cart) { throw new errors.InvalidArgumentError(`Parameter 'cart' is required`) }
 
        const api = new hybris.UsersApi(this.client)
 
        return api.getCartDeliveryModes(cart.customerInfo.id, cart.id, {...opts, fields: 'FULL'})
            .then(({deliveryModes}) => deliveryModes.map(this.parseShippingMethod.bind(this)))
    }
 
    /**
     * @inheritDoc
     */
    setShippingMethod(cart, shippingMethod) {
        Iif (!cart) { throw new errors.InvalidArgumentError(`Parameter 'cart' is required`) }
        Iif (!shippingMethod) { throw new errors.InvalidArgumentError(`Parameter 'shippingMethod' is required`) }
 
        const api = new hybris.UsersApi(this.client)
        return api.putCartDeliveryMode(cart.customerInfo.id, cart.id, shippingMethod.id)
            .then(() => {
                cart.selectedShippingMethodId = shippingMethod.id
                return cart
            })
            .catch(() => { throw new errors.ServerError('Could not set shipping method') })
    }
 
    /**
     * @inheritDoc
     * Billing Address model : this order address needs to have a titleCode defined.
     * The default titleCodes are: ['mr', 'ms', 'miss', 'mrs', 'dr', 'rev']
     * But these may change depending on your backend, please refer to your backend instance to confirm valid titleCodes.
     *
     * If the billing address is set before adding a payment, the billing address will not yet be saved in the hybris instance.
     * Instead, the billing address will be saved in the hybris instance upon setting a payment.
     */
    setBillingAddress(cart, billingAddress, opts = {}) {
        Iif (!cart) { throw new errors.InvalidArgumentError(`Parameter 'cart' is required`) }
        Iif (!billingAddress) { throw new errors.InvalidArgumentError(`Parameter 'billingAddress' is required`) }
 
        const isMissingFields = !billingAddress.countryCode || !billingAddress.addressLine1 || !billingAddress.stateCode ||
        !billingAddress.titleCode || !billingAddress.postalCode || !billingAddress.city || !billingAddress.firstName || !billingAddress.lastName
        Iif (isMissingFields) { throw new errors.InvalidArgumentError('Missing hybris required fields') }
 
        // if the cart does not have a payment yet, give back a cart with the billing address set.
        // else, there a payment already exists and it's billing address needs to be updated
        if (cart.payments.length <= 0) {
            cart.billingAddress = billingAddress
            return Promise.resolve(cart)
        }
 
        const api = new hybris.UsersApi(this.client)
 
        // For a registered user, the existing payment can be patched to update it's billing address
        if (cart.customerInfo.id === 'current') {
            return api.patchPaymentDetail(cart.customerInfo.id, cart.payments[0].id, {billingAddress: this.transformOrderAddress(billingAddress)})
                .then(() => {
                    cart.billingAddress = billingAddress
                    return cart
                })
                .catch(() => { throw new errors.ServerError('Could not set billing address') })
        }
 
        // For a guest user, the existing payment can only be updated if the payment detail number is re-injected.
        if (cart.payments[0].details.number === undefined) {
            throw new errors.InvalidArgumentError('As a guest user, please re-inject payment details number before updating billing address')
        }
 
 
        return api.postCartPaymentDetail(cart.customerInfo.id, cart.id, this.transformPayment(cart.payments[0], billingAddress), {...opts, fields: 'FULL'})
                .then((data) => {
                    cart.billingAddress = billingAddress
                    cart.payments[0] = this.parsePayment({...data, amount: cart.total})
                    return cart
                })
                .catch(() => {
                    throw new errors.ServerError('Could not set billing address')
                })
    }
 
    /**
     * @inheritDoc
     * Must call setCustomerInformation() to add an email before setting payment for a guest user.
     */
    setShippingAddress(cart, shippingAddress, opts = {}) {
        Iif (!cart) { throw new errors.InvalidArgumentError(`Parameter 'cart' is required`) }
        Iif (!shippingAddress) { throw new errors.InvalidArgumentError(`Parameter 'shippingAddress' is required`) }
 
        if (cart.customerInfo.id === 'anonymous' && cart.customerInfo.email === undefined) {
            throw new errors.InvalidArgumentError('Please set email for guest user cart')
        }
 
        const isMissingFields = !shippingAddress.firstName || !shippingAddress.lastName || !shippingAddress.addressLine1 || !shippingAddress.city ||
        !shippingAddress.countryCode || !shippingAddress.stateCode || !shippingAddress.postalCode
 
        Iif (isMissingFields) { throw new errors.InvalidArgumentError('Missing hybris required fields') }
 
        const api = new hybris.UsersApi(this.client)
        // For a registered user, api.postCartDeliveryAddress() returns an unauthorized error (unknown reason)
        // A workaround: post or put (if already exists a shipping address) the user address and then put that address to the cart by its id.
        let apiCommand
        if (cart.customerInfo.id === 'current') {
            const userAddressApiCommand = cart.shippingAddress === undefined ?
                api.postUserAddress(cart.customerInfo.id, this.transformOrderAddress(shippingAddress), {fields: 'FULL'})
                : api.putUserAddress(cart.customerInfo.id, shippingAddress.id, {...this.transformOrderAddress(shippingAddress), id: shippingAddress.id})
 
            apiCommand = userAddressApiCommand
                .then((data) => {
                    return api.putCartDeliveryAddress(cart.customerInfo.id, cart.id, data.id)
                })
        } else {
            apiCommand = api.postCartDeliveryAddress(cart.customerInfo.id, cart.id, this.transformOrderAddress(shippingAddress), {...opts, fields: 'FULL'})
        }
 
        return apiCommand
            .then(() => {
                cart.shippingAddress = shippingAddress
                return cart
            })
            .catch(() => {
                throw new errors.ServerError('Could not set shipping address')
            })
    }
 
    /**
     * @inheritDoc
     * Hybris only supports payments by credit card attained from their cardtypes endpoint
     * so this command will return only one payment method with the id 'CREDIT_CARD', name 'Credit Card'
     * and all of it's valid credit card types.
     */
    getPaymentMethods(cart, opts = {}) {
        const api = new hybris.CardtypesApi(this.client)
        return api.getCardTypes({...opts, fields: 'FULL'})
            .then((data) => [this.parsePaymentMethod({id: 'CREDIT_CARD', name: 'Credit Card', types: data.cardTypes})])
            .catch(() => { throw new errors.ServerError('Could not get payment methods') })
    }
}