fix controller and service name in shop module

master
aliMohtarami 1 month ago
parent a79e6c68e4
commit a864ed9999
  1. 64
      src/shop/shop.controller.ts
  2. 15
      src/shop/shop.module.ts
  3. 2
      src/shop/shop.service.ts

@ -1,5 +1,5 @@
import { Controller, Get, Post, Body, Param, Delete, Query, Put, UseGuards, Request, Patch, HttpException, HttpStatus } from "@nestjs/common"; import { Controller, Get, Post, Body, Param, Delete, Query, Put, UseGuards, Request, Patch, HttpException, HttpStatus } from "@nestjs/common";
import { ProductsService } from "./shop.service"; import { ShopService } from "./shop.service";
import { Product } from "./entities/product.entity"; import { Product } from "./entities/product.entity";
import { CreateProductDto } from "./dto/products/create-product.dto"; import { CreateProductDto } from "./dto/products/create-product.dto";
import { UpdateProductDto } from "./dto/products/update-product.dto"; import { UpdateProductDto } from "./dto/products/update-product.dto";
@ -12,9 +12,9 @@ import { Transaction } from "./entities/transaction.entity";
import { Payment } from "./entities/payment.entity"; import { Payment } from "./entities/payment.entity";
@Controller("shop") @Controller("shop")
export class ProductsController { export class ShopController {
constructor( constructor(
private readonly productsService: ProductsService, private readonly shopService: ShopService,
@InjectModel(Transaction) private readonly transactionModel: typeof Transaction, @InjectModel(Transaction) private readonly transactionModel: typeof Transaction,
@InjectModel(Payment) private readonly paymentModel: typeof Payment, @InjectModel(Payment) private readonly paymentModel: typeof Payment,
) {} ) {}
@ -24,7 +24,7 @@ export class ProductsController {
@UseGuards(RoleGuard) @UseGuards(RoleGuard)
@Post("product") @Post("product")
async create(@Body() createProductDto: CreateProductDto) { async create(@Body() createProductDto: CreateProductDto) {
const product = await this.productsService.create(createProductDto); const product = await this.shopService.create(createProductDto);
return { return {
message: "Product created successfully!", message: "Product created successfully!",
product, product,
@ -34,18 +34,18 @@ export class ProductsController {
@Get("product") @Get("product")
async findAll(@Query() query: { search?: string; priceMin?: number; priceMax?: number }) { async findAll(@Query() query: { search?: string; priceMin?: number; priceMax?: number }) {
const { search, priceMin, priceMax } = query; const { search, priceMin, priceMax } = query;
return this.productsService.findAll(search, priceMin, priceMax); return this.shopService.findAll(search, priceMin, priceMax);
} }
//get a product detail //get a product detail
@Get("product/:id") @Get("product/:id")
async findOne(@Param("id") id: string) { async findOne(@Param("id") id: string) {
return this.productsService.findOne(id); return this.shopService.findOne(id);
} }
//edit a product info (admin) //edit a product info (admin)
@UseGuards(RoleGuard) @UseGuards(RoleGuard)
@Put("product/:id") @Put("product/:id")
async update(@Param("id") id: string, @Body() updateProductDto: UpdateProductDto) { async update(@Param("id") id: string, @Body() updateProductDto: UpdateProductDto) {
const product = await this.productsService.update(id, updateProductDto); const product = await this.shopService.update(id, updateProductDto);
return { return {
message: "product updated successful", message: "product updated successful",
product, product,
@ -55,7 +55,7 @@ export class ProductsController {
@UseGuards(RoleGuard) @UseGuards(RoleGuard)
@Delete("product/:id") @Delete("product/:id")
async remove(@Param("id") id: string): Promise<{ message: string }> { async remove(@Param("id") id: string): Promise<{ message: string }> {
return this.productsService.remove(id); return this.shopService.remove(id);
} }
////////////////////////////////////////cart//////////////////////////////////////// ////////////////////////////////////////cart////////////////////////////////////////
//create and a item to cart (user) //create and a item to cart (user)
@ -63,21 +63,21 @@ export class ProductsController {
@Post("cart") @Post("cart")
async createAndAddItemToCart(@Body() addToCartDto: AddToCartDto, @Request() req: any) { async createAndAddItemToCart(@Body() addToCartDto: AddToCartDto, @Request() req: any) {
const userId = req.user.id; const userId = req.user.id;
return this.productsService.createAndAddItemToCart({ ...addToCartDto, userId }); return this.shopService.createAndAddItemToCart({ ...addToCartDto, userId });
} }
//get user cart items(user) //get user cart items(user)
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Get("cart") @Get("cart")
async getUserOpenCart(@Request() req: any) { async getUserOpenCart(@Request() req: any) {
const userId = req.user.id; const userId = req.user.id;
return this.productsService.getUserOpenCart(userId); return this.shopService.getUserOpenCart(userId);
} }
//edit quantity an item in cart (user) //edit quantity an item in cart (user)
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Patch("cart/:productId") @Patch("cart/:productId")
async updateCart(@Param("productId") productId: number, @Body() updateCartDto: UpdateCartDto, @Request() req: any) { async updateCart(@Param("productId") productId: number, @Body() updateCartDto: UpdateCartDto, @Request() req: any) {
const userId = req.user.id; const userId = req.user.id;
const updatedCart = await this.productsService.updateCart(userId, productId, updateCartDto.quantity); const updatedCart = await this.shopService.updateCart(userId, productId, updateCartDto.quantity);
return { return {
message: "Cart updated successfully", message: "Cart updated successfully",
updatedCart, updatedCart,
@ -88,14 +88,14 @@ export class ProductsController {
@Delete("cart/:productId") @Delete("cart/:productId")
async removeFromCart(@Param("productId") productId: number, @Request() req: any) { async removeFromCart(@Param("productId") productId: number, @Request() req: any) {
const userId = req.user.id; const userId = req.user.id;
return await this.productsService.removeFromCart(userId, productId); return await this.shopService.removeFromCart(userId, productId);
} }
//clear whole cart (user) //clear whole cart (user)
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Get("cart/clear-cart") @Get("cart/clear-cart")
async clearCart(@Request() req: any) { async clearCart(@Request() req: any) {
const userId = req.user.id; const userId = req.user.id;
return await this.productsService.clearCart(userId); return await this.shopService.clearCart(userId);
} }
//get checkout process (user) //get checkout process (user)
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@ -103,8 +103,8 @@ export class ProductsController {
async processOrder(@Request() req: any) { async processOrder(@Request() req: any) {
const userId = req.user.id; const userId = req.user.id;
try { try {
const totalAmount = (await this.productsService.getUserOpenCart(userId)).totalPrice; const totalAmount = (await this.shopService.getUserOpenCart(userId)).totalPrice;
const result = await this.productsService.processOrder(userId, totalAmount); const result = await this.shopService.processOrder(userId, totalAmount);
return result; return result;
} catch (error) { } catch (error) {
throw new HttpException(error.message || "Order processing failed.", HttpStatus.INTERNAL_SERVER_ERROR); throw new HttpException(error.message || "Order processing failed.", HttpStatus.INTERNAL_SERVER_ERROR);
@ -116,7 +116,7 @@ export class ProductsController {
@Get("wallet") @Get("wallet")
async getBalance(@Request() req) { async getBalance(@Request() req) {
const userId = req.user.id; const userId = req.user.id;
return this.productsService.getBalance(userId); return this.shopService.getBalance(userId);
} }
//charging wallet (user) //charging wallet (user)
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@ -124,7 +124,7 @@ export class ProductsController {
async addBalance(@Body("amount") amount: number, @Request() req) { async addBalance(@Body("amount") amount: number, @Request() req) {
const userId = req.user.id; const userId = req.user.id;
const callbackUrl = `http://localhost:3000/payment/verify?userId=${userId}&amount=${amount}`; const callbackUrl = `http://localhost:3000/payment/verify?userId=${userId}&amount=${amount}`;
const paymentUrl = this.productsService.requestPayment(amount, "Wallet Charge", callbackUrl); const paymentUrl = this.shopService.requestPayment(amount, "Wallet Charge", callbackUrl);
return paymentUrl; return paymentUrl;
} }
//get transaction (user) //get transaction (user)
@ -132,13 +132,13 @@ export class ProductsController {
@Get("wallet/transaction") @Get("wallet/transaction")
async getTransactionById(@Request() req) { async getTransactionById(@Request() req) {
const userId = req.user.id; const userId = req.user.id;
return this.productsService.getTransactionById(userId); return this.shopService.getTransactionById(userId);
} }
//get specific user transaction (admin) //get specific user transaction (admin)
@UseGuards(RoleGuard) @UseGuards(RoleGuard)
@Get("wallet/transaction/:id") @Get("wallet/transaction/:id")
async getTransactionByIdForAdmin(@Param("id") id: number) { async getTransactionByIdForAdmin(@Param("id") id: number) {
return this.productsService.getTransactionByIdForAdmin(id); return this.shopService.getTransactionByIdForAdmin(id);
} }
////////////////////////////////////////payment//////////////////////////////////////// ////////////////////////////////////////payment////////////////////////////////////////
//payment request //payment request
@ -146,18 +146,18 @@ export class ProductsController {
@Get("payment/request") @Get("payment/request")
async requestPayment(@Request() req) { async requestPayment(@Request() req) {
const userId = req.user.id; const userId = req.user.id;
const invoice = await this.productsService.getInvoicePendingByUser(userId); const invoice = await this.shopService.getInvoicePendingByUser(userId);
const totalAmount = invoice.totalPaymentAmount; const totalAmount = invoice.totalPaymentAmount;
if (totalAmount < 1000) { if (totalAmount < 1000) {
return { message: "please enter amount above 1000" }; return { message: "please enter amount above 1000" };
} }
const callbackUrl = `http://localhost:3000/payment/verify?userId=${userId}&amount=${totalAmount}`; const callbackUrl = `http://localhost:3000/shop/payment/verify?userId=${userId}&amount=${totalAmount}`;
const paymentUrl = await this.productsService.requestPayment(totalAmount, "Purchase products", callbackUrl); const paymentUrl = await this.shopService.requestPayment(totalAmount, "Purchase products", callbackUrl);
return { url: paymentUrl }; return { url: paymentUrl };
} }
//payment verify //payment verify
@Get("verify") @Get("payment/verify")
async verifyPayment(@Query() query: { Authority: string; Status: string; userId: number; amount: number }): Promise<any> { async verifyPayment(@Query() query: { Authority: string; Status: string; userId: number; amount: number }): Promise<any> {
const { Authority, Status, userId, amount } = query; const { Authority, Status, userId, amount } = query;
@ -168,11 +168,11 @@ export class ProductsController {
if (!userId) { if (!userId) {
throw new Error("User ID is required."); throw new Error("User ID is required.");
} }
const wallet = this.productsService.getWalletInfo(userId); const wallet = this.shopService.getWalletInfo(userId);
try { try {
const refId = await this.productsService.verifyPayment(Authority, amount); const refId = await this.shopService.verifyPayment(Authority, amount);
await this.productsService.addBalance(userId, amount); await this.shopService.addBalance(userId, amount);
const wallet = this.productsService.getWalletInfo(userId); const wallet = this.shopService.getWalletInfo(userId);
await this.paymentModel.create({ await this.paymentModel.create({
userId, userId,
walletId: (await wallet).walletId, walletId: (await wallet).walletId,
@ -185,7 +185,9 @@ export class ProductsController {
}); });
return { message: "Payment successful", refId }; return { message: "Payment successful", refId };
} catch (error) { } catch (error) {
console.log(error); if(error instanceof HttpException){
throw error
}
await this.paymentModel.create({ await this.paymentModel.create({
userId, userId,
walletId: (await wallet).walletId, walletId: (await wallet).walletId,
@ -201,19 +203,19 @@ export class ProductsController {
@Get('invoice') @Get('invoice')
async getInvoiceByUser(@Request() req) { async getInvoiceByUser(@Request() req) {
const userId = req.user.id; const userId = req.user.id;
return this.productsService.getInvoiceByUser(userId); return this.shopService.getInvoiceByUser(userId);
} }
//get invoices list (admin) //get invoices list (admin)
@UseGuards(RoleGuard) @UseGuards(RoleGuard)
@Get('invoice/list') @Get('invoice/list')
async getInvoices() { async getInvoices() {
return this.productsService.getInvoices(); return this.shopService.getInvoices();
} }
//get specific user invoices //get specific user invoices
@UseGuards(RoleGuard) @UseGuards(RoleGuard)
@Get('invoice/:id') @Get('invoice/:id')
async getUserInvoice(@Param('id') id:number) { async getUserInvoice(@Param('id') id:number) {
return this.productsService.getUserInvoices(id); return this.shopService.getUserInvoices(id);
} }
} }

@ -1,6 +1,6 @@
import { Module } from "@nestjs/common"; import { Module } from "@nestjs/common";
import { ProductsService } from "./shop.service"; import { ShopService } from "./shop.service";
import { ProductsController } from "./shop.controller"; import { ShopController } from "./shop.controller";
import { SequelizeModule } from "@nestjs/sequelize"; import { SequelizeModule } from "@nestjs/sequelize";
import { Product } from "./entities/product.entity"; import { Product } from "./entities/product.entity";
import { RoleGuard } from "src/users/guard/role.guard"; import { RoleGuard } from "src/users/guard/role.guard";
@ -13,13 +13,14 @@ import { Payment } from "./entities/payment.entity";
import { Invoice } from "./entities/invoice.entity"; import { Invoice } from "./entities/invoice.entity";
@Module({ @Module({
imports: [SequelizeModule.forFeature([Product,Cart,Invoice,Wallet, Transaction,Payment]), imports: [
SequelizeModule.forFeature([Product, Cart, Invoice, Wallet, Transaction, Payment]),
JwtModule.register({ JwtModule.register({
secret: process.env.JWT_SECRET, secret: process.env.JWT_SECRET,
signOptions: { expiresIn: '1h' }, signOptions: { expiresIn: "1h" },
}), }),
], ],
controllers: [ProductsController], controllers: [ShopController],
providers: [ProductsService,RoleGuard,JwtAuthGuard], providers: [ShopService, RoleGuard, JwtAuthGuard],
}) })
export class ProductsModule {} export class ProductsModule {}

@ -13,7 +13,7 @@ import { Invoice } from "./entities/invoice.entity";
const ZarinpalCheckout = require("zarinpal-checkout"); const ZarinpalCheckout = require("zarinpal-checkout");
@Injectable() @Injectable()
export class ProductsService { export class ShopService {
private zarinpal; private zarinpal;
constructor( constructor(
@InjectModel(Product) private readonly productModel: typeof Product, @InjectModel(Product) private readonly productModel: typeof Product,

Loading…
Cancel
Save