feat: implement sysadmin subscription management and plan usage cycle recalculation tools
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
import { connect } from "mongoose";
|
||||
import dayjs from "dayjs";
|
||||
import AppointmentList from "../../../Models/Appointments/Appointments";
|
||||
import CompaniesList from "../../../Models/Companies/Companies";
|
||||
import PlanUsageCycleList from "../../../Models/PlanUsageCycle/PlanUsageCycle";
|
||||
import {
|
||||
SysAdminRecalculatePlanUsageCycleParams,
|
||||
SysAdminRecalculatePlanUsageCycleResult,
|
||||
} from "../../../Models/PlanUsageCycle/PlanUsageCycle.Interface";
|
||||
|
||||
export class SysAdminPlanUsageCycleService {
|
||||
public async recalculateUserUsageCycle(
|
||||
params: SysAdminRecalculatePlanUsageCycleParams
|
||||
): Promise<SysAdminRecalculatePlanUsageCycleResult> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
|
||||
const usageCycle = await PlanUsageCycleList.getCurrentCycle({ userId: params.userId });
|
||||
const companies = await CompaniesList.companies.find({ ownerId: params.userId });
|
||||
const companyIds = companies.map((company) => String(company.id));
|
||||
|
||||
const appointmentsCount = companyIds.length === 0
|
||||
? 0
|
||||
: await AppointmentList.Appointments.AppointmentList.countDocuments({
|
||||
companyId: { $in: companyIds },
|
||||
creationDate: {
|
||||
$gte: dayjs(usageCycle.cycleStart).toDate(),
|
||||
$lt: dayjs(usageCycle.cycleEnd).toDate(),
|
||||
},
|
||||
});
|
||||
|
||||
const updatedCycle = await PlanUsageCycleList.setAppointmentsCount({
|
||||
userId: params.userId,
|
||||
appointmentsCount,
|
||||
});
|
||||
|
||||
if (!updatedCycle) {
|
||||
throw new Error("No se pudo recalcular el uso del plan.");
|
||||
}
|
||||
|
||||
return {
|
||||
userId: params.userId,
|
||||
subscriptionId: String(updatedCycle.subscriptionId),
|
||||
planId: String(updatedCycle.planId),
|
||||
cycleStart: updatedCycle.cycleStart,
|
||||
cycleEnd: updatedCycle.cycleEnd,
|
||||
appointmentsCount: updatedCycle.appointmentsCount,
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user