cart.js 4.09 KB
Newer Older
nabil el mahiri committed
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
(function () {
  'use strict';
  // Source: src/html/scripts/cart/index.js
  angular.module('pine.cart', ['LocalStorageModule']).config([
    'localStorageServiceProvider',
    function (localStorageServiceProvider) {
      localStorageServiceProvider.setStorageType('sessionStorage');
      //    .setNotify(true, true);
      ;
    }
  ]).factory('$cart', [
    '$http',
    '$q',
    'localStorageService',
    function ($http, $q, localStorageService) {
      var cart;
      // public API
      return {
        load: load,
        add: add,
        remove: remove,
        clear: clear,
        save: save,
        items: items
      };
      function load() {
        var cartId;
        var promise;
        // return if already loaded;
        if (cart) {
          return $q.when(cart);
        }
        // check if we already have one (id in local storage)
        cartId = localStorageService.get('cart');
        // if we have no cart id create one
        if (!cartId) {
          return $q.when(initCart());
        }
        // finally if we have an id, get the cart from the server.
        return $http.get('/carts/' + cartId, { 'Accept-Content': 'application/json' }).then(function (res) {
          cart = res.data;
          return cart;
        }, initCart);
      }
      function initCart() {
        // might add some defaults ?
        cart = {
          isNew: true,
          currency: '',
          trip: {
            travellers: [],
            segments: []
          },
          items: [],
          totals: { total: 0 }
        };
        return cart;
      }
      function items(type) {
        if (!type) {
          return cart.items;
        }
        return cart.items.filter(function (item) {
          return (item.type || item['@type']) === type;
        });
      }
      function add(item) {
        cart.items.push(item);
        // make sure we only add ints (you know addition in javascript are approxumate)
        var total = Math.round(cart.totals.total * 100);
        total += item.totals.total * 100;
        cart.totals.total = total / 100;
        return total;
      }
      function remove(item) {
        var index = cart.items.indexOf(item);
        var amount, total;
        if (index > -1) {
          total = cart.totals.total * 100;
          amount = item.totals.total * 100;
          total = total - amount;
          cart.totals.total = total / 100;
          cart.items.splice(index, 1);
          return item;
        }
        return false;
      }
      function clear(type) {
        var cleared, items = cart.items;
        if (type) {
          // mutating a looping array scares me
          // so doing it in two steps
          cleared = items.filter(function (item) {
            return item.type === type || item['@type'] === type;
          });
          for (var i = 0; i < cleared.length; i++) {
            items.splice(cart.items.indexOf(cleared[i]), 1);
          }
        } else {
          cleared = items.slice();
          items.length = 0;
        }
        return cleared;
      }
      function value() {
        return cart;
      }
      function save() {
        var cartId = localStorageService.get('cart'), isNew = !cartId, opts = {
            method: 'POST',
            url: '/carts',
            data: cart
          };
        if (!isNew) {
          // this is a new cart. we should post
          opts.method = 'PUT';
          opts.url += '/' + cartId;
        }
        return $http(opts).then(function (res) {
          // pine-mongo bug : returs array for POST
          if (angular.isArray(res.data)) {
            res.data = res.data[0];
          }
          // WATCHOUT: changinf ref. should we mutate old object (merge) or change ref ?
          cart = res.data;
          // if this was a newly created cart
          // track the id on local storage for later use.
          if (isNew) {
            localStorageService.set('cart', cart._id);
          }
          return cart;
        }, function failed(res) {
          var error = new Error('could not save cart');
          error.status = res.status;
          return error;
        });
      }
    }
  ]);
}());