218 lines
6.8 KiB
TypeScript
218 lines
6.8 KiB
TypeScript
import {
|
|
Controller,
|
|
Get,
|
|
Post,
|
|
Put,
|
|
Delete,
|
|
Body,
|
|
Param,
|
|
Query,
|
|
Res,
|
|
UseGuards,
|
|
NotFoundException,
|
|
} from "@nestjs/common";
|
|
import type { Response } from "express";
|
|
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
|
|
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
|
|
import { RolesGuard } from "../common/guards/roles.guard";
|
|
import { Roles } from "../common/decorators/roles.decorator";
|
|
import { PrismaService } from "../prisma/prisma.service";
|
|
import {
|
|
CreateCompetitorPriceDto,
|
|
UpdateCompetitorPriceDto,
|
|
QueryCompetitorPriceDto,
|
|
} from "./dto/competitor-price.dto";
|
|
import { generateCsv } from "../common/utils/csv-helper";
|
|
|
|
@ApiTags("Admin - Competitor Pricing")
|
|
@ApiBearerAuth()
|
|
@UseGuards(JwtAuthGuard, RolesGuard)
|
|
@Roles("Admin", "SUPER_ADMIN")
|
|
@Controller("admin/competitors/pricing")
|
|
export class CompetitorPricingController {
|
|
constructor(private readonly prisma: PrismaService) {}
|
|
|
|
@Get()
|
|
@ApiOperation({ summary: "لیست لاگهای قیمت رقبا" })
|
|
async findAll(@Query() query: QueryCompetitorPriceDto) {
|
|
const page = Number(query.page) || 1;
|
|
const limit = Number(query.limit) || 10;
|
|
const skip = (page - 1) * limit;
|
|
|
|
const where: any = {};
|
|
if (query.productId) {
|
|
where.productId = query.productId;
|
|
}
|
|
if (query.competitorName) {
|
|
where.competitorName = { contains: query.competitorName, mode: "insensitive" };
|
|
}
|
|
if (query.inStock !== undefined) {
|
|
where.inStock = String(query.inStock) === "true";
|
|
}
|
|
if (query.search) {
|
|
where.OR = [
|
|
{ competitorName: { contains: query.search, mode: "insensitive" } },
|
|
{ shopUrl: { contains: query.search, mode: "insensitive" } },
|
|
];
|
|
}
|
|
|
|
const [total, items] = await Promise.all([
|
|
this.prisma.competitorPriceLog.count({ where }),
|
|
this.prisma.competitorPriceLog.findMany({
|
|
where,
|
|
skip,
|
|
take: limit,
|
|
orderBy: { [query.sortBy || "checkedAt"]: query.sortOrder || "desc" },
|
|
include: {
|
|
product: {
|
|
select: { id: true, nameFa: true, artNo: true, priceValue: true },
|
|
},
|
|
},
|
|
}),
|
|
]);
|
|
|
|
return {
|
|
success: true,
|
|
data: items,
|
|
meta: {
|
|
total,
|
|
page,
|
|
limit,
|
|
totalPages: Math.ceil(total / limit),
|
|
},
|
|
};
|
|
}
|
|
|
|
@Get("export/csv")
|
|
@ApiOperation({ summary: "خروجی CSV لاگهای قیمت رقبا" })
|
|
async exportCsv(@Query() query: QueryCompetitorPriceDto, @Res() res: Response) {
|
|
const where: any = {};
|
|
if (query.productId) {
|
|
where.productId = query.productId;
|
|
}
|
|
if (query.competitorName) {
|
|
where.competitorName = { contains: query.competitorName, mode: "insensitive" };
|
|
}
|
|
if (query.inStock !== undefined) {
|
|
where.inStock = String(query.inStock) === "true";
|
|
}
|
|
|
|
const items: any[] = await this.prisma.competitorPriceLog.findMany({
|
|
where,
|
|
orderBy: { checkedAt: "desc" },
|
|
include: {
|
|
product: {
|
|
select: { nameFa: true, artNo: true, priceValue: true },
|
|
},
|
|
},
|
|
});
|
|
|
|
const rows = items.map((item: any) => ({
|
|
id: item.id,
|
|
productId: item.productId,
|
|
productName: item.product?.nameFa || "",
|
|
productArtNo: item.product?.artNo || "",
|
|
ourPrice: item.product?.priceValue ? item.product.priceValue.toString() : "",
|
|
competitorName: item.competitorName,
|
|
competitorPrice: item.competitorPrice.toString(),
|
|
shopUrl: item.shopUrl,
|
|
inStock: item.inStock ? "Yes" : "No",
|
|
checkedAt: item.checkedAt.toISOString(),
|
|
}));
|
|
|
|
const csvData = generateCsv(rows, [
|
|
{ key: "id", header: "ID" },
|
|
{ key: "productId", header: "Product ID" },
|
|
{ key: "productName", header: "Product Name" },
|
|
{ key: "productArtNo", header: "Art No" },
|
|
{ key: "ourPrice", header: "Our Price" },
|
|
{ key: "competitorName", header: "Competitor" },
|
|
{ key: "competitorPrice", header: "Competitor Price" },
|
|
{ key: "shopUrl", header: "Shop URL" },
|
|
{ key: "inStock", header: "In Stock" },
|
|
{ key: "checkedAt", header: "Checked At" },
|
|
]);
|
|
|
|
res.setHeader("Content-Type", "text/csv; charset=utf-8");
|
|
res.setHeader(
|
|
"Content-Disposition",
|
|
`attachment; filename="competitor-pricing-${Date.now()}.csv"`,
|
|
);
|
|
return res.status(200).send(csvData);
|
|
}
|
|
|
|
@Get(":id")
|
|
@ApiOperation({ summary: "دریافت جزییات یک لاگ قیمت رقیب" })
|
|
async findOne(@Param("id") id: string) {
|
|
const item = await this.prisma.competitorPriceLog.findUnique({
|
|
where: { id },
|
|
include: {
|
|
product: {
|
|
select: { id: true, nameFa: true, artNo: true, priceValue: true },
|
|
},
|
|
},
|
|
});
|
|
if (!item) {
|
|
throw new NotFoundException(`Competitor price log with ID ${id} not found`);
|
|
}
|
|
return { success: true, data: item };
|
|
}
|
|
|
|
@Post()
|
|
@ApiOperation({ summary: "ثبت لاگ قیمت جدید برای رقیب" })
|
|
async create(@Body() dto: CreateCompetitorPriceDto) {
|
|
const item = await this.prisma.competitorPriceLog.create({
|
|
data: {
|
|
productId: dto.productId,
|
|
competitorName: dto.competitorName,
|
|
competitorPrice: dto.competitorPrice,
|
|
shopUrl: dto.shopUrl,
|
|
inStock: dto.inStock ?? true,
|
|
},
|
|
include: {
|
|
product: {
|
|
select: { id: true, nameFa: true, artNo: true },
|
|
},
|
|
},
|
|
});
|
|
return { success: true, data: item };
|
|
}
|
|
|
|
@Put(":id")
|
|
@ApiOperation({ summary: "ویرایش لاگ قیمت رقیب" })
|
|
async update(@Param("id") id: string, @Body() dto: UpdateCompetitorPriceDto) {
|
|
const exists = await this.prisma.competitorPriceLog.findUnique({ where: { id } });
|
|
if (!exists) {
|
|
throw new NotFoundException(`Competitor price log with ID ${id} not found`);
|
|
}
|
|
|
|
const updated = await this.prisma.competitorPriceLog.update({
|
|
where: { id },
|
|
data: {
|
|
...(dto.productId && { productId: dto.productId }),
|
|
...(dto.competitorName && { competitorName: dto.competitorName }),
|
|
...(dto.competitorPrice !== undefined && { competitorPrice: dto.competitorPrice }),
|
|
...(dto.shopUrl && { shopUrl: dto.shopUrl }),
|
|
...(dto.inStock !== undefined && { inStock: dto.inStock }),
|
|
},
|
|
include: {
|
|
product: {
|
|
select: { id: true, nameFa: true, artNo: true },
|
|
},
|
|
},
|
|
});
|
|
return { success: true, data: updated };
|
|
}
|
|
|
|
@Delete(":id")
|
|
@ApiOperation({ summary: "حذف لاگ قیمت رقیب" })
|
|
async remove(@Param("id") id: string) {
|
|
const exists = await this.prisma.competitorPriceLog.findUnique({ where: { id } });
|
|
if (!exists) {
|
|
throw new NotFoundException(`Competitor price log with ID ${id} not found`);
|
|
}
|
|
await this.prisma.competitorPriceLog.delete({ where: { id } });
|
|
return { success: true, message: "Deleted successfully" };
|
|
}
|
|
}
|