Skip to content
Open
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
4 changes: 4 additions & 0 deletions .env.template
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ MAIL_WEBHOOK_SECRET=

# Optional: sunset date for the legacy, unauthenticated /yemot/handle-call URL. Unset = no cutoff.
YEMOT_LEGACY_ROUTE_DEADLINE=

# Optional: base API address of the student-report (tikuf) site, e.g. https://api.<its domain>.
# Lets the student report card include tikuf days for users that have additionalData.studentReportApiKey.
STUDENT_REPORT_API_URL=
# Enables the background job worker + schedule heartbeat (recurring jobs like
# attendance-cleanup-sweep) on this server instance. Defaults to true for the
# common single-container deployment. If ever running multiple server
Expand Down
5 changes: 4 additions & 1 deletion client/src/reports/studentReportCardReactButton.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { TextInput, DateInput, NumberInput, BooleanInput } from 'react-admin';
import { TextInput, DateInput, NumberInput, BooleanInput, useGetIdentity } from 'react-admin';
import { defaultYearFilter } from '@shared/utils/yearFilter';
import { CommonYearInput } from '@shared/components/fields/CommonYear';
import NoteAltIcon from '@mui/icons-material/NoteAlt';
Expand All @@ -14,6 +14,8 @@ const defaultValues = {

export default ({ defaultRequestValues }) => {
const reportCardSettings = useReportCardSettings();
const { identity } = useGetIdentity();
const hasTikufConnection = Boolean(identity?.additionalData?.studentReportApiKey);

return (
<BulkReportButton
Expand Down Expand Up @@ -54,6 +56,7 @@ export default ({ defaultRequestValues }) => {
source="limitFilterUseOr"
label="כאשר שני הסינונים הקודמים מלאים, הצג שורה כשמתקיים לפחות אחד מהם (במקום שניהם יחד)"
/>
{hasTikufConnection && <BooleanInput source="showTikuf" label="הוסף סיכום תיקופי נוכחות (מאתר התיקוף)" />}
</BulkReportButton>
);
};
1 change: 1 addition & 0 deletions client/src/roadmapFeatures.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions docker-compose-swarm.yml
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ services:
MAINTENANCE_MESSAGE: $MAINTENANCE_MESSAGE
MAIL_WEBHOOK_SECRET: $MAIL_WEBHOOK_SECRET
YEMOT_LEGACY_ROUTE_DEADLINE: $YEMOT_LEGACY_ROUTE_DEADLINE
STUDENT_REPORT_API_URL: ${STUDENT_REPORT_API_URL:-}
WORKER_ENABLED: ${WORKER_ENABLED:-true}
# ports:
# - '30004:3000'
Expand Down
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ services:
MAINTENANCE_MESSAGE: $MAINTENANCE_MESSAGE
MAIL_WEBHOOK_SECRET: $MAIL_WEBHOOK_SECRET
YEMOT_LEGACY_ROUTE_DEADLINE: $YEMOT_LEGACY_ROUTE_DEADLINE
STUDENT_REPORT_API_URL: ${STUDENT_REPORT_API_URL:-}
WORKER_ENABLED: ${WORKER_ENABLED:-true}
depends_on:
- database
Expand Down
10 changes: 10 additions & 0 deletions server/src/reports/__tests__/reportGenerator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,16 @@ describe('reportGenerator', () => {
});
});

it('should pass the tikuf summary flag as a boolean', () => {
const generator: BaseReportGenerator = {} as any;

const on = generateStudentReportCard('123', { ids: '1', showTikuf: 'true' }, generator);
const off = generateStudentReportCard('123', { ids: '1' }, generator);

expect(on.params[0].showTikuf).toBe(true);
expect(off.params[0].showTikuf).toBeFalsy();
});

