danylokhodus commited on
Commit
ed6f5fc
·
1 Parent(s): c342b09

Fix achievement and habit notification concurrency, suppress achievement alerts, and localized default name

Browse files
src/context/AchievementNotificationContext.jsx CHANGED
@@ -58,13 +58,99 @@ const playUnlockSound = () => {
58
  }
59
  };
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  export const AchievementNotificationProvider = ({ children }) => {
62
  const { user } = useAuth();
63
  const { t } = useTranslation();
64
  const [activeNotification, setActiveNotification] = useState(null);
65
  const knownUnlockedIds = useRef(new Set());
66
  const isInitialized = useRef(false);
 
 
67
  const lastUserId = useRef(null);
 
 
68
  const API_URL = import.meta.env.VITE_API_URL;
69
 
70
  const fetchCurrentAchievements = async () => {
@@ -110,29 +196,160 @@ export const AchievementNotificationProvider = ({ children }) => {
110
  };
111
 
112
  const checkAchievements = async () => {
113
- if (!user) return;
114
- const achievements = await fetchCurrentAchievements();
115
- if (!achievements || achievements.length === 0) return;
116
-
117
- // Separate checking based on whether we have completed the initial load
118
- if (!isInitialized.current) {
119
- // First load: just populate the set of already unlocked achievements
120
- achievements.forEach(ach => {
121
- if (ach.unlocked) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  knownUnlockedIds.current.add(ach.id);
123
  }
124
- });
125
- isInitialized.current = true;
126
- console.log('[Achievements] Initialized unlocked cache with:', knownUnlockedIds.current.size, 'achievements.');
127
- return;
128
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
 
130
- // Subsequent loads: check if any achievement is newly unlocked
131
- for (const ach of achievements) {
132
- if (ach.unlocked && !knownUnlockedIds.current.has(ach.id)) {
133
- console.log('[Achievements] Newly Unlocked Achievement Detected (Notification Suppressed):', ach.title);
134
- knownUnlockedIds.current.add(ach.id);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  }
137
  };
138
 
@@ -169,6 +386,8 @@ export const AchievementNotificationProvider = ({ children }) => {
169
  if (!user) {
170
  isInitialized.current = false;
171
  knownUnlockedIds.current.clear();
 
 
172
  lastUserId.current = null;
173
  return;
174
  }
@@ -177,11 +396,15 @@ export const AchievementNotificationProvider = ({ children }) => {
177
  console.log('[Achievements] User changed. Resetting unlocked achievements cache.');
178
  isInitialized.current = false;
179
  knownUnlockedIds.current.clear();
 
 
180
  lastUserId.current = user.id;
181
  checkAchievements();
 
182
  } else {
183
  // Same user updated (e.g. profile updated). Keep cache, just check for new achievements!
184
  checkAchievements();
 
185
  }
186
  }, [user]);
187
 
@@ -190,6 +413,7 @@ export const AchievementNotificationProvider = ({ children }) => {
190
  if (!user) return;
191
  const interval = setInterval(() => {
192
  checkAchievements();
 
193
  }, 12000);
194
  return () => clearInterval(interval);
195
  }, [user]);
 
58
  }
59
  };
60
 
