CognxSafeTrack commited on
Commit
d04688d
路
1 Parent(s): 79712c3

feat(audit): hardened graduation flow and industrialized badge system

Browse files
apps/whatsapp-worker/src/index.ts CHANGED
@@ -53,6 +53,10 @@ const worker = new Worker('whatsapp-queue', async (job: Job) => {
53
  }) as any;
54
  if (!user?.phone) return;
55
 
 
 
 
 
56
  console.log(`[WORKER] Generating feedback for User ${userId}`);
57
  const AI_API_BASE_URL = getApiUrl();
58
  const apiKey = getAdminApiKey();
@@ -144,20 +148,14 @@ const worker = new Worker('whatsapp-queue', async (job: Job) => {
144
  }
145
 
146
  // 馃弲 WORKER WOW: Award Badge 馃弲
147
- const dayBadges: Record<number, string> = {
148
- 1: "CLART脡",
149
- 2: "CONFIANCE",
150
- 3: "CLIENT",
151
- 7: "OFFRE",
152
- 12: "PITCH"
153
- };
154
- const badgeToAward = dayBadges[currentDay];
155
-
156
  const currentProgress = await prisma.userProgress.findUnique({ where: { id: pendingProgressId } });
157
  const currentBadges = ((currentProgress as any)?.badges as string[]) || [];
158
- const updatedBadges = badgeToAward && !currentBadges.includes(badgeToAward)
159
- ? [...currentBadges, badgeToAward]
160
- : currentBadges;
 
 
161
 
162
  await prisma.userProgress.update({
163
  where: { id: pendingProgressId },
@@ -217,18 +215,19 @@ const worker = new Worker('whatsapp-queue', async (job: Job) => {
217
  } as any
218
  });
219
 
220
- if (currentDay >= totalDays) {
221
  await sendTextMessage(user.phone, language === 'WOLOF'
222
  ? "馃帀 Baraka Allahu fik ! Jeex nga module bi. Dokumaan yi dina帽u leen y贸nnee ci kanam !"
223
  : "馃帀 F茅licitations ! Vous avez termin茅 ce module. Vos documents intelligents arrivent bient么t !"
224
  );
225
 
226
- const { Queue } = await import('bullmq');
227
- const conn = process.env.REDIS_URL
228
- ? new Redis(process.env.REDIS_URL, { maxRetriesPerRequest: null })
229
- : new Redis({ host: process.env.REDIS_HOST || 'localhost', port: parseInt(process.env.REDIS_PORT || '6379'), maxRetriesPerRequest: null });
230
- const q = new Queue('whatsapp-queue', { connection: conn as any });
231
  await q.add('send-content', { userId, trackId, dayNumber: currentDay + 1 });
 
 
 
 
 
232
  } else {
233
  await sendTextMessage(user.phone, language === 'WOLOF'
234
  ? "Baax na ! Y贸nnee *SUITE* ngir dem ci kanam."
@@ -494,7 +493,7 @@ const worker = new Worker('whatsapp-queue', async (job: Job) => {
494
  });
495
 
496
  // 馃帗 Graduation Flow: Successive Track Unlocking (v1.0) 馃帗
497
- const trackMatch = trackId.match(/^T(\d)-(FR|WOLOF|WO)$/);
498
  if (trackMatch) {
499
  const currentLevel = parseInt(trackMatch[1]);
500
  const lang = trackMatch[2];
@@ -509,7 +508,7 @@ const worker = new Worker('whatsapp-queue', async (job: Job) => {
509
 
510
  if (!existingNextEnrollment) {
511
  console.log(`[WORKER] Auto-graduating User ${userId}: ${trackId} -> ${nextTrackId}`);
512
- const isWolof = lang.startsWith('WO');
513
 
514
  const congratsMsg = isWolof
515
  ? `馃帀 Baraka Allahu fik ! Mat nga Niveau ${currentLevel}. Maangi lay t脿mbaleel Niveau ${nextLevel} : *${nextTrack.title}*...`
@@ -523,8 +522,8 @@ const worker = new Worker('whatsapp-queue', async (job: Job) => {
523
  data: { userId, trackId: nextTrackId, status: 'ACTIVE', currentDay: 1 }
524
  });
525
  // Trigger Day 1 for next track with 10s delay to let graduation docs/badges arrive
526
- const whatsappQueue = new (await import('bullmq')).Queue('whatsapp-queue', { connection: connection as any });
527
- await whatsappQueue.add('send-content', { userId, trackId: nextTrackId, dayNumber: 1 }, { delay: 10000 });
528
  } else {
529
  const payMsg = isWolof
530
  ? `馃挸 Niveau ${nextLevel} bi dafa laaj pass. Y贸nnee ma "PAYER" ngir t脿mbaleeti.`
 
53
  }) as any;
54
  if (!user?.phone) return;
55
 
56
+ const trackDay = await prisma.trackDay.findFirst({
57
+ where: { trackId, dayNumber: currentDay }
58
+ });
59
+
60
  console.log(`[WORKER] Generating feedback for User ${userId}`);
61
  const AI_API_BASE_URL = getApiUrl();
62
  const apiKey = getAdminApiKey();
 
148
  }
149
 
150
  // 馃弲 WORKER WOW: Award Badge 馃弲
151
+ const trackDayBadges = (trackDay as any)?.badges as string[] || [];
 
 
 
 
 
 
 
 
152
  const currentProgress = await prisma.userProgress.findUnique({ where: { id: pendingProgressId } });
153
  const currentBadges = ((currentProgress as any)?.badges as string[]) || [];
154
+
155
+ let updatedBadges = [...currentBadges];
156
+ for (const b of trackDayBadges) {
157
+ if (!updatedBadges.includes(b)) updatedBadges.push(b);
158
+ }
159
 
160
  await prisma.userProgress.update({
161
  where: { id: pendingProgressId },
 
215
  } as any
216
  });
217
 
218
+ if (currentDay >= totalDays && feedbackData?.isQualified !== false) {
219
  await sendTextMessage(user.phone, language === 'WOLOF'
220
  ? "馃帀 Baraka Allahu fik ! Jeex nga module bi. Dokumaan yi dina帽u leen y贸nnee ci kanam !"
221
  : "馃帀 F茅licitations ! Vous avez termin茅 ce module. Vos documents intelligents arrivent bient么t !"
222
  );
223
 
224
+ const q = new Queue('whatsapp-queue', { connection: connection as any });
 
 
 
 
225
  await q.add('send-content', { userId, trackId, dayNumber: currentDay + 1 });
226
+ } else if (currentDay >= totalDays && feedbackData?.isQualified === false) {
227
+ await sendTextMessage(user.phone, language === 'WOLOF'
228
+ ? "馃毃 Am na lo xamni leerul bu baax. Xoolal missal yi ma la y贸nnee te t脿mbaleet ko nd脿nk."
229
+ : "馃毃 Certains points sont encore 脿 renforcer pour valider ce module. Regarde bien mes conseils et r茅essaie."
230
+ );
231
  } else {
232
  await sendTextMessage(user.phone, language === 'WOLOF'
233
  ? "Baax na ! Y贸nnee *SUITE* ngir dem ci kanam."
 
493
  });
494
 
495
  // 馃帗 Graduation Flow: Successive Track Unlocking (v1.0) 馃帗
496
+ const trackMatch = trackId.match(/^T(\d)-(FR|WO)$/);
497
  if (trackMatch) {
498
  const currentLevel = parseInt(trackMatch[1]);
499
  const lang = trackMatch[2];
 
508
 
509
  if (!existingNextEnrollment) {
510
  console.log(`[WORKER] Auto-graduating User ${userId}: ${trackId} -> ${nextTrackId}`);
511
+ const isWolof = lang === 'WO';
512
 
513
  const congratsMsg = isWolof
514
  ? `馃帀 Baraka Allahu fik ! Mat nga Niveau ${currentLevel}. Maangi lay t脿mbaleel Niveau ${nextLevel} : *${nextTrack.title}*...`
 
522
  data: { userId, trackId: nextTrackId, status: 'ACTIVE', currentDay: 1 }
523
  });
524
  // Trigger Day 1 for next track with 10s delay to let graduation docs/badges arrive
525
+ const q = new Queue('whatsapp-queue', { connection: connection as any });
526
+ await q.add('send-content', { userId, trackId: nextTrackId, dayNumber: 1 }, { delay: 10000 });
527
  } else {
528
  const payMsg = isWolof
529
  ? `馃挸 Niveau ${nextLevel} bi dafa laaj pass. Y贸nnee ma "PAYER" ngir t脿mbaleeti.`
packages/database/prisma/schema.prisma CHANGED
@@ -81,6 +81,7 @@ model TrackDay {
81
  validationKeyword String?
82
  buttonsJson Json?
83
  exerciseCriteria Json?
 
84
  unlockCondition String?
85
  createdAt DateTime @default(now())
86
  updatedAt DateTime @updatedAt
 
81
  validationKeyword String?
82
  buttonsJson Json?
83
  exerciseCriteria Json?
84
+ badges Json? // Array of strings: ["B_MODULE_1_OK"]
85
  unlockCondition String?
86
  createdAt DateTime @default(now())
87
  updatedAt DateTime @updatedAt
packages/database/src/seed.ts CHANGED
@@ -65,6 +65,7 @@ export async function seedDatabase(prisma: PrismaClient): Promise<{ seeded: bool
65
  exercisePrompt: day.exercisePrompt,
66
  exerciseType: day.exerciseType || 'TEXT',
67
  exerciseCriteria: day.exerciseCriteria || null,
 
68
  audioUrl: day.audioUrl || null,
69
  buttonsJson: day.buttonsJson || null,
70
  };
 
65
  exercisePrompt: day.exercisePrompt,
66
  exerciseType: day.exerciseType || 'TEXT',
67
  exerciseCriteria: day.exerciseCriteria || null,
68
+ badges: day.badges || null,
69
  audioUrl: day.audioUrl || null,
70
  buttonsJson: day.buttonsJson || null,
71
  };