Files
turnosxpress/server/src/api/SysAdmin/PlanUsageCycle/SysAdminPlanUsageCycle.Service.ts
T

59 lines
2.4 KiB
TypeScript

import { connect } from "mongoose";
import dayjs from "dayjs";
import AppointmentList from "../../../Models/Appointments/Appointments";
import CompaniesList from "../../../Models/Companies/Companies";
import MetricsList from "../../../Models/Metrics/Metrics";
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.");
}
await MetricsList.calculateMetrics({ userId: params.userId });
const metrics = await MetricsList.getMetrics(params.userId);
return {
userId: params.userId,
subscriptionId: String(updatedCycle.subscriptionId),
planId: String(updatedCycle.planId),
cycleStart: updatedCycle.cycleStart,
cycleEnd: updatedCycle.cycleEnd,
organizationsCount: metrics.organizationsCount,
employeesCount: metrics.employeesCount,
servicesCount: metrics.servicesCount,
clientsCount: metrics.clientsCount,
repeatsCount: metrics.repeatsCount || 0,
appointmentsCount: updatedCycle.appointmentsCount,
};
}
}