61
+ const isResetDue = (lastResetTime, rule) => {
62
+ if (!lastResetTime) return false;
63
+ const lastReset = new Date(lastResetTime);
64
+ const now = new Date();
65
+
66
+ if (rule?.type === 'daily') {
67
+ const [hour, minute] = (rule.time || '00:00').split(':').map(Number);
68
+ const rDate = new Date(lastReset);
69
+ rDate.setHours(hour, minute, 0, 0);
70
+
71
+ if (lastReset.getTime() < rDate.getTime() && now.getTime() >= rDate.getTime()) {
72
+ return true;
73
+ }
74
+
75
+ const tomorrowDate = new Date(rDate);
76
+ tomorrowDate.setDate(tomorrowDate.getDate() + 1);
77
+ if (lastReset.getTime() < tomorrowDate.getTime() && now.getTime() >= tomorrowDate.getTime()) {
78
+ return true;
79
+ }
80
+ } else if (rule?.type === 'weekly') {
81
+ const dayOfWeek = rule.day !== undefined ? Number(rule.day) : 1;
82
+ const [hour, minute] = (rule.time || '00:00').split(':').map(Number);
83
+ const rDate = new Date(lastReset);
84
+ rDate.setHours(hour, minute, 0, 0);
85
+
86
+ let nextReset = rDate;
87
+ while (nextReset.getDay() !== dayOfWeek || nextReset.getTime() <= lastReset.getTime()) {
88
+ nextReset.setDate(nextReset.getDate() + 1);
89
+ }
90
+
91
+ if (now.getTime() >= nextReset.getTime()) {
92
+ return true;
93
+ }
94
+ } else if (rule?.type === 'hourly') {
95
+ const hours = Number(rule.hours || 24);
96
+ const nextReset = new Date(lastReset.getTime() + hours * 60 * 60 * 1000);
97
+ if (now.getTime() >= nextReset.getTime()) {
98
+ return true;
99
+ }
100
+ } else if (rule?.type === 'minutely') {
101
+ const minutes = Number(rule.minutes || 5);
102
+ const nextReset = new Date(lastReset.getTime() + minutes * 60 * 1000);
103
+ if (now.getTime() >= nextReset.getTime()) {
104
+ return true;
105
+ }
106
+ }
107
+ return false;
108
+ };
109
+
110
+ const resetDownstreamNodesBackground = (startNodeId, nodes, edges) => {
111
+ const visited = new Set();
112
+ const queue = [startNodeId];
113
+
114
+ while (queue.length > 0) {
115
+ const currentId = queue.shift();
116
+ const outEdges = edges.filter(e => e.source === currentId || e.Source === currentId);
117
+ outEdges.forEach(edge => {
118
+ const targetId = edge.target || edge.Target;
119
+ if (targetId && !visited.has(targetId)) {
120
+ visited.add(targetId);
121
+ queue.push(targetId);
122
+ }
123
+ });
124
+ }
125
+
126
+ return nodes.map(node => {
127
+ if (visited.has(node.id || node.Id)) {
128
+ const nodeType = (node.type || node.Type || '').toLowerCase();
129
+ if (nodeType === 'sketch' || nodeType === 'habit') {
130
+ return {
131
+ ...node,
132
+ data: {
133
+ ...node.data,
134
+ status: 'Pending'
135
+ }
136
+ };
137
+ }
138
+ }
139
+ return node;
140
+ });
141
+ };
142
+
143
  export const AchievementNotificationProvider = ({ children }) => {
144
  const { user } = useAuth();
145
  const { t } = useTranslation();
146
  const [activeNotification, setActiveNotification] = useState(null);
147
  const knownUnlockedIds = useRef(new Set());
148
  const isInitialized = useRef(false);
149
+ const knownHabitStatuses = useRef(new Map());
150
+ const isHabitsInitialized = useRef(false);
151
  const lastUserId = useRef(null);
152
+ const isCheckingAchievements = useRef(false);
153
+ const isCheckingHabits = useRef(false);
154
  const API_URL = import.meta.env.VITE_API_URL;
155
 
156
  const fetchCurrentAchievements = async () => {
 
196
  };
197
 
198
  const checkAchievements = async () => {
199
+ if (!user || isCheckingAchievements.current) return;
200
+ isCheckingAchievements.current = true;
201
+ try {
202
+ const achievements = await fetchCurrentAchievements();
203
+ if (!achievements || achievements.length === 0) return;
204
+
205
+ // Separate checking based on whether we have completed the initial load
206
+ if (!isInitialized.current) {
207
+ // First load: just populate the set of already unlocked achievements
208
+ achievements.forEach(ach => {
209
+ if (ach.unlocked) {
210
+ knownUnlockedIds.current.add(ach.id);
211
+ }
212
+ });
213
+ isInitialized.current = true;
214
+ console.log('[Achievements] Initialized unlocked cache with:', knownUnlockedIds.current.size, 'achievements.');
215
+ return;
216
+ }
217
+
218
+ // Subsequent loads: check if any achievement is newly unlocked
219
+ for (const ach of achievements) {
220
+ if (ach.unlocked && !knownUnlockedIds.current.has(ach.id)) {
221
+ console.log('[Achievements] Newly Unlocked Achievement Detected (Notification Suppressed):', ach.title);
222
  knownUnlockedIds.current.add(ach.id);
223
  }
224
+ }
225
+ } finally {
226
+ isCheckingAchievements.current = false;
 
227
  }
228
+ };
229
+
230
+ const checkHabitCooldowns = async () => {
231
+ if (!user || isCheckingHabits.current) return;
232
+ isCheckingHabits.current = true;
233
+ try {
234
+ const graphsRes = await axios.get(`${API_URL}/graphs/user/${user.id}`);
235
+ const graphs = graphsRes.data;
236
+
237
+ let newlyRechargedHabits = [];
238
+
239
+ for (const g of graphs) {
240
+ try {
241
+ const graphRes = await axios.get(`${API_URL}/graphs/${g.id}/full`);
242
+ const originalNodes = graphRes.data?.nodes || [];
243
+ const edges = graphRes.data?.edges || [];
244
+
245
+ let hasChanges = false;
246
+ let updatedNodes = [...originalNodes];
247
+
248
+ for (const node of originalNodes) {
249
+ const nodeType = (node.type || node.Type || '').toLowerCase();
250
+ if (nodeType === 'habit') {
251
+ const nodeId = node.id;
252
+ const currentStatus = node.data?.status || 'Pending';
253
+
254
+ if (!knownHabitStatuses.current.has(nodeId)) {
255
+ knownHabitStatuses.current.set(nodeId, currentStatus);
256
+ if (currentStatus === 'Done') {
257
+ const lastResetTime = node.data.lastResetTime || node.data.createdAt || new Date().toISOString();
258
+ const rule = node.data.resetRule || { type: 'daily', time: '00:00' };
259
+ if (isResetDue(lastResetTime, rule)) {
260
+ console.log(`[HabitTrackerBackground] Initial check found habit due: "${node.data.label}"`);
261
+ hasChanges = true;
262
+ updatedNodes = updatedNodes.map(n => {
263
+ if (n.id === nodeId) {
264
+ return {
265
+ ...n,
266
+ data: {
267
+ ...n.data,
268
+ status: 'Pending',
269
+ lastResetTime: new Date().toISOString()
270
+ }
271
+ };
272
+ }
273
+ return n;
274
+ });
275
+ updatedNodes = resetDownstreamNodesBackground(nodeId, updatedNodes, edges);
276
+ knownHabitStatuses.current.set(nodeId, 'Pending');
277
+ newlyRechargedHabits.push(node.data?.label || t('canvas.habit'));
278
+ }
279
+ }
280
+ continue;
281
+ }
282
 
283
+ const prevStatus = knownHabitStatuses.current.get(nodeId);
284
+
285
+ if (currentStatus === 'Done') {
286
+ const lastResetTime = node.data.lastResetTime || node.data.createdAt || new Date().toISOString();
287
+ const rule = node.data.resetRule || { type: 'daily', time: '00:00' };
288
+
289
+ if (isResetDue(lastResetTime, rule)) {
290
+ console.log(`[HabitTrackerBackground] Resetting habit: "${node.data.label}"`);
291
+ hasChanges = true;
292
+
293
+ // 1. Reset target node
294
+ updatedNodes = updatedNodes.map(n => {
295
+ if (n.id === nodeId) {
296
+ return {
297
+ ...n,
298
+ data: {
299
+ ...n.data,
300
+ status: 'Pending',
301
+ lastResetTime: new Date().toISOString()
302
+ }
303
+ };
304
+ }
305
+ return n;
306
+ });
307
+
308
+ // 2. Reset downstream nodes
309
+ updatedNodes = resetDownstreamNodesBackground(nodeId, updatedNodes, edges);
310
+
311
+ knownHabitStatuses.current.set(nodeId, 'Pending');
312
+ newlyRechargedHabits.push(node.data?.label || t('canvas.habit'));
313
+ } else {
314
+ knownHabitStatuses.current.set(nodeId, 'Done');
315
+ }
316
+ } else if (currentStatus === 'Pending') {
317
+ if (prevStatus === 'Done') {
318
+ console.log(`[HabitTrackerBackground] Habit transitioned to Pending externally: "${node.data.label}"`);
319
+ newlyRechargedHabits.push(node.data?.label || t('canvas.habit'));
320
+ }
321
+ knownHabitStatuses.current.set(nodeId, 'Pending');
322
+ }
323
+ }
324
+ }
325
+
326
+ if (hasChanges) {
327
+ const payload = {
328
+ nodes: updatedNodes,
329
+ edges: edges
330
+ };
331
+ await axios.post(`${API_URL}/graphs/${g.id}/full`, payload);
332
+ console.log(`[HabitTrackerBackground] Successfully persisted reset status for graph ${g.id}`);
333
+ }
334
+ } catch (e) {
335
+ console.warn(`[HabitsBackground] Error checking/resetting graph ${g.id}:`, e);
336
+ }
337
  }
338
+
339
+ for (const name of newlyRechargedHabits) {
340
+ triggerNotification({
341
+ id: 'habit-recharge-' + Date.now() + '-' + Math.random(),
342
+ icon: 'Flame',
343
+ title: t('habits.recharge_notification_title', 'Habit Recharged! ⚡'),
344
+ desc: t('habits.recharge_notification_desc', `Habit "${name}" is ready to be performed again!`, { name }),
345
+ color: 'bg-orange-500/20',
346
+ headerText: t('habits.recharge_notification_header', 'ЗВИЧКА ГОТОВА')
347
+ });
348
+ }
349
+ } catch (e) {
350
+ console.error('[HabitsBackground] Error fetching cooldown info:', e);
351
+ } finally {
352
+ isCheckingHabits.current = false;
353
  }
354
  };
355
 
 
386
  if (!user) {
387
  isInitialized.current = false;
388
  knownUnlockedIds.current.clear();
389
+ knownHabitStatuses.current.clear();
390
+ isHabitsInitialized.current = false;
391
  lastUserId.current = null;
392
  return;
393
  }
 
396
  console.log('[Achievements] User changed. Resetting unlocked achievements cache.');
397
  isInitialized.current = false;
398
  knownUnlockedIds.current.clear();
399
+ knownHabitStatuses.current.clear();
400
+ isHabitsInitialized.current = false;
401
  lastUserId.current = user.id;
402
  checkAchievements();
403
+ checkHabitCooldowns();
404
  } else {
405
  // Same user updated (e.g. profile updated). Keep cache, just check for new achievements!
406
  checkAchievements();
407
+ checkHabitCooldowns();
408
  }
