partial #1503 - pre loading user's presets

This commit is contained in:
Daniel Camargo 2013-08-05 17:38:59 -03:00
parent 92e2a13fb1
commit cf34e204b1
6 changed files with 241 additions and 308 deletions

View File

@ -88,7 +88,6 @@
<!-- Customizable - select --> <!-- Customizable - select -->
<div ng-switch-when="select"> <div ng-switch-when="select">
<label class="cart-item-customize-select-name">{{option.name}}</label> <label class="cart-item-customize-select-name">{{option.name}}</label>
<select ng-change="order.cart.customizeItem(option, item)" ng-model="option.selected" ng-options="opt.id_option as opt.name for opt in option.options" class="cart-customize-select"></select> <select ng-change="order.cart.customizeItem(option, item)" ng-model="option.selected" ng-options="opt.id_option as opt.name for opt in option.options" class="cart-customize-select"></select>
</div> </div>
@ -231,18 +230,15 @@
</div> </div>
<label ng-show="order.form.pay_type=='card'">Credit card #</label> <label ng-show="order.form.pay_type=='card'">Credit card #</label>
<div ng-show="order.form.pay_type=='card'" class="input-item"><input type="tel" name="pay-card-number" tabindex="6" value="{{order.form.card.number}}"></div><div class="divider"></div> <div ng-show="order.form.pay_type=='card'" class="input-item"><input type="tel" name="pay-card-number" tabindex="6" value="{{order.form.cardNumber}}"></div><div class="divider"></div>
<label ng-show="order.form.pay_type=='card'">Expiration</label> <label ng-show="order.form.pay_type=='card'">Expiration</label>
<div ng-show="order.form.pay_type=='card'" class="input-item"> <div ng-show="order.form.pay_type=='card'" class="input-item">
<select name="pay-card-month" tabindex="7">
<option>Month</option> <select ng-model="order.form.cardMonth" ng-options="month.value as month.label for month in order._months()" tabindex="7">{{order.form.card.month}}</select>
<option ng-repeat="x in order._months()" value="{{x}}">{{x}}</option>
</select> <select ng-model="order.form.cardYear" ng-options="year.value as year.label for year in order._years()" tabindex="8"></select>
<select name="pay-card-year" tabindex="8">
<option>Year</option>
<option ng-repeat="x in order._years()" value="{{x}}">{{x}}</option>
</select>
<div class="divider"></div> <div class="divider"></div>
</div> </div>
@ -275,7 +271,7 @@
</form> </form>
<div ng-show="restaurant._open" class="button-bottom-wrapper" data-role="footer" data-position="fixed"><button class="button-submitorder-form button-bottom"><div>Get Food</div></button></div> <div ng-show="restaurant._open" class="button-bottom-wrapper" data-role="footer" data-position="fixed"><button class="button-bottom" ng-click="order.submit();"><div>Get Food</div></button></div>
<? /* stored user info */ ?> <? /* stored user info */ ?>
<div class="delivery-payment-info main-content-readable" ng-show="restaurant._open"> <div class="delivery-payment-info main-content-readable" ng-show="restaurant._open">

View File

@ -63,8 +63,11 @@
<div class="footer"> <div class="footer">
<div class="fb-like-mobile fb-like-box" data-href="http://www.facebook.com/crunchbutton" data-width="300" data-show-faces="false" data-stream="false" data-header="false"></div> <!--
TODO: remove this comment
<div class="fb-like-mobile fb-like-box" data-href="http://www.facebook.com/crunchbutton" data-width="300" data-show-faces="false" data-stream="false" data-header="false"></div>
-->
<div class="footer-content hidden-phone" ng-controller="MainHeaderCtrl"> <div class="footer-content hidden-phone" ng-controller="MainHeaderCtrl">
<a href="javascript:;" ng-click="navigation.link('/help')">Help</a> <a href="javascript:;" ng-click="navigation.link('/help')">Help</a>

View File