it('should use provided year instead of current year', () => {
const userId = '123';
const reqExtra = {
Expand Down
1 change: 1 addition & 0 deletions server/src/reports/reportGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export function generateStudentReportCard(userId: any, reqExtra: any, generator:
attendanceLessThan: getPercentLessThanParam(reqExtra.attendanceLessThan),
gradesLessThan: getPercentLessThanParam(reqExtra.gradesLessThan),
limitFilterUseOr: getAsBoolean(reqExtra.limitFilterUseOr),
showTikuf: getAsBoolean(reqExtra.showTikuf),
};
console.log('student report card extra params: ', extraParams);
const params = getAsArray(reqExtra.ids)?.map((id) => ({
Expand Down
12 changes: 12 additions & 0 deletions server/src/reports/studentReportCardReact.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { formatHebrewDate, formatDisplayName } from '@shared/utils/formatting/fo
import { groupDataByKeysAndCalc, calcSum, groupDataByKeys, getItemById } from '@shared/utils/reportData.util';
import { getDisplayGrade, getDisplayAttendance, getAttPercents, getUnknownAbsCount, calcReportsData, getReportsFilterForReportCard, getGradeEffect, getRelevantGrade } from 'src/utils/studentReportData.util';
import { getReportDateFilter, dateFromString } from '@shared/utils/entity/filters.util';
import { TikufSummary, buildTikufSummaryQuery, getStudentTikufSummary } from 'src/utils/tikuf-summary.util';
import { StudentSpeciality } from 'src/db/view-entities/StudentSpeciality.entity';

enum ReportElementType {
Expand Down Expand Up @@ -94,6 +95,7 @@ interface AppProps {
att_grade_effect: AttGradeEffect[];
grade_names: GradeName[];
attendance_names: AttendanceName[];
tikufSummary?: TikufSummary;
};
const useAppStyles = () => {
const appStyle: React.CSSProperties = {
Expand Down Expand Up @@ -122,6 +124,7 @@ const App: React.FunctionComponent<AppProps> = (props) => {
reports={props.reports} reportParams={props.reportParams}
knownAbsMap={props.knownAbsMap}
att_grade_effect={props.att_grade_effect} grade_names={props.grade_names} attendance_names={props.attendance_names} />
<TikufSummaryNote summary={props.tikufSummary} />
<PersonalNote note={props.reportParams.personalNote} />
<YomanetNotice />
</td></tr></tbody>
Expand Down Expand Up @@ -172,6 +175,10 @@ const PersonalNote = ({ note }: { note: string }) => note && (
<h4>{note}</h4>
);

const TikufSummaryNote = ({ summary }: { summary?: TikufSummary }) => summary && (
<h4>תיקופי נוכחות: {summary.count} ימים</h4>
);

const yomanetNoticeStyle: React.CSSProperties = {
position: 'absolute',
top: '50%',
Expand Down Expand Up @@ -500,6 +507,7 @@ export interface IReportParams {
attendanceLessThan?: number;
gradesLessThan?: number;
limitFilterUseOr?: boolean;
showTikuf?: boolean;
}
export const getReportData: IGetReportDataFunction<IReportParams, AppProps> = async (params, dataSource) => {
const reportDate = getReportDateFilter(dateFromString(params.startDate), dateFromString(params.endDate));
Expand Down Expand Up @@ -534,6 +542,9 @@ export const getReportData: IGetReportDataFunction<IReportParams, AppProps> = as

const knownAbsMap = groupDataByKeysAndCalc(knownAbsences, ['klassReferenceId'], (arr) => groupDataByKeysAndCalc(arr, ['lessonReferenceId'], (arr) => calcSum(arr, item => item.absnceCount)));
const reports = getReports(params, studentReports, knownAbsMap, studentBaseKlass, klasses, lessons, teachers);
const tikufSummary = params.showTikuf
? await getStudentTikufSummary(user, student.tz, buildTikufSummaryQuery(params))
: undefined;

return {
userStyles: user?.additionalData?.reportStyles,
Expand All @@ -547,6 +558,7 @@ export const getReportData: IGetReportDataFunction<IReportParams, AppProps> = as
att_grade_effect,
grade_names,
attendance_names,
tikufSummary,
};
}

Expand Down
117 changes: 117 additions & 0 deletions server/src/utils/__tests__/tikuf-summary.util.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { BadGatewayException, BadRequestException } from '@nestjs/common';
import {
buildTikufSummaryQuery,
clearTikufSummaryCache,
getStudentTikufSummary,
normalizeTz,
} from '../tikuf-summary.util';

const user = { additionalData: { studentReportApiKey: 'k'.repeat(32) } };
const body = { students: [{ tz: '0123', count: 2, dates: ['2026-11-01', '2026-11-09'] }, { tz: '555', count: 1, dates: ['2026-11-02'] }] };

const mockFetch = (response: Partial<Response> | Error) =>
jest.spyOn(global, 'fetch').mockImplementation(async () => {
if (response instanceof Error) throw response;
return { ok: true, status: 200, json: async () => body, ...response } as Response;
});

describe('tikuf summary util', () => {
const originalUrl = process.env.STUDENT_REPORT_API_URL;

beforeEach(() => {
process.env.STUDENT_REPORT_API_URL = 'https://tikuf.example.org/api/';
clearTikufSummaryCache();
});

afterEach(() => {
jest.restoreAllMocks();
process.env.STUDENT_REPORT_API_URL = originalUrl;
});

describe('normalizeTz', () => {
it('trims and drops leading zeros', () => {
expect(normalizeTz(' 0123 ')).toBe('123');
expect(normalizeTz(123)).toBe('123');
expect(normalizeTz(undefined)).toBe('');
});
});

describe('buildTikufSummaryQuery', () => {
it('uses explicit dates and ignores the default year', () => {
expect(buildTikufSummaryQuery({ startDate: '2026-11-01', endDate: '2026-11-30', year: 5787 })).toEqual({
fromDate: '2026-11-01',
toDate: '2026-11-30',
});
});

it('accepts a single date', () => {
expect(buildTikufSummaryQuery({ startDate: '2026-11-01', year: 5787 })).toEqual({ fromDate: '2026-11-01', toDate: undefined });
});

it('falls back to the year when there are no valid dates', () => {
expect(buildTikufSummaryQuery({ startDate: '', endDate: 'x', year: 5787 })).toEqual({ year: 5787 });
});
});

describe('getStudentTikufSummary', () => {
it('calls the site once with the key and matches the student by normalized tz', async () => {
const fetchSpy = mockFetch({});

const [first, second, missing] = await Promise.all([
getStudentTikufSummary(user, '123', { year: 5787 }),
getStudentTikufSummary(user, '555', { year: 5787 }),
getStudentTikufSummary(user, '999', { year: 5787 }),
]);

expect(first).toEqual({ count: 2, dates: ['2026-11-01', '2026-11-09'] });
expect(second).toEqual({ count: 1, dates: ['2026-11-02'] });
expect(missing).toEqual({ count: 0, dates: [] });
expect(fetchSpy).toHaveBeenCalledTimes(1);
const [url, init] = fetchSpy.mock.calls[0];
expect(url).toBe('https://tikuf.example.org/api/integration/tikuf-summary?year=5787');
expect((init as RequestInit).headers).toEqual({ 'x-api-key': user.additionalData.studentReportApiKey });
});

it('sends date filters instead of year', async () => {
const fetchSpy = mockFetch({});
await getStudentTikufSummary(user, '123', { fromDate: '2026-11-01', toDate: '2026-11-30' });
expect(fetchSpy.mock.calls[0][0]).toBe(
'https://tikuf.example.org/api/integration/tikuf-summary?fromDate=2026-11-01&toDate=2026-11-30',
);
});

it('asks again for a different query', async () => {
const fetchSpy = mockFetch({});
await getStudentTikufSummary(user, '123', { year: 5787 });
await getStudentTikufSummary(user, '123', { year: 5786 });
expect(fetchSpy).toHaveBeenCalledTimes(2);
});

it('requires the site address and the key', async () => {
const fetchSpy = mockFetch({});
await expect(getStudentTikufSummary({ additionalData: {} }, '123', {})).rejects.toBeInstanceOf(BadRequestException);
delete process.env.STUDENT_REPORT_API_URL;
await expect(getStudentTikufSummary(user, '123', {})).rejects.toBeInstanceOf(BadRequestException);
expect(fetchSpy).not.toHaveBeenCalled();
});

it('fails clearly when the site is unreachable, and retries on the next call', async () => {
mockFetch(new Error('ECONNREFUSED'));
await expect(getStudentTikufSummary(user, '123', { year: 1 })).rejects.toBeInstanceOf(BadGatewayException);

jest.restoreAllMocks();
const fetchSpy = mockFetch({});
await expect(getStudentTikufSummary(user, '123', { year: 1 })).resolves.toEqual({ count: 2, dates: ['2026-11-01', '2026-11-09'] });
expect(fetchSpy).toHaveBeenCalledTimes(1);
});

it('fails clearly on a rejected key or a server error', async () => {
mockFetch({ ok: false, status: 401 });
await expect(getStudentTikufSummary(user, '123', {})).rejects.toThrow('מפתח החיבור');

clearTikufSummaryCache();
mockFetch({ ok: false, status: 500 });
await expect(getStudentTikufSummary(user, '123', {})).rejects.toThrow('500');
});
});
});
93 changes: 93 additions & 0 deletions server/src/utils/tikuf-summary.util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { BadGatewayException, BadRequestException } from '@nestjs/common';
import { User } from '@shared/entities/User.entity';

export interface TikufSummary {
count: number;
dates: string[];
}

export interface TikufSummaryQuery {
fromDate?: string;
toDate?: string;
year?: number;
}

type TikufSummaryByTz = Map<string, TikufSummary>;

const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
const CACHE_TTL_MS = 60 * 1000;
const REQUEST_TIMEOUT_MS = 30 * 1000;

// A bulk report asks for every student at once: they share one request instead of one each
const cache = new Map<string, { expires: number; promise: Promise<TikufSummaryByTz> }>();

export const normalizeTz = (tz: string | number): string => String(tz ?? '').trim().replace(/^0+/, '');

// Explicit dates win; the default year only applies when no dates were chosen
export function buildTikufSummaryQuery(params: { startDate?: string; endDate?: string; year?: number }): TikufSummaryQuery {
const fromDate = DATE_PATTERN.test(params.startDate ?? '') ? params.startDate : undefined;
const toDate = DATE_PATTERN.test(params.endDate ?? '') ? params.endDate : undefined;
return fromDate || toDate ? { fromDate, toDate } : { year: params.year };
}

async function requestTikufSummary(baseUrl: string, apiKey: string, query: TikufSummaryQuery): Promise<TikufSummaryByTz> {
const searchParams = new URLSearchParams();
Object.entries(query).forEach(([key, value]) => value && searchParams.set(key, String(value)));
const url = `${baseUrl.replace(/\/+$/, '')}/integration/tikuf-summary?${searchParams}`;

let response: Response;
try {
response = await fetch(url, { headers: { 'x-api-key': apiKey }, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
} catch {
throw new BadGatewayException('לא ניתן להתחבר לאתר התיקוף. נסו שוב מאוחר יותר');
}
if (response.status === 401) {
throw new BadGatewayException('מפתח החיבור לאתר התיקוף אינו תקין. יש לפנות לתמיכה');
}
if (!response.ok) {
throw new BadGatewayException(`אתר התיקוף החזיר שגיאה (${response.status}). נסו שוב מאוחר יותר`);
}

const body = await response.json();
const summaries: TikufSummaryByTz = new Map();
for (const student of body?.students ?? []) {
summaries.set(normalizeTz(student.tz), { count: student.count, dates: student.dates ?? [] });
}
return summaries;
}

function getTikufSummaries(baseUrl: string, apiKey: string, query: TikufSummaryQuery): Promise<TikufSummaryByTz> {
const cacheKey = JSON.stringify([baseUrl, apiKey, query]);
const cached = cache.get(cacheKey);
if (cached && cached.expires > Date.now()) {
return cached.promise;
}

const promise = requestTikufSummary(baseUrl, apiKey, query);
cache.set(cacheKey, { expires: Date.now() + CACHE_TTL_MS, promise });
promise.catch(() => cache.delete(cacheKey));
return promise;
}

/**
* The tikuf days of one student, read from the student-report site. The site address comes from the
* server environment, the key from the user's settings (`additionalData.studentReportApiKey`).
* Throws when the site is not set up or unreachable, so a letter is never produced without data
* the caller asked for.
*/
export async function getStudentTikufSummary(
user: Pick<User, 'additionalData'>,
studentTz: string,
query: TikufSummaryQuery,
): Promise<TikufSummary> {
const baseUrl = process.env.STUDENT_REPORT_API_URL;
const apiKey = user?.additionalData?.studentReportApiKey;
if (!baseUrl || !apiKey) {
throw new BadRequestException('לא הוגדר חיבור לאתר התיקוף. יש לפנות לתמיכה');
}

const summaries = await getTikufSummaries(baseUrl, apiKey, query);
return summaries.get(normalizeTz(studentTz)) ?? { count: 0, dates: [] };
}

export const clearTikufSummaryCache = () => cache.clear();
Loading