213 lines
6.6 KiB
TypeScript
213 lines
6.6 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 {
|
|
CreatePriceSuggestionDto,
|
|
UpdatePriceSuggestionDto,
|
|
QueryPriceSuggestionDto,
|
|
} from "./dto/price-suggestion.dto";
|
|
import { generateCsv } from "../common/utils/csv-helper";
|
|
|
|
@ApiTags("Admin - Pricing Suggestions")
|
|
@ApiBearerAuth()
|
|
@UseGuards(JwtAuthGuard, RolesGuard)
|
|
@Roles("Admin", "SUPER_ADMIN")
|
|
@Controller("admin/pricing/suggestions")
|
|
export class PricingSuggestionsController {
|
|
constructor(private readonly prisma: PrismaService) {}
|
|
|
|
@Get()
|
|
@ApiOperation({ summary: "لیست پیشنهادات هوشمند قیمتگذاری" })
|
|
async findAll(@Query() query: QueryPriceSuggestionDto) {
|
|
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.status) {
|
|
where.status = query.status;
|
|
}
|
|
if (query.search) {
|
|
where.OR = [
|
|
{ rationale: { contains: query.search, mode: "insensitive" } },
|
|
{ product: { nameFa: { contains: query.search, mode: "insensitive" } } },
|
|
];
|
|
}
|
|
|
|
const [total, items] = await Promise.all([
|
|
this.prisma.priceSuggestion.count({ where }),
|
|
this.prisma.priceSuggestion.findMany({
|
|
where,
|
|
skip,
|
|
take: limit,
|
|
orderBy: { [query.sortBy || "createdAt"]: 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: QueryPriceSuggestionDto, @Res() res: Response) {
|
|
const where: any = {};
|
|
if (query.productId) {
|
|
where.productId = query.productId;
|
|
}
|
|
if (query.status) {
|
|
where.status = query.status;
|
|
}
|
|
|
|
const items: any[] = await this.prisma.priceSuggestion.findMany({
|
|
where,
|
|
orderBy: { createdAt: "desc" },
|
|
include: {
|
|
product: {
|
|
select: { nameFa: true, artNo: true },
|
|
},
|
|
},
|
|
});
|
|
|
|
const rows = items.map((item: any) => ({
|
|
id: item.id,
|
|
productId: item.productId,
|
|
productName: item.product?.nameFa || "",
|
|
productArtNo: item.product?.artNo || "",
|
|
currentPrice: item.currentPrice.toString(),
|
|
suggestedPrice: item.suggestedPrice.toString(),
|
|
competitorBenchmark: item.competitorBenchmark ? item.competitorBenchmark.toString() : "",
|
|
rationale: item.rationale || "",
|
|
status: item.status,
|
|
createdAt: item.createdAt.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: "currentPrice", header: "Current Price" },
|
|
{ key: "suggestedPrice", header: "Suggested Price" },
|
|
{ key: "competitorBenchmark", header: "Competitor Benchmark" },
|
|
{ key: "rationale", header: "Rationale" },
|
|
{ key: "status", header: "Status" },
|
|
{ key: "createdAt", header: "Created At" },
|
|
]);
|
|
|
|
res.setHeader("Content-Type", "text/csv; charset=utf-8");
|
|
res.setHeader(
|
|
"Content-Disposition",
|
|
`attachment; filename="price-suggestions-${Date.now()}.csv"`,
|
|
);
|
|
return res.status(200).send(csvData);
|
|
}
|
|
|
|
@Get(":id")
|
|
@ApiOperation({ summary: "دریافت جزییات پیشنهاد قیمت" })
|
|
async findOne(@Param("id") id: string) {
|
|
const item = await this.prisma.priceSuggestion.findUnique({
|
|
where: { id },
|
|
include: {
|
|
product: {
|
|
select: { id: true, nameFa: true, artNo: true, priceValue: true },
|
|
},
|
|
},
|
|
});
|
|
if (!item) {
|
|
throw new NotFoundException(`Price suggestion with ID ${id} not found`);
|
|
}
|
|
return { success: true, data: item };
|
|
}
|
|
|
|
@Post()
|
|
@ApiOperation({ summary: "ایجاد پیشنهاد قیمت جدید" })
|
|
async create(@Body() dto: CreatePriceSuggestionDto) {
|
|
const item = await this.prisma.priceSuggestion.create({
|
|
data: {
|
|
productId: dto.productId,
|
|
suggestedPrice: dto.suggestedPrice,
|
|
currentPrice: dto.currentPrice,
|
|
competitorBenchmark: dto.competitorBenchmark,
|
|
rationale: dto.rationale,
|
|
status: dto.status || "pending",
|
|
},
|
|
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: UpdatePriceSuggestionDto) {
|
|
const exists = await this.prisma.priceSuggestion.findUnique({ where: { id } });
|
|
if (!exists) {
|
|
throw new NotFoundException(`Price suggestion with ID ${id} not found`);
|
|
}
|
|
|
|
const updated = await this.prisma.priceSuggestion.update({
|
|
where: { id },
|
|
data: {
|
|
...(dto.suggestedPrice !== undefined && { suggestedPrice: dto.suggestedPrice }),
|
|
...(dto.currentPrice !== undefined && { currentPrice: dto.currentPrice }),
|
|
...(dto.competitorBenchmark !== undefined && { competitorBenchmark: dto.competitorBenchmark }),
|
|
...(dto.rationale !== undefined && { rationale: dto.rationale }),
|
|
...(dto.status && { status: dto.status }),
|
|
},
|
|
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.priceSuggestion.findUnique({ where: { id } });
|
|
if (!exists) {
|
|
throw new NotFoundException(`Price suggestion with ID ${id} not found`);
|
|
}
|
|
await this.prisma.priceSuggestion.delete({ where: { id } });
|
|
return { success: true, message: "Deleted successfully" };
|
|
}
|
|
}
|