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
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ const mockBaseConstructor = jest.fn();
jest.mock('@shared/base-entity/base-entity.service', () => {
class MockBaseEntityService {
dataSource: any;
constructor(
public repo: any,
public mailSendService: any,
) {
constructor(public repo: any, public mailSendService: any) {
mockBaseConstructor(repo, mailSendService);
}
async createOne(req: any, dto: any) {
Expand Down Expand Up @@ -83,6 +80,8 @@ describe('att-report-with-report-month.config', () => {

// Mock getOne on the service instance itself since it calls this.getOne()
service.getOne = jest.fn().mockResolvedValue({ id: 1, reportDate: '2022-01-01' });
// By default every selected id is accessible to the caller
service.getManyByIds = jest.fn().mockImplementation((req, ids) => Promise.resolve(ids.map((id) => ({ id }))));

mockBaseCreateOne.mockClear();
mockBaseCreateMany.mockClear();
Expand Down Expand Up @@ -150,6 +149,26 @@ describe('att-report-with-report-month.config', () => {
expect(result).toBe('עודכנו 2 רשומות');
});

it('bulkEdit should only update ids the caller can access', async () => {
service.getManyByIds.mockResolvedValueOnce([{ id: 1 }]);
const req = { parsed: { extra: { action: 'bulkEdit', ids: '1,99', absCount: '1' } } } as any;

await service.doAction(req, {});

expect(service.getManyByIds).toHaveBeenCalledWith(req, [1, 99]);
expect(mockRepo.update.mock.calls[0][0].id.value).toEqual([1]);
});

it('bulkEdit should do nothing when no selected id is accessible', async () => {
service.getManyByIds.mockResolvedValueOnce([]);
const req = { parsed: { extra: { action: 'bulkEdit', ids: '99', absCount: '1' } } } as any;

const result = await service.doAction(req, {});

expect(mockRepo.update).not.toHaveBeenCalled();
expect(result).toBe('לא נבחרו רשומות');
});

it('bulkEdit should not update when no field is filled', async () => {
const req = { parsed: { extra: { action: 'bulkEdit', ids: '1,2', reportDate: 'null' } } } as any;

Expand Down
13 changes: 12 additions & 1 deletion server/src/entity-modules/__tests__/student-klass.config.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ const createMockCrudRequest = (extra: any): CrudRequest =>
},
params: {},
},
}) as CrudRequest;
} as CrudRequest);

const createMockStudentKlass = (data: Partial<StudentKlass> = {}): StudentKlass => ({
id: 1,
Expand Down Expand Up @@ -169,6 +169,7 @@ describe('StudentKlassConfig', () => {
const Service = config.service;
service = new Service(mockRepository as Repository<StudentKlass>, mockMailService);
service.dataSource = mockDataSource as DataSource;
service.getManyByIds = jest.fn().mockImplementation((req, ids) => Promise.resolve(ids.map((id) => ({ id }))));
});

describe('getReportData', () => {
Expand Down Expand Up @@ -225,6 +226,16 @@ describe('StudentKlassConfig', () => {
expect(mockRepository.save).toHaveBeenCalled();
});

it('should only fix references of ids the caller can access', async () => {
const req = createMockCrudRequest({ action: 'fixReferences', ids: '1,99' });
service.getManyByIds.mockResolvedValueOnce([{ id: 1 }]);
mockRepository.findBy.mockResolvedValueOnce([createMockStudentKlass({ id: 1, studentTz: '123', klassId: 1 })]);

await service.doAction(req, {});

expect(mockRepository.findBy).toHaveBeenCalledWith({ id: In([1]) });
});

it('should call super.doAction for unknown action', async () => {
const req = createMockCrudRequest({
action: 'unknownAction',
Expand Down
45 changes: 21 additions & 24 deletions server/src/entity-modules/att-report-with-report-month.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,7 @@ import { fixReferences } from '@shared/utils/entity/fixReference.util';
import { getHebrewDateFormatter } from '@shared/utils/formatting/formatter.util';
import { shouldShowTopic } from './att-report.config';
import { getBulkEditUpdate } from '@shared/utils/entity/bulkEdit.util';
import {
getAsArray,
getAsDate,
getAsNumber,
getAsBoolean,
getAsString,
getAsNumberArray,
} from '@shared/utils/queryParam.util';
import { getAsDate, getAsNumber, getAsBoolean, getAsString, getAsNumberArray } from '@shared/utils/queryParam.util';

function getConfig(): BaseEntityModuleOptions {
return {
Expand Down Expand Up @@ -114,20 +107,27 @@ class AttReportWithReportMonthService<T extends Entity | AttReportWithReportMont
async doAction(req: CrudRequest<any, any>, body: any): Promise<any> {
switch (req.parsed.extra.action) {
case 'bulkEdit':
return this.bulkEdit(req.parsed.extra);
return this.bulkEdit(req.parsed.extra, await this.getOwnedIds(req));
case 'bulkKnownAbsences':
return this.bulkKnownAbsences(req.parsed.extra);
return this.bulkKnownAbsences(req.parsed.extra, await this.getOwnedIds(req));
case 'fixStudentReferenceV2':
return this.fixStudentReferenceV2(req.parsed.extra);
return this.fixStudentReferenceV2(await this.getOwnedIds(req));
case 'fixReferences':
return this.fixReferences(req.parsed.extra);
return this.fixReferences(await this.getOwnedIds(req));
}
return super.doAction(req, body);
}

private async bulkEdit(extra: Record<string, string>): Promise<string> {
const ids = getAsNumberArray(extra.ids);
if (!ids || ids.length === 0) return 'לא נבחרו רשומות';
// Keeps only the selected ids the caller may access (crudAuth filter), so a
// caller-supplied id from another user's data is never touched.
private async getOwnedIds(req: CrudRequest<any, any>): Promise<number[]> {
const ids = getAsNumberArray(req.parsed.extra.ids);
const entities = await this.getManyByIds(req, ids);
return entities.map((entity: any) => entity.id);
}

private async bulkEdit(extra: Record<string, string>, ids: number[]): Promise<string> {
if (ids.length === 0) return 'לא נבחרו רשומות';

const update = getBulkEditUpdate(extra, {
numbers: ['klassReferenceId', 'teacherReferenceId', 'lessonReferenceId', 'howManyLessons', 'absCount'],
Expand All @@ -140,9 +140,8 @@ class AttReportWithReportMonthService<T extends Entity | AttReportWithReportMont
return `עודכנו ${result.affected} רשומות`;
}

private async bulkKnownAbsences(extra: Record<string, string>): Promise<string> {
const ids = getAsArray(extra.ids);
if (!ids) return 'לא נבחרו רשומות';
private async bulkKnownAbsences(extra: Record<string, string>, ids: number[]): Promise<string> {
if (ids.length === 0) return 'לא נבחרו רשומות';
const reports = await this.dataSource.getRepository(AttReport).findBy({ id: In(ids) });

const knownAbsences: Array<Partial<KnownAbsence>> = reports.map((report) => ({
Expand All @@ -165,9 +164,8 @@ class AttReportWithReportMonthService<T extends Entity | AttReportWithReportMont
return `נוצרו ${reports.length} חיסורים מאושרים`;
}

private async fixStudentReferenceV2(extra: Record<string, string>): Promise<string> {
const ids = getAsArray(extra.ids);
if (!ids) return 'לא נבחרו רשומות';
private async fixStudentReferenceV2(ids: number[]): Promise<string> {
if (ids.length === 0) return 'לא נבחרו רשומות';
const reports = await this.dataSource.getRepository(AttReport).findBy({ id: In(ids) });

const reportsToSave = [];
Expand All @@ -185,9 +183,8 @@ class AttReportWithReportMonthService<T extends Entity | AttReportWithReportMont
return `עודכנו ${reportsToSave.length} רשומות`;
}

private async fixReferences(extra: Record<string, string>): Promise<string> {
const ids = getAsNumberArray(extra.ids);
if (!ids) return 'לא נבחרו רשומות';
private async fixReferences(ids: number[]): Promise<string> {
if (ids.length === 0) return 'לא נבחרו רשומות';
const referenceFields = {
studentTz: 'studentReferenceId',
klassId: 'klassReferenceId',
Expand Down
6 changes: 4 additions & 2 deletions server/src/entity-modules/klass.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,10 @@ class KlassService<T extends Entity | Klass> extends BaseEntityService<T> {
async doAction(req: CrudRequest<any, any>, body: any): Promise<any> {
switch (req.parsed.extra.action) {
case 'fixReferences': {
const ids = getAsNumberArray(req.parsed.extra.ids);
if (!ids) return 'לא נבחרו רשומות';
const ids = (await this.getManyByIds(req, getAsNumberArray(req.parsed.extra.ids))).map(
(entity: any) => entity.id,
);
if (!ids.length) return 'לא נבחרו רשומות';
const referenceFields = {
klassTypeId: 'klassTypeReferenceId',
teacherId: 'teacherReferenceId',
Expand Down
6 changes: 4 additions & 2 deletions server/src/entity-modules/report-group-session.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,16 @@ class ReportGroupSessionService<T extends Entity | ReportGroupSession> extends B
async doAction(req: CrudRequest<any, any>, body: any): Promise<any> {
switch (req.parsed.extra.action) {
case 'adjustTime': {
const ids = getAsNumberArray(req.parsed.extra.ids);
const ids = (await this.getManyByIds(req, getAsNumberArray(req.parsed.extra.ids))).map(
(entity: any) => entity.id,
);
const hoursAdjustment = getAsNumber(req.parsed.extra.hoursAdjustment) || 0;

if (hoursAdjustment === 0) {
return 'לא בוצע שינוי - יש להזין מספר שעות';
}

if (!ids) return 'לא נבחרו מפגשים';
if (!ids.length) return 'לא נבחרו מפגשים';

const sessions = await this.dataSource.getRepository(ReportGroupSession).find({
where: { id: In(ids) },
Expand Down
6 changes: 4 additions & 2 deletions server/src/entity-modules/report-group.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,10 @@ class ReportGroupService<T extends Entity | ReportGroup> extends BaseEntityServi
async doAction(req: CrudRequest<any, any>, body: any): Promise<any> {
switch (req.parsed.extra.action) {
case 'updateSignatureData': {
const ids = getAsNumberArray(req.parsed.extra.ids);
if (!ids) return 'לא נבחרו רשומות';
const ids = (await this.getManyByIds(req, getAsNumberArray(req.parsed.extra.ids))).map(
(entity: any) => entity.id,
);
if (!ids.length) return 'לא נבחרו רשומות';
const signatureData = getAsString(req.parsed.extra.signatureData);
await this.updateSignatureData(ids, signatureData);
return `עודכנו חתימות ל-${ids.length} קבוצות דוחות`;
Expand Down
6 changes: 4 additions & 2 deletions server/src/entity-modules/student-klass.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,10 @@ class StudentKlassService<T extends Entity | StudentKlass> extends BaseEntitySer
async doAction(req: CrudRequest<any, any>, body: any): Promise<any> {
switch (req.parsed.extra.action) {
case 'fixReferences': {
const ids = getAsNumberArray(req.parsed.extra.ids);
if (!ids) return 'לא נבחרו רשומות';
const ids = (await this.getManyByIds(req, getAsNumberArray(req.parsed.extra.ids))).map(
(entity: any) => entity.id,
);
if (!ids.length) return 'לא נבחרו רשומות';
const referenceFields = {
studentTz: 'studentReferenceId',
klassId: 'klassReferenceId',
Expand Down
8 changes: 5 additions & 3 deletions server/src/entity-modules/student.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import studentReportCardReact from 'src/reports/studentReportCardReact';
import { getUserIdFromUser } from '@shared/auth/auth.util';
import { generateStudentReportCard } from 'src/reports/reportGenerator';
import { In } from 'typeorm';
import { getAsArray, getAsBoolean } from '@shared/utils/queryParam.util';
import { getAsBoolean, getAsNumberArray } from '@shared/utils/queryParam.util';

function getConfig(): BaseEntityModuleOptions {
return {
Expand Down Expand Up @@ -47,9 +47,11 @@ class StudentService<T extends Entity | Student> extends BaseEntityService<T> {
async doAction(req: CrudRequest<any, any>, body: any): Promise<any> {
switch (req.parsed.extra.action) {
case 'bulkUpdateActive': {
const ids = getAsArray(req.parsed.extra.ids);
const ids = (await this.getManyByIds(req, getAsNumberArray(req.parsed.extra.ids))).map(
(entity: any) => entity.id,
);
const isActive = getAsBoolean(req.parsed.extra.isActive) ?? false;
if (!ids) return 'לא נבחרו רשומות';
if (!ids.length) return 'לא נבחרו רשומות';

const result = await this.dataSource.getRepository(Student).update({ id: In(ids) }, { isActive });

Expand Down
Loading