var linkElement = document.createElement("link"); linkElement.rel = "stylesheet"; linkElement.type = "text/css"; linkElement.media = "screen" linkElement.href = "/assets/plugins/alerts/toastr.min.css"; //Replace here document.head.appendChild(linkElement); addScript("/assets/plugins/alerts/toastr.min.js", () => { /* start configure toastr when ready*/ const onOrdersWindow = location.href.includes('/pedidos/list'); const onProdWindow = location.href.includes('/produccion/list'); const refreshEvent = new CustomEvent("refresh-pedidos", { detail: "Evento para actualizar pedidos" }); toastr.options.escapeHtml = true; toastr.options.closeButton = true; toastr.options.closeMethod = 'fadeOut'; toastr.options.closeDuration = 300; toastr.options.closeEasing = 'swing'; if(onOrdersWindow) { toastr.options.timeOut = 0; toastr.options.extendedTimeOut = 0; toastr.options.onclick = () => { if(onOrdersWindow) document.dispatchEvent(refreshEvent); else window.open("/pedidos/list", "_blank"); } toastr.options.onCloseClick = () => { if(onOrdersWindow) document.dispatchEvent(refreshEvent); }; } /* end configure toastr*/ if(onOrdersWindow) { navigator.serviceWorker.addEventListener('message', event => { document.dispatchEvent(refreshEvent); }); } }); /* End toastr imports */ // Your web app's Firebase configuration var firebaseConfig = { apiKey: "AIzaSyCiubDaNIJ2CXYzEWN6P3--HuGbh3nQdMM", authDomain: "carnescayal-2018.firebaseapp.com", databaseURL: "https://carnescayal-2018.firebaseio.com", projectId: "carnescayal-2018", storageBucket: "carnescayal-2018.appspot.com", messagingSenderId: "962112650031", appId: "1:962112650031:web:c7ec2a29850c2ad9b87fda", measurementId: "G-JFVDHNR0M2" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); // firebase.analytics(); const messaging = firebase.messaging(); messaging.usePublicVapidKey( "BD9WImxyRpGsWjDQ79fDbz2QQA7U8H9PR-4t9H1dff5lmvS8r5a11KcjjRsLbnld4aGndGV4-uwm1DaEBGcmpKU"); messaging.onMessage(payload => { console.log('Message received. ', payload); if (payload) { let title = 'Pedidos: '; const message = payload.data.message; const status = parseInt(payload.data.status); switch (status) { case 200: // Se mando de manera correcta title += 'Correcto'; toastr.success(message, title); break; case 103: // Info: El pedido ya había había sido enviado case 199: // Info title += 'Información'; toastr.warning(message, title); break; case 514: // Error case 512: // Error case 513: // Error case 500: // Error default: // Un error inesperado title += 'Oops, un error'; toastr.error(message, title); } } // [START_EXCLUDE] // Update the UI to include the received message. // [END_EXCLUDE] }); // [START refresh_token] // Callback fired if Instance ID token is updated. messaging.onTokenRefresh(() => { messaging.getToken().then(refreshedToken => { console.log('Token refreshed.'); // Indicate that the new Instance ID token has not yet been sent to the // app server. // setTokenSentToServer(false); // Send Instance ID token to app server. assertUserHasSyncedToken(refreshedToken); // [START_EXCLUDE] // Display new Instance ID token and clear UI of all previous messages. // [END_EXCLUDE] }).catch(err => { console.log('Unable to retrieve refreshed token ', err); }); }); // [END refresh_token] Notification.requestPermission().then(permission => { if (permission === 'granted') { console.log('Notification permission granted.'); // Get Instance ID token. Initially this makes a network call, once retrieved // subsequent calls to getToken will return from cache. messaging.getToken().then(currentToken => { if (currentToken) { // console.log('currentToken: ', currentToken); assertUserHasSyncedToken(currentToken); } else { // Show permission request. console.log('No Instance ID token available. Request permission to generate one.'); // Show permission UI. setTokenSentToServer(false); } }).catch(err => { console.log('An error occurred while retrieving token. ', err); setTokenSentToServer(false); }); } else { console.log('Unable to get permission to notify.'); } }); function sendTokenToServer(currentToken) { if (!isTokenSentToServer()) { console.log('Sending token to server...'); // TODO(developer): Send the current token to your server. fetch("/pushmessage/setToken", { method: 'POST', body: currentToken, headers: { 'Content-Type': 'application/json' } }) .then(res => res.json()) .catch(err => { setTokenSentToServer(false); }) .then(res => { console.log(res); switch (res.Status) { case 200: // Se asignó correctamente el token para notificaciones setTokenSentToServer(true); // Configuramos este token como "enviado" break; case 400: // No se ha iniciado sesión case 500: // No se encontró al usuario en Datastore setTokenSentToServer(false); // Configuramos este token como "no enviado" break; } console.log(res.Message); }) } else { console.log('Token already sent to server so won\'t send it again ' + 'unless it changes'); } } function assertUserHasSyncedToken(currentToken) { setTokenSentToServer(false); fetch("/pushmessage/assertTokenIsSynced", { method: 'POST', body: currentToken, headers: { 'Content-Type': 'application/json' } }) .then(res => res.json()) .catch(err => { setTokenSentToServer(false); }) .then(res => { console.log(res); switch (res.Status) { case 200: //El token está actualizado para este usuario setTokenSentToServer(true); // Asignamos como "enviado" este token break; case 199: // El token no está actualizado o el usuario no tenia ningun token asignado case 400: // No se ha iniciado sesión case 500: // No se encontró al usuario en Datastore setTokenSentToServer(false); // Asignamos como "no enviado" este token break; } console.log(res.Message); sendTokenToServer(currentToken); //Intentamos enviar este token al servidor }); } function isTokenSentToServer() { return window.localStorage.getItem('sentToServer') === '1'; } function setTokenSentToServer(sent) { window.localStorage.setItem('sentToServer', sent ? '1' : '0'); } function addScript(filepath, callback) { if (filepath) { var fileref = document.createElement('script'); var done = false; var head = document.head; fileref.onload = fileref.onreadystatechange = function () { if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) { done = true; callback(); // Handle memory leak in IE fileref.onload = fileref.onreadystatechange = null; if (head && fileref.parentNode) { head.removeChild(fileref); } } }; fileref.type = "text/javascript"; fileref.src = filepath; head.appendChild(fileref); } }