2 Commits
17 changed files with 68 additions and 408 deletions
+1 -1
View File
@@ -76,7 +76,7 @@ Set `VITE_BACKEND_URL` to the public API base URL **before** `npm run build`.
## 6. Checklist for the other deployer ## 6. Checklist for the other deployer
- [ ] MySQL migrated + seeded (11 course sessions + 9 assignment definitions) - [ ] MySQL migrated + seeded (11 course sessions)
- [ ] Backend `CORS_ORIGIN` matches the real frontend origin - [ ] Backend `CORS_ORIGIN` matches the real frontend origin
- [ ] `OPENAI_API_KEY` set on backend - [ ] `OPENAI_API_KEY` set on backend
- [ ] Frontend built with correct `VITE_BACKEND_URL` - [ ] Frontend built with correct `VITE_BACKEND_URL`
+2 -2
View File
@@ -33,7 +33,7 @@ npm run dev
API default: `http://localhost:3001` API default: `http://localhost:3001`
PWA (CORS): `http://localhost:5173` PWA (CORS): `http://localhost:5173`
`prisma:seed` upserts the 11 course sessions and 9 assignment definitions. Server startup also upserts both as a safety net. `prisma:seed` upserts the 11 course sessions. Server startup also upserts them as a safety net.
## Scripts ## Scripts
@@ -49,7 +49,7 @@ PWA (CORS): `http://localhost:5173`
| `npm run prisma:validate` | Validate schema | | `npm run prisma:validate` | Validate schema |
| `npm run prisma:migrate:dev` | Dev migrations | | `npm run prisma:migrate:dev` | Dev migrations |
| `npm run prisma:migrate:deploy` | Apply migrations (prod) | | `npm run prisma:migrate:deploy` | Apply migrations (prod) |
| `npm run prisma:seed` | Upsert 11 `course_sessions` + 9 assignment definitions | | `npm run prisma:seed` | Upsert 11 `course_sessions` |
## Project Structure ## Project Structure
+1 -2
View File
@@ -27,11 +27,10 @@ export const errorHandler: ErrorHandler = (err, c) => {
if (err instanceof ZodError) { if (err instanceof ZodError) {
log.warn({ issues: err.issues }, 'validation error'); log.warn({ issues: err.issues }, 'validation error');
const firstMessage = err.issues[0]?.message?.trim();
return errorResponse(c, { return errorResponse(c, {
code: ERROR_CODES.VALIDATION_ERROR, code: ERROR_CODES.VALIDATION_ERROR,
message: firstMessage || 'اطلاعات واردشده نامعتبر است', message: 'Validation failed',
status: HTTP_STATUS.UNPROCESSABLE_ENTITY, status: HTTP_STATUS.UNPROCESSABLE_ENTITY,
details: err.issues, details: err.issues,
}); });
@@ -485,7 +485,7 @@ export async function listAssignmentsForSession(userId: bigint, sessionOrder: nu
/** All session assignment slots (definitions 2–10) with optional user progress. */ /** All session assignment slots (definitions 2–10) with optional user progress. */
export async function listAssignmentCatalog(userId: bigint) { export async function listAssignmentCatalog(userId: bigint) {
const seededCount = await seedAssignmentDefinitions(); await seedAssignmentDefinitions();
await backfillAssignmentsForCompletedSessions(userId); await backfillAssignmentsForCompletedSessions(userId);
const completedOrders = await getCompletedSessionOrderSet(userId); const completedOrders = await getCompletedSessionOrderSet(userId);
@@ -494,14 +494,6 @@ export async function listAssignmentCatalog(userId: bigint) {
orderBy: [{ displayOrder: 'asc' }, { sessionOrder: 'asc' }], orderBy: [{ displayOrder: 'asc' }, { sessionOrder: 'asc' }],
}); });
if (definitions.length === 0) {
throw new ValidationError(
seededCount === 0
? 'تعاریف تکالیف در پایگاه‌داده موجود نیست. لطفاً migrate و seed را اجرا کنید.'
: 'بارگذاری فهرست تکالیف ناموفق بود',
);
}
const userRows = await prisma.userAssignment.findMany({ const userRows = await prisma.userAssignment.findMany({
where: { userId }, where: { userId },
include: { include: {
@@ -514,35 +506,8 @@ export async function listAssignmentCatalog(userId: bigint) {
const byDefinitionId = new Map(userRows.map((r) => [r.definitionId.toString(), r])); const byDefinitionId = new Map(userRows.map((r) => [r.definitionId.toString(), r]));
let activatedMissing = 0;
for (const definition of definitions) {
if (
isAssignmentUnlockedByCompletedSessions(definition.sessionOrder, completedOrders) &&
!byDefinitionId.has(definition.id.toString())
) {
activatedMissing += await activateAssignmentsForSession(userId, definition.sessionOrder, prisma, {
ensureSeeded: false,
});
}
}
const rows =
activatedMissing > 0
? await prisma.userAssignment.findMany({
where: { userId },
include: {
definition: true,
reports: { orderBy: { createdAt: 'desc' }, take: 1 },
dailyEntries: { orderBy: { entryDate: 'desc' } },
_count: { select: { reports: true, dailyEntries: true } },
},
})
: userRows;
const byId = new Map(rows.map((r) => [r.definitionId.toString(), r]));
return definitions.map((definition) => { return definitions.map((definition) => {
const ua = byId.get(definition.id.toString()); const ua = byDefinitionId.get(definition.id.toString());
const unlocked = isAssignmentUnlockedByCompletedSessions( const unlocked = isAssignmentUnlockedByCompletedSessions(
definition.sessionOrder, definition.sessionOrder,
completedOrders, completedOrders,
+10 -11
View File
@@ -2,22 +2,21 @@ import { z } from 'zod';
export const NAME_MAX_LENGTH = 100; export const NAME_MAX_LENGTH = 100;
/** Minimum allowed profile age (years). Keep in sync with frontend ProfileCompletionPage. */
export const PROFILE_AGE_MIN = 12;
export const profileNameSchema = z export const profileNameSchema = z
.string({ required_error: 'نام الزامی است' }) .string({ required_error: 'Name is required' })
.trim() .trim()
.min(1, 'نام نمی‌تواند خالی باشد') .min(1, 'Name cannot be empty')
.max(NAME_MAX_LENGTH, `نام حداکثر ${NAME_MAX_LENGTH} کاراکتر باشد`); .max(NAME_MAX_LENGTH, `Name must be at most ${NAME_MAX_LENGTH} characters`);
export const PROFILE_AGE_MIN = 12;
export const profileAgeSchema = z export const profileAgeSchema = z
.number({ .number({
required_error: 'سن الزامی است', required_error: 'Age is required',
invalid_type_error: 'سن باید یک عدد صحیح باشد', invalid_type_error: 'Age must be an integer',
}) })
.int('سن باید یک عدد صحیح باشد') .int('Age must be an integer')
.min(PROFILE_AGE_MIN, `حداقل سن ${PROFILE_AGE_MIN} سال است`); .min(PROFILE_AGE_MIN, `Age must be at least ${PROFILE_AGE_MIN}`);
export const patchProfileSchema = z export const patchProfileSchema = z
.object({ .object({
@@ -25,7 +24,7 @@ export const patchProfileSchema = z
age: profileAgeSchema.optional(), age: profileAgeSchema.optional(),
}) })
.refine((value) => value.name !== undefined || value.age !== undefined, { .refine((value) => value.name !== undefined || value.age !== undefined, {
message: 'نام یا سن لازم است', message: 'At least one of name or age is required',
}); });
export type PatchProfileInput = z.infer<typeof patchProfileSchema>; export type PatchProfileInput = z.infer<typeof patchProfileSchema>;
+1 -1
View File
@@ -49,7 +49,7 @@ export async function updateOwnProfile(
if (!existing.profile) { if (!existing.profile) {
if (input.name === undefined || input.age === undefined) { if (input.name === undefined || input.age === undefined) {
throw new ValidationError('برای تکمیل مشخصات، نام و سن هر دو لازم است'); throw new ValidationError('Name and age are both required to create a profile');
} }
await prisma.userProfile.create({ await prisma.userProfile.create({
-5
View File
@@ -16,13 +16,8 @@ async function startServer() {
await connectPrisma(); await connectPrisma();
logger.info('database connection established'); logger.info('database connection established');
const { seedCourseSessions } = await import('./modules/sessions/sessions.service.js'); const { seedCourseSessions } = await import('./modules/sessions/sessions.service.js');
const { seedAssignmentDefinitions } = await import(
'./modules/assignments/assignments.service.js'
);
await seedCourseSessions(); await seedCourseSessions();
logger.info('course sessions seeded'); logger.info('course sessions seeded');
const assignmentCount = await seedAssignmentDefinitions();
logger.info({ assignmentCount }, 'assignment definitions seeded');
} catch (err) { } catch (err) {
logger.warn({ err }, 'database connection failed at startup; /ready will report unavailable'); logger.warn({ err }, 'database connection failed at startup; /ready will report unavailable');
} }
+2 -2
View File
@@ -1,8 +1,8 @@
export const APP_NAME = 'Novya API'; export const APP_NAME = 'Novya API';
export const APP_DESCRIPTION = 'Novya learning platform backend API'; export const APP_DESCRIPTION = 'Novya learning platform backend API';
/** Minimum wait after completing session N before session N+1 unlocks. Set to 0 so next session unlocks immediately. */ /** Minimum wait after completing session N before session N+1 unlocks (sessions 3–10). */
export const SESSION_UNLOCK_INTERVAL_MS = 0; export const SESSION_UNLOCK_INTERVAL_MS = 24 * 60 * 60 * 1000;
export const DEFAULT_PAGE = 1; export const DEFAULT_PAGE = 1;
export const DEFAULT_PAGE_SIZE = 20; export const DEFAULT_PAGE_SIZE = 20;
+34 -26
View File
@@ -143,7 +143,14 @@ describe('assignments API', () => {
}); });
assert.equal((list.body.data?.assignments as unknown[]).length, 1); assert.equal((list.body.data?.assignments as unknown[]).length, 1);
// Session 3 is unlocked immediately (no 24h waiting period) // Backdate session 2 completion so session 3 unlocks (24h gate for order >= 3)
await prisma.sessionProgress.update({
where: {
userId_sessionOrder: { userId: owner.user.id, sessionOrder: 2 },
},
data: { completedAt: new Date(Date.now() - 25 * 60 * 60 * 1000) },
});
// Incomplete homework must NOT block starting session 3 // Incomplete homework must NOT block starting session 3
const chat3 = await requestJson(app, '/chat/sessions', { const chat3 = await requestJson(app, '/chat/sessions', {
method: 'POST', method: 'POST',
@@ -356,8 +363,12 @@ describe('assignments API', () => {
await openChatAndComplete(token, 1); await openChatAndComplete(token, 1);
await openChatAndComplete(token, 2); await openChatAndComplete(token, 2);
// Unlock sessions 3–10 sequentially without cooldown delays // Unlock sessions 3–10 by backdating previous completions as we go
for (let order = 3; order <= 10; order += 1) { for (let order = 3; order <= 10; order += 1) {
await prisma.sessionProgress.updateMany({
where: { userId: user.id, sessionOrder: order - 1 },
data: { completedAt: new Date(Date.now() - 25 * 60 * 60 * 1000) },
});
await openChatAndComplete(token, order); await openChatAndComplete(token, order);
} }
@@ -461,13 +472,13 @@ describe('assignments API', () => {
await openChatAndComplete(token, 2); await openChatAndComplete(token, 2);
// With waiting period removed, no cooldown is set // completeSession helper only asserts 200 — fetch progress for cooldown fields
const progress = await requestJson(app, '/sessions/progress', { const progress = await requestJson(app, '/sessions/progress', {
headers: authHeader(token), headers: authHeader(token),
}); });
assert.equal(progress.status, 200); assert.equal(progress.status, 200);
assert.equal(progress.body.data?.waitingForSessionOrder, null); assert.ok(progress.body.data?.waitingForSessionOrder === 3);
assert.equal(progress.body.data?.nextSessionUnlocksAt, null); assert.ok(progress.body.data?.nextSessionUnlocksAt);
// Re-complete to read unlockedAssignments payload from complete endpoint // Re-complete to read unlockedAssignments payload from complete endpoint
const redo = await requestJson(app, '/sessions/2/complete', { const redo = await requestJson(app, '/sessions/2/complete', {
@@ -497,7 +508,7 @@ describe('assignments API', () => {
assert.equal(joy.lockReason, null); assert.equal(joy.lockReason, null);
assert.ok(joy.userAssignment?.id); assert.ok(joy.userAssignment?.id);
// Session 3 is unlocked immediately (no 24h wait) // Session 3 still locked by cooldown — must NOT block assignment 1
const sessions = await requestJson(app, '/sessions', { const sessions = await requestJson(app, '/sessions', {
headers: authHeader(token), headers: authHeader(token),
}); });
@@ -507,19 +518,18 @@ describe('assignments API', () => {
unlocksAt?: string | null; unlocksAt?: string | null;
}>; }>;
const s3 = sessionList.find((s) => s.order === 3)!; const s3 = sessionList.find((s) => s.order === 3)!;
assert.equal(s3.unlocked, true); assert.equal(s3.unlocked, false);
assert.equal(s3.unlocksAt, null); assert.ok(s3.unlocksAt);
// Prerequisites still hold: Session 4 is NOT unlocked yet // Opening cooldown (simulate later unlock of session 3) must not change assignment-1 state
const s4 = sessionList.find((s) => s.order === 4)!; await prisma.sessionProgress.update({
assert.equal(s4.unlocked, false); where: { userId_sessionOrder: { userId: user.id, sessionOrder: 2 } },
data: { completedAt: new Date(Date.now() - 25 * 60 * 60 * 1000) },
// Complete session 3 immediately without any time delay });
await openChatAndComplete(token, 3); const sessionsAfter = await requestJson(app, '/sessions', {
const sessionsAfter3 = await requestJson(app, '/sessions', {
headers: authHeader(token), headers: authHeader(token),
}); });
const s3After = (sessionsAfter3.body.data as typeof sessionList).find((s) => s.order === 3)!; const s3After = (sessionsAfter.body.data as typeof sessionList).find((s) => s.order === 3)!;
assert.equal(s3After.unlocked, true); assert.equal(s3After.unlocked, true);
catalog = await requestJson(app, '/assignments/catalog', { catalog = await requestJson(app, '/assignments/catalog', {
@@ -529,18 +539,18 @@ describe('assignments API', () => {
const joyAfter = items.find((i) => i.definition.key === 'joy-activities')!; const joyAfter = items.find((i) => i.definition.key === 'joy-activities')!;
assert.equal(joyAfter.unlocked, true); assert.equal(joyAfter.unlocked, true);
assert.equal(joyAfter.userAssignment?.id, joy.userAssignment?.id); assert.equal(joyAfter.userAssignment?.id, joy.userAssignment?.id);
// Assignment 2 (meaning) is now unlocked immediately on session 3 complete
const meaningAfter3 = items.find((i) => i.definition.key === 'meaning-purpose')!;
assert.equal(meaningAfter3.unlocked, true);
assert.equal( assert.equal(
items.filter((i) => i.unlocked).length, items.filter((i) => i.unlocked).length,
2, 1,
'unlocking session 3 must not unlock later assignments (session 4+)', 'unlocking session 3 must not unlock later assignments',
); );
// Mid assignment: تکلیف پنجم (displayOrder 5 / sessionOrder 6) after completing session 6 // Mid assignment: تکلیف پنجم (displayOrder 5 / sessionOrder 6) after completing session 6
for (let order = 4; order <= 6; order += 1) { for (let order = 3; order <= 6; order += 1) {
await prisma.sessionProgress.updateMany({
where: { userId: user.id, sessionOrder: order - 1 },
data: { completedAt: new Date(Date.now() - 25 * 60 * 60 * 1000) },
});
await openChatAndComplete(token, order); await openChatAndComplete(token, order);
} }
@@ -558,9 +568,7 @@ describe('assignments API', () => {
headers: authHeader(token), headers: authHeader(token),
}); });
const s7 = (sessionsMid.body.data as typeof sessionList).find((s) => s.order === 7)!; const s7 = (sessionsMid.body.data as typeof sessionList).find((s) => s.order === 7)!;
assert.equal(s7.unlocked, true, 'session 7 unlocks immediately after session 6 completion'); assert.equal(s7.unlocked, false, 'session 7 may still be on cooldown');
const s8 = (sessionsMid.body.data as typeof sessionList).find((s) => s.order === 8)!;
assert.equal(s8.unlocked, false, 'session 8 remains locked until session 7 is completed');
assert.equal( assert.equal(
items.find((i) => i.definition.sessionOrder === 7)?.unlocked, items.find((i) => i.definition.sessionOrder === 7)?.unlocked,
false, false,
-1
View File
@@ -109,7 +109,6 @@ describe('profile API', () => {
body: JSON.stringify({ name: 'Sara', age: 11 }), body: JSON.stringify({ name: 'Sara', age: 11 }),
}); });
assert.equal(underage.status, 422); assert.equal(underage.status, 422);
assert.match(String(underage.body.error?.message ?? ''), /حداقل سن 12/);
const teenOk = await requestJson(app, '/users/me/profile', { const teenOk = await requestJson(app, '/users/me/profile', {
method: 'PATCH', method: 'PATCH',
-263
View File
@@ -1,263 +0,0 @@
import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test';
import { prisma } from '../src/lib/prisma.js';
import { PCQ_QUESTION_IDS } from '../src/modules/assessments/scoring/index.js';
import { exampleCompletionSignal } from '../src/modules/ai/sessionCompletion.js';
import { buildAiCoachSessionContext } from '../src/modules/ai/sessionContext.js';
import { getSessionByOrder, PROGRAM_SESSION_COUNT } from '../src/modules/sessions/catalog.js';
import { seedCourseSessions } from '../src/modules/sessions/seedCatalog.js';
import { seedAssignmentDefinitions } from '../src/modules/assignments/assignments.service.js';
import {
getNextLockedSessionUnlockTime,
getPreviousSessionUnlockTime,
isSessionUnlockedForProgress,
sessionUsesUnlockInterval,
} from '../src/modules/sessions/unlock.js';
import {
authHeader,
createTestApp,
isDatabaseAvailable,
requestJson,
} from './helpers.js';
const app = createTestApp();
const createdUserIds: bigint[] = [];
function pcqAnswers(value: number) {
return PCQ_QUESTION_IDS.map((questionId) => ({
questionId,
selectedValue: String(value),
}));
}
async function registerUser(suffix: string) {
const email = `session-unlock-${suffix}-${Date.now()}@example.com`;
const { status, body } = await requestJson(app, '/auth/register', {
method: 'POST',
body: JSON.stringify({ email, password: 'password12' }),
});
assert.equal(status, 201);
const token = body.data?.sessionToken as string;
const externalId = (body.data?.user as { id: string }).id;
const user = await prisma.user.findUnique({ where: { externalId } });
assert.ok(user);
createdUserIds.push(user.id);
return { token, user };
}
import { ChatRole } from '@prisma/client';
async function completePreTest(token: string) {
const res = await requestJson(app, '/assessments/attempts', {
method: 'POST',
headers: authHeader(token),
body: JSON.stringify({ phase: 'pre', answers: pcqAnswers(4) }),
});
assert.equal(res.status, 201);
}
async function openChatAndComplete(token: string, order: number) {
const chat = await requestJson(app, '/chat/sessions', {
method: 'POST',
headers: authHeader(token),
body: JSON.stringify({ sessionOrder: order }),
});
assert.equal(chat.status, 201);
const chatId = (chat.body.data as { id: string }).id;
await prisma.chatMessage.createMany({
data: [
{ chatSessionId: BigInt(chatId), role: ChatRole.user, content: `سلام جلسه ${order}` },
{ chatSessionId: BigInt(chatId), role: ChatRole.user, content: `ادامه جلسه ${order}` },
],
});
const session = getSessionByOrder(order)!;
const complete = await requestJson(app, `/sessions/${order}/complete`, {
method: 'POST',
headers: authHeader(token),
body: JSON.stringify({
...exampleCompletionSignal(buildAiCoachSessionContext(session)),
chatSessionId: chatId,
}),
});
assert.equal(complete.status, 200);
return { chatId };
}
describe('session unlock logic and waiting period removal', () => {
let dbAvailable = false;
before(async () => {
dbAvailable = await isDatabaseAvailable();
if (dbAvailable) {
await seedCourseSessions();
await seedAssignmentDefinitions();
}
});
after(async () => {
if (dbAvailable && createdUserIds.length > 0) {
await prisma.user.deleteMany({ where: { id: { in: createdUserIds } } });
}
});
it('unit: unlock interval functions confirm 0 waiting period', () => {
// 1. sessionUsesUnlockInterval returns false for all session orders
for (let order = 1; order <= PROGRAM_SESSION_COUNT; order++) {
assert.equal(
sessionUsesUnlockInterval(order),
false,
`session ${order} should not use unlock interval`,
);
}
const completionTimes = new Map<number, Date>();
completionTimes.set(1, new Date());
completionTimes.set(2, new Date());
// 2. getPreviousSessionUnlockTime returns null (no waiting delay)
assert.equal(getPreviousSessionUnlockTime(3, completionTimes), null);
// 3. isSessionUnlockedForProgress unlocks session 3 immediately when 1 and 2 are complete
assert.equal(
isSessionUnlockedForProgress(3, [1, 2], true, false, completionTimes),
true,
'session 3 should unlock immediately after sessions 1 and 2 are complete',
);
// 4. Prerequisites still block: session 4 is NOT unlocked when only 1 and 2 are complete
assert.equal(
isSessionUnlockedForProgress(4, [1, 2], true, false, completionTimes),
false,
'session 4 must remain locked when session 3 is not complete',
);
// 5. canOpenTraining prerequisite still blocks all sessions
assert.equal(
isSessionUnlockedForProgress(1, [], false, false, completionTimes),
false,
'session 1 must be locked if canOpenTraining is false',
);
// 6. getNextLockedSessionUnlockTime returns null when next eligible session has no cooldown
assert.equal(
getNextLockedSessionUnlockTime([1, 2], completionTimes),
null,
'next eligible session should have no locked cooldown delay',
);
});
it('integration: completes sessions sequentially without delays; preserves assignments and prerequisites', async (t) => {
if (!dbAvailable) {
t.skip('MySQL is not running');
return;
}
const participantA = await registerUser('part-a');
const participantB = await registerUser('part-b');
// Participant A takes pre-test
await completePreTest(participantA.token);
// Participant B has NOT taken pre-test — training is locked
const bSessions = await requestJson(app, '/sessions', {
headers: authHeader(participantB.token),
});
const bList = bSessions.body.data as Array<{ order: number; unlocked: boolean }>;
assert.ok(bList.every((s) => !s.unlocked), 'all sessions locked for participant B without pre-test');
// Participant A: session 1 is unlocked initially, session 2-11 are locked
let aSessions = await requestJson(app, '/sessions', {
headers: authHeader(participantA.token),
});
let aList = aSessions.body.data as Array<{ order: number; unlocked: boolean; completed: boolean; unlocksAt: string | null }>;
assert.equal(aList[0]?.unlocked, true);
assert.equal(aList[1]?.unlocked, false);
assert.equal(aList[2]?.unlocked, false);
// Complete session 1
await openChatAndComplete(participantA.token, 1);
// Session 2 is now unlocked immediately
aSessions = await requestJson(app, '/sessions', {
headers: authHeader(participantA.token),
});
aList = aSessions.body.data as typeof aList;
assert.equal(aList[0]?.completed, true);
assert.equal(aList[1]?.unlocked, true);
assert.equal(aList[2]?.unlocked, false);
// Complete session 2
await openChatAndComplete(participantA.token, 2);
// Progress endpoint shows NO cooldown waiting
const aProgress = await requestJson(app, '/sessions/progress', {
headers: authHeader(participantA.token),
});
assert.equal(aProgress.status, 200);
assert.equal(aProgress.body.data?.waitingForSessionOrder, null);
assert.equal(aProgress.body.data?.nextSessionUnlocksAt, null);
// Session 3 is unlocked IMMEDIATELY (no 24h waiting period!)
aSessions = await requestJson(app, '/sessions', {
headers: authHeader(participantA.token),
});
aList = aSessions.body.data as typeof aList;
const s3 = aList.find((s) => s.order === 3)!;
assert.equal(s3.unlocked, true, 'session 3 must be unlocked immediately');
assert.equal(s3.unlocksAt, null, 'session 3 unlocksAt must be null');
// Completing session 2 does NOT unlock session 4 or the rest of the program
const s4 = aList.find((s) => s.order === 4)!;
assert.equal(s4.unlocked, false, 'session 4 must remain locked');
const s11 = aList.find((s) => s.order === 11)!;
assert.equal(s11.unlocked, false, 'session 11 must remain locked');
// Associated assignment for session 2 (joy-activities) is unlocked immediately
const aCatalog = await requestJson(app, '/assignments/catalog', {
headers: authHeader(participantA.token),
});
const catalogItems = aCatalog.body.data?.catalog as Array<{
unlocked: boolean;
definition: { key: string; sessionOrder: number };
}>;
const joyAssignment = catalogItems.find((i) => i.definition.key === 'joy-activities')!;
assert.equal(joyAssignment.unlocked, true, 'joy assignment unlocked after session 2 complete');
// Assignment for session 3 (meaning-purpose) is STILL locked because session 3 is not yet completed
const meaningAssignment = catalogItems.find((i) => i.definition.key === 'meaning-purpose')!;
assert.equal(meaningAssignment.unlocked, false, 'meaning assignment remains locked until session 3 is completed');
// Participant B cannot access participant A's assignments
const bAssignments = await requestJson(app, '/assignments?filter=all', {
headers: authHeader(participantB.token),
});
assert.equal(bAssignments.status, 200);
assert.equal((bAssignments.body.data?.assignments as unknown[]).length, 0, 'participant B sees no assignments');
// Participant A immediately accesses and completes session 3 without any delay
await openChatAndComplete(participantA.token, 3);
// Associated assignment for session 3 is now unlocked immediately
const aCatalogAfter3 = await requestJson(app, '/assignments/catalog', {
headers: authHeader(participantA.token),
});
const itemsAfter3 = aCatalogAfter3.body.data?.catalog as typeof catalogItems;
const meaningAfter3 = itemsAfter3.find((i) => i.definition.key === 'meaning-purpose')!;
assert.equal(meaningAfter3.unlocked, true, 'meaning assignment unlocks immediately after session 3 completion');
// Session 4 is now unlocked immediately
aSessions = await requestJson(app, '/sessions', {
headers: authHeader(participantA.token),
});
aList = aSessions.body.data as typeof aList;
const s4After3 = aList.find((s) => s.order === 4)!;
assert.equal(s4After3.unlocked, true, 'session 4 unlocks immediately after session 3 completion');
// Completed sessions 1, 2, 3 remain completed
assert.equal(aList.find((s) => s.order === 1)!.completed, true);
assert.equal(aList.find((s) => s.order === 2)!.completed, true);
assert.equal(aList.find((s) => s.order === 3)!.completed, true);
});
});
-13
View File
@@ -91,25 +91,12 @@ export function getLoginErrorMessage(error: unknown): string {
function localizeValidationMessage(message: string | undefined): string | null { function localizeValidationMessage(message: string | undefined): string | null {
if (!message) return null; if (!message) return null;
const lower = message.toLowerCase(); const lower = message.toLowerCase();
if (/حداقل سن|سن باید|سن الزامی/.test(message)) {
return message;
}
if (/age must be at least\s*(\d+)/i.test(message)) {
const min = message.match(/age must be at least\s*(\d+)/i)?.[1] ?? '12';
return `حداقل سن ${min} سال است`;
}
if (/age must be an integer|age is required/i.test(message)) {
return 'سن باید یک عدد صحیح باشد';
}
if (lower.includes('email')) { if (lower.includes('email')) {
return 'فرمت ایمیل نامعتبر است.'; return 'فرمت ایمیل نامعتبر است.';
} }
if (lower.includes('password')) { if (lower.includes('password')) {
return 'رمز عبور نامعتبر است.'; return 'رمز عبور نامعتبر است.';
} }
if (/^validation failed$/i.test(message.trim())) {
return 'اطلاعات واردشده نامعتبر است.';
}
return localizeKnownEnglishMessage(message); return localizeKnownEnglishMessage(message);
} }
+2 -2
View File
@@ -1,7 +1,7 @@
import { PROGRAM_SESSION_COUNT } from '@/data/program/sessions'; import { PROGRAM_SESSION_COUNT } from '@/data/program/sessions';
/** Minimum wait after completing session N before session N+1 unlocks. Set to 0 so next session unlocks immediately. */ /** Minimum wait after completing session N before session N+1 unlocks (sessions 3–10). */
export const SESSION_UNLOCK_INTERVAL_MS = 0; export const SESSION_UNLOCK_INTERVAL_MS = 24 * 60 * 60 * 1000;
export type SessionCompletionTimes = Record<number, string>; export type SessionCompletionTimes = Record<number, string>;
+1 -16
View File
@@ -6,13 +6,12 @@ import { PROGRAM_SESSION_COUNT } from '@/data/program/sessions';
import { getProgramProgress } from '@/services/programService'; import { getProgramProgress } from '@/services/programService';
import { Progress } from '@/components/ui/progress'; import { Progress } from '@/components/ui/progress';
import { Navigate, useNavigate } from 'react-router-dom'; import { Navigate, useNavigate } from 'react-router-dom';
import { Check, ChevronLeft, Lock, NotebookPen } from 'lucide-react'; import { Check, ChevronLeft, Lock } from 'lucide-react';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { StaggeredList, StaggerItem, AnimationWrapper } from '@/components/motion'; import { StaggeredList, StaggerItem, AnimationWrapper } from '@/components/motion';
import { motion } from 'framer-motion'; import { motion } from 'framer-motion';
import { fastTransition } from '@/lib/motion'; import { fastTransition } from '@/lib/motion';
import { CourseStatusSkeleton } from '@/components/skeletons'; import { CourseStatusSkeleton } from '@/components/skeletons';
import { Button } from '@/components/ui/button';
type StepState = 'open' | 'locked' | 'done'; type StepState = 'open' | 'locked' | 'done';
@@ -86,20 +85,6 @@ export default function AccountPage() {
</span> </span>
</p> </p>
)} )}
{!isGuest ? (
<Button
type="button"
variant="outline"
className="mt-3 w-full justify-between"
onClick={() => navigate('/assignments')}
>
<span className="inline-flex items-center gap-2">
<NotebookPen className="h-4 w-4 text-sky-600 dark:text-sky-400" />
تکالیف من
</span>
<ChevronLeft className="h-4 w-4 text-muted-foreground" />
</Button>
) : null}
</AnimationWrapper> </AnimationWrapper>
<StaggeredList itemCount={3} className="space-y-3" role="region" aria-label="وضعیت دوره"> <StaggeredList itemCount={3} className="space-y-3" role="region" aria-label="وضعیت دوره">
+8 -15
View File
@@ -8,7 +8,6 @@ import {
fetchAssignmentCatalog, fetchAssignmentCatalog,
type AssignmentCatalogItem, type AssignmentCatalogItem,
} from '@/services/assignmentService'; } from '@/services/assignmentService';
import { getBackendErrorMessage } from '@/lib/backendError';
import { AnimationWrapper, StaggerItem, StaggeredList } from '@/components/motion'; import { AnimationWrapper, StaggerItem, StaggeredList } from '@/components/motion';
import { PageSkeleton } from '@/components/skeletons'; import { PageSkeleton } from '@/components/skeletons';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
@@ -41,7 +40,7 @@ export default function AssignmentsPage() {
const rows = await fetchAssignmentCatalog(); const rows = await fetchAssignmentCatalog();
setItems(rows); setItems(rows);
} catch (err) { } catch (err) {
setError(getBackendErrorMessage(err, 'بارگذاری تکالیف ناموفق بود')); setError(err instanceof Error ? err.message : 'بارگذاری تکالیف ناموفق بود');
setItems([]); setItems([]);
} finally { } finally {
setLoading(false); setLoading(false);
@@ -110,20 +109,14 @@ export default function AssignmentsPage() {
</Button> </Button>
</div> </div>
) : items.length === 0 ? ( ) : items.length === 0 ? (
<div className="rounded-xl border border-dashed border-slate-300 p-6 text-center text-sm text-muted-foreground dark:border-slate-600"> <p className="rounded-xl border border-dashed border-slate-300 p-6 text-center text-sm text-muted-foreground dark:border-slate-600">
<p>فهرست تکالیف هنوز از سرور بارگذاری نشده است.</p> هنوز تکلیفی تعریف نشده است.
<p className="mt-2 text-xs"> </p>
پس از تکمیل هر یک از جلسات ۲ تا ۱۰، تکلیف همان جلسه اینجا باز می‌شود.
</p>
<Button variant="link" className="mt-2 px-0" onClick={() => void load()}>
تلاش مجدد
</Button>
</div>
) : ( ) : (
<StaggeredList itemCount={items.length} className="space-y-3"> <StaggeredList itemCount={items.length} className="space-y-3">
{items.map((item) => { {items.map((item) => {
const ua = item.userAssignment; const ua = item.userAssignment;
const isOpen = item.unlocked && Boolean(ua); const unlocked = item.unlocked && ua;
const completed = ua?.status === 'COMPLETED'; const completed = ua?.status === 'COMPLETED';
const content = ( const content = (
@@ -137,7 +130,7 @@ export default function AssignmentsPage() {
{item.definition.title} {item.definition.title}
</h2> </h2>
</div> </div>
{isOpen ? ( {unlocked ? (
<ChevronLeft className="mt-1 h-4 w-4 shrink-0 text-muted-foreground" /> <ChevronLeft className="mt-1 h-4 w-4 shrink-0 text-muted-foreground" />
) : ( ) : (
<Lock className="mt-1 h-4 w-4 shrink-0 text-muted-foreground" /> <Lock className="mt-1 h-4 w-4 shrink-0 text-muted-foreground" />
@@ -150,7 +143,7 @@ export default function AssignmentsPage() {
<span className="rounded-md bg-slate-100 px-2 py-0.5 dark:bg-slate-700"> <span className="rounded-md bg-slate-100 px-2 py-0.5 dark:bg-slate-700">
{assignmentTypeLabel(item.definition.assignmentType)} {assignmentTypeLabel(item.definition.assignmentType)}
</span> </span>
{isOpen && ua ? ( {unlocked && ua ? (
<> <>
<span <span
className={cn( className={cn(
@@ -176,7 +169,7 @@ export default function AssignmentsPage() {
return ( return (
<StaggerItem key={item.definition.id}> <StaggerItem key={item.definition.id}>
{isOpen && ua ? ( {unlocked ? (
<Link <Link
to={`/assignments/${ua.id}`} to={`/assignments/${ua.id}`}
className="block rounded-xl border border-slate-200/80 bg-white p-4 shadow-sm transition hover:border-sky-300 dark:border-slate-700 dark:bg-slate-800 dark:hover:border-sky-600" className="block rounded-xl border border-slate-200/80 bg-white p-4 shadow-sm transition hover:border-sky-300 dark:border-slate-700 dark:bg-slate-800 dark:hover:border-sky-600"
+2 -10
View File
@@ -144,7 +144,7 @@ export default function ProfileCompletionPage() {
id="profile-age" id="profile-age"
type="text" type="text"
inputMode="numeric" inputMode="numeric"
placeholder={`حداقل ${PROFILE_AGE_MIN} سال`} placeholder="سن"
value={age} value={age}
onChange={(event) => { onChange={(event) => {
setAge(event.target.value); setAge(event.target.value);
@@ -152,17 +152,9 @@ export default function ProfileCompletionPage() {
}} }}
disabled={isLoading} disabled={isLoading}
autoComplete="off" autoComplete="off"
min={PROFILE_AGE_MIN}
aria-invalid={Boolean(fieldError.age)} aria-invalid={Boolean(fieldError.age)}
aria-describedby="profile-age-hint"
/> />
{fieldError.age ? ( {fieldError.age ? <p className="text-xs text-red-400">{fieldError.age}</p> : null}
<p className="text-xs text-red-400">{fieldError.age}</p>
) : (
<p id="profile-age-hint" className="text-xs text-muted-foreground">
حداقل سن ورود {PROFILE_AGE_MIN} سال است
</p>
)}
</div> </div>
<Button type="submit" variant="neon" className="w-full" disabled={isLoading}> <Button type="submit" variant="neon" className="w-full" disabled={isLoading}>
+2 -1
View File
@@ -334,7 +334,8 @@ export async function submitHomeworkReport(
/** /**
* Check if a specific session is unlocked for a user. * Check if a specific session is unlocked for a user.
* Session N unlocks immediately when previous sessions 1…N-1 are complete. * Session N unlocks when sessions 1…N-1 are complete and at least 1 hour has passed
* since session N-1 was completed.
*/ */
export function isSessionUnlocked(userId: string, sessionOrder: number): boolean { export function isSessionUnlocked(userId: string, sessionOrder: number): boolean {
const cachedSessions = getSessions(userId); const cachedSessions = getSessions(userId);