Untitled
unknown
plain_text
a year ago
3.4 kB
9
Indexable
create = this.catchAsync('create', async (body: CreateFullCamp) => { if (isCrud()) throw new ApiError( this.translate('guard.NOT_ACCESS'), HttpStatus.FORBIDDEN, ); const owner: UserProfile = this.activeUser().userProfile; const usedQuestionTypes: Set<QuestionType> = new Set(); const { title, description, startDate, endDate, current_point, target_point, dayOfWeek, } = body; const numberOfTasks = (target_point - current_point) * 2.5; const totalDays = Math.round( (endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24), ); const maxDays = 28; // Maximum 4 weeks const minDays = 7; // Minimum 1 week if (totalDays < minDays || totalDays > maxDays) { throw new ApiError( this.translate('service.CAMP.INVALID_DURATION'), HttpStatus.BAD_REQUEST, ); } const selectedWeekdays = Object.keys(dayOfWeek).filter( (key) => dayOfWeek[key], ); const maxTasks: number = 40; // Maximum 3 tasks per day const finalNumberOfTasks: number = Math.min(numberOfTasks, maxTasks); const questionTypes: QuestionType[] = await this.questionTypeRepository.find(); const campTasks: CampTasksEntity[] = []; let currentTaskIndex: number = 0; for (let i: number = 0; i < totalDays; i++) { const currentDate: Date = new Date(startDate); currentDate.setDate(startDate.getDate() + i); if (selectedWeekdays.includes(currentDate.getDay().toString())) { if (currentTaskIndex < finalNumberOfTasks) { let filteredQuestionTypes: QuestionType[] = questionTypes.filter(item => item.id !== 11 && item.id !== 12); if (owner?.examType?.id !== 1) { filteredQuestionTypes = filteredQuestionTypes.filter(item => item.id !== 3 && item.id !== 5); } let randomQuestionType: QuestionType; do { randomQuestionType = filteredQuestionTypes[Math.floor(Math.random() * questionTypes.length)]; } while (usedQuestionTypes.has(randomQuestionType)); // Check if the questionType is already used usedQuestionTypes.add(randomQuestionType); const targetPoint: number = (target_point - current_point) / 2; const taskPayload: Partial<CampTasksEntity> = { date: currentDate, correct_answer: 0, wrong_answer: 0, point: targetPoint * 1.5, isCompleted: false, checked: false, target: targetPoint, questionType: randomQuestionType, }; campTasks.push(new CampTasksEntity(taskPayload)); currentTaskIndex++; } } } const campPayload: Partial<Camp> = { owner, title, description, startDate, endDate, point: campTasks.length * 15, current_point, target_point, isCompleted: false, examType: owner.examType, tag: owner.tag || null, dayOfWeek: body.dayOfWeek, campTasks, }; return this.campRepository.manager .transaction(async (em: EntityManager) => { return await em.save(new Camp(campPayload)); }) .catch((err) => { throw new ApiError( this.translate('global.INTERNAL_SERVER_ERROR'), HttpStatus.INTERNAL_SERVER_ERROR, err, ); }); });
Editor is loading...
Leave a Comment