chore: add new service to add subs to danak services in array
This commit is contained in:
@@ -8,6 +8,7 @@ import { RoleEnum } from "../../users/enums/role.enum";
|
||||
import { UsersService } from "../../users/providers/users.service";
|
||||
import { OTPService } from "../../utils/providers/otp.service";
|
||||
import { PasswordService } from "../../utils/providers/password.service";
|
||||
import { SmsService } from "../../utils/providers/sms.service";
|
||||
import { CompleteRegistrationDto } from "../DTO/complete-register.dto";
|
||||
import { CheckUserExistDto, LoginPasswordDTO } from "../DTO/loginPassword.dto";
|
||||
import { RequestOtpDto } from "../DTO/request-otp.dto";
|
||||
@@ -24,6 +25,7 @@ export class AuthService {
|
||||
private readonly tokensService: TokensService,
|
||||
private readonly dataSource: DataSource,
|
||||
private readonly notificationService: NotificationsService,
|
||||
private readonly smsService: SmsService,
|
||||
) {}
|
||||
//****************** */
|
||||
//****************** */
|
||||
@@ -40,7 +42,8 @@ export class AuthService {
|
||||
};
|
||||
}
|
||||
const otpCode = await this.otpService.generateAndSetInCache(phone, "REGISTER");
|
||||
// await SmsService.sendOtp(phone, otpCode);
|
||||
//
|
||||
await this.smsService.sendSmsVerifyCode(phone, otpCode);
|
||||
this.logger.debug(`OTP sent to ${phone}: ${otpCode}`);
|
||||
|
||||
return {
|
||||
@@ -142,7 +145,8 @@ export class AuthService {
|
||||
}
|
||||
|
||||
const otpCode = await this.otpService.generateAndSetInCache(phone, "LOGIN");
|
||||
// await SmsService.sendOtp(phone, otpCode);
|
||||
//
|
||||
await this.smsService.sendSmsVerifyCode(phone, otpCode);
|
||||
this.logger.debug(`OTP sent to ${phone}: ${otpCode}`);
|
||||
|
||||
return {
|
||||
|
||||
@@ -9,6 +9,7 @@ import { DanakServicesService } from "./providers/danak-services.service";
|
||||
import { AuthGuards } from "../../common/decorators/auth-guard.decorator";
|
||||
import { Pagination } from "../../common/decorators/pagination.decorator";
|
||||
import { Roles } from "../../common/decorators/roles.decorator";
|
||||
import { UserDec } from "../../common/decorators/user.decorator";
|
||||
import { ParamDto } from "../../common/DTO/param.dto";
|
||||
import { RoleEnum } from "../users/enums/role.enum";
|
||||
|
||||
@@ -44,7 +45,7 @@ export class DanakServicesController {
|
||||
}
|
||||
|
||||
@AuthGuards()
|
||||
@Roles(RoleEnum.USER)
|
||||
@Roles(RoleEnum.USER, RoleEnum.ADMIN)
|
||||
@ApiOperation({ summary: "Get all service categories user side" })
|
||||
@Get("categories/public")
|
||||
getCategoriesUserSide() {
|
||||
@@ -52,7 +53,7 @@ export class DanakServicesController {
|
||||
}
|
||||
|
||||
@AuthGuards()
|
||||
@Roles(RoleEnum.USER)
|
||||
@Roles(RoleEnum.USER, RoleEnum.ADMIN)
|
||||
@ApiOperation({ summary: "get category services with category id" })
|
||||
@Get("categories/:id/services")
|
||||
getCategoryServices(@Param() paramDto: ParamDto) {
|
||||
@@ -103,10 +104,10 @@ export class DanakServicesController {
|
||||
|
||||
@ApiOperation({ summary: "get danak service by id" })
|
||||
@AuthGuards()
|
||||
@Roles(RoleEnum.USER)
|
||||
@Roles(RoleEnum.USER, RoleEnum.ADMIN)
|
||||
@Get(":id")
|
||||
getDanakServiceById(@Param() paramDto: ParamDto) {
|
||||
return this.danakServicesService.getDanakServiceByID(paramDto.id);
|
||||
getDanakServiceById(@Param() paramDto: ParamDto, @UserDec("role") userRole: RoleEnum) {
|
||||
return this.danakServicesService.getDanakServiceByIdWithSubs(paramDto.id, userRole);
|
||||
}
|
||||
|
||||
// @AuthGuards()
|
||||
|
||||
@@ -25,5 +25,5 @@ export class DanakServiceCategory extends BaseEntity {
|
||||
parentId: string | null;
|
||||
|
||||
@OneToMany(() => DanakService, (danakService) => danakService.category)
|
||||
danakService: DanakService[];
|
||||
danakServices: DanakService[];
|
||||
}
|
||||
|
||||
@@ -14,6 +14,9 @@ export class DanakService extends BaseEntity {
|
||||
@Column({ type: "varchar", length: 100, nullable: false, unique: true })
|
||||
name: string;
|
||||
|
||||
@Column({ type: "varchar", length: 150, nullable: true })
|
||||
title: string;
|
||||
|
||||
@Column({ type: "boolean", nullable: false, default: false })
|
||||
isDanakSuggest: boolean;
|
||||
|
||||
@@ -47,7 +50,7 @@ export class DanakService extends BaseEntity {
|
||||
@Column({ type: "varchar", length: 255, nullable: false })
|
||||
icon: string;
|
||||
|
||||
@ManyToOne(() => DanakServiceCategory, (danakServiceCategory) => danakServiceCategory.danakService, {
|
||||
@ManyToOne(() => DanakServiceCategory, (danakServiceCategory) => danakServiceCategory.danakServices, {
|
||||
nullable: false,
|
||||
onDelete: "RESTRICT",
|
||||
})
|
||||
|
||||
@@ -3,6 +3,7 @@ import { FindOptionsWhere, In, IsNull } from "typeorm";
|
||||
|
||||
import { ParamDto } from "../../../common/DTO/param.dto";
|
||||
import { CategoryMessage, CommonMessage, ServiceMessage } from "../../../common/enums/message.enum";
|
||||
import { RoleEnum } from "../../users/enums/role.enum";
|
||||
import { PaginationUtils } from "../../utils/providers/pagination.utils";
|
||||
import { CategoryListSearchQueryDto, CategorySearchQueryDto } from "../DTO/category-search-query.dto";
|
||||
import { CreateCategoryDto } from "../DTO/create-category.dto";
|
||||
@@ -92,9 +93,9 @@ export class DanakServicesService {
|
||||
|
||||
async getCategoryServices(categoryId: string) {
|
||||
const category = await this.danakServicesCategoryRepository.findOne({
|
||||
where: { id: categoryId },
|
||||
where: { id: categoryId, isActive: true, danakServices: { isActive: true } },
|
||||
relations: {
|
||||
danakService: true,
|
||||
danakServices: true,
|
||||
},
|
||||
order: { createdAt: "DESC" },
|
||||
});
|
||||
@@ -172,9 +173,9 @@ export class DanakServicesService {
|
||||
}
|
||||
/******************************************** */
|
||||
|
||||
async getDanakServiceByID(serviceId: string) {
|
||||
async getDanakServiceByIdWithSubs(serviceId: string, role: RoleEnum) {
|
||||
const danakService = await this.danakServicesRepository.findOne({
|
||||
where: { id: serviceId, isActive: true },
|
||||
where: { id: serviceId, ...(role !== RoleEnum.ADMIN && { isActive: true, subscriptionPlans: { isActive: true } }) },
|
||||
relations: { images: true, subscriptionPlans: true },
|
||||
});
|
||||
if (!danakService) throw new BadRequestException(ServiceMessage.SERVICE_NOT_FOUND_BY_ID);
|
||||
|
||||
@@ -25,6 +25,7 @@ export class DanakServicesRepository extends Repository<DanakService> {
|
||||
|
||||
const queryBuilder = this.createQueryBuilder("service")
|
||||
.leftJoinAndSelect("service.category", "category")
|
||||
.loadRelationCountAndMap("service.subscriptionCount", "service.subscriptionPlans")
|
||||
.orderBy("service.createdAt", "DESC")
|
||||
.skip(skip)
|
||||
.take(limit);
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { IsBoolean, IsInt, IsNotEmpty, IsString, IsUUID, Length, Min } from "class-validator";
|
||||
import { Type } from "class-transformer";
|
||||
import { ArrayMinSize, IsArray, IsBoolean, IsInt, IsNotEmpty, IsString, IsUUID, Length, Min, ValidateNested } from "class-validator";
|
||||
|
||||
import { SubscriptionMessage } from "../../../common/enums/message.enum";
|
||||
|
||||
export class CreateSubscriptionPlanDto {
|
||||
export class SubscriptionPlanDto {
|
||||
@IsNotEmpty({ message: SubscriptionMessage.NAME_REQUIRED })
|
||||
@IsString({ message: SubscriptionMessage.NAME_SHOULD_BE_STRING })
|
||||
@Length(3, 100, { message: SubscriptionMessage.NAME_LENGTH })
|
||||
@@ -25,6 +26,18 @@ export class CreateSubscriptionPlanDto {
|
||||
@IsBoolean({ message: SubscriptionMessage.IS_ACTIVE_SHOULD_BE_BOOLEAN })
|
||||
@ApiProperty({ description: "the status of the subscription plan", example: true })
|
||||
isActive: boolean;
|
||||
}
|
||||
|
||||
export class AddSubscriptionsToServiceDto {
|
||||
@IsNotEmpty({ message: SubscriptionMessage.SUBS_REQUIRED })
|
||||
@IsArray({ message: SubscriptionMessage.SUBS_SHOULD_BE_ARRAY })
|
||||
@ArrayMinSize(1, { message: SubscriptionMessage.SUBS_MIN_SIZE })
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => SubscriptionPlanDto)
|
||||
@ApiProperty({
|
||||
type: [SubscriptionPlanDto],
|
||||
})
|
||||
subs: SubscriptionPlanDto[];
|
||||
|
||||
@IsNotEmpty({ message: SubscriptionMessage.SERVICE_REQUIRED })
|
||||
@IsUUID("4", { message: SubscriptionMessage.SERVICE_MUST_BE_UUID })
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { Type } from "class-transformer";
|
||||
import { IsOptional, IsString } from "class-validator";
|
||||
|
||||
import { PaginationDto } from "../../../common/DTO/pagination.dto";
|
||||
import { SubscriptionMessage } from "../../../common/enums/message.enum";
|
||||
|
||||
export class ServiceSubsQueryDto extends PaginationDto {
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
// @IsBoolean({ message: CategoryMessage.IS_ACTIVE_SHOULD_BE_BOOLEAN })
|
||||
@ApiPropertyOptional({ description: "Category status", example: 1 })
|
||||
isActive?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString({ message: SubscriptionMessage.SEARCH_QUERY_STRING })
|
||||
@ApiPropertyOptional({ description: "Search query", example: "search query" })
|
||||
q?: string;
|
||||
}
|
||||
@@ -1,5 +1,12 @@
|
||||
import { PartialType } from "@nestjs/swagger";
|
||||
import { ApiProperty, PartialType } from "@nestjs/swagger";
|
||||
import { IsNotEmpty, IsUUID } from "class-validator";
|
||||
|
||||
import { CreateSubscriptionPlanDto } from "./create-subscription.dto";
|
||||
import { SubscriptionPlanDto } from "./create-subscription.dto";
|
||||
import { SubscriptionMessage } from "../../../common/enums/message.enum";
|
||||
|
||||
export class UpdateSubscriptionPlanDto extends PartialType(CreateSubscriptionPlanDto) {}
|
||||
export class UpdateSubscriptionPlanDto extends PartialType(SubscriptionPlanDto) {
|
||||
@IsNotEmpty({ message: SubscriptionMessage.SERVICE_REQUIRED })
|
||||
@IsUUID("4", { message: SubscriptionMessage.SERVICE_MUST_BE_UUID })
|
||||
@ApiProperty({ description: "Service ID", example: "d290f1ee-6c54-4b01-90e6-d701748f0851" })
|
||||
serviceId: string;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
// eslint-disable-next-line import/no-named-as-default
|
||||
import Decimal from "decimal.js";
|
||||
import { Column, Entity, ManyToOne } from "typeorm";
|
||||
import { Column, Entity, Index, ManyToOne } from "typeorm";
|
||||
|
||||
import { BaseEntity } from "../../../common/entities/base.entity";
|
||||
import { DecimalTransformer } from "../../../common/transformers/decimal.transformer";
|
||||
import { DanakService } from "../../danak-services/entities/danak-service.entity";
|
||||
|
||||
@Entity()
|
||||
@Index(["service", "name"], { unique: true })
|
||||
export class SubscriptionPlan extends BaseEntity {
|
||||
@Column({ type: "varchar", length: 150, nullable: false, unique: true })
|
||||
@Column({ type: "varchar", length: 150, nullable: false })
|
||||
name: string;
|
||||
|
||||
@Column({ type: "int", nullable: false })
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
// eslint-disable-next-line import/no-named-as-default
|
||||
import Decimal from "decimal.js";
|
||||
import { DataSource } from "typeorm";
|
||||
import { DataSource, In } from "typeorm";
|
||||
|
||||
import { ServiceMessage, SubscriptionMessage, WalletMessage } from "../../../common/enums/message.enum";
|
||||
import { DanakServicesService } from "../../danak-services/providers/danak-services.service";
|
||||
import { InvoicesService } from "../../invoices/providers/invoices.service";
|
||||
import { UsersService } from "../../users/providers/users.service";
|
||||
import { PaginationUtils } from "../../utils/providers/pagination.utils";
|
||||
import { Wallet } from "../../wallets/entities/wallet.entity";
|
||||
import { WalletsService } from "../../wallets/providers/wallets.service";
|
||||
import { CreateSubscriptionPlanDto } from "../DTO/create-subscription.dto";
|
||||
import { AddSubscriptionsToServiceDto } from "../DTO/create-subscription.dto";
|
||||
import { ServiceSubsQueryDto } from "../DTO/service-subs-query.dto";
|
||||
import { SubscribeServiceDto } from "../DTO/subscribe-service.dto";
|
||||
import { UpdateSubscriptionPlanDto } from "../DTO/update-subscription.dto";
|
||||
import { SubscriptionPlan } from "../entities/subscription.entity";
|
||||
@@ -31,18 +33,29 @@ export class SubscriptionsService {
|
||||
) {}
|
||||
|
||||
//************************************ */
|
||||
async createSubscriptionsPlan(createDto: CreateSubscriptionPlanDto) {
|
||||
async createSubscriptionsPlan(createDto: AddSubscriptionsToServiceDto) {
|
||||
const danakService = await this.danakServices.findServiceById(createDto.serviceId);
|
||||
if (!danakService) throw new BadRequestException(ServiceMessage.SERVICE_NOT_FOUND_BY_ID);
|
||||
|
||||
const existSubscription = await this.subscriptionsPlanRepository.findOneByName(createDto.name);
|
||||
if (existSubscription) throw new BadRequestException(SubscriptionMessage.NAME_EXIST);
|
||||
const subscriptions = createDto.subs.map((sub) => ({ ...sub, service: { id: createDto.serviceId } }));
|
||||
|
||||
const subscriptionNames = createDto.subs.map((sub) => sub.name);
|
||||
const existingSubscriptions = await this.subscriptionsPlanRepository.find({
|
||||
where: {
|
||||
name: In(subscriptionNames),
|
||||
service: { id: createDto.serviceId },
|
||||
},
|
||||
});
|
||||
|
||||
if (existingSubscriptions.length > 0)
|
||||
throw new BadRequestException({ message: [SubscriptionMessage.NAME_EXIST, existingSubscriptions] });
|
||||
|
||||
const createdSubscriptions = this.subscriptionsPlanRepository.create(subscriptions);
|
||||
await this.subscriptionsPlanRepository.save(createdSubscriptions);
|
||||
|
||||
const subscription = this.subscriptionsPlanRepository.create({ ...createDto, service: { id: createDto.serviceId } });
|
||||
await this.subscriptionsPlanRepository.save(subscription);
|
||||
return {
|
||||
message: SubscriptionMessage.CREATED,
|
||||
subscription,
|
||||
subscriptions: createdSubscriptions,
|
||||
};
|
||||
}
|
||||
//************************************ */
|
||||
@@ -82,15 +95,51 @@ export class SubscriptionsService {
|
||||
}
|
||||
//************************************ */
|
||||
|
||||
async getSubscriptionsPlans() {
|
||||
const subscriptions = await this.subscriptionsPlanRepository.find({ relations: ["service"] });
|
||||
async getServiceSubscriptions(serviceId: string, queryDto: ServiceSubsQueryDto) {
|
||||
const service = await this.danakServices.findServiceById(serviceId);
|
||||
|
||||
const { limit, skip } = PaginationUtils(queryDto);
|
||||
|
||||
const queryBuilder = this.subscriptionsPlanRepository
|
||||
.createQueryBuilder("subscription")
|
||||
.leftJoin("subscription.service", "service")
|
||||
.addSelect(["service.id"])
|
||||
.where("service.id = :serviceId", { serviceId });
|
||||
|
||||
if (queryDto.q) {
|
||||
queryBuilder.andWhere("subscription.name ILIKE :query", { query: `%${queryDto.q}%` });
|
||||
}
|
||||
|
||||
if (queryDto.isActive !== undefined) {
|
||||
queryBuilder.andWhere("subscription.isActive = :isActive", { isActive: queryDto.isActive === 1 });
|
||||
}
|
||||
|
||||
const [subscriptions, count] = await queryBuilder.skip(skip).take(limit).getManyAndCount();
|
||||
|
||||
return {
|
||||
service,
|
||||
subscriptions,
|
||||
count,
|
||||
pagination: true,
|
||||
};
|
||||
}
|
||||
|
||||
//************************************ */
|
||||
|
||||
async toggleSubStatus(subId: string) {
|
||||
const subscription = await this.subscriptionsPlanRepository.findOneBy({ id: subId });
|
||||
if (!subscription) throw new BadRequestException(SubscriptionMessage.NOT_FOUND);
|
||||
|
||||
subscription.isActive = !subscription.isActive;
|
||||
|
||||
await this.subscriptionsPlanRepository.save(subscription);
|
||||
return {
|
||||
message: SubscriptionMessage.STATUS_UPDATED,
|
||||
isActive: subscription.isActive,
|
||||
};
|
||||
}
|
||||
//************************************ */
|
||||
|
||||
async subscribeToPlan(serviceId: string, subscribeDto: SubscribeServiceDto, userId: string) {
|
||||
const queryRunner = this.dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { Body, Controller, Get, Param, Patch, Post } from "@nestjs/common";
|
||||
import { Body, Controller, Get, Param, Patch, Post, Query } from "@nestjs/common";
|
||||
import { ApiOperation } from "@nestjs/swagger";
|
||||
|
||||
import { CreateSubscriptionPlanDto } from "./DTO/create-subscription.dto";
|
||||
import { AddSubscriptionsToServiceDto } from "./DTO/create-subscription.dto";
|
||||
import { ServiceIdParamDto } from "./DTO/service-id.param.dto";
|
||||
import { ServiceSubsQueryDto } from "./DTO/service-subs-query.dto";
|
||||
import { SubscribeServiceDto } from "./DTO/subscribe-service.dto";
|
||||
import { UpdateSubscriptionPlanDto } from "./DTO/update-subscription.dto";
|
||||
import { SubscriptionsService } from "./providers/subscriptions.service";
|
||||
@@ -20,16 +21,24 @@ export class SubscriptionsController {
|
||||
@AuthGuards()
|
||||
@Roles(RoleEnum.ADMIN)
|
||||
@Post()
|
||||
createSubscription(@Body() createDto: CreateSubscriptionPlanDto) {
|
||||
createSubscription(@Body() createDto: AddSubscriptionsToServiceDto) {
|
||||
return this.subscriptionService.createSubscriptionsPlan(createDto);
|
||||
}
|
||||
|
||||
@ApiOperation({ summary: "get all subscription plans" })
|
||||
@AuthGuards()
|
||||
@Roles(RoleEnum.ADMIN)
|
||||
@Get()
|
||||
getAllSubscriptions() {
|
||||
return this.subscriptionService.getSubscriptionsPlans();
|
||||
@Get("service/:serviceId")
|
||||
getServiceSubscriptions(@Param() paramDto: ServiceIdParamDto, @Query() queryDto: ServiceSubsQueryDto) {
|
||||
return this.subscriptionService.getServiceSubscriptions(paramDto.serviceId, queryDto);
|
||||
}
|
||||
|
||||
@ApiOperation({ summary: "toggle status of service subs" })
|
||||
@AuthGuards()
|
||||
@Roles(RoleEnum.ADMIN)
|
||||
@Post("toggle-status/:id")
|
||||
toggleStatusOfServiceSub(@Param() paramDto: ParamDto) {
|
||||
return this.subscriptionService.toggleSubStatus(paramDto.id);
|
||||
}
|
||||
|
||||
@ApiOperation({ summary: "get a subscription plan by id" })
|
||||
|
||||
@@ -1,18 +1,28 @@
|
||||
export interface ISmsBody {
|
||||
ParameterArray: IParameterArray[];
|
||||
export interface IParameterArray {
|
||||
name: TemplateParams;
|
||||
value: string;
|
||||
}
|
||||
export interface ISmsResponse {
|
||||
status: number;
|
||||
message: string;
|
||||
}
|
||||
//----------------------------------------------
|
||||
|
||||
export interface ISmsGetLineResponse extends ISmsResponse {
|
||||
data: string[];
|
||||
}
|
||||
|
||||
export interface ISmsVerifyResponse extends ISmsResponse {
|
||||
data: { MessageId: number; Cost: number };
|
||||
}
|
||||
|
||||
//----------------------------------------------
|
||||
export interface ISmsVerifyBody {
|
||||
Parameters: IParameterArray[];
|
||||
Mobile: string;
|
||||
TemplateId: string;
|
||||
UserApiKey: string;
|
||||
SecretKey: string;
|
||||
}
|
||||
|
||||
export interface IParameterArray {
|
||||
Parameter: string;
|
||||
ParameterValue: string;
|
||||
}
|
||||
// export type SmsBodyType = ISmsVerifyBody;
|
||||
|
||||
export interface ISmsResponse {
|
||||
VerificationCodeId: number;
|
||||
isSuccessful: boolean;
|
||||
Message: string;
|
||||
}
|
||||
export type TemplateParams = "Code";
|
||||
|
||||
@@ -1,22 +1,27 @@
|
||||
import { Injectable, Logger } from "@nestjs/common";
|
||||
import { MailerService } from "@nestjs-modules/mailer";
|
||||
|
||||
import { EmailMessage } from "../../../common/enums/message.enum";
|
||||
|
||||
@Injectable()
|
||||
export class EmailService {
|
||||
private readonly logger = new Logger(EmailService.name);
|
||||
constructor(private readonly mailerService: MailerService) {}
|
||||
|
||||
async sendEmail(to: string, subject: string) {
|
||||
async sendEmail(to: string, subject: string, link: string, fullName: string) {
|
||||
try {
|
||||
await this.mailerService.sendMail({
|
||||
const emailInfo = await this.mailerService.sendMail({
|
||||
to: to,
|
||||
from: "noreply@nestjs.com",
|
||||
// from: "noreply@nestjs.com",
|
||||
subject: subject,
|
||||
template: "otp",
|
||||
template: "email-verify",
|
||||
context: {
|
||||
//Data to be sent to template
|
||||
title: EmailMessage.EMAIL_VERIFICATION,
|
||||
link,
|
||||
fullName,
|
||||
},
|
||||
});
|
||||
return emailInfo;
|
||||
} catch (error) {
|
||||
this.logger.error("Email sending failed:", error);
|
||||
return false;
|
||||
|
||||
@@ -1,36 +1,76 @@
|
||||
import { Inject, Injectable, Logger } from "@nestjs/common";
|
||||
import axios from "axios";
|
||||
import { HttpService } from "@nestjs/axios";
|
||||
import { Inject, Injectable, InternalServerErrorException, Logger } from "@nestjs/common";
|
||||
import { AxiosError } from "axios";
|
||||
import { catchError, firstValueFrom } from "rxjs";
|
||||
|
||||
import { ISmsConfigs } from "../../../configs/sms.config";
|
||||
import { SMS_CONFIG } from "../constants";
|
||||
import { ISmsBody } from "../interfaces/ISms";
|
||||
import { ISmsGetLineResponse, ISmsVerifyBody, ISmsVerifyResponse } from "../interfaces/ISms";
|
||||
|
||||
@Injectable()
|
||||
export class SmsService {
|
||||
private logger = new Logger(SmsService.name);
|
||||
constructor(@Inject(SMS_CONFIG) private smsConfigs: ISmsConfigs) {}
|
||||
private readonly logger = new Logger(SmsService.name);
|
||||
|
||||
constructor(
|
||||
@Inject(SMS_CONFIG) private smsConfigs: ISmsConfigs,
|
||||
private readonly httpService: HttpService,
|
||||
) {}
|
||||
//************************************************* */
|
||||
|
||||
async sendSmsVerifyCode(mobile: string, otpCode: string) {
|
||||
const smsData: ISmsBody = {
|
||||
ParameterArray: [{ Parameter: "otp", ParameterValue: otpCode }],
|
||||
//
|
||||
const smsData: ISmsVerifyBody = {
|
||||
Parameters: [{ name: "Code", value: otpCode }],
|
||||
Mobile: mobile,
|
||||
TemplateId: this.smsConfigs.SMS_PATTERN_OTP,
|
||||
...this.smsConfigs.SMS_SECRET_BODY,
|
||||
};
|
||||
|
||||
return this.sendSms(smsData);
|
||||
}
|
||||
|
||||
private async sendSms(body: ISmsBody) {
|
||||
//
|
||||
try {
|
||||
const { data } = await axios.post(this.smsConfigs.URL, body, {
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
const { data } = await firstValueFrom(
|
||||
this.httpService
|
||||
.post<ISmsVerifyResponse>(
|
||||
`${this.smsConfigs.API_URL}/send/verify`,
|
||||
{ smsData },
|
||||
{
|
||||
headers: { "X-API-KEY": this.smsConfigs.API_KEY },
|
||||
},
|
||||
)
|
||||
.pipe(
|
||||
catchError((err: AxiosError) => {
|
||||
this.logger.error("error in sending verify sms", err);
|
||||
throw new InternalServerErrorException("error in sending verify sms");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return data;
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
this.logger.error("error in sending sms", error);
|
||||
}
|
||||
}
|
||||
|
||||
//************************************************* */
|
||||
|
||||
async getSmsLines() {
|
||||
try {
|
||||
const { data } = await firstValueFrom(
|
||||
this.httpService
|
||||
.get<ISmsGetLineResponse>(`${this.smsConfigs.API_URL}/lines`, {
|
||||
headers: { "X-API-KEY": this.smsConfigs.API_KEY },
|
||||
})
|
||||
.pipe(
|
||||
catchError((error: AxiosError) => {
|
||||
this.logger.error("error in getting sms lines", error);
|
||||
throw new InternalServerErrorException("error in getting sms lines");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return data;
|
||||
} catch (error) {
|
||||
this.logger.error("error in getting sms lines", error);
|
||||
}
|
||||
}
|
||||
|
||||
//************************************************* */
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Module } from "@nestjs/common";
|
||||
|
||||
import { S3_CONFIG, SMS_CONFIG } from "./constants";
|
||||
import { CacheService } from "./providers/cache.service";
|
||||
import { EmailService } from "./providers/email.service";
|
||||
import { OTPService } from "./providers/otp.service";
|
||||
import { PasswordService } from "./providers/password.service";
|
||||
import { S3Service } from "./providers/s3.service";
|
||||
@@ -11,6 +12,7 @@ import { smsConfigs } from "../../configs/sms.config";
|
||||
|
||||
@Module({
|
||||
providers: [
|
||||
EmailService,
|
||||
OTPService,
|
||||
PasswordService,
|
||||
CacheService,
|
||||
@@ -27,6 +29,6 @@ import { smsConfigs } from "../../configs/sms.config";
|
||||
inject: S3Configs().inject,
|
||||
},
|
||||
],
|
||||
exports: [SMS_CONFIG, S3_CONFIG, S3Service, OTPService, PasswordService, CacheService, SmsService],
|
||||
exports: [SMS_CONFIG, S3_CONFIG, S3Service, OTPService, PasswordService, CacheService, SmsService, EmailService],
|
||||
})
|
||||
export class UtilsModule {}
|
||||
|
||||
Reference in New Issue
Block a user