Files
shop-api/src/modules/admin/admin.service.ts
T
mahyargdz be82059172 first
2025-09-14 15:15:03 +03:30

235 lines
9.4 KiB
TypeScript

import { compare, hash } from "bcrypt";
import { inject, injectable } from "inversify";
import { LoginPassDTO } from "./DTO/loginPassword.dto";
import { AdminMessage, AuthMessage, CommonMessage, ContractMessage, RoleMessage, ShopMessage } from "../../common/enums/message.enum";
import { TokenService } from "../token/token.service";
import { ChangePasswordDTO } from "./DTO/changePassword.dto";
import { CreateContractDTO, UpdateContractDTO } from "./DTO/contract.dto";
import { CreateAdminDTO } from "./DTO/createAdmin.dto";
import { CreateRoleDTO } from "./DTO/createRole.dto";
import { AdminRepository } from "./repository/admin";
import { ContractRepository } from "./repository/contract";
import { BannerRepository, SliderRepository } from "./repository/media";
import { PermissionRepository } from "./repository/permission";
import { RoleRepository } from "./repository/role";
import { BadRequestError } from "../../core/app/app.errors";
import { IOCTYPES } from "../../IOC/ioc.types";
import { BrandService } from "../brand/brand.service";
import { OrderService } from "../order/order.service";
import { ProductService } from "../product/providers/product.service";
import { SellerService } from "../seller/seller.service";
import { OwnerRef } from "../shop/models/Abstraction/IShop";
import { ShopRepo } from "../shop/shop.repository";
import { UserService } from "../user/user.service";
import { WalletService } from "../wallet/wallet.service";
import { WarrantyService } from "../warranty/warranty.service";
import { RoleEnum } from "./models/Abstraction/IRole";
@injectable()
class AdminService {
@inject(IOCTYPES.AdminRepository) adminRepo: AdminRepository;
@inject(IOCTYPES.RoleRepository) roleRepo: RoleRepository;
@inject(IOCTYPES.PermissionRepository) permissionRepo: PermissionRepository;
@inject(IOCTYPES.TokenService) tokenService: TokenService;
@inject(IOCTYPES.SliderRepository) sliderRepo: SliderRepository;
@inject(IOCTYPES.BannerRepository) bannerRepo: BannerRepository;
@inject(IOCTYPES.ContractRepository) contractRepo: ContractRepository;
@inject(IOCTYPES.OrderService) private orderService: OrderService;
@inject(IOCTYPES.WalletService) private walletService: WalletService;
@inject(IOCTYPES.ProductService) private productService: ProductService;
@inject(IOCTYPES.SellerService) private sellerService: SellerService;
@inject(IOCTYPES.UserService) private userService: UserService;
@inject(IOCTYPES.BrandService) private brandService: BrandService;
@inject(IOCTYPES.WarrantyService) private warrantyService: WarrantyService;
@inject(IOCTYPES.ShopRepo) private shopRepo: ShopRepo;
async loginPasswordS(loginDto: LoginPassDTO) {
const { password, email } = loginDto;
const admin = await this.adminRepo.findByEmail(email);
if (!admin) throw new BadRequestError(AuthMessage.EmailOrPasswordInc);
console.log(admin);
const passMatch = await this.comparePassword(password, admin.password);
if (!passMatch) throw new BadRequestError(AuthMessage.EmailOrPasswordInc);
const tokens = await this.tokenService.generateAuthTokens({ sub: admin._id.toString() });
return {
message: AuthMessage.SuccessLogin,
...tokens,
};
}
async profileS(adminId: string) {
const admin = await this.adminRepo.model.findOne({ _id: adminId }, { password: 0, role: 0 });
if (!admin) throw new BadRequestError(CommonMessage.NotFound);
return { admin };
}
async changePasswordS(changePasswordDto: ChangePasswordDTO) {
const { email, password, newPassword } = changePasswordDto;
const admin = await this.adminRepo.findByEmail(email);
if (!admin) throw new BadRequestError(AuthMessage.EmailOrPasswordInc);
const passMatch = await this.comparePassword(password, admin.password);
if (!passMatch) throw new BadRequestError(AuthMessage.EmailOrPasswordInc);
const newChangedPassword = await hash(newPassword, 10);
const updatedAdmin = await this.adminRepo.model.findByIdAndUpdate(admin._id.toString(), { password: newChangedPassword });
console.log(updatedAdmin);
return {
message: AuthMessage.PasswordChangedSuccessfully,
};
}
async getContactContent() {
const contract = await this.contractRepo.model.findOne();
return { contract };
}
async createContentS(createDto: CreateContractDTO) {
const contract = await this.contractRepo.model.findOne();
if (contract) {
throw new BadRequestError(ContractMessage.AlreadyExist);
}
const createdContent = await this.contractRepo.model.create({
...createDto,
});
return { createdContent };
}
async updateContentS(updateDto: UpdateContractDTO) {
const contract = await this.contractRepo.model.findOne();
if (!contract) {
throw new BadRequestError(ContractMessage.NotFound);
}
const updatedContent = await this.contractRepo.model.findByIdAndUpdate(
contract._id.toString(),
{
...updateDto,
},
{ new: true },
);
return { updatedContent };
}
async comparePassword(raw: string, hashed: string) {
return await compare(raw, hashed);
}
async createAdminS(adminId: string, createDto: CreateAdminDTO) {
const { password, userName, fullName, email, phoneNumber, permissions } = createDto;
const admin = await this.adminRepo.findAdmin(email, phoneNumber);
if (admin) throw new BadRequestError(AdminMessage.AdminIsExist);
const roleDoc = await this.roleRepo.model.findOne({ name: RoleEnum.SUPERADMIN });
if (!roleDoc) throw new BadRequestError(AdminMessage.RoleNotFound);
const permissionDocs = await this.permissionRepo.model.find({ _id: { $in: permissions } });
const createdAdmin = await this.adminRepo.model.create({
userName,
fullName,
phoneNumber,
email,
password,
permissions: permissionDocs.map((perm) => perm._id),
role: roleDoc._id,
createdBy: adminId,
});
const { password: adminPassword, ...newAdmin } = createdAdmin.toObject();
return { newAdmin };
}
async getAdminsS() {
const admins = await this.adminRepo.getAdmins();
return { admins };
}
async deleteAdminS(adminId: string) {
const admin = await this.adminRepo.model.findByIdAndDelete(adminId);
if (!admin) throw new BadRequestError(AdminMessage.NotFound);
return { message: AdminMessage.DeletedSuccessfully };
}
async createRoleS(createDto: CreateRoleDTO) {
const { name, permissions } = createDto;
const roleExist = await this.roleRepo.model.findOne({ name });
if (roleExist) throw new BadRequestError(RoleMessage.RoleExist);
const permissionDocs = await this.permissionRepo.model.find({ _id: { $in: permissions } });
const role = await this.roleRepo.model.create({ name, permissions: permissionDocs.map((perm) => perm._id) });
return { role };
}
async getRoles() {
const roles = await this.roleRepo.model.find({});
return { roles };
}
async getPermissions() {
const permissions = await this.permissionRepo.model.find();
return { permissions };
}
async reports() {
const dailySales = await this.orderService.getDailySalesReport();
const weeklySales = await this.orderService.getWeeklySalesReport();
const monthlySales = await this.orderService.getMonthlySalesReport();
const yearlySales = await this.orderService.getAnnualSalesReport();
const dailyShipmentSales = await this.orderService.getDailyShipmentSalesReport();
const weeklyShipmentSales = await this.orderService.getWeeklyShipmentSalesReport();
const monthlyShipmentSales = await this.orderService.getMonthlyShipmentSalesReport();
const yearlyShipmentSales = await this.orderService.getAnnualShipmentSalesReport();
const FiveDaysAgoSales = await this.orderService.getFiveDaysAgoSalesReport();
const topProducts = await this.orderService.getTopSellingProductsS();
const proccessingOrders = await this.orderService.getAllProcessingOrders();
const withdrawalRequests = await this.walletService.getWithdrawalRequestsReport();
const pendingComments = await this.productService.getCommentsForReport();
const pendingQuestions = await this.productService.getQuestionsForReport();
const sellersCount = await this.sellerService.getAllSellerForReport();
const usersCount = await this.userService.getUsersCount();
const wholesaleRequestCount = await this.sellerService.getWholesaleRequestCount();
const pendingBrandsCount = await this.brandService.getPendingBrandsCount();
const pendingWarranties = await this.warrantyService.getPendingWarranties();
const productCount = await this.productService.getProductCount();
const pendingProductCount = await this.productService.getPendingProductCount();
return {
dailySales,
weeklySales,
monthlySales,
yearlySales,
dailyShipmentSales,
weeklyShipmentSales,
monthlyShipmentSales,
yearlyShipmentSales,
withdrawalRequests,
FiveDaysAgoSales,
topProducts,
proccessingOrders,
pendingComments,
pendingQuestions,
sellersCount,
usersCount,
wholesaleRequestCount,
pendingBrandsCount,
pendingWarranties,
productCount,
pendingProductCount,
};
}
async changeShopChatStatus(sellerId: string) {
const shop = await this.shopRepo.model.findOne({ owner: sellerId, ownerRef: OwnerRef.ADMIN });
if (!shop) throw new BadRequestError(ShopMessage.ShopNotFound);
shop.isChatActive = !shop.isChatActive;
await shop.save();
return {
message: CommonMessage.Updated,
};
}
}
export { AdminService };