chore: approve invoice, reports for admin dashboard

This commit is contained in:
Matin
2025-02-22 16:04:26 +03:30
parent e711ffd3ee
commit 3b0120d338
12 changed files with 448 additions and 8 deletions
+2
View File
@@ -21,6 +21,7 @@ import { AuthModule } from "./modules/auth/auth.module";
import { ContactUsModule } from "./modules/contact-us/contact-us.module";
import { CriticismModule } from "./modules/criticisms/criticisms.module";
import { DanakServicesModule } from "./modules/danak-services/danak-services.module";
import { DashboardModule } from "./modules/dashboards/dashboard.module";
import { DiscountModule } from "./modules/discounts/discounts.module";
import { InvoicesModule } from "./modules/invoices/invoices.module";
import { LearningModule } from "./modules/learnings/learning.module";
@@ -61,6 +62,7 @@ import { WalletsModule } from "./modules/wallets/wallets.module";
DiscountModule,
AdsModule,
AddressModule,
DashboardModule,
],
controllers: [],
providers: [],
+13
View File
@@ -193,4 +193,17 @@ export class AdsService {
}
//***************************************** */
async getAdsCount() {
const count = await this.adsRepository.count({
where: {
isActive: true,
startDate: LessThanOrEqual(new Date()),
endDate: MoreThan(new Date()),
},
});
return count;
}
//***************************************** */
}
@@ -299,4 +299,18 @@ export class DanakServicesService {
review,
};
}
/******************************************** */
async getServicesCount() {
const count = await this.danakServicesRepository.count({
where: {
isActive: true,
},
});
return count;
}
/******************************************** */
}
@@ -0,0 +1,13 @@
import { Controller, Get } from "@nestjs/common";
import { DashboardService } from "./providers/dashboard.service";
@Controller("dashboards")
export class DashboardController {
constructor(private readonly dashboardService: DashboardService) {}
@Get("reports")
async reports() {
return this.dashboardService.reports();
}
}
@@ -0,0 +1,17 @@
import { Module } from "@nestjs/common";
import { DashboardController } from "./dashboard.controller";
import { AdsModule } from "../ads/ads.module";
import { DanakServicesModule } from "../danak-services/danak-services.module";
import { InvoicesModule } from "../invoices/invoices.module";
import { TicketsModule } from "../tickets/tickets.module";
import { UsersModule } from "../users/users.module";
import { DashboardService } from "./providers/dashboard.service";
import { SubscriptionsModule } from "../subscriptions/subscriptions.module";
@Module({
imports: [InvoicesModule, TicketsModule, UsersModule, AdsModule, DanakServicesModule, SubscriptionsModule],
providers: [DashboardService],
controllers: [DashboardController],
})
export class DashboardModule {}
@@ -0,0 +1,126 @@
import { Injectable } from "@nestjs/common";
import { AdsService } from "../../ads/providers/ads.service";
import { DanakServicesService } from "../../danak-services/providers/danak-services.service";
import { InvoicesService } from "../../invoices/providers/invoices.service";
import { SubscriptionsService } from "../../subscriptions/providers/subscriptions.service";
import { TicketsService } from "../../tickets/providers/tickets.service";
import { UsersService } from "../../users/providers/users.service";
@Injectable()
export class DashboardService {
constructor(
private readonly danakServicesService: DanakServicesService,
private readonly usersService: UsersService,
private readonly invoicesService: InvoicesService,
private readonly ticketsService: TicketsService,
private readonly adsService: AdsService,
private readonly subscriptionsService: SubscriptionsService,
) {}
//************************************ */
async reports() {
const danakServicesCount = await this.getDanakServicesCount();
const customersCount = await this.getCustomersCount();
const invoicesCount = await this.getInvoicesCount();
const unreadTickets = await this.unreadTickets();
const adsCount = await this.getAdsCount();
const planRevenueAverage = await this.getPlanRevenueAverage();
const plansSalesCount = await this.getPlansSalesCount();
const subscriptionGrowthRate = await this.getSubscriptionGrowthRate();
const plansSalesCountByMonthsInYear = await this.getPlansSalesCountByMonthsInYear();
const plansSalesCountByDaysInMonth = await this.getPlansSalesCountByDaysInMonth();
const plansSalesCountByDaysInWeek = await this.getPlansSalesCountByDaysInWeek();
return {
danakServicesCount,
customersCount,
invoicesCount,
unreadTickets,
adsCount,
planRevenueAverage,
plansSalesCount,
subscriptionGrowthRate,
plansSalesCountByMonthsInYear,
plansSalesCountByDaysInMonth,
plansSalesCountByDaysInWeek,
};
}
//************************************ */
private async getDanakServicesCount() {
const danakServicesCount = await this.danakServicesService.getServicesCount();
return danakServicesCount;
}
//************************************ */
private async getCustomersCount() {
const customersCount = await this.usersService.getCustomersCount();
return customersCount;
}
//************************************ */
private async getInvoicesCount() {
const invoicesCount = await this.invoicesService.getInvoicesCount();
return invoicesCount;
}
//************************************ */
private async unreadTickets() {
const unreadTickets = await this.ticketsService.getUnreadTickets();
return unreadTickets;
}
//************************************ */
private async getAdsCount() {
const adsCount = await this.adsService.getAdsCount();
return adsCount;
}
//************************************ */
private async getPlanRevenueAverage() {
const planRevenueCount = await this.subscriptionsService.getPlanRevenueAverage();
return planRevenueCount;
}
//************************************ */
private async getPlansSalesCount() {
const plansSalesCount = await this.subscriptionsService.getPlansSalesCount();
return plansSalesCount;
}
//************************************ */
private async getSubscriptionGrowthRate() {
const subscriptionGrowthRate = await this.subscriptionsService.getSubscriptionGrowthRate();
return subscriptionGrowthRate;
}
//************************************ */
private async getPlansSalesCountByMonthsInYear() {
const plansSalesCountByMonthsInYear = await this.subscriptionsService.getPlansSalesCountByMonthsInYear();
return plansSalesCountByMonthsInYear;
}
//************************************ */
private async getPlansSalesCountByDaysInMonth() {
const plansSalesCountByDaysInMonth = await this.subscriptionsService.getPlansSalesCountByDaysInMonth();
return plansSalesCountByDaysInMonth;
}
//************************************ */
private async getPlansSalesCountByDaysInWeek() {
const plansSalesCountByDaysInWeek = await this.subscriptionsService.getPlansSalesCountByDaysInWeek();
return plansSalesCountByDaysInWeek;
}
}
+13 -2
View File
@@ -10,6 +10,8 @@ import { Pagination } from "../../common/decorators/pagination.decorator";
import { PermissionsDec } from "../../common/decorators/permission.decorator";
import { UserDec } from "../../common/decorators/user.decorator";
import { ParamDto } from "../../common/DTO/param.dto";
import { RequestOtpDto } from "../auth/DTO/request-otp.dto";
import { VerifyOtpDto } from "../auth/DTO/verify-otp.dto";
import { PermissionEnum } from "../users/enums/permission.enum";
@Controller("invoices")
@@ -58,11 +60,20 @@ export class InvoicesController {
/**************************************** */
@ApiOperation({ summary: "approve request invoice by user" })
@AuthGuards()
@Post(":id/approve/request")
approveRequestInvoiceByUser(@Param() paramDto: ParamDto, @UserDec("id") userId: string, @Body() updateDto: RequestOtpDto) {
return this.invoiceService.approveRequest(paramDto.id, userId, updateDto);
}
/**************************************** */
@ApiOperation({ summary: "approve invoice by user" })
@AuthGuards()
@Patch(":id/approve")
approveInvoiceByUser(@Param() paramDto: ParamDto, @UserDec("id") userId: string) {
return this.invoiceService.approveInvoiceByUser(paramDto.id, userId);
approveInvoiceByUser(@Param() paramDto: ParamDto, @UserDec("id") userId: string, @Body() verifyOtpDto: VerifyOtpDto) {
return this.invoiceService.approveInvoiceByUser(paramDto.id, userId, verifyOtpDto);
}
/**************************************** */
+2 -1
View File
@@ -11,10 +11,11 @@ import { UsageDiscount } from "../discounts/entities/usage-discount.entity";
import { DiscountRepository } from "../discounts/repositories/discount.repository";
import { UsageDiscountRepository } from "../discounts/repositories/usage-discount.repository";
import { UsersModule } from "../users/users.module";
import { UtilsModule } from "../utils/utils.module";
import { WalletsModule } from "../wallets/wallets.module";
@Module({
imports: [TypeOrmModule.forFeature([Invoice, InvoiceItem, Discount, UsageDiscount]), UsersModule, WalletsModule],
imports: [TypeOrmModule.forFeature([Invoice, InvoiceItem, Discount, UsageDiscount]), UsersModule, WalletsModule, UtilsModule],
providers: [InvoicesService, InvoicesRepository, DiscountRepository, UsageDiscountRepository],
controllers: [InvoicesController],
exports: [InvoicesService],
@@ -1,16 +1,20 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import { BadRequestException, Injectable, Logger } from "@nestjs/common";
// eslint-disable-next-line import/no-named-as-default
import dayjs from "dayjs";
// eslint-disable-next-line import/no-named-as-default
import Decimal from "decimal.js";
import { DataSource, QueryRunner } from "typeorm";
import { Between, DataSource, QueryRunner } from "typeorm";
import { DiscountMessage, InvoiceMessage, WalletMessage } from "../../../common/enums/message.enum";
import { AuthMessage, DiscountMessage, InvoiceMessage, UserMessage, WalletMessage } from "../../../common/enums/message.enum";
import { RequestOtpDto } from "../../auth/DTO/request-otp.dto";
import { VerifyOtpDto } from "../../auth/DTO/verify-otp.dto";
import { DiscountRepository } from "../../discounts/repositories/discount.repository";
import { UsageDiscountRepository } from "../../discounts/repositories/usage-discount.repository";
import { SubscriptionPlan } from "../../subscriptions/entities/subscription.entity";
import { UsersService } from "../../users/providers/users.service";
import { OTPService } from "../../utils/providers/otp.service";
import { PaginationUtils } from "../../utils/providers/pagination.utils";
import { SmsService } from "../../utils/providers/sms.service";
import { Wallet } from "../../wallets/entities/wallet.entity";
import { WalletsService } from "../../wallets/providers/wallets.service";
import { ApplyDiscountDto } from "../DTO/apply-discount-invoice.dto";
@@ -23,12 +27,16 @@ import { InvoicesRepository } from "../repositories/invoices.repository";
@Injectable()
export class InvoicesService {
private readonly logger = new Logger(InvoicesService.name);
constructor(
private readonly invoiceRepository: InvoicesRepository,
private readonly discountRepository: DiscountRepository,
private readonly usageDiscountRepository: UsageDiscountRepository,
private readonly usersService: UsersService,
private readonly walletsService: WalletsService,
private readonly otpService: OTPService,
private readonly smsService: SmsService,
private readonly dataSource: DataSource,
// private readonly invoiceItemsRepository: InvoiceItemsRepository,
) {}
@@ -69,9 +77,50 @@ export class InvoicesService {
invoice,
};
}
///********************************** */
async approveInvoiceByUser(invoiceId: string, userId: string) {
//********************************** */
async approveRequest(invoiceId: string, userId: string, requestOtpDto: RequestOtpDto) {
const { phone } = requestOtpDto;
const user = await this.usersService.findOneById(userId);
if (!user) throw new BadRequestException(UserMessage.USER_NOT_FOUND);
const invoice = await this.invoiceRepository.findOneBy({ id: invoiceId, user: { id: userId } });
if (!invoice) throw new BadRequestException(InvoiceMessage.NOT_FOUND_BY_ID);
if (invoice.status === InvoiceStatus.APPROVED) throw new BadRequestException(InvoiceMessage.ALREADY_APPROVED);
if (invoice.status === InvoiceStatus.PAID) throw new BadRequestException(InvoiceMessage.INVOICE_ALREADY_PAID);
if (dayjs().isAfter(invoice.dueDate)) throw new BadRequestException(InvoiceMessage.INVOICE_IS_OVERDUE);
if (invoice.status !== InvoiceStatus.PENDING) throw new BadRequestException(InvoiceMessage.INVOICE_CAN_NOT_APPROVED);
const existCode = await this.otpService.checkExistOtp(phone, "LOGIN");
if (existCode) {
return {
message: AuthMessage.OTP_ALREADY_SENT,
ttlSecond: existCode,
};
}
const otpCode = await this.otpService.generateAndSetInCache(phone, "LOGIN");
//
await this.smsService.sendSmsVerifyCode(phone, otpCode);
this.logger.debug(`OTP sent to ${phone}: ${otpCode}`);
return {
message: AuthMessage.OTP_SENT,
otpCode,
};
}
//********************************** */
async approveInvoiceByUser(invoiceId: string, userId: string, verifyOtpDto: VerifyOtpDto) {
const { code, phone } = verifyOtpDto;
const user = await this.checkUserVerifyCredentialWithPhone(phone, code, userId);
if (!user) throw new BadRequestException(InvoiceMessage.INVOICE_CAN_NOT_APPROVED);
const invoice = await this.invoiceRepository.findOneBy({ id: invoiceId, user: { id: userId } });
if (!invoice) throw new BadRequestException(InvoiceMessage.NOT_FOUND_BY_ID);
@@ -309,6 +358,8 @@ export class InvoicesService {
};
}
//*********************************** */
async cancelDiscount(invoiceId: string, userId: string) {
// Find the invoice by ID and ensure it is in a PENDING status
const invoice = await this.invoiceRepository.findOneBy({ id: invoiceId, status: InvoiceStatus.PENDING });
@@ -351,6 +402,19 @@ export class InvoicesService {
};
}
//*********************************** */
async getInvoicesCount() {
const count = await this.invoiceRepository.count({
where: {
createdAt: Between(new Date(new Date().setHours(0, 0, 0, 0)), new Date(new Date().setHours(23, 59, 59, 999))),
},
});
return count;
}
//*********************************** */
private async hasUserUsedDiscount(userId: string, discountId: string): Promise<boolean> {
const usage = await this.usageDiscountRepository.findOne({
where: {
@@ -365,6 +429,23 @@ export class InvoicesService {
return !!usage;
}
//*********************************** */
private async checkUserVerifyCredentialWithPhone(phone: string, otpCode: string, userId: string) {
//TODO: Change key from LOGIN to something else
const isValid = await this.otpService.verifyOtp(phone, otpCode, "LOGIN");
if (!isValid) throw new BadRequestException(AuthMessage.INVALID_OTP);
await this.otpService.delOtpFormCache(phone, "LOGIN");
const { user } = await this.usersService.findOneById(userId);
if (!user) throw new BadRequestException(UserMessage.USER_NOT_FOUND);
return user;
}
//*********************************** */
// async calculateFinalPrice(invoiceId: string): Promise<Decimal> {
// const invoice = await this.invoiceRepository.findOneBy({ id: invoiceId });
// if (!invoice) throw new BadRequestException(InvoiceMessage.NOT_FOUND_BY_ID);
@@ -284,4 +284,140 @@ export class SubscriptionsService {
await queryRunner.release();
}
}
//************************************ */
async getPlanRevenueAverage() {
const currentYear = new Date().getFullYear();
const startOfYear = new Date(currentYear, 0, 1);
const endOfYear = new Date(currentYear, 11, 31);
const result = await this.userSubscriptionsRepository
.createQueryBuilder("userSubscription")
.leftJoin("userSubscription.plan", "plan")
.select("AVG(plan.price)", "averageRevenue")
.where("userSubscription.startDate >= :startDate", { startDate: startOfYear })
.andWhere("userSubscription.startDate <= :endDate", { endDate: endOfYear })
.andWhere("userSubscription.status = :status", { status: SubscriptionStatus.ACTIVE })
.getRawOne();
return Number(result.averageRevenue) || 0;
}
async getPlansSalesCount() {
const currentYear = new Date().getFullYear();
const startOfYear = new Date(currentYear, 0, 1);
const endOfYear = new Date(currentYear, 11, 31);
return await this.userSubscriptionsRepository
.createQueryBuilder("userSubscription")
.where("userSubscription.startDate >= :startDate", { startDate: startOfYear })
.andWhere("userSubscription.startDate <= :endDate", { endDate: endOfYear })
.andWhere("userSubscription.status = :status", { status: SubscriptionStatus.ACTIVE })
.getCount();
}
async getPlansSalesCountByMonthsInYear() {
const now = new Date();
const startOfYear = new Date(now.getFullYear(), 0, 1);
const endOfYear = new Date(now.getFullYear(), 11, 31);
const sales = await this.userSubscriptionsRepository
.createQueryBuilder("userSubscription")
.select("EXTRACT(MONTH FROM userSubscription.startDate)", "month")
.addSelect("COUNT(*)", "count")
.where("userSubscription.startDate >= :startDate", { startDate: startOfYear })
.andWhere("userSubscription.startDate <= :endDate", { endDate: endOfYear })
.andWhere("userSubscription.status = :status", { status: SubscriptionStatus.ACTIVE })
.groupBy("EXTRACT(MONTH FROM userSubscription.startDate)")
.orderBy("month", "ASC")
.getRawMany();
const salesByMonth = Array(12).fill(0);
sales.forEach((sale) => {
const month = parseInt(sale.month) - 1;
salesByMonth[month] = parseInt(sale.count);
});
return salesByMonth;
}
async getPlansSalesCountByDaysInMonth() {
const now = new Date();
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0);
const sales = await this.userSubscriptionsRepository
.createQueryBuilder("userSubscription")
.select("DATE(userSubscription.startDate)", "date")
.addSelect("COUNT(*)", "count")
.where("userSubscription.startDate >= :startDate", { startDate: startOfMonth })
.andWhere("userSubscription.startDate <= :endDate", { endDate: endOfMonth })
.andWhere("userSubscription.status = :status", { status: SubscriptionStatus.ACTIVE })
.groupBy("DATE(userSubscription.startDate)")
.orderBy("date", "ASC")
.getRawMany();
const daysInMonth = endOfMonth.getDate();
const salesByDay = Array(daysInMonth).fill(0);
sales.forEach((sale) => {
const day = new Date(sale.date).getDate() - 1;
salesByDay[day] = parseInt(sale.count);
});
return salesByDay;
}
async getPlansSalesCountByDaysInWeek() {
const now = new Date();
const daysSinceStart = now.getDay(); // Remove the +1 and % 7
const startOfWeek = new Date(now);
startOfWeek.setDate(now.getDate() - daysSinceStart);
const endOfWeek = new Date(startOfWeek);
endOfWeek.setDate(startOfWeek.getDate() + 6);
const sales = await this.userSubscriptionsRepository
.createQueryBuilder("userSubscription")
.select("DATE(userSubscription.startDate)", "date")
.addSelect("COUNT(*)", "count")
.where("userSubscription.startDate >= :startDate", { startDate: startOfWeek })
.andWhere("userSubscription.startDate <= :endDate", { endDate: endOfWeek })
.andWhere("userSubscription.status = :status", { status: SubscriptionStatus.ACTIVE })
.groupBy("DATE(userSubscription.startDate)")
.orderBy("date", "ASC")
.getRawMany();
const salesByDay = Array(7).fill(0);
sales.forEach((sale) => {
const day = new Date(sale.date).getDay(); // Remove the +1 and % 7
salesByDay[day] = parseInt(sale.count);
});
return salesByDay;
}
async getSubscriptionGrowthRate() {
const currentYear = new Date().getFullYear();
const lastYear = currentYear - 1;
const currentYearCount = await this.userSubscriptionsRepository
.createQueryBuilder("userSubscription")
.where("EXTRACT(YEAR FROM userSubscription.startDate) = :year", { year: currentYear })
.andWhere("userSubscription.status = :status", { status: SubscriptionStatus.ACTIVE })
.getCount();
const lastYearCount = await this.userSubscriptionsRepository
.createQueryBuilder("userSubscription")
.where("EXTRACT(YEAR FROM userSubscription.startDate) = :year", { year: lastYear })
.andWhere("userSubscription.status = :status", { status: SubscriptionStatus.ACTIVE })
.getCount();
if (lastYearCount === 0) return 100;
const growthRate = ((currentYearCount - lastYearCount) / lastYearCount) * 100;
return Math.round(growthRate * 100) / 100;
}
}
@@ -307,6 +307,17 @@ export class TicketsService {
}
//******************************** */
async getUnreadTickets() {
const unreadTickets = await this.ticketsRepository.count({
where: {
status: TicketStatus.PENDING,
},
});
return unreadTickets;
}
//******************************** */
}
// async getTickets(queryDto: SearchTicketQueryDto, userId: string) {
@@ -638,6 +638,21 @@ export class UsersService {
};
}
/************************************************************ */
async getCustomersCount() {
const count = await this.userRepository.count({
where: {
roles: {
name: RoleEnum.USER,
},
},
});
return count;
}
/************************************************************ */
private async createEmailHashLink(userId: string) {
const secret = this.configService.getOrThrow<string>("EMAIL_SECRET");
const timestamp = Date.now();