fix(build): resolve linter and tsconfig project service errors, guarantee dist/main existence in start-dev
Deploy Canina / deploy (push) Has been cancelled

This commit is contained in:
parsa aghaei committed 2026-08-18 20:23:59 +03:30
1 parent a291fa0c4a
commit 6362750dea
50 files changed
+12128 -10959

No files matched your search

+1 -4
View File
@@ -66,10 +66,7 @@ export class AdminController {
@Put('users/:id')
@ApiOperation({ summary: 'ویرایش مشخصات کامل کاربر' })
async updateUser(
@Param('id') id: string,
@Body() dto: UpdateUserDto,
) {
async updateUser(@Param('id') id: string, @Body() dto: UpdateUserDto) {
const user = await this.adminService.updateUser(id, dto);
return {
success: true,
+84 -27
View File
@@ -119,9 +119,20 @@ export class AdminService {
}
}
const sortField = (query.sortBy && typeof query.sortBy === 'string' && ['createdAt', 'firstName', 'lastName', 'mobile', 'email', 'role', 'walletBalance'].includes(query.sortBy))
? query.sortBy
: 'createdAt';
const sortField =
query.sortBy &&
typeof query.sortBy === 'string' &&
[
'createdAt',
'firstName',
'lastName',
'mobile',
'email',
'role',
'walletBalance',
].includes(query.sortBy)
? query.sortBy
: 'createdAt';
const sortDirection = query.sortOrder === 'asc' ? 'asc' : 'desc';
const [data, total] = await Promise.all([
@@ -167,7 +178,9 @@ export class AdminService {
where: { mobile },
});
if (existingMobile) {
throw new BadRequestException('کاربری با این شماره موبایل قبلاً در سیستم ثبت شده است');
throw new BadRequestException(
'کاربری با این شماره موبایل قبلاً در سیستم ثبت شده است',
);
}
if (dto.email) {
@@ -175,12 +188,16 @@ export class AdminService {
where: { email: dto.email.trim().toLowerCase() },
});
if (existingEmail) {
throw new BadRequestException('کاربری با این آدرس ایمیل قبلاً در سیستم ثبت شده است');
throw new BadRequestException(
'کاربری با این آدرس ایمیل قبلاً در سیستم ثبت شده است',
);
}
}
const passwordToHash = dto.password?.trim();
const hashedPassword = passwordToHash ? await bcrypt.hash(passwordToHash, 10) : '';
const hashedPassword = passwordToHash
? await bcrypt.hash(passwordToHash, 10)
: '';
return this.prisma.user.create({
data: {
@@ -200,7 +217,9 @@ export class AdminService {
async updateUser(id: string, dto: UpdateUserDto) {
if (id === '12345678-1234-1234-1234-123456789012') {
throw new BadRequestException('امکان ویرایش حساب ادمین پیش‌فرض وجود ندارد');
throw new BadRequestException(
'امکان ویرایش حساب ادمین پیش‌فرض وجود ندارد',
);
}
const user = await this.prisma.user.findUnique({ where: { id } });
@@ -208,31 +227,41 @@ export class AdminService {
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
}
const normalizedMobile = dto.mobile ? normalizeMobile(dto.mobile) : undefined;
const normalizedMobile = dto.mobile
? normalizeMobile(dto.mobile)
: undefined;
if (normalizedMobile && normalizedMobile !== user.mobile) {
const existingMobile = await this.prisma.user.findUnique({
where: { mobile: normalizedMobile },
});
if (existingMobile && existingMobile.id !== id) {
throw new BadRequestException('این شماره موبایل متعلق به کاربر دیگری است');
throw new BadRequestException(
'این شماره موبایل متعلق به کاربر دیگری است',
);
}
}
const normalizedEmail = dto.email ? dto.email.trim().toLowerCase() : undefined;
const normalizedEmail = dto.email
? dto.email.trim().toLowerCase()
: undefined;
if (normalizedEmail && normalizedEmail !== user.email) {
const existingEmail = await this.prisma.user.findUnique({
where: { email: normalizedEmail },
});
if (existingEmail && existingEmail.id !== id) {
throw new BadRequestException('این آدرس ایمیل متعلق به کاربر دیگری است');
throw new BadRequestException(
'این آدرس ایمیل متعلق به کاربر دیگری است',
);
}
}
const updateData: Prisma.UserUpdateInput = {};
if (dto.firstName !== undefined) updateData.firstName = dto.firstName.trim();
if (dto.firstName !== undefined)
updateData.firstName = dto.firstName.trim();
if (dto.lastName !== undefined) updateData.lastName = dto.lastName.trim();
if (normalizedMobile !== undefined) updateData.mobile = normalizedMobile;
if (normalizedEmail !== undefined) updateData.email = normalizedEmail || null;
if (normalizedEmail !== undefined)
updateData.email = normalizedEmail || null;
if (dto.role !== undefined) updateData.role = dto.role;
if (dto.walletBalance !== undefined) {
updateData.walletBalance = new Prisma.Decimal(dto.walletBalance);
@@ -319,16 +348,28 @@ export class AdminService {
}
if (query.suitableFor && query.suitableFor !== 'all') {
andConditions.push({ suitableFor: { in: [query.suitableFor, 'سگ و گربه', 'هر دو'] } });
andConditions.push({
suitableFor: { in: [query.suitableFor, 'سگ و گربه', 'هر دو'] },
});
}
if (andConditions.length > 0) {
where.AND = andConditions;
}
const sortField = (query.sortBy && typeof query.sortBy === 'string' && ['nameFa', 'artNo', 'priceValue', 'packageSize', 'createdAt', 'updatedAt'].includes(query.sortBy))
? query.sortBy
: 'createdAt';
const sortField =
query.sortBy &&
typeof query.sortBy === 'string' &&
[
'nameFa',
'artNo',
'priceValue',
'packageSize',
'createdAt',
'updatedAt',
].includes(query.sortBy)
? query.sortBy
: 'createdAt';
const sortDirection = query.sortOrder === 'asc' ? 'asc' : 'desc';
const [data, total] = await Promise.all([
@@ -366,7 +407,8 @@ export class AdminService {
categorySlug: data.categorySlug || 'general',
buyPrice: data.buyPrice !== undefined ? data.buyPrice : 0,
priceValue: data.priceValue || 0,
wholesalePrice: data.wholesalePrice !== undefined ? data.wholesalePrice : null,
wholesalePrice:
data.wholesalePrice !== undefined ? data.wholesalePrice : null,
priceDisplay: data.priceDisplay || '',
unit: data.unit || 'عدد',
packageSize: data.packageSize || 100,
@@ -431,7 +473,8 @@ export class AdminService {
categorySlug: data.categorySlug,
buyPrice: data.buyPrice !== undefined ? data.buyPrice : undefined,
priceValue: data.priceValue,
wholesalePrice: data.wholesalePrice !== undefined ? data.wholesalePrice : undefined,
wholesalePrice:
data.wholesalePrice !== undefined ? data.wholesalePrice : undefined,
priceDisplay: data.priceDisplay,
unit: data.unit,
packageSize: data.packageSize,
@@ -444,16 +487,25 @@ export class AdminService {
? [data.images]
: undefined,
podcastUrl: data.podcastUrl !== undefined ? data.podcastUrl : undefined,
podcastTitle: data.podcastTitle !== undefined ? data.podcastTitle : undefined,
podcastDescription: data.podcastDescription !== undefined ? data.podcastDescription : undefined,
podcastCover: data.podcastCover !== undefined ? data.podcastCover : undefined,
podcastTitle:
data.podcastTitle !== undefined ? data.podcastTitle : undefined,
podcastDescription:
data.podcastDescription !== undefined
? data.podcastDescription
: undefined,
podcastCover:
data.podcastCover !== undefined ? data.podcastCover : undefined,
videoUrl: data.videoUrl !== undefined ? data.videoUrl : undefined,
videoTitle: data.videoTitle !== undefined ? data.videoTitle : undefined,
videoDescription: data.videoDescription !== undefined ? data.videoDescription : undefined,
videoDescription:
data.videoDescription !== undefined
? data.videoDescription
: undefined,
videoCover: data.videoCover !== undefined ? data.videoCover : undefined,
pdfUrl: data.pdfUrl !== undefined ? data.pdfUrl : undefined,
pdfTitle: data.pdfTitle !== undefined ? data.pdfTitle : undefined,
pdfDescription: data.pdfDescription !== undefined ? data.pdfDescription : undefined,
pdfDescription:
data.pdfDescription !== undefined ? data.pdfDescription : undefined,
pdfCover: data.pdfCover !== undefined ? data.pdfCover : undefined,
metaTitle: data.metaTitle,
metaDescription: data.metaDescription,
@@ -506,9 +558,14 @@ export class AdminService {
where.status = query.status;
}
const sortField = (query.sortBy && typeof query.sortBy === 'string' && ['createdAt', 'totalAmount', 'status', 'finalAmount'].includes(query.sortBy))
? query.sortBy
: 'createdAt';
const sortField =
query.sortBy &&
typeof query.sortBy === 'string' &&
['createdAt', 'totalAmount', 'status', 'finalAmount'].includes(
query.sortBy,
)
? query.sortBy
: 'createdAt';
const sortDirection = query.sortOrder === 'asc' ? 'asc' : 'desc';
const [data, total] = await Promise.all([
+20 -4
View File
@@ -1,4 +1,11 @@
import { IsNotEmpty, IsString, IsOptional, IsEmail, MinLength, IsNumber } from 'class-validator';
import {
IsNotEmpty,
IsString,
IsOptional,
IsEmail,
MinLength,
IsNumber,
} from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
export class CreateUserDto {
@@ -17,7 +24,10 @@ export class CreateUserDto {
@IsString()
mobile!: string;
@ApiPropertyOptional({ description: 'ایمیل کاربر', example: 'ali@example.com' })
@ApiPropertyOptional({
description: 'ایمیل کاربر',
example: 'ali@example.com',
})
@IsOptional()
@IsEmail({}, { message: 'فرمت ایمیل نامعتبر است' })
email?: string;
@@ -55,12 +65,18 @@ export class UpdateUserDto {
@IsString()
mobile?: string;
@ApiPropertyOptional({ description: 'ایمیل کاربر', example: 'ali@example.com' })
@ApiPropertyOptional({
description: 'ایمیل کاربر',
example: 'ali@example.com',
})
@IsOptional()
@IsEmail({}, { message: 'فرمت ایمیل نامعتبر است' })
email?: string;
@ApiPropertyOptional({ description: 'رمز عبور جدید', example: 'NewPassword123' })
@ApiPropertyOptional({
description: 'رمز عبور جدید',
example: 'NewPassword123',
})
@IsOptional()
@IsString()
@MinLength(6, { message: 'رمز عبور باید حداقل ۶ کاراکتر باشد' })
+6 -2
View File
@@ -42,7 +42,9 @@ export class SslController {
@Post('upload')
@UseInterceptors(AnyFilesInterceptor())
@ApiOperation({ summary: 'آپلود فایل‌های گواهی SSL (FullChain/CRT و PrivateKey)' })
@ApiOperation({
summary: 'آپلود فایل‌های گواهی SSL (FullChain/CRT و PrivateKey)',
})
uploadFiles(
@UploadedFiles() files: Array<Express.Multer.File>,
@Body('certificateText') certText?: string,
@@ -90,7 +92,9 @@ export class SslController {
}
@Get('test-domain')
@ApiOperation({ summary: 'بررسی آنلاین گواهی SSL یک دامنه مشخص روی پورت ۴۴۳' })
@ApiOperation({
summary: 'بررسی آنلاین گواهی SSL یک دامنه مشخص روی پورت ۴۴۳',
})
testDomain(@Query('domain') domain: string) {
if (!domain) {
throw new BadRequestException('نام دامنه الزامی است');
+27 -10
View File
@@ -2,6 +2,7 @@ import { Injectable, Logger, BadRequestException } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';
import * as crypto from 'crypto';
import * as tls from 'tls';
export interface SslCertInfo {
exists: boolean;
@@ -21,14 +22,17 @@ export interface SslCertInfo {
@Injectable()
export class SslService {
private readonly logger = new Logger(SslService.name);
private readonly certsDir = process.env.SSL_CERTS_DIR || path.join(process.cwd(), 'ssl_certs');
private readonly certsDir =
process.env.SSL_CERTS_DIR || path.join(process.cwd(), 'ssl_certs');
constructor() {
if (!fs.existsSync(this.certsDir)) {
try {
fs.mkdirSync(this.certsDir, { recursive: true });
} catch (err) {
this.logger.warn(`Could not create ssl_certs dir at ${this.certsDir}: ${err}`);
this.logger.warn(
`Could not create ssl_certs dir at ${this.certsDir}: ${err}`,
);
}
}
}
@@ -69,7 +73,10 @@ export class SslService {
const validToDate = new Date(cert.validTo);
const now = new Date();
const diffMs = validToDate.getTime() - now.getTime();
const daysRemaining = Math.max(0, Math.floor(diffMs / (1000 * 60 * 60 * 24)));
const daysRemaining = Math.max(
0,
Math.floor(diffMs / (1000 * 60 * 60 * 24)),
);
const isExpired = diffMs <= 0;
// Extract SAN domains
@@ -108,7 +115,9 @@ export class SslService {
const cleanKey = keyContent.trim();
if (!cleanCert || !cleanKey) {
throw new BadRequestException('محتوای گواهی (Certificate) و کلید خصوصی (Private Key) الزامی است.');
throw new BadRequestException(
'محتوای گواهی (Certificate) و کلید خصوصی (Private Key) الزامی است.',
);
}
// 1. Validate Certificate format
@@ -117,7 +126,9 @@ export class SslService {
cert = new crypto.X509Certificate(cleanCert);
} catch (err: unknown) {
const errObj = err as Error;
throw new BadRequestException(`فرمت گواهی نامعتبر است: ${errObj.message}`);
throw new BadRequestException(
`فرمت گواهی نامعتبر است: ${errObj.message}`,
);
}
// 2. Validate Private Key format
@@ -125,7 +136,9 @@ export class SslService {
crypto.createPrivateKey(cleanKey);
} catch (err: unknown) {
const errObj = err as Error;
throw new BadRequestException(`فرمت کلید خصوصی نامعتبر است: ${errObj.message}`);
throw new BadRequestException(
`فرمت کلید خصوصی نامعتبر است: ${errObj.message}`,
);
}
// 3. Ensure certs directory exists
@@ -150,7 +163,9 @@ export class SslService {
fs.writeFileSync(certPath, cleanCert, 'utf8');
fs.writeFileSync(keyPath, cleanKey, 'utf8');
this.logger.log(`SSL Certificates updated successfully. Subject: ${cert.subject}`);
this.logger.log(
`SSL Certificates updated successfully. Subject: ${cert.subject}`,
);
return {
success: true,
@@ -161,8 +176,10 @@ export class SslService {
public testOnlineDomainSsl(domain: string): Promise<Record<string, unknown>> {
return new Promise((resolve) => {
const cleanDomain = domain.replace(/^https?:\/\//, '').replace(/\/.*$/, '').trim();
const tls = require('tls');
const cleanDomain = domain
.replace(/^https?:\/\//, '')
.replace(/\/.*$/, '')
.trim();
const socket = tls.connect(
{
host: cleanDomain,
@@ -192,7 +209,7 @@ export class SslService {
issuer: peerCert.issuer?.O || peerCert.issuer?.CN,
subject: peerCert.subject?.CN,
});
}
},
);
socket.on('error', (err: Error) => {
+2 -5
View File
@@ -5,10 +5,7 @@ export const DEFAULT_JWT_REFRESH_SECRET =
'canina_jwt_fallback_refresh_secret_32_characters_minimum_len_2026';
export const getJwtSecret = (): string =>
process.env.JWT_ACCESS_SECRET ||
process.env.JWT_SECRET ||
DEFAULT_JWT_SECRET;
process.env.JWT_ACCESS_SECRET || process.env.JWT_SECRET || DEFAULT_JWT_SECRET;
export const getJwtRefreshSecret = (): string =>
process.env.JWT_REFRESH_SECRET ||
DEFAULT_JWT_REFRESH_SECRET;
process.env.JWT_REFRESH_SECRET || DEFAULT_JWT_REFRESH_SECRET;
+15 -2
View File
@@ -1,4 +1,12 @@
import { Controller, Post, Body, HttpCode, HttpStatus, UseGuards, Req } from '@nestjs/common';
import {
Controller,
Post,
Body,
HttpCode,
HttpStatus,
UseGuards,
Req,
} from '@nestjs/common';
import { AuthService } from './auth.service';
import { SendOtpDto } from './dto/send-otp.dto';
import { VerifyOtpDto } from './dto/verify-otp.dto';
@@ -96,7 +104,12 @@ export class AuthController {
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'تازه‌سازی توکن دسترسی (Refresh Token)' })
@ApiOkResponse({ description: 'توکن جدید با موفقیت صادر شد' })
refresh(@Req() req: { user: { id: string; email?: string; role?: string; mobile?: string } }) {
refresh(
@Req()
req: {
user: { id: string; email?: string; role?: string; mobile?: string };
},
) {
return this.authService.refresh(req.user);
}
-1
View File
@@ -23,4 +23,3 @@ import { getJwtSecret } from './auth.constants';
exports: [AuthService],
})
export class AuthModule {}
+19 -6
View File
@@ -1,4 +1,9 @@
import { Injectable, BadRequestException, HttpException, HttpStatus } from '@nestjs/common';
import {
Injectable,
BadRequestException,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { PrismaService } from '../prisma/prisma.service';
import { RedisService } from '../redis/redis.service';
@@ -65,7 +70,8 @@ export class AuthService {
{
success: false,
statusCode: HttpStatus.TOO_MANY_REQUESTS,
message: 'تعداد دفعات ارسال پیامک در یک ساعت بیش از حد مجاز است. لطفاً ساعتی دیگر تلاش کنید.',
message:
'تعداد دفعات ارسال پیامک در یک ساعت بیش از حد مجاز است. لطفاً ساعتی دیگر تلاش کنید.',
code: 'HOURLY_RATE_LIMIT_EXCEEDED',
},
HttpStatus.TOO_MANY_REQUESTS,
@@ -80,7 +86,8 @@ export class AuthService {
{
success: false,
statusCode: HttpStatus.TOO_MANY_REQUESTS,
message: 'سقف ارسال روزانه پیامک برای این شماره تکمیل شده است. لطفاً فردا مجدداً تلاش کنید.',
message:
'سقف ارسال روزانه پیامک برای این شماره تکمیل شده است. لطفاً فردا مجدداً تلاش کنید.',
code: 'DAILY_RATE_LIMIT_EXCEEDED',
},
HttpStatus.TOO_MANY_REQUESTS,
@@ -161,7 +168,9 @@ export class AuthService {
const firstName = registerDto.firstName.trim();
const lastName = registerDto.lastName.trim();
const mobile = normalizeMobile(registerDto.mobile);
const email = registerDto.email ? registerDto.email.trim().toLowerCase() : null;
const email = registerDto.email
? registerDto.email.trim().toLowerCase()
: null;
const password = registerDto.password?.trim();
const existingUser = await this.prisma.user.findUnique({
@@ -307,7 +316,12 @@ export class AuthService {
});
}
async refresh(user: { id: string; email?: string; role?: string; mobile?: string }) {
refresh(user: {
id: string;
email?: string;
role?: string;
mobile?: string;
}) {
const payload = {
sub: user.id,
email: user.email,
@@ -323,4 +337,3 @@ export class AuthService {
};
}
}
@@ -104,7 +104,10 @@ export class CustomHttpExceptionFilter implements ExceptionFilter {
if (lower === 'bad request' || msg === 'Bad Request') {
return 'درخواست نامعتبر است. لطفاً پارامترهای ورودی را چک کنید.';
}
if (lower === 'too many requests' || msg === 'ThrottlerException: Too Many Requests') {
if (
lower === 'too many requests' ||
msg === 'ThrottlerException: Too Many Requests'
) {
return 'تعداد درخواست‌های شما بیش از حد مجاز است. لطفاً کمی صبر کرده و مجدداً تلاش کنید.';
}
+5 -1
View File
@@ -297,7 +297,11 @@ export class SmsService {
/**
* Fetch remaining SMS balance/credit (in Rials or count) from MeliPayamak
*/
async getCredit(): Promise<{ success: boolean; credit: number; message?: string }> {
async getCredit(): Promise<{
success: boolean;
credit: number;
message?: string;
}> {
const config = await this.getSmsConfig();
if (!config.username || !config.password) {
+8 -2
View File
@@ -187,7 +187,9 @@ export class OrdersController {
},
})
@Post(':id/retry-payment')
@ApiOperation({ summary: 'پرداخت مجدد و تکمیل سفارش با امکان انتخاب روش پرداخت' })
@ApiOperation({
summary: 'پرداخت مجدد و تکمیل سفارش با امکان انتخاب روش پرداخت',
})
@ApiOkResponse({
description: 'درخواست پرداخت مجدد با موفقیت پردازش شد',
})
@@ -196,7 +198,11 @@ export class OrdersController {
@Param('id') id: string,
@Body() body: { paymentMethod?: string },
) {
return this.ordersService.retryPayment(req.user.id, id, body?.paymentMethod);
return this.ordersService.retryPayment(
req.user.id,
id,
body?.paymentMethod,
);
}
findOne(@Req() req: { user: { id: string } }, @Param('id') id: string) {
+26 -19
View File
@@ -104,10 +104,15 @@ export class OrdersService {
where: { key: { in: ['catalog_mode', 'catalog_disable_checkout'] } },
});
const catalogUiText = await this.prisma.uiText.findFirst({
where: { key: { in: ['catalog_mode', 'catalog_disable_checkout'] }, value: 'true' },
where: {
key: { in: ['catalog_mode', 'catalog_disable_checkout'] },
value: 'true',
},
});
if ((catalogSetting && String(catalogSetting.value) === 'true') || catalogUiText) {
throw new BadRequestException('امکان ثبت سفارش به دلیل فعال بودن حالت کاتالوگ در حال حاضر وجود ندارد.');
if ((catalogSetting && catalogSetting.value === 'true') || catalogUiText) {
throw new BadRequestException(
'امکان ثبت سفارش به دلیل فعال بودن حالت کاتالوگ در حال حاضر وجود ندارد.',
);
}
if (!createOrderDto.items || createOrderDto.items.length === 0) {
@@ -424,15 +429,16 @@ export class OrdersService {
*/
async releaseExpiredInventoryReservations() {
const now = new Date();
const expiredReservations = await this.prisma.inventoryReservation.updateMany({
where: {
status: 'ACTIVE',
expiresAt: { lte: now },
},
data: {
status: 'RELEASED',
},
});
const expiredReservations =
await this.prisma.inventoryReservation.updateMany({
where: {
status: 'ACTIVE',
expiresAt: { lte: now },
},
data: {
status: 'RELEASED',
},
});
return {
releasedCount: expiredReservations.count,
@@ -443,11 +449,7 @@ export class OrdersService {
/**
* Retry or complete payment for an existing pending order with selectable payment method
*/
async retryPayment(
userId: string,
orderId: string,
paymentMethod?: string,
) {
async retryPayment(userId: string, orderId: string, paymentMethod?: string) {
const order = await this.prisma.order.findFirst({
where: { id: orderId, userId },
include: { user: true },
@@ -494,7 +496,11 @@ export class OrdersService {
if (Number(order.charityDonation) > 0) {
await tx.user.update({
where: { id: userId },
data: { charityDonationTotal: { increment: Number(order.charityDonation) } },
data: {
charityDonationTotal: {
increment: Number(order.charityDonation),
},
},
});
}
@@ -535,7 +541,8 @@ export class OrdersService {
return {
success: true,
message: 'روش پرداخت به کارت به کارت تغییر یافت. لطفاً پس از واریز فیش را ثبت فرمایید.',
message:
'روش پرداخت به کارت به کارت تغییر یافت. لطفاً پس از واریز فیش را ثبت فرمایید.',
paymentMethod: 'card',
orderId: order.id,
};
@@ -15,12 +15,16 @@ export class AdminTransactionFilterDto {
@IsNumber()
limit?: number = 15;
@ApiPropertyOptional({ description: 'جستجو (نام، موبایل، کد پیگیری، شماره مرجع، کد رهگیری)' })
@ApiPropertyOptional({
description: 'جستجو (نام، موبایل، کد پیگیری، شماره مرجع، کد رهگیری)',
})
@IsOptional()
@IsString()
search?: string;
@ApiPropertyOptional({ description: 'فیلتر وضعیت (VERIFIED, PENDING, FAILED)' })
@ApiPropertyOptional({
description: 'فیلتر وضعیت (VERIFIED, PENDING, FAILED)',
})
@IsOptional()
@IsString()
status?: string;
@@ -30,7 +34,9 @@ export class AdminTransactionFilterDto {
@IsString()
gateway?: string;
@ApiPropertyOptional({ description: 'فیلتر نوع تراکنش (ORDER, WALLET_TOPUP)' })
@ApiPropertyOptional({
description: 'فیلتر نوع تراکنش (ORDER, WALLET_TOPUP)',
})
@IsOptional()
@IsString()
type?: string;
@@ -62,7 +68,10 @@ export class AdminTransactionFilterDto {
@IsString()
sortBy?: string = 'createdAt';
@ApiPropertyOptional({ description: 'جهت مرتب‌سازی (asc, desc)', default: 'desc' })
@ApiPropertyOptional({
description: 'جهت مرتب‌سازی (asc, desc)',
default: 'desc',
})
@IsOptional()
@IsIn(['asc', 'desc'])
sortOrder?: 'asc' | 'desc' = 'desc';
+20 -7
View File
@@ -152,10 +152,16 @@ export class PaymentController {
if (!trackId) {
throw new BadRequestException('trackId is required');
}
return this.paymentService.verifyAndProcess(trackId, success, status, orderId, {
ipAddress: ip,
userAgent,
});
return this.paymentService.verifyAndProcess(
trackId,
success,
status,
orderId,
{
ipAddress: ip,
userAgent,
},
);
}
@Post('zibal/callback')
@@ -218,7 +224,9 @@ export class PaymentController {
@Roles('Admin')
@ApiBearerAuth()
@Post('admin/reconcile')
@ApiOperation({ summary: 'اجرای فرایند انطباق و استعلام خودکار تراکنش‌های بلاتکلیف' })
@ApiOperation({
summary: 'اجرای فرایند انطباق و استعلام خودکار تراکنش‌های بلاتکلیف',
})
async reconcilePending() {
return this.paymentService.reconcilePendingTransactions();
}
@@ -236,7 +244,9 @@ export class PaymentController {
@Roles('Admin')
@ApiBearerAuth()
@Post('admin/manual-verify/:id')
@ApiOperation({ summary: 'تایید دستی تراکنش یا فیش واریزی کارت‌به‌کارت توسط ادمین' })
@ApiOperation({
summary: 'تایید دستی تراکنش یا فیش واریزی کارت‌به‌کارت توسط ادمین',
})
async manualVerify(
@Param('id') id: string,
@Body() body: { adminNote?: string },
@@ -260,7 +270,10 @@ export class PaymentController {
@Roles('Admin')
@ApiBearerAuth()
@Get('admin/health')
@ApiOperation({ summary: 'بررسی وضعیت آنلاین بودن و سلامت درگاه پرداخت (Health Check & Latency)' })
@ApiOperation({
summary:
'بررسی وضعیت آنلاین بودن و سلامت درگاه پرداخت (Health Check & Latency)',
})
async getHealth() {
return this.paymentService.checkGatewayHealth();
}
+55 -23
View File
@@ -58,7 +58,8 @@ export class PaymentService {
const backendUrl = await this.zibalService.getBackendUrl();
const callbackUrl =
customCallbackUrl || `${backendUrl}/payment/zibal/callback?orderId=${order.id}`;
customCallbackUrl ||
`${backendUrl}/payment/zibal/callback?orderId=${order.id}`;
const requestPayload = {
amountRials,
@@ -81,7 +82,7 @@ export class PaymentService {
description: `پرداخت آنلاین سفارش ${order.trackingNumber || order.id}`,
ipAddress: clientMeta?.ipAddress,
userAgent: clientMeta?.userAgent,
rawRequest: requestPayload as unknown as Prisma.InputJsonValue,
rawRequest: requestPayload,
},
});
@@ -153,7 +154,8 @@ export class PaymentService {
const amountRials = Math.round(amountTomans * 10);
const backendUrl = await this.zibalService.getBackendUrl();
const callbackUrl =
customCallbackUrl || `${backendUrl}/payment/zibal/callback?type=WALLET_TOPUP`;
customCallbackUrl ||
`${backendUrl}/payment/zibal/callback?type=WALLET_TOPUP`;
const requestPayload = {
amountRials,
@@ -173,7 +175,7 @@ export class PaymentService {
description: `افزایش موجودی کیف پول کاربر ${user.mobile}`,
ipAddress: clientMeta?.ipAddress,
userAgent: clientMeta?.userAgent,
rawRequest: requestPayload as unknown as Prisma.InputJsonValue,
rawRequest: requestPayload,
},
});
@@ -355,8 +357,7 @@ export class PaymentService {
// --- AMOUNT MATCH VERIFICATION ---
const expectedAmountRials = Number(
transaction.amountRials ||
Math.round(Number(transaction.amount) * 10),
transaction.amountRials || Math.round(Number(transaction.amount) * 10),
);
if (
@@ -572,10 +573,23 @@ export class PaymentService {
`Inquiry for trackId=${tx.trackId}: status=${inquiry.status}, result=${inquiry.result}`,
);
if (inquiry.status === 1 || inquiry.status === 2 || inquiry.result === 100) {
await this.verifyAndProcess(tx.trackId, '1', String(inquiry.status), tx.orderId || undefined);
if (
inquiry.status === 1 ||
inquiry.status === 2 ||
inquiry.result === 100
) {
await this.verifyAndProcess(
tx.trackId,
'1',
String(inquiry.status),
tx.orderId || undefined,
);
results.verified++;
} else if (inquiry.status === 3 || inquiry.status === -2 || inquiry.result === 202) {
} else if (
inquiry.status === 3 ||
inquiry.status === -2 ||
inquiry.result === 202
) {
const msg = this.zibalService.getStatusMessage(inquiry.status || 3);
await this.prisma.paymentTransaction.update({
where: { id: tx.id },
@@ -654,12 +668,14 @@ export class PaymentService {
paidAt: transaction.paidAt,
createdAt: transaction.createdAt,
order: transaction.order,
user: transaction.user ? {
id: transaction.user.id,
firstName: transaction.user.firstName,
lastName: transaction.user.lastName,
mobile: transaction.user.mobile,
} : null,
user: transaction.user
? {
id: transaction.user.id,
firstName: transaction.user.firstName,
lastName: transaction.user.lastName,
mobile: transaction.user.mobile,
}
: null,
};
}
@@ -705,8 +721,10 @@ export class PaymentService {
if (minAmount !== undefined || maxAmount !== undefined) {
where.amount = {};
if (minAmount !== undefined) where.amount.gte = new Prisma.Decimal(minAmount);
if (maxAmount !== undefined) where.amount.lte = new Prisma.Decimal(maxAmount);
if (minAmount !== undefined)
where.amount.gte = new Prisma.Decimal(minAmount);
if (maxAmount !== undefined)
where.amount.lte = new Prisma.Decimal(maxAmount);
}
if (search && search.trim() !== '') {
@@ -838,13 +856,19 @@ export class PaymentService {
throw new BadRequestException('این تراکنش فاقد TrackId زیبال است');
}
const inquiryRes = await this.zibalService.inquiryPayment(transaction.trackId);
const statusMsg = this.zibalService.getStatusMessage(inquiryRes.status ?? 3);
const inquiryRes = await this.zibalService.inquiryPayment(
transaction.trackId,
);
const statusMsg = this.zibalService.getStatusMessage(
inquiryRes.status ?? 3,
);
const resultMsg = this.zibalService.getResultMessage(inquiryRes.result);
if (
transaction.status === 'PENDING' &&
(inquiryRes.status === 1 || inquiryRes.status === 2 || inquiryRes.result === 100)
(inquiryRes.status === 1 ||
inquiryRes.status === 2 ||
inquiryRes.result === 100)
) {
await this.verifyAndProcess(
transaction.trackId,
@@ -891,7 +915,9 @@ export class PaymentService {
where: { id: transactionId },
data: {
status: 'VERIFIED',
message: adminNote || 'تایید دستی توسط مدیر سیستم (کارت به کارت / فیش بانکی)',
message:
adminNote ||
'تایید دستی توسط مدیر سیستم (کارت به کارت / فیش بانکی)',
paidAt: new Date(),
},
});
@@ -924,7 +950,10 @@ export class PaymentService {
}
});
return { success: true, message: 'تراکنش با موفقیت به صورت دستی تایید و اعمال شد' };
return {
success: true,
message: 'تراکنش با موفقیت به صورت دستی تایید و اعمال شد',
};
}
/**
@@ -947,7 +976,10 @@ export class PaymentService {
},
});
return { success: true, message: 'تراکنش به عنوان ناموفق/رد شده علامت‌گذاری شد' };
return {
success: true,
message: 'تراکنش به عنوان ناموفق/رد شده علامت‌گذاری شد',
};
}
/**
+25 -10
View File
@@ -73,7 +73,9 @@ export class ZibalService implements IPaymentGateway {
if (attempt < maxRetries) {
const delayMs = delays[attempt - 1] || 1000;
this.logger.log(`Waiting ${delayMs}ms before retry attempt ${attempt + 1}...`);
this.logger.log(
`Waiting ${delayMs}ms before retry attempt ${attempt + 1}...`,
);
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
}
@@ -151,10 +153,12 @@ export class ZibalService implements IPaymentGateway {
* 1. Request Payment (درخواست پرداخت با قابلیت Retry)
* Amount must be in Rials.
*/
async requestPayment(params: PaymentRequestOptions & {
nationalCode?: string;
allowedCards?: string[];
}): Promise<ZibalRequestResponse> {
async requestPayment(
params: PaymentRequestOptions & {
nationalCode?: string;
allowedCards?: string[];
},
): Promise<ZibalRequestResponse> {
const merchant = await this.getMerchant();
const payload = {
@@ -188,7 +192,9 @@ export class ZibalService implements IPaymentGateway {
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Zibal request HTTP ${response.status}: ${errorText}`);
throw new Error(
`Zibal request HTTP ${response.status}: ${errorText}`,
);
}
const data = (await response.json()) as ZibalRequestResponse;
@@ -218,7 +224,9 @@ export class ZibalService implements IPaymentGateway {
};
return this.callWithRetry(async () => {
this.logger.log(`Verifying payment for trackId=${trackId}, merchant=${merchant}`);
this.logger.log(
`Verifying payment for trackId=${trackId}, merchant=${merchant}`,
);
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000);
@@ -249,7 +257,9 @@ export class ZibalService implements IPaymentGateway {
/**
* 4. Inquiry Payment (استعلام تراکنش با قابلیت Retry)
*/
async inquiryPayment(trackId: string | number): Promise<ZibalInquiryResponse> {
async inquiryPayment(
trackId: string | number,
): Promise<ZibalInquiryResponse> {
const merchant = await this.getMerchant();
const payload = {
@@ -275,7 +285,9 @@ export class ZibalService implements IPaymentGateway {
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Zibal inquiry HTTP ${response.status}: ${errorText}`);
throw new Error(
`Zibal inquiry HTTP ${response.status}: ${errorText}`,
);
}
const data = (await response.json()) as ZibalInquiryResponse;
@@ -313,7 +325,10 @@ export class ZibalService implements IPaymentGateway {
status: latencyMs < 1500 ? 'ONLINE' : 'DEGRADED',
latencyMs,
merchantConfigured: merchant !== 'zibal',
activeMerchant: merchant === 'zibal' ? 'zibal (تستی/سندباکس)' : `${merchant.slice(0, 4)}****`,
activeMerchant:
merchant === 'zibal'
? 'zibal (تستی/سندباکس)'
: `${merchant.slice(0, 4)}****`,
message: 'اتصال به درگاه زیبال با موفقیت برقرار است',
checkedAt: new Date(),
};
@@ -153,7 +153,10 @@ export class PrescriptionsService {
try {
await this.smsService.sendSms(item.user.mobile, smsText);
} catch (smsErr) {
this.logger.warn(`Failed to send prescription SMS to ${item.user.mobile}:`, smsErr);
this.logger.warn(
`Failed to send prescription SMS to ${item.user.mobile}:`,
smsErr,
);
}
}
+5 -2
View File
@@ -76,14 +76,17 @@ export class PrismaService
)`,
`CREATE INDEX IF NOT EXISTS "product_reviews_product_id_idx" ON "product_reviews"("product_id")`,
`CREATE INDEX IF NOT EXISTS "product_reviews_status_idx" ON "product_reviews"("status")`,
`CREATE INDEX IF NOT EXISTS "product_reviews_created_at_idx" ON "product_reviews"("created_at")`
`CREATE INDEX IF NOT EXISTS "product_reviews_created_at_idx" ON "product_reviews"("created_at")`,
];
for (const sql of ddlStatements) {
try {
await this.$executeRawUnsafe(sql);
} catch (err: any) {
console.warn(`[PrismaService] DDL execution note for (${sql.substring(0, 40)}...):`, err?.message || err);
console.warn(
`[PrismaService] DDL execution note for (${sql.substring(0, 40)}...):`,
err?.message || err,
);
}
}
}
+22 -4
View File
@@ -1,4 +1,11 @@
import { IsString, IsNotEmpty, IsInt, Min, Max, IsOptional } from 'class-validator';
import {
IsString,
IsNotEmpty,
IsInt,
Min,
Max,
IsOptional,
} from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class CreateReviewDto {
@@ -8,17 +15,28 @@ export class CreateReviewDto {
@Max(5)
rating: number;
@ApiProperty({ description: 'متن دیدگاه یا نظر کاربر', example: 'کیفیت عالی و اثربخشی فوق‌العاده' })
@ApiProperty({
description: 'متن دیدگاه یا نظر کاربر',
example: 'کیفیت عالی و اثربخشی فوق‌العاده',
})
@IsString()
@IsNotEmpty({ message: 'متن نظر نمی‌تواند خالی باشد' })
comment: string;
@ApiProperty({ description: 'نام نمایشی کاربر', required: false, example: 'امیر رضایی' })
@ApiProperty({
description: 'نام نمایشی کاربر',
required: false,
example: 'امیر رضایی',
})
@IsString()
@IsOptional()
userName?: string;
@ApiProperty({ description: 'شماره تماس کاربر', required: false, example: '09123456789' })
@ApiProperty({
description: 'شماره تماس کاربر',
required: false,
example: '09123456789',
})
@IsString()
@IsOptional()
userPhone?: string;
+5 -1
View File
@@ -2,7 +2,11 @@ import { IsString, IsIn, IsOptional } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class UpdateReviewDto {
@ApiProperty({ description: 'وضعیت بررسی نظر', enum: ['PENDING', 'APPROVED', 'REJECTED'], required: false })
@ApiProperty({
description: 'وضعیت بررسی نظر',
enum: ['PENDING', 'APPROVED', 'REJECTED'],
required: false,
})
@IsString()
@IsIn(['PENDING', 'APPROVED', 'REJECTED'])
@IsOptional()
+25 -6
View File
@@ -1,4 +1,9 @@
import { Injectable, NotFoundException, BadRequestException, Logger } from '@nestjs/common';
import {
Injectable,
NotFoundException,
BadRequestException,
Logger,
} from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateReviewDto } from './dto/create-review.dto';
import { UpdateReviewDto } from './dto/update-review.dto';
@@ -32,7 +37,9 @@ export class ReviewsService {
});
if (user) {
if (!resolvedName) {
resolvedName = `${user.firstName || ''} ${user.lastName || ''}`.trim() || 'کاربر کنینا';
resolvedName =
`${user.firstName || ''} ${user.lastName || ''}`.trim() ||
'کاربر کنینا';
}
if (!resolvedPhone) {
resolvedPhone = user.mobile;
@@ -58,7 +65,8 @@ export class ReviewsService {
return {
success: true,
message: 'دیدگاه شما با موفقیت ثبت شد و پس از بررسی و تایید کارشناسان در سایت نمایش داده می‌شود.',
message:
'دیدگاه شما با موفقیت ثبت شد و پس از بررسی و تایید کارشناسان در سایت نمایش داده می‌شود.',
data: review,
};
}
@@ -66,7 +74,11 @@ export class ReviewsService {
/**
* 2. Get approved reviews for a single product with pagination and rating statistics
*/
async getProductReviews(productId: string, page: number = 1, limit: number = 10) {
async getProductReviews(
productId: string,
page: number = 1,
limit: number = 10,
) {
const skip = (Math.max(1, page) - 1) * limit;
const [reviews, total, aggregateRating] = await Promise.all([
@@ -157,7 +169,13 @@ export class ReviewsService {
take: limit,
include: {
product: {
select: { id: true, nameFa: true, nameEn: true, slug: true, imageUrl: true },
select: {
id: true,
nameFa: true,
nameEn: true,
slug: true,
imageUrl: true,
},
},
user: {
select: { id: true, firstName: true, lastName: true, mobile: true },
@@ -195,7 +213,8 @@ export class ReviewsService {
where: { id },
data: {
status: dto.status || review.status,
adminReply: dto.adminReply !== undefined ? dto.adminReply : review.adminReply,
adminReply:
dto.adminReply !== undefined ? dto.adminReply : review.adminReply,
},
});
+141 -125
View File
@@ -1,148 +1,164 @@
export const DEFAULT_UI_TEXTS: Record<string, string> = {
// === Catalog & Maintenance Mode ===
"maintenance_mode": "false",
"maintenance_title": "سامانه در حال به‌روزرسانی و ارتقای فنی است",
"maintenance_desc": "وب‌سایت رسمی کنینا ایران جهت ارتقای زیرساخت‌ها و بهبود عملکرد به صورت موقت در دست به‌روزرسانی است. از شکیبایی شما سپاسگزاریم.",
"maintenance_eta": "زمان تقریبی بازگشایی: کمتر از ۲ ساعت آینده",
"maintenance_contact_phone": "۰۲۱-۸۸۸۸۸۸۸۸",
"maintenance_contact_phone_link": "tel:02188888888",
"maintenance_badge": "سامانه در حال ارتقا",
"catalog_mode": "false",
"catalog_hide_prices": "false",
"catalog_disable_cart": "false",
"catalog_disable_checkout": "false",
maintenance_mode: 'false',
maintenance_title: 'سامانه در حال به‌روزرسانی و ارتقای فنی است',
maintenance_desc:
'وب‌سایت رسمی کنینا ایران جهت ارتقای زیرساخت‌ها و بهبود عملکرد به صورت موقت در دست به‌روزرسانی است. از شکیبایی شما سپاسگزاریم.',
maintenance_eta: 'زمان تقریبی بازگشایی: کمتر از ۲ ساعت آینده',
maintenance_contact_phone: '۰۲۱-۸۸۸۸۸۸۸۸',
maintenance_contact_phone_link: 'tel:02188888888',
maintenance_badge: 'سامانه در حال ارتقا',
catalog_mode: 'false',
catalog_hide_prices: 'false',
catalog_disable_cart: 'false',
catalog_disable_checkout: 'false',
// === Brand & Logo ===
"site_logo": "",
"site_logo_text_en": "Canina",
"site_logo_text_fa": "ایران",
"site_logo_subtitle": "نماینده رسمی CANINA PHARMA GMBH GERMANY",
"contact_phone": "۰۲۱-۸۸۸۸۴۴۴۴",
"contact_phone_link": "tel:02188884444",
"contact_email": "info@canina.ir",
"contact_address": "تهران، جردن، خیابان سعیدی، ساختمان کنینا، طبقه ۵، واحد ۱۹",
"contact_whatsapp": "09120000000",
"contact_telegram": "https://t.me/canina_iran",
"contact_instagram": "https://instagram.com/canina_iran",
site_logo: '',
site_logo_text_en: 'Canina',
site_logo_text_fa: 'ایران',
site_logo_subtitle: 'نماینده رسمی CANINA PHARMA GMBH GERMANY',
contact_phone: '۰۲۱-۸۸۸۸۴۴۴۴',
contact_phone_link: 'tel:02188884444',
contact_email: 'info@canina.ir',
contact_address: 'تهران، جردن، خیابان سعیدی، ساختمان کنینا، طبقه ۵، واحد ۱۹',
contact_whatsapp: '09120000000',
contact_telegram: 'https://t.me/canina_iran',
contact_instagram: 'https://instagram.com/canina_iran',
// === Header / Navigation ===
"shipping_notice": "ارسال رایگان برای سفارش‌های بالای ۱۵۰ هزار تومان — گارانتی اصالت کنینا آلمان",
"brand_name_fa": "کنینا ایران",
"brand_subtitle": "نمایندگی رسمی مکمل‌های دارویی کنینا آلمان",
"nav_solutions": "راهکارهای درمانی",
"nav_products": "محصولات تخصصی",
"nav_wiki": "دانشنامه علمی",
"nav_blog": "مجله سلامت پت",
"nav_pet_profiles": "شناسنامه پت‌ها",
"nav_search_placeholder": "جستجوی محصولات، علائم بالینی، مقالات سلامت...",
"nav_search_button": "جستجو",
"nav_pet_switcher_title": "تغییر پت یا مدیریت پرونده سلامت",
"nav_register_pet": "ثبت همدم (Pet) جدید",
"nav_wallet_orders": "کیف پول و سفارشات",
"nav_logout": "خروج از حساب",
"nav_login": "ورود / ثبت‌نام",
"nav_cart": "سبد خرید",
shipping_notice:
'ارسال رایگان برای سفارش‌های بالای ۱۵۰ هزار تومان — گارانتی اصالت کنینا آلمان',
brand_name_fa: 'کنینا ایران',
brand_subtitle: 'نمایندگی رسمی مکمل‌های دارویی کنینا آلمان',
nav_solutions: 'راهکارهای درمانی',
nav_products: 'محصولات تخصصی',
nav_wiki: 'دانشنامه علمی',
nav_blog: 'مجله سلامت پت',
nav_pet_profiles: 'شناسنامه پت‌ها',
nav_search_placeholder: 'جستجوی محصولات، علائم بالینی، مقالات سلامت...',
nav_search_button: 'جستجو',
nav_pet_switcher_title: 'تغییر پت یا مدیریت پرونده سلامت',
nav_register_pet: 'ثبت همدم (Pet) جدید',
nav_wallet_orders: 'کیف پول و سفارشات',
nav_logout: 'خروج از حساب',
nav_login: 'ورود / ثبت‌نام',
nav_cart: 'سبد خرید',
// === Hero Section ===
"hero_badge": "از ۱۹۸۴ در خدمت سلامت حیوانات",
"hero_title": "تخصص آلمانی در خدمت سلامت پت‌های خانگی",
"hero_desc": "از سال ۱۹۸۴، شرکت Canina pharma GmbH در آلمان با بهره‌گیری از مواد اولیه ارگانیک و پیشرفته‌ترین فرمولاسیون دامپزشکی، استاندارد طلایی مکمل‌های بالینی را ارائه می‌دهد.",
"hero_btn_advisor": "دستیار هوشمند سلامت پت",
"hero_btn_products": "مشاهده محصولات",
"hero_image_badge": "سرآمد علمی در پزشکی پت‌ها",
"hero_image_title": "مکمل‌های تایید شده دامپزشکی با گواهی IFS",
"hero_quality_standard": "استاندارد کیفی آلمان (IFS & HACCP)",
"hero_image_url": "/assets/images/hero-section-image.png",
"hero_stat_founded": "۱۹۸۴ سال تأسیس",
"hero_stat_agencies": "نمایندگی‌های فعال جهانی",
"hero_stat_german_formula": "۱۰۰٪ فرمولاسیون آلمانی",
hero_badge: 'از ۱۹۸۴ در خدمت سلامت حیوانات',
hero_title: 'تخصص آلمانی در خدمت سلامت پت‌های خانگی',
hero_desc:
'از سال ۱۹۸۴، شرکت Canina pharma GmbH در آلمان با بهره‌گیری از مواد اولیه ارگانیک و پیشرفته‌ترین فرمولاسیون دامپزشکی، استاندارد طلایی مکمل‌های بالینی را ارائه می‌دهد.',
hero_btn_advisor: 'دستیار هوشمند سلامت پت',
hero_btn_products: 'مشاهده محصولات',
hero_image_badge: 'سرآمد علمی در پزشکی پت‌ها',
hero_image_title: 'مکمل‌های تایید شده دامپزشکی با گواهی IFS',
hero_quality_standard: 'استاندارد کیفی آلمان (IFS & HACCP)',
hero_image_url: '/assets/images/hero-section-image.png',
hero_stat_founded: '۱۹۸۴ سال تأسیس',
hero_stat_agencies: 'نمایندگی‌های فعال جهانی',
hero_stat_german_formula: '۱۰۰٪ فرمولاسیون آلمانی',
// === Smart Advisor ===
"advisor_badge": "تکنولوژی پایش هوشمند",
"advisor_title": "دستیار هوشمند سلامت کنینا",
"advisor_subtitle": "تنها با چند کلیک شناسنامه سلامت پت خود را تکمیل کرده و مشاوره تخصصی دریافت کنید",
"advisor_step1_title": "گام اول: مشخصات و هویت پت",
"advisor_step1_desc": "نام و نژاد همدم دوست‌داشتنی شما چیست؟",
"advisor_pet_name_label": "نام پت",
"advisor_pet_name_placeholder": "مثلاً لوسی، تدی، ببری...",
"advisor_pet_breed_label": "نژاد پت",
"advisor_pet_breed_placeholder": "مثلاً ژرمن شپرد، پرشین، هاسکی...",
"advisor_submit_btn": "ثبت و ادامه به مرحله بعد",
"advisor_validation_warning": "لطفاً ابتدا نام و نژاد پت را وارد نمایید.",
"advisor_step2_title": "گام دوم: پایش فیزیکی و سطح فعالیت",
"advisor_step2_desc": "اطلاعات فیزیکی به محاسبه دقیق دوز مصرفی کمک می‌کند",
"advisor_age_label": "سن (سال)",
"advisor_weight_label": "وزن تقریبی (کیلوگرم)",
"advisor_activity_label": "سطح فعالیت روزانه",
"advisor_back": "مرحله قبل",
"advisor_next_final": "ادامه به مرحله نهایی",
"advisor_step3_title": "گام آخر: سوابق پزشکی و نیازهای ویژه",
"advisor_step3_desc": "در صورت وجود هرگونه حساسیت یا نیاز درمانی آن را مشخص کنید",
"advisor_complete": "صدور شناسنامه و دریافت رژیم سلامتی",
advisor_badge: 'تکنولوژی پایش هوشمند',
advisor_title: 'دستیار هوشمند سلامت کنینا',
advisor_subtitle:
'تنها با چند کلیک شناسنامه سلامت پت خود را تکمیل کرده و مشاوره تخصصی دریافت کنید',
advisor_step1_title: 'گام اول: مشخصات و هویت پت',
advisor_step1_desc: 'نام و نژاد همدم دوست‌داشتنی شما چیست؟',
advisor_pet_name_label: 'نام پت',
advisor_pet_name_placeholder: 'مثلاً لوسی، تدی، ببری...',
advisor_pet_breed_label: 'نژاد پت',
advisor_pet_breed_placeholder: 'مثلاً ژرمن شپرد، پرشین، هاسکی...',
advisor_submit_btn: 'ثبت و ادامه به مرحله بعد',
advisor_validation_warning: 'لطفاً ابتدا نام و نژاد پت را وارد نمایید.',
advisor_step2_title: 'گام دوم: پایش فیزیکی و سطح فعالیت',
advisor_step2_desc: 'اطلاعات فیزیکی به محاسبه دقیق دوز مصرفی کمک می‌کند',
advisor_age_label: 'سن (سال)',
advisor_weight_label: 'وزن تقریبی (کیلوگرم)',
advisor_activity_label: 'سطح فعالیت روزانه',
advisor_back: 'مرحله قبل',
advisor_next_final: 'ادامه به مرحله نهایی',
advisor_step3_title: 'گام آخر: سوابق پزشکی و نیازهای ویژه',
advisor_step3_desc:
'در صورت وجود هرگونه حساسیت یا نیاز درمانی آن را مشخص کنید',
advisor_complete: 'صدور شناسنامه و دریافت رژیم سلامتی',
// === Featured Products ===
"featured_badge": "انتخاب نخست دامپزشکان و کلینیک‌ها",
"featured_title_line1": "محصولات برگزیده و راهکارهای",
"featured_title_line2": "درمان تخصصی بالینی",
"featured_desc": "مکمل‌های تخصصی دارویی کنینا با بالاترین درجه خلوص مواد اولیه در آلمان فرآوری شده‌اند.",
"featured_view_all": "مشاهده کاتالوگ کامل محصولات",
"product_view_details": "مشاهده جزئیات و خرید",
"featured_no_products_title": "محصولی یافت نشد",
"featured_no_products_desc": "در حال حاضر محصولی در این دسته موجود نمی‌باشد.",
featured_badge: 'انتخاب نخست دامپزشکان و کلینیک‌ها',
featured_title_line1: 'محصولات برگزیده و راهکارهای',
featured_title_line2: 'درمان تخصصی بالینی',
featured_desc:
'مکمل‌های تخصصی دارویی کنینا با بالاترین درجه خلوص مواد اولیه در آلمان فرآوری شده‌اند.',
featured_view_all: 'مشاهده کاتالوگ کامل محصولات',
product_view_details: 'مشاهده جزئیات و خرید',
featured_no_products_title: 'محصولی یافت نشد',
featured_no_products_desc: 'در حال حاضر محصولی در این دسته موجود نمی‌باشد.',
// === Videos & Media ===
"videos_badge": "ویدئوهای آموزشی دامپزشکی",
"videos_title": "توصیه‌های بالینی و ویدئویی",
"videos_title_highlight": "متخصصان و دامپزشکان",
"videos_desc": "مشاهده نحوه مصرف صحیح، عملکرد بیولوژیکی و پاسخ به پرسش‌های پرتکرار سرپرستان پت.",
"videos_view_all": "مشاهده تمامی ویدئوها",
videos_badge: 'ویدئوهای آموزشی دامپزشکی',
videos_title: 'توصیه‌های بالینی و ویدئویی',
videos_title_highlight: 'متخصصان و دامپزشکان',
videos_desc:
'مشاهده نحوه مصرف صحیح، عملکرد بیولوژیکی و پاسخ به پرسش‌های پرتکرار سرپرستان پت.',
videos_view_all: 'مشاهده تمامی ویدئوها',
// === Navigation Cards ===
"nav_card_shop_title": "داروخانه تخصصی مکمل‌ها",
"nav_card_shop_desc": "دسته‌بندی جامع بر اساس نیازهای مفاصل، پوست و مو، رشد، گوارش و ایمنی.",
"nav_card_shop_cta": "ورود به فروشگاه",
"nav_card_wiki_title": "دانشنامه علمی و مقالات",
"nav_card_wiki_desc": "جدیدترین مقالات تخصصی سلامت و تغذیه حیوانات خانگی با ترجمه متون علمی آلمان.",
"nav_card_wiki_cta": "مطالعه دانشنامه",
nav_card_shop_title: 'داروخانه تخصصی مکمل‌ها',
nav_card_shop_desc:
'دسته‌بندی جامع بر اساس نیازهای مفاصل، پوست و مو، رشد، گوارش و ایمنی.',
nav_card_shop_cta: 'ورود به فروشگاه',
nav_card_wiki_title: 'دانشنامه علمی و مقالات',
nav_card_wiki_desc:
'جدیدترین مقالات تخصصی سلامت و تغذیه حیوانات خانگی با ترجمه متون علمی آلمان.',
nav_card_wiki_cta: 'مطالعه دانشنامه',
// === About Us ===
"about_label": "درباره برند کنینا",
"about_title": "چرا کنینا آلمان انتخاب اول متخصصان است؟",
"about_item1_title": "مواد اولیه ۱۰۰٪ طبیعی",
"about_item1_desc": "استفاده از عصاره صدف سبز نیوزیلند و املاح معدنی ارگانیک با جذب زیستی بالا.",
"about_item2_title": "فاقد افزودنی‌های مضر",
"about_item2_desc": "بدون رنگ‌های مصنوعی، نگهدارنده‌های شیمیایی و قندهای افزودنی.",
"about_item3_title": "استاندارد دارویی اروپا",
"about_item3_desc": "تولید مطابق استانداردهای سخت‌گیرانه داروسازی آلمان IFS و HACCP.",
about_label: 'درباره برند کنینا',
about_title: 'چرا کنینا آلمان انتخاب اول متخصصان است؟',
about_item1_title: 'مواد اولیه ۱۰۰٪ طبیعی',
about_item1_desc:
'استفاده از عصاره صدف سبز نیوزیلند و املاح معدنی ارگانیک با جذب زیستی بالا.',
about_item2_title: 'فاقد افزودنی‌های مضر',
about_item2_desc:
'بدون رنگ‌های مصنوعی، نگهدارنده‌های شیمیایی و قندهای افزودنی.',
about_item3_title: 'استاندارد دارویی اروپا',
about_item3_desc:
'تولید مطابق استانداردهای سخت‌گیرانه داروسازی آلمان IFS و HACCP.',
// === CTA Section ===
"cta_title": "می‌خواهید بدانید کدام محصول برای پت شما مناسب‌تر است؟",
"cta_desc": "با استفاده از دستیار هوشمند سلامت یا مشاوره رایگان با دامپزشکان ما، بهترین برنامه مکمل را انتخاب کنید.",
"cta_btn_primary": "شروع ارزیابی هوشمند پت",
"cta_btn_secondary": "مشاوره با دامپزشک",
cta_title: 'می‌خواهید بدانید کدام محصول برای پت شما مناسب‌تر است؟',
cta_desc:
'با استفاده از دستیار هوشمند سلامت یا مشاوره رایگان با دامپزشکان ما، بهترین برنامه مکمل را انتخاب کنید.',
cta_btn_primary: 'شروع ارزیابی هوشمند پت',
cta_btn_secondary: 'مشاوره با دامپزشک',
// === Footer ===
"footer_brand_title": "کنینا ایران (Canina Iran)",
"footer_brand_subtitle": "نمایندگی رسمی شرکت Canina pharma GmbH آلمان",
"footer_brand_desc": "تولیدکننده و توزیع‌کننده برتر مکمل‌های دارویی و بهداشتی با بیش از ۴۰ سال سابقه در آلمان و عرضه رسمی در ایران.",
"footer_links_title": "دسترسی سریع",
"footer_link_products": "کاتالوگ محصولات",
"footer_link_blog": "مجله سلامت و مقالات",
"footer_link_profiles": "شناسنامه و پرونده پت‌ها",
"footer_link_wiki": "دانشنامه دارویی",
"footer_link_b2b": "پرتال همکاری و دامپزشکان",
"footer_contact_title": "ارتباط با پشتیبانی",
"footer_phone_label": "تلفن تماس",
"footer_phone": "۰۲۱-۸۸۸۸۸۸۸۸",
"footer_email_label": "پست الکترونیک",
"footer_email": "info@canina.ir",
"footer_address_label": "نشانی مرکزی",
"footer_address": "تهران، خیابان ولیعصر، برج تجاری کنینا",
"footer_auth_title": "ضمانت اصالت کالا",
"footer_auth_desc": "کلیه محصولات دارای برچسب اصالت و مجوز واردات رسمی می‌باشند.",
"footer_auth_badge": "تضمین ۱۰۰٪ اصالت کالا",
"footer_copyright": "تمامی حقوق مادی و معنوی این وب‌سایت متعلق به شرکت کنینا ایران می‌باشد.",
"footer_about": "درباره ما",
"footer_contact": "تماس با ما",
"footer_privacy": "حریم خصوصی و قوانین",
footer_brand_title: 'کنینا ایران (Canina Iran)',
footer_brand_subtitle: 'نمایندگی رسمی شرکت Canina pharma GmbH آلمان',
footer_brand_desc:
'تولیدکننده و توزیع‌کننده برتر مکمل‌های دارویی و بهداشتی با بیش از ۴۰ سال سابقه در آلمان و عرضه رسمی در ایران.',
footer_links_title: 'دسترسی سریع',
footer_link_products: 'کاتالوگ محصولات',
footer_link_blog: 'مجله سلامت و مقالات',
footer_link_profiles: 'شناسنامه و پرونده پت‌ها',
footer_link_wiki: 'دانشنامه دارویی',
footer_link_b2b: 'پرتال همکاری و دامپزشکان',
footer_contact_title: 'ارتباط با پشتیبانی',
footer_phone_label: 'تلفن تماس',
footer_phone: '۰۲۱-۸۸۸۸۸۸۸۸',
footer_email_label: 'پست الکترونیک',
footer_email: 'info@canina.ir',
footer_address_label: 'نشانی مرکزی',
footer_address: 'تهران، خیابان ولیعصر، برج تجاری کنینا',
footer_auth_title: 'ضمانت اصالت کالا',
footer_auth_desc:
'کلیه محصولات دارای برچسب اصالت و مجوز واردات رسمی می‌باشند.',
footer_auth_badge: 'تضمین ۱۰۰٪ اصالت کالا',
footer_copyright:
'تمامی حقوق مادی و معنوی این وب‌سایت متعلق به شرکت کنینا ایران می‌باشد.',
footer_about: 'درباره ما',
footer_contact: 'تماس با ما',
footer_privacy: 'حریم خصوصی و قوانین',
};
+13 -3
View File
@@ -15,7 +15,10 @@ export class SmsLogQueryDto {
@IsNumber()
limit?: number;
@ApiPropertyOptional({ description: 'جستجو در گیرنده، پیام یا شناسه', example: '0912' })
@ApiPropertyOptional({
description: 'جستجو در گیرنده، پیام یا شناسه',
example: '0912',
})
@IsOptional()
@IsString()
search?: string;
@@ -30,12 +33,19 @@ export class SmsLogQueryDto {
@IsString()
status?: string;
@ApiPropertyOptional({ description: 'مرتب‌سازی بر اساس فیلد', example: 'createdAt' })
@ApiPropertyOptional({
description: 'مرتب‌سازی بر اساس فیلد',
example: 'createdAt',
})
@IsOptional()
@IsString()
sortBy?: string;
@ApiPropertyOptional({ description: 'ترتیب مرتب‌سازی', example: 'desc', enum: ['asc', 'desc'] })
@ApiPropertyOptional({
description: 'ترتیب مرتب‌سازی',
example: 'desc',
enum: ['asc', 'desc'],
})
@IsOptional()
@IsIn(['asc', 'desc'])
sortOrder?: 'asc' | 'desc';
+10 -6
View File
@@ -42,14 +42,16 @@ export class SettingsController {
@Roles('Admin')
@ApiBearerAuth()
@Put('ui-texts/:key')
@ApiOperation({ summary: 'ویرایش یا ثبت متن یک کلید در رابط کاربری با متد PUT' })
@ApiOperation({
summary: 'ویرایش یا ثبت متن یک کلید در رابط کاربری با متد PUT',
})
putUiText(@Param('key') key: string, @Body() body: any) {
const val =
typeof body === 'object' && body !== null && 'value' in body
? body.value
: typeof body === 'string'
? body
: JSON.stringify(body);
? body
: JSON.stringify(body);
return this.settingsService.updateUiText(key, String(val ?? ''));
}
@@ -57,14 +59,16 @@ export class SettingsController {
@Roles('Admin')
@ApiBearerAuth()
@Patch('ui-texts/:key')
@ApiOperation({ summary: 'ویرایش یا ثبت متن یک کلید در رابط کاربری با متد PATCH' })
@ApiOperation({
summary: 'ویرایش یا ثبت متن یک کلید در رابط کاربری با متد PATCH',
})
patchUiText(@Param('key') key: string, @Body() body: any) {
const val =
typeof body === 'object' && body !== null && 'value' in body
? body.value
: typeof body === 'string'
? body
: JSON.stringify(body);
? body
: JSON.stringify(body);
return this.settingsService.updateUiText(key, String(val ?? ''));
}
+95 -19
View File
@@ -25,11 +25,36 @@ export const CANONICAL_ALIASES: Record<string, string[]> = {
brand_logo_url: ['BRAND_LOGO_URL', 'site_logo'],
// Contact Info
CONTACT_PHONE: ['contact_phone', 'maintenance_contact_phone', 'footer_phone', 'supportPhone'],
contact_phone: ['CONTACT_PHONE', 'maintenance_contact_phone', 'footer_phone', 'supportPhone'],
maintenance_contact_phone: ['CONTACT_PHONE', 'contact_phone', 'footer_phone', 'supportPhone'],
footer_phone: ['CONTACT_PHONE', 'contact_phone', 'maintenance_contact_phone', 'supportPhone'],
supportPhone: ['CONTACT_PHONE', 'contact_phone', 'maintenance_contact_phone', 'footer_phone'],
CONTACT_PHONE: [
'contact_phone',
'maintenance_contact_phone',
'footer_phone',
'supportPhone',
],
contact_phone: [
'CONTACT_PHONE',
'maintenance_contact_phone',
'footer_phone',
'supportPhone',
],
maintenance_contact_phone: [
'CONTACT_PHONE',
'contact_phone',
'footer_phone',
'supportPhone',
],
footer_phone: [
'CONTACT_PHONE',
'contact_phone',
'maintenance_contact_phone',
'supportPhone',
],
supportPhone: [
'CONTACT_PHONE',
'contact_phone',
'maintenance_contact_phone',
'footer_phone',
],
CONTACT_PHONE_LINK: ['contact_phone_link', 'maintenance_contact_phone_link'],
contact_phone_link: ['CONTACT_PHONE_LINK', 'maintenance_contact_phone_link'],
@@ -97,7 +122,9 @@ export class SettingsService implements OnModuleInit {
async seedDefaultUiTexts() {
try {
const existing = await this.prisma.uiText.findMany({ select: { key: true } });
const existing = await this.prisma.uiText.findMany({
select: { key: true },
});
const existingKeys = new Set(existing.map((e) => e.key));
const missingEntries = Object.entries(DEFAULT_UI_TEXTS).filter(
@@ -109,10 +136,14 @@ export class SettingsService implements OnModuleInit {
data: missingEntries.map(([key, value]) => ({ key, value })),
skipDuplicates: true,
});
this.logger.log(`[SettingsService] Auto-seeded ${missingEntries.length} default UI texts.`);
this.logger.log(
`[SettingsService] Auto-seeded ${missingEntries.length} default UI texts.`,
);
}
} catch (err: any) {
this.logger.warn(`[SettingsService] Failed to auto-seed UI texts: ${err?.message || err}`);
this.logger.warn(
`[SettingsService] Failed to auto-seed UI texts: ${err?.message || err}`,
);
}
}
@@ -185,7 +216,12 @@ export class SettingsService implements OnModuleInit {
});
}
return { success: true, key, value: strVal, syncedKeys: Array.from(allKeysToUpdate) };
return {
success: true,
key,
value: strVal,
syncedKeys: Array.from(allKeysToUpdate),
};
}
async updateBulkUiTexts(texts: Record<string, string>) {
@@ -202,13 +238,44 @@ export class SettingsService implements OnModuleInit {
const map = new Map<string, string>();
texts.forEach((t) => map.set(t.key, t.value));
const standardShippingFee = Number(map.get('SHIPPING_FEE') || map.get('shipping_fee') || map.get('standardShippingFee') || '0');
const minOrderAmount = Number(map.get('MIN_ORDER_AMOUNT') || map.get('min_order_amount') || map.get('minOrderAmount') || '0');
const freeShippingThreshold = Number(map.get('FREE_SHIPPING_THRESHOLD') || map.get('free_shipping_threshold') || map.get('freeShippingThreshold') || '2000000');
const taxPercentage = Number(map.get('TAX_PERCENTAGE') || map.get('tax_percentage') || map.get('taxPercentage') || '10');
const b2bDiscountPercent = Number(map.get('B2B_DISCOUNT_PERCENT') || map.get('b2b_discount_percent') || map.get('b2bDiscountPercent') || '0');
const charityRoundStep = Number(map.get('CHARITY_ROUND_STEP') || map.get('charity_round_step') || map.get('charityRoundStep') || '10000');
const walletWithdrawalEnabled = map.get('walletWithdrawalEnabled') === 'true';
const standardShippingFee = Number(
map.get('SHIPPING_FEE') ||
map.get('shipping_fee') ||
map.get('standardShippingFee') ||
'0',
);
const minOrderAmount = Number(
map.get('MIN_ORDER_AMOUNT') ||
map.get('min_order_amount') ||
map.get('minOrderAmount') ||
'0',
);
const freeShippingThreshold = Number(
map.get('FREE_SHIPPING_THRESHOLD') ||
map.get('free_shipping_threshold') ||
map.get('freeShippingThreshold') ||
'2000000',
);
const taxPercentage = Number(
map.get('TAX_PERCENTAGE') ||
map.get('tax_percentage') ||
map.get('taxPercentage') ||
'10',
);
const b2bDiscountPercent = Number(
map.get('B2B_DISCOUNT_PERCENT') ||
map.get('b2b_discount_percent') ||
map.get('b2bDiscountPercent') ||
'0',
);
const charityRoundStep = Number(
map.get('CHARITY_ROUND_STEP') ||
map.get('charity_round_step') ||
map.get('charityRoundStep') ||
'10000',
);
const walletWithdrawalEnabled =
map.get('walletWithdrawalEnabled') === 'true';
return {
standardShippingFee,
@@ -305,10 +372,19 @@ export class SettingsService implements OnModuleInit {
const map = new Map<string, string>();
texts.forEach((t) => map.set(t.key, t.value));
const isMaintenance = map.get('MAINTENANCE_MODE') === 'true' || map.get('maintenance_mode') === 'true' || map.get('maintenanceMode') === 'true';
const isMaintenance =
map.get('MAINTENANCE_MODE') === 'true' ||
map.get('maintenance_mode') === 'true' ||
map.get('maintenanceMode') === 'true';
const allowGuestCheckout = map.get('allowGuestCheckout') !== 'false';
const b2bRegistrationOpen = map.get('b2bRegistrationOpen') !== 'false' && map.get('b2b_enabled') !== 'false';
const supportPhone = map.get('CONTACT_PHONE') || map.get('contact_phone') || map.get('supportPhone') || '۰۲۱-۸۸۸۸۴۴۴۴';
const b2bRegistrationOpen =
map.get('b2bRegistrationOpen') !== 'false' &&
map.get('b2b_enabled') !== 'false';
const supportPhone =
map.get('CONTACT_PHONE') ||
map.get('contact_phone') ||
map.get('supportPhone') ||
'۰۲۱-۸۸۸۸۴۴۴۴';
return {
maintenanceMode: isMaintenance,
+45 -10
View File
@@ -1,28 +1,51 @@
import { IsString, IsNotEmpty, IsOptional, IsEnum, IsArray } from 'class-validator';
import {
IsString,
IsNotEmpty,
IsOptional,
IsEnum,
IsArray,
} from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
export class CreateTicketDto {
@ApiProperty({ description: 'موضوع تیکت یا عنوان مشاوره', example: 'مشاوره مصرف مکمل کانینوکال' })
@ApiProperty({
description: 'موضوع تیکت یا عنوان مشاوره',
example: 'مشاوره مصرف مکمل کانینوکال',
})
@IsString()
@IsNotEmpty()
subject: string;
@ApiProperty({ description: 'متن پیام یا شرح وضعیت', example: 'سگ من ۵ ماهشه و می‌خواستم بدونم...' })
@ApiProperty({
description: 'متن پیام یا شرح وضعیت',
example: 'سگ من ۵ ماهشه و می‌خواستم بدونم...',
})
@IsString()
@IsNotEmpty()
message: string;
@ApiPropertyOptional({ description: 'دسته‌بندی تیکت', example: 'VET_CONSULTATION', enum: ['VET_CONSULTATION', 'ORDER_SUPPORT', 'PRODUCT_INQUIRY', 'GENERAL'] })
@ApiPropertyOptional({
description: 'دسته‌بندی تیکت',
example: 'VET_CONSULTATION',
enum: ['VET_CONSULTATION', 'ORDER_SUPPORT', 'PRODUCT_INQUIRY', 'GENERAL'],
})
@IsOptional()
@IsString()
category?: string;
@ApiPropertyOptional({ description: 'اولویت تیکت', example: 'MEDIUM', enum: ['LOW', 'MEDIUM', 'HIGH', 'URGENT'] })
@ApiPropertyOptional({
description: 'اولویت تیکت',
example: 'MEDIUM',
enum: ['LOW', 'MEDIUM', 'HIGH', 'URGENT'],
})
@IsOptional()
@IsString()
priority?: string;
@ApiPropertyOptional({ description: 'شناسه حیوان خانگی مرتبط (اختیاری)', example: '9a8f4171-86bb-4236-9d6d-e4bc60255156' })
@ApiPropertyOptional({
description: 'شناسه حیوان خانگی مرتبط (اختیاری)',
example: '9a8f4171-86bb-4236-9d6d-e4bc60255156',
})
@IsOptional()
@IsString()
petId?: string;
@@ -34,7 +57,10 @@ export class CreateTicketDto {
}
export class ReplyTicketDto {
@ApiProperty({ description: 'متن پاسخ تیکت', example: 'با سلام، دوز مصرفی پیشنهادی...' })
@ApiProperty({
description: 'متن پاسخ تیکت',
example: 'با سلام، دوز مصرفی پیشنهادی...',
})
@IsString()
@IsNotEmpty()
message: string;
@@ -44,19 +70,28 @@ export class ReplyTicketDto {
@IsString()
attachment?: string;
@ApiPropertyOptional({ description: 'تغییر وضعیت تیکت (توسط ادمین)', enum: ['OPEN', 'IN_PROGRESS', 'ANSWERED', 'CLOSED'] })
@ApiPropertyOptional({
description: 'تغییر وضعیت تیکت (توسط ادمین)',
enum: ['OPEN', 'IN_PROGRESS', 'ANSWERED', 'CLOSED'],
})
@IsOptional()
@IsString()
status?: string;
}
export class AdminUpdateTicketDto {
@ApiPropertyOptional({ description: 'وضعیت جدید تیکت', enum: ['OPEN', 'IN_PROGRESS', 'ANSWERED', 'CLOSED'] })
@ApiPropertyOptional({
description: 'وضعیت جدید تیکت',
enum: ['OPEN', 'IN_PROGRESS', 'ANSWERED', 'CLOSED'],
})
@IsOptional()
@IsString()
status?: string;
@ApiPropertyOptional({ description: 'اولویت تیکت', enum: ['LOW', 'MEDIUM', 'HIGH', 'URGENT'] })
@ApiPropertyOptional({
description: 'اولویت تیکت',
enum: ['LOW', 'MEDIUM', 'HIGH', 'URGENT'],
})
@IsOptional()
@IsString()
priority?: string;
+11 -3
View File
@@ -15,17 +15,25 @@ export class TicketQueryDto {
@IsNumber()
limit?: number = 15;
@ApiPropertyOptional({ description: 'فیلتر بر اساس وضعیت', enum: ['OPEN', 'IN_PROGRESS', 'ANSWERED', 'CLOSED'] })
@ApiPropertyOptional({
description: 'فیلتر بر اساس وضعیت',
enum: ['OPEN', 'IN_PROGRESS', 'ANSWERED', 'CLOSED'],
})
@IsOptional()
@IsString()
status?: string;
@ApiPropertyOptional({ description: 'فیلتر بر اساس دسته‌بندی', enum: ['VET_CONSULTATION', 'ORDER_SUPPORT', 'PRODUCT_INQUIRY', 'GENERAL'] })
@ApiPropertyOptional({
description: 'فیلتر بر اساس دسته‌بندی',
enum: ['VET_CONSULTATION', 'ORDER_SUPPORT', 'PRODUCT_INQUIRY', 'GENERAL'],
})
@IsOptional()
@IsString()
category?: string;
@ApiPropertyOptional({ description: 'جستجو در موضوع، شماره تیکت یا مشخصات کاربر' })
@ApiPropertyOptional({
description: 'جستجو در موضوع، شماره تیکت یا مشخصات کاربر',
})
@IsOptional()
@IsString()
search?: string;
+11 -3
View File
@@ -10,7 +10,11 @@ import {
Req,
} from '@nestjs/common';
import { TicketsService } from './tickets.service';
import { CreateTicketDto, ReplyTicketDto, AdminUpdateTicketDto } from './dto/create-ticket.dto';
import {
CreateTicketDto,
ReplyTicketDto,
AdminUpdateTicketDto,
} from './dto/create-ticket.dto';
import { TicketQueryDto } from './dto/ticket-query.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
@@ -22,7 +26,9 @@ import {
ApiOkResponse,
} from '@nestjs/swagger';
@ApiTags('Tickets & Vet Consultation - تیکتینگ، پشتیبانی و مشاوره آنلاین دامپزشک')
@ApiTags(
'Tickets & Vet Consultation - تیکتینگ، پشتیبانی و مشاوره آنلاین دامپزشک',
)
@Controller('tickets')
export class TicketsController {
constructor(private readonly ticketsService: TicketsService) {}
@@ -30,7 +36,9 @@ export class TicketsController {
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@Post()
@ApiOperation({ summary: 'ثبت تیکت جدید یا درخواست مشاوره دامپزشک توسط کاربر' })
@ApiOperation({
summary: 'ثبت تیکت جدید یا درخواست مشاوره دامپزشک توسط کاربر',
})
async createTicket(
@Req() req: { user: { id: string } },
@Body() dto: CreateTicketDto,
+26 -8
View File
@@ -6,7 +6,11 @@ import {
Logger,
} from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateTicketDto, ReplyTicketDto, AdminUpdateTicketDto } from './dto/create-ticket.dto';
import {
CreateTicketDto,
ReplyTicketDto,
AdminUpdateTicketDto,
} from './dto/create-ticket.dto';
import { TicketQueryDto } from './dto/ticket-query.dto';
import { Prisma } from '@prisma/client';
@@ -31,7 +35,8 @@ export class TicketsService {
}
const ticketNumber = this.generateTicketNumber();
const senderName = `${user.firstName || ''} ${user.lastName || ''}`.trim() || user.mobile;
const senderName =
`${user.firstName || ''} ${user.lastName || ''}`.trim() || user.mobile;
const ticket = await this.prisma.ticket.create({
data: {
@@ -62,7 +67,8 @@ export class TicketsService {
return {
success: true,
message: 'تیکت شما با موفقیت ثبت شد و به زودی توسط کارشناسان پاسخ داده می‌شود.',
message:
'تیکت شما با موفقیت ثبت شد و به زودی توسط کارشناسان پاسخ داده می‌شود.',
data: ticket,
};
}
@@ -91,7 +97,11 @@ export class TicketsService {
/**
* 3. Get single ticket details
*/
async getTicketDetails(ticketId: string, userId?: string, isAdmin: boolean = false) {
async getTicketDetails(
ticketId: string,
userId?: string,
isAdmin: boolean = false,
) {
const ticket = await this.prisma.ticket.findUnique({
where: { id: ticketId },
include: {
@@ -148,13 +158,21 @@ export class TicketsService {
throw new ForbiddenException('شما دسترسی به این تیکت را ندارید');
}
const sender = await this.prisma.user.findUnique({ where: { id: senderId } });
const senderRole = isAdmin ? (sender?.role.includes('Doctor') ? 'VET_DOCTOR' : 'ADMIN') : 'USER';
const sender = await this.prisma.user.findUnique({
where: { id: senderId },
});
const senderRole = isAdmin
? sender?.role.includes('Doctor')
? 'VET_DOCTOR'
: 'ADMIN'
: 'USER';
const senderName = isAdmin
? `${sender?.firstName || 'پشتیبان'} ${sender?.lastName || 'کنینا'}`.trim()
: `${sender?.firstName || ''} ${sender?.lastName || ''}`.trim() || sender?.mobile || 'کاربر';
: `${sender?.firstName || ''} ${sender?.lastName || ''}`.trim() ||
sender?.mobile ||
'کاربر';
const newStatus = isAdmin ? (dto.status || 'ANSWERED') : 'IN_PROGRESS';
const newStatus = isAdmin ? dto.status || 'ANSWERED' : 'IN_PROGRESS';
const [newMessage] = await this.prisma.$transaction([
this.prisma.ticketMessage.create({
+15 -5
View File
@@ -130,7 +130,8 @@ export class UsersService {
const updateData: Prisma.UserUpdateInput = {};
if (dto.firstName !== undefined) updateData.firstName = dto.firstName.trim();
if (dto.firstName !== undefined)
updateData.firstName = dto.firstName.trim();
if (dto.lastName !== undefined) updateData.lastName = dto.lastName.trim();
if (dto.mobile !== undefined) {
@@ -140,7 +141,9 @@ export class UsersService {
where: { mobile: normalizedMobile },
});
if (existing && existing.id !== id) {
throw new BadRequestException('این شماره موبایل قبلاً توسط کاربر دیگری ثبت شده است');
throw new BadRequestException(
'این شماره موبایل قبلاً توسط کاربر دیگری ثبت شده است',
);
}
updateData.mobile = normalizedMobile;
}
@@ -153,7 +156,9 @@ export class UsersService {
where: { email: normalizedEmail },
});
if (existing && existing.id !== id) {
throw new BadRequestException('این آدرس ایمیل قبلاً توسط کاربر دیگری ثبت شده است');
throw new BadRequestException(
'این آدرس ایمیل قبلاً توسط کاربر دیگری ثبت شده است',
);
}
}
updateData.email = normalizedEmail;
@@ -163,9 +168,14 @@ export class UsersService {
// If user already has a password set, require and verify currentPassword
if (user.password) {
if (!dto.currentPassword) {
throw new BadRequestException('برای تغییر رمز عبور، وارد کردن رمز عبور فعلی الزامی است');
throw new BadRequestException(
'برای تغییر رمز عبور، وارد کردن رمز عبور فعلی الزامی است',
);
}
const isCurrentMatch = await bcrypt.compare(dto.currentPassword.trim(), user.password);
const isCurrentMatch = await bcrypt.compare(
dto.currentPassword.trim(),
user.password,
);
if (!isCurrentMatch) {
throw new BadRequestException('رمز عبور فعلی اشتباه است');
}