· 7 years ago · Feb 25, 2019, 11:36 AM
1// Ionic Starter App
2
3// angular.module is a global place for creating, registering and retrieving Angular modules
4// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
5// the 2nd parameter is an array of 'requires'
6// 'starter.services' is found in services.js
7// 'starter.controllers' is found in controllers.js
8angular.module('starter', ['ionic', 'ionic.cloud', 'starter.controllers', 'starter.services', 'ngMap', 'auth0.auth0', 'auth0.lock', 'angular-jwt', 'ionic-datepicker', 'ngCordova', 'ngTouch', 'ionic.native', 'firebase', 'ngTagsInput'])
9 .constant('ApiEndpont', {
10 url: 'http://localhost:8100/api'
11 })
12 .config(function($ionicCloudProvider, $ionicConfigProvider, angularAuth0Provider, appConfig, ionicDatePickerProvider) {
13 $ionicConfigProvider.tabs.position('top');
14
15 $ionicConfigProvider.views.swipeBackEnabled(false);
16
17 $ionicCloudProvider.init({
18 "core": {
19 "app_id": "f2b4b1a8"
20 },
21 "push": {
22 "sender_id": "130749830575",
23 "pluginConfig": {
24 "ios": {
25 "badge": true,
26 "sound": true
27 },
28 "android": {
29 "iconColor": "#343434"
30 }
31 }
32 }
33 });
34 // Initialization for the angular-auth0 library
35 angularAuth0Provider.init({
36 clientID: appConfig.CLIENT_ID_AUTH0,
37 clientId: appConfig.CLIENT_ID_AUTH0,
38 domain: appConfig.DOMAIN_AUTH0,
39 packageIdentifier: appConfig.APP_PACKAGE_NAME,
40 scope: 'openid profile email'
41 });
42
43 // Initialize Firebase
44 var config = {
45 apiKey: appConfig.FIREBASE_APIKEY,
46 authDomain: appConfig.FIREBASE_AUTHDOMAIN,
47 databaseURL: appConfig.FIREBASE_DATABASEURL,
48 projectId: appConfig.FIREBASE_PROJECTID,
49 storageBucket: appConfig.FIREBASE_STORAGEBUCKET,
50 messagingSenderId: appConfig.FIREBASE_MESSAGINGSENDERID
51 };
52 firebase.initializeApp(config);
53
54 var datePickerObj = {
55 inputDate: new Date(),
56 titleLabel: 'Seleccione una fecha',
57 closeLabel: 'Cerrar',
58 todayLabel: 'Hoy',
59 setLabel: 'Aceptar',
60 mondayFirst: false,
61 weeksList: ["D", "L", "M", "X", "J", "V", "S"],
62 monthsList: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"],
63 templateType: 'popup',
64 from: new Date(2000, 1, 1),
65 to: new Date(),
66 showTodayButton: true,
67 dateFormat: 'dd MMMM yyyy',
68 closeOnSelect: false,
69 disableWeekdays: []
70 };
71 ionicDatePickerProvider.configDatePicker(datePickerObj);
72 })
73 .run(function ($ionicPlatform, $ionicPopup, $rootScope, AppService, appConfig, $injector, AuthService, $state, UserService, ProductService, EventLogService, $interval,NotificationService, DeviceService, $cordovaDeeplinks, $timeout,ListCategoryService, ErrorService, LogService, FirebaseService, StatusForLog, SelligentService, LocalStorageService, LocalStorageKeys, UtilsService,ApiServer) {
74 var errorHandler = function(event) {
75 var messageError = "";
76 if (event.message) {
77 messageError = event.message;
78 } else if (event.exception && event.exception.message) {
79 messageError = event.exception.message;
80 } else if (event.error && event.error.message) {
81 messageError = event.error.message;
82 }
83
84 var errorObj = {origin_fn: "run", fn: "myCustomErrorHandler", error: messageError};
85 LogService.javascriptError(errorObj);
86 };
87 window.addEventListener('error', errorHandler);
88 window.myCustomErrorHandler = errorHandler;
89
90 FirebaseService.init(ErrorService);
91
92 /*
93 * settings
94 * countries
95 * categories
96 * portadas
97 * colors_sizes
98 * manufacturers
99 */
100 $rootScope.configurationElementsToLoad = AppService.isAppTiendas() ? 5 : 6;
101 $rootScope.optionSelected = 1;
102
103 var cmpVersion = function (a, b) {
104 var i, cmp, len;
105 a = ((a || 0) + '').split('.');
106 b = (b + '').split('.');
107 len = Math.max(a.length, b.length);
108 for (i = 0; i < len; i++) {
109 if (a[i] === undefined) {
110 a[i] = '0';
111 }
112 if (b[i] === undefined) {
113 b[i] = '0';
114 }
115 cmp = parseInt(a[i], 10) - parseInt(b[i], 10);
116 if (cmp !== 0) {
117 return (cmp < 0 ? -1 : 1);
118 }
119 }
120 return 0;
121 };
122
123 var currentSettingsVersion = window.localStorage.getItem("settingsVersion");
124 //noinspection JSUnusedLocalSymbols,JSDuplicatedDeclaration
125 var needToResetSettings = false;
126 // si venimos de menor a 1.1.0 y ahora es igual o mayor
127 //noinspection JSDuplicatedDeclaration
128 var needToResetSettings =
129 (cmpVersion(currentSettingsVersion, '1.1.0') < 0 &&
130 cmpVersion(appConfig.APP_VERSION_NUMBER_CORE, '1.1.0') >= 0) ||
131 (cmpVersion(currentSettingsVersion, '1.1.2') < 0 &&
132 cmpVersion(appConfig.APP_VERSION_NUMBER_CORE, '1.1.2') >= 0) ||
133 (cmpVersion(currentSettingsVersion, '1.3.19') < 0 &&
134 cmpVersion(appConfig.APP_VERSION_NUMBER_CORE, '1.3.19') >= 0);
135 if (needToResetSettings) {
136 console.warn("borrando settings...");
137 localStorage.clear();
138 }
139 window.localStorage.setItem("settingsVersion", appConfig.APP_VERSION_NUMBER_CORE);
140
141 var loadProductDataFromServer = function(actualDateHour) {
142
143 if (!window.sqlitePlugin) return;
144
145 var callbackErrorDb = function (error) {
146 LogService.offlineDbAction({type: 'callbackErrorDb', origin: 'app.js', value: JSON.stringify(error)});
147 console.error("Error de DB", db, arguments);
148 db.close();
149 };
150
151 var db = window.sqlitePlugin.openDatabase({
152 name: 'krack_tiendas.db',
153 location: 'default',
154 androidDatabaseImplementation: appConfig.DATABASE_VERSION_NUMBER
155 }, function (response) {
156 LogService.offlineDbAction({type: 'openDatabase', origin: 'app.js', value: JSON.stringify(response)});
157 }, callbackErrorDb);
158
159 db.transaction(function (tx) {
160 LogService.offlineDbAction({type: 'transaction_callback', origin: 'app.js', value: JSON.stringify(tx)});
161 tx.executeSql('DROP TABLE IF EXISTS products_light', undefined, function (response) {
162 LogService.offlineDbAction({type: 'executeSQL_DROP', origin: 'app.js', value: JSON.stringify(response)});
163 }, callbackErrorDb);
164 tx.executeSql('CREATE TABLE IF NOT EXISTS products_light (id INTEGER PRIMARY KEY AUTOINCREMENT , id_prestashop INTEGER, name VARCHAR(255), reference VARCHAR(255), manufacturer VARCHAR(255), price REAL DEFAULT 0, price_discount REAL)', undefined, function (response) {
165 LogService.offlineDbAction({type: 'executeSQL_CREATE', origin: 'app.js', value: JSON.stringify(response)});
166 }, callbackErrorDb);
167 }, callbackErrorDb, function (response) {
168 db.close();
169 LogService.offlineDbAction({type: 'transaction_successCallback', origin: 'app.js', value: JSON.stringify(response)});
170 ProductService.getProducts_Light().then(function (listProducts) {
171 var countToSave = 0;
172 var countTotal = 0;
173 var valuesToInsert = '';
174 var arrayValuesToInsert = [];
175
176 if (listProducts && listProducts.length) {
177 db = window.sqlitePlugin.openDatabase({
178 name: 'krack_tiendas.db',
179 location: 'default',
180 androidDatabaseImplementation: appConfig.DATABASE_VERSION_NUMBER
181 }, function (response) {
182 LogService.offlineDbAction({type: 'openDatabase_getProductsLight', origin: 'app.js', value: JSON.stringify(response)});
183 }, callbackErrorDb);
184 db.transaction(function (tx) {
185 LogService.offlineDbAction({type: 'transaction_callback_getProductsLight', origin: 'app.js', value: JSON.stringify(tx)});
186 for (var indexProduct in listProducts) {
187 var product = listProducts[indexProduct];
188 if (valuesToInsert != '' && (countToSave != 129 || countTotal != (listProducts.length - 1))) {
189 valuesToInsert += ',';
190 }
191 valuesToInsert += '(?, ?, ?, ?, ?, ?, ?)';
192 arrayValuesToInsert = arrayValuesToInsert.concat([null, product.id, product.name || 'Unknown', product.reference || 'Unknown', product.manufacturer || null, product.price || 0, product.price_discount || null]);
193
194 countToSave++;
195 countTotal++;
196 if (countToSave == 130 || countTotal == listProducts.length) {
197 tx.executeSql("INSERT INTO products_light (id, id_prestashop, name, reference, manufacturer, price, price_discount) VALUES " + valuesToInsert, arrayValuesToInsert, function(response) {
198 LogService.offlineDbAction({type: 'transaction_callback_getProductsLight', origin: 'app.js', value: JSON.stringify(response)});
199 }, callbackErrorDb);
200 countToSave = 0;
201 valuesToInsert = '';
202 arrayValuesToInsert = [];
203 }
204 }
205 }, callbackErrorDb, function (response) {
206 LogService.offlineDbAction({type: 'transaction_successCallback_getProductsLight', origin: 'app.js', value: JSON.stringify(response)});
207 window.localStorage.setItem("dayLastGetProducts", actualDateHour);
208 db.close();
209 });
210 }
211 });
212 });
213 };
214
215 $ionicPlatform.ready(function () {
216 LogService.init(ErrorService,ApiServer);
217
218 LogService.getLogIdentifier();
219 LogService.setIdUserLogIdentifier();
220
221 if (window.cordova && window.Scandit && AppService.isAppTiendas()) {
222 window.Scandit.License.setAppKey(appConfig.SCANDIT_LICENSE_TEST);
223 }
224
225 window.addEventListener('native.keyboardshow', function(){
226 LogService.keyboard(StatusForLog.keyboard.SHOW);
227 });
228 window.addEventListener('native.keyboardhide', function(){
229 LogService.keyboard(StatusForLog.keyboard.HIDE);
230 });
231
232 LogService.appLifecycle(StatusForLog.appLifecycle.OPEN);
233
234 $ionicPlatform.on('resume', function() {
235 if ($rootScope.paypalInitialized) {
236 LogService.paymentLog({id: "step_resume", title: "Resumes-ResumeApp", time: new Date().getTime()}, true);
237 }
238 LogService.appLifecycle(StatusForLog.appLifecycle.RESUME);
239 if ($rootScope.isPrinting) {
240 LogService.printProcess({function: "onResume", action: 'app_to_foreground'});
241 }
242 });
243 $ionicPlatform.on('pause', function() {
244 if ($rootScope.paypalInitialized) {
245 LogService.paymentLog({id: "step_pause", title: "Pauses-PauseApp", time: new Date().getTime()}, true);
246 }
247 LogService.appLifecycle(StatusForLog.appLifecycle.PAUSE);
248 if ($rootScope.isPrinting) {
249 LogService.printProcess({function: "onPause", action: 'app_to_background'});
250 }
251 });
252
253 if (cmpVersion(currentSettingsVersion, '1.12.15') < 0 &&
254 cmpVersion(appConfig.APP_VERSION_NUMBER_CORE, '1.12.15') >= 0 &&
255 (LocalStorageService.get(LocalStorageKeys.isLogin) || LocalStorageService.get(LocalStorageKeys.isLoginSocial))) {
256 var userLogged = JSON.parse(LocalStorageService.get(LocalStorageKeys.userInfo));
257 var userLoggedEmail = userLogged.email;
258
259 SelligentService.sendEvent(SelligentService.eventTypes().USER_LOGIN, userLoggedEmail);
260 if (userLogged.addresses && userLogged.addresses.length > 0) {
261 SelligentService.sendEvent(SelligentService.eventTypes().CUSTOM, userLoggedEmail);
262 }
263 }
264
265 window.handleOpenURL = function (url) {
266 console.log("DEEPLINKS::HandleOpenUrl", url);
267 };
268
269 $rootScope.mergeObjects = function (obj1, obj2) {
270 var obj3 = {};
271 for (var attrname in obj1) {
272 obj3[attrname] = obj1[attrname];
273 }
274 for (var attrname in obj2) {
275 obj3[attrname] = obj2[attrname];
276 }
277 return obj3;
278 }
279
280 if (AppService.isAppTiendas()) {
281 LogService.offlineDbAction({type: 'check_need_re-download', origin: 'app.js'});
282 var actualDateHour = new Date();
283 var lastDayGetProducts = window.localStorage.getItem("dayLastGetProducts");
284 var redownload = true;
285
286 if(lastDayGetProducts) {
287 lastDayGetProducts = new Date(lastDayGetProducts);
288 console.debug("Remove-Lastday", lastDayGetProducts);
289 var now = new Date(actualDateHour.getTime() - 7 * 60 * 60 * 1000);
290 var download = new Date(lastDayGetProducts.getTime() - 7 * 60 * 60 * 1000);
291
292 redownload = now.getDay() != download.getDay() || now.getMonth() != download.getMonth() || now.getFullYear() != download.getFullYear();
293 }
294
295
296 if (redownload) {
297 LogService.offlineDbAction({type: 're-download_data', origin: 'app.js'});
298 loadProductDataFromServer(actualDateHour);
299
300 setInterval(function () {
301 LogService.offlineDbAction({type: 're-download_data_timeout', origin: 'app.js'});
302 loadProductDataFromServer(actualDateHour);
303 }, 600000);
304 }
305
306 //Check Permissions record audio
307 if ($ionicPlatform.is('android') && window.cordova && typeof window.cordova.plugins.permissions !== "undefined") {
308 var permissions = cordova.plugins.permissions;
309 permissions.hasPermission(permissions.RECORD_AUDIO, function (status) {
310 if (status.hasPermission) {
311 permissions.hasPermission(permissions.WRITE_EXTERNAL_STORAGE, function (status_storage) {
312 if (status_storage.hasPermission) {
313 $rootScope.permission_record_audio = true;
314 }
315 });
316 }
317 });
318 }
319
320 $rootScope.checkUpdates = true;
321 var checkUpdates = function (interval) {
322 if($rootScope.checkUpdates){
323 DeviceService.checkUpdates().then(function (data) {
324 if(data && data.update){
325 var myNullAction = $ionicPlatform.registerBackButtonAction(function(){
326 // do nothing
327 }, 401);
328 $rootScope.checkUpdates = false;
329 if(interval){
330 $interval.cancel(intervalCheckUpdates);
331 intervalCheckUpdates = null;
332 }
333 if(!data.mandatory){
334 var popup = $ionicPopup.alert({
335 title: $rootScope.appLanguage.UPGRADE,
336 template: $rootScope.appLanguage.TEXT_UPDATE_NO_MANDATORY,
337 buttons: [
338 {
339 text: $rootScope.appLanguage.UPDATE,
340 type: 'button-positive',
341 onTap: function (e) {
342 e.preventDefault();
343
344 $rootScope.checkUpdates = true;
345 intervalCheckUpdates = $interval(function () {
346 checkUpdates(intervalCheckUpdates);
347 }, 5 * (60 * 1000)); //Cada 5 minutos
348 if(window.cordova){
349 // chequeamos si está el fichero, usamos
350 // cordova plugin add cordova-plugin-file
351 //ShopAndGo_2_13_25.apk
352 $cordovaFile.checkFile(cordova.file.dataDirectory, 'updates/ShopAndGo_'+ data.version +'.apk')
353 .then(function (success) {
354 // success esta el fichero
355 // instalamos el fichero
356 window.open('updates/ShopAndGo_'+ data.version +'.apk', '_system');
357 //cerramos la app
358 if (navigator.app) {
359 navigator.app.exitApp();
360 } else if (navigator.device) {
361 navigator.device.exitApp();
362 } else {
363 window.close();
364 }
365 }, function (error) {
366 // no está el fichero
367 //borramos el directorio
368 // REMOVE
369 $cordovaFile.removeDir(cordova.file.dataDirectory, "updates")
370 .then(function (success) {
371 // success
372 // se ha borrado el directorio
373 // CREATE
374 // Creamos el directorio nuevamente
375 $cordovaFile.createDir(cordova.file.dataDirectory, "updates", false)
376 .then(function (success) {
377 // success
378 // bajamos el fichero, para eso usamos
379 // cordova plugin add cordova-plugin-file-downloader
380 downloader.init({folder: "updates"});
381 // carpeta a la que bajará
382 downloader.get("http://url-de-mirror/updates/ShopAndGo_"+ data.version +'.apk');
383 // descargar apk
384 }, function (error) {
385 // error
386 console.log('ERROR Actualizacion: no se ha podido Crear el directorio');
387 });
388 }, function (error) {
389 // error
390 console.log('ERROR Actualizacion: no se ha podido Borrar el directorio');
391 });
392 });
393 }
394 // antiguo windows.open
395 }
396 },
397 {
398 text: $rootScope.appLanguage.POSTPONE,
399 type: 'button-positive',
400 onTap: function (e) {
401 e.preventDefault();
402
403 $rootScope.checkUpdates = true;
404 intervalCheckUpdates = $interval(function () {
405 checkUpdates(intervalCheckUpdates);
406 }, 5 * (60 * 1000)); //Cada 10 minutos
407
408 popup.close();
409 }
410 }
411 ]
412 });
413 popup.then(function(res) {
414 myNullAction();
415 });
416
417 } else {
418 var popup = $ionicPopup.alert({
419 title: $rootScope.appLanguage.UPGRADE,
420 template: $rootScope.appLanguage.TEXT_UPDATE_MANDATORY,
421 buttons: [
422 {
423 text: $rootScope.appLanguage.UPDATE,
424 type: 'button-positive',
425 onTap: function (e) {
426 e.preventDefault();
427
428 $rootScope.checkUpdates = true;
429 intervalCheckUpdates = $interval(function () {
430 checkUpdates(intervalCheckUpdates);
431 }, 5 * (60 * 1000)); //Cada 10 minutos
432
433 window.open("https://play.google.com/store/apps/details?id=com.galvintec.prestaappkrack.tiendas", '_system');
434 }
435 }
436 ]
437 });
438 popup.then(function(res) {
439 myNullAction();
440 });
441 }
442
443 }
444 });
445 } else if(interval){
446 $interval.cancel(intervalCheckUpdates);
447 intervalCheckUpdates = null;
448 }
449 }
450
451 checkUpdates(false);
452
453 var intervalCheckUpdates = $interval(function () {
454 checkUpdates(intervalCheckUpdates);
455 }, 10 * (60 * 1000)); //Cada 10 minutos
456
457
458 } else {
459
460 if (window.cordova) {
461 $rootScope.subscribeRoutes = function () {
462 $cordovaDeeplinks.route({
463 '/:lang/:friendy': {
464 target: 'tab.product',
465 parent: 'tab.home'
466 },
467 '/:lang/:friendy/': {
468 target: 'tab.category',
469 parent: 'tab.home'
470 },
471 '/:lang/': {
472 target: 'tab.home',
473 parent: 'tab.home'
474 },
475 '/:lang': {
476 target: 'tab.home',
477 parent: 'tab.home'
478 },
479 '/': {
480 target: 'tab.home',
481 parent: 'tab.home'
482 }
483 }).subscribe(function (match) {
484 console.log("DEEPLINKS::match", match);
485 console.log("DEEPLINKS::args", match.$args);
486 $timeout(function () {
487 $state.go(match.$route.parent, match.$args);
488 if (match.$route.target != match.$route.parent) {
489 if (typeof match.$args.friendy !== "undefined") {
490 switch (match.$route.target) {
491 case 'tab.product':
492 console.log("Abriendo productooooooo");
493 var preg_match = match.$args.friendy.match(/-(\d+).html/);
494 if (preg_match && preg_match[1] > 0) {
495 console.log("DEEPLINKS::preg_match", preg_match);
496 $rootScope.openProductDeepLink(preg_match[1]);
497 }
498 break;
499 case 'tab.category':
500 console.log("Abriendo categorÃa desde enlace deeplink");
501 ListCategoryService.getCateogryIdFromLinkRewrite(match.$args.friendy).then(function (idCategory) {
502 console.log("ID category -> ", idCategory);
503 if (idCategory) {
504 console.log("Abrimos la categorÃa -> ", idCategory);
505 $rootScope.goCategory({id: idCategory});
506 }
507 });
508 break;
509 default:
510 console.log("defaulttttttttttt");
511 break;
512 }
513 }
514 } else {
515 if (match.$route.target == "tab.home") {
516 console.log("No hacemos nada porque ya estamos en la home");
517 }
518 }
519 }, 100); // Timeouts can be tweaked to customize the feel of the deeplink
520 }, function (nomatch) {
521 console.warn('DEEPLINKS::No match', nomatch);
522 if (nomatch.$link && nomatch.$link.path) {
523 console.warn('DEEPLINKS::No match path', nomatch.$link.path);
524 $state.go('tab.home');
525 var arr_nomatch = nomatch.$link.path.split('/');
526 console.log('DEEPLINKS::path array', arr_nomatch);
527 if (arr_nomatch && arr_nomatch.length > 2) {
528 var friendy = arr_nomatch[2];
529 var preg_match = friendy.match(/-(\d+).html/);
530 if (preg_match && preg_match[1] > 0) {
531 console.log("DEEPLINKS::preg_match", preg_match);
532 $rootScope.openProductDeepLink(preg_match[1]);
533 }
534 }
535 }
536
537 $rootScope.subscribeRoutes();
538 });
539 };
540 $rootScope.subscribeRoutes();
541 }
542 }
543
544 $rootScope.openProductDeepLink = function(id_product){
545 ProductService.getIdProductLocal(id_product).then(function (productIdLocal) {
546 if(productIdLocal){
547 $rootScope.openProduct({id: productIdLocal});
548 }
549 });
550 };
551
552 setTimeout(function () {
553 navigator && navigator.splashscreen && navigator.splashscreen.hide();
554 }, 5000);
555
556 // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
557 // for form inputs)
558 if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
559 cordova.plugins.Keyboard.hideKeyboardAccessoryBar(false);
560 cordova.plugins.Keyboard.disableScroll(true);
561 }
562 UserService.resetUserShop();
563
564 if (window.StatusBar) {
565 if ($ionicPlatform.is('android')) {
566 StatusBar.styleLightContent();
567 } else {
568 StatusBar.styleDefault();
569 }
570 }
571
572 try {
573 if(appConfig.ENABLE_PUSH_PLUGIN) {
574 var NotificationService = $injector.get('NotificationService');
575 NotificationService.init();
576 }
577 }
578 catch(err) {
579 var originObj = {origin_fn: "run", fn: "catch_notificationService"};
580 var errorObj = {title: $rootScope.appLanguage.MESSAGE_TEXT, message: "Push Notification plugin not found"};
581 ErrorService.manageError(originObj, errorObj, true);
582 }
583 // Use the authManager from angular-jwt to check for
584 // the user's authentication state when the page is
585 // refreshed and maintain authentication
586 AuthService.checkAuthOnRefresh();
587
588 // Process the auth token if it exists and fetch the profile
589 // AuthService.authenticateAndGetProfile();
590
591 if (window.cordova && window.cordova.getAppVersion && window.cordova.getAppVersion.getVersionNumber) {
592 cordova.getAppVersion.getVersionNumber().then(
593 function (version) {
594 $rootScope.appVersionNumberPackageMetadata = version;
595 if (version !== appConfig.APP_VERSION_NUMBER_PRODUCT) {
596 // TODO exit
597 navigator.app.exitApp();
598 }
599 },
600 function (error) {
601 var originObj = {origin_fn: "run", fn: "appVersion.getVersionNumber"};
602 ErrorService.manageError(originObj, error);
603 }
604 );
605 }
606 // TODO comprobar también nombre de paquete
607
608 //$rootScope.deviceImei = "123456789012345";
609 var countAlertImeiShowed = 0;
610 var getImei = function () {
611 countAlertImeiShowed++;
612 window.plugins.imei.get(function (imei) {
613 $rootScope.deviceImei = imei;
614 }, function (error) {
615 var messageAlert = 'Es necesario que acepte el permiso de identificación del teléfono para poder hacer uso de <b>Shop&Go</b>.';
616 if (countAlertImeiShowed > 1) {
617 messageAlert += '<br/><br/>Si no sucede nada al pulsar sobre este botón, la identificación está bloqueada, contacta por favor con soporte informático.';
618 }
619 $ionicPopup.alert({
620 title: 'Permiso necesario',
621 template: messageAlert,
622 buttons: [{
623 text: 'Aceptar',
624 type: 'button-positive',
625 onTap: function () {
626 acceptAlertImeiDenied();
627 }
628 }, {
629 text: 'Cancelar',
630 type: 'button-positive',
631 onTap: function () {
632 navigator.app.exitApp();
633 }
634 }]
635 });
636 });
637 }
638 var acceptAlertImeiDenied = function () {
639 getImei();
640 }
641 if (window.plugins && window.plugins.imei && AppService.isAppTiendas()) {
642 getImei();
643 } else {
644 $rootScope.deviceImei = "000000000000000";
645 }
646
647 if (AppService.isAppTiendas()) {
648 if (window.FirebasePlugin) {
649 EventLogService.initAutomaticNetworkEventsLogging();
650
651 window.FirebasePlugin.getToken(function(token) {
652 console.debug("Test-GetToken", token);
653 window.localStorage.setItem("terminal_push_token", token);
654 DeviceService.saveDeviceToken();
655 }, function(error) {
656 console.error(error);
657 var originObj = {origin_fn: "run", fn: "FirebasePlugin.getToken"};
658 ErrorService.manageError(originObj, error);
659 });
660 window.FirebasePlugin.token
661 window.FirebasePlugin.onTokenRefresh(function(token) {
662 console.debug("Test-onTokenRefresh", token);
663 window.localStorage.setItem("terminal_push_token", token);
664 DeviceService.saveDeviceToken();
665 }, function(error) {
666 console.error(error);
667 var originObj = {origin_fn: "run", fn: "FirebasePlugin.onTokenRefresh"};
668 ErrorService.manageError(originObj, error);
669 });
670
671 $rootScope.manageNotifications();
672 }
673 }
674
675 $rootScope.toast = function(options){
676 if(typeof options.success !== "undefined"){
677 if(typeof options.styling === "undefined"){
678 options.styling = {
679 opacity: 0.75, // 0.0 (transparent) to 1.0 (opaque). Default 0.8
680 backgroundColor: options.success ? "#007B14" : "#7B001A", // make sure you use #RRGGBB. Default #333333
681 textColor: '#FFFFFF', // Ditto. Default #FFFFFF
682 cornerRadius: 16, // minimum is 0 (square). iOS default 20, Android default 100
683 horizontalPadding: 5, // iOS default 16, Android default 50
684 verticalPadding: 4 // iOS default 12, Android default 30
685 }
686 }
687 if(typeof options.message === "undefined"){
688 options.message = options.success ? "Se ha realizado correctamente la acción" : "Ha ocurrido un error";
689 }
690 }
691 options = $.extend(true, {
692 message: "Se ha realizado correctamente la acción",
693 duration: "short", // 2000 ms
694 position: "top",
695 styling: {
696 opacity: 0.75, // 0.0 (transparent) to 1.0 (opaque). Default 0.8
697 backgroundColor: '#007B14', // make sure you use #RRGGBB. Default #333333
698 textColor: '#FFFFFF', // Ditto. Default #FFFFFF
699 cornerRadius: 16, // minimum is 0 (square). iOS default 20, Android default 100
700 horizontalPadding: 5, // iOS default 16, Android default 50
701 verticalPadding: 4 // iOS default 12, Android default 30
702 }
703 }, options);
704
705 window.plugins.toast.showWithOptions(options);
706 }
707
708 });
709 })
710 .config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider, appConfig) {
711
712 $ionicConfigProvider.platform.android.tabs.position('bottom');
713
714 // Ionic uses AngularUI Router which uses the concept of states
715 // Learn more here: https://github.com/angular-ui/ui-router
716 // Set up the various states which the app can be in.
717 // Each state's controller can be found in controllers.js
718 $stateProvider
719
720 // setup an abstract state for the tabs directive
721 .state('tab', {
722 url: '/tab',
723 abstract: true,
724 controller: 'AppCtrl',
725 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tabs.html'
726 })
727
728 .state('tab.home', {
729 url: '/home',
730 views: {
731 'mainContent': {
732 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tab-home.html',
733 controller: 'HomeCtrl'
734 }
735 }
736 })
737
738 .state('tab.categories', {
739 url: '/categories/:categoryId',
740 views: {
741 'mainContent': {
742 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tab-categories.html',
743 controller: 'CategoriesCtrl'
744 }
745 }
746 })
747 /*.state('tab.filters', {
748 url: '/filters',
749 views: {
750 'mainContent': {
751 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tab-filters.html',
752 controller: 'FilterCtrl'
753 }
754 }
755 })*/
756 .state('tab.splash', {
757 url: '/splash',
758 views: {
759 'mainContent': {
760 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tab-splash.html',
761 controller: 'SplashCtrl'
762 }
763 }
764 })
765 .state('tab.promotions', {
766 url: '/promotions',
767 views: {
768 'mainContent': {
769 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tab-promotions.html',
770 controller: 'HomeCtrl'
771 }
772 }
773 })
774
775 .state('tab.category', {
776 url: '/category/:categoryId&:before&:marca&:categoryName',
777 views: {
778 'mainContent': {
779 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tab-category.html',
780 controller: 'SingleCategoryCtrl'
781 }
782 }
783 })
784
785 .state('tab.wishlist', {
786 url: '/wishlist',
787 views: {
788 'mainContent': {
789 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tab-wishlist.html',
790 controller: 'WishlistCtrl'
791 }
792 }
793 })
794
795 .state('tab.product', {
796 //url: '/product/:productId',
797 url: '/product',
798 params: {
799 'productId': 0,
800 productData: null,
801 productHistoryData: null,
802 'isScanned': false
803 },
804 //cache: false,
805 views: {
806 'mainContent': {
807 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tab-product.html',
808 controller: 'ProductCtrl'
809 }
810 }
811 })
812
813 .state('tab.blog', {
814 url: '/blog',
815 views: {
816 'mainContent': {
817 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tab-blog.html',
818 controller: 'BlogCtrl'
819 }
820 }
821 })
822
823 .state('tab.blog-category', {
824 url: '/blog-category/:categoryId',
825 views: {
826 'mainContent': {
827 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tab-blog-category.html',
828 controller: 'BlogCategoryCtrl'
829 }
830 }
831 })
832
833 .state('tab.blog-single', {
834 url: '/blog/:blogId',
835 views: {
836 'mainContent': {
837 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tab-blog-single.html',
838 controller: 'SingleBlogCtrl'
839 }
840 }
841 })
842
843 .state('tab.cart', {
844 url: '/cart',
845 views: {
846 'mainContent': {
847 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tab-cart.html',
848 controller: 'CartCtrl'
849 }
850 }
851 })
852
853 .state('tab.notification', {
854 url: '/notification',
855 views: {
856 'mainContent': {
857 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tab-notification.html',
858 controller: 'NotificationCtrl'
859 }
860 }
861 })
862
863 .state('tab.orders', {
864 url: '/orders',
865 views: {
866 'mainContent': {
867 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tab-orders.html',
868 controller: 'OrdersCtrl'
869 }
870 }
871 })
872
873 .state('tab.order', {
874 url: '/order/:orderId',
875 views: {
876 'mainContent': {
877 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tab-order.html',
878 controller: 'OrderDetailCtrl'
879 }
880 }
881 })
882
883 .state('tab.account', {
884 url: '/account',
885 params: {
886 'goToDireccion': null,
887 'goToTerminal': null,
888 },
889 views: {
890 'mainContent': {
891 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tab-account.html',
892 controller: 'AccountCtrl'
893 }
894 }
895 })
896
897 .state('tab.contactus', {
898 url: '/contactus',
899 views: {
900 'mainContent': {
901 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tab-contactus.html',
902 controller: 'ContactUsCtrl'
903 }
904 }
905 })
906
907 .state('tab.settings', {
908 url: '/settings',
909 views: {
910 'mainContent': {
911 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tab-settings.html',
912 controller: 'SettingsCtrl'
913 }
914 }
915 })
916
917 .state('tab.language', {
918 url: '/language',
919 views: {
920 'mainContent': {
921 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tab-language.html',
922 controller: 'LanguageCtrl'
923 }
924 }
925 })
926
927 .state('tab.checkout', {
928 url: '/checkout',
929 views: {
930 'mainContent': {
931 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/checkout/login.html',
932 controller: 'CheckoutCtrl'
933 }
934 }
935 })
936
937 .state('tab.shops', {
938 url: '/shops',
939 views: {
940 'mainContent': {
941 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tab-shops.html',
942 controller: 'ShopsCtrl'
943 }
944 }
945 })
946
947 .state('tab.checkout-billing', {
948 url: '/checkout-billing',
949 views: {
950 'mainContent': {
951 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/checkout/billing.html',
952 controller: 'CheckoutBillingCtrl'
953 }
954 }
955 })
956
957 .state('tab.checkout-note', {
958 url: '/checkout-note',
959 views: {
960 'mainContent': {
961 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/checkout/note.html',
962 controller: 'CheckoutNoteCtrl'
963 }
964 }
965 })
966
967 .state('tab.checkout-payment', {
968 url: '/checkout-payment',
969 views: {
970 'mainContent': {
971 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/checkout/payment.html',
972 controller: 'CheckoutPaymentCtrl'
973 }
974 }
975 })
976
977 .state('tab.checkout-success', {
978 url: '/checkout-success',
979 views: {
980 'mainContent': {
981 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/checkout/success.html',
982 controller: 'CheckoutSuccessCtrl'
983 }
984 }
985 })
986
987 .state('tab.policies', {
988 url: '/policies',
989 views: {
990 'mainContent': {
991 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/tab-policies.html',
992 controller: 'PoliciesCtrl'
993 }
994 }
995 })
996
997 .state('tab.checkout-error-payment', {
998 url: '/checkout-error-payment',
999 views: {
1000 'mainContent': {
1001 templateUrl: 'templates/'+appConfig.ENABLE_THEME+'/checkout/error-payment.html',
1002 controller: 'CheckoutErrorCtrl'
1003 }
1004 }
1005 })
1006 ;
1007
1008 // if none of the above states are matched, use this as the fallback
1009 $urlRouterProvider.otherwise('/tab/home');
1010
1011 });