Files
dsc-api/src/modules/dpage/dpage.service.ts
T
2026-03-15 14:15:03 +03:30

150 lines
5.0 KiB
TypeScript

import { BadRequestException, HttpException, Injectable, Logger } from "@nestjs/common";
import { HttpService } from "@nestjs/axios";
import { Inject } from "@nestjs/common";
import { AxiosError } from "axios";
import { catchError, firstValueFrom, throwError } from "rxjs";
import { SubscriptionsService } from "../subscriptions/providers/subscriptions.service";
import { IDPageConfig } from "../../configs/dpage.config";
import { LoginDto } from './dto/login.dto';
import { DPAGE_CONFIG } from "./constants";
import { FindBusinessesDto } from "./dto/find-businesses.dto";
@Injectable()
export class DPageService {
private readonly logger = new Logger(DPageService.name);
constructor(
@Inject(DPAGE_CONFIG) private readonly config: IDPageConfig,
private readonly httpService: HttpService,
private readonly subscriptionService: SubscriptionsService,
) { }
private getHeaders(): Record<string, string> {
const credentials = Buffer.from(`${this.config.username}:${this.config.password}`).toString("base64");
return {
"Content-Type": "application/json",
Authorization: `Basic ${credentials}`,
};
}
async findAll(dto: FindBusinessesDto) {
try {
// 2. Login with userSubscriptionId
const { data } = await firstValueFrom(
this.httpService
.get(`${this.config.baseUrl}/super-admin/business/list`,
{
params: dto,
headers: this.getHeaders(),
})
.pipe(
catchError((err: AxiosError) => {
this.logger.error(`Failed to perform direct login: ${err.message}`, err.stack);
return throwError(() => err);
}),
),
);
return data;
} catch (error: unknown) {
if (error instanceof AxiosError && error.response) {
this.logger.error(`External API error response:`, error.response.data);
const errorResponse = {
...error.response.data,
message: error.response.data.error?.message || error.message,
};
throw new HttpException(errorResponse, error.response.status);
}
this.logger.error(`Error performing direct login: ${error instanceof Error ? error.message : "Unknown error"}`);
throw error;
}
}
async setupDpageAccount(dto: SetupAccountDto) {
try {
const { data } = await firstValueFrom(
this.httpService
.post(`${this.config.baseUrl}/super-admin/business/setup`, dto,
{
headers: this.getHeaders(),
})
.pipe(
catchError((err: AxiosError) => {
this.logger.error(`Failed to perform setup account: ${err.message}`, err.stack);
return throwError(() => err);
}),
),
);
return data;
} catch (error: unknown) {
if (error instanceof AxiosError && error.response) {
this.logger.error(`External API error response:`, error.response.data);
const errorResponse = {
...error.response.data,
message: error.response.data.error?.message || error.message,
};
throw new HttpException(errorResponse, error.response.status);
}
this.logger.error(`Error performing setup account: ${error instanceof Error ? error.message : "Unknown error"}`);
throw error;
}
}
remove(id: number) {
return `This action removes a #${id} dpage`;
}
async loginToDpage(dto: LoginDto, userId: string) {
const { userSubscriptionId } = dto
// 1. validate userSubscription by id
const userSubscription = await this.subscriptionService.findOneOrFail(userSubscriptionId)
if (userSubscription.user.id !== userId) {
throw new BadRequestException("this subscription doesnt belongs to you")
}
try {
// 2. Login with userSubscriptionId
const { data } = await firstValueFrom(
this.httpService
.post(`${this.config.baseUrl}/super-admin/auth/direct-login`, {
subscriptionId: userSubscriptionId
}, {
headers: this.getHeaders(),
})
.pipe(
catchError((err: AxiosError) => {
this.logger.error(`Failed to perform direct login: ${err.message}`, err.stack);
return throwError(() => err);
}),
),
);
return data;
} catch (error: unknown) {
if (error instanceof AxiosError && error.response) {
this.logger.error(`External API error response:`, error.response.data);
const errorResponse = {
...error.response.data,
message: error.response.data.error?.message || error.message,
};
throw new HttpException(errorResponse, error.response.status);
}
this.logger.error(`Error performing direct login: ${error instanceof Error ? error.message : "Unknown error"}`);
throw error;
}
}
}
export class SetupAccountDto {
danakSubscriptionId: string;
name: string;
slug: string;
phone: string;
firstName: string;
lastName: string;
maxCataloguesCount: number
}