Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 10 additions & 88 deletions src/services/api/SupabaseApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -402,11 +402,6 @@ type CampaignClassGradeRow = Pick<TableTypes<'class'>, 'id' | 'grade_id'> & {
grade?: CampaignGradeRow | CampaignGradeRow[] | null;
};

type CampaignClassUserRow = Pick<
TableTypes<'class_user'>,
'class_id' | 'user_id'
>;

type CampaignSchoolCourseGradeRow = {
course?:
| {
Expand Down Expand Up @@ -10384,93 +10379,20 @@ export class SupabaseApi implements ServiceApi {
return { totalStudents: 0, grades: [] };
}

const { data: classRows, error: classError } = await this.supabase
.from('class')
.select('id, grade_id, grade:grade_id(id, name, sort_index)')
.in('school_id', schoolIds)
.in('grade_id', gradeIds)
.eq('is_deleted', false);
const { data, error } = await this.supabase.rpc(
'get_campaign_audience_summary',

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add the missing campaign audience summary RPC

This new code makes every campaign audience summary depend on the get_campaign_audience_summary RPC, but this commit only adds the TypeScript declaration; a repo-wide rg "get_campaign_audience_summary" finds no SQL/migration/function definition outside this call and the type entry. In any environment that has not had this function created manually, Supabase will return an RPC-not-found error, this method falls back to { totalStudents: 0, grades: [] }, and the campaign setup UI treats the selected audience as having 0 students and blocks progression. Please include the DB function/migration or keep the client-side path until the RPC is deployed.

Useful? React with 👍 / 👎.

{
p_school_ids: schoolIds,
p_grade_ids: gradeIds,
},
);

if (classError) {
logger.error('Error fetching campaign summary classes:', classError);
if (error) {
logger.error('Error fetching campaign audience summary:', error);
return { totalStudents: 0, grades: [] };
}

const classGradeMap = new Map<
string,
{ gradeId: string; gradeName: string; sort: number }
>();

((classRows ?? []) as CampaignClassGradeRow[]).forEach((row) => {
const grade = firstOrSelf(row.grade);
if (!row.id || !row.grade_id || !grade?.name) return;
classGradeMap.set(String(row.id), {
gradeId: String(row.grade_id),
gradeName: String(grade.name),
sort: Number(grade.sort_index ?? 9999),
});
});

const classIds = Array.from(classGradeMap.keys());
if (classIds.length === 0) return { totalStudents: 0, grades: [] };

const classUserRows: CampaignClassUserRow[] = [];
for (const classIdBatch of chunkArray(classIds, 500)) {
const { data, error: classUserError } = await this.supabase
.from('class_user')
.select('class_id, user_id')
.in('class_id', classIdBatch)
.eq('role', RoleType.STUDENT)
.eq('is_deleted', false);

if (classUserError) {
logger.error(
'Error fetching campaign summary class users:',
classUserError,
);
return { totalStudents: 0, grades: [] };
}

classUserRows.push(...((data ?? []) as CampaignClassUserRow[]));
}

const studentsByGrade = new Map<string, Set<string>>();
const gradeMeta = new Map<string, { gradeName: string; sort: number }>();

(classUserRows ?? []).forEach((row) => {
const classMeta = classGradeMap.get(String(row.class_id));
if (!classMeta || !row.user_id) return;
if (!studentsByGrade.has(classMeta.gradeId)) {
studentsByGrade.set(classMeta.gradeId, new Set<string>());
gradeMeta.set(classMeta.gradeId, {
gradeName: classMeta.gradeName,
sort: classMeta.sort,
});
}
studentsByGrade.get(classMeta.gradeId)?.add(String(row.user_id));
});

const grades = Array.from(studentsByGrade.entries())
.map(([gradeId, students]) => ({
gradeId,
gradeName: gradeMeta.get(gradeId)?.gradeName ?? 'Grade',
sort: gradeMeta.get(gradeId)?.sort ?? 9999,
studentCount: students.size,
}))
.sort((a, b) => a.sort - b.sort || a.gradeName.localeCompare(b.gradeName))
.map(({ gradeId, gradeName, studentCount }) => ({
gradeId,
gradeName,
studentCount,
}));

return {
totalStudents: grades.reduce(
(total, grade) => total + grade.studentCount,
0,
),
grades,
};
return data ?? { totalStudents: 0, grades: [] };
}

async createCampaignAudienceGroup(
Expand Down
14 changes: 14 additions & 0 deletions src/services/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6276,6 +6276,20 @@ export type Database = {
Args: { p_class_id: string; p_days: number };
Returns: number;
};
get_campaign_audience_summary: {
Args: {
p_grade_ids: string[];
p_school_ids: string[];
};
Returns: {
grades: {
gradeId: string;
gradeName: string;
studentCount: number;
}[];
totalStudents: number;
};
};
get_campaign_dashboard_metrics: {
Args: {
p_campaign_ids: string[];
Expand Down
4 changes: 2 additions & 2 deletions src/teachers-module/pages/SubjectSelection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,8 @@ const SubjectSelection: React.FC = () => {
roles.includes(role),
);
setCanModify(
schoolMatches &&
(normalizedRole === RoleType.PRINCIPAL || hasSubjectModificationRole),
hasSubjectModificationRole ||
(schoolMatches && normalizedRole === RoleType.PRINCIPAL),
);
Comment on lines 129 to 134

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The roles array destructured from the auth state can potentially be undefined or null (as indicated by the fallback const userRoles = roles || []; on line 99). Accessing roles.includes(role) directly inside the useEffect hook without a safety guard can lead to a runtime TypeError if roles is not yet loaded.

Using optional chaining roles?.includes(role) ensures the application does not crash during initialization or when the auth state is loading.

Suggested change
roles.includes(role),
);
setCanModify(
schoolMatches &&
(normalizedRole === RoleType.PRINCIPAL || hasSubjectModificationRole),
hasSubjectModificationRole ||
(schoolMatches && normalizedRole === RoleType.PRINCIPAL),
);
roles?.includes(role),
);
setCanModify(
hasSubjectModificationRole ||
(schoolMatches && normalizedRole === RoleType.PRINCIPAL),
);

}, [currentSchool?.id, paramSchoolId, roleMap, roles]);

Expand Down
Loading