-
Notifications
You must be signed in to change notification settings - Fork 150
Expand file tree
/
Copy pathlottery-functions.js
More file actions
169 lines (145 loc) · 7.36 KB
/
Copy pathlottery-functions.js
File metadata and controls
169 lines (145 loc) · 7.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
// ===== LOTTERY & TURN LOCK FUNCTIONS =====
// Added for tombola and locked positions feature
// Security: HTML escape helper
var _lottEsc = typeof escapeHtml === "function" ? escapeHtml : function(s) {
return String(s).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");
};
// Get current user ID (consistent with main system)
function getLotteryUserId() {
// 1. Try latanda_user object first (main auth)
try {
var userJson = localStorage.getItem("latanda_user");
if (userJson) {
var user = JSON.parse(userJson);
if (user && user.user_id) return user.user_id;
if (user && user.id) return user.id;
}
} catch (e) {}
// 2. Direct keys
return localStorage.getItem("latanda_user_id") ||
sessionStorage.getItem("latanda_user_id") ||
localStorage.getItem("userId") ||
localStorage.getItem("user_id") ||
null;
}
// Toggle lock status for a turn position
function toggleTurnLock(index) {
if (!turnsMembers || !turnsMembers[index]) return;
turnsMembers[index].turn_locked = !turnsMembers[index].turn_locked;
renderTurnsList();
}
// Start lottery countdown (10 seconds)
async function startLotteryCountdown() {
var unlockedCount = turnsMembers.filter(function(m) { return !m.turn_locked; }).length;
if (unlockedCount === 0) {
if (typeof showNotification === "function") showNotification("No hay posiciones desbloqueadas para sortear. Desbloquea al menos una posicion.", "error");
return;
}
// Confirm before starting
if (typeof showConfirm === "function") {
var proceed = await showConfirm("Se sortearan " + unlockedCount + " posiciones no bloqueadas. Las posiciones con candado no cambiaran. ¿Iniciar tombola?");
if (!proceed) return;
}
// Create countdown modal
var countdownModal = document.createElement("div");
countdownModal.id = "lotteryCountdownModal";
countdownModal.style.cssText = "position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.9); display: flex; align-items: center; justify-content: center; z-index: 20000;";
countdownModal.innerHTML =
"<div style=\"text-align: center;\">" +
"<div style=\"font-size: 8rem; color: #f59e0b; font-weight: bold;\" id=\"countdownNumber\">10</div>" +
"<div style=\"font-size: 1.5rem; color: white; margin-top: 20px;\">🎲 Preparando tombola...</div>" +
"<button onclick=\"cancelLottery()\" style=\"margin-top: 30px; padding: 10px 30px; background: #dc2626; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 1rem;\">Cancelar</button>" +
"</div>";
document.body.appendChild(countdownModal);
var count = 10;
window.lotteryInterval = setInterval(function() {
count--;
var numberEl = document.getElementById("countdownNumber");
if (numberEl) numberEl.textContent = count;
if (count <= 0) {
clearInterval(window.lotteryInterval);
executeLottery();
}
}, 1000);
}
// Cancel lottery countdown
function cancelLottery() {
if (window.lotteryInterval) {
clearInterval(window.lotteryInterval);
}
var modal = document.getElementById("lotteryCountdownModal");
if (modal) modal.remove();
}
// Execute the lottery via API
async function executeLottery() {
var modal = document.getElementById("lotteryCountdownModal");
if (modal) {
modal.innerHTML =
"<div style=\"text-align: center;\">" +
"<div style=\"font-size: 4rem;\">🎲</div>" +
"<div style=\"font-size: 1.5rem; color: white; margin-top: 20px;\">Sorteando posiciones...</div>" +
"</div>";
}
try {
var userId = getLotteryUserId();
console.log("[Lottery] User ID:", userId);
console.log("[Lottery] Group ID:", manageTurnsGroupId);
if (!userId) {
throw new Error("No se pudo obtener el ID del usuario");
}
var apiBase = window.API_BASE_URL || "https://latanda.online";
var response = await fetch(apiBase + "/api/groups/" + manageTurnsGroupId + "/lottery-assign?user_id=" + userId, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ coordinator_id: userId })
});
var result = await response.json();
console.log("[Lottery] API Response:", result);
if (result.success) {
showLotteryResults(result.data);
} else {
if (modal) modal.remove();
console.error("[Lottery] API error:", result.data?.error?.message || result.error);
if (typeof showNotification === "function") showNotification("Error en la tombola. Intenta de nuevo.", "error");
}
} catch (error) {
console.error("[Lottery] Error:", error);
if (modal) modal.remove();
if (typeof showNotification === "function") showNotification("Error de conexion. Verifica tu internet.", "error");
}
}
// Show lottery results with animation
function showLotteryResults(data) {
var modal = document.getElementById("lotteryCountdownModal");
if (!modal) return;
var assignmentsHtml = data.assignments.map(function(a) {
return "<div style=\"display: flex; align-items: center; gap: 12px; padding: 12px; background: rgba(255,255,255,0.1); border-radius: 8px; margin: 8px 0;\">" +
"<div style=\"width: 36px; height: 36px; background: linear-gradient(135deg, #f59e0b, #d97706); border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; color: white;\">" + a.new_position + "</div>" +
"<div style=\"color: white; font-weight: 500;\">" + _lottEsc(a.display_name || "Usuario") + "</div>" +
"</div>";
}).join("");
modal.innerHTML =
"<div style=\"text-align: center; max-width: 400px; width: 90%;\">" +
"<div style=\"font-size: 4rem; margin-bottom: 16px;\">🎉</div>" +
"<div style=\"font-size: 1.5rem; color: #10b981; font-weight: bold; margin-bottom: 8px;\">¡Tombola completada!</div>" +
"<div style=\"color: #9ca3af; margin-bottom: 20px;\">" + data.assigned_count + " posiciones asignadas • " + data.locked_count + " bloqueadas</div>" +
"<div style=\"max-height: 300px; overflow-y: auto;\">" + assignmentsHtml + "</div>" +
"<button onclick=\"closeLotteryAndRefresh()\" style=\"margin-top: 20px; padding: 12px 40px; background: linear-gradient(135deg, #10b981, #059669); color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 1rem; font-weight: 600;\">Aceptar</button>" +
"</div>";
}
// Close lottery modal and refresh turns list
async function closeLotteryAndRefresh() {
var modal = document.getElementById("lotteryCountdownModal");
if (modal) modal.remove();
// Reload members to get updated positions
await loadTurnsMembers(manageTurnsGroupId);
}
// Make functions global
window.getLotteryUserId = getLotteryUserId;
window.toggleTurnLock = toggleTurnLock;
window.startLotteryCountdown = startLotteryCountdown;
window.cancelLottery = cancelLottery;
window.executeLottery = executeLottery;
window.showLotteryResults = showLotteryResults;
window.closeLotteryAndRefresh = closeLotteryAndRefresh;
console.log("[Lottery] Lottery functions loaded v3");