Best JavaScript code snippet using qawolf
C2.js
Source:C2.js
1/**2 * @author dsokol3 */4function C2() {5 var Mask = require('mask');6 var moment = require('moment');7 var me = {8 debugMode : false,9 baseSvcUrl : 'https://www.ballparkconcierge.com/data/wcf.svc/',10 stripeTokenSvcUrl : 'https://api.stripe.com/v1/tokens',11 //stripePublishableKey: 'pk_test_yBtBDP9MPxfeZay5RizEiOOR',12 stripePublishableKey : 'pk_live_imZ4gn7hfr3aenXwgGNW3WNS',13 //baseSvcUrl: 'http://10.0.0.15/Data/wcf.svc/',14 isAuthenticated : false,15 customerEmail : '',16 customerFirstName : '',17 customerLastName : '',18 customerGuid : null,19 customerSavedVendorID : 26,20 customerSection : null,21 customerRow : null,22 customerSeat : null,23 orderCreditCardId : null,24 creditCardInfo : null,25 hasPayment : false,26 saveCard : false,27 condiments : [],28 cartItems : [],29 pastOrders : [],30 orderType : 1,31 orderTypeText : "PICKUP",32 tipAmount : 1,33 // this is the order format we send to wcf service34 customerCurrentOrder : {35 UserGuid : '',36 Order : {37 SpecialInstructions : 'test',38 VendorOrderNumber : 'VEN',39 VendorID : 13,40 FulfillmentTypeID : 1,41 OrderItems : [{42 MenuItemID : 31,43 Quantity : 1,44 OrderItemAddons : [{45 MenuItemID : 3546 }]47 }]48 },49 StripeToken : '',50 SaveCard : false51 },52 orderFees : {53 serviceFee : 1.00,54 deliveryServiceFee : 2.0055 },56 settings : Alloy.Models.instance("settings"),57 vendor : Alloy.Models.instance('vendor'),58 venue : Alloy.Models.instance('venue'),59 pastOrders : Alloy.Collections.pastOrders,60 vendorMenuItems : Alloy.Collections.vendorMenuItems,61 vendorMenu : [],62 vendorMinServiceFee : 0.0,63 vendorMaxServiceFee : 0.0,64 vendorServiceFeePercentage : 0.0,65 vendorCanDeliver : false,66 vendorInfo : null,67 mainWindow : null,68 loginWindow : null,69 runnerMainWindow : null70 };71 // Utlity functions72 me.customerName = function() {73 return me.customerFirstName + ' ' + me.customerLastName;74 };75 me.showAlert = function(title, message) {76 var dialog = Ti.UI.createAlertDialog({77 title : title,78 message : message,79 ok : 'Okay'80 });81 dialog.show();82 };83 me.selectPickup = function() {84 me.orderType = 1;85 me.orderTypeText = "PICKUP";86 me.refreshFooter();87 };88 me.selectDelivery = function(section, row, seat) {89 me.orderType = 2;90 me.orderTypeText = "DELIVERY";91 if (section)92 me.customerSection = section;93 if (row)94 me.customerRow = row;95 if (seat)96 me.customerSeat = seat;97 me.refreshFooter();98 };99 me.selectTrackDelivery = function(section, row, seat) {100 me.orderType = 2;101 me.orderTypeText = "DELIVERY";102 me.customerSection = '';103 me.customerRow = '';104 me.customerSeat = '';105 };106 me.refreshFooter = function() {107 if (me.mainWindow)108 me.mainWindow.refreshFooter();109 };110 me.postAsync = function(method, data, success, error) {111 try {112 if (Titanium.Network.networkType === Titanium.Network.NETWORK_NONE) {113 console.log("no network connection found");114 success({}, -1, "No network connection found, please ensure you are connected to the internet");115 return;116 }117 var xhr = Ti.Network.createHTTPClient();118 //xhr.setOption(2, 13056);119 xhr.timeout = 30000;120 var url = me.baseSvcUrl + method;121 Ti.API.info('---method url--- ' + url);122 Ti.API.info('---method data--- ' + JSON.stringify(data));123 xhr.open("POST", url);124 xhr.setRequestHeader("Content-Type", "application/json");125 xhr.onload = function() {126 Ti.API.info('---postAsync---- ' + this.responseText);127 if (this.responseText) {128 if (me.debugMode) {129 console.log("resp", this.responseText);130 }131 try {132 var resp = JSON.parse(this.responseText);133 var msg = resp.Message;134 var status = resp.Status;135 var payload = JSON.parse(resp.Payload);136 //Ti.API.info('=====method===== ' + method + ' ===payload=== ' + JSON.stringify(payload));137 success(payload, status, msg);138 } catch (e) {139 error(e);140 }141 } else {142 error();143 }144 };145 xhr.onerror = function(e) {146 console.log("xhr error", e, this.responseText);147 error();148 };149 var d = data;150 if (!d)151 d = {};152 if (me.debugMode) {153 console.log("posting " + JSON.stringify(d) + " to " + url);154 }155 xhr.send(JSON.stringify(d));156 } catch(e) {157 error(e);158 }159 };160 // *************161 // location services API calls162 me.getVenueLocations = function(query, success, error) {163 me.getVenueLocationsByQuery({164 Query : query165 }, success, error);166 };167 me.getVenueLocationsByLatLong = function(lat, longitude, success, error) {168 me.getVenueLocationsByGeoloction({169 Latitude : lat,170 Longitude : longitude171 }, success, error);172 };173 // *************174 // stripe service calls175 // data should have number, expMonth, expYear, cvc, zip, and name176 me.createStripeCardToken = function(data, success, error) {177 try {178 var xhr = Ti.Network.createHTTPClient();179 xhr.timeout = 30000;180 var url = me.stripeTokenSvcUrl;181 xhr.open("POST", url);182 xhr.setRequestHeader("Authorization", "Bearer " + me.stripePublishableKey);183 xhr.onload = function() {184 if (this.responseText) {185 try {186 var resp = JSON.parse(this.responseText);187 console.log("stripe resp", resp);188 success(resp);189 } catch (e) {190 console.log("ERROR in createStripeCardToken onload", e);191 error("credit card could not be procesed");192 }193 } else {194 error("credit card could not be processed");195 }196 };197 xhr.onerror = function(e) {198 if (xhr.responseText) {199 var resp = JSON.parse(xhr.responseText);200 if (resp.error && resp.error.message) {201 error(resp.error.message);202 return;203 }204 }205 error("credit card could not be processed.");206 };207 var d = "card[number]=" + data.number + ";card[exp_month]=" + data.expMonth + ";card[exp_year]=" + data.expYear + ";card[cvc]=" + data.cvc + ";card[address_zip]=" + data.zip + ";card[name]=" + data.name;208 console.log("posting " + d + " to " + url);209 xhr.send(d);210 } catch(e) {211 error(e);212 }213 };214 // *************215 // wcf service calls216 //SvcReturnObject SendCustomerSupportMessage(Guid UserGUID, string Title, string Message)217 me.sendCustomerSupportMessage = function(data, success, error) {218 me.postAsync("SendCustomerSupportMessage", data, success, error);219 };220 // SvcReturnObject CreateCustomer(string FirstName, string LastName, string Email, string Phone, string Password, bool AllowSMSNotifications = true, bool AllowEmailNotifications = true)221 me.createCustomer = function(data, success, error) {222 me.postAsync("CreateCustomer", data, success, error);223 };224 me.CreateFacbookCustomer = function(data, success, error) {225 me.postAsync("CreateFacebookCustomer", data, success, error);226 };227 me.createOrder = function(data, success, error) {228 me.postAsync("CreateOrder", data, success, error);229 };230 me.createCashOrder = function(data, success, error) {231 Ti.API.info('----createCashOrder---- ' + JSON.stringify(data));232 me.postAsync("CreateCashOrder", data, success, error);233 };234 me.DonateWithStripe = function(data, success, error) {235 Ti.API.info('----DonateWithStripe---- ' + JSON.stringify(data));236 me.postAsync("DonateWithStripe", data, success, error);237 };238 me.DonateWithPaypal = function(data, success, error) {239 Ti.API.info('----DonateWithPaypal---- ' + JSON.stringify(data));240 me.postAsync("DonateWithPaypal", data, success, error);241 };242 me.getCustomerInfo = function(data, success, error) {243 me.postAsync("GetCustomerInfo", data, success, error);244 };245 me.GetHeaderFooterList = function(data, success, error) {246 me.postAsync("GetHeaderFooterList", data, success, error);247 };248 me.GetGoalsByVendor = function(data, success, error) {249 me.postAsync("GetGoalsByVendor", data, success, error);250 };251 me.UpdateVendorGoalById = function(data, success, error) {252 me.postAsync("UpdateVendorGoalById", data, success, error);253 };254 // public SvcReturnObject GetCustomerOrderStatus(Guid UserGUID, int OrderID)255 me.getCustomerOrderStatus = function(data, success, error) {256 me.postAsync("GetCustomerOrderStatus", data, success, error);257 };258 // public SvcReturnObject GetCustomerOrder(Guid UserGUID, int OrderID)259 me.getCustomerOrder = function(data, success, error) {260 me.postAsync("GetCustomerOrder", data, success, error);261 };262 // public SvcReturnObject GetCustomerOrders(Guid UserGUID)263 me.getCustomerOrders = function(data, success, error) {264 me.postAsync("GetCustomerOrders", data, success, error);265 };266 me.deleteStripeCard = function(data, success, error) {267 me.postAsync("DeleteStripeCard", data, success, error);268 };269 me.getMenuItemsForCustomer = function(data, success, error) {270 //return me.postAsync("GetMenuItemsForCustomerWithImageURL", data, success, error);271 return me.postAsync("GetMenuItemsForCustomerWithCombo", data, success, error);272 };273 me.updateCustomer = function(data, success, error) {274 return me.postAsync("UpdateCustomer", data, success, error);275 };276 me.getStripeCards = function(data, success, error) {277 return me.postAsync("GetStripeCards", data, success, error);278 };279 me.saveStripeCard = function(data, success, error) {280 return me.postAsync("SaveCard", data, success, error);281 };282 me.getVendorInfo = function(data, success, error) {283 return me.postAsync("GetVendorInfo", data, success, error);284 };285 // SvcReturnObject GetVendors(int? VenueID)286 me.getVendors = function(data, success, error) {287 return me.postAsync("GetVendors", data, success, error);288 };289 // SvcReturnObject GetVenueLocationsByGeoloction(string Latitude, string Longitude, double? MileRadius)290 me.getVenueLocationsByGeoloction = function(data, success, error) {291 me.postAsync("GetVenueLocationsByGeoloction", data, success, error);292 };293 //public SvcReturnObject GetVenueLocationsByZipCode(string City, string State)294 me.getVenueLocationsByZipCode = function(data, success, error) {295 me.postAsync("GetVenueLocationsByZipCode", data, success, error);296 };297 //public SvcReturnObject GetVenueLocationsByQuery(string Query)298 me.getVenueLocationsByQuery = function(data, success, error) {299 me.postAsync("GetVenueLocationsByQuery", data, success, error);300 };301 // SvcReturnObject LoginCustomer(string Email, string Password)302 me.loginCustomer = function(data, success, error) {303 me.postAsync("LoginCustomer", data, success, error);304 };305 // SvcReturnObject LoginCustomer(string Email, string Password)306 me.loginRunner = function(data, success, error) {307 me.postAsync("LoginRunner", data, success, error);308 };309 me.sendForgotPasswordEmailToCustomer = function(data, success, error) {310 me.postAsync("SendForgotPasswordEmailToCustomer", data, success, error);311 };312 me.Test = function(data, success, error) {313 me.postAsync("Test", data, success, error);314 };315 me.changePasswordForCustomerWithChangePasswordGUID = function(data, success, error) {316 me.postAsync("ChangePasswordForCustomerWithChangePasswordGUID", data, success, error);317 };318 me.changePassword = function(password, newPassword, success, error) {319 var data = {320 UserGUID : me.customerGuid.UserGUID,321 Password : password,322 NewPassword : newPassword323 };324 me.updateCustomerPassword(data, success, error);325 };326 me.updateCustomerPassword = function(data, success, error) {327 me.postAsync("UpdateCustomerPassword", data, success, error);328 };329 // *************330 // auth functions331 me.authenticateUser = function(email, password, success, error) {332 var data = {333 Email : email,334 Password : password,335 PlayerId : Ti.App.Properties.getString("ONESIGNAL_PLAYER_ID")336 };337 me.loginCustomer(data, function(resp, status, msg) {338 if (status == 1) {339 me.isAuthenticated = true;340 me.customerEmail = email;341 me.customerGuid = resp;342 console.log("user logged in, customer guid: " + JSON.stringify(resp));343 console.log("user logged in, customer guid: " + me.customerGuid);344 Ti.App.Properties.setString("lastUserEmail", email);345 Ti.App.Properties.setString("lastUserPassword", password);346 Ti.App.Properties.setBool("isRunner", false);347 Alloy.Globals.lastUserPasssword = password;348 }349 success(resp, status, msg);350 }, function() {351 error();352 });353 };354 // auth functions355 me.authenticateRunner = function(email, password, success, error) {356 var data = {357 Email : email,358 Password : password,359 PlayerId : Ti.App.Properties.getString("ONESIGNAL_PLAYER_ID")360 };361 me.loginRunner(data, function(resp, status, msg) {362 if (status == 1) {363 Ti.API.info('=====loginRunner resp===== ' + JSON.stringify(resp));364 me.isAuthenticated = true;365 me.customerEmail = email;366 me.customerGuid = resp;367 //me.VendorGUID = resp.VendorGUID;368 console.log("user logged in, customer guid: " + JSON.stringify(resp));369 console.log("user logged in, customer guid: " + me.customerGuid);370 Ti.App.Properties.setString("lastUserEmail", email);371 Ti.App.Properties.setString("VendorGUID", resp.VendorGUID);372 Ti.App.Properties.setString("runnerID", resp.ID);373 Ti.App.Properties.setString("lastUserPassword", password);374 Ti.App.Properties.setBool("isRunner", true);375 var localVenue = {376 id : resp.Venue.id,377 name : resp.Venue.VenueName,378 address : resp.Venue.Address,379 cityStateZip : resp.Venue.City + ", " + resp.Venue.State + " " + resp.Venue.Zip380 };381 var vendorJson = resp.Vendor;382 me.setVenue(localVenue.id, localVenue.name, localVenue.address, localVenue.cityStateZip);383 me.setVendor(vendorJson.VendorId, vendorJson.Name, vendorJson.Description, vendorJson.serviceFee, vendorJson, vendorJson.CanDeliver);384 Alloy.Globals.lastVendorID = vendorJson.VendorId;385 Alloy.Globals.lastUserPasssword = password;386 }387 success(resp, status, msg);388 }, function() {389 Ti.API.info(' ====loginRunner error==== ');390 error();391 });392 };393 me.signOut = function() {394 var dialog = Ti.UI.createAlertDialog({395 cancel : 1,396 buttonNames : ['Yes', 'No'],397 message : 'Are you sure you want to continue? You will be logged out and your cart will be cleared.',398 title : 'Confirm log out'399 });400 dialog.addEventListener('click', function(e) {401 if (e.index === e.source.cancel) {402 Ti.API.info('The cancel button was clicked');403 } else {404 me.clearCart();405 me.isAuthenticated = false;406 me.customerEmail = "";407 me.customerGuid = "";408 Ti.App.Properties.setString("lastUserPassword", "");409 me.mainWindow.close();410 }411 });412 dialog.show();413 };414 // *************415 // cart functions416 me.getServiceCharge = function(subTotal, orderItems) {417 if (me.orderFees.calcFee) {418 try {419 return me.orderFees.calcFee(me.getOrderItems(), me.orderType);420 } catch(e) {421 console.log("ERROR Calculating total", e);422 }423 }424 if (me.orderType == 2) {425 return me.orderFees.deliveryServiceFee;426 } else {427 return me.orderFees.serviceFee;428 }429 var serviceCharge = subTotal * me.vendorServiceFeePercentage;430 if (serviceCharge < me.vendorMinServiceFee) {431 serviceCharge = me.vendorMinServiceFee;432 } else if (serviceCharge > me.vendorMaxServiceFee) {433 serviceCharge = me.vendorMaxServiceFee;434 }435 return serviceCharge;436 };437 me.updateCartCountText = function() {438 var text = "";439 if (me.cartItems.length) {440 text = me.cartItems.length + " item";441 if (me.cartItems.length > 1) {442 text = text + "s";443 }444 text = text + " in your cart";445 }446 me.settings.set("cartCountText", text);447 };448 me.addItemToCart = function(item) {449 me.cartItems.push(item);450 me.settings.set("cartCount", me.cartItems.length);451 me.settings.set("cartEmpty", 0);452 me.settings.set("isCartEmpty", false);453 me.settings.set("isItemInCart", true);454 me.updateCartCountText();455 me.settings.save();456 if (me.mainWindow && me.mainWindow.notify) {457 me.mainWindow.notify("item added to cart!");458 }459 if (me.mainWindow) {460 me.mainWindow.refreshFooter();461 }462 };463 me.clearCart = function() {464 me.cartItems = [];465 me.settings.set("cartCount", 0);466 me.settings.set("cartEmpty", 1);467 me.settings.set("isCartEmpty", true);468 me.settings.set("isItemInCart", false);469 me.settings.set("specialInstructions", "");470 me.updateCartCountText();471 me.settings.save();472 /*473 if(me.mainWindow && me.mainWindow.notify) {474 me.mainWindow.notify("cart cleard!");475 }476 */477 if (me.mainWindow) {478 console.log("refreshing footer");479 me.mainWindow.refreshFooter();480 }481 };482 me.getCartSubTotal = function() {483 var subTotal = 0.00;484 for (var i = 0; i < me.cartItems.length; i++) {485 var item = me.cartItems[i];486 subTotal += (item.price * item.quantity);487 if (item.addOns) {488 for (var j = 0; j < item.addOns.length; j++) {489 var addOn = item.addOns[j];490 subTotal += (addOn.price * item.quantity);491 }492 }493 }494 return subTotal;495 };496 me.removeItemFromCart = function(item) {497 var index = me.cartItems.indexOf(item);498 if (index > -1) {499 me.cartItems.splice(index, 1);500 }501 me.settings.set("cartCount", me.cartItems.length);502 me.settings.set("cartEmpty", me.cartItems.length == 0);503 if (me.cartItems.length == 0) {504 me.settings.set("isCartEmpty", true);505 me.settings.set("isItemInCart", false);506 }507 me.updateCartCountText();508 me.settings.save();509 if (me.mainWindow) {510 me.mainWindow.refreshFooter();511 }512 };513 me.setPastOrders = function(orders) {514 };515 // *************516 // utility functions517 me.getFontAwesomeIconFromStripeCardBrand = function(ccBrand) {518 /*519 * he brand parameter of the card object exposes whether the card brand is520 * Visa, American Express, MasterCard, Discover, JCB or Diners Club.521 * A card brand may be Unknown if we are unable to determine its brand.522 */523 var ret = "fa-credit-card";524 switch(ccBrand.toLowerCase()) {525 case "visa":526 ret = "fa-cc-visa";527 break;528 case "american express":529 ret = "fa-cc-amex";530 break;531 case "mastercard":532 ret = "fa-cc-mastercard";533 break;534 case "discover":535 ret = "fa-cc-discover";536 break;537 case "jcb":538 ret = "fa-cc-jcb";539 break;540 case "diners club":541 ret = "fa-cc-diners-club";542 break;543 }544 return ret;545 };546 me.getOrderItems = function() {547 var orderItems = [];548 for (var i = 0; i < me.cartItems.length; i++) {549 var item = me.cartItems[i];550 var itemAddons = [];551 if (item.addOns && item.addOns.length > 0) {552 for (var j = 0; j < item.addOns.length; j++) {553 var addOn = item.addOns[j];554 itemAddons.push({555 MenuItemID : addOn.id556 });557 }558 }559 orderItems.push({560 MenuItemID : item.id,561 Quantity : item.quantity,562 OrderItemAddons : itemAddons563 });564 }565 return orderItems;566 };567 me.getCashOrderForSubmission = function() {568 var subTotal = me.getCartSubTotal();569 //var serviceFee = me.vendor.get("serviceFee");570 var serviceFee = me.getServiceCharge(subTotal, me.cartItems);571 var tip = 0;572 //if (me.orderType == 2) {573 tip = me.tipAmount;574 //}575 var total = subTotal + serviceFee + tip;576 var o = {577 UserGUID : Ti.App.Properties.getBool("isRunner") ? null : me.customerGuid.UserGUID,578 RunnerId : Ti.App.Properties.getBool("isRunner") ? Ti.App.Properties.getString("runnerID") : null,579 Order : {580 Subtotal : subTotal,581 ServiceFee : serviceFee,582 TipAmount : tip,583 Total : total,584 SpecialInstructions : me.settings.get("specialInstructions"),585 VendorOrderNumber : '',586 VendorID : me.vendor.get("id"),587 FulfillmentTypeID : me.orderType,588 },589 Latitude : Ti.App.Properties.getString('user_latitude'),590 Longitude : Ti.App.Properties.getString('user_longitude')591 };592 orderItems = [];593 for (var i = 0; i < me.cartItems.length; i++) {594 Ti.API.info('---me.cartItems.--- ' + JSON.stringify(me.cartItems));595 var item = me.cartItems[i];596 var itemAddons = [];597 if (item.addOns && item.addOns.length > 0) {598 for (var j = 0; j < item.addOns.length; j++) {599 var addOn = item.addOns[j];600 itemAddons.push({601 MenuItemID : addOn.id602 });603 }604 }605 orderItems.push({606 MenuItemID : item.id,607 Quantity : item.quantity,608 OrderItemAddons : itemAddons,609 IsCombo : item.IsCombo610 });611 }612 o.Order.OrderItems = orderItems;613 if (me.orderType == 2) {614 o.Order.OrderLocations = [{615 CustomerName : me.customerName(),616 Section : me.customerSection,617 Row : me.customerRow,618 Seat : me.customerSeat619 }];620 }621 return o;622 };623 me.getOrderTotalAndFee = function(data, success, error) {624 if (!data) {625 data = {626 VendorID : me.vendor.get("id"),627 FulfillmentType : me.orderType,628 PaymentType : null,629 OrderItems : me.getOrderItems()630 };631 }632 me.postAsync("GetOrderTotalAndFee", data, success, error);633 };634 me.getOrderForSubmission = function() {635 var subTotal = parseFloat(me.getCartSubTotal());636 var ccFee = parseFloat((subTotal * .035).toFixed(2));637 //var serviceFee = me.vendor.get("serviceFee");638 var serviceFee = parseFloat(me.getServiceCharge(subTotal, me.cartItems)) + ccFee;639 var tip = 0;640 if (me.orderType == 2) {641 tip = me.tipAmount;642 }643 var total = subTotal + serviceFee + parseFloat(tip);644 var o = {645 UserGUID : Ti.App.Properties.getBool("isRunner") ? null : me.customerGuid.UserGUID,646 RunnerId : Ti.App.Properties.getBool("isRunner") ? Ti.App.Properties.getString("runnerID") : null,647 Order : {648 Subtotal : subTotal,649 ServiceFee : serviceFee,650 TipAmount : tip,651 Total : total,652 SpecialInstructions : me.settings.get("specialInstructions"),653 VendorOrderNumber : '',654 VendorID : me.vendor.get("id"),655 FulfillmentTypeID : me.orderType,656 },657 StripeToken : me.creditCardInfo.id,658 StripeCardID : me.orderCreditCardId,659 SaveCard : me.saveCard,660 Latitude : Ti.App.Properties.getString('user_latitude'),661 Longitude : Ti.App.Properties.getString('user_longitude')662 };663 orderItems = [];664 for (var i = 0; i < me.cartItems.length; i++) {665 var item = me.cartItems[i];666 var itemAddons = [];667 if (item.addOns && item.addOns.length > 0) {668 for (var j = 0; j < item.addOns.length; j++) {669 var addOn = item.addOns[j];670 itemAddons.push({671 MenuItemID : addOn.id672 });673 }674 }675 orderItems.push({676 MenuItemID : item.id,677 Quantity : item.quantity,678 OrderItemAddons : itemAddons679 });680 }681 o.Order.OrderItems = orderItems;682 if (me.orderType == 2) {683 o.Order.OrderLocations = [{684 CustomerName : me.customerName(),685 Section : me.customerSection,686 Row : me.customerRow,687 Seat : me.customerSeat688 }];689 }690 return o;691 };692 me.getOrderStatus = function(id, success, error) {693 if (me.customerGuid && me.customerGuid.UserGUID) {694 me.getCustomerOrder({695 UserGUID : me.customerGuid.UserGUID,696 OrderID : id697 }, function(data, status, msg) {698 success(data, status, msg);699 }, function(err) {700 error(err);701 });702 } else if (Ti.App.Properties.getBool("isRunner")) {703 me.getCustomerOrder({704 OrderID : id705 }, function(data, status, msg) {706 success(data, status, msg);707 }, function(err) {708 error(err);709 });710 }711 };712 me.goToHome = function() {713 me.mainWindow.goToHome();714 };715 me.goToPastOrders = function(backButtonHandler) {716 if (me.customerGuid && me.customerGuid.UserGUID) {717 console.log("getting past orders...");718 me.mainWindow.showLoading("Retreiving orders...");719 me.getCustomerOrders(me.customerGuid, function(data, status, msg) {720 Ti.API.info('======data======= ' + JSON.stringify(data));721 if (status == 1) {722 console.log("got orders successfully " + JSON.stringify(data));723 me.pastOrders.fetch();724 for (var i = me.pastOrders.models.length - 1; i >= 0; i--) {725 me.pastOrders.models[i].destroy();726 }727 for (var i = data.length - 1; i > -1; i--) {728 var item = data[i];729 var createdAt = moment.utc(item.CreatedAt).toDate();730 createdAt = createdAt - createdAt.getTimezoneOffset();731 var o = me.pastOrders.push({732 id : item.OrderID,733 vendorOrderNumber : item.VendorOrderNumber,734 serviceFee : item.ServiceFee,735 subTotal : item.Subtotal,736 total : item.Total,737 vendorID : item.Vendor.VendorID,738 vendorName : item.Vendor.Name,739 vendorDescription : item.Vendor.Description,740 venueID : item.Venue.VenueID,741 venueName : item.Venue.VenueName,742 venueAddress : item.Venue.Address,743 venueCity : item.Venue.City,744 venueState : item.Venue.State,745 venueZip : item.Venue.Zip,746 orderStatusID : item.OrderStatus.OrderStatusID,747 orderStatusName : item.OrderStatus.Name,748 orderStatusDescription : item.OrderStatus.Description,749 fulfillmentTypeName : item.FulfillmentTypeName,750 specialInstructions : item.SpecialInstructions,751 itemCount : item.OrderItems.length,752 delivering : (item.OrderStatus.Name == "Delivering") ? true : false,753 serviceFeeTxt : "$" + parseFloat(item.ServiceFee).toFixed(2),754 subTotalTxt : "$" + parseFloat(item.Subtotal).toFixed(2),755 totalTxt : "$" + parseFloat(item.Total).toFixed(2),756 vendorOrderNumberTxt : "Order #" + item.VendorOrderNumber,757 dateCreatedTxt : moment(createdAt).format("M/D/YYYY h:mm A"),758 orderStatusWidth : item.OrderStatus.PercentComplete + "%"759 });760 o.save();761 }762 var backFunc = backButtonHandler ||763 function() {764 me.goToHome();765 };766 me.mainWindow.changeView('pastOrdersView', 'Past Orders', true, backFunc);767 } else {768 alert("Error getting past orders: " + msg);769 }770 me.mainWindow.hideLoading();771 }, function(err) {772 me.mainWindow.hideLoading();773 if (err) {774 alert("Error getting past orders: " + err);775 } else {776 alert("Error getting past orders");777 }778 });779 } else {780 console.log("getting past orders else...");781 me.mainWindow.showLoading("Retreiving orders...");782 me.getCustomerOrders(me.customerGuid, function(data, status, msg) {783 console.log("got orders successfully " + JSON.stringify(data));784 if (status == 1) {785 me.pastOrders.fetch();786 for (var i = me.pastOrders.models.length - 1; i >= 0; i--) {787 me.pastOrders.models[i].destroy();788 }789 for (var i = data.length - 1; i > -1; i--) {790 var item = data[i];791 var createdAt = moment.utc(item.CreatedAt).toDate();792 createdAt = createdAt - createdAt.getTimezoneOffset();793 var o = me.pastOrders.push({794 id : item.OrderID,795 vendorOrderNumber : item.VendorOrderNumber,796 serviceFee : item.ServiceFee,797 subTotal : item.Subtotal,798 total : item.Total,799 vendorID : item.Vendor.VendorID,800 vendorName : item.Vendor.Name,801 vendorDescription : item.Vendor.Description,802 venueID : item.Venue.VenueID,803 venueName : item.Venue.VenueName,804 venueAddress : item.Venue.Address,805 venueCity : item.Venue.City,806 venueState : item.Venue.State,807 venueZip : item.Venue.Zip,808 orderStatusID : item.OrderStatus.OrderStatusID,809 orderStatusName : item.OrderStatus.Name,810 orderStatusDescription : item.OrderStatus.Description,811 fulfillmentTypeName : item.FulfillmentTypeName,812 specialInstructions : item.SpecialInstructions,813 itemCount : item.OrderItems.length,814 serviceFeeTxt : "$" + parseFloat(item.ServiceFee).toFixed(2),815 subTotalTxt : "$" + parseFloat(item.Subtotal).toFixed(2),816 totalTxt : "$" + parseFloat(item.Total).toFixed(2),817 vendorOrderNumberTxt : "Order #" + item.VendorOrderNumber,818 dateCreatedTxt : moment(createdAt).format("M/D/YYYY h:mm A"),819 orderStatusWidth : item.OrderStatus.PercentComplete + "%"820 });821 o.save();822 }823 var backFunc = backButtonHandler ||824 function() {825 me.goToHome();826 };827 me.mainWindow.changeView('pastOrdersView', 'Past Orders', true, backFunc);828 } else {829 alert("Error getting past orders: else " + msg);830 }831 me.mainWindow.hideLoading();832 }, function(err) {833 me.mainWindow.hideLoading();834 if (err) {835 alert("Error getting past orders: err" + err);836 } else {837 alert("Error getting past orders");838 }839 });840 }841 };842 me.goToVendorMenu = function(backButtonHandler) {843 if (me.vendor.has("id")) {844 me.mainWindow.showLoading("Getting menu...");845 /*me.vendorMenuItems.fetch();846 for (var i = me.vendorMenuItems.models.length-1; i >= 0; i--) {847 me.vendorMenuItems.models[i].destroy();848 }*/849 me.vendorMenu = [];850 me.getMenuItemsForCustomer({851 VendorID : me.vendor.get("id")852 }, function(resp, status, msg) {853 if (status == 1) {854 //console.log("got menu items for customer successfully " + status + msg);855 console.log("--MENU RESPONSE--> " + JSON.stringify(resp));856 //var imageBlob = Ti.Utils.base64decode(resp[0].Image);857 // set condiments858 me.condiments = [];859 for (var i = 0; i < resp.menuitem.length; i++) {860 var item = resp.menuitem[i];861 //console.log("item", item.Name, item.MenuItemType.MenuItemTypeID);862 //if(!item.Image) continue;863 if (item.MenuItemType.IsCondiment) {864 me.condiments.push(item);865 }866 //console.log(item);867 var m = {868 id : item.MenuItemID,869 itemName : item.Name,870 menuItemTypeID : item.MenuItemType.MenuItemTypeID,871 price : item.Price,872 isCondiment : item.MenuItemType.IsCondiment,873 canCustomize : item.MenuItemType.MenuItemTypeID == 1,874 priceTxt : "$" + parseFloat(item.Price).toFixed(2),875 itemImage : item.imageUrl,876 isAlcohol : item.IsAlcohol,877 type : "item",878 properties : {// Sets the label properties879 backgroundColor : '#5568a2',880 backgroundImage : null//"/images/Rectangle.png"881 },882 item_parent : {883 backgroundColor : '#5568a2',884 }885 };886 m.id = {887 text : item.MenuItemID888 };889 m.CanCustomize = {890 visible : false,//m.canCustomize891 };892 m.ItemImage = {893 image : m.itemImage,894 id : m.id,895 defaultImage : "/images/loading.png"896 };897 m.ItemName = {898 text : m.itemName899 };900 m.Price = {901 text : m.price902 };903 m.PriceText = {904 text : m.priceTxt905 };906 m.type = {907 text : m.type908 };909 m.sepParent = {910 visible : false911 };912 // alcohol913 me.vendorMenu.push(m);914 //m.set("itemImage", Ti.Utils.base64decode(item.Image));915 //m.save();916 }917 for (var i = 0; i < resp.Comboitems.length; i++) {918 var item = resp.Comboitems[i];919 //console.log(item);920 var m = {921 id : item.ComboId,922 itemName : item.ComboName,923 menuItemTypeID : 1, //"combo"+i,924 price : item.ComboPrice,925 isCondiment : false,926 canCustomize : false,927 priceTxt : "$" + parseFloat(item.ComboPrice).toFixed(2),928 itemImage : "",929 isAlcohol : false,930 type : "combo",931 properties : {// Sets the label properties932 backgroundColor : null, //'#5568a2',933 backgroundImage : "/images/Rectangle.png",934 top : 5,935 },936 item_parent : {937 //backgroundImage : "/images/Rectangle.png"938 }939 };940 m.id = {941 text : m.id942 };943 m.CanCustomize = {944 visible : m.canCustomize945 };946 m.ItemImage = {947 image : m.itemImage,948 id : m.id,949 visible : false950 };951 m.ItemName = {952 text : m.itemName,953 left : 10,954 top : 10,955 right : null,956 font : {957 fontSize : "24",958 fontWeight : "normal"959 },960 color : "#000"961 };962 m.Price = {963 text : m.price,964 };965 m.PriceText = {966 text : m.priceTxt,967 left : 10,968 top : 40,969 right : null,970 font : {971 fontSize : "24",972 fontWeight : "normal"973 },974 color : "#000"975 };976 m.type = {977 text : m.type978 };979 m.textParent = {980 left : 0,981 layout : 'absolute',982 width : Ti.UI.FILL,983 top : 5984 };985 m.sepParent = {986 visible : false987 };988 m.btn_parent = {989 width : '50%',990 right : 5,991 bottom : 5,992 };993 // alcohol994 me.vendorMenu.push(m);995 //m.set("itemImage", Ti.Utils.base64decode(item.Image));996 //m.save();997 }998 var backFunc = backButtonHandler ||999 function() {1000 me.goToHome();1001 };1002 me.mainWindow.goToVendorMenu(backFunc);1003 } else {1004 alert(msg);1005 me.mainWindow.goToHome();1006 }1007 me.mainWindow.hideLoading();1008 }, function(e) {1009 console.log("Error getting menu items:", e);1010 me.mainWindow.hideLoading();1011 });1012 } else {1013 me.openVenueSelectionWindow({1014 callback : function() {1015 if (me.vendor.has("id"))1016 me.goToVendorMenu();1017 }1018 });1019 }1020 };1021 me.maskTextField = function(txtField, mask) {1022 var madeChange = false;1023 var last;1024 txtField.addEventListener("change", function() {1025 console.log("txtField changed");1026 if (madeChange) {1027 madeChange = false;1028 return;1029 }1030 if (last != txtField.value) {1031 console.log("MASK?");1032 madeChange = true;1033 Mask.mask(txtField, mask);1034 last = txtField.value;1035 txtField.setSelection(last.length, last.length);1036 }1037 });1038 };1039 me.openCartWindow = function(cartArgs) {1040 me.mainWindow.showLoading("Loading cart...");1041 me.refreshVendor(function() {1042 me.mainWindow.hideLoading();1043 var cartWindow = Alloy.createController("cartWindow", cartArgs);1044 cartWindow.getView().open();1045 });1046 /*1047 var count = 0;1048 var done = function() {1049 me.mainWindow.hideLoading();1050 var cartWindow = Alloy.createController("cartWindow", cartArgs);1051 cartWindow.getView().open();1052 };1053 var checkDone = function() {1054 count++;1055 if(count > 1) done();1056 };1057 me.refreshVendor(function() {1058 checkDone();1059 }, function(){1060 checkDone();1061 });1062 me.getOrderTotalAndFee(null, function(data, status, msg) {1063 console.log("ORDER TOTAL AND FEEs", data);1064 if(status == 1) {1065 me.orderFees.serviceFee = data.serviceFee;1066 me.orderFees.deliveryServiceFee = data.deliveryServiceFee;1067 }1068 console.log("parsing func...");1069 try {1070 eval("me.orderFees.calcFee = " + data.calcFee);1071 if(me.orderFees.calcFee) {1072 console.log("parse calcFee!");1073 }1074 } catch(e) {1075 console.log("ERROR creating calcFee function: ", e);1076 }1077 checkDone();1078 }, function() {1079 checkDone();1080 });1081 */1082 };1083 me.openCustomizeWindow = function(custArgs) {1084 var custWindow = Alloy.createController("customizeWindow", custArgs);1085 custWindow.getView().open();1086 };1087 me.openOrderStatus = function(id, callback) {1088 if (me.customerGuid && me.customerGuid.UserGUID) {1089 me.mainWindow.showLoading("Retreiving order...");1090 me.getCustomerOrder({1091 UserGUID : me.customerGuid.UserGUID,1092 OrderID : id1093 }, function(data, status, msg) {1094 if (status == 1) {1095 if (data.length) {1096 console.log("got order successfully");1097 var orderStatus = Alloy.createController("orderStatusWindow", [data[0], callback]);1098 orderStatus.getView().open();1099 } else {1100 alert("Order not found");1101 }1102 } else {1103 alert("Error getting order: " + msg);1104 }1105 me.mainWindow.hideLoading();1106 }, function(err) {1107 me.mainWindow.hideLoading();1108 if (err) {1109 alert("Error getting order: " + err);1110 } else {1111 alert("Error getting order");1112 }1113 });1114 }1115 };1116 me.openOrderStatusForTracking = function(id, callback) {1117 if (me.customerGuid && me.customerGuid.UserGUID) {1118 me.mainWindow.showLoading("Retreiving order...");1119 me.getCustomerOrder({1120 UserGUID : me.customerGuid.UserGUID,1121 OrderID : id1122 }, function(data, status, msg) {1123 if (status == 1) {1124 if (data.length) {1125 console.log("got order successfully");1126 // var orderStatus = Alloy.createController("orderStatusWindow", [data[0], callback]);1127 // orderStatus.getView().open();1128 var win_mileageTracker = require("map/mileageTracker");1129 var windowInstance = new win_mileageTracker(data[0]);1130 windowInstance.open();1131 } else {1132 alert("Order not found");1133 }1134 } else {1135 alert("Error getting order: " + msg);1136 }1137 me.mainWindow.hideLoading();1138 }, function(err) {1139 me.mainWindow.hideLoading();1140 if (err) {1141 alert("Error getting order: " + err);1142 } else {1143 alert("Error getting order");1144 }1145 });1146 }1147 };1148 me.openVenueSelectionWindow = function(venArgs) {1149 var venueWindow = Alloy.createController("venueWindow", venArgs);1150 venueWindow.getView().open();1151 };1152 me.openContactUsWindow = function() {1153 var contactWindow = Alloy.createController("contactUsWindow");1154 contactWindow.getView().open();1155 };1156 me.resetOrder = function(goHome) {1157 /*1158 * creditCardInfo: null,1159 hasPayment: false,1160 saveCard: false,1161 cartItems: [],1162 specialInstructions: '',1163 columns: {1164 currentView: 'String',1165 itemsInCart: 'integer',1166 specialInstructions: 'String'1167 },1168 // this is the order format we send to wcf service1169 customerCurrentOrder: {1170 },1171 */1172 me.creditCardInfo = null;1173 me.orderCreditCardId = null;1174 me.hasPayment = false;1175 me.saveCard = false;1176 me.specialInstructions = '';1177 me.clearCart();1178 me.tipAmount = 1;1179 if (me.mainWindow) {1180 me.mainWindow.refreshFooter();1181 }1182 if (goHome && me.mainWindow) {1183 me.mainWindow.goToHome();1184 }1185 };1186 me.refreshVendor = function(success, error) {1187 var vendorId = me.vendor.get("id") || Alloy.Globals.lastVendorID;1188 if (vendorId) {1189 me.getVendorInfo({1190 VendorID : vendorId1191 }, function(resp, status, msg) {1192 if (status == 1) {1193 if (resp.IsActive) {1194 me.orderFees.serviceFee = resp.VendorServiceFee;1195 me.orderFees.deliveryServiceFee = resp.VendorDeliveryFee;1196 try {1197 eval("me.orderFees.calcFee = " + resp.VendorCalcFee);1198 if (me.orderFees.calcFee) {1199 console.log("parsed calcFee!");1200 }1201 } catch(e) {1202 console.log("ERROR creating calcFee function: ", e);1203 }1204 me.setVenue(resp.VenueID, resp.VenueName, resp.VenueAddress, resp.VenueCity + ", " + resp.VenueState + " " + resp.VenueZip);1205 me.setVendor(resp.VendorID, resp.VendorName, resp.VendorDescription, resp.ServiceFee, resp, resp.VendorCanDeliver);1206 me.refreshFooter();1207 }1208 }1209 if (success)1210 success();1211 }, function() {1212 if (error)1213 error();1214 });1215 }1216 };1217 me.getVendorDeliverySections = function(vendorId, success, error) {1218 vendorId = vendorId || me.vendor.get("id") || Alloy.Globals.lastVendorID;1219 me.getVendorInfo({1220 VendorID : vendorId1221 }, function(resp, status, msg) {1222 if (status == 1) {1223 if (resp.IsActive && resp.VendorIsOpen && resp.VendorCanDeliver) {1224 Ti.API.info('===success==== ' + resp.VendorSections);1225 success(resp.VendorSections);1226 } else {1227 success([]);1228 }1229 } else {1230 success([]);1231 }1232 }, function() {1233 error();1234 });1235 };1236 me.setVenue = function(id, name, address, cityStateZip) {1237 console.log("setting venue...");1238 me.venue.set({1239 id : id,1240 name : name,1241 address : address,1242 cityStateZip : cityStateZip1243 });1244 me.venue.save();1245 };1246 me.setVendor = function(id, name, description, serviceFee, vendor, canDeliver) {1247 console.log("setting vendor...");1248 me.vendor.set({1249 id : id,1250 name : name,1251 description : description,1252 serviceFee : serviceFee1253 });1254 me.vendor.save();1255 me.vendorMaxServiceFee = vendor.MaxServiceFee;1256 me.vendorMinServiceFee = vendor.MinServiceFee;1257 me.vendorServiceFeePercentage = vendor.ServiceFeePercentage;1258 me.vendorCanDeliver = canDeliver;1259 me.vendorInfo = vendor;1260 me.settings.set("hasVendor", true);1261 me.settings.set("noVendor", false);1262 me.settings.save();1263 if (me.mainWindow) {1264 me.mainWindow.refreshFooter();1265 }1266 };1267 me.showLoader = function() {1268 var loadingView = Alloy.createController('loadingView').getView();1269 loadingView.open({1270 modal : true1271 });1272 };1273 me.swapViews = function(viewOut, viewIn, callback) {1274 viewOut.right = "0%";1275 viewOut.left = null;1276 viewOut.animate(me.animateLeft, function() {1277 viewIn.visible = true;1278 viewIn.opacity = 0;1279 viewIn.left = 0;1280 console.log("animating into focus");1281 viewIn.animate(me.animateIntoFocus, function() {1282 console.log("animated into focus");1283 if (callback)1284 callback();1285 });1286 });1287 };1288 me.swapViewsBack = function(viewFade, viewIn, callback) {1289 viewFade.animate(me.animateOutOfFocus, function() {1290 viewIn.animate(me.animateResetFromLeft, function() {1291 viewFade.visible = false;1292 if (callback)1293 callback();1294 });1295 });1296 };1297 // *************1298 // animations1299 me.animateLeft = Ti.UI.createAnimation({1300 right : "100%",1301 curve : Ti.UI.ANIMATION_CURVE_EASE_OUT,1302 duration : 1501303 });1304 me.animateResetFromLeft = Ti.UI.createAnimation({1305 right : "0%",1306 opacity : 1.0,1307 curve : Ti.UI.ANIMATION_CURVE_EASE_OUT,1308 duration : 1501309 });1310 me.animateIntoFocus = Ti.UI.createAnimation({1311 opacity : 1.0,1312 curve : Ti.UI.ANIMATION_CURVE_EASE_OUT,1313 duration : 2501314 });1315 me.animateOutOfFocus = Ti.UI.createAnimation({1316 opacity : 0.0,1317 curve : Ti.UI.ANIMATION_CURVE_EASE_OUT,1318 duration : 2501319 });1320 me.animateRight = Ti.UI.createAnimation({1321 left : "100%",1322 curve : Ti.UI.ANIMATION_CURVE_EASE_OUT,1323 duration : 1501324 });1325 var animateResetFromRight = Ti.UI.createAnimation({1326 left : "0%",1327 opacity : 1.0,1328 curve : Ti.UI.ANIMATION_CURVE_EASE_OUT,1329 duration : 1501330 });1331 return me;1332}...
login.js
Source:login.js
...149 // $.img5.animate(animateIntoFocus);150 var oldOpacity = $.img4.opacity;151 $.img4.animate(animateIntoFocus);152 if (isRunner) {153 C2.authenticateRunner(email, password, function(resp, status, msg) {154 if (status == 1) {155 console.log("authenitcated user, loading mainWindow");156 C2.mainWindow = Alloy.createController("mainWindow");157 $.txtPassword.value = "";158 C2.mainWindow.getView().open();159 $.img4.animate(animateOutOfFocus);160 } else {161 alert("Error logging in: " + msg);162 }163 hideLoading();164 }, function(e) {165 console.log("error trying to auth user", e);166 alert("Our server is currently down for maintenance, please try again later.");167 hideLoading();...
Using AI Code Generation
1const { authenticateRunner } = require('@qawolf/qawolf');2const { chromium } = require('playwright');3const browser = await chromium.launch();4const context = await browser.newContext();5const page = await context.newPage();6await authenticateRunner(page, '************');7await page.click('input[name="q"]');8await page.fill('input[name="q"]', 'Hello World');9await page.press('input[name="q"]', 'Enter');10await page.close();11await context.close();12await browser.close();13const { authenticateRunner } = require('@qawolf/qawolf');14const { chromium } = require('playwright');15const browser = await chromium.launch();16const context = await browser.newContext();17const page = await context.newPage();18await authenticateRunner(page, '************');19await page.click('input[name="q"]');20await page.fill('input[name="q"]', 'Hello World');21await page.press('input[name="q"]', 'Enter');22await page.close();23await context.close();24await browser.close();25const { authenticateRunner } = require('@qawolf/qawolf');26const { chromium } = require('playwright');27const browser = await chromium.launch();28const context = await browser.newContext();29const page = await context.newPage();30await authenticateRunner(page, '************');31await page.click('input[name="q"]');32await page.fill('input[name="q"]', 'Hello World');33await page.press('input[name="q"]', 'Enter');34await page.close();35await context.close();36await browser.close();
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!