Spaces:
Running
Running
Commit ·
ed6f5fc
1
Parent(s): c342b09
Fix achievement and habit notification concurrency, suppress achievement alerts, and localized default name
Browse filesFiles changed (3)
57 unmodified lines58596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515639 unmodified lines19619719819920011311411511611711811912012120120220320420520620720820921021121221321421521621721821922022122222312412512612722422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128213013113213313428328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435530 unmodified lines3863873883893903913923932 unmodified lines3963973983994004014024034044054064074084094102 unmodified lines41341441541641741841957 unmodified lines }};
const isResetDue = (lastResetTime, rule) => { if (!lastResetTime) return false; const lastReset = new Date(lastResetTime); const now = new Date(); if (rule?.type === 'daily') { const [hour, minute] = (rule.time || '00:00').split(':').map(Number); const rDate = new Date(lastReset); rDate.setHours(hour, minute, 0, 0); if (lastReset.getTime() < rDate.getTime() && now.getTime() >= rDate.getTime()) { return true; } const tomorrowDate = new Date(rDate); tomorrowDate.setDate(tomorrowDate.getDate() + 1); if (lastReset.getTime() < tomorrowDate.getTime() && now.getTime() >= tomorrowDate.getTime()) { return true; } } else if (rule?.type === 'weekly') { const dayOfWeek = rule.day !== undefined ? Number(rule.day) : 1; const [hour, minute] = (rule.time || '00:00').split(':').map(Number); const rDate = new Date(lastReset); rDate.setHours(hour, minute, 0, 0); let nextReset = rDate; while (nextReset.getDay() !== dayOfWeek || nextReset.getTime() <= lastReset.getTime()) { nextReset.setDate(nextReset.getDate() + 1); } if (now.getTime() >= nextReset.getTime()) { return true; } } else if (rule?.type === 'hourly') { const hours = Number(rule.hours || 24); const nextReset = new Date(lastReset.getTime() + hours * 60 * 60 * 1000); if (now.getTime() >= nextReset.getTime()) { return true; } } else if (rule?.type === 'minutely') { const minutes = Number(rule.minutes || 5); const nextReset = new Date(lastReset.getTime() + minutes * 60 * 1000); if (now.getTime() >= nextReset.getTime()) { return true; } } return false;};
const resetDownstreamNodesBackground = (startNodeId, nodes, edges) => { const visited = new Set(); const queue = [startNodeId]; while (queue.length > 0) { const currentId = queue.shift(); const outEdges = edges.filter(e => e.source === currentId || e.Source === currentId); outEdges.forEach(edge => { const targetId = edge.target || edge.Target; if (targetId && !visited.has(targetId)) { visited.add(targetId); queue.push(targetId); } }); } return nodes.map(node => { if (visited.has(node.id || node.Id)) { const nodeType = (node.type || node.Type || '').toLowerCase(); if (nodeType === 'sketch' || nodeType === 'habit') { return { ...node, data: { ...node.data, status: 'Pending' } }; } } return node; });};
export const AchievementNotificationProvider = ({ children }) => { const { user } = useAuth(); const { t } = useTranslation(); const [activeNotification, setActiveNotification] = useState(null); const knownUnlockedIds = useRef(new Set()); const isInitialized = useRef(false); const knownHabitStatuses = useRef(new Map()); const isHabitsInitialized = useRef(false); const lastUserId = useRef(null); const isCheckingAchievements = useRef(false); const isCheckingHabits = useRef(false); const API_URL = import.meta.env.VITE_API_URL;
const fetchCurrentAchievements = async () => {39 unmodified lines };
const checkAchievements = async () => { if (!user || isCheckingAchievements.current) return; isCheckingAchievements.current = true; if (!user) return; const achievements = await fetchCurrentAchievements(); if (!achievements || achievements.length === 0) return;
// Separate checking based on whether we have completed the initial load if (!isInitialized.current) { // First load: just populate the set of already unlocked achievements achievements.forEach(ach => { if (ach.unlocked) { try { const achievements = await fetchCurrentAchievements(); if (!achievements || achievements.length === 0) return;
// Separate checking based on whether we have completed the initial load if (!isInitialized.current) { // First load: just populate the set of already unlocked achievements achievements.forEach(ach => { if (ach.unlocked) { knownUnlockedIds.current.add(ach.id); } }); isInitialized.current = true; console.log('[Achievements] Initialized unlocked cache with:', knownUnlockedIds.current.size, 'achievements.'); return; }
// Subsequent loads: check if any achievement is newly unlocked for (const ach of achievements) { if (ach.unlocked && !knownUnlockedIds.current.has(ach.id)) { console.log('[Achievements] Newly Unlocked Achievement Detected (Notification Suppressed):', ach.title); knownUnlockedIds.current.add(ach.id); } }); isInitialized.current = true; console.log('[Achievements] Initialized unlocked cache with:', knownUnlockedIds.current.size, 'achievements.'); return; } } finally { isCheckingAchievements.current = false; } };
const checkHabitCooldowns = async () => { if (!user || isCheckingHabits.current) return; isCheckingHabits.current = true; try { const graphsRes = await axios.get(`${API_URL}/graphs/user/${user.id}`); const graphs = graphsRes.data;
let newlyRechargedHabits = [];
for (const g of graphs) { try { const graphRes = await axios.get(`${API_URL}/graphs/${g.id}/full`); const originalNodes = graphRes.data?.nodes || []; const edges = graphRes.data?.edges || []; let hasChanges = false; let updatedNodes = [...originalNodes];
for (const node of originalNodes) { const nodeType = (node.type || node.Type || '').toLowerCase(); if (nodeType === 'habit') { const nodeId = node.id; const currentStatus = node.data?.status || 'Pending'; if (!knownHabitStatuses.current.has(nodeId)) { knownHabitStatuses.current.set(nodeId, currentStatus); if (currentStatus === 'Done') { const lastResetTime = node.data.lastResetTime || node.data.createdAt || new Date().toISOString(); const rule = node.data.resetRule || { type: 'daily', time: '00:00' }; if (isResetDue(lastResetTime, rule)) { console.log(`[HabitTrackerBackground] Initial check found habit due: "${node.data.label}"`); hasChanges = true; updatedNodes = updatedNodes.map(n => { if (n.id === nodeId) { return { ...n, data: { ...n.data, status: 'Pending', lastResetTime: new Date().toISOString() } }; } return n; }); updatedNodes = resetDownstreamNodesBackground(nodeId, updatedNodes, edges); knownHabitStatuses.current.set(nodeId, 'Pending'); newlyRechargedHabits.push(node.data?.label || t('canvas.habit')); } } continue; }
// Subsequent loads: check if any achievement is newly unlocked for (const ach of achievements) { if (ach.unlocked && !knownUnlockedIds.current.has(ach.id)) { console.log('[Achievements] Newly Unlocked Achievement Detected (Notification Suppressed):', ach.title); knownUnlockedIds.current.add(ach.id); const prevStatus = knownHabitStatuses.current.get(nodeId);
if (currentStatus === 'Done') { const lastResetTime = node.data.lastResetTime || node.data.createdAt || new Date().toISOString(); const rule = node.data.resetRule || { type: 'daily', time: '00:00' }; if (isResetDue(lastResetTime, rule)) { console.log(`[HabitTrackerBackground] Resetting habit: "${node.data.label}"`); hasChanges = true; // 1. Reset target node updatedNodes = updatedNodes.map(n => { if (n.id === nodeId) { return { ...n, data: { ...n.data, status: 'Pending', lastResetTime: new Date().toISOString() } }; } return n; });
// 2. Reset downstream nodes updatedNodes = resetDownstreamNodesBackground(nodeId, updatedNodes, edges);
knownHabitStatuses.current.set(nodeId, 'Pending'); newlyRechargedHabits.push(node.data?.label || t('canvas.habit')); } else { knownHabitStatuses.current.set(nodeId, 'Done'); } } else if (currentStatus === 'Pending') { if (prevStatus === 'Done') { console.log(`[HabitTrackerBackground] Habit transitioned to Pending externally: "${node.data.label}"`); newlyRechargedHabits.push(node.data?.label || t('canvas.habit')); } knownHabitStatuses.current.set(nodeId, 'Pending'); } } }
if (hasChanges) { const payload = { nodes: updatedNodes, edges: edges }; await axios.post(`${API_URL}/graphs/${g.id}/full`, payload); console.log(`[HabitTrackerBackground] Successfully persisted reset status for graph ${g.id}`); } } catch (e) { console.warn(`[HabitsBackground] Error checking/resetting graph ${g.id}:`, e); } }
for (const name of newlyRechargedHabits) { triggerNotification({ id: 'habit-recharge-' + Date.now() + '-' + Math.random(), icon: 'Flame', title: t('habits.recharge_notification_title', 'Habit Recharged! ⚡'), desc: t('habits.recharge_notification_desc', `Habit "${name}" is ready to be performed again!`, { name }), color: 'bg-orange-500/20', headerText: t('habits.recharge_notification_header', 'ЗВИЧКА ГОТОВА') }); } } catch (e) { console.error('[HabitsBackground] Error fetching cooldown info:', e); } finally { isCheckingHabits.current = false; } };
30 unmodified lines if (!user) { isInitialized.current = false; knownUnlockedIds.current.clear(); knownHabitStatuses.current.clear(); isHabitsInitialized.current = false; lastUserId.current = null; return; }2 unmodified lines console.log('[Achievements] User changed. Resetting unlocked achievements cache.'); isInitialized.current = false; knownUnlockedIds.current.clear(); knownHabitStatuses.current.clear(); isHabitsInitialized.current = false; lastUserId.current = user.id; checkAchievements(); checkHabitCooldowns(); } else { // Same user updated (e.g. profile updated). Keep cache, just check for new achievements! checkAchievements(); checkHabitCooldowns(); } }, [user]);
2 unmodified lines if (!user) return; const interval = setInterval(() => { checkAchievements(); checkHabitCooldowns(); }, 12000); return () => clearInterval(interval); }, [user]);202 unmodified lines203204205206206207208209210202 unmodified lines "complete_notification_desc_custom": "Recorded check-in for {{date}}", "complete_notification_desc": "Dynamic streak increased! +50 XP awarded!", "recharge_notification_title": "Habit Recharged! ⚡", "recharge_notification_desc": "Habit \"{{name}}\" is ready to be performed again!" "recharge_notification_desc": "Habit \"{{name}}\" is ready to be performed again!", "recharge_notification_header": "HABIT READY" }, "profile": { "profile": "Profile",202 unmodified lines203204205206206207208209210202 unmodified lines "complete_notification_desc_custom": "Зафіксовано виконання для {{date}}", "complete_notification_desc": "Активну серію збільшено! Нараховано +50 XP!", "recharge_notification_title": "Звичку перезаряджено! ⚡", "recharge_notification_desc": "Звичка \"{{name}}\" знову готова до виконання!" "recharge_notification_desc": "Звичка \"{{name}}\" знову готова до виконання!", "recharge_notification_header": "ЗВИЧКА ГОТОВА" }, "profile": { "profile": "Профіль",src/context/AchievementNotificationContext.jsx+242-18
src/locales/en.json+2-1
src/locales/uk.json+2-1