angular.module('app.app.controllers', [ 'ionic', 'ngCordova.plugins.beacon', 'ngCordova.plugins.nativeStorage' ]) .controller('AppController', function( $rootScope, $scope, $http, $ionicActionSheet, $ionicHistory, $ionicLoading, $ionicModal, $ionicPlatform, $ionicPopup, $location, $timeout, //$cordovaGoogleAnalytics, //localStorageService, $cordovaNativeStorage, notifications, API_END_POINT, DEBUG ) { //var user = localStorageService.get('user'); var user = false; $ionicPlatform.ready(function() { console.log("C28_get"); $cordovaNativeStorage.getItem('user').then(function (value) { console.log("C28_get OK"); user = value; $rootScope.user = user; }, function(error) { console.log("C28_get ERROR"); console.log(JSON.stringify(error)); }); }); $scope.doLogout = function () { var logoutPopup = $ionicPopup.confirm({ title: 'Logout', template: 'Sei sicuro di voler uscire?', okText: 'Sì', cancelText: 'No' }); logoutPopup.then(function(res) { if (res) { $ionicHistory.nextViewOptions({ disableAnimate: false, disableBack: true }); //localStorageService.remove('user'); console.log("C50_rm"); $cordovaNativeStorage.remove('user').then(function (value) { console.log("C50_rm OK"); $location.path('/welcome'); }, function(error) { console.log("C50_rm ERROR"); console.log(JSON.stringify(error)); $location.path('/welcome'); }); } }); }; var loadState = function () { $ionicLoading.show({ template: 'Attendere, aggiornamento dati in corso...' }); $http({ url: API_END_POINT + '/state', method: "GET", timeout: 10000, headers: { 'Authorization': 'Basic ' + btoa($rootScope.user.id + ':' + $rootScope.user.card), 'Content-Type': 'application/json' } }) .success(function(data, status, headers, config) { $ionicLoading.hide(); if (data.user) { $rootScope.user = data.user; //localStorageService.set('user', data.user); console.log("C78_set"); $cordovaNativeStorage.setItem('user', data.user).then(function (value) { console.log("C78_set OK"); }, function (error) { console.log("C78_set ERROR"); console.log(JSON.stringify(error)); }); delete data.user; } if (data && data.push) { $rootScope.push = data.push; } if (data && data.beacons) { $rootScope.beacons = data.beacons; setupBeacons(); } //localStorageService.set('state', data); console.log("C94_set"); $cordovaNativeStorage.setItem('state', data).then(function (value) { console.log("C94_set OK"); $rootScope.$broadcast('ali:state'); }, function (error) { console.log("C94_set ERROR"); console.log(JSON.stringify(error)); }); }) .error(function(data, status, headers, config) { $ionicLoading.hide(); }); }; $rootScope.$on('ali:state', function () { //var state = localStorageService.get('state') || {}; //var read = localStorageService.get('read_notifications') || []; var state = {}; var read = []; console.log("C109_get"); $cordovaNativeStorage.getItem('state').then(function (value) { console.log("C109_get OK"); state = value; console.log("C116_get"); $cordovaNativeStorage.getItem('read_notifications').then(function (value) { console.log("C116_get OK"); read = value; $rootScope.menu_pages = state.pages || []; $rootScope.notifications_count = _.filter(state.notifications, function (n) { return _.indexOf(read, n.id) == -1; }).length; }, function(error) { console.log("C116_get ERROR"); console.log(JSON.stringify(error)); }); }, function(error) { console.log("C109_get ERROR"); console.log(JSON.stringify(error)); $rootScope.menu_pages = []; }); }); $ionicPlatform.ready(function() { $timeout(function() { loadState(); }, 300); }); var modal; $ionicModal.fromTemplateUrl('templates/carta.html', { scope: $scope, animation: 'slide-in-up' }).then(function(m) { modal = m; }); $scope.hideCarta = function () { modal.hide(); }; $scope.showCarta = function () { //$cordovaGoogleAnalytics.trackView('app.carta'); window.FirebasePlugin.setScreenName("app.carta"); window.FirebasePlugin.logEvent("page_view", {page: "app.carta"}); $scope.data = { card: $rootScope.user.card, points: $rootScope.user.points, points_pending: $rootScope.user.points_pending, }; modal.show(); if ($scope.data.card) { $('#barcode').barcode($scope.data.card, "ean13", { barWidth: 2, barHeight: 50, bgColor: '#fff', fontSize: 24, marginHRI: 12 }); } }; // push notifications var modalWelcome; $ionicModal.fromTemplateUrl('templates/welcome.html', { scope: $scope, animation: 'slide-in-up' }).then(function(m) { modalWelcome = m; }); $scope.hideWelcome = function () { modalWelcome.hide(); }; $scope.showWelcome = function () { //$cordovaGoogleAnalytics.trackView('app.welcome'); window.FirebasePlugin.setScreenName("app.welcome"); window.FirebasePlugin.logEvent("page_view", {page: "app.welcome"}); modalWelcome.show(); }; $ionicPlatform.ready(function() { /**/ if (ionic.Platform.isWebView() && ionic.Platform.isIOS()) { //var push = localStorageService.get('push'); var push = 0; console.log("C183_get"); $cordovaNativeStorage.getItem('push').then(function (value) { console.log("C183_get OK"); push = value; if (!push) { var text_msg = 'Vuoi ricevere le notifiche dell’app Cadoro in tempo reale?<br><br>Così resterai sempre aggiornato sulle nuove offerte.'; if(user.first_app) { text_msg = 'Vuoi ricevere le notifiche dell’app Cadoro in tempo reale?<br><br>Se dai il tuo consenso riceverai 100 punti di benvenuto, e resterai sempre aggiornato sulle nuove offerte.'; } var confirmPopup = $ionicPopup.confirm({ title: 'Notifiche in tempo reale', template: text_msg, okText: 'Sì!', cancelText: 'No, grazie.' }); confirmPopup.then(function(res) { if (res) { notifications.initialize(); notifications.register(function (token) { //localStorageService.set('push', 1); console.log("C204_set"); $cordovaNativeStorage.setItem('push', 1).then(function (value) { console.log("C204_set OK"); }, function (error) { console.log("C204_set ERROR"); console.log(JSON.stringify(error)); }); if(user.first_app) { $scope.showWelcome(); } }); } }); } else { notifications.initialize(); notifications.register(); } }, function(error) { console.log("C183_get ERROR"); console.log(JSON.stringify(error)); notifications.initialize(); notifications.register(); }); } else { notifications.initialize(); notifications.register(function (token) { //var push = localStorageService.get('push'); var push = 0; console.log("C231_get"); $cordovaNativeStorage.getItem('push').then(function (value) { console.log("C231_get OK"); push = value; if (!push) { //localStorageService.set('push', 1); console.log("C238_set"); $cordovaNativeStorage.setItem('push', 1).then(function (value) { console.log("C238_set OK"); }, function (error) { console.log("C238_set ERROR"); console.log(JSON.stringify(error)); }); if(user.first_app) { $scope.showWelcome(); } } }, function(error) { console.log("C231_get ERROR"); console.log(JSON.stringify(error)); //localStorageService.set('push', 1); console.log("C252_set"); $cordovaNativeStorage.setItem('push', 1).then(function (value) { console.log("C252_set OK"); }, function (error) { console.log("C252_set ERROR"); console.log(JSON.stringify(error)); }); if(user.first_app) { $scope.showWelcome(); } }); }); } /**/ }); // iBeacon var foreground = true; var didSetupBeacons = false; $ionicPlatform.on('resume', function(event) { foreground = true; loadState(); }); $ionicPlatform.on('pause', function(event) { foreground = false; }); $rootScope.beacons = []; var setupBeacons = function () { if (didSetupBeacons || !window.cordova || !window.cordova.plugins || !window.cordova.plugins.locationManager) { return; } didSetupBeacons = true; $ionicPlatform.ready(function() { var beaconStatus = {}; var delegate = new cordova.plugins.locationManager.Delegate(); delegate.didDetermineStateForRegion = function (pluginResult) { // didEnterRegion if (pluginResult.eventType == 'didDetermineStateForRegion' && pluginResult.state == 'CLRegionStateInside') { if (beaconStatus[pluginResult.region.uuid.toUpperCase()].state != "inside") { console.log('didEnterRegion: ' + JSON.stringify(pluginResult.region)); beaconStatus[pluginResult.region.uuid.toUpperCase()].state = "inside"; cordova.plugins.locationManager.startRangingBeaconsInRegion(beaconStatus[pluginResult.region.uuid.toUpperCase()].beaconRegion) .fail(function(e) { console.error(e); }) .done(); // local notification _.each($rootScope.push || [], function (notification) { if (notification.target == 2 && _.find(beaconStatus[pluginResult.region.uuid.toUpperCase()].beacons, function (b) { return b.id == notification.target_beacon_id; })) { var message = { title: notification.title, message: notification.message, data: notification.data }; cordova.plugins.notification.local.schedule(message); if (foreground) { localNotification(message); } } }); } } // didExitRegion else if (pluginResult.eventType == 'didDetermineStateForRegion' && pluginResult.state == 'CLRegionStateOutside') { if (beaconStatus[pluginResult.region.uuid.toUpperCase()].state == "inside") { console.log('didExitRegion: ' + JSON.stringify(pluginResult.region)); beaconStatus[pluginResult.region.uuid.toUpperCase()].devices = {}; beaconStatus[pluginResult.region.uuid.toUpperCase()].state = "outside"; cordova.plugins.locationManager.stopRangingBeaconsInRegion(beaconStatus[pluginResult.region.uuid.toUpperCase()].beaconRegion) .fail(function(e) { console.error(e); }) .done(); // local notification _.each($rootScope.push || [], function (notification) { if (notification.target == 3 && _.find(beaconStatus[pluginResult.region.uuid.toUpperCase()].beacons, function (b) { return b.id == notification.target_beacon_id; })) { var message = { title: notification.title, message: notification.message, data: notification.data }; cordova.plugins.notification.local.schedule(message); if (foreground) { localNotification(message); } } }); } } }; // didRangeBeacon delegate.didRangeBeaconsInRegion = function (pluginResult) { console.log('didRangeBeaconsInRegion:' + JSON.stringify(pluginResult)); cordova.plugins.locationManager.appendToDeviceLog('didRangeBeaconsInRegion: ' + JSON.stringify(pluginResult)); if (pluginResult.eventType == 'didRangeBeaconsInRegion') { _.each(pluginResult.beacons, function (b) { var key = b.uuid.toUpperCase() + "/" + b.major.toString() + "/" + b.minor.toString(); var b_data = {'accuracy': b.accuracy, 'rssi': b.rssi, 'proximity': b.proximity}; if (beaconStatus[pluginResult.region.uuid.toUpperCase()].devices[key] && b_data.proximity != beaconStatus[pluginResult.region.uuid.toUpperCase()].devices[key].proximity) { var target = null; if (b_data.proximity == 'ProximityImmediate') { target = 4; } else if (b_data.proximity == 'ProximityNear') { target = 5; } else if (b_data.proximity == 'ProximityFar') { target = 6; } if (target) { // local notification _.each($rootScope.push || [], function (notification) { _.each(beaconStatus[pluginResult.region.uuid.toUpperCase()].beacons, function (beacon) { if (notification.target == target && notification.target_beacon_id == beacon.id && beacon.uuid.toUpperCase() == b.uuid.toUpperCase() && beacon.major == b.major && beacon.minor == b.minor) { var message = { title: notification.title, message: notification.message, data: notification.data }; cordova.plugins.notification.local.schedule(message); if (foreground) { localNotification(message); } } }); }); } } // update status beaconStatus[pluginResult.region.uuid.toUpperCase()].devices[key] = b_data; }); } }; cordova.plugins.locationManager.setDelegate(delegate); cordova.plugins.locationManager.requestAlwaysAuthorization(); _.each($rootScope.beacons, function (beacon) { var uuid = beacon.uuid.toUpperCase(); var identifier = beacon.identifier; var minor = beacon.major; var major = beacon.minor; if (!beaconStatus[beacon.uuid.toUpperCase()]) { var beaconRegion = new cordova.plugins.locationManager.BeaconRegion(beacon.identifier, beacon.uuid.toUpperCase()); beaconStatus[beacon.uuid.toUpperCase()] = { beacons: [beacon], beaconRegion: beaconRegion, state: null, devices: {} }; cordova.plugins.locationManager.startMonitoringForRegion(beaconRegion) .fail(function(e) { console.error(e); }) .done(); } else { beaconStatus[beacon.uuid.toUpperCase()].beacons.push(beacon); } }); }); }; // android permissions $ionicPlatform.ready(function() { if (ionic.Platform.isWebView() && ionic.Platform.isAndroid() && window.cordova && window.cordova.plugins && window.cordova.plugins.permissions) { cordova.plugins.permissions.hasPermission(cordova.plugins.permissions.ACCESS_COARSE_LOCATION, function (status) { if (!status.hasPermission) { cordova.plugins.permissions.requestPermission(cordova.plugins.permissions.ACCESS_COARSE_LOCATION, function(status) { if (!status.hasPermission) { didSetupBeacons = true; } }, null); } }, null); } }); // local notifications var localNotification = function (notification) { if (DEBUG) { console.log('Local notification', JSON.stringify(notification)); } if (typeof notification.data == "string") { notification.data = JSON.parse(notification.data); } if (notification.data && notification.data.popup_title) { var buttons = []; if (notification.data.popup_button) { buttons = [{text: (notification.data.popup_button_icon ? '<i class="' + notification.data.popup_button_icon + '"></i> ' : '') + notification.data.popup_button}]; } hideSheet = $ionicActionSheet.show({ titleText: notification.data.popup_title, cancelText: '<i class="fa fa-times red"></i> Close', cancel: function() { hideSheet(); }, buttons: buttons, buttonClicked: function(index) { if (typeof notification.data == "string") { notification.data = JSON.parse(notification.data); } if (index === 0 && notification.data.location) { $timeout(function () { if (notification.data.location.indexOf("cadoro.it") != -1) { window.open(notification.data.location, '_blank'); } else if (notification.data.location.indexOf("http") === 0) { window.open(notification.data.location, '_system', 'location=yes'); } else { $location.path(notification.data.location); } }, 10); } } }); } else if (notification.data && notification.data.location) { if (notification.data.location.indexOf("cadoro.it") != -1) { window.open(notification.data.location, '_blank'); } else if (notification.data.location.indexOf("http") === 0) { window.open(notification.data.location, '_system', 'location=yes'); } else { $location.path(notification.data.location); } } }; $ionicPlatform.ready(function() { if (window.cordova) { cordova.plugins.notification.local.on('click', function (notification, state) { localNotification(notification); }); $rootScope.openQrReader = function () { cordova.plugins.barcodeScanner.scan( function (result) { //console.log(result.text); $http({ url: API_END_POINT + '/landing/', method: "POST", timeout: 10000, headers: { 'Authorization': 'Basic ' + btoa($rootScope.user.id + ':' + $rootScope.user.card), 'Content-Type': 'application/json' }, data: JSON.stringify({link: result.text}), }) .success(function(data, status, headers, config) { if (data && data.landing) { $location.path('/app/landing/'+data.landing); } else { window.open(result.text, '_system'); } }) .error(function(data, status, headers, config) { console.log("error"); }); }, function (error) { console.log("Scanning failed: " + error); }, { prompt : "Inquadra il QRcode", // Android }); }; } }); }) .controller('AppHomeController', function( $rootScope, $scope, //$cordovaGoogleAnalytics, $http, $ionicLoading, $ionicPopup, $ionicScrollDelegate, //localStorageService, $cordovaNativeStorage, $timeout, $location, API_END_POINT, DEBUG ) { var state = {}; var init = function () { //var state = localStorageService.get('state') || {}; state = {}; console.log("C528_get"); $cordovaNativeStorage.getItem('state').then(function (value) { console.log("C528_get OK"); state = value; $scope.magazine = state.magazine; $scope.store = _.find(state.stores || [], function (s) { return s.id == $rootScope.user.store; }); }, function(error) { console.log("C528_get ERROR"); console.log(JSON.stringify(error)); $scope.magazine = []; $scope.store = []; }); $http({ url: API_END_POINT + '/punti-vendita/' + $rootScope.user.store, method: "GET", timeout: 10000, headers: { 'Authorization': 'Basic ' + btoa($rootScope.user.id + ':' + $rootScope.user.card), 'Content-Type': 'application/json' } }) .success(function(data, status, headers, config) { $ionicLoading.hide(); $scope.store = data.store; }) .error(function(data, status, headers, config) { $ionicLoading.hide(); }); }; $scope.$on('$ionicView.beforeEnter', function () { init(); }); $scope.$on('ali:state', function () { init(); }); $scope.$on('$ionicView.enter', function () { //$cordovaGoogleAnalytics.trackView('app.home'); window.FirebasePlugin.setScreenName("app.home"); window.FirebasePlugin.logEvent("page_view", {page: "app.home"}); $timeout(function () { if (navigator.splashscreen) { navigator.splashscreen.hide(); } }, 50); }); $scope.noSondaggi = function () { $ionicPopup.alert({ title: 'AVVISO', template: '<p class="text-center">Al momento non ci sono sondaggi disponibili, ritorna presto per rispondere ad alcune domande sui nostri prodotti e attività. Potrai accedere a tanti vantaggi che Cadoro ti ha riservato.</p>' }); }; }) .controller('AppListaSpesaController', function( $rootScope, $scope, //$cordovaGoogleAnalytics, $http, $ionicLoading, $ionicPopup, $location, //localStorageService, $cordovaNativeStorage, API_END_POINT, DEBUG ) { $scope.$on('$ionicView.beforeEnter', function () { //$scope.lists = localStorageService.get('lists') || []; $scope.lists = []; console.log("C643_get"); $cordovaNativeStorage.getItem('lists').then(function (value) { console.log("C643_get OK"); $scope.lists = value; }, function(error) { console.log("C643_get ERROR"); console.log(JSON.stringify(error)); }); $ionicLoading.show({ template: 'Attendere, aggiornamento dati in corso...' }); $http({ url: API_END_POINT + '/lista-spesa', method: "GET", timeout: 10000, headers: { 'Authorization': 'Basic ' + btoa($rootScope.user.id + ':' + $rootScope.user.card), 'Content-Type': 'application/json' } }) .success(function(data, status, headers, config) { //localStorageService.set('lists', data.lists); console.log("C666_set"); $cordovaNativeStorage.setItem('lists', data.lists).then(function (value) { console.log("C666_set OK"); }, function (error) { console.log("C666_set ERROR"); console.log(JSON.stringify(error)); }); $scope.lists = data.lists; $ionicLoading.hide(); }) .error(function(data, status, headers, config) { $ionicLoading.hide(); }); }); $scope.$on('$ionicView.enter', function () { //$cordovaGoogleAnalytics.trackView('app.lista_spesa'); window.FirebasePlugin.setScreenName("app.lista_spesa"); window.FirebasePlugin.logEvent("page_view", {page: "app.lista_spesa"}); }); $scope.createList = function () { $scope.data = {}; var myPopup = $ionicPopup.show({ template: '<input type="text" ng-model="data.name">', title: 'Aggiungi un ingrediente...', scope: $scope, buttons: [ { text: 'Annulla' }, { text: '<b>AGGIUNGI</b>', type: 'button-positive', onTap: function(e) { if (!$scope.data.name) { e.preventDefault(); } else { return $scope.data.name; } } } ] }).then(function(res) { if (res) { $ionicLoading.show({ template: 'Attendere, invio dati in corso...' }); $http({ url: API_END_POINT + '/lista-spesa', method: "POST", data: JSON.stringify({name: res}), timeout: 10000, headers: { 'Authorization': 'Basic ' + btoa($rootScope.user.id + ':' + $rootScope.user.card), 'Content-Type': 'application/json' } }) .success(function(data, status, headers, config) { $ionicLoading.hide(); if (data.list) { $scope.lists.splice(0, 0, data.list); //localStorageService.set('lists', $scope.lists); console.log("C723_set"); $cordovaNativeStorage.setItem('lists', $scope.lists).then(function (value) { console.log("C723_set OK"); }, function (error) { console.log("C723_set ERROR"); console.log(JSON.stringify(error)); }); } }) .error(function(data, status, headers, config) { $ionicLoading.hide(); $ionicPopup.alert({ title: 'ERRORE', template: '<p class="text-center">Il server non è raggiungibile, verifica la tua connessione di rete prima di riprovare!</p>' }); }); } }); }; $scope.sendList = function () { $ionicLoading.show({ template: 'Attendere, aggiornamento dati in corso...' }); $http({ url: API_END_POINT + '/lista-spesa', data: {email: 1}, method: "POST", timeout: 10000, headers: { 'Authorization': 'Basic ' + btoa($rootScope.user.id + ':' + $rootScope.user.card), 'Content-Type': 'application/json' } }) .success(function(data, status, headers, config) { $ionicLoading.hide(); $ionicPopup.alert({ title: 'CONFERMA', template: '<p class="text-center">La lista della spesa è stata inviata alla tua email!</p>' }); }) .error(function(data, status, headers, config) { $ionicLoading.hide(); $ionicPopup.alert({ title: 'ERRORE', template: '<p class="text-center">Il server non è raggiungibile, verifica la tua connessione di rete prima di riprovare!</p>' }); }); }; $scope.pdfList = function () { $ionicLoading.show({ template: 'Attendere, aggiornamento dati in corso...' }); $http({ url: API_END_POINT + '/lista-spesa', data: {pdf: 1}, method: "POST", timeout: 10000, headers: { 'Authorization': 'Basic ' + btoa($rootScope.user.id + ':' + $rootScope.user.card), 'Content-Type': 'application/json' } }) .success(function(data, status, headers, config) { $ionicLoading.hide(); if (data.pdf) { window.open(data.pdf, '_system'); } }) .error(function(data, status, headers, config) { $ionicLoading.hide(); $ionicPopup.alert({ title: 'ERRORE', template: '<p class="text-center">Il server non è raggiungibile, verifica la tua connessione di rete prima di riprovare!</p>' }); }); }; $scope.deleteList = function (idList) { $ionicPopup.confirm({ title: 'CONFERMA ELIMINAZIONE', template: idList ? '<p class="text-center">Sei sicuro di voler eliminare la riga selezionata?</p>' : '<p class="text-center">Sei sicuro di voler eliminare la lista della spesa?</p>', }).then(function (res) { if (res) { $ionicLoading.show({ template: 'Attendere, aggiornamento dati in corso...' }); $http({ url: API_END_POINT + '/lista-spesa/' + (idList ? idList.toString() : ""), method: "DELETE", timeout: 10000, headers: { 'Authorization': 'Basic ' + btoa($rootScope.user.id + ':' + $rootScope.user.card), 'Content-Type': 'application/json' } }) .success(function(data, status, headers, config) { if (idList) { $scope.lists = _.filter($scope.lists, function (list) { return list.id != idList; }); } else { $scope.lists = []; } //localStorageService.set('lists', $scope.lists); console.log("C826_set"); $cordovaNativeStorage.setItem('lists', $scope.lists).then(function (value) { console.log("C826_set OK"); }, function (error) { console.log("C826_set ERROR"); console.log(JSON.stringify(error)); }); $ionicLoading.hide(); }) .error(function(data, status, headers, config) { $ionicLoading.hide(); $ionicPopup.alert({ title: 'ERRORE', template: '<p class="text-center">Il server non è raggiungibile, verifica la tua connessione di rete prima di riprovare!</p>' }); }); } }); }; }) .controller('AppOfferteController', function( $rootScope, $scope, $stateParams, //$cordovaGoogleAnalytics, $http, $ionicLoading, $ionicPopup, //localStorageService, $cordovaNativeStorage, API_END_POINT, DEBUG ) { var initialized = false; $scope.$on('$ionicView.beforeEnter', function () { $scope.points = 0; $scope.categories = []; $scope.products = []; $ionicLoading.show({ template: 'Attendere, aggiornamento dati in corso...' }); $http({ url: API_END_POINT + '/offerte', method: "GET", timeout: 30000, headers: { 'Authorization': 'Basic ' + btoa($rootScope.user.id + ':' + $rootScope.user.card), 'Content-Type': 'application/json' } }) .success(function(data, status, headers, config) { $scope.points = data.points; $scope.products = data.products; $scope.categories = _.map(data.categories, function (category) { category.products = $scope.paginate(_.filter(data.products, function (p) { return p.category_id == category.id; }), 2); return category; }); $ionicLoading.hide(); }) .error(function(data, status, headers, config) { $ionicLoading.hide(); }); }); $scope.$on('$ionicView.enter', function () { //$cordovaGoogleAnalytics.trackView('app.offerte'); window.FirebasePlugin.setScreenName("app.offerte"); window.FirebasePlugin.logEvent("page_view", {page: "app.offerte"}); }); $scope.paginate = function(arr, size) { var pages = []; size = size || this.length; while (arr.length) { pages.push(arr.splice(0, size)); } return pages; }; }) .controller('AppPreferitiController', function( $rootScope, $scope, $stateParams, //$cordovaGoogleAnalytics, $http, $ionicLoading, $ionicPopup, //localStorageService, $cordovaNativeStorage, API_END_POINT, DEBUG ) { var initialized = false; $scope.$on('$ionicView.beforeEnter', function () { $scope.favourites = []; $ionicLoading.show({ template: 'Attendere, aggiornamento dati in corso...' }); $http({ url: API_END_POINT + '/preferiti', method: "GET", timeout: 30000, headers: { 'Authorization': 'Basic ' + btoa($rootScope.user.id + ':' + $rootScope.user.card), 'Content-Type': 'application/json' } }) .success(function(data, status, headers, config) { $scope.favourites = data.favourites; $ionicLoading.hide(); }) .error(function(data, status, headers, config) { $ionicLoading.hide(); }); }); $scope.$on('$ionicView.enter', function () { //$cordovaGoogleAnalytics.trackView('app.preferiti'); window.FirebasePlugin.setScreenName("app.preferiti"); window.FirebasePlugin.logEvent("page_view", {page: "app.preferiti"}); }); }) .controller('AppPaginaController', function( $rootScope, $scope, $stateParams, //$cordovaGoogleAnalytics, //localStorageService, $cordovaNativeStorage, API_END_POINT, DEBUG ) { $scope.$on('$ionicView.beforeEnter', function () { //var state = localStorageService.get('state') || {}; var state = {}; console.log("C957_get"); $cordovaNativeStorage.getItem('state').then(function (value) { console.log("C957_get OK"); state = value; $scope.page = _.find(state.pages || [], function (p) { return p.id == $stateParams.pageId; }); }, function(error) { console.log("C957_get ERROR"); console.log(JSON.stringify(error)); $scope.page = []; }); }); $scope.$on('$ionicView.enter', function () { //$cordovaGoogleAnalytics.trackView('app.pagina.' + $scope.page.id.toString()); window.FirebasePlugin.setScreenName('app.pagina.' + $scope.page.id.toString()); window.FirebasePlugin.logEvent("page_view", {page: 'app.pagina.' + $scope.page.id.toString()}); }); }) .controller('AppImpostazioniController', function( $rootScope, $scope, //$cordovaGoogleAnalytics, $http, $ionicLoading, $ionicPopup, $ionicScrollDelegate, $timeout, //localStorageService, $cordovaNativeStorage, API_END_POINT, DEBUG ) { $scope.$on('$ionicView.beforeEnter', function () { $scope.notifications = {value: !!$rootScope.user.app_notifications}; //var state = localStorageService.get('state') || {}; //$scope.privacy_intro = state.privacy_intro || ""; //$scope.privacy_text = state.privacy_text || ""; var state = {}; $scope.privacy_intro = ""; $scope.privacy_text = ""; console.log("C999_get"); $cordovaNativeStorage.getItem('state').then(function (value) { console.log("C999_get OK"); state = value; $scope.privacy_intro = state.privacy_intro || ""; $scope.privacy_text = state.privacy_text || ""; }, function(error) { console.log("C999_get ERROR"); console.log(JSON.stringify(error)); }); }); $scope.$on('$ionicView.enter', function () { //$cordovaGoogleAnalytics.trackView('app.impostazioni'); window.FirebasePlugin.setScreenName('app.impostazioni'); window.FirebasePlugin.logEvent("page_view", {page: 'app.impostazioni'}); }); $scope.toggleExpand = function () { $scope.expand = !$scope.expand; $timeout(function () { $ionicScrollDelegate.resize(); }, 50); }; $scope.$watch('notifications', function (newValue, oldValue) { if (newValue.value == $rootScope.user.app_notifications) { return; } $ionicLoading.show({ template: 'Attendere, aggiornamento dati in corso...' }); //var data = localStorageService.get('notifications') || {}; var data = {}; console.log("C1029_get"); $cordovaNativeStorage.getItem('notifications').then(function (value) { console.log("C1029_get OK"); data = value; data.app_notifications = newValue.value; $http({ url: API_END_POINT + '/token', method: "POST", data: JSON.stringify(data), timeout: 10000, headers: { 'Authorization': 'Basic ' + btoa($rootScope.user.id + ':' + $rootScope.user.card), 'Content-Type': 'application/json' } }) .success(function(data, status, headers, config) { $ionicLoading.hide(); $rootScope.user.app_notifications = newValue.value; //localStorageService.set('user', $rootScope.user); console.log("C1049_set"); $cordovaNativeStorage.setItem('user', $rootScope.user).then(function (value) { console.log("C1049_set OK"); }, function (error) { console.log("C1049_set ERROR"); console.log(JSON.stringify(error)); }); }) .error(function(data, status, headers, config) { $ionicLoading.hide(); $ionicPopup.alert({ title: 'ERRORE', template: '<p class="text-center">Il server non è raggiungibile, verifica la tua connessione di rete prima di riprovare!</p>' }); }); }, function(error) { console.log("C1029_get ERROR"); console.log(JSON.stringify(error)); $ionicLoading.hide(); }); }, true); }) .controller('AppAssistenzaController', function( $rootScope, $scope, //$cordovaGoogleAnalytics, $http, $ionicLoading, $ionicPopup, //localStorageService, $cordovaNativeStorage, API_END_POINT, DEBUG ) { $scope.$on('$ionicView.beforeEnter', function () { //var state = localStorageService.get('state') || {}; var state = {}; console.log("C1088_get"); $cordovaNativeStorage.getItem('state').then(function (value) { console.log("C1088_get OK"); state = value; $scope.subjects = state.subjects; }, function(error) { console.log("C1088_get ERROR"); console.log(JSON.stringify(error)); $scope.subjects = []; }); $scope.data = { subject: null, message: null, card: $rootScope.user.card, email: $rootScope.user.email, firstname: $rootScope.user.firstname, lastname: $rootScope.user.lastname }; }); $scope.$on('$ionicView.enter', function () { //$cordovaGoogleAnalytics.trackView('app.assistenza'); window.FirebasePlugin.setScreenName('app.assistenza'); window.FirebasePlugin.logEvent("page_view", {page: 'app.assistenza'}); }); $scope.send = function (data) { $ionicLoading.show({ template: 'Attendere, invio dati in corso...' }); $http({ url: API_END_POINT + '/assistenza', method: "POST", data: JSON.stringify(data), timeout: 10000, headers: { 'Authorization': 'Basic ' + btoa($rootScope.user.id + ':' + $rootScope.user.card), 'Content-Type': 'application/json' } }) .success(function(data, status, headers, config) { $ionicLoading.hide(); $ionicPopup.alert({ title: 'CONFERMA', template: '<p class="text-center">Il messaggio è stato inviato correttamente, ti contatteremo il prima possibile!</p>' }); $scope.data.subject = null; $scope.data.message = null; $scope.data.email = false; }) .error(function(data, status, headers, config) { $ionicLoading.hide(); $ionicPopup.alert({ title: 'ERRORE', template: '<p class="text-center">Il server non è raggiungibile, verifica la tua connessione di rete prima di riprovare!</p>' }); }); }; }) .controller('AppAssistenzaTourController', function( $rootScope, $scope, //$cordovaGoogleAnalytics, //localStorageService, $cordovaNativeStorage, API_END_POINT, DEBUG ) { $scope.$on('$ionicView.beforeEnter', function () { //var state = localStorageService.get('state') || {}; var state = {}; $scope.banners = []; console.log("C1159_get"); $cordovaNativeStorage.getItem('state').then(function (value) { console.log("C1159_get OK"); state = value; $scope.banners = state.tour; }, function(error) { console.log("C1159_get ERROR"); console.log(JSON.stringify(error)); }); }); $scope.$on('$ionicView.enter', function () { //$cordovaGoogleAnalytics.trackView('app.assistenza.tour'); window.FirebasePlugin.setScreenName('app.assistenza.tour'); window.FirebasePlugin.logEvent("page_view", {page: 'app.assistenza.tour'}); }); }) .controller('AppProfiloController', function( $rootScope, $scope, //$cordovaGoogleAnalytics, $http, $ionicLoading, $ionicPopup, $ionicScrollDelegate, $timeout, //localStorageService, $cordovaNativeStorage, API_END_POINT, DEBUG ) { $scope.$on('$ionicView.beforeEnter', function () { }); $scope.$on('$ionicView.enter', function () { //$cordovaGoogleAnalytics.trackView('app.profilo'); window.FirebasePlugin.setScreenName('app.profilo'); window.FirebasePlugin.logEvent("page_view", {page: 'app.profilo'}); }); }) .controller('AppProfiloModificaController', function( $rootScope, $scope, //$cordovaGoogleAnalytics, $http, $ionicHistory, $ionicLoading, $ionicPopup, $timeout, //localStorageService, $cordovaNativeStorage, API_END_POINT, DEBUG ) { $scope.$on('$ionicView.beforeEnter', function () { $scope.user = _.clone($rootScope.user); }); $scope.$on('$ionicView.enter', function () { //$cordovaGoogleAnalytics.trackView('app.profilo_modifica'); window.FirebasePlugin.setScreenName('app.profilo_modifica'); window.FirebasePlugin.logEvent("page_view", {page: 'app.profilo_modifica'}); }); $scope.update = function (user) { $http({ url: API_END_POINT + '/profilo', method: "PUT", data: JSON.stringify(user), timeout: 10000, headers: { 'Authorization': 'Basic ' + btoa($rootScope.user.id + ':' + $rootScope.user.card), 'Content-Type': 'application/json' } }) .success(function(data, status, headers, config) { $ionicLoading.hide(); $ionicHistory.goBack(-1); }) .error(function(data, status, headers, config) { $ionicLoading.hide(); $ionicPopup.alert({ title: 'ERRORE', template: '<p class="text-center">Il server non è raggiungibile, verifica la tua connessione di rete prima di riprovare!</p>' }); }); }; }) .controller('AppNotificheController', function( $rootScope, $scope, //$cordovaGoogleAnalytics, $http, $ionicLoading, $ionicPopup, //localStorageService, $cordovaNativeStorage, API_END_POINT, DEBUG ) { var initialized = false; $scope.$on('$ionicView.beforeEnter', function () { $scope.notifications = []; $ionicLoading.show({ template: 'Attendere, aggiornamento dati in corso...' }); $http({ url: API_END_POINT + '/notifiche', method: "GET", timeout: 30000, headers: { 'Authorization': 'Basic ' + btoa($rootScope.user.id + ':' + $rootScope.user.card), 'Content-Type': 'application/json' } }) .success(function(data, status, headers, config) { //var read = localStorageService.get('read_notifications') || []; var read = []; $scope.notifications = []; console.log("C1272_get"); $cordovaNativeStorage.getItem('read_notifications').then(function (value) { console.log("C1272_get OK"); read = value; $scope.notifications = _.map(data.notifications, function (n) { n.read = (_.indexOf(read, n.id) != -1); return n; }); }, function(error) { console.log("C1272_get ERROR"); console.log(JSON.stringify(error)); }); $ionicLoading.hide(); }) .error(function(data, status, headers, config) { $ionicLoading.hide(); }); }); $scope.$on('$ionicView.enter', function () { //$cordovaGoogleAnalytics.trackView('app.notifiche'); window.FirebasePlugin.setScreenName('app.notifiche'); window.FirebasePlugin.logEvent("page_view", {page: 'app.notifiche'}); }); $scope.read = function (notification) { //var read = localStorageService.get('read_notifications') || []; var read = []; console.log("C1298_get"); $cordovaNativeStorage.getItem('read_notifications').then(function (value) { console.log("C1298_get OK"); read = value; if (_.indexOf(read, notification.id) == -1) { read.push(notification.id); //localStorageService.set('read_notifications', read); console.log("C1306_set"); $cordovaNativeStorage.setItem('read_notifications', read).then(function (value) { console.log("C1306_set OK"); }, function (error) { console.log("C1306_set ERROR"); console.log(JSON.stringify(error)); }); } }, function(error) { console.log("C1298_get ERROR"); console.log(JSON.stringify(error)); }); $rootScope.$broadcast('ali:state'); window.open(notification.url, '_system'); }; }) .controller('AppPuntiVenditaController', function( $rootScope, $scope, $http, $ionicLoading, $ionicPopup, //$cordovaGoogleAnalytics, $timeout, //localStorageService, $cordovaNativeStorage, API_END_POINT, DEBUG, utilities ) { $scope.$on('$ionicView.beforeEnter', function () { //var state = localStorageService.get('state') || {}; var state = {}; console.log("C1340_get"); $cordovaNativeStorage.getItem('state').then(function (value) { console.log("C1340_get OK"); state = value; $scope.stores = state.stores || []; }, function(error) { console.log("C1340_get ERROR"); console.log(JSON.stringify(error)); $scope.stores = []; }); $scope.stores_results = []; $scope.provinces = []; $scope.cities = []; $scope.data = { province: null, city: null, }; $http({ url: API_END_POINT + '/punti-vendita', method: "GET", timeout: 10000, headers: { 'Authorization': 'Basic ' + btoa($rootScope.user.id + ':' + $rootScope.user.card), 'Content-Type': 'application/json' } }) .success(function(data, status, headers, config) { $ionicLoading.hide(); $scope.stores = state.stores = data.stores; $scope.filter(); //localStorageService.set('state', state); console.log("C1373_set"); $cordovaNativeStorage.setItem('state', state).then(function (value) { console.log("C1373_set OK"); }, function (error) { console.log("C1373_set ERROR"); console.log(JSON.stringify(error)); }); var current_position = function () { navigator.geolocation.getCurrentPosition( function (position, force) { var stores = _.map($scope.stores, function (s) { var d = position ? utilities.geodistance(s.lat, s.lng, position.coords.latitude, position.coords.longitude) : null; s.distance = parseInt(d); return s; }); $timeout(function (stores) { return function () { $scope.stores = _.sortBy(stores, function (e) { return e.distance; }); $scope.filter(); }; }(stores)); } , function (error) { if (error.code == 1 && !$rootScope.punti_vendita_nogeo) { $rootScope.punti_vendita_nogeo = 1; $ionicPopup.alert({ title: 'AVVISO', template: '<p class="text-center">Per trovare il supermercato più vicino a te, abilita la localizzazione nelle impostazioni del tuo smartphone.</p>', }); } } , {timeout: 10000, enableHighAccuracy: false, maximumAge: 600000} ); }; if (ionic.Platform.isWebView() && ionic.Platform.isAndroid() && window.cordova && window.cordova.plugins && window.cordova.plugins.permissions) { cordova.plugins.permissions.hasPermission(cordova.plugins.permissions.ACCESS_FINE_LOCATION, function (status) { if (!status.hasPermission) { cordova.plugins.permissions.requestPermission(cordova.plugins.permissions.ACCESS_FINE_LOCATION, function(status) { current_position(); }, null); } else { current_position(); } }, null); } else { current_position(); } }) .error(function(data, status, headers, config) { $ionicLoading.hide(); $ionicPopup.alert({ title: 'ERRORE', template: '<p class="text-center">Il server non è raggiungibile, verifica la tua connessione di rete prima di riprovare!</p>' }); }); }); $scope.$on('$ionicView.enter', function () { //$cordovaGoogleAnalytics.trackView('app.punti_vendita'); window.FirebasePlugin.setScreenName('app.punti_vendita'); window.FirebasePlugin.logEvent("page_view", {page: 'app.punti_vendita'}); }); $scope.filter = function () { $scope.stores_results = []; $scope.provinces = []; $scope.cities = []; _.each($scope.stores, function (s) { if (!_.find($scope.provinces, function (p) { return p == s.province; })) { $scope.provinces.push(s.province); } if ((!$scope.data.province || $scope.data.province == s.province) && (!$scope.data.city || $scope.data.city == s.city)) { $scope.stores_results.push(s); if (!_.find($scope.cities, function (p) { return p == s.city; })) { $scope.cities.push(s.city); } } }); }; $scope.$watch('data', function (newValue, oldValue) { $scope.filter(); }, true); }) .controller('AppPuntiVenditaDettaglioController', function( $rootScope, $scope, $http, $ionicLoading, //$cordovaGoogleAnalytics, $ionicHistory, $ionicNavBarDelegate, $ionicPopup, $ionicScrollDelegate, $ionicPlatform, $state, $stateParams, $timeout, //localStorageService, $cordovaNativeStorage, API_END_POINT, DEBUG ) { $scope.$on('$ionicView.beforeEnter', function () { //var state = localStorageService.get('state') || {}; var state = {}; $ionicPlatform.ready(function() { console.log("C1318_get"); $cordovaNativeStorage.getItem('state').then(function (value) { console.log("C1318_get OK"); state = value; $scope.store = _.find(state.stores || [], function (s) { return s.id == $stateParams.id; }); }, function(error) { console.log("C1318_get ERROR"); console.log(JSON.stringify(error)); }); $scope.view = 1; $timeout(function(){ $http({ url: API_END_POINT + '/punti-vendita/' + $stateParams.id, method: "GET", timeout: 10000, headers: { 'Authorization': 'Basic ' + btoa($rootScope.user.id + ':' + $rootScope.user.card), 'Content-Type': 'application/json' } }) .success(function(data, status, headers, config) { $ionicLoading.hide(); $scope.store = data.store; //localStorageService.set('state', state); console.log("C1343_set"); $cordovaNativeStorage.setItem('state', state).then(function (value) { console.log("C1343_set OK"); }, function (error) { console.log("C1343_set ERROR"); console.log(JSON.stringify(error)); }); }) .error(function(data, status, headers, config) { $ionicLoading.hide(); $ionicPopup.alert({ title: 'ERRORE', template: '<p class="text-center">Il server non è raggiungibile, verifica la tua connessione di rete prima di riprovare!</p>' }); }); }, 1000); $ionicNavBarDelegate.showBackButton(false); }); }); $scope.$on('$ionicView.enter', function () { //$cordovaGoogleAnalytics.trackView('app.punti_vendita_dettaglio'); $ionicPlatform.ready(function() { window.FirebasePlugin.setScreenName('app.punti_vendita_dettaglio'); window.FirebasePlugin.logEvent("page_view", {page: 'app.punti_vendita_dettaglio'}); }); }); $scope.$on('$ionicView.leave', function () { $ionicNavBarDelegate.showBackButton(false); }); $scope.setView = function (v) { $scope.view = v; $timeout(function () { if (v == 2) { var store = $scope.store , options = { zoom: 13 , mapTypeId: google.maps.MapTypeId.ROADMAP , disableDefaultUI: true , zoomControl: true }; var map = new google.maps.Map(document.getElementById("gmap-" + $scope.store.id.toString()), options); var marker = new google.maps.Marker({ position: new google.maps.LatLng(store.lat, store.lng) , map: map , title: store.title }); map.setCenter(new google.maps.LatLng(store.lat, store.lng)); map.setZoom(13); } $ionicScrollDelegate.resize(); }, 100); }; $scope.goBack = function () { if ($ionicHistory.backView()) { $ionicHistory.goBack(); } else { $ionicHistory.nextViewOptions({ disableBack: true }); if (!$scope.store || $scope.store.id == $rootScope.user.store) { $state.go('app.home'); } else { $state.go('app.punti_vendita'); } } }; }) .controller('AppMagazineController', function( $rootScope, $scope, $http, $ionicLoading, //$cordovaGoogleAnalytics, $ionicHistory, $ionicNavBarDelegate, $ionicPopup, $ionicScrollDelegate, $state, $stateParams, $timeout, //localStorageService, $cordovaNativeStorage, $sce, API_END_POINT, DEBUG ) { var initialized = false; $scope.$on('$ionicView.beforeEnter', function () { //var state = localStorageService.get('state') || {}; var state = {}; $scope.magazine = []; console.log("C1585_get"); $cordovaNativeStorage.getItem('state').then(function (value) { console.log("C1585_get OK"); state = value; $scope.magazine = state.magazine; }, function(error) { console.log("C1585_get ERROR"); console.log(JSON.stringify(error)); }); }); $scope.$on('$ionicView.enter', function () { //$cordovaGoogleAnalytics.trackView('app.magazine'); window.FirebasePlugin.setScreenName('app.magazine'); window.FirebasePlugin.logEvent("page_view", {page: 'app.magazine'}); }); $scope.trustAsHtml = function(string) { return $sce.trustAsHtml(string); }; }) .controller('AppLandingController', function( $rootScope, $scope, $http, $ionicLoading, //$cordovaGoogleAnalytics, $ionicHistory, $ionicNavBarDelegate, $ionicPopup, $ionicScrollDelegate, $state, $stateParams, $timeout, //localStorageService, $cordovaNativeStorage, $location, $sce, API_END_POINT, DEBUG ) { var id = $stateParams.id; console.log('id: '+id); $scope.$on('$ionicView.beforeEnter', function () { $http({ url: API_END_POINT + '/landing/' + id, method: "GET", timeout: 30000, headers: { 'Authorization': 'Basic ' + btoa($rootScope.user.id + ':' + $rootScope.user.card), 'Content-Type': 'application/json' } }) .success(function(data, status, headers, config) { $scope.landing = data.landing; $ionicLoading.hide(); }) .error(function(data, status, headers, config) { $ionicLoading.hide(); }); }); $scope.$on('$ionicView.enter', function () { //$cordovaGoogleAnalytics.trackView('app.landing'); window.FirebasePlugin.setScreenName('app.landing'); window.FirebasePlugin.logEvent("page_view", {page: 'app.landing'}); if (navigator.splashscreen) { navigator.splashscreen.hide(); } }); $scope.trustAsHtml = function(string) { return $sce.trustAsHtml(string); }; });