Files
Colaborando/manejoDeSesiones.js

225 lines
7.4 KiB
JavaScript

// Función para obtener el valor de un parámetro de la URL
function getUrlParameterXX(name) {
name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]')
const regex = new RegExp('[\\?&]' + name + '=([^&#]*)'),
results = regex.exec(location.search)
return results === null
? ''
: decodeURIComponent(results[1].replace(/\+/g, ' '))
}
function getUrlParameter(name) {
name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]')
const regex = new RegExp('[\\?&]' + name + '=([^&#]*)', 'i'),
results = regex.exec(location.search)
return results === null
? ''
: decodeURIComponent(results[1].replace(/\+/g, ' '))
}
// Función para cargar datos desde el servidor
function cargarDatosDesdeServidor() {
// Si es "Nueva sesión", no cargar datos desde el servidor
console.log('NS: ', getUrlParameter('NS'))
if (getUrlParameter('NS') == '') {
console.log('Cargando datos desde el servidor...')
let nombreArchivo = getUrlParameter('nombre')
if (nombreArchivo == '') {
nombreArchivo = getUrlParameter('n')
}
console.log('nombreArchivo:', nombreArchivo)
let url = 'manejoDeSesiones.php'
if (nombreArchivo != '') {
url +=
'?nombre=' +
encodeURIComponent(nombreArchivo) +
'&_t=' +
new Date().getTime()
} else {
url += '?_t=' + new Date().getTime()
}
fetch(url, { cache: 'no-store' })
.then((response) => response.json())
.then((data) => {
datosCarga = data
console.log('DATA: ', data)
console.log('eeeeee')
console.log(
'TAMAÑO DATOS: ',
data.data.size,
data.status,
data.data.arregloGeneral,
typeof data.data.arregloGeneral
)
if (
typeof data.data.arregloGeneral !== undefined &&
data.status === 'success'
) {
console.log('Datos cargados exitosamente desde el servidor')
arregloGeneral = data.data.arregloGeneral
// --- INICIO DEL PARCHE para ganancias por trimestre ---
if (typeof arregloGeneral.trimestre1 === 'undefined') {
arregloGeneral.trimestre1 = 0
}
if (typeof arregloGeneral.trimestre2 === 'undefined') {
arregloGeneral.trimestre2 = 0
}
if (typeof arregloGeneral.trimestre3 === 'undefined') {
arregloGeneral.trimestre3 = 0
}
if (typeof arregloGeneral.trimestre4 === 'undefined') {
arregloGeneral.trimestre4 = 0
}
if (typeof arregloGeneral.objetivoT1 === 'undefined') {
arregloGeneral.objetivoT1 = 100000
}
if (typeof arregloGeneral.objetivoT2 === 'undefined') {
arregloGeneral.objetivoT2 = 100000
}
if (typeof arregloGeneral.objetivoT3 === 'undefined') {
arregloGeneral.objetivoT3 = 100000
}
if (typeof arregloGeneral.objetivoT4 === 'undefined') {
arregloGeneral.objetivoT4 = 100000
}
if (typeof arregloGeneral.bAccion1 === 'undefined') {
arregloGeneral.bAccion1 = 0
}
if (typeof arregloGeneral.bAccion2 === 'undefined') {
arregloGeneral.bAccion2 = 0
}
// --- FIN DEL PARCHE ---
arreglosCapacitaciones = data.data.arreglosCapacitaciones
arreglosActivos = data.data.arreglosActivos
arreglosDeptos = data.data.arreglosDeptos
proyectos = data.data.proyectos
// Si el estado guardado contiene el ID del proyecto grande, lo cargamos.
if (data.data.arregloGeneral.hasOwnProperty('proyectoGdeActual')) {
proyectoGdeActual = data.data.arregloGeneral.proyectoGdeActual
} else {
proyectoGdeActual = '' // Limpiamos por si no viene en el archivo de guardado.
}
console.log(arregloGeneral)
console.log(arreglosDeptos)
continuamos()
} else if (
data.status === 'error' &&
data.data.message === 'File not found'
) {
console.log(
'El archivo de sesión no existe. Usando arreglos predefinidos.'
)
continuamos()
// Usar los arreglos definidos en colaborando_arreglos.js
guardarDatosEnServidor() // Guardar los arreglos predefinidos
} else {
console.error('Error cargando los datos:', data.data.message)
console.error('Data:', data)
}
})
.catch(
(error) =>
function () {
console.log('Error:', error)
}
)
} else if (getUrlParameter('NS') == '1') {
// Usar los arreglos definidos en colaborando_arreglos.js
continuamos() //Creamos la nueva sesion
guardarDatosEnServidor().then(() => {
let url = new URL(window.location.href)
url.searchParams.delete('NS') // Quitamos el parametro NS de el URL
url.searchParams.delete('ns')
console.log('REFRESCANDO SIN ')
window.location.href = url.toString() // Refrescamos la pagina SIN el "NS"
})
} else {
console.log(
'No se cargan datos desde el servidor porque es una nueva sesión'
)
// Usar los arreglos definidos en colaborando_arreglos.js
continuamos()
}
}
// Función para guardar datos en el servidor
function guardarDatosEnServidor() {
// Añadimos el ID del proyecto grande actual para que se guarde en la sesión.
arregloGeneral.proyectoGdeActual = proyectoGdeActual
const datos = {
arregloGeneral,
arreglosCapacitaciones,
arreglosActivos,
arreglosDeptos,
proyectos,
}
console.log('Guardando datos en el servidor...')
// console.log('TAMAÑO DATOS: ', datos.size)
let nombreArchivo = getUrlParameter('nombre')
if (nombreArchivo == '') {
nombreArchivo = getUrlParameter('n')
}
let url = 'manejoDeSesiones.php'
if (nombreArchivo != '') {
url += '?nombre=' + encodeURIComponent(nombreArchivo)
}
return fetch(url, {
method: 'POST',
keepalive: true, // Asegura que la petición termine aunque se cierre la página
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ data: datos }),
})
.then((response) => response.json())
.then((data) => {
if (data.status === 'success') {
console.log('Datos guardados exitosamente')
} else {
console.error('Error guardando los datos:', data.message)
}
})
.catch((error) => console.error('Error:', error))
}
const guardaSesion = guardarDatosEnServidor
// Cargar datos al iniciar la página
document.addEventListener('DOMContentLoaded', cargarDatosDesdeServidor)
// Guardar datos al cerrar la página
window.addEventListener('beforeunload', function () {
guardarDatosEnServidor()
})
// Función global para alternar pantalla completa
function toggleFullscreen() {
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen().catch((err) => {
console.error(
`Error al intentar activar pantalla completa: ${err.message}`
)
})
} else {
document.exitFullscreen()
}
}
// Escuchar el cambio de estado de pantalla completa para actualizar el texto del botón
document.addEventListener('fullscreenchange', () => {
const btn = document.getElementById('btnFullscreen')
if (btn) {
if (document.fullscreenElement) {
btn.textContent = 'Salir Pantalla Completa'
} else {
btn.textContent = 'Pantalla Completa'
}
}
})