creating extrafeeUser

creating extrafeeUser
 avatar
Yash
typescript
24 days ago
7.1 kB
5
Indexable
async create(data: any): Promise<any> {
        try {
            if (data.student_wise) {
                const { iid, extraFeesIds, userId, branchId, userCourseId, dueDate, initialAmount } = data;
                const findUserCourse = await this.userCourseService.findOne(userCourseId)
                if (!findUserCourse) {
                    throw new BadRequestException(`userCourse not found`)
                }
                const extraFeeUsers = [];
                const skippedFees = [];
    
                for (const extraFeeId of extraFeesIds) {
                    const findextrafee = await this.extraFeeService.findOne(extraFeeId);
                    if (!findextrafee) {
                        throw new BadRequestException(`Extra fee with ID ${extraFeeId} not found.`);
                    }
                    if (findextrafee.feesType === "ONE_TIME") {
                        const existingRecord = await this.extraFeeUserModel.findOne({
                            userId,
                            extraFeesId: extraFeeId,
                            status: { $ne: "cancel" },
                        });
                        if (existingRecord) {
                            skippedFees.push({
                                extraFeeId,
                                reason: "Extra fee is type ONE_TIME and has already been assigned"
                            });
                            continue; 
                        }
                    }
    
                    const result = await this.extraFeeUserModel.findOneAndUpdate(
                        {
                            userId,
                            courseId: findUserCourse.courseId,
                            extraFeesId: extraFeeId,
                            status: { $ne: "cancel" }
                        },
                        {
                            $setOnInsert: {
                                userCourseId: userCourseId,
                                createdBy: data.createdBy,
                                initialAmount: initialAmount,
                                dueDate: dueDate,
                                iid,
                                branchId
                            }
                        },
                        { 
                            upsert: true, 
                            new: true, 
                            setDefaultsOnInsert: true 
                        }
                    );
                    if (result.isNew) {
                        extraFeeUsers.push(result);
                    } else {
                        skippedFees.push({
                            extraFeeId,
                            reason: "Fee already assigned to this user"
                        });
                    }
                }
    
                return {
                    message: "Extra fees processed successfully.",
                    extraFeeUsers,
                    skippedFees,
                };
            }
            
            const { iid, courseId, extraFeesIds, branchId } = data;
    
            const existingCourse = await this.courseService.findOneByQuery({ _id: courseId });
    
            if (!existingCourse) {
                throw new BadRequestException(`Course with ID ${courseId} does not exist.`);
            }
    
            const removedExtraFees = filter(existingCourse.extraFeesIds,
                (feeId: any) => !includes(extraFeesIds, feeId)
            );
    
            if (removedExtraFees.length > 0) {
                await this.extraFeeUserModel.deleteMany({
                    extraFeesId: { $in: removedExtraFees },
                    status: { $in: ['pending', 'cancel'] }
                });
            }
    
            const updatedCourse = await this.courseService.updateCourseExtraFee(
                { _id: courseId },
                { $set: { extraFeesIds } }
            );
            if (!updatedCourse) {
                throw new BadRequestException(`Course with ID ${courseId} does not update.`);
            }
    
            const existingRecords = await this.userCourseService.findAll({ iid, courseId });
    
            if (!existingRecords) {
                throw new BadRequestException(`Record for IID ${iid} and Course ID ${courseId} not exists.`);
            }
    
            const extraFeeUsers = [];
            const skippedFees = [];
    
            for (const extraFeeId of extraFeesIds) {
                const findextrafee = await this.extraFeeService.findOne(extraFeeId);
    
                if (!findextrafee) {
                    throw new BadRequestException(`Extra fee with ID ${extraFeeId} not found.`);
                }
    
                const skippedForThisFee = [];
                const createdForThisFee = [];
    
                for (const record of existingRecords) {
                    const result:any = await this.extraFeeUserModel.findOneAndUpdate(
                        {
                            userId: record.userId,
                            courseId: record.courseId,
                            extraFeesId: extraFeeId,
                            status: { $ne: "cancel" }
                        },
                        {
                            $setOnInsert: {
                                userCourseId: record._id,
                                createdBy: data.createdBy,
                                initialAmount: findextrafee.defaultAmount,
                                dueDate: findextrafee.dueDate,
                                iid: data.iid,
                                branchId
                            }
                        },
                        { 
                            upsert: true, 
                            new: true,
                            setDefaultsOnInsert: true 
                        }
                    );
    
                    if (result && !result.createdAt) { 
                        createdForThisFee.push(result);
                        extraFeeUsers.push(result);
                    } else {
                        skippedForThisFee.push({
                            userId: record.userId,
                            userCourseId: record._id
                        });
                    }
                }
    
                if (skippedForThisFee.length > 0) {
                    skippedFees.push({
                        extraFeeId,
                        skippedUsers: skippedForThisFee,
                        createdUsers: createdForThisFee.length
                    });
                }
            }
    
            return {
                message: "Extra fees processed successfully.",
                extraFeeUsers,
                skippedFees,
            };
    
        } catch (error) {
            throw new BadRequestException(error.message || error);
        }
    }
Editor is loading...
Leave a Comment