diff --git a/.env.template b/.env.template index b79ddc1f..850e1b9b 100644 --- a/.env.template +++ b/.env.template @@ -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.. +# 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 diff --git a/client/src/reports/studentReportCardReactButton.jsx b/client/src/reports/studentReportCardReactButton.jsx index 491a9928..5d42db22 100644 --- a/client/src/reports/studentReportCardReactButton.jsx +++ b/client/src/reports/studentReportCardReactButton.jsx @@ -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'; @@ -14,6 +14,8 @@ const defaultValues = { export default ({ defaultRequestValues }) => { const reportCardSettings = useReportCardSettings(); + const { identity } = useGetIdentity(); + const hasTikufConnection = Boolean(identity?.additionalData?.studentReportApiKey); return ( { source="limitFilterUseOr" label="כאשר שני הסינונים הקודמים מלאים, הצג שורה כשמתקיים לפחות אחד מהם (במקום שניהם יחד)" /> + {hasTikufConnection && } ); }; diff --git a/client/src/roadmapFeatures.js b/client/src/roadmapFeatures.js index 603ea138..2b5563fc 100644 --- a/client/src/roadmapFeatures.js +++ b/client/src/roadmapFeatures.js @@ -48,4 +48,5 @@ export default [ { html: 'דיווחים למורה וציונים למורה: סינון "יש שיעורים שלא דווחו", ומיון לפי מספר השיעורים שדווחו / שלא דווחו', status: 'בוצע', statusColor: 'success' }, { html: 'דף חדש "אפשרויות שדרוג" בהסברים נוספים: כל היכולות שאפשר להפעיל בהרשאה, עם הסבר ומחיר', status: 'בוצע', statusColor: 'success' }, { html: 'התקנה כאפליקציה: אפשר להתקין את המערכת מהדפדפן (בכרום: סמל ההתקנה בשורת הכתובת) ולפתוח אותה בחלון נפרד, עם לוגו משלה בשולחן העבודה ובשורת המשימות', status: 'בוצע', statusColor: 'success' }, + { html: 'תעודה לתלמידה: אפשר להוסיף סיכום תיקופי נוכחות מאתר התיקוף (למי שחובר לשני האתרים, באמצעות התמיכה)', status: 'בוצע', statusColor: 'success' }, ].reverse(); diff --git a/docker-compose-swarm.yml b/docker-compose-swarm.yml index f2980fd0..d4979e18 100644 --- a/docker-compose-swarm.yml +++ b/docker-compose-swarm.yml @@ -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' diff --git a/docker-compose.yml b/docker-compose.yml index 67dda108..293e040b 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -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 diff --git a/server/src/reports/__tests__/reportGenerator.spec.ts b/server/src/reports/__tests__/reportGenerator.spec.ts index 25391f91..df48a5d3 100644 --- a/server/src/reports/__tests__/reportGenerator.spec.ts +++ b/server/src/reports/__tests__/reportGenerator.spec.ts @@ -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 = { diff --git a/server/src/reports/reportGenerator.ts b/server/src/reports/reportGenerator.ts index 22cdc299..8c08a971 100644 --- a/server/src/reports/reportGenerator.ts +++ b/server/src/reports/reportGenerator.ts @@ -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) => ({ diff --git a/server/src/reports/studentReportCardReact.tsx b/server/src/reports/studentReportCardReact.tsx index 202c38ae..aef74d92 100644 --- a/server/src/reports/studentReportCardReact.tsx +++ b/server/src/reports/studentReportCardReact.tsx @@ -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 { @@ -94,6 +95,7 @@ interface AppProps { att_grade_effect: AttGradeEffect[]; grade_names: GradeName[]; attendance_names: AttendanceName[]; + tikufSummary?: TikufSummary; }; const useAppStyles = () => { const appStyle: React.CSSProperties = { @@ -122,6 +124,7 @@ const App: React.FunctionComponent = (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} /> + @@ -172,6 +175,10 @@ const PersonalNote = ({ note }: { note: string }) => note && (

{note}

); +const TikufSummaryNote = ({ summary }: { summary?: TikufSummary }) => summary && ( +

תיקופי נוכחות: {summary.count} ימים

+); + const yomanetNoticeStyle: React.CSSProperties = { position: 'absolute', top: '50%', @@ -500,6 +507,7 @@ export interface IReportParams { attendanceLessThan?: number; gradesLessThan?: number; limitFilterUseOr?: boolean; + showTikuf?: boolean; } export const getReportData: IGetReportDataFunction = async (params, dataSource) => { const reportDate = getReportDateFilter(dateFromString(params.startDate), dateFromString(params.endDate)); @@ -534,6 +542,9 @@ export const getReportData: IGetReportDataFunction = 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, @@ -547,6 +558,7 @@ export const getReportData: IGetReportDataFunction = as att_grade_effect, grade_names, attendance_names, + tikufSummary, }; } diff --git a/server/src/utils/__tests__/tikuf-summary.util.spec.ts b/server/src/utils/__tests__/tikuf-summary.util.spec.ts new file mode 100644 index 00000000..f4e465d7 --- /dev/null +++ b/server/src/utils/__tests__/tikuf-summary.util.spec.ts @@ -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 | 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'); + }); + }); +}); diff --git a/server/src/utils/tikuf-summary.util.ts b/server/src/utils/tikuf-summary.util.ts new file mode 100644 index 00000000..bd668cc4 --- /dev/null +++ b/server/src/utils/tikuf-summary.util.ts @@ -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; + +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 }>(); + +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 { + 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 { + 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, + studentTz: string, + query: TikufSummaryQuery, +): Promise { + 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();