409
  }, [user]);
410
 
 
413
  if (!user) return;
414
  const interval = setInterval(() => {
415
  checkAchievements();
416
+ checkHabitCooldowns();
417
  }, 12000);
418
  return () => clearInterval(interval);
419
  }, [user]);
src/locales/en.json CHANGED
@@ -203,7 +203,8 @@
203
  "complete_notification_desc_custom": "Recorded check-in for {{date}}",
204
  "complete_notification_desc": "Dynamic streak increased! +50 XP awarded!",
205
  "recharge_notification_title": "Habit Recharged! ⚡",
206
- "recharge_notification_desc": "Habit \"{{name}}\" is ready to be performed again!"
 
207
  },
208
  "profile": {
209
  "profile": "Profile",
 
203
  "complete_notification_desc_custom": "Recorded check-in for {{date}}",
204
  "complete_notification_desc": "Dynamic streak increased! +50 XP awarded!",
205
  "recharge_notification_title": "Habit Recharged! ⚡",
206
+ "recharge_notification_desc": "Habit \"{{name}}\" is ready to be performed again!",
207
+ "recharge_notification_header": "HABIT READY"
208
  },
209
  "profile": {
210
  "profile": "Profile",
src/locales/uk.json CHANGED
@@ -203,7 +203,8 @@
203
  "complete_notification_desc_custom": "Зафіксовано виконання для {{date}}",
204
  "complete_notification_desc": "Активну серію збільшено! Нараховано +50 XP!",
205
  "recharge_notification_title": "Звичку перезаряджено! ⚡",
206
- "recharge_notification_desc": "Звичка \"{{name}}\" знову готова до виконання!"
 
207
  },
208
  "profile": {
209
  "profile": "Профіль",
 
203
  "complete_notification_desc_custom": "Зафіксовано виконання для {{date}}",
204
  "complete_notification_desc": "Активну серію збільшено! Нараховано +50 XP!",
205
  "recharge_notification_title": "Звичку перезаряджено! ⚡",
206
+ "recharge_notification_desc": "Звичка \"{{name}}\" знову готова до виконання!",
207
+ "recharge_notification_header": "ЗВИЧКА ГОТОВА"
208
  },
209
  "profile": {
210
  "profile": "Профіль",