Compare commits

..

10 Commits

Author SHA1 Message Date
hamid bf4e4c8d65 list of card to card 2026-07-11 20:56:38 +03:30
hamid 8b2d1b0a47 fix warning 2026-07-11 20:00:41 +03:30
hamid c41f5567c5 migration 2026-07-10 15:11:29 +03:30
hamid 7a5d2bb137 Fix SMS/notification migrations seeding keys before enum values exist 2026-07-10 15:03:38 +03:30
hamid 3e79cb69b3 port 2026-07-10 15:00:59 +03:30
hamid 83f8db336e Default port 4000 2026-07-10 14:52:49 +03:30
hamid 0020f95a61 fix 2026-07-10 14:35:05 +03:30
hamid 7c0f3a1d0e added service with excel 2026-07-10 14:09:41 +03:30
hamid 33f0afaf10 order sms 2026-07-10 13:55:59 +03:30
hamid 42f08397a2 profile avatar 2026-07-10 13:50:25 +03:30
22 changed files with 1348 additions and 34 deletions
+791 -13
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -39,6 +39,7 @@
"bcrypt": "^6.0.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.15.1",
"exceljs": "^4.4.0",
"multer": "^2.2.0",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
+14 -14
View File
@@ -39,6 +39,7 @@ export interface AuthTokensResponse {
lastName: string;
mobile: string;
role: UserRole;
avatarUrl: string | null;
};
}
@@ -403,13 +404,7 @@ export class AuthService {
const user = await this.usersService.findOne(authUser.id);
const response: MeResponse = {
user: {
id: user.id,
firstName: user.firstName,
lastName: user.lastName,
mobile: user.mobile,
role: user.role,
},
user: this.toAuthUserResponse(user),
};
if (user.role === UserRole.SALON) {
@@ -477,13 +472,18 @@ export class AuthService {
return {
accessToken,
refreshToken,
user: {
id: user.id,
firstName: user.firstName,
lastName: user.lastName,
mobile: user.mobile,
role: user.role,
},
user: this.toAuthUserResponse(user),
};
}
private toAuthUserResponse(user: User): AuthTokensResponse['user'] {
return {
id: user.id,
firstName: user.firstName,
lastName: user.lastName,
mobile: user.mobile,
role: user.role,
avatarUrl: user.avatarUrl ?? null,
};
}
+3
View File
@@ -16,6 +16,9 @@ class AuthUserResponseDto {
@ApiProperty({ enum: UserRole })
role: UserRole;
@ApiProperty({ nullable: true, required: false })
avatarUrl?: string | null;
}
export class AuthTokensResponseDto {
+3
View File
@@ -18,6 +18,9 @@ class MeUserResponseDto {
@ApiProperty({ enum: UserRole })
role: UserRole;
@ApiPropertyOptional({ nullable: true })
avatarUrl?: string | null;
}
export class MeResponseDto {
+1
View File
@@ -13,5 +13,6 @@ export default new DataSource({
database: process.env.DB_NAME,
entities: [join(__dirname, '../**/*.entity.{js,ts}')],
migrations: [join(__dirname, '/migrations/*.{js,ts}')],
migrationsTransactionMode: 'each',
...(isCompiled ? {} : { requireTsNode: true }),
});
@@ -6,6 +6,16 @@ import {
TableIndex,
} from 'typeorm';
import { SMS_SCENARIOS } from '../../sms-settings/constants/sms-scenarios.constants';
import { SmsScenarioKey } from '../../sms-settings/enums/sms-scenario-key.enum';
/** Keys that exist on the enum created in this migration (later keys are seeded elsewhere). */
const INITIAL_SCENARIO_KEYS = [
SmsScenarioKey.OTP_LOGIN,
SmsScenarioKey.RESERVE_CREATED,
SmsScenarioKey.RESERVE_REMINDER,
SmsScenarioKey.RESERVE_CONFIRMED,
SmsScenarioKey.RESERVE_CANCELLED,
];
export class AddSmsScenarioSettings1721200000000 implements MigrationInterface {
name = 'AddSmsScenarioSettings1721200000000';
@@ -67,11 +77,17 @@ export class AddSmsScenarioSettings1721200000000 implements MigrationInterface {
}),
);
for (const scenario of SMS_SCENARIOS) {
for (const key of INITIAL_SCENARIO_KEYS) {
const scenario = SMS_SCENARIOS.find((item) => item.key === key);
if (!scenario) {
continue;
}
await queryRunner.query(
`
INSERT INTO sms_scenario_settings (key, body, "isActive")
VALUES ($1, $2, true)
ON CONFLICT (key) DO NOTHING
`,
[scenario.key, scenario.defaultBody],
);
@@ -6,6 +6,17 @@ import {
TableIndex,
} from 'typeorm';
import { NOTIFICATION_SCENARIOS } from '../../notifications/constants/notification-scenarios.constants';
import { NotificationScenarioKey } from '../../notifications/enums/notification-scenario-key.enum';
/** Keys that exist on the enum created in this migration (deposit key is seeded later). */
const INITIAL_NOTIFICATION_KEYS = [
NotificationScenarioKey.RESERVE_CREATED,
NotificationScenarioKey.RESERVE_CONFIRMED,
NotificationScenarioKey.RESERVE_CANCELLED,
NotificationScenarioKey.RESERVE_REMINDER_SENT,
NotificationScenarioKey.CAMPAIGN_SENT,
NotificationScenarioKey.CAMPAIGN_FAILED,
];
export class AddNotifications1721500000000 implements MigrationInterface {
name = 'AddNotifications1721500000000';
@@ -142,11 +153,17 @@ export class AddNotifications1721500000000 implements MigrationInterface {
}),
);
for (const scenario of NOTIFICATION_SCENARIOS) {
for (const key of INITIAL_NOTIFICATION_KEYS) {
const scenario = NOTIFICATION_SCENARIOS.find((item) => item.key === key);
if (!scenario) {
continue;
}
await queryRunner.query(
`
INSERT INTO notification_scenario_settings (key, title, body, "isActive")
VALUES ($1, $2, $3, true)
ON CONFLICT (key) DO NOTHING
`,
[scenario.key, scenario.defaultTitle, scenario.defaultBody],
);
@@ -15,9 +15,11 @@ const NEW_NOTIFICATION_KEYS = [NotificationScenarioKey.DEPOSIT_RECEIPT_SUBMITTED
* Only adds the new enum values. Postgres forbids using a newly added enum
* value in the same transaction it was created in, so seeding the actual
* scenario rows is handled by the follow-up `SeedDepositScenarios` migration.
* `transaction = false` commits ADD VALUE immediately (required by Postgres).
*/
export class AddDepositScenarios1722000000000 implements MigrationInterface {
name = 'AddDepositScenarios1722000000000';
transaction = false;
public async up(queryRunner: QueryRunner): Promise<void> {
for (const key of NEW_SMS_KEYS) {
@@ -0,0 +1,21 @@
import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm';
export class AddUserAvatarUrl1722200000000 implements MigrationInterface {
name = 'AddUserAvatarUrl1722200000000';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.addColumn(
'users',
new TableColumn({
name: 'avatarUrl',
type: 'varchar',
length: '500',
isNullable: true,
}),
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropColumn('users', 'avatarUrl');
}
}
+3
View File
@@ -15,5 +15,8 @@ export function getTypeOrmOptions(): TypeOrmModuleOptions {
// by both reserves and reserve_status_history). Use migrations instead.
synchronize: false,
migrationsRun: true,
// Each migration commits separately so Postgres enum ADD VALUE can be
// used by a follow-up seed migration (unsafe in the same transaction).
migrationsTransactionMode: 'each',
};
}
+7 -2
View File
@@ -37,6 +37,11 @@ async function bootstrap() {
app.enableCors();
}
await app.listen(process.env.PORT ?? 3000);
const port = Number(process.env.PORT ?? 4000);
await app.listen(port, '0.0.0.0');
console.log(`grow-api listening on 0.0.0.0:${port}`);
}
bootstrap();
bootstrap().catch((error) => {
console.error('Failed to start grow-api:', error);
process.exit(1);
});
@@ -27,6 +27,8 @@ import { SalonSubscriptionsService } from '../subscriptions/salon-subscriptions.
import { UploaderService } from '../uploader/uploader.service';
import { UserRole } from '../users/enums/user-role.enum';
import { ShortLinksService } from '../short-links/short-links.service';
import { DepositListItemDto } from './dto/deposit-list-item.dto';
import { FindDepositsQueryDto } from './dto/find-deposits-query.dto';
import { PublicDepositPaymentDto } from './dto/public-deposit-payment.dto';
import { ReviewDepositDto } from './dto/review-deposit.dto';
import { Payment } from './entities/payment.entity';
@@ -35,6 +37,8 @@ import { PaymentStatus } from './enums/payment-status.enum';
import { PaymentType } from './enums/payment-type.enum';
const MIN_AMOUNT_TOMAN = 100;
/** Gives the reserve-created SMS time to reach the customer before the deposit link SMS. */
const DEPOSIT_SMS_DELAY_MS = 2_500;
@Injectable()
export class CardToCardDepositService {
@@ -146,6 +150,8 @@ export class CardToCardDepositService {
const variables = buildReserveSmsVariables(reserve);
const mobile = reserve.customer?.user?.mobile;
if (mobile) {
await this.delay(DEPOSIT_SMS_DELAY_MS);
await this.sendDepositSms(
SmsScenarioKey.DEPOSIT_PAYMENT_REQUEST,
mobile,
@@ -249,6 +255,43 @@ export class CardToCardDepositService {
return this.getPublicPaymentByToken(token);
}
async findForSalon(
user: AuthUser,
query: FindDepositsQueryDto,
): Promise<DepositListItemDto[]> {
if (user.role !== UserRole.SALON && user.role !== UserRole.ADMIN) {
throw new ForbiddenException();
}
const qb = this.paymentsRepository
.createQueryBuilder('payment')
.innerJoinAndSelect('payment.reserve', 'reserve')
.innerJoinAndSelect('reserve.salon', 'salon')
.leftJoinAndSelect('reserve.customer', 'customer')
.leftJoinAndSelect('customer.user', 'customerUser')
.where('payment.type = :type', { type: PaymentType.DEPOSIT })
.andWhere('payment.method = :method', {
method: PaymentMethod.CARD_TO_CARD,
})
.orderBy('payment.createdAt', 'DESC');
if (query.status) {
qb.andWhere('payment.status = :status', { status: query.status });
}
if (!this.authorizationService.isAdmin(user)) {
qb.andWhere('salon.ownerId = :ownerId', { ownerId: user.id });
}
const limit = query.limit ?? 50;
const offset = query.offset ?? 0;
qb.take(limit).skip(offset);
const payments = await qb.getMany();
return payments.map((payment) => this.toDepositListItem(payment));
}
async findForReview(paymentId: string, user: AuthUser): Promise<Payment> {
const payment = await this.loadPaymentWithRelations(paymentId);
this.assertCanReview(user, payment);
@@ -376,6 +419,10 @@ export class CardToCardDepositService {
return this.smsService.sendSms(mobile, message);
}
private delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
private tomanToRial(amountToman: number): number {
return Math.round(amountToman * 10);
}
@@ -383,4 +430,23 @@ export class CardToCardDepositService {
private rialToToman(amountRial: number): number {
return Math.round(amountRial / 10);
}
private toDepositListItem(payment: Payment): DepositListItemDto {
const user = payment.reserve?.customer?.user;
const customerName = user
? `${user.firstName} ${user.lastName}`.trim()
: 'مشتری';
return {
id: payment.id,
status: payment.status,
amountToman: this.rialToToman(payment.amountRial),
receiptUrl: payment.receiptUrl,
createdAt: payment.createdAt,
customerName,
customerMobile: user?.mobile ?? null,
appointmentDate: payment.reserve?.appointmentDate ?? null,
startTime: payment.reserve?.startTime ?? null,
};
}
}
+15
View File
@@ -5,6 +5,7 @@ import {
Param,
ParseUUIDPipe,
Post,
Query,
UploadedFile,
UseGuards,
UseInterceptors,
@@ -25,6 +26,8 @@ import { ApiPublicEndpoint } from '../swagger/decorators/swagger-auth.decorator'
import { SWAGGER_JWT_AUTH } from '../swagger/swagger.setup';
import { UserRole } from '../users/enums/user-role.enum';
import { CardToCardDepositService } from './card-to-card-deposit.service';
import { DepositListItemDto } from './dto/deposit-list-item.dto';
import { FindDepositsQueryDto } from './dto/find-deposits-query.dto';
import { PublicDepositPaymentDto } from './dto/public-deposit-payment.dto';
import { ReviewDepositDto } from './dto/review-deposit.dto';
import { Payment } from './entities/payment.entity';
@@ -84,6 +87,18 @@ export class DepositsController {
return this.cardToCardDepositService.submitReceipt(token, file);
}
@ApiBearerAuth(SWAGGER_JWT_AUTH)
@UseGuards(RolesGuard)
@Roles(UserRole.ADMIN, UserRole.SALON)
@ApiStandardOkResponse(DepositListItemDto, { isArray: true })
@Get()
findAll(
@Query() query: FindDepositsQueryDto,
@CurrentUser() user: AuthUser,
) {
return this.cardToCardDepositService.findForSalon(user, query);
}
@ApiBearerAuth(SWAGGER_JWT_AUTH)
@UseGuards(RolesGuard)
@Roles(UserRole.ADMIN, UserRole.SALON)
+31
View File
@@ -0,0 +1,31 @@
import { ApiProperty } from '@nestjs/swagger';
import { PaymentStatus } from '../enums/payment-status.enum';
export class DepositListItemDto {
@ApiProperty()
id: string;
@ApiProperty({ enum: PaymentStatus })
status: PaymentStatus;
@ApiProperty({ example: 500000 })
amountToman: number;
@ApiProperty({ required: false, nullable: true })
receiptUrl: string | null;
@ApiProperty()
createdAt: Date;
@ApiProperty({ example: 'مریم احمدی' })
customerName: string;
@ApiProperty({ required: false, nullable: true, example: '09121234567' })
customerMobile: string | null;
@ApiProperty({ required: false, nullable: true })
appointmentDate: string | null;
@ApiProperty({ required: false, nullable: true })
startTime: string | null;
}
@@ -0,0 +1,22 @@
import { Type } from 'class-transformer';
import { IsEnum, IsInt, IsOptional, Max, Min } from 'class-validator';
import { PaymentStatus } from '../enums/payment-status.enum';
export class FindDepositsQueryDto {
@IsOptional()
@IsEnum(PaymentStatus)
status?: PaymentStatus;
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
@Max(100)
limit?: number;
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(0)
offset?: number;
}
@@ -0,0 +1,24 @@
import { ApiProperty } from '@nestjs/swagger';
import { ServiceSkill } from '../entities/service-skill.entity';
export class ImportServiceSkillRowErrorDto {
@ApiProperty({ example: 3 })
row: number;
@ApiProperty({ example: 'عنوان مهارت الزامی است' })
message: string;
}
export class ImportServiceSkillsResultDto {
@ApiProperty({ example: 5 })
created: number;
@ApiProperty({ example: 1 })
failed: number;
@ApiProperty({ type: [ServiceSkill] })
skills: ServiceSkill[];
@ApiProperty({ type: [ImportServiceSkillRowErrorDto] })
errors: ImportServiceSkillRowErrorDto[];
}
+66 -1
View File
@@ -8,9 +8,21 @@ import {
Patch,
Post,
Query,
Res,
UploadedFile,
UseGuards,
UseInterceptors,
} from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { FileInterceptor } from '@nestjs/platform-express';
import {
ApiBearerAuth,
ApiBody,
ApiConsumes,
ApiProduces,
ApiTags,
} from '@nestjs/swagger';
import type { Response } from 'express';
import { memoryStorage } from 'multer';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import { Public } from '../auth/decorators/public.decorator';
import { Permissions } from '../auth/decorators/permissions.decorator';
@@ -22,6 +34,7 @@ import { PermissionCode } from '../authorization/enums/permission-code.enum';
import { UserRole } from '../users/enums/user-role.enum';
import { CreateServiceSkillDto } from './dto/create-service-skill.dto';
import { CreateServiceDto } from './dto/create-service.dto';
import { ImportServiceSkillsResultDto } from './dto/import-service-skills-result.dto';
import {
CreateSalonServiceDto,
FindSalonServicesQueryDto,
@@ -39,6 +52,8 @@ import {
import { ServiceSkill } from './entities/service-skill.entity';
import { Service } from './entities/service.entity';
const MAX_EXCEL_SIZE_BYTES = 5 * 1024 * 1024;
@ApiTags('Services')
@ApiBearerAuth(SWAGGER_JWT_AUTH)
@ApiStandardController()
@@ -99,6 +114,24 @@ export class ServicesController {
return this.servicesService.removeServiceForSalon(serviceId, user);
}
@Roles(UserRole.ADMIN)
@Permissions(PermissionCode.SERVICES_WRITE)
@ApiProduces(
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
)
@Get('skills/import-template')
async downloadSkillsImportTemplate(@Res() res: Response) {
const buffer = await this.servicesService.buildSkillsImportTemplate();
res.set({
'Content-Type':
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'Content-Disposition':
'attachment; filename="service-skills-import-template.xlsx"',
'Content-Length': buffer.length,
});
res.send(buffer);
}
@Public()
@ApiPublicEndpoint('Get service by ID')
@ApiStandardOkResponse(Service)
@@ -146,6 +179,38 @@ export class ServicesController {
);
}
@Roles(UserRole.ADMIN)
@Permissions(PermissionCode.SERVICES_WRITE)
@ApiConsumes('multipart/form-data')
@ApiBody({
schema: {
type: 'object',
required: ['file'],
properties: {
file: {
type: 'string',
format: 'binary',
description: 'Excel file (.xlsx) with skill title and renewalDays columns',
},
},
},
})
@ApiStandardOkResponse(ImportServiceSkillsResultDto)
@UseInterceptors(
FileInterceptor('file', {
storage: memoryStorage(),
limits: { fileSize: MAX_EXCEL_SIZE_BYTES },
}),
)
@Post(':serviceId/skills/import')
importSkills(
@Param('serviceId', ParseUUIDPipe) serviceId: string,
@UploadedFile() file: Express.Multer.File,
@CurrentUser() user: AuthUser,
) {
return this.servicesService.importSkillsFromExcel(serviceId, file, user);
}
@Public()
@ApiPublicEndpoint('List skills for a service')
@ApiStandardOkResponse(ServiceSkill, { isArray: true })
+225
View File
@@ -6,6 +6,7 @@ import {
NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import ExcelJS from 'exceljs';
import { In, Repository } from 'typeorm';
import { ServicePolicy } from '../authorization/policies/service.policy';
import { AuthUser } from '../auth/interfaces/auth-user.interface';
@@ -13,6 +14,7 @@ import { Salon } from '../salons/entities/salon.entity';
import { UserRole } from '../users/enums/user-role.enum';
import { CreateServiceSkillDto } from './dto/create-service-skill.dto';
import { CreateServiceDto } from './dto/create-service.dto';
import { ImportServiceSkillsResultDto } from './dto/import-service-skills-result.dto';
import {
CreateSalonServiceDto,
FindSalonServicesQueryDto,
@@ -23,6 +25,27 @@ import { SalonServiceOffering } from './entities/salon-service-offering.entity';
import { ServiceSkill } from './entities/service-skill.entity';
import { Service } from './entities/service.entity';
const TITLE_HEADERS = new Set(['عنوان مهارت', 'title', 'عنوان']);
const RENEWAL_HEADERS = new Set([
'دوره بازگشت (روز)',
'دوره بازگشت',
'renewaldays',
'renewal_days',
'renewal days',
]);
const SAMPLE_SKILL_ROWS: Array<{ title: string; renewalDays: number }> = [
{ title: 'کاشت ناخن ژل', renewalDays: 30 },
{ title: 'مانیکور ساده', renewalDays: 21 },
{ title: 'پدیکور', renewalDays: 30 },
];
const EXCEL_MIME_TYPES = new Set([
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.ms-excel',
'application/octet-stream',
]);
@Injectable()
export class ServicesService {
constructor(
@@ -97,6 +120,97 @@ export class ServicesService {
return this.findSkill(serviceId, saved.id);
}
async buildSkillsImportTemplate(): Promise<Buffer> {
const workbook = new ExcelJS.Workbook();
const sheet = workbook.addWorksheet('مهارت‌ها');
sheet.columns = [
{ header: 'عنوان مهارت', key: 'title', width: 40 },
{ header: 'دوره بازگشت (روز)', key: 'renewalDays', width: 22 },
];
sheet.getRow(1).font = { bold: true };
SAMPLE_SKILL_ROWS.forEach((row) => sheet.addRow(row));
const buffer = await workbook.xlsx.writeBuffer();
return Buffer.from(buffer);
}
async importSkillsFromExcel(
serviceId: string,
file: Express.Multer.File | undefined,
user: AuthUser,
): Promise<ImportServiceSkillsResultDto> {
this.ensureCanManage(user);
await this.findOne(serviceId);
this.ensureExcelFile(file);
const rows = await this.parseSkillsExcel(file.buffer);
if (rows.length === 0) {
throw new BadRequestException('فایل اکسل هیچ ردیف معتبری ندارد');
}
const errors: ImportServiceSkillsResultDto['errors'] = [];
const toCreate: Array<{ title: string; renewalDays: number }> = [];
for (const row of rows) {
const title = row.title?.trim() ?? '';
const renewalDays = row.renewalDays;
if (!title) {
errors.push({ row: row.rowNumber, message: 'عنوان مهارت الزامی است' });
continue;
}
if (title.length > 200) {
errors.push({
row: row.rowNumber,
message: 'عنوان مهارت نباید بیشتر از ۲۰۰ کاراکتر باشد',
});
continue;
}
if (
renewalDays === null ||
!Number.isInteger(renewalDays) ||
renewalDays < 1
) {
errors.push({
row: row.rowNumber,
message: 'دوره بازگشت باید عدد صحیح و حداقل ۱ باشد',
});
continue;
}
toCreate.push({ title, renewalDays });
}
if (toCreate.length === 0) {
throw new BadRequestException(
errors.length > 0
? errors
.map((error) => `ردیف ${error.row}: ${error.message}`)
.join('؛ ')
: 'هیچ ردیف معتبری برای ثبت یافت نشد',
);
}
const saved = await this.serviceSkillsRepository.manager.transaction(
async (manager) => {
const repository = manager.getRepository(ServiceSkill);
const entities = toCreate.map((item) =>
repository.create({ ...item, serviceId }),
);
return repository.save(entities);
},
);
return {
created: saved.length,
failed: errors.length,
skills: saved,
errors,
};
}
async findSkills(serviceId: string): Promise<ServiceSkill[]> {
await this.ensureServiceExists(serviceId);
return this.serviceSkillsRepository.find({
@@ -263,4 +377,115 @@ export class ServicesService {
throw new NotFoundException(`Service #${serviceId} not found`);
}
}
private ensureExcelFile(file: Express.Multer.File | undefined): asserts file is Express.Multer.File {
if (!file) {
throw new BadRequestException('فایل اکسل الزامی است');
}
const extension = file.originalname.split('.').pop()?.toLowerCase();
const isExcelExtension = extension === 'xlsx' || extension === 'xls';
const isExcelMime = EXCEL_MIME_TYPES.has(file.mimetype);
if (!isExcelExtension && !isExcelMime) {
throw new BadRequestException('فقط فایل‌های Excel (.xlsx) مجاز هستند');
}
}
private async parseSkillsExcel(
buffer: Buffer,
): Promise<
Array<{ rowNumber: number; title: string | null; renewalDays: number | null }>
> {
const workbook = new ExcelJS.Workbook();
// exceljs Buffer typings conflict with Node 22+ Buffer generics
await workbook.xlsx.load(buffer as unknown as ExcelJS.Buffer);
const sheet = workbook.worksheets[0];
if (!sheet) {
throw new BadRequestException('فایل اکسل خالی است');
}
const headerRow = sheet.getRow(1);
let titleCol = 0;
let renewalCol = 0;
headerRow.eachCell((cell, colNumber) => {
const header = this.normalizeHeader(cell.value);
if (TITLE_HEADERS.has(header)) {
titleCol = colNumber;
}
if (RENEWAL_HEADERS.has(header)) {
renewalCol = colNumber;
}
});
if (!titleCol || !renewalCol) {
throw new BadRequestException(
'ستون‌های «عنوان مهارت» و «دوره بازگشت (روز)» در ردیف اول الزامی هستند',
);
}
const rows: Array<{
rowNumber: number;
title: string | null;
renewalDays: number | null;
}> = [];
sheet.eachRow((row, rowNumber) => {
if (rowNumber === 1) {
return;
}
const titleValue = this.cellToString(row.getCell(titleCol).value);
const renewalValue = this.cellToNumber(row.getCell(renewalCol).value);
if (!titleValue && renewalValue === null) {
return;
}
rows.push({
rowNumber,
title: titleValue,
renewalDays: renewalValue,
});
});
return rows;
}
private normalizeHeader(value: ExcelJS.CellValue): string {
const text = this.cellToString(value)?.trim().toLowerCase() ?? '';
return text.replace(/\s+/g, ' ');
}
private cellToString(value: ExcelJS.CellValue): string | null {
if (value === null || value === undefined) {
return null;
}
if (typeof value === 'string' || typeof value === 'number') {
return String(value).trim() || null;
}
if (typeof value === 'object' && 'text' in value && typeof value.text === 'string') {
return value.text.trim() || null;
}
if (typeof value === 'object' && 'result' in value) {
return this.cellToString(value.result as ExcelJS.CellValue);
}
return String(value).trim() || null;
}
private cellToNumber(value: ExcelJS.CellValue): number | null {
if (value === null || value === undefined || value === '') {
return null;
}
if (typeof value === 'number') {
return value;
}
if (typeof value === 'object' && 'result' in value) {
return this.cellToNumber(value.result as ExcelJS.CellValue);
}
const parsed = Number(String(value).trim());
return Number.isFinite(parsed) ? parsed : null;
}
}
+15 -1
View File
@@ -1,4 +1,12 @@
import { IsEnum, IsOptional, IsString, Length, Matches } from 'class-validator';
import {
IsEnum,
IsOptional,
IsString,
IsUrl,
Length,
Matches,
ValidateIf,
} from 'class-validator';
import { UserRole } from '../enums/user-role.enum';
export class UpdateUserDto {
@@ -19,4 +27,10 @@ export class UpdateUserDto {
@IsOptional()
@IsEnum(UserRole)
role?: UserRole;
@IsOptional()
@ValidateIf((_, value) => value !== null)
@IsString()
@IsUrl()
avatarUrl?: string | null;
}
+3
View File
@@ -24,6 +24,9 @@ export class User {
@Column({ type: 'enum', enum: UserRole, default: UserRole.CUSTOMER })
role: UserRole;
@Column({ type: 'varchar', length: 500, nullable: true })
avatarUrl: string | null;
@CreateDateColumn()
createdAt: Date;
-1
View File
@@ -13,7 +13,6 @@
"target": "ES2023",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": true,