@ -604,7 +604,7 @@ App.init = function() {
$('.cart-item-config a').click(function() { $('.cart-item-config a').click(function() {
App.cart.customize($(this).closest('.cart-item')); App.cart.customize($(this).closest('.cart-item'));
}); });
*/
$('.button-submitorder-form').click(function(e) { $('.button-submitorder-form').click(function(e) {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
@ -612,7 +612,7 @@ App.init = function() {
App.isDeliveryAddressOk = false; App.isDeliveryAddressOk = false;
App.cart.submit($(this),true); App.cart.submit($(this),true);
}); });
*/
$(document).on('click', '.button-deliver-payment, .dp-display-item a, .dp-display-item .clickable', function() { $(document).on('click', '.button-deliver-payment, .dp-display-item a, .dp-display-item .clickable', function() {
$('.payment-form').show(); $('.payment-form').show();
$('.delivery-payment-info, .content-padder-before').hide(); $('.delivery-payment-info, .content-padder-before').hide();

View File

@ -220,9 +220,9 @@ NGApp.controller('restaurant', function ($scope, $http, $routeParams, Restaurant
$scope.restaurant = $scope.restaurantService.restaurant; $scope.restaurant = $scope.restaurantService.restaurant;
$scope.order.restaurant = $scope.restaurant; $scope.order.restaurant = $scope.restaurant;
$scope.order.init(); $scope.order.init();
/*$scope.cart.restaurant = $scope.restaurant; /*
$scope.cart.updateTotal();
$scope.lastOrderDelivery = $scope.service.lastOrderDelivery; $scope.lastOrderDelivery = $scope.service.lastOrderDelivery;
$scope.community = $scope.service.community; $scope.community = $scope.service.community;
@ -230,6 +230,10 @@ NGApp.controller('restaurant', function ($scope, $http, $routeParams, Restaurant
} }
}); });
$scope.$watch( 'order.cart.items', function( newValue, oldValue, scope ) {
$scope.order.updateTotal();
}, true);
$scope.$watch( 'order.cart.items', function( newValue, oldValue, scope ) { $scope.$watch( 'order.cart.items', function( newValue, oldValue, scope ) {
$scope.order.updateTotal(); $scope.order.updateTotal();
}, true); }, true);

View File

@ -1,25 +1,43 @@
// CartService service // CartService service
NGApp.factory( 'CartService', function ( RestaurantService ) { NGApp.factory('CartService', function (RestaurantService) {
var service = { var service = {
uuidInc: 0, uuidInc: 0,
items: {} items: {}
} }
service.uuid = function () { service.uuid = function () {
var id = 'c-' + service.uuidInc; var id = 'c-' + service.uuidInc;
service.uuidInc++; service.uuidInc++;
return id; return id;
} }
service.add = function (item) { service.add = function (item) {
var id = service.uuid(), var id = service.uuid(),
dish = App.cache('Dish', item); dish = App.cache('Dish', item);
dish_options = dish.options(), dish_options = dish.options(),
options = []; options = [];
if (arguments[1]) { if (arguments[1]) {
options = arguments[1].options; options = arguments[1].options;
// This lines above will verify is there are any 'select' option without a selected value
for (var i in dish_options) {
if (dish_options[i].type == 'select') {
var hasSelectedOption = false;
var defaultValue = false;
for (var j in dish_options) {
if (dish_options[j].id_option_parent == dish_options[i].id_option) {
if (dish_options[j]['default'] == 1) {
defaultValue = dish_options[j]['id_option'];
}
for (var k in options) {
if (options[k] == dish_options[j].id_option) {
hasSelectedOption = true;
}
}
}
}
if (defaultValue && !hasSelectedOption) {
options[options.length] = defaultValue;
}
}
}
} else { } else {
for (var x in dish_options) { for (var x in dish_options) {
if (dish_options[x]['default'] == 1) { if (dish_options[x]['default'] == 1) {
@ -27,65 +45,60 @@ NGApp.factory( 'CartService', function ( RestaurantService ) {
} }
} }
} }
service.items[id] = {}; service.items[id] = {};
service.items[id].id = item; service.items[id].id = item;
service.items[id].options = options; service.items[id].options = options;
/* Template viewer stuff */ /* Template viewer stuff */
service.items[id].details = {}; service.items[id].details = {};
service.items[id].details.id = id; service.items[id].details.id = id;
service.items[id].details.name = dish.name; service.items[id].details.name = dish.name;
service.items[id].details.description = dish.description != null ? dish.description : ''; service.items[id].details.description = dish.description != null ? dish.description : '';
/* Customization stuff */ /* Customization stuff */
service.items[id].details.customization = {}; service.items[id].details.customization = {};
service.items[id].details.customization.customizable = ( dish.options().length > 0 ); service.items[id].details.customization.customizable = (dish.options().length > 0);
service.items[id].details.customization.expanded = ( parseInt(dish.expand_view ) > 0 ); service.items[id].details.customization.expanded = (parseInt(dish.expand_view) > 0);
service.items[id].details.customization.options = service._parseCustomOptions( dish_options, options ); service.items[id].details.customization.options = service._parseCustomOptions(dish_options, options);
service.items[id].details.customization.rawOptions = dish_options; service.items[id].details.customization.rawOptions = dish_options;
//TODO:: If it is a mobile add the items at the top #1035 //TODO:: If it is a mobile add the items at the top #1035
App.track('Dish added', {
App.track('Dish added', { id_dish: dish.id_dish, name: dish.name }); id_dish: dish.id_dish,
name: dish.name
});
} }
service.clone = function (item) { service.clone = function (item) {
var var
cart = service.items[item], cart = service.items[item],
newoptions = []; newoptions = [];
for (var x in cart.options) { for (var x in cart.options) {
newoptions[newoptions.length] = cart.options[x]; newoptions[newoptions.length] = cart.options[x];
} }
service.add(cart.id, { options: newoptions }); service.add(cart.id, {
options: newoptions
});
App.track('Dish cloned'); App.track('Dish cloned');
} }
service.remove = function (item) { service.remove = function (item) {
App.track('Dish removed'); App.track('Dish removed');
delete service.items[item]; delete service.items[item];
} }
service.customizeItem = function (option, item) { service.customizeItem = function (option, item) {
var cartitem = service.items[item.details.id]; var cartitem = service.items[item.details.id];
if (option) { if (option) {
if ( option.type == 'select' ) { if (option.type == 'select') {
var options = item.details.customization.rawOptions; var options = item.details.customization.rawOptions;
for (var i in options) { for (var i in options) {
if (options[i].id_option_parent != option.id_option) { if (options[i].id_option_parent != option.id_option) {
continue; continue;
} }
for (var x in cartitem.options) { for (var x in cartitem.options) {
if ( cartitem.options[x] == options[i].id_option && options[i].id_option_parent == option.id_option ) { if (cartitem.options[x] == options[i].id_option && options[i].id_option_parent == option.id_option) {
cartitem.options.splice(x, 1); cartitem.options.splice(x, 1);
break; break;
} }
} }
} }
cartitem.options[cartitem.options.length] = option.selected; cartitem.options[cartitem.options.length] = option.selected;
} else if ( option.type == 'check' ) { } else if (option.type == 'check') {
if (option.checked) { if (option.checked) {
cartitem.options[cartitem.options.length] = option.id_option; cartitem.options[cartitem.options.length] = option.id_option;
} else { } else {
@ -100,14 +113,12 @@ NGApp.factory( 'CartService', function ( RestaurantService ) {
} }
service.items[item.details.id] = cartitem; service.items[item.details.id] = cartitem;
} }
service.customizeItemPrice = function (price, force) { service.customizeItemPrice = function (price, force) {
if (price != '0.00' || force) { if (price != '0.00' || force) {
return ' (' + ( (price < 0) ? 'minus $' : '+ $' ) + parseFloat(Math.abs(price)).toFixed(2) + ')'; return ' (' + ((price < 0) ? 'minus $' : '+ $') + parseFloat(Math.abs(price)).toFixed(2) + ')';
} }
return ''; return '';
} }
service.getCart = function () { service.getCart = function () {
var cart = []; var cart = [];
for (x in service.items) { for (x in service.items) {
@ -115,22 +126,19 @@ NGApp.factory( 'CartService', function ( RestaurantService ) {
} }
return cart; return cart;
} }
service.hasItems = function () { service.hasItems = function () {
if (!$.isEmptyObject(service.items)) { if (!$.isEmptyObject(service.items)) {
return true; return true;
} }
return false; return false;
} }
service.summary = function () {
service.summary = function(){
var items = {}; var items = {};
for (var x in service.items) { for (var x in service.items) {
if( items[ service.items[x].details.name ] ){ if (items[service.items[x].details.name]) {
items[ service.items[x].details.name ]++; items[service.items[x].details.name]++;
} else { } else {
items[ service.items[x].details.name ] = 1; items[service.items[x].details.name] = 1;
} }
} }
var text = ''; var text = '';
@ -144,16 +152,13 @@ NGApp.factory( 'CartService', function ( RestaurantService ) {
} }
return text.substr(0, text.length - 13); return text.substr(0, text.length - 13);
} }
service.subtotal = function () { service.subtotal = function () {
var var
total = 0, total = 0,
options; options;
for (var x in service.items) { for (var x in service.items) {
total += parseFloat(App.cached['Dish'][service.items[x].id].price); total += parseFloat(App.cached['Dish'][service.items[x].id].price);
options = service.items[x].options; options = service.items[x].options;
for (var xx in options) { for (var xx in options) {
var option = App.cached['Option'][options[xx]]; var option = App.cached['Option'][options[xx]];
if (option === undefined) continue; // option does not exist anymore if (option === undefined) continue; // option does not exist anymore
@ -163,59 +168,54 @@ NGApp.factory( 'CartService', function ( RestaurantService ) {
total = App.ceil(total); total = App.ceil(total);
return total; return total;
} }
service.totalItems = function () {
service.totalItems = function(){
var size = 0; var size = 0;
for (var x in service.items) { for (var x in service.items) {
if (service.items.hasOwnProperty(x)){ if (service.items.hasOwnProperty(x)) {
size++; size++;
} }
} }
return size; return size;
} }
service._parseCustomOptions = function (options, selectedOptions) {
service._parseCustomOptions = function( options, selectedOptions ){
var parsedOptions = []; var parsedOptions = [];
for (var x in options) {
for( var x in options ){
var newOption = {}; var newOption = {};
var rawOption = options[x]; var rawOption = options[x];
if ( rawOption.id_option_parent ) { if (rawOption.id_option_parent) {
continue; continue;
} }
newOption.type = rawOption.type; newOption.type = rawOption.type;
newOption.id_option = rawOption.id_option; newOption.id_option = rawOption.id_option;
newOption.name = rawOption.name + ( rawOption.description || '' ); newOption.name = rawOption.name + (rawOption.description || '');
if( rawOption.type == 'check' ){ if (rawOption.type == 'check') {
newOption.id_option = rawOption.id_option; newOption.id_option = rawOption.id_option;
newOption.price = rawOption.optionPrice(options); newOption.price = rawOption.optionPrice(options);
newOption.priceFormated = service.customizeItemPrice(newOption.price); newOption.priceFormated = service.customizeItemPrice(newOption.price);
newOption.checked = ( $.inArray(rawOption.id_option, selectedOptions) !== -1); newOption.checked = ($.inArray(rawOption.id_option, selectedOptions) !== -1);
} }
if( rawOption.type == 'select' ){ if (rawOption.type == 'select') {
newOption.options = []; newOption.options = [];
newOption.selected = false; newOption.selected = false;
for( var i in options ){ for (var i in options) {
if (options[i].id_option_parent == rawOption.id_option) { if (options[i].id_option_parent == rawOption.id_option) {
var newSubOption = {}; var newSubOption = {};
newSubOption.id_option = options[i].id_option; newSubOption.id_option = options[i].id_option;
newSubOption.id_option_parent = options[i].id_option_parent; newSubOption.id_option_parent = options[i].id_option_parent;
newSubOption.price = options[i].price; newSubOption.price = options[i].price;
newSubOption.priceFormated = service.customizeItemPrice(newSubOption.price); newSubOption.priceFormated = service.customizeItemPrice(newSubOption.price);
newSubOption.selected = ($.inArray( options[i].id_option, selectedOptions) !== -1); newSubOption.selected = ($.inArray(options[i].id_option, selectedOptions) !== -1);
newSubOption.name = options[i].name + (options[i].description || '') + service.customizeItemPrice(newSubOption.price, (rawOption.price_linked == '1')); newSubOption.name = options[i].name + (options[i].description || '') + service.customizeItemPrice(newSubOption.price, (rawOption.price_linked == '1'));
newOption.options.push( newSubOption ); newOption.options.push(newSubOption);
if( newSubOption.selected ){ if (newSubOption.selected) {
newOption.selected = options[i].id_option; newOption.selected = options[i].id_option;
} }
} }
} }
} }
parsedOptions.push( newOption ); parsedOptions.push(newOption);
} }
return parsedOptions; return parsedOptions;
} }
return service; return service;
}); });

View File

@ -1,73 +1,77 @@
//OrderService Service //OrderService Service
NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){ NGApp.factory('OrderService', function ($http, AccountService, CartService) {
var service = {}; var service = {};
service.account = AccountService; service.account = AccountService;
service.cart = CartService; service.cart = CartService;
service.restaurant = {}; service.restaurant = {};
// Default values // Default values
service.form = { service.form = {
delivery_type : 'delivery', delivery_type: 'delivery',
pay_type : 'card' pay_type: 'card'
}; };
// Info that will be shown to the user // Info that will be shown to the user
service.info = { service.info = {
dollarSign : '', dollarSign: '',
breakdownDescription : '', breakdownDescription: '',
extraCharges : '', extraCharges: '',
deliveryMinDiff : '', deliveryMinDiff: '',
cartSummary : '', cartSummary: '',
totalText : '' totalText: ''
} }
service.toogleDelivery = function (type) {
service.toogleDelivery = function( type ){ if (type != service.form.delivery_type) {
if( type != service.form.delivery_type ){
service.form.delivery_type = type; service.form.delivery_type = type;
service.updateTotal(); service.updateTotal();
} }
} }
service.tooglePayment = function (type) {
service.tooglePayment = function( type ){ if (type != service.form.pay_type) {
if( type != service.form.pay_type ){
service.form.pay_type = type; service.form.pay_type = type;
service.updateTotal(); service.updateTotal();
} }
} }
service.init = function () {
service.init = function(){ if (App.config.ab && App.config.ab.dollarSign == 'show') {
if( App.config.ab && App.config.ab.dollarSign == 'show' ){
service.info.dollarSign = '$'; service.info.dollarSign = '$';
} }
// Tip stuff // Tip stuff
if( service.account.user && service.account.user.last_tip ){ if (service.account.user && service.account.user.last_tip) {
var tip = service.account.user.last_tip; var tip = service.account.user.last_tip;
} else{ } else {
var tip = 'autotip'; var tip = 'autotip';
} }
service._tipHasChanged = false; service._tipHasChanged = false;
service.form.autotip = 0; service.form.autotip = 0;
service.form.tip = service._lastTipNormalize( tip ); service.form.tip = service._lastTipNormalize(tip);
service.form.name = service.account.user.name; service.form.name = service.account.user.name;
service.form.phone = App.phone.format( service.account.user.phone ); service.form.phone = App.phone.format(service.account.user.phone);
service.form.address = service.account.user.address; service.form.address = service.account.user.address;
service.form.notes = ( service.account.user && service.account.user.presets && service.account.user.presets[service.restaurant.id_restaurant]) ? service.account.user.presets[service.restaurant.id_restaurant].notes : ''; service.form.notes = (service.account.user && service.account.user.presets && service.account.user.presets[service.restaurant.id_restaurant]) ? service.account.user.presets[service.restaurant.id_restaurant].notes : '';
service.form.card = { // Credit card stuff
number: service.account.user.card, service.form.cardNumber = service.account.user.card;
month: service.account.user.card_exp_month, service.form.cardMonth = service.account.user.card_exp_month;
year: service.account.user.card_exp_year service.form.cardYear = service.account.user.card_exp_year;
};
service.updateTotal(); service.updateTotal();
}
// Load the order
if( service.cart.hasItems() ){
service.reloadOrder();
// Load user presets
} else if ( service.account.user && service.account.user.presets && service.account.user.presets[service.restaurant.id_restaurant] ) {
try {
service.loadOrder(service.account.user.presets[service.restaurant.id_restaurant]);
} catch (e) {
service.loadOrder(service.restaurant.preset());
}
} else {
service.loadOrder(service.restaurant.preset());
}
}
service.reloadOrder = function () { service.reloadOrder = function () {
var cart = service.items; var cart = service.items;
service.resetOrder(); service.resetOrder();
service.loadFlatOrder(cart); service.loadFlatOrder(cart);
} }
service.loadFlatOrder = function (cart) { service.loadFlatOrder = function (cart) {
for (var x in cart) { for (var x in cart) {
service.add(cart[x].id, { service.add(cart[x].id, {
@ -75,7 +79,6 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
}); });
} }
} }
service.loadOrder = function (order) { service.loadOrder = function (order) {
// @todo: convert this to preset object // @todo: convert this to preset object
try { try {
@ -87,11 +90,10 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
options[options.length] = dishes[x]['_options'][xx].id_option; options[options.length] = dishes[x]['_options'][xx].id_option;
} }
if (App.cached.Dish[dishes[x].id_dish] != undefined) { if (App.cached.Dish[dishes[x].id_dish] != undefined) {
service.add(dishes[x].id_dish, { service.cart.add(dishes[x].id_dish, {
options: options options: options
}); });
} }
} }
} }
} catch (e) { } catch (e) {
@ -99,7 +101,6 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
// throw e; // throw e;
} }
} }
/** /**
* subtotal, delivery, fee, taxes and tip * subtotal, delivery, fee, taxes and tip
* *
@ -108,11 +109,9 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
service.extraChargesText = function (breakdown) { service.extraChargesText = function (breakdown) {
var elements = []; var elements = [];
var text = ''; var text = '';
if (breakdown.delivery) { if (breakdown.delivery) {
elements.push(service.info.dollarSign + breakdown.delivery.toFixed(2) + ' delivery'); elements.push(service.info.dollarSign + breakdown.delivery.toFixed(2) + ' delivery');
} }
if (breakdown.fee) { if (breakdown.fee) {
elements.push(service.info.dollarSign + breakdown.fee.toFixed(2) + ' fee'); elements.push(service.info.dollarSign + breakdown.fee.toFixed(2) + ' fee');
} }
@ -122,7 +121,6 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
if (breakdown.tip && breakdown.tip > 0) { if (breakdown.tip && breakdown.tip > 0) {
elements.push(service.info.dollarSign + breakdown.tip + ' tip'); elements.push(service.info.dollarSign + breakdown.tip + ' tip');
} }
if (elements.length) { if (elements.length) {
if (elements.length > 2) { if (elements.length > 2) {
var lastOne = elements.pop(); var lastOne = elements.pop();
@ -133,11 +131,9 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
} }
return text; return text;
} }
service.subtotal = function () { service.subtotal = function () {
return service.cart.subtotal(); return service.cart.subtotal();
} }
/** /**
* delivery cost * delivery cost
* *
@ -151,7 +147,6 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
delivery = App.ceil(delivery); delivery = App.ceil(delivery);
return delivery; return delivery;
} }
/** /**
* Crunchbutton service * Crunchbutton service
* *
@ -165,13 +160,11 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
fee = App.ceil(fee); fee = App.ceil(fee);
return fee; return fee;
} }
service._breackDownTaxes = function (feeTotal) { service._breackDownTaxes = function (feeTotal) {
var taxes = (feeTotal * (service.restaurant.tax / 100)); var taxes = (feeTotal * (service.restaurant.tax / 100));
taxes = App.ceil(taxes); taxes = App.ceil(taxes);
return taxes; return taxes;
} }
service._breakdownTip = function (total) { service._breakdownTip = function (total) {
var tip = 0; var tip = 0;
if (service.form.pay_type == 'card') { if (service.form.pay_type == 'card') {
@ -183,7 +176,6 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
tip = App.ceil(tip); tip = App.ceil(tip);
return tip; return tip;
} }
service.total = function () { service.total = function () {
var var
total = 0, total = 0,
@ -192,7 +184,6 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
feeTotal = 0, feeTotal = 0,
totalItems = 0, totalItems = 0,
finalAmount = 0; finalAmount = 0;
var breakdown = this.totalbreakdown(); var breakdown = this.totalbreakdown();
total = breakdown.subtotal; total = breakdown.subtotal;
feeTotal = total; feeTotal = total;
@ -202,11 +193,8 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
finalAmount += this._breakdownTip(total); finalAmount += this._breakdownTip(total);
return App.ceil(finalAmount).toFixed(2); return App.ceil(finalAmount).toFixed(2);
} }
service.charged = function () { service.charged = function () {
var finalAmount = this.total(); var finalAmount = this.total();
if (App.order.pay_type == 'card' && App.credit.restaurant[service.restaurant.id]) { if (App.order.pay_type == 'card' && App.credit.restaurant[service.restaurant.id]) {
finalAmount = finalAmount - App.ceil(App.credit.restaurant[service.restaurant.id]).toFixed(2); finalAmount = finalAmount - App.ceil(App.credit.restaurant[service.restaurant.id]).toFixed(2);
if (finalAmount < 0) { if (finalAmount < 0) {
@ -215,7 +203,6 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
} }
return App.ceil(finalAmount).toFixed(2); return App.ceil(finalAmount).toFixed(2);
} }
/** /**
* Returns the elements that calculates the total * Returns the elements that calculates the total
* *
@ -224,11 +211,9 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
* @return array * @return array
*/ */
service.totalbreakdown = function () { service.totalbreakdown = function () {
var elements = {}; var elements = {};
var total = this.subtotal(); var total = this.subtotal();
var feeTotal = total; var feeTotal = total;
elements['subtotal'] = this.subtotal(); elements['subtotal'] = this.subtotal();
elements['delivery'] = this._breackDownDelivery(); elements['delivery'] = this._breackDownDelivery();
feeTotal += elements['delivery']; feeTotal += elements['delivery'];
@ -238,26 +223,21 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
elements['tip'] = this._breakdownTip(total); elements['tip'] = this._breakdownTip(total);
return elements; return elements;
} }
service.resetOrder = function () { service.resetOrder = function () {
service.cart.items = {}; service.cart.items = {};
} }
/** /**
* Submits the cart order * Submits the cart order
* *
* @returns void * @returns void
*/ */
service.submit = function () { service.submit = function () {
if (App.busy.isBusy()) { if (App.busy.isBusy()) {
return; return;
} }
// TODO: put it in a service
App.busy.makeBusy(); // App.busy.makeBusy();
var read = $('.payment-form').length ? true : false; var read = $('.payment-form').length ? true : false;
if (read) { if (read) {
App.config.user.name = $('[name="pay-name"]').val(); App.config.user.name = $('[name="pay-name"]').val();
App.config.user.phone = $('[name="pay-phone"]').val().replace(/[^\d]*/gi, ''); App.config.user.phone = $('[name="pay-phone"]').val().replace(/[^\d]*/gi, '');
@ -266,7 +246,6 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
} }
service.form.tip = $('[name="pay-tip"]').val(); service.form.tip = $('[name="pay-tip"]').val();
} }
var order = { var order = {
cart: service.getCart(), cart: service.getCart(),
pay_type: service.form.pay_type, pay_type: service.form.pay_type,
@ -277,12 +256,10 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
lat: (App.loc.pos()) ? App.loc.pos().lat : null, lat: (App.loc.pos()) ? App.loc.pos().lat : null,
lon: (App.loc.pos()) ? App.loc.pos().lon : null lon: (App.loc.pos()) ? App.loc.pos().lon : null
}; };
if (order.pay_type == 'card') { if (order.pay_type == 'card') {
order.tip = service.form.tip || '3'; order.tip = service.form.tip || '3';
order.autotip_value = $('[name=pay-autotip-value]').val(); order.autotip_value = $('[name=pay-autotip-value]').val();
} }
if (read) { if (read) {
order.address = App.config.user.address; order.address = App.config.user.address;
order.phone = App.config.user.phone; order.phone = App.config.user.phone;
@ -297,31 +274,23 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
order.card = {}; order.card = {};
} }
} }
console.log('ORDER:', order); console.log('ORDER:', order);
var errors = {}; var errors = {};
if (!order.name) { if (!order.name) {
errors['name'] = 'Please enter your name.'; errors['name'] = 'Please enter your name.';
} }
if (!App.phone.validate(order.phone)) { if (!App.phone.validate(order.phone)) {
errors['phone'] = 'Please enter a valid phone #.'; errors['phone'] = 'Please enter a valid phone #.';
} }
if (order.delivery_type == 'delivery' && !order.address) { if (order.delivery_type == 'delivery' && !order.address) {
errors['address'] = 'Please enter an address.'; errors['address'] = 'Please enter an address.';
} }
if (order.pay_type == 'card' && ((App.order.cardChanged && !order.card.number) || (!App.config.user.id_user && !order.card.number))) { if (order.pay_type == 'card' && ((App.order.cardChanged && !order.card.number) || (!App.config.user.id_user && !order.card.number))) {
errors['card'] = 'Please enter a valid card #.'; errors['card'] = 'Please enter a valid card #.';
} }
if (!service.hasItems()) { if (!service.hasItems()) {
errors['noorder'] = 'Please add something to your order.'; errors['noorder'] = 'Please add something to your order.';
} }
if (!$.isEmptyObject(errors)) { if (!$.isEmptyObject(errors)) {
var error = ''; var error = '';
for (var x in errors) { for (var x in errors) {
@ -337,31 +306,24 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
}, 'validation error'); }, 'validation error');
return; return;
} }
// Play the crunch audio just once, when the user clicks at the Get Food button // Play the crunch audio just once, when the user clicks at the Get Food button
if (App.iOS() && !App.crunchSoundAlreadyPlayed) { if (App.iOS() && !App.crunchSoundAlreadyPlayed) {
App.playAudio('get-food-audio'); App.playAudio('get-food-audio');
App.crunchSoundAlreadyPlayed = true; App.crunchSoundAlreadyPlayed = true;
} }
// if it is a delivery order we need to check the address // if it is a delivery order we need to check the address
if (order.delivery_type == 'delivery') { if (order.delivery_type == 'delivery') {
// Correct Legacy Addresses in Database to Avoid Screwing Users #1284 // Correct Legacy Addresses in Database to Avoid Screwing Users #1284
// If the user has already ordered food // If the user has already ordered food
if (App.config && App.config.user && App.config.user.last_order) { if (App.config && App.config.user && App.config.user.last_order) {
// Check if the order was made at this community // Check if the order was made at this community
if (App.config.user.last_order.communities.indexOf(service.restaurant.id_community) > -1) { if (App.config.user.last_order.communities.indexOf(service.restaurant.id_community) > -1) {
// Get the last address the user used at this community // Get the last address the user used at this community
var lastAddress = App.config.user.last_order.address; var lastAddress = App.config.user.last_order.address;
var currentAdress = $('[name=pay-address]').val(); var currentAdress = $('[name=pay-address]').val();
// Make sure the the user address is the same of his last order // Make sure the the user address is the same of his last order
if ($.trim(lastAddress) != '' && $.trim(lastAddress) == $.trim(currentAdress)) { if ($.trim(lastAddress) != '' && $.trim(lastAddress) == $.trim(currentAdress)) {
App.isDeliveryAddressOk = true; App.isDeliveryAddressOk = true;
// Log the legacy address // Log the legacy address
App.log.order({ App.log.order({
'address': lastAddress, 'address': lastAddress,
@ -467,7 +429,6 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
} }
*/ */
} }
if (order.delivery_type == 'takeout') { if (order.delivery_type == 'takeout') {
App.isDeliveryAddressOk = true; App.isDeliveryAddressOk = true;
} }
@ -475,13 +436,11 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
if (!App.isDeliveryAddressOk) { if (!App.isDeliveryAddressOk) {
return; return;
} }
// Play the crunch audio just once, when the user clicks at the Get Food button // Play the crunch audio just once, when the user clicks at the Get Food button
if (!App.crunchSoundAlreadyPlayed) { if (!App.crunchSoundAlreadyPlayed) {
App.playAudio('get-food-audio'); App.playAudio('get-food-audio');
App.crunchSoundAlreadyPlayed = true; App.crunchSoundAlreadyPlayed = true;
} }
$.ajax({ $.ajax({
url: App.service + 'order', url: App.service + 'order',
data: order, data: order,
@ -498,7 +457,6 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
errors: ['Sorry! Something went horribly wrong trying to place your order!'] errors: ['Sorry! Something went horribly wrong trying to place your order!']
}; };
} }
if (json.status == 'false') { if (json.status == 'false') {
var error = ''; var error = '';
for (x in json.errors) { for (x in json.errors) {
@ -511,25 +469,18 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
'errors': json.errors 'errors': json.errors
}, 'validation error - php'); }, 'validation error - php');
} else { } else {
if (json.token) { if (json.token) {
$.totalStorage('token', json.token); $.totalStorage('token', json.token);
} }
$('.link-orders').show(); $('.link-orders').show();
order.cardChanged = false; order.cardChanged = false;
App.justCompleted = true; App.justCompleted = true;
App.giftcard.notesCode = false; App.giftcard.notesCode = false;
var totalItems = 0; var totalItems = 0;
for (var x in service.items) { for (var x in service.items) {
totalItems++; totalItems++;
} }
$.getJSON('/api/config', App.processConfig); $.getJSON('/api/config', App.processConfig);
App.cache('Order', json.uuid, function () { App.cache('Order', json.uuid, function () {
App.track('Ordered', { App.track('Ordered', {
'total': this.final_price, 'total': this.final_price,
@ -541,12 +492,10 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
'user': this.user, 'user': this.user,
'items': totalItems 'items': totalItems
}); });
App.order.cardChanged = false; App.order.cardChanged = false;
App.loc.changeLocationAddressHasChanged = false; App.loc.changeLocationAddressHasChanged = false;
delete tipHasChanged; delete tipHasChanged;
App.go('/order/' + this.uuid); App.go('/order/' + this.uuid);
}); });
} }
setTimeout(function () { setTimeout(function () {
@ -554,14 +503,11 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
}, 400); }, 400);
} }
}); });
} // end service.submit() } // end service.submit()
service.tipChanged = function () {
service.tipChanged = function(){
service._tipHasChanged = true; service._tipHasChanged = true;
service.updateTotal(); service.updateTotal();
} }
/** /**
* Gets called after the cart is updarted to refresh the total * Gets called after the cart is updarted to refresh the total
* *
@ -569,86 +515,74 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
* *
* @return void * @return void
*/ */
service.updateTotal = function(){ service.updateTotal = function () {
// Stop runing the method if the restaurant wasn't loaded yet // Stop runing the method if the restaurant wasn't loaded yet
if( !service.restaurant.id_restaurant ){ if (!service.restaurant.id_restaurant) {
return; return;
} }
service.info.totalText = service.info.dollarSign + service.charged(); service.info.totalText = service.info.dollarSign + service.charged();
var tipText = '', var tipText = '',
feesText = '', feesText = '',
totalItems = 0, totalItems = 0,
credit = 0, credit = 0,
hasFees = ((service.restaurant.delivery_fee && service.form.delivery_type == 'delivery') || service.restaurant.fee_customer) ? true : false; hasFees = ((service.restaurant.delivery_fee && service.form.delivery_type == 'delivery') || service.restaurant.fee_customer) ? true : false;
if (App.credit.restaurant[service.restaurant.id]) {
if (App.credit.restaurant[service.restaurant.id]) { credit = parseFloat(App.credit.restaurant[service.restaurant.id]);
credit = parseFloat(App.credit.restaurant[service.restaurant.id]); }
for (var x in service.items) {
totalItems++;
}
service._autotip();
/* If the user changed the delivery method to takeout and the payment is card
* the default tip will be 0%. If the delivery method is delivery and the payment is
* card the default tip will be autotip.
* If the user had changed the tip value the default value will be the chosen one.
*/
var wasTipChanged = false;
if (service.form.delivery_type == 'takeout' && service.form.pay_type == 'card') {
if (!service._tipHasChanged) {
service.form.tip = 0;
wasTipChanged = true;
} }
} else if (service.form.delivery_type == 'delivery' && service.form.pay_type == 'card') {
for (var x in service.items) { if (!service._tipHasChanged) {
totalItems++; service.form.tip = (App.config.user.last_tip) ? App.config.user.last_tip : 'autotip';
service.form.tip = service._lastTipNormalize(service.form.tip);
wasTipChanged = true;
} }
}
service._autotip(); if (wasTipChanged) {
// Forces the recalculation of total because the tip was changed.
/* If the user changed the delivery method to takeout and the payment is card service.info.totalText = service.info.dollarSign + this.charged();
* the default tip will be 0%. If the delivery method is delivery and the payment is }
* card the default tip will be autotip. var _total = service.restaurant.delivery_min_amt == 'subtotal' ? service.subtotal() : service.total();
* If the user had changed the tip value the default value will be the chosen one. if (service.restaurant.meetDeliveryMin(_total) && service.form.delivery_type == 'delivery') {
*/ service.info.deliveryMinDiff = service.restaurant.deliveryDiff(_total);
var wasTipChanged = false; } else {
if (service.form.delivery_type == 'takeout' && service.form.pay_type == 'card') { service.info.deliveryMinDiff = '';
if ( !service._tipHasChanged ) { }
service.form.tip = 0; service.info.totalItems = service.cart.totalItems();
wasTipChanged = true; service.info.extraCharges = service.extraChargesText(service.totalbreakdown());
} service.info.breakdownDescription = service.info.dollarSign + this.subtotal().toFixed(2);
} else if (service.form.delivery_type == 'delivery' && service.form.pay_type == 'card') { service.info.cartSummary = service.cart.summary();
if ( !service._tipHasChanged ) { if (App.order.pay_type == 'card' && credit > 0) {
service.form.tip = (App.config.user.last_tip) ? App.config.user.last_tip : 'autotip'; var creditLeft = '';
service.form.tip = service._lastTipNormalize( service.form.tip ); if (this.total() < credit) {
wasTipChanged = true; var creditLeft = '<span class="gift-left"> - You\'ll still have ' + service.info.dollarSign + App.ceil((credit - this.total())).toFixed(2) + ' gift card left </span>';
} credit = this.total();
} }
$('.cart-gift').html('&nbsp;(- ' + service.info.dollarSign + App.ceil(credit).toFixed(2) + ' credit ' + creditLeft + ') ');
if (wasTipChanged) { } else {
// Forces the recalculation of total because the tip was changed. $('.cart-gift').html('');
service.info.totalText = service.info.dollarSign + this.charged(); }
} setTimeout(function () {
if (App.order.pay_type == 'cash' && credit > 0 /* && App.giftcard.showGiftCardCashMessage */ ) {
var _total = service.restaurant.delivery_min_amt == 'subtotal' ? service.subtotal() : service.total(); $('.cart-giftcard-message').html('<span class="giftcard-payment-message">Pay with a card, NOT CASH, to use your ' + service.info.dollarSign + App.ceil(credit).toFixed(2) + ' gift card!</span>');
if (service.restaurant.meetDeliveryMin(_total) && service.form.delivery_type == 'delivery') {
service.info.deliveryMinDiff = service.restaurant.deliveryDiff(_total);
} else { } else {
service.info.deliveryMinDiff = ''; $('.cart-giftcard-message').html('');
} }
service.info.totalItems = service.cart.totalItems(); }, 1000);
service.info.extraCharges = service.extraChargesText( service.totalbreakdown() ); /* TODO: find out what this piece of code does
service.info.breakdownDescription = service.info.dollarSign + this.subtotal().toFixed(2);
service.info.cartSummary = service.cart.summary();
if (App.order.pay_type == 'card' && credit > 0) {
var creditLeft = '';
if (this.total() < credit) {
var creditLeft = '<span class="gift-left"> - You\'ll still have ' + service.info.dollarSign + App.ceil((credit - this.total())).toFixed(2) + ' gift card left </span>';
credit = this.total();
}
$('.cart-gift').html('&nbsp;(- ' + service.info.dollarSign + App.ceil(credit).toFixed(2) + ' credit ' + creditLeft + ') ');
} else {
$('.cart-gift').html('');
}
setTimeout(function () {
if (App.order.pay_type == 'cash' && credit > 0 /* && App.giftcard.showGiftCardCashMessage */ ) {
$('.cart-giftcard-message').html('<span class="giftcard-payment-message">Pay with a card, NOT CASH, to use your ' + service.info.dollarSign + App.ceil(credit).toFixed(2) + ' gift card!</span>');
} else {
$('.cart-giftcard-message').html('');
}
}, 1000);
/* TODO: find out what this piece of code does
$('.cart-item-customize-price').each(function () { $('.cart-item-customize-price').each(function () {
var dish = $(this).closest('.cart-item-customize').attr('data-id_cart_item'), var dish = $(this).closest('.cart-item-customize').attr('data-id_cart_item'),
option = $(this).closest('.cart-item-customize-item').attr('data-id_option'), option = $(this).closest('.cart-item-customize-item').attr('data-id_option'),
@ -660,7 +594,6 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
}); });
*/ */
} }
service._autotip = function () { service._autotip = function () {
var subtotal = service.totalbreakdown().subtotal; var subtotal = service.totalbreakdown().subtotal;
var autotipValue var autotipValue
@ -672,72 +605,87 @@ NGApp.factory( 'OrderService', function( $http, AccountService, CartService ){
} }
service.form.autotip = autotipValue; service.form.autotip = autotipValue;
} }
service._autotipText = function () {
service._autotipText = function(){
var autotipText = service.form.autotip ? ' (' + service.info.dollarSign + service.form.autotip + ')' : ''; var autotipText = service.form.autotip ? ' (' + service.info.dollarSign + service.form.autotip + ')' : '';
return 'Autotip' + autotipText; return 'Autotip' + autotipText;
} }
// Credit card years // Credit card years
service._years = function(){ service._years = function () {
var date = new Date().getFullYear();
var years = []; var years = [];
years.push({
value: '',
label: 'Year'
});
var date = new Date().getFullYear();
for (var x = date; x <= date + 20; x++) { for (var x = date; x <= date + 20; x++) {
years[years.length] = x; years.push({
value: x.toString(),
label: x.toString()
});
} }
return years; return years;
} }
// Credit card months // Credit card months
service._months = function(){ service._months = function () {
return [1,2,3,4,5,6,7,8,9,10,11,12]; var months = [];
months.push({
value: '',
label: 'Month'
});
for (var x = 1; x <= 12; x++) {
months.push({
value: x.toString(),
label: x.toString()
});
}
return months;
} }
// Tips // Tips
service._tips = function(){ service._tips = function () {
return [ { value : 'autotip', label : service._autotipText() }, var tips = [];
{ value : 0, label : 'Tip with cash' }, tips.push({
{ value : 10, label : 'tip 10 %' }, value: 'autotip',
{ value : 15, label : 'tip 15 %' }, label: service._autotipText()
{ value : 18, label : 'tip 18 %' }, });
{ value : 20, label : 'tip 20 %' }, tips.push({
{ value : 25, label : 'tip 25 %' }, value: 0,
{ value : 30, label : 'tip 30 %' }]; label: 'Tip with cash'
});
var _tips = [0, 10, 15, 18, 20, 25, 30];
for (var x in _tips) {
tips.push({
value: _tips[x],
label: 'tip ' + _tips[x] + ' %'
});
}
return tips;
} }
service._lastTipNormalize = function (lastTip) {
service._lastTipNormalize = function( lastTip ){
/* The default tip is autotip */ /* The default tip is autotip */
if( lastTip === 'autotip' ) { if (lastTip === 'autotip') {
return lastTip; return lastTip;
} }
if( service.account.user && service.account.user.last_tip_type && service.account.user.last_tip_type == 'number' ){ if (service.account.user && service.account.user.last_tip_type && service.account.user.last_tip_type == 'number') {
return 'autotip'; return 'autotip';
} }
// it means the last tipped value is not at the permitted value, return default. // it means the last tipped value is not at the permitted value, return default.
lastTip = parseInt( lastTip ); lastTip = parseInt(lastTip);
var tips = service._tips(); var tips = service._tips();
for( x in tips ){ for (x in tips) {
if( lastTip == parseInt( tips[ x ].value ) ){ if (lastTip == parseInt(tips[x].value)) {
return lastTip; return lastTip;
} }
} }
return 'autotip'; return 'autotip';
} }
return service; return service;
} ); });
// OrdersService service // OrdersService service
NGApp.factory('OrdersService', function ($http, $location) { NGApp.factory('OrdersService', function ($http, $location) {
var service = { var service = {
list: false list: false
}; };
service.all = function () { service.all = function () {
$http.get(App.service + 'user/orders', { $http.get(App.service + 'user/orders', {
cache: true cache: true
}).success(function (json) { }).success(function (json) {
@ -746,35 +694,24 @@ NGApp.factory('OrdersService', function ($http, $location) {
} }
service.list = json; service.list = json;
}); });
} }
service.restaurant = function (permalink) { service.restaurant = function (permalink) {
$location.path('/' + App.restaurants.permalink + '/' + permalink); $location.path('/' + App.restaurants.permalink + '/' + permalink);
}; };
service.receipt = function (id_order) { service.receipt = function (id_order) {
$location.path('/order/' + id_order); $location.path('/order/' + id_order);
}; };
return service; return service;
}); });
// OrdersService service // OrdersService service
NGApp.factory('OrderViewService', function ( $routeParams, $location, $rootScope, FacebookService) { NGApp.factory('OrderViewService', function ($routeParams, $location, $rootScope, FacebookService) {
var service = {}; var service = {};
service.facebook = FacebookService; service.facebook = FacebookService;
App.cache('Order', $routeParams.id, function () {
App.cache( 'Order', $routeParams.id, function () {
service.order = this; service.order = this;
var complete = function () { var complete = function () {
$location.path('/'); $location.path('/');
}; };
if (!service.order.uuid) { if (!service.order.uuid) {
if (!$rootScope.$$phase) { if (!$rootScope.$$phase) {
$rootScope.$apply(complete); $rootScope.$apply(complete);
@ -783,23 +720,17 @@ NGApp.factory('OrderViewService', function ( $routeParams, $location, $rootScope
} }
return; return;
} }
service.facebook._order_uuid = service.order.uuid; service.facebook._order_uuid = service.order.uuid;
service.facebook.preLoadOrderStatus(); service.facebook.preLoadOrderStatus();
App.cache('Restaurant', service.order.id_restaurant, function () { App.cache('Restaurant', service.order.id_restaurant, function () {
service.restaurant = this; service.restaurant = this;
var complete = function () { var complete = function () {
if (service.order['new']) {
if (service.order['new']) { setTimeout(function () {
setTimeout(function () { service.order['new'] = false;
service.order['new'] = false; }, 500);
}, 500); }
} };
};
if (!$rootScope.$$phase) { if (!$rootScope.$$phase) {
$rootScope.$apply(complete); $rootScope.$apply(complete);
} else { } else {
@ -808,5 +739,4 @@ NGApp.factory('OrderViewService', function ( $routeParams, $location, $rootScope
}); });
}); });
return service; return service;
}); });