From 514c3ccaf0acd6bd1e52ddf39ddfee954ceb1fb7 Mon Sep 17 00:00:00 2001 From: "s.hajizadeh" Date: Tue, 13 Oct 2026 16:11:51 +0330 Subject: [PATCH] database migrated to POSTGRESQL --- src/app.module.ts | 9 +- src/audit/audit.module.ts | 6 +- src/audit/audit.service.ts | 31 +- src/audit/schemas/audit-log.schema.ts | 46 +- src/auth/auth.service.ts | 20 +- src/auth/strategies/jwt.strategy.ts | 2 +- src/cli/cli.module.ts | 15 +- src/cli/create-super-admin.service.ts | 57 +- src/common/helpers/request-logger.helper.ts | 2 +- src/common/helpers/validation-error.helper.ts | 4 + src/config/configuration.ts | 11 +- src/database/data-source.ts | 28 + src/database/database-seeder.module.ts | 6 +- src/database/database-seeder.service.ts | 68 ++- .../1760356800000-InitialPostgresSchema.ts | 172 ++++++ src/database/postgres.helpers.ts | 12 + src/database/snake-naming.strategy.ts | 40 ++ src/database/typeorm.config.ts | 16 + src/health/health.controller.ts | 6 +- src/health/health.module.ts | 3 +- src/idempotency/idempotency.module.ts | 13 +- src/idempotency/idempotency.service.ts | 159 ++++-- .../schemas/idempotency-record.schema.ts | 41 +- src/inquiry/dto/person-inquiry-request.dto.ts | 9 +- src/logging/inquiry-log.service.ts | 525 ++++++++---------- src/logging/logging.module.ts | 8 +- src/logging/schemas/inquiry-log.schema.ts | 57 +- .../implementations/amitis.provider.ts | 10 +- .../implementations/tejaratnou.provider.ts | 134 ++++- .../interfaces/tejaratnou-config.interface.ts | 4 + src/providers/providers.module.ts | 17 +- .../schemas/distributed-lock.schema.ts | 28 +- src/providers/schemas/general-token.schema.ts | 42 +- .../schemas/inquiry-result-cache.schema.ts | 30 +- .../services/distributed-lock.service.ts | 82 ++- .../services/general-token.service.ts | 31 +- .../services/inquiry-result-cache.service.ts | 69 +-- src/public/app.js | 2 +- src/users/mappers/user.mapper.ts | 16 +- src/users/schemas/user.schema.ts | 80 +-- src/users/users.module.ts | 11 +- src/users/users.service.ts | 178 +++--- test/unit/helpers-and-mappers.spec.ts | 2 +- test/unit/idempotency.service.spec.ts | 44 +- test/unit/tejarat-inquiries.spec.ts | 103 ++++ test/unit/tejarat-policy-by-plate.spec.ts | 72 +++ test/unit/third-party-car-rules.spec.ts | 70 +++ 47 files changed, 1500 insertions(+), 891 deletions(-) create mode 100644 src/database/data-source.ts create mode 100644 src/database/migrations/1760356800000-InitialPostgresSchema.ts create mode 100644 src/database/postgres.helpers.ts create mode 100644 src/database/snake-naming.strategy.ts create mode 100644 src/database/typeorm.config.ts create mode 100644 test/unit/tejarat-inquiries.spec.ts create mode 100644 test/unit/tejarat-policy-by-plate.spec.ts create mode 100644 test/unit/third-party-car-rules.spec.ts diff --git a/src/app.module.ts b/src/app.module.ts index e498b7a..7a95330 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -1,6 +1,7 @@ import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'; -import { MongooseModule } from '@nestjs/mongoose'; import { ConfigService } from '@nestjs/config'; +import { TypeOrmModule } from '@nestjs/typeorm'; +import { typeOrmConfig } from './database/typeorm.config'; import { CommonModule } from './common/common.module'; import { RequestIdMiddleware } from './common/middleware/request-id.middleware'; import { AppConfigModule } from './config/config.module'; @@ -23,11 +24,9 @@ import { IdempotencyModule } from './idempotency/idempotency.module'; AppConfigModule, CommonModule, AuditModule, - MongooseModule.forRootAsync({ + TypeOrmModule.forRootAsync({ inject: [ConfigService], - useFactory: (config: ConfigService) => ({ - uri: config.get('mongodb.uri'), - }), + useFactory: typeOrmConfig, }), RateLimitModule, LoggingModule, diff --git a/src/audit/audit.module.ts b/src/audit/audit.module.ts index d35fbb0..4b7f0dc 100644 --- a/src/audit/audit.module.ts +++ b/src/audit/audit.module.ts @@ -1,11 +1,11 @@ import { Global, Module } from '@nestjs/common'; -import { MongooseModule } from '@nestjs/mongoose'; +import { TypeOrmModule } from '@nestjs/typeorm'; import { AuditService } from './audit.service'; -import { AuditLog, AuditLogSchema } from './schemas/audit-log.schema'; +import { AuditLog } from './schemas/audit-log.schema'; @Global() @Module({ - imports: [MongooseModule.forFeature([{ name: AuditLog.name, schema: AuditLogSchema }])], + imports: [TypeOrmModule.forFeature([AuditLog])], providers: [AuditService], exports: [AuditService], }) diff --git a/src/audit/audit.service.ts b/src/audit/audit.service.ts index 9a4a205..896bca7 100644 --- a/src/audit/audit.service.ts +++ b/src/audit/audit.service.ts @@ -1,8 +1,9 @@ import { Injectable } from '@nestjs/common'; -import { InjectModel } from '@nestjs/mongoose'; -import { Model, Types } from 'mongoose'; +import { InjectRepository } from '@nestjs/typeorm'; +import { Repository } from 'typeorm'; import { AuditEvent } from '../common/enums/audit-event.enum'; -import { AuditLog, AuditLogDocument } from './schemas/audit-log.schema'; +import { isUuid } from '../database/postgres.helpers'; +import { AuditLog } from './schemas/audit-log.schema'; export interface AuditContext { userId?: string; @@ -19,19 +20,21 @@ export interface AuditContext { @Injectable() export class AuditService { constructor( - @InjectModel(AuditLog.name) - private readonly auditModel: Model, + @InjectRepository(AuditLog) + private readonly auditLogs: Repository, ) {} async log(event: AuditEvent, context: AuditContext = {}): Promise { - await this.auditModel.create({ - event, - userId: context.userId ? new Types.ObjectId(context.userId) : undefined, - actorId: context.actorId ? new Types.ObjectId(context.actorId) : undefined, - username: context.username, - ip: context.ip, - userAgent: context.userAgent, - metadata: context.metadata ?? {}, - }); + await this.auditLogs.save( + this.auditLogs.create({ + event, + userId: isUuid(context.userId) ? context.userId : null, + actorId: isUuid(context.actorId) ? context.actorId : null, + username: context.username, + ip: context.ip, + userAgent: context.userAgent, + metadata: context.metadata ?? {}, + }), + ); } } diff --git a/src/audit/schemas/audit-log.schema.ts b/src/audit/schemas/audit-log.schema.ts index 757e13e..b633d95 100644 --- a/src/audit/schemas/audit-log.schema.ts +++ b/src/audit/schemas/audit-log.schema.ts @@ -1,37 +1,39 @@ -import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; -import { HydratedDocument, Types } from 'mongoose'; +import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn } from 'typeorm'; import { AuditEvent } from '../../common/enums/audit-event.enum'; -export type AuditLogDocument = HydratedDocument; - /** * Immutable security audit trail — separate from inquiry_logs (business audit). */ -@Schema({ timestamps: { createdAt: true, updatedAt: false }, collection: 'audit_logs' }) +@Entity('audit_logs') +@Index(['createdAt']) +@Index(['event', 'createdAt']) export class AuditLog { - @Prop({ required: true, enum: AuditEvent, index: true }) + @PrimaryGeneratedColumn('uuid') + id!: string; + + @Index() + @Column({ type: 'text' }) event!: AuditEvent; - @Prop({ type: Types.ObjectId, ref: 'User', index: true }) - userId?: Types.ObjectId; + @Index() + @Column({ type: 'uuid', nullable: true }) + userId?: string | null; - @Prop({ type: Types.ObjectId, ref: 'User' }) - actorId?: Types.ObjectId; + @Column({ type: 'uuid', nullable: true }) + actorId?: string | null; - @Prop() - username?: string; + @Column({ type: 'text', nullable: true }) + username?: string | null; - @Prop() - ip?: string; + @Column({ type: 'text', nullable: true }) + ip?: string | null; - @Prop() - userAgent?: string; + @Column({ type: 'text', nullable: true }) + userAgent?: string | null; - @Prop({ type: Object, default: {} }) + @Column({ type: 'jsonb', default: () => "'{}'::jsonb" }) metadata!: Record; + + @CreateDateColumn({ type: 'timestamptz' }) + createdAt!: Date; } - -export const AuditLogSchema = SchemaFactory.createForClass(AuditLog); - -AuditLogSchema.index({ createdAt: -1 }); -AuditLogSchema.index({ event: 1, createdAt: -1 }); diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts index 4833c30..88488ba 100644 --- a/src/auth/auth.service.ts +++ b/src/auth/auth.service.ts @@ -35,27 +35,27 @@ export class AuthService { } if (!user.isActive) { - await this.auditFailedLogin(user._id.toString(), user.username, 'inactive', context); + await this.auditFailedLogin(user.id, user.username, 'inactive', context); throw new AppException('ACCOUNT_INACTIVE'); } if (user.isBlocked) { - await this.auditFailedLogin(user._id.toString(), user.username, 'blocked', context); + await this.auditFailedLogin(user.id, user.username, 'blocked', context); throw new AppException('ACCOUNT_BLOCKED'); } const valid = await this.passwordService.compare(dto.password, user.password); if (!valid) { - await this.auditFailedLogin(user._id.toString(), user.username, 'invalid_credentials', context); + await this.auditFailedLogin(user.id, user.username, 'invalid_credentials', context); throw new AppException('INVALID_CREDENTIALS'); } const tokens = await this.issueTokens(user); - await this.usersService.saveRefreshToken(user._id.toString(), tokens.refreshToken); - await this.usersService.recordLogin(user._id.toString()); + await this.usersService.saveRefreshToken(user.id, tokens.refreshToken); + await this.usersService.recordLogin(user.id); await this.auditService.log(AuditEvent.LOGIN, { - userId: user._id.toString(), + userId: user.id, username: user.username, ip: context.ip, userAgent: context.userAgent, @@ -86,10 +86,10 @@ export class AuthService { } const tokens = await this.issueTokens(user); - await this.usersService.saveRefreshToken(user._id.toString(), tokens.refreshToken); + await this.usersService.saveRefreshToken(user.id, tokens.refreshToken); await this.auditService.log(AuditEvent.LOGIN, { - userId: user._id.toString(), + userId: user.id, username: user.username, ip: context.ip, userAgent: context.userAgent, @@ -117,13 +117,13 @@ export class AuthService { } private async issueTokens(user: { - _id: { toString(): string }; + id: string; role: JwtPayload['role']; clientType: JwtPayload['clientType']; appName: string; }): Promise { const payload: JwtPayload = { - sub: user._id.toString(), + sub: user.id, role: user.role, clientType: user.clientType, appName: user.appName, diff --git a/src/auth/strategies/jwt.strategy.ts b/src/auth/strategies/jwt.strategy.ts index 6117453..0a8840c 100644 --- a/src/auth/strategies/jwt.strategy.ts +++ b/src/auth/strategies/jwt.strategy.ts @@ -35,7 +35,7 @@ export class JwtStrategy extends PassportStrategy(Strategy, JWT_ACCESS_STRATEGY) } return { - id: user._id.toString(), + id: user.id, username: user.username, email: user.email, role: user.role, diff --git a/src/cli/cli.module.ts b/src/cli/cli.module.ts index c3d5737..0cfe514 100644 --- a/src/cli/cli.module.ts +++ b/src/cli/cli.module.ts @@ -1,9 +1,10 @@ import { Module } from '@nestjs/common'; -import { MongooseModule } from '@nestjs/mongoose'; import { ConfigService } from '@nestjs/config'; -import { AppConfigModule } from '../config/config.module'; +import { TypeOrmModule } from '@nestjs/typeorm'; import { PasswordService } from '../auth/services/password.service'; -import { User, UserSchema } from '../users/schemas/user.schema'; +import { AppConfigModule } from '../config/config.module'; +import { typeOrmConfig } from '../database/typeorm.config'; +import { User } from '../users/schemas/user.schema'; import { CreateSuperAdminService } from './create-super-admin.service'; /** @@ -13,13 +14,11 @@ import { CreateSuperAdminService } from './create-super-admin.service'; @Module({ imports: [ AppConfigModule, - MongooseModule.forRootAsync({ + TypeOrmModule.forRootAsync({ inject: [ConfigService], - useFactory: (config: ConfigService) => ({ - uri: config.get('mongodb.uri'), - }), + useFactory: typeOrmConfig, }), - MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]), + TypeOrmModule.forFeature([User]), ], providers: [CreateSuperAdminService, PasswordService], }) diff --git a/src/cli/create-super-admin.service.ts b/src/cli/create-super-admin.service.ts index 4666393..8bd24fd 100644 --- a/src/cli/create-super-admin.service.ts +++ b/src/cli/create-super-admin.service.ts @@ -1,14 +1,15 @@ import { Injectable, Logger } from '@nestjs/common'; -import { InjectModel } from '@nestjs/mongoose'; -import { Model } from 'mongoose'; +import { InjectRepository } from '@nestjs/typeorm'; import { randomBytes } from 'crypto'; +import { Repository } from 'typeorm'; import { ClientType } from '../common/enums/client-type.enum'; import { Role } from '../common/enums/role.enum'; +import { AppException } from '../common/exceptions/app-exception'; +import { isUniqueViolation } from '../database/postgres.helpers'; import { PasswordService } from '../auth/services/password.service'; -import { User, UserDocument } from '../users/schemas/user.schema'; +import { User } from '../users/schemas/user.schema'; import { UserMapper } from '../users/mappers/user.mapper'; import { UserResponseDto } from '../users/dto/user-response.dto'; -import { AppException } from '../common/exceptions/app-exception'; export interface CreateSuperAdminInput { fullName: string; @@ -22,7 +23,7 @@ export class CreateSuperAdminService { private readonly logger = new Logger(CreateSuperAdminService.name); constructor( - @InjectModel(User.name) private readonly userModel: Model, + @InjectRepository(User) private readonly users: Repository, private readonly passwordService: PasswordService, ) {} @@ -34,34 +35,42 @@ export class CreateSuperAdminService { const username = input.username.toLowerCase().trim(); const email = input.email.toLowerCase().trim(); - const existing = await this.userModel.findOne({ $or: [{ username }, { email }] }); + const existing = await this.users.findOne({ where: [{ username }, { email }] }); if (existing) { throw new AppException('USERNAME_OR_EMAIL_EXISTS'); } - const superAdminExists = await this.userModel.exists({ role: Role.SUPER_ADMIN }); + const superAdminExists = await this.users.exists({ where: { role: Role.SUPER_ADMIN } }); if (superAdminExists) { this.logger.warn('A SUPER_ADMIN already exists; creating another.'); } const passwordHash = await this.passwordService.hash(input.password); - const user = await this.userModel.create({ - fullName: input.fullName.trim(), - username, - email, - password: passwordHash, - role: Role.SUPER_ADMIN, - clientType: ClientType.INTERNAL, - appName: 'inquiry-gateway', - clientName: 'Internal', - isActive: true, - isBlocked: false, - allowedInquiries: [], - apiKey: `esg_${randomBytes(32).toString('hex')}`, - passwordChangedAt: new Date(), - }); - - return UserMapper.toResponseDto(user); + try { + const user = await this.users.save( + this.users.create({ + fullName: input.fullName.trim(), + username, + email, + password: passwordHash, + role: Role.SUPER_ADMIN, + clientType: ClientType.INTERNAL, + appName: 'inquiry-gateway', + clientName: 'Internal', + isActive: true, + isBlocked: false, + allowedInquiries: [], + apiKey: `esg_${randomBytes(32).toString('hex')}`, + passwordChangedAt: new Date(), + }), + ); + return UserMapper.toResponseDto(user); + } catch (error) { + if (isUniqueViolation(error)) { + throw new AppException('USERNAME_OR_EMAIL_EXISTS'); + } + throw error; + } } } diff --git a/src/common/helpers/request-logger.helper.ts b/src/common/helpers/request-logger.helper.ts index 1914db9..d3dee25 100644 --- a/src/common/helpers/request-logger.helper.ts +++ b/src/common/helpers/request-logger.helper.ts @@ -12,7 +12,7 @@ export interface RequestLogContext { /** * Structured console logging for inquiry lifecycle events. - * Complements MongoDB persistence in LoggingModule. + * Complements inquiry log persistence in LoggingModule. */ export class RequestLogger { private readonly logger: Logger; diff --git a/src/common/helpers/validation-error.helper.ts b/src/common/helpers/validation-error.helper.ts index a403272..9a855d6 100644 --- a/src/common/helpers/validation-error.helper.ts +++ b/src/common/helpers/validation-error.helper.ts @@ -68,6 +68,10 @@ function translateValidationConstraint(field: string, constraint: string): strin return 'تاریخ تولد باید با فرمت YYYY-MM-DD باشد'; } + if (constraint.includes('birthDate must be in YYYY or YYYY-MM-DD format')) { + return 'تاریخ تولد باید با فرمت YYYY یا YYYY-MM-DD باشد'; + } + if (constraint.includes('birthDate must be in YYYY-MM-DD or YYYYMMDD format')) { return 'تاریخ تولد باید با فرمت YYYY-MM-DD یا YYYYMMDD باشد'; } diff --git a/src/config/configuration.ts b/src/config/configuration.ts index 1a5cf4c..8cc36c3 100644 --- a/src/config/configuration.ts +++ b/src/config/configuration.ts @@ -37,6 +37,7 @@ export interface TejaratNouConfig { clientSecret: string; username: string; password: string; + inquiries: Partial>; } export interface InquiryRoutingConfig { @@ -54,8 +55,8 @@ export default () => ({ port: parseInt(process.env.PORT ?? '8085', 10), nodeEnv: process.env.NODE_ENV ?? 'development', }, - mongodb: { - uri: process.env.MONGODB_URI ?? 'mongodb://localhost:27017/inquiry-gateway', + database: { + url: process.env.DATABASE_URL ?? 'postgresql://esg:esg@localhost:5432/inquiry_gateway', }, auth: { apiKey: process.env.API_KEY ?? '', @@ -86,13 +87,17 @@ export default () => ({ enabled: process.env.TEJARATNOU_ENABLED !== 'false', timeout: parseInt(process.env.TEJARATNOU_TIMEOUT ?? '15000', 10), maxRetries: parseInt(process.env.TEJARATNOU_MAX_RETRIES ?? '3', 10), - baseUrl: process.env.TEJARATNOU_BASE_URL ?? 'https://accounts.tejaratnoins.ir', + baseUrl: + process.env.TEJARATNOU_BASE_URL ?? + process.env.TEJARATNOU_AUTH_URL ?? + 'https://accounts.tejaratnoins.ir', inquiryBaseUrl: process.env.TEJARATNOU_INQUIRY_BASE_URL ?? 'https://gateway.tejaratnoins.ir', clientId: process.env.TEJARATNOU_CLIENT_ID ?? 'api-gateway', clientSecret: process.env.TEJARATNOU_CLIENT_SECRET ?? '', username: process.env.TEJARATNOU_USERNAME ?? '', password: process.env.TEJARATNOU_PASSWORD ?? '', + inquiries: buildProviderConfig('TEJARATNOU').inquiries, } satisfies TejaratNouConfig, inquiryRouting: { [InquiryType.PERSON]: buildInquiryRoutingConfig('PERSON', ProviderName.PARSIAN, [ diff --git a/src/database/data-source.ts b/src/database/data-source.ts new file mode 100644 index 0000000..4f54444 --- /dev/null +++ b/src/database/data-source.ts @@ -0,0 +1,28 @@ +import 'dotenv/config'; +import { join } from 'path'; +import { DataSource } from 'typeorm'; +import { AuditLog } from '../audit/schemas/audit-log.schema'; +import { IdempotencyRecord } from '../idempotency/schemas/idempotency-record.schema'; +import { InquiryLog } from '../logging/schemas/inquiry-log.schema'; +import { DistributedLock } from '../providers/schemas/distributed-lock.schema'; +import { GeneralToken } from '../providers/schemas/general-token.schema'; +import { InquiryResultCache } from '../providers/schemas/inquiry-result-cache.schema'; +import { User } from '../users/schemas/user.schema'; +import { SnakeNamingStrategy } from './snake-naming.strategy'; + +export const AppDataSource = new DataSource({ + type: 'postgres', + url: process.env.DATABASE_URL ?? 'postgresql://esg:esg@localhost:5432/inquiry_gateway', + synchronize: false, + namingStrategy: new SnakeNamingStrategy(), + entities: [ + User, + AuditLog, + InquiryLog, + InquiryResultCache, + GeneralToken, + IdempotencyRecord, + DistributedLock, + ], + migrations: [join(__dirname, 'migrations', '*.{js,ts}')], +}); diff --git a/src/database/database-seeder.module.ts b/src/database/database-seeder.module.ts index 7cfa909..ca3bb1b 100644 --- a/src/database/database-seeder.module.ts +++ b/src/database/database-seeder.module.ts @@ -1,10 +1,10 @@ import { Module } from '@nestjs/common'; -import { MongooseModule } from '@nestjs/mongoose'; -import { User, UserSchema } from '../users/schemas/user.schema'; +import { TypeOrmModule } from '@nestjs/typeorm'; +import { User } from '../users/schemas/user.schema'; import { DatabaseSeederService } from './database-seeder.service'; @Module({ - imports: [MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])], + imports: [TypeOrmModule.forFeature([User])], providers: [DatabaseSeederService], }) export class DatabaseSeederModule {} diff --git a/src/database/database-seeder.service.ts b/src/database/database-seeder.service.ts index dbd9521..e6ade7d 100644 --- a/src/database/database-seeder.service.ts +++ b/src/database/database-seeder.service.ts @@ -1,9 +1,10 @@ import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common'; -import { InjectModel } from '@nestjs/mongoose'; +import { InjectRepository } from '@nestjs/typeorm'; import { existsSync, readFileSync } from 'fs'; import { join } from 'path'; -import { Model, Types } from 'mongoose'; -import { User, UserDocument } from '../users/schemas/user.schema'; +import { DeepPartial, Repository } from 'typeorm'; +import { isUuid } from '../database/postgres.helpers'; +import { User } from '../users/schemas/user.schema'; type ExtendedJsonValue = | string @@ -14,7 +15,7 @@ type ExtendedJsonValue = | { [key: string]: ExtendedJsonValue }; interface SeedUser { - _id?: Types.ObjectId; + id?: string; fullName: string; username: string; email: string; @@ -32,7 +33,7 @@ interface SeedUser { requestLimitPerDay: number; totalRequests?: number; passwordChangedAt?: Date; - createdBy?: Types.ObjectId; + createdBy?: string | null; createdAt?: Date; updatedAt?: Date; lastLoginAt?: Date; @@ -44,7 +45,7 @@ export class DatabaseSeederService implements OnApplicationBootstrap { private readonly logger = new Logger(DatabaseSeederService.name); private readonly usersSeedFile = 'inquiry-gateway.users.json'; - constructor(@InjectModel(User.name) private readonly userModel: Model) {} + constructor(@InjectRepository(User) private readonly users: Repository) {} async onApplicationBootstrap(): Promise { await this.seedUsers(); @@ -52,12 +53,17 @@ export class DatabaseSeederService implements OnApplicationBootstrap { private async seedUsers(): Promise { const users = this.loadSeedUsers(); + if (!users) { + this.logger.warn(`Seed file ${this.usersSeedFile} not found; skipping baseline user seed.`); + return; + } + let inserted = 0; let skipped = 0; for (const user of users) { - const existing = await this.userModel.exists({ - $or: [{ _id: user._id }, { username: user.username }, { email: user.email }], + const existing = await this.users.findOne({ + where: [{ username: user.username }, { email: user.email }], }); if (existing) { @@ -65,7 +71,7 @@ export class DatabaseSeederService implements OnApplicationBootstrap { continue; } - await this.userModel.create(user); + await this.users.save(this.users.create(user as DeepPartial)); inserted += 1; } @@ -77,8 +83,10 @@ export class DatabaseSeederService implements OnApplicationBootstrap { this.logger.log(`Baseline users already exist; skipped ${skipped} user(s).`); } - private loadSeedUsers(): SeedUser[] { + private loadSeedUsers(): SeedUser[] | null { const seedPath = this.resolveSeedPath(); + if (!seedPath) return null; + const raw = readFileSync(seedPath, 'utf8'); const parsed = JSON.parse(raw) as ExtendedJsonValue; const normalized = this.normalizeExtendedJson(parsed); @@ -92,27 +100,46 @@ export class DatabaseSeederService implements OnApplicationBootstrap { throw new Error(`${this.usersSeedFile} contains an invalid user document`); } + const rawId = (user as SeedUser & { _id?: string })._id ?? user.id; + const id = typeof rawId === 'string' && isUuid(rawId) ? rawId : undefined; + const createdBy = typeof user.createdBy === 'string' && isUuid(user.createdBy) ? user.createdBy : null; + return { - ...user, + ...(id ? { id } : {}), + fullName: user.fullName, username: user.username.toLowerCase().trim(), email: user.email.toLowerCase().trim(), + mobile: user.mobile, + password: user.password, + role: user.role, + clientType: user.clientType, + appName: user.appName ?? '', + clientName: user.clientName ?? '', + isActive: user.isActive, + isBlocked: user.isBlocked, + apiKey: user.apiKey, + allowedInquiries: user.allowedInquiries, + requestLimitPerMinute: user.requestLimitPerMinute, + requestLimitPerDay: user.requestLimitPerDay, + totalRequests: user.totalRequests ?? 0, + passwordChangedAt: user.passwordChangedAt, + createdBy, + createdAt: user.createdAt, + updatedAt: user.updatedAt, + lastLoginAt: user.lastLoginAt, + refreshToken: user.refreshToken, }; }); } - private resolveSeedPath(): string { + private resolveSeedPath(): string | undefined { const candidates = [ join(__dirname, 'seeds', this.usersSeedFile), join(process.cwd(), 'src', 'database', 'seeds', this.usersSeedFile), join(process.cwd(), 'dist', 'database', 'seeds', this.usersSeedFile), ]; - const seedPath = candidates.find((candidate) => existsSync(candidate)); - if (!seedPath) { - throw new Error(`Unable to find seed file: ${this.usersSeedFile}`); - } - - return seedPath; + return candidates.find((candidate) => existsSync(candidate)); } private normalizeExtendedJson(value: ExtendedJsonValue): unknown { @@ -125,7 +152,7 @@ export class DatabaseSeederService implements OnApplicationBootstrap { } if (typeof value.$oid === 'string') { - return new Types.ObjectId(value.$oid); + return value.$oid; } if (typeof value.$date === 'string') { @@ -133,12 +160,13 @@ export class DatabaseSeederService implements OnApplicationBootstrap { } return Object.entries(value).reduce>((acc, [key, child]) => { + if (key === '__v') return acc; acc[key] = this.normalizeExtendedJson(child); return acc; }, {}); } - private isSeedUser(value: unknown): value is SeedUser { + private isSeedUser(value: unknown): value is SeedUser & { _id?: string; createdBy?: string } { if (!value || typeof value !== 'object') { return false; } diff --git a/src/database/migrations/1760356800000-InitialPostgresSchema.ts b/src/database/migrations/1760356800000-InitialPostgresSchema.ts new file mode 100644 index 0000000..e55976b --- /dev/null +++ b/src/database/migrations/1760356800000-InitialPostgresSchema.ts @@ -0,0 +1,172 @@ +import { MigrationInterface, QueryRunner } from 'typeorm'; + +export class InitialPostgresSchema1760356800000 implements MigrationInterface { + name = 'InitialPostgresSchema1760356800000'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(`CREATE EXTENSION IF NOT EXISTS pgcrypto`); + + await queryRunner.query(` + CREATE TABLE users ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + full_name text NOT NULL, + username text NOT NULL, + email text NOT NULL, + mobile text, + password text NOT NULL, + role text NOT NULL, + client_type text NOT NULL, + app_name text NOT NULL DEFAULT '', + client_name text NOT NULL DEFAULT '', + is_active boolean NOT NULL DEFAULT true, + is_blocked boolean NOT NULL DEFAULT false, + api_key text, + allowed_inquiries text[] NOT NULL DEFAULT '{}', + request_limit_per_minute integer NOT NULL DEFAULT 60, + request_limit_per_day integer NOT NULL DEFAULT 10000, + total_requests integer NOT NULL DEFAULT 0, + last_login_at timestamptz, + password_changed_at timestamptz, + created_by uuid, + refresh_token text, + metadata jsonb NOT NULL DEFAULT '{}'::jsonb, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + CONSTRAINT uq_users_username UNIQUE (username), + CONSTRAINT uq_users_email UNIQUE (email), + CONSTRAINT fk_users_created_by FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL + ) + `); + await queryRunner.query(`CREATE INDEX idx_users_role ON users (role)`); + await queryRunner.query(`CREATE INDEX idx_users_client_type ON users (client_type)`); + await queryRunner.query(`CREATE INDEX idx_users_role_is_active ON users (role, is_active)`); + await queryRunner.query(`CREATE INDEX idx_users_client_type_app_name ON users (client_type, app_name)`); + + await queryRunner.query(` + CREATE TABLE audit_logs ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + event text NOT NULL, + user_id uuid, + actor_id uuid, + username text, + ip text, + user_agent text, + metadata jsonb NOT NULL DEFAULT '{}'::jsonb, + created_at timestamptz NOT NULL DEFAULT now(), + CONSTRAINT fk_audit_logs_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE SET NULL, + CONSTRAINT fk_audit_logs_actor FOREIGN KEY (actor_id) REFERENCES users (id) ON DELETE SET NULL + ) + `); + await queryRunner.query(`CREATE INDEX idx_audit_logs_event ON audit_logs (event)`); + await queryRunner.query(`CREATE INDEX idx_audit_logs_user_id ON audit_logs (user_id)`); + await queryRunner.query(`CREATE INDEX idx_audit_logs_created_at ON audit_logs (created_at DESC)`); + await queryRunner.query(`CREATE INDEX idx_audit_logs_event_created_at ON audit_logs (event, created_at DESC)`); + + await queryRunner.query(` + CREATE TABLE inquiry_logs ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + inquiry_type text NOT NULL, + provider text NOT NULL, + request_payload jsonb NOT NULL, + masked_request jsonb NOT NULL, + response_payload jsonb, + status text NOT NULL, + duration integer NOT NULL, + request_id text NOT NULL, + tracking_code text NOT NULL, + error jsonb, + attempt_summary jsonb, + outbound_requests jsonb, + created_at timestamptz NOT NULL DEFAULT now() + ) + `); + await queryRunner.query(`CREATE INDEX idx_inquiry_logs_request_id ON inquiry_logs (request_id)`); + await queryRunner.query(`CREATE INDEX idx_inquiry_logs_tracking_code ON inquiry_logs (tracking_code)`); + await queryRunner.query( + `CREATE INDEX idx_inquiry_logs_created_provider_type_status ON inquiry_logs (created_at DESC, provider, inquiry_type, status)`, + ); + await queryRunner.query( + `CREATE INDEX idx_inquiry_logs_provider_type_created ON inquiry_logs (provider, inquiry_type, created_at DESC)`, + ); + await queryRunner.query( + `CREATE INDEX idx_inquiry_logs_error_code_created_at ON inquiry_logs ((error->>'code'), created_at DESC)`, + ); + + await queryRunner.query(` + CREATE TABLE inquiry_result_cache ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + inquiry_type text NOT NULL, + cache_key text NOT NULL, + provider text NOT NULL, + data jsonb NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + CONSTRAINT uq_inquiry_result_cache_type_key UNIQUE (inquiry_type, cache_key) + ) + `); + await queryRunner.query(`CREATE INDEX idx_inquiry_result_cache_inquiry_type ON inquiry_result_cache (inquiry_type)`); + await queryRunner.query(`CREATE INDEX idx_inquiry_result_cache_cache_key ON inquiry_result_cache (cache_key)`); + + await queryRunner.query(` + CREATE TABLE general_tokens ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + service_provider text NOT NULL, + token_type text NOT NULL, + url text NOT NULL, + client_id text NOT NULL, + username text NOT NULL, + scope text NOT NULL, + access_token text NOT NULL, + refresh_token text, + expires_in integer NOT NULL, + expires_at timestamptz NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() + ) + `); + await queryRunner.query(`CREATE INDEX idx_general_tokens_service_provider ON general_tokens (service_provider)`); + await queryRunner.query(`CREATE INDEX idx_general_tokens_expires_at ON general_tokens (expires_at)`); + await queryRunner.query( + `CREATE INDEX idx_general_tokens_provider_created_at ON general_tokens (service_provider, created_at DESC)`, + ); + + await queryRunner.query(` + CREATE TABLE idempotency_records ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + scope_hash text NOT NULL, + request_fingerprint text NOT NULL, + status text NOT NULL, + expires_at timestamptz NOT NULL, + response_status integer, + response_body jsonb, + request_id text, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + CONSTRAINT uq_idempotency_records_scope_hash UNIQUE (scope_hash) + ) + `); + await queryRunner.query(`CREATE INDEX idx_idempotency_records_expires_at ON idempotency_records (expires_at)`); + + await queryRunner.query(` + CREATE TABLE distributed_locks ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + lock_key text NOT NULL, + owner_id text NOT NULL, + lease_until timestamptz NOT NULL, + fencing_token integer NOT NULL DEFAULT 0, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + CONSTRAINT uq_distributed_locks_lock_key UNIQUE (lock_key) + ) + `); + await queryRunner.query(`CREATE INDEX idx_distributed_locks_lease_until ON distributed_locks (lease_until)`); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`DROP TABLE IF EXISTS distributed_locks`); + await queryRunner.query(`DROP TABLE IF EXISTS idempotency_records`); + await queryRunner.query(`DROP TABLE IF EXISTS general_tokens`); + await queryRunner.query(`DROP TABLE IF EXISTS inquiry_result_cache`); + await queryRunner.query(`DROP TABLE IF EXISTS inquiry_logs`); + await queryRunner.query(`DROP TABLE IF EXISTS audit_logs`); + await queryRunner.query(`DROP TABLE IF EXISTS users`); + } +} diff --git a/src/database/postgres.helpers.ts b/src/database/postgres.helpers.ts new file mode 100644 index 0000000..e4c4b4d --- /dev/null +++ b/src/database/postgres.helpers.ts @@ -0,0 +1,12 @@ +export function isUniqueViolation(error: unknown): boolean { + if (!error || typeof error !== 'object') return false; + const candidate = error as { code?: string; driverError?: { code?: string } }; + return candidate.code === '23505' || candidate.driverError?.code === '23505'; +} + +const UUID_PATTERN = + /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; + +export function isUuid(value: string | undefined | null): value is string { + return Boolean(value && UUID_PATTERN.test(value)); +} diff --git a/src/database/snake-naming.strategy.ts b/src/database/snake-naming.strategy.ts new file mode 100644 index 0000000..77dcd06 --- /dev/null +++ b/src/database/snake-naming.strategy.ts @@ -0,0 +1,40 @@ +import { DefaultNamingStrategy, NamingStrategyInterface } from 'typeorm'; + +function snakeCase(value: string): string { + return value + .replace(/([a-z0-9])([A-Z])/g, '$1_$2') + .replace(/([A-Z])([A-Z][a-z])/g, '$1_$2') + .toLowerCase(); +} + +/** Maps TypeORM property names to PostgreSQL snake_case columns. */ +export class SnakeNamingStrategy extends DefaultNamingStrategy implements NamingStrategyInterface { + tableName(className: string, customName: string): string { + return customName || snakeCase(className); + } + + columnName(propertyName: string, customName: string, embeddedPrefixes: string[]): string { + const name = customName || propertyName; + return snakeCase([...embeddedPrefixes, name].filter(Boolean).join('_')); + } + + relationName(propertyName: string): string { + return snakeCase(propertyName); + } + + joinColumnName(relationName: string, referencedColumnName: string): string { + return snakeCase(`${relationName}_${referencedColumnName}`); + } + + joinTableName( + firstTableName: string, + secondTableName: string, + firstPropertyName: string, + ): string { + return snakeCase(`${firstTableName}_${firstPropertyName}_${secondTableName}`); + } + + joinTableColumnName(tableName: string, propertyName: string, columnName?: string): string { + return snakeCase(`${tableName}_${columnName || propertyName}`); + } +} diff --git a/src/database/typeorm.config.ts b/src/database/typeorm.config.ts new file mode 100644 index 0000000..8725290 --- /dev/null +++ b/src/database/typeorm.config.ts @@ -0,0 +1,16 @@ +import { ConfigService } from '@nestjs/config'; +import { TypeOrmModuleOptions } from '@nestjs/typeorm'; +import { join } from 'path'; +import { SnakeNamingStrategy } from './snake-naming.strategy'; + +export function typeOrmConfig(config: ConfigService): TypeOrmModuleOptions { + return { + type: 'postgres', + url: config.get('database.url'), + autoLoadEntities: true, + synchronize: false, + migrationsRun: true, + namingStrategy: new SnakeNamingStrategy(), + migrations: [join(__dirname, 'migrations', '*.{js,ts}')], + }; +} diff --git a/src/health/health.controller.ts b/src/health/health.controller.ts index faa0601..c90f3ee 100644 --- a/src/health/health.controller.ts +++ b/src/health/health.controller.ts @@ -4,7 +4,7 @@ import { HealthCheck, HealthCheckService, MemoryHealthIndicator, - MongooseHealthIndicator, + TypeOrmHealthIndicator, } from '@nestjs/terminus'; import { HealthService } from './health.service'; @@ -12,7 +12,7 @@ import { HealthService } from './health.service'; export class HealthController { constructor( private readonly health: HealthCheckService, - private readonly mongoose: MongooseHealthIndicator, + private readonly database: TypeOrmHealthIndicator, private readonly memory: MemoryHealthIndicator, private readonly disk: DiskHealthIndicator, private readonly healthService: HealthService, @@ -28,7 +28,7 @@ export class HealthController { @HealthCheck({ swaggerDocumentation: false }) readiness() { return this.health.check([ - () => this.mongoose.pingCheck('mongodb', { timeout: 1000 }), + () => this.database.pingCheck('postgres', { timeout: 1000 }), () => this.memory.checkHeap('memory_heap', this.healthService.heapThresholdBytes()), () => this.disk.checkStorage('disk', { diff --git a/src/health/health.module.ts b/src/health/health.module.ts index 68dde6a..ae5c3d7 100644 --- a/src/health/health.module.ts +++ b/src/health/health.module.ts @@ -1,11 +1,10 @@ import { Module } from '@nestjs/common'; -import { MongooseModule } from '@nestjs/mongoose'; import { TerminusModule } from '@nestjs/terminus'; import { HealthController } from './health.controller'; import { HealthService } from './health.service'; @Module({ - imports: [TerminusModule.forRoot(), MongooseModule], + imports: [TerminusModule.forRoot()], controllers: [HealthController], providers: [HealthService], }) diff --git a/src/idempotency/idempotency.module.ts b/src/idempotency/idempotency.module.ts index f1af3d3..892a33a 100644 --- a/src/idempotency/idempotency.module.ts +++ b/src/idempotency/idempotency.module.ts @@ -1,18 +1,11 @@ import { Module } from '@nestjs/common'; -import { MongooseModule } from '@nestjs/mongoose'; +import { TypeOrmModule } from '@nestjs/typeorm'; import { IdempotencyInterceptor } from './idempotency.interceptor'; import { IdempotencyService } from './idempotency.service'; -import { - IdempotencyRecord, - IdempotencyRecordSchema, -} from './schemas/idempotency-record.schema'; +import { IdempotencyRecord } from './schemas/idempotency-record.schema'; @Module({ - imports: [ - MongooseModule.forFeature([ - { name: IdempotencyRecord.name, schema: IdempotencyRecordSchema }, - ]), - ], + imports: [TypeOrmModule.forFeature([IdempotencyRecord])], providers: [IdempotencyService, IdempotencyInterceptor], exports: [IdempotencyService, IdempotencyInterceptor], }) diff --git a/src/idempotency/idempotency.service.ts b/src/idempotency/idempotency.service.ts index e7a2ae2..f42d641 100644 --- a/src/idempotency/idempotency.service.ts +++ b/src/idempotency/idempotency.service.ts @@ -1,11 +1,11 @@ import { createHash } from 'node:crypto'; -import { Injectable } from '@nestjs/common'; -import { InjectModel } from '@nestjs/mongoose'; -import { Model } from 'mongoose'; +import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common'; +import { InjectRepository } from '@nestjs/typeorm'; +import { QueryDeepPartialEntity, Repository } from 'typeorm'; import { AppException } from '../common/exceptions/app-exception'; +import { isUniqueViolation } from '../database/postgres.helpers'; import { IdempotencyRecord, - IdempotencyRecordDocument, IdempotencyRecordStatus, } from './schemas/idempotency-record.schema'; @@ -31,16 +31,30 @@ export interface IdempotencyBeginResult { const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000; const IN_PROGRESS_TTL_MS = 5 * 60 * 1000; +const CLEANUP_INTERVAL_MS = 15 * 60 * 1000; @Injectable() -export class IdempotencyService { +export class IdempotencyService implements OnModuleInit, OnModuleDestroy { private readonly ttlMs = this.readPositiveEnv('IDEMPOTENCY_TTL_MS', DEFAULT_TTL_MS); + private cleanupTimer?: NodeJS.Timeout; constructor( - @InjectModel(IdempotencyRecord.name) - private readonly recordModel: Model, + @InjectRepository(IdempotencyRecord) + private readonly records: Repository, ) {} + onModuleInit(): void { + void this.deleteExpired().catch(() => undefined); + this.cleanupTimer = setInterval(() => { + void this.deleteExpired().catch(() => undefined); + }, CLEANUP_INTERVAL_MS); + this.cleanupTimer.unref?.(); + } + + onModuleDestroy(): void { + if (this.cleanupTimer) clearInterval(this.cleanupTimer); + } + async begin(input: IdempotencyBeginInput): Promise { const key = input.key.trim(); if (!key || key.length > 256) { @@ -52,23 +66,32 @@ export class IdempotencyService { const scopeHash = this.hash(`${input.callerId}:${input.method}:${input.path}:${key}`); const requestFingerprint = this.hash(this.stableStringify(input.body)); const now = Date.now(); - const expiresAt = new Date(now + this.ttlMs); + const inProgressExpiresAt = new Date(now + Math.min(this.ttlMs, IN_PROGRESS_TTL_MS)); + + let record = await this.records.findOne({ where: { scopeHash } }); + if (record && record.expiresAt.getTime() <= now) { + if (await this.reclaim(record.id, requestFingerprint, inProgressExpiresAt, input.requestId)) { + return { scopeHash }; + } + record = await this.records.findOne({ where: { scopeHash } }); + } - let record = await this.recordModel.findOne({ scopeHash }).exec(); let created = false; - if (!record) { + if (!record || record.expiresAt.getTime() <= now) { try { - record = await this.recordModel.create({ - scopeHash, - requestFingerprint, - status: IdempotencyRecordStatus.IN_PROGRESS, - expiresAt: new Date(now + Math.min(this.ttlMs, IN_PROGRESS_TTL_MS)), - requestId: input.requestId, - }); + record = await this.records.save( + this.records.create({ + scopeHash, + requestFingerprint, + status: IdempotencyRecordStatus.IN_PROGRESS, + expiresAt: inProgressExpiresAt, + requestId: input.requestId, + }), + ); created = true; } catch (error) { - if (!this.isDuplicateKey(error)) throw error; - record = await this.recordModel.findOne({ scopeHash }).exec(); + if (!isUniqueViolation(error)) throw error; + record = await this.records.findOne({ where: { scopeHash } }); } } @@ -78,6 +101,13 @@ export class IdempotencyService { if (created) return { scopeHash }; + if (record.expiresAt.getTime() <= now) { + if (await this.reclaim(record.id, requestFingerprint, inProgressExpiresAt, input.requestId)) { + return { scopeHash }; + } + throw new AppException('IDEMPOTENCY_REQUEST_IN_PROGRESS'); + } + if (record.requestFingerprint !== requestFingerprint) { throw new AppException('IDEMPOTENCY_KEY_REUSED'); } @@ -93,47 +123,66 @@ export class IdempotencyService { }; } - if (record.expiresAt.getTime() <= now) { - const reclaimed = await this.recordModel - .findOneAndUpdate( - { _id: record._id, expiresAt: { $lte: new Date(now) } }, - { - $set: { - requestFingerprint, - status: IdempotencyRecordStatus.IN_PROGRESS, - expiresAt, - requestId: input.requestId, - }, - }, - { new: true }, - ) - .exec(); - if (reclaimed) return { scopeHash }; - } - throw new AppException('IDEMPOTENCY_REQUEST_IN_PROGRESS'); } async complete(scopeHash: string, responseBody: unknown, responseStatus = 200): Promise { - await this.recordModel - .updateOne( - { scopeHash, status: IdempotencyRecordStatus.IN_PROGRESS }, - { - $set: { - status: IdempotencyRecordStatus.COMPLETED, - responseStatus, - responseBody, - expiresAt: new Date(Date.now() + this.ttlMs), - }, - }, - ) - .exec(); + const values: QueryDeepPartialEntity = { + status: IdempotencyRecordStatus.COMPLETED, + responseStatus, + responseBody: this.asJsonObject(responseBody) as QueryDeepPartialEntity< + IdempotencyRecord + >['responseBody'], + expiresAt: new Date(Date.now() + this.ttlMs), + }; + await this.records.update( + { scopeHash, status: IdempotencyRecordStatus.IN_PROGRESS }, + values, + ); } async abandon(scopeHash: string): Promise { - await this.recordModel - .deleteOne({ scopeHash, status: IdempotencyRecordStatus.IN_PROGRESS }) - .exec(); + await this.records.delete({ scopeHash, status: IdempotencyRecordStatus.IN_PROGRESS }); + } + + private async reclaim( + id: string, + requestFingerprint: string, + expiresAt: Date, + requestId?: string, + ): Promise { + const result = await this.records + .createQueryBuilder() + .update(IdempotencyRecord) + .set({ + requestFingerprint, + status: IdempotencyRecordStatus.IN_PROGRESS, + expiresAt, + requestId: requestId ?? null, + responseStatus: null, + responseBody: () => 'NULL', + }) + .where('id = :id', { id }) + .andWhere('expires_at <= :now', { now: new Date() }) + .execute(); + return (result.affected ?? 0) > 0; + } + + private async deleteExpired(): Promise { + await this.records + .createQueryBuilder() + .delete() + .from(IdempotencyRecord) + .where('expires_at <= :now', { now: new Date() }) + .execute(); + } + + private asJsonObject(value: unknown): Record | null { + if (value === null || value === undefined) return null; + if (typeof value === 'object' && !Array.isArray(value)) { + return value as Record; + } + return { value }; } private hash(value: string): string { @@ -150,10 +199,6 @@ export class IdempotencyService { .join(',')}}`; } - private isDuplicateKey(error: unknown): boolean { - return Boolean(error && typeof error === 'object' && 'code' in error && (error as { code?: number }).code === 11000); - } - private readPositiveEnv(name: string, fallback: number): number { const value = Number.parseInt(process.env[name] ?? '', 10); return Number.isFinite(value) && value > 0 ? value : fallback; diff --git a/src/idempotency/schemas/idempotency-record.schema.ts b/src/idempotency/schemas/idempotency-record.schema.ts index 94e12cd..a81dcf7 100644 --- a/src/idempotency/schemas/idempotency-record.schema.ts +++ b/src/idempotency/schemas/idempotency-record.schema.ts @@ -1,36 +1,41 @@ -import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; -import { HydratedDocument, Schema as MongooseSchema } from 'mongoose'; - -export type IdempotencyRecordDocument = HydratedDocument; +import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn, UpdateDateColumn } from 'typeorm'; export enum IdempotencyRecordStatus { IN_PROGRESS = 'IN_PROGRESS', COMPLETED = 'COMPLETED', } -@Schema({ timestamps: true, collection: 'idempotency_records' }) +@Entity('idempotency_records') export class IdempotencyRecord { - @Prop({ required: true, unique: true, index: true }) + @PrimaryGeneratedColumn('uuid') + id!: string; + + @Index({ unique: true }) + @Column({ type: 'text' }) scopeHash!: string; - @Prop({ required: true }) + @Column({ type: 'text' }) requestFingerprint!: string; - @Prop({ required: true, enum: IdempotencyRecordStatus }) + @Column({ type: 'text' }) status!: IdempotencyRecordStatus; - @Prop({ required: true }) + @Index() + @Column({ type: 'timestamptz' }) expiresAt!: Date; - @Prop() - responseStatus?: number; + @Column({ type: 'int', nullable: true }) + responseStatus?: number | null; - @Prop({ type: MongooseSchema.Types.Mixed }) - responseBody?: unknown; + @Column({ type: 'jsonb', nullable: true }) + responseBody?: Record | null; - @Prop() - requestId?: string; + @Column({ type: 'text', nullable: true }) + requestId?: string | null; + + @CreateDateColumn({ type: 'timestamptz' }) + createdAt!: Date; + + @UpdateDateColumn({ type: 'timestamptz' }) + updatedAt!: Date; } - -export const IdempotencyRecordSchema = SchemaFactory.createForClass(IdempotencyRecord); -IdempotencyRecordSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 }); diff --git a/src/inquiry/dto/person-inquiry-request.dto.ts b/src/inquiry/dto/person-inquiry-request.dto.ts index 931856f..d25aac5 100644 --- a/src/inquiry/dto/person-inquiry-request.dto.ts +++ b/src/inquiry/dto/person-inquiry-request.dto.ts @@ -9,8 +9,13 @@ export class PersonInquiryRequestDto { @Matches(/^\d{10}$/, { message: 'nationalCode must be exactly 10 digits' }) nationalCode!: string; - @ApiProperty({ example: '1378-11-24', description: 'Jalali birth date (YYYY-MM-DD)' }) - @Matches(/^\d{4}-\d{2}-\d{2}$/, { message: 'birthDate must be in YYYY-MM-DD format' }) + @ApiProperty({ + example: '1378-11-24', + description: 'Jalali birth date (YYYY-MM-DD) or Jalali birth year (YYYY)', + }) + @Matches(/^\d{4}(-\d{2}-\d{2})?$/, { + message: 'birthDate must be in YYYY or YYYY-MM-DD format', + }) @IsNotEmpty() birthDate!: string; diff --git a/src/logging/inquiry-log.service.ts b/src/logging/inquiry-log.service.ts index 0d633e4..66aed23 100644 --- a/src/logging/inquiry-log.service.ts +++ b/src/logging/inquiry-log.service.ts @@ -1,22 +1,19 @@ import { Injectable } from '@nestjs/common'; -import { InjectModel } from '@nestjs/mongoose'; -import { FilterQuery, Model } from 'mongoose'; +import { InjectRepository } from '@nestjs/typeorm'; +import { Repository } from 'typeorm'; import { AttemptSummaryDto } from '../common/dto/attempt-summary.dto'; -import { - InquiryStatus, - NO_MATCH_ERROR_CODES, -} from '../common/enums/inquiry-status.enum'; +import { InquiryStatus, NO_MATCH_ERROR_CODES } from '../common/enums/inquiry-status.enum'; import { InquiryType } from '../common/enums/inquiry-type.enum'; import { ProviderName } from '../common/enums/provider-name.enum'; import { maskPayload } from '../common/helpers/mask-payload.helper'; +import type { OutboundRequestTrace } from '../common/helpers/http-client.helper'; import { InquiryLogQueryDto, InquiryLogTimelineQueryDto, LogTimelineInterval, LogTimeRangePreset, } from './dto/inquiry-log-query.dto'; -import { InquiryLog, InquiryLogDocument } from './schemas/inquiry-log.schema'; -import type { OutboundRequestTrace } from '../common/helpers/http-client.helper'; +import { InquiryLog } from './schemas/inquiry-log.schema'; export interface CreateInquiryLogInput { inquiryType: InquiryType; @@ -94,20 +91,32 @@ export interface TimelineBucket { @Injectable() export class InquiryLogService { constructor( - @InjectModel(InquiryLog.name) - private readonly inquiryLogModel: Model, + @InjectRepository(InquiryLog) + private readonly inquiryLogs: Repository, ) {} - async create(input: CreateInquiryLogInput): Promise { - return this.inquiryLogModel.create({ - ...input, - maskedRequest: maskPayload(input.requestPayload), - }); + async create(input: CreateInquiryLogInput): Promise { + return this.inquiryLogs.save( + this.inquiryLogs.create({ + inquiryType: input.inquiryType, + provider: input.provider, + requestPayload: input.requestPayload, + maskedRequest: maskPayload(input.requestPayload), + responsePayload: input.responsePayload ?? null, + status: input.status, + duration: input.duration, + requestId: input.requestId, + trackingCode: input.trackingCode, + error: input.error ?? null, + attemptSummary: (input.attemptSummary as Record | undefined) ?? null, + outboundRequests: (input.outboundRequests as Record[] | undefined) ?? null, + }), + ); } async purgeAll(): Promise<{ deletedCount: number }> { - const result = await this.inquiryLogModel.deleteMany({}).exec(); - return { deletedCount: result.deletedCount ?? 0 }; + const result = await this.inquiryLogs.createQueryBuilder().delete().from(InquiryLog).execute(); + return { deletedCount: result.affected ?? 0 }; } async findLogs(query: InquiryLogQueryDto): Promise<{ @@ -116,299 +125,239 @@ export class InquiryLogService { limit: number; total: number; }> { - const filter = this.buildFilter(query); + const params: unknown[] = []; + const where = this.buildWhere(query, params); const limit = query.limit ?? 50; const page = query.page ?? 1; const skip = (page - 1) * limit; - const [logs, total] = await Promise.all([ - this.inquiryLogModel - .find(filter) - .sort({ createdAt: -1 }) - .skip(skip) - .limit(limit) - .select('inquiryType provider status duration requestId trackingCode maskedRequest responsePayload error outboundRequests createdAt') - .lean() - .exec(), - this.inquiryLogModel.countDocuments(filter), - ]); + const countRows = await this.inquiryLogs.query>( + `SELECT COUNT(*)::int AS total FROM inquiry_logs WHERE ${where}`, + params, + ); + const pageParams = [...params, limit, skip]; + const logs = await this.inquiryLogs.query( + `SELECT id, + inquiry_type AS "inquiryType", + provider, + status, + duration, + request_id AS "requestId", + tracking_code AS "trackingCode", + masked_request AS "maskedRequest", + response_payload AS "responsePayload", + error, + outbound_requests AS "outboundRequests", + created_at AS "createdAt" + FROM inquiry_logs + WHERE ${where} + ORDER BY created_at DESC + LIMIT $${params.length + 1} OFFSET $${params.length + 2}`, + pageParams, + ); return { - data: logs.map((log) => ({ - id: log._id.toString(), - inquiryType: log.inquiryType, - provider: log.provider, - status: log.status, - duration: log.duration, - requestId: log.requestId, - trackingCode: log.trackingCode, - maskedRequest: log.maskedRequest, - responsePayload: log.responsePayload, - error: log.error, - outboundRequests: log.outboundRequests, - createdAt: log.createdAt, - })), + data: logs, page, limit, - total, + total: countRows[0]?.total ?? 0, }; } async getSummary(query: InquiryLogQueryDto): Promise { - const [summary] = await this.inquiryLogModel.aggregate([ - { $match: this.buildFilter(query) }, - { - $group: { - _id: null, - total: { $sum: 1 }, - success: { - $sum: { $cond: [{ $eq: ['$status', InquiryStatus.SUCCESS] }, 1, 0] }, - }, - failure: { - $sum: { $cond: [{ $eq: ['$status', InquiryStatus.FAILURE] }, 1, 0] }, - }, - noMatch: { - $sum: { - $cond: [ - { - $or: [ - { $eq: ['$status', InquiryStatus.NO_MATCH] }, - { - $and: [ - { $eq: ['$status', InquiryStatus.FAILURE] }, - { $in: ['$error.code', NO_MATCH_ERROR_CODES] }, - ], - }, - ], - }, - 1, - 0, - ], - }, - }, - noMatchFailure: { - $sum: { - $cond: [ - { - $and: [ - { $eq: ['$status', InquiryStatus.FAILURE] }, - { $in: ['$error.code', NO_MATCH_ERROR_CODES] }, - ], - }, - 1, - 0, - ], - }, - }, - partial: { - $sum: { $cond: [{ $eq: ['$status', InquiryStatus.PARTIAL] }, 1, 0] }, - }, - averageDuration: { $avg: '$duration' }, - minDuration: { $min: '$duration' }, - maxDuration: { $max: '$duration' }, - }, - }, - { - $project: { - _id: 0, - total: 1, - success: 1, - failure: { $subtract: ['$failure', '$noMatchFailure'] }, - evaluated: { - $add: ['$success', { $subtract: ['$failure', '$noMatchFailure'] }], - }, - noMatch: 1, - partial: 1, - successRate: { - $cond: [ - { $eq: [{ $add: ['$success', { $subtract: ['$failure', '$noMatchFailure'] }] }, 0] }, - 0, - { $divide: ['$success', { $add: ['$success', { $subtract: ['$failure', '$noMatchFailure'] }] }] }, - ], - }, - failureRate: { - $cond: [ - { $eq: [{ $add: ['$success', { $subtract: ['$failure', '$noMatchFailure'] }] }, 0] }, - 0, - { $divide: [{ $subtract: ['$failure', '$noMatchFailure'] }, { $add: ['$success', { $subtract: ['$failure', '$noMatchFailure'] }] }] }, - ], - }, - averageDuration: { $ifNull: ['$averageDuration', 0] }, - minDuration: { $ifNull: ['$minDuration', 0] }, - maxDuration: { $ifNull: ['$maxDuration', 0] }, - }, - }, - ]); + const params: unknown[] = []; + const where = this.buildWhere(query, params); + params.push([...NO_MATCH_ERROR_CODES]); + const codesParam = `$${params.length}`; + const rows = await this.inquiryLogs.query< + Array<{ + total: number; + success: number; + failure: number; + noMatch: number; + partial: number; + averageDuration: string | number | null; + minDuration: number | null; + maxDuration: number | null; + }> + >( + `SELECT COUNT(*)::int AS total, + COUNT(*) FILTER (WHERE status = '${InquiryStatus.SUCCESS}')::int AS success, + COUNT(*) FILTER ( + WHERE status = '${InquiryStatus.FAILURE}' + AND COALESCE(error->>'code', '') <> ALL(${codesParam}::text[]) + )::int AS failure, + COUNT(*) FILTER ( + WHERE status = '${InquiryStatus.NO_MATCH}' + OR ( + status = '${InquiryStatus.FAILURE}' + AND error->>'code' = ANY(${codesParam}::text[]) + ) + )::int AS "noMatch", + COUNT(*) FILTER (WHERE status = '${InquiryStatus.PARTIAL}')::int AS partial, + AVG(duration) AS "averageDuration", + MIN(duration)::int AS "minDuration", + MAX(duration)::int AS "maxDuration" + FROM inquiry_logs + WHERE ${where}`, + params, + ); - return summary ?? this.emptySummary(); + const row = rows[0]; + if (!row || Number(row.total) === 0) return this.emptySummary(); + + const success = Number(row.success); + const failure = Number(row.failure); + const evaluated = success + failure; + return { + total: Number(row.total), + evaluated, + success, + failure, + noMatch: Number(row.noMatch), + partial: Number(row.partial), + successRate: evaluated === 0 ? 0 : success / evaluated, + failureRate: evaluated === 0 ? 0 : failure / evaluated, + averageDuration: Number(row.averageDuration ?? 0), + minDuration: Number(row.minDuration ?? 0), + maxDuration: Number(row.maxDuration ?? 0), + }; } async getCommonErrors(query: InquiryLogQueryDto): Promise { - const limit = query.limit ?? 10; + const params: unknown[] = []; + const where = this.buildWhere(query, params); + params.push(query.limit ?? 10); + const limitParam = `$${params.length}`; - return this.inquiryLogModel.aggregate([ - { - $match: { - ...this.buildFilter(query), - error: { $exists: true, $ne: null }, - }, - }, - { - $group: { - _id: { - code: { $ifNull: ['$error.code', 'UNKNOWN_ERROR'] }, - message: { $ifNull: ['$error.message', 'Unknown error'] }, - }, - count: { $sum: 1 }, - lastSeenAt: { $max: '$createdAt' }, - }, - }, - { $sort: { count: -1, lastSeenAt: -1 } }, - { $limit: limit }, - { - $project: { - _id: 0, - code: '$_id.code', - message: '$_id.message', - count: 1, - lastSeenAt: 1, - }, - }, - ]); + return this.inquiryLogs.query( + `SELECT COALESCE(error->>'code', 'UNKNOWN_ERROR') AS code, + COALESCE(error->>'message', 'Unknown error') AS message, + COUNT(*)::int AS count, + MAX(created_at) AS "lastSeenAt" + FROM inquiry_logs + WHERE ${where} AND error IS NOT NULL + GROUP BY 1, 2 + ORDER BY count DESC, "lastSeenAt" DESC + LIMIT ${limitParam}`, + params, + ); } async getDurationExtremes(query: InquiryLogQueryDto): Promise<{ fastest: DurationExtremeItem[]; slowest: DurationExtremeItem[]; }> { - const filter = this.buildFilter(query); + const params: unknown[] = []; + const where = this.buildWhere(query, params); const limit = query.limit ?? 10; - const projection = - 'inquiryType provider status duration requestId trackingCode error createdAt'; + const select = `SELECT id, + inquiry_type AS "inquiryType", + provider, + status, + duration, + request_id AS "requestId", + tracking_code AS "trackingCode", + error, + created_at AS "createdAt" + FROM inquiry_logs + WHERE ${where}`; const [fastest, slowest] = await Promise.all([ - this.inquiryLogModel.find(filter).sort({ duration: 1 }).limit(limit).select(projection).lean(), - this.inquiryLogModel.find(filter).sort({ duration: -1 }).limit(limit).select(projection).lean(), + this.inquiryLogs.query( + `${select} ORDER BY duration ASC LIMIT $${params.length + 1}`, + [...params, limit], + ), + this.inquiryLogs.query( + `${select} ORDER BY duration DESC LIMIT $${params.length + 1}`, + [...params, limit], + ), ]); - return { - fastest: fastest.map((log) => this.toDurationExtremeItem(log)), - slowest: slowest.map((log) => this.toDurationExtremeItem(log)), - }; + return { fastest, slowest }; } async getTimeline(query: InquiryLogTimelineQueryDto): Promise { - const interval = query.interval ?? LogTimelineInterval.HOUR; + const params: unknown[] = []; + const where = this.buildWhere(query, params); + const format = this.timelineFormat(query.interval ?? LogTimelineInterval.HOUR); + params.push(format); + const formatParam = `$${params.length}`; - return this.inquiryLogModel.aggregate([ - { $match: this.buildFilter(query) }, - { - $group: { - _id: { - bucket: { - $dateToString: { - format: this.timelineFormat(interval), - date: '$createdAt', - timezone: 'Asia/Tehran', - }, - }, - errorCode: { $ifNull: ['$error.code', null] }, - }, - total: { $sum: 1 }, - success: { - $sum: { $cond: [{ $eq: ['$status', InquiryStatus.SUCCESS] }, 1, 0] }, - }, - failure: { - $sum: { $cond: [{ $eq: ['$status', InquiryStatus.FAILURE] }, 1, 0] }, - }, - partial: { - $sum: { $cond: [{ $eq: ['$status', InquiryStatus.PARTIAL] }, 1, 0] }, - }, - durationSum: { $sum: '$duration' }, - maxDuration: { $max: '$duration' }, - }, - }, - { - $addFields: { - errorCount: { - $cond: [{ $ne: ['$_id.errorCode', null] }, '$total', 0], - }, - }, - }, - { $sort: { '_id.bucket': 1, errorCount: -1 } }, - { - $group: { - _id: '$_id.bucket', - total: { $sum: '$total' }, - success: { $sum: '$success' }, - failure: { $sum: '$failure' }, - partial: { $sum: '$partial' }, - durationSum: { $sum: '$durationSum' }, - maxDuration: { $max: '$maxDuration' }, - commonErrorCode: { $first: '$_id.errorCode' }, - }, - }, - { $sort: { _id: 1 } }, - { - $project: { - _id: 0, - bucket: '$_id', - total: 1, - success: 1, - failure: 1, - partial: 1, - averageDuration: { - $cond: [{ $eq: ['$total', 0] }, 0, { $divide: ['$durationSum', '$total'] }], - }, - maxDuration: { $ifNull: ['$maxDuration', 0] }, - commonErrorCode: 1, - }, - }, - ]); + const rows = await this.inquiryLogs.query< + Array + >( + `WITH grouped AS ( + SELECT to_char(created_at AT TIME ZONE 'Asia/Tehran', ${formatParam}) AS bucket, + error->>'code' AS error_code, + COUNT(*)::int AS total, + COUNT(*) FILTER (WHERE status = '${InquiryStatus.SUCCESS}')::int AS success, + COUNT(*) FILTER (WHERE status = '${InquiryStatus.FAILURE}')::int AS failure, + COUNT(*) FILTER (WHERE status = '${InquiryStatus.PARTIAL}')::int AS partial, + COALESCE(SUM(duration), 0)::float AS duration_sum, + COALESCE(MAX(duration), 0)::int AS max_duration + FROM inquiry_logs + WHERE ${where} + GROUP BY 1, 2 + ), + ranked AS ( + SELECT *, + ROW_NUMBER() OVER ( + PARTITION BY bucket + ORDER BY CASE WHEN error_code IS NOT NULL THEN total ELSE 0 END DESC + ) AS rn + FROM grouped + ) + SELECT bucket, + SUM(total)::int AS total, + SUM(success)::int AS success, + SUM(failure)::int AS failure, + SUM(partial)::int AS partial, + CASE WHEN SUM(total) = 0 THEN 0 ELSE SUM(duration_sum) / SUM(total) END AS "averageDuration", + MAX(max_duration)::int AS "maxDuration", + MAX(CASE WHEN rn = 1 THEN error_code END) AS "commonErrorCode" + FROM ranked + GROUP BY bucket + ORDER BY bucket`, + params, + ); + + return rows.map((row) => ({ + bucket: row.bucket, + total: Number(row.total), + success: Number(row.success), + failure: Number(row.failure), + partial: Number(row.partial), + averageDuration: Number(row.averageDuration), + maxDuration: Number(row.maxDuration), + ...(row.commonErrorCode ? { commonErrorCode: row.commonErrorCode } : {}), + })); } - private buildFilter(query: InquiryLogQueryDto): FilterQuery { - const filter: FilterQuery = {}; - const createdAt = this.buildCreatedAtFilter(query); - - if (createdAt) { - filter.createdAt = createdAt; - } - - if (query.inquiryType) { - filter.inquiryType = query.inquiryType; - } - if (query.provider) { - filter.provider = query.provider; - } - if (query.status) { - filter.status = query.status; - } - if (query.errorCode) { - filter['error.code'] = query.errorCode; - } - if (query.errorMessage) { - filter['error.message'] = { $regex: query.errorMessage, $options: 'i' }; - } - if (query.trackingCode) { - filter.trackingCode = query.trackingCode; - } - - return filter; - } - - private buildCreatedAtFilter(query: InquiryLogQueryDto): { $gte?: Date; $lte?: Date } | undefined { - if (!query.from && !query.to && !query.preset) { - return undefined; - } + private buildWhere(query: InquiryLogQueryDto, params: unknown[]): string { + const clauses: string[] = []; + const add = (sql: string, value: unknown) => { + params.push(value); + clauses.push(sql.replace('?', `$${params.length}`)); + }; const to = query.to ? new Date(query.to) : undefined; - const from = query.from ? new Date(query.from) : this.defaultFromDate(query.preset); + const from = + query.from ? new Date(query.from) : query.preset || query.to ? this.defaultFromDate(query.preset) : undefined; + if (from) add('created_at >= ?', from); + if (to) add('created_at <= ?', to); + if (query.inquiryType) add('inquiry_type = ?', query.inquiryType); + if (query.provider) add('provider = ?', query.provider); + if (query.status) add('status = ?', query.status); + if (query.errorCode) add(`error->>'code' = ?`, query.errorCode); + if (query.errorMessage) add(`error->>'message' ILIKE ? ESCAPE '\\'`, this.likeContains(query.errorMessage)); + if (query.trackingCode) add('tracking_code = ?', query.trackingCode); - return { - ...(from && { $gte: from }), - ...(to && { $lte: to }), - }; + return clauses.length ? clauses.join(' AND ') : 'TRUE'; + } + + private likeContains(value: string): string { + return `%${value.replace(/[\\%_]/g, (character) => `\\${character}`)}%`; } private defaultFromDate(preset?: LogTimeRangePreset): Date { @@ -429,12 +378,12 @@ export class InquiryLogService { private timelineFormat(interval: LogTimelineInterval): string { switch (interval) { case LogTimelineInterval.MONTH: - return '%Y-%m'; + return 'YYYY-MM'; case LogTimelineInterval.DAY: - return '%Y-%m-%d'; + return 'YYYY-MM-DD'; case LogTimelineInterval.HOUR: default: - return '%Y-%m-%d %H:00'; + return 'YYYY-MM-DD HH24:00'; } } @@ -453,28 +402,4 @@ export class InquiryLogService { maxDuration: 0, }; } - - private toDurationExtremeItem(log: { - _id: unknown; - inquiryType: InquiryType; - provider: ProviderName; - status: InquiryStatus; - duration: number; - requestId: string; - trackingCode: string; - error?: Record; - createdAt?: Date; - }): DurationExtremeItem { - return { - id: String(log._id), - inquiryType: log.inquiryType, - provider: log.provider, - status: log.status, - duration: log.duration, - requestId: log.requestId, - trackingCode: log.trackingCode, - error: log.error, - createdAt: log.createdAt, - }; - } } diff --git a/src/logging/logging.module.ts b/src/logging/logging.module.ts index a15dd92..c399ea7 100644 --- a/src/logging/logging.module.ts +++ b/src/logging/logging.module.ts @@ -1,13 +1,11 @@ import { Module } from '@nestjs/common'; -import { MongooseModule } from '@nestjs/mongoose'; +import { TypeOrmModule } from '@nestjs/typeorm'; import { InquiryLogsController } from './inquiry-logs.controller'; import { InquiryLogService } from './inquiry-log.service'; -import { InquiryLog, InquiryLogSchema } from './schemas/inquiry-log.schema'; +import { InquiryLog } from './schemas/inquiry-log.schema'; @Module({ - imports: [ - MongooseModule.forFeature([{ name: InquiryLog.name, schema: InquiryLogSchema }]), - ], + imports: [TypeOrmModule.forFeature([InquiryLog])], controllers: [InquiryLogsController], providers: [InquiryLogService], exports: [InquiryLogService], diff --git a/src/logging/schemas/inquiry-log.schema.ts b/src/logging/schemas/inquiry-log.schema.ts index 7205a58..cb35f1c 100644 --- a/src/logging/schemas/inquiry-log.schema.ts +++ b/src/logging/schemas/inquiry-log.schema.ts @@ -1,57 +1,56 @@ -import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; -import { HydratedDocument } from 'mongoose'; +import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn } from 'typeorm'; import { InquiryStatus } from '../../common/enums/inquiry-status.enum'; import { InquiryType } from '../../common/enums/inquiry-type.enum'; import { ProviderName } from '../../common/enums/provider-name.enum'; -export type InquiryLogDocument = HydratedDocument; - /** - * MongoDB audit trail for every inquiry attempt. + * Audit trail for every inquiry attempt. */ -@Schema({ timestamps: { createdAt: true, updatedAt: false }, collection: 'inquiry_logs' }) +@Entity('inquiry_logs') +@Index(['createdAt', 'provider', 'inquiryType', 'status']) +@Index(['provider', 'inquiryType', 'createdAt']) export class InquiryLog { - @Prop({ required: true, enum: InquiryType }) + @PrimaryGeneratedColumn('uuid') + id!: string; + + @Column({ type: 'text' }) inquiryType!: InquiryType; - @Prop({ required: true, enum: ProviderName }) + @Column({ type: 'text' }) provider!: ProviderName; - @Prop({ type: Object, required: true }) + @Column({ type: 'jsonb' }) requestPayload!: Record; - @Prop({ type: Object, required: true }) + @Column({ type: 'jsonb' }) maskedRequest!: Record; - @Prop({ type: Object }) - responsePayload?: Record; + @Column({ type: 'jsonb', nullable: true }) + responsePayload?: Record | null; - @Prop({ required: true, enum: InquiryStatus }) + @Column({ type: 'text' }) status!: InquiryStatus; - @Prop({ required: true }) + @Column({ type: 'int' }) duration!: number; - @Prop({ required: true, index: true }) + @Index() + @Column({ type: 'text' }) requestId!: string; - @Prop({ required: true, index: true }) + @Index() + @Column({ type: 'text' }) trackingCode!: string; - @Prop({ type: Object }) - error?: Record; + @Column({ type: 'jsonb', nullable: true }) + error?: Record | null; - @Prop({ type: Object }) - attemptSummary?: Record; + @Column({ type: 'jsonb', nullable: true }) + attemptSummary?: Record | null; - @Prop({ type: [Object] }) - outboundRequests?: Record[]; + @Column({ type: 'jsonb', nullable: true }) + outboundRequests?: Record[] | null; - createdAt?: Date; + @CreateDateColumn({ type: 'timestamptz' }) + createdAt!: Date; } - -export const InquiryLogSchema = SchemaFactory.createForClass(InquiryLog); - -InquiryLogSchema.index({ createdAt: -1, provider: 1, inquiryType: 1, status: 1 }); -InquiryLogSchema.index({ provider: 1, inquiryType: 1, createdAt: -1 }); -InquiryLogSchema.index({ 'error.code': 1, createdAt: -1 }); diff --git a/src/providers/implementations/amitis.provider.ts b/src/providers/implementations/amitis.provider.ts index 351adb0..da41c51 100644 --- a/src/providers/implementations/amitis.provider.ts +++ b/src/providers/implementations/amitis.provider.ts @@ -19,7 +19,7 @@ import { } from '../../common/helpers/provider-resilience.helper'; import { withRetry } from '../../common/helpers/retry.helper'; import { AmitisAuthServiceConfig } from '../../config/configuration'; -import { GeneralTokenDocument } from '../schemas/general-token.schema'; +import { GeneralToken } from '../schemas/general-token.schema'; import { GeneralTokenService } from '../services/general-token.service'; import { DistributedLockService } from '../services/distributed-lock.service'; @@ -172,7 +172,7 @@ export class AmitisProvider { } private async refreshAccessToken( - latestToken: GeneralTokenDocument, + latestToken: GeneralToken, providerName: ProviderName, inquiryType: InquiryType, signal?: AbortSignal, @@ -184,7 +184,7 @@ export class AmitisProvider { RefreshToken: latestToken.refreshToken, }, { signal }), ); - const token = this.extractToken(response.data, latestToken.refreshToken); + const token = this.extractToken(response.data, latestToken.refreshToken ?? undefined); await this.saveToken( token, @@ -276,7 +276,7 @@ export class AmitisProvider { }; } - private isExpired(token: GeneralTokenDocument): boolean { + private isExpired(token: GeneralToken): boolean { // Access token expires in 20 minutes, add 60 second buffer const refreshBufferMs = 60 * 1000; return !token.expiresAt || Date.now() + refreshBufferMs >= token.expiresAt.getTime(); @@ -286,7 +286,7 @@ export class AmitisProvider { * Check if token is within 24-hour window from creation * Refresh token is valid for 24 hours after initial login */ - private isWithin24Hours(token: GeneralTokenDocument): boolean { + private isWithin24Hours(token: GeneralToken): boolean { if (!token.createdAt) { return false; } diff --git a/src/providers/implementations/tejaratnou.provider.ts b/src/providers/implementations/tejaratnou.provider.ts index 4e19921..ba610ff 100644 --- a/src/providers/implementations/tejaratnou.provider.ts +++ b/src/providers/implementations/tejaratnou.provider.ts @@ -6,6 +6,7 @@ import { CentInsurApiResponse, getCentInsurProviderError, } from '../../common/helpers/centinsur-response.helper'; +import { getSayahProviderError, SayahApiResponse } from '../../common/helpers/sayah-response.helper'; import { InquiryType } from '../../common/enums/inquiry-type.enum'; import { ProviderName } from '../../common/enums/provider-name.enum'; import { jalaliDateToGregorianDate } from '../../common/helpers/jalali-date.helper'; @@ -69,10 +70,12 @@ export class TejaratNouProvider implements InquiryProvider { - const providerBirthDate = jalaliDateToGregorianDate(payload.birthDate); + const root = this.configuredUrl(InquiryType.PERSON, '/api/identity-inquiry'); + const yearOnly = /^\d{4}$/.test(payload.birthDate); const response = await this.authenticatedRequest( - 'POST', - `/api/identity-inquiry/national-code/${payload.nationalCode}/birthdate/${encodeURIComponent(providerBirthDate)}`, - {}, + yearOnly ? 'POST' : 'GET', + yearOnly + ? `${root}/national-code/${payload.nationalCode}/birthdate-year/${payload.birthDate}` + : `${root}/national-code/${payload.nationalCode}/birthdate/${encodeURIComponent(this.toGregorianBirthDate(payload.birthDate))}`, + undefined, context, ); @@ -361,7 +370,7 @@ export class TejaratNouProvider implements InquiryProvider { const data = await this.authenticatedRequest( 'POST', - '/api/compliance-inquiry/compatibility', + this.configuredUrl(InquiryType.SHAHKAR, '/api/compliance-inquiry/compatibility'), { nationalCode, mobileNo }, context, ); @@ -396,7 +405,7 @@ export class TejaratNouProvider implements InquiryProvider { const data = await this.authenticatedRequest>( 'POST', - '/api/central-insurance-amlak-inquiry', + this.configuredUrl(InquiryType.REAL_ESTATE, '/api/central-insurance-amlak-inquiry'), { nationalId: nationalCode, postalCode: Number(postalCode), @@ -422,6 +431,66 @@ export class TejaratNouProvider implements InquiryProvider { + const nationalId = this.getRequiredString( + payload.nationalCode ?? payload.NationalId ?? payload.nationalId, + 'nationalCode', + ); + const shebaId = this.getRequiredString(payload.sheba ?? payload.ShebaId, 'sheba'); + const accountOwnerType = Number(payload.accountOwnerType ?? payload.AccountOwnerType ?? 1); + + return this.withResilience( + async () => { + const data = await this.authenticatedRequest>( + 'POST', + this.configuredUrl(InquiryType.SHEBA, '/api/central-insurance-sheba-inquiry'), + { + AccountOwnerType: Number.isFinite(accountOwnerType) ? accountOwnerType : 1, + NationalId: nationalId, + ShebaId: shebaId, + }, + context, + ); + + if (data && typeof data === 'object') { + const providerError = getSayahProviderError(data as SayahApiResponse); + if (providerError) { + throw this.createProviderError(providerError.message, providerError.code); + } + } + + return { + raw: { + nationalCode: nationalId, + sheba: shebaId, + ...(typeof data === 'object' && data !== null ? (data as Record) : { data }), + }, + }; + }, + context, + 'sheba inquiry', + ); + } + + private configuredUrl(inquiryType: InquiryType, fallbackPath: string): string { + const configured = this.config.inquiries?.[inquiryType]?.url?.trim(); + return configured ? configured.replace(/\/$/, '') : fallbackPath; + } + + private toGregorianBirthDate(birthDate: string): string { + try { + return jalaliDateToGregorianDate(birthDate); + } catch (error) { + throw this.createProviderError( + error instanceof Error ? error.message : 'birthDate is not a valid Jalali date', + 'VALIDATION_ERROR', + ); + } + } + private async withResilience( fn: () => Promise, context: ProviderExecutionContext, @@ -449,7 +518,7 @@ export class TejaratNouProvider implements InquiryProvider>({ + const response = await this.httpClient.request | string>({ method, url: path, data: method === 'POST' ? body : undefined, @@ -460,16 +529,18 @@ export class TejaratNouProvider implements InquiryProvider= 400)) { - throw this.createProviderError( - envelope.message ?? 'TejaratNou inquiry failed', - String(envelope.statusCode ?? 'PROVIDER_ERROR'), - ); - } + const envelope = this.parseGatewayBody(response.data); + if (this.isGatewayEnvelope(envelope)) { + if (envelope.isSuccess === false || (envelope.statusCode && envelope.statusCode >= 400)) { + throw this.createProviderError( + envelope.message ?? 'TejaratNou inquiry failed', + String(envelope.statusCode ?? 'PROVIDER_ERROR'), + ); + } - if (envelope?.data !== undefined) { - return envelope.data; + if (envelope.data !== undefined) { + return envelope.data as T; + } } return envelope as T; @@ -489,6 +560,27 @@ export class TejaratNouProvider implements InquiryProvider, ): { message: string; code: string } | null { @@ -561,9 +653,13 @@ export class TejaratNouProvider implements InquiryProvider>; } diff --git a/src/providers/providers.module.ts b/src/providers/providers.module.ts index 31d0c61..9a3b3f8 100644 --- a/src/providers/providers.module.ts +++ b/src/providers/providers.module.ts @@ -1,5 +1,5 @@ import { Module } from '@nestjs/common'; -import { MongooseModule } from '@nestjs/mongoose'; +import { TypeOrmModule } from '@nestjs/typeorm'; import { ProviderFactory } from './factory/provider.factory'; import { HamtaProvider } from './implementations/hamta.provider'; import { MoallemProvider } from './implementations/moallem.provider'; @@ -8,28 +8,21 @@ import { TejaratNouProvider } from './implementations/tejaratnou.provider'; import { AmitisProvider } from './implementations/amitis.provider'; import { ProviderOrchestratorService } from './strategy/provider-orchestrator.service'; import { ProviderIsolationService } from './strategy/provider-isolation.service'; -import { GeneralToken, GeneralTokenSchema } from './schemas/general-token.schema'; -import { - InquiryResultCache, - InquiryResultCacheSchema, -} from './schemas/inquiry-result-cache.schema'; +import { GeneralToken } from './schemas/general-token.schema'; +import { InquiryResultCache } from './schemas/inquiry-result-cache.schema'; import { CentInsurCarPolicyClient } from './shared/centinsur-car-policy.client'; import { CentInsurCarProviderSupport } from './shared/centinsur-car-provider.support'; import { GeneralTokenService } from './services/general-token.service'; import { InquiryResultCacheService } from './services/inquiry-result-cache.service'; import { DistributedLockService } from './services/distributed-lock.service'; -import { DistributedLock, DistributedLockSchema } from './schemas/distributed-lock.schema'; +import { DistributedLock } from './schemas/distributed-lock.schema'; /** * Provider adapters, factory, and orchestration strategy. */ @Module({ imports: [ - MongooseModule.forFeature([ - { name: GeneralToken.name, schema: GeneralTokenSchema }, - { name: InquiryResultCache.name, schema: InquiryResultCacheSchema }, - { name: DistributedLock.name, schema: DistributedLockSchema }, - ]), + TypeOrmModule.forFeature([GeneralToken, InquiryResultCache, DistributedLock]), ], providers: [ HamtaProvider, diff --git a/src/providers/schemas/distributed-lock.schema.ts b/src/providers/schemas/distributed-lock.schema.ts index 083be73..fbbdac7 100644 --- a/src/providers/schemas/distributed-lock.schema.ts +++ b/src/providers/schemas/distributed-lock.schema.ts @@ -1,21 +1,27 @@ -import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; -import { HydratedDocument } from 'mongoose'; +import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn, UpdateDateColumn } from 'typeorm'; -export type DistributedLockDocument = HydratedDocument; - -@Schema({ timestamps: true, collection: 'distributed_locks' }) +@Entity('distributed_locks') export class DistributedLock { - @Prop({ required: true, unique: true, index: true }) + @PrimaryGeneratedColumn('uuid') + id!: string; + + @Index({ unique: true }) + @Column({ type: 'text' }) lockKey!: string; - @Prop({ required: true }) + @Column({ type: 'text' }) ownerId!: string; - @Prop({ required: true, index: true }) + @Index() + @Column({ type: 'timestamptz' }) leaseUntil!: Date; - @Prop({ required: true, default: 0 }) + @Column({ type: 'int', default: 0 }) fencingToken!: number; -} -export const DistributedLockSchema = SchemaFactory.createForClass(DistributedLock); + @CreateDateColumn({ type: 'timestamptz' }) + createdAt!: Date; + + @UpdateDateColumn({ type: 'timestamptz' }) + updatedAt!: Date; +} diff --git a/src/providers/schemas/general-token.schema.ts b/src/providers/schemas/general-token.schema.ts index 2c0e3c2..1cce970 100644 --- a/src/providers/schemas/general-token.schema.ts +++ b/src/providers/schemas/general-token.schema.ts @@ -1,44 +1,44 @@ -import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; -import { HydratedDocument } from 'mongoose'; - -export type GeneralTokenDocument = HydratedDocument; +import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn } from 'typeorm'; /** OAuth tokens for outbound provider APIs — credentials stay in env, not stored here. */ -@Schema({ timestamps: { createdAt: true, updatedAt: false }, collection: 'general_tokens' }) +@Entity('general_tokens') +@Index(['serviceProvider', 'createdAt']) export class GeneralToken { - @Prop({ required: true, index: true }) + @PrimaryGeneratedColumn('uuid') + id!: string; + + @Index() + @Column({ type: 'text' }) serviceProvider!: string; - @Prop({ required: true }) + @Column({ type: 'text' }) tokenType!: string; - @Prop({ required: true }) + @Column({ type: 'text' }) url!: string; - @Prop({ required: true }) + @Column({ type: 'text' }) clientId!: string; - @Prop({ required: true }) + @Column({ type: 'text' }) username!: string; - @Prop({ required: true }) + @Column({ type: 'text' }) scope!: string; - @Prop({ required: true }) + @Column({ type: 'text' }) accessToken!: string; - @Prop() - refreshToken?: string; + @Column({ type: 'text', nullable: true }) + refreshToken?: string | null; - @Prop({ required: true }) + @Column({ type: 'int' }) expiresIn!: number; - @Prop({ required: true, index: true }) + @Index() + @Column({ type: 'timestamptz' }) expiresAt!: Date; - createdAt?: Date; + @CreateDateColumn({ type: 'timestamptz' }) + createdAt!: Date; } - -export const GeneralTokenSchema = SchemaFactory.createForClass(GeneralToken); - -GeneralTokenSchema.index({ serviceProvider: 1, createdAt: -1 }); diff --git a/src/providers/schemas/inquiry-result-cache.schema.ts b/src/providers/schemas/inquiry-result-cache.schema.ts index b6cf762..956b242 100644 --- a/src/providers/schemas/inquiry-result-cache.schema.ts +++ b/src/providers/schemas/inquiry-result-cache.schema.ts @@ -1,36 +1,36 @@ -import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; -import { HydratedDocument, Schema as MongooseSchema } from 'mongoose'; +import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn } from 'typeorm'; import { InquiryType } from '../../common/enums/inquiry-type.enum'; import { ProviderName } from '../../common/enums/provider-name.enum'; -export type InquiryResultCacheDocument = HydratedDocument; - /** - * Domain-level inquiry result cache — one collection for all inquiry types. + * Domain-level inquiry result cache — one table for all inquiry types. * * Separate from inquiry_logs (operational audit per request) because: * - Cache keys are inquiry-specific (nationalCode+birthDate, plate number, etc.) * - Data is immutable for most inquiries (civil registration identity) * - Retention and query patterns differ from audit trails */ -@Schema({ timestamps: { createdAt: true, updatedAt: false }, collection: 'inquiry_result_cache' }) +@Entity('inquiry_result_cache') +@Index(['inquiryType', 'cacheKey'], { unique: true }) export class InquiryResultCache { - @Prop({ required: true, enum: InquiryType, index: true }) + @PrimaryGeneratedColumn('uuid') + id!: string; + + @Index() + @Column({ type: 'text' }) inquiryType!: InquiryType; /** Stable lookup key, e.g. "0012345678|1378-11-24" for person inquiry. */ - @Prop({ required: true, index: true }) + @Index() + @Column({ type: 'text' }) cacheKey!: string; - @Prop({ required: true, enum: ProviderName }) + @Column({ type: 'text' }) provider!: ProviderName; - @Prop({ type: MongooseSchema.Types.Mixed, required: true }) + @Column({ type: 'jsonb' }) data!: Record; - createdAt?: Date; + @CreateDateColumn({ type: 'timestamptz' }) + createdAt!: Date; } - -export const InquiryResultCacheSchema = SchemaFactory.createForClass(InquiryResultCache); - -InquiryResultCacheSchema.index({ inquiryType: 1, cacheKey: 1 }, { unique: true }); diff --git a/src/providers/services/distributed-lock.service.ts b/src/providers/services/distributed-lock.service.ts index 4f30136..149ee0f 100644 --- a/src/providers/services/distributed-lock.service.ts +++ b/src/providers/services/distributed-lock.service.ts @@ -1,11 +1,8 @@ import { randomUUID } from 'node:crypto'; import { Injectable } from '@nestjs/common'; -import { InjectModel } from '@nestjs/mongoose'; -import { Model } from 'mongoose'; -import { - DistributedLock, - DistributedLockDocument, -} from '../schemas/distributed-lock.schema'; +import { InjectRepository } from '@nestjs/typeorm'; +import { Repository } from 'typeorm'; +import { DistributedLock } from '../schemas/distributed-lock.schema'; export interface LockOptions { leaseMs?: number; @@ -25,8 +22,8 @@ const DEFAULT_WAIT_MS = 10_000; @Injectable() export class DistributedLockService { constructor( - @InjectModel(DistributedLock.name) - private readonly lockModel: Model, + @InjectRepository(DistributedLock) + private readonly locks: Repository, ) {} async acquire( @@ -35,44 +32,36 @@ export class DistributedLockService { leaseMs = DEFAULT_LEASE_MS, ): Promise { const now = new Date(); - try { - const lock = await this.lockModel - .findOneAndUpdate( - { - lockKey, - $or: [{ leaseUntil: { $lte: now } }, { leaseUntil: { $exists: false } }], - }, - { - $set: { - lockKey, - ownerId, - leaseUntil: new Date(now.getTime() + leaseMs), - }, - $inc: { fencingToken: 1 }, - }, - { new: true, upsert: true, setDefaultsOnInsert: true }, - ) - .exec(); + const leaseUntil = new Date(now.getTime() + leaseMs); + const rows = await this.locks.query>( + `INSERT INTO distributed_locks (lock_key, owner_id, lease_until, fencing_token) + VALUES ($1, $2, $3, 1) + ON CONFLICT (lock_key) DO UPDATE + SET owner_id = EXCLUDED.owner_id, + lease_until = EXCLUDED.lease_until, + fencing_token = distributed_locks.fencing_token + 1, + updated_at = now() + WHERE distributed_locks.lease_until <= $4 + RETURNING lock_key AS "lockKey", owner_id AS "ownerId", fencing_token AS "fencingToken"`, + [lockKey, ownerId, leaseUntil, now], + ); - if (!lock || lock.ownerId !== ownerId) return null; - return { - lockKey, - ownerId, - fencingToken: lock.fencingToken, - }; - } catch (error) { - if (this.isDuplicateKey(error)) return null; - throw error; - } + const lock = rows[0]; + if (!lock || lock.ownerId !== ownerId) return null; + return { + lockKey: lock.lockKey, + ownerId: lock.ownerId, + fencingToken: Number(lock.fencingToken), + }; } async release(lease: LockLease): Promise { - await this.lockModel - .updateOne( - { lockKey: lease.lockKey, ownerId: lease.ownerId }, - { $set: { leaseUntil: new Date(0) } }, - ) - .exec(); + await this.locks.query( + `UPDATE distributed_locks + SET lease_until = $3, updated_at = now() + WHERE lock_key = $1 AND owner_id = $2`, + [lease.lockKey, lease.ownerId, new Date(0)], + ); } async withLock( @@ -132,13 +121,4 @@ export class DistributedLockService { (error as NodeJS.ErrnoException).code = 'ECANCELED'; return error; } - - private isDuplicateKey(error: unknown): boolean { - return Boolean( - error && - typeof error === 'object' && - 'code' in error && - (error as { code?: number }).code === 11000, - ); - } } diff --git a/src/providers/services/general-token.service.ts b/src/providers/services/general-token.service.ts index d7a66d0..6fd9c4d 100644 --- a/src/providers/services/general-token.service.ts +++ b/src/providers/services/general-token.service.ts @@ -1,7 +1,7 @@ import { Injectable, Logger } from '@nestjs/common'; +import { InjectRepository } from '@nestjs/typeorm'; import axios from 'axios'; -import { InjectModel } from '@nestjs/mongoose'; -import { Model } from 'mongoose'; +import { Repository } from 'typeorm'; import { mergeOutboundAxiosConfig } from '../../common/helpers/http-client.helper'; import { AUTH_MAX_ATTEMPTS, @@ -9,7 +9,7 @@ import { isAuthTransportRetryable, } from '../../common/helpers/provider-resilience.helper'; import { withRetry } from '../../common/helpers/retry.helper'; -import { GeneralToken, GeneralTokenDocument } from '../schemas/general-token.schema'; +import { GeneralToken } from '../schemas/general-token.schema'; import { TejaratNouConfig } from '../interfaces/tejaratnou-config.interface'; import { DistributedLockService } from './distributed-lock.service'; @@ -28,17 +28,20 @@ export class GeneralTokenService { private readonly logger = new Logger(GeneralTokenService.name); constructor( - @InjectModel(GeneralToken.name) - private readonly generalTokenModel: Model, + @InjectRepository(GeneralToken) + private readonly generalTokens: Repository, private readonly distributedLockService: DistributedLockService, ) {} - async getLatestToken(serviceProvider: string): Promise { - return this.generalTokenModel.findOne({ serviceProvider }).sort({ createdAt: -1 }).exec(); + async getLatestToken(serviceProvider: string): Promise { + return this.generalTokens.findOne({ + where: { serviceProvider }, + order: { createdAt: 'DESC' }, + }); } async isTokenExpired( - token: GeneralTokenDocument, + token: GeneralToken, bufferSeconds = TOKEN_EXPIRY_BUFFER_SECONDS, ): Promise { if (!token.expiresAt) return true; @@ -47,7 +50,7 @@ export class GeneralTokenService { } /** - * Returns a valid access token — reuses MongoDB-stored token when not expired, + * Returns a valid access token — reuses the stored token when not expired, * otherwise fetches a new one via the supplied OAuth fetcher. */ async getValidAccessToken( @@ -62,7 +65,7 @@ export class GeneralTokenService { ): Promise { const latest = await this.getLatestToken(serviceProvider); if (latest && !(await this.isTokenExpired(latest))) { - this.logger.debug(`Reusing ${serviceProvider} token ${latest._id}`); + this.logger.debug(`Reusing ${serviceProvider} token ${latest.id}`); return latest.accessToken; } @@ -77,7 +80,7 @@ export class GeneralTokenService { const fresh = await fetchNewToken(signal); const expiresAt = new Date(Date.now() + fresh.expiresIn * 1000); - await this.generalTokenModel.create({ + await this.generalTokens.save(this.generalTokens.create({ serviceProvider, tokenType: fresh.tokenType, url: persistContext.url, @@ -87,7 +90,7 @@ export class GeneralTokenService { accessToken: fresh.accessToken, expiresIn: fresh.expiresIn, expiresAt, - }); + })); this.logger.log(`Stored new ${serviceProvider} token, expires at ${expiresAt.toISOString()}`); return fresh.accessToken; @@ -108,8 +111,8 @@ export class GeneralTokenService { refreshToken?: string; expiresIn: number; expiresAt: Date; - }): Promise { - return this.generalTokenModel.create(data); + }): Promise { + return this.generalTokens.save(this.generalTokens.create(data)); } /** OAuth2 password grant for Tejarat No identity gateway. */ diff --git a/src/providers/services/inquiry-result-cache.service.ts b/src/providers/services/inquiry-result-cache.service.ts index ec0688b..4e8be7a 100644 --- a/src/providers/services/inquiry-result-cache.service.ts +++ b/src/providers/services/inquiry-result-cache.service.ts @@ -1,12 +1,9 @@ import { Injectable } from '@nestjs/common'; -import { InjectModel } from '@nestjs/mongoose'; -import { Model } from 'mongoose'; +import { InjectRepository } from '@nestjs/typeorm'; +import { Repository } from 'typeorm'; import { InquiryType } from '../../common/enums/inquiry-type.enum'; import { ProviderName } from '../../common/enums/provider-name.enum'; -import { - InquiryResultCache, - InquiryResultCacheDocument, -} from '../schemas/inquiry-result-cache.schema'; +import { InquiryResultCache } from '../schemas/inquiry-result-cache.schema'; export interface PersonInquiryCacheData { nationalCode: string; @@ -30,8 +27,8 @@ export interface PersonInquiryCacheData { @Injectable() export class InquiryResultCacheService { constructor( - @InjectModel(InquiryResultCache.name) - private readonly cacheModel: Model, + @InjectRepository(InquiryResultCache) + private readonly cache: Repository, ) {} static personCacheKey(nationalCode: string, birthDate: string): string { @@ -42,44 +39,25 @@ export class InquiryResultCacheService { nationalCode: string, birthDate: string, ): Promise { - const entry = await this.cacheModel - .findOne({ - inquiryType: InquiryType.PERSON, - cacheKey: InquiryResultCacheService.personCacheKey(nationalCode, birthDate), - }) - .exec(); - - if (!entry) return null; - return entry.data as unknown as PersonInquiryCacheData; + const data = await this.find( + InquiryType.PERSON, + InquiryResultCacheService.personCacheKey(nationalCode, birthDate), + ); + return data as PersonInquiryCacheData | null; } - async savePersonInquiry( - provider: ProviderName, - data: PersonInquiryCacheData, - ): Promise { - await this.cacheModel.updateOne( - { - inquiryType: InquiryType.PERSON, - cacheKey: InquiryResultCacheService.personCacheKey(data.nationalCode, data.birthDate), - }, - { - $set: { - inquiryType: InquiryType.PERSON, - cacheKey: InquiryResultCacheService.personCacheKey(data.nationalCode, data.birthDate), - provider, - data, - }, - }, - { upsert: true }, + async savePersonInquiry(provider: ProviderName, data: PersonInquiryCacheData): Promise { + await this.save( + InquiryType.PERSON, + InquiryResultCacheService.personCacheKey(data.nationalCode, data.birthDate), + provider, + data as unknown as Record, ); } /** Generic cache read for future inquiry types. */ - async find( - inquiryType: InquiryType, - cacheKey: string, - ): Promise | null> { - const entry = await this.cacheModel.findOne({ inquiryType, cacheKey }).exec(); + async find(inquiryType: InquiryType, cacheKey: string): Promise | null> { + const entry = await this.cache.findOne({ where: { inquiryType, cacheKey } }); return entry?.data ?? null; } @@ -89,10 +67,13 @@ export class InquiryResultCacheService { provider: ProviderName, data: Record, ): Promise { - await this.cacheModel.updateOne( - { inquiryType, cacheKey }, - { $set: { inquiryType, cacheKey, provider, data } }, - { upsert: true }, + await this.cache.query( + `INSERT INTO inquiry_result_cache (inquiry_type, cache_key, provider, data) + VALUES ($1, $2, $3, $4::jsonb) + ON CONFLICT (inquiry_type, cache_key) DO UPDATE + SET provider = EXCLUDED.provider, + data = EXCLUDED.data`, + [inquiryType, cacheKey, provider, JSON.stringify(data)], ); } } diff --git a/src/public/app.js b/src/public/app.js index bfbf9f4..54feca8 100644 --- a/src/public/app.js +++ b/src/public/app.js @@ -783,7 +783,7 @@ } } async function clearInquiryLogs() { - if (!window.confirm('Delete every inquiry log from MongoDB? This cannot be undone.')) return; + if (!window.confirm('Delete every inquiry log from the database? This cannot be undone.')) return; try { const result = await request('/inquiry-logs', { method: 'DELETE' }); $('logsBody').replaceChildren(); $('logOutput').textContent = 'Inquiry logs were cleared.'; diff --git a/src/users/mappers/user.mapper.ts b/src/users/mappers/user.mapper.ts index b595999..b752945 100644 --- a/src/users/mappers/user.mapper.ts +++ b/src/users/mappers/user.mapper.ts @@ -1,16 +1,16 @@ -import { UserDocument } from '../schemas/user.schema'; +import { User } from '../schemas/user.schema'; import { ProfileDto } from '../../auth/dto/profile.dto'; import { UserResponseDto } from '../dto/user-response.dto'; -/** Maps Mongoose user documents to API DTOs (never exposes password/hash fields). */ +/** Maps user rows to API DTOs (never exposes password or token fields). */ export class UserMapper { - static toProfileDto(user: UserDocument): ProfileDto { + static toProfileDto(user: User): ProfileDto { return { - id: user._id.toString(), + id: user.id, fullName: user.fullName, username: user.username, email: user.email, - mobile: user.mobile, + mobile: user.mobile ?? undefined, role: user.role, clientType: user.clientType, appName: user.appName, @@ -21,14 +21,14 @@ export class UserMapper { requestLimitPerMinute: user.requestLimitPerMinute, requestLimitPerDay: user.requestLimitPerDay, totalRequests: user.totalRequests, - lastLoginAt: user.lastLoginAt, - passwordChangedAt: user.passwordChangedAt, + lastLoginAt: user.lastLoginAt ?? undefined, + passwordChangedAt: user.passwordChangedAt ?? undefined, createdAt: user.createdAt, updatedAt: user.updatedAt, }; } - static toResponseDto(user: UserDocument): UserResponseDto { + static toResponseDto(user: User): UserResponseDto { return UserMapper.toProfileDto(user); } } diff --git a/src/users/schemas/user.schema.ts b/src/users/schemas/user.schema.ts index b7d3af2..09ef860 100644 --- a/src/users/schemas/user.schema.ts +++ b/src/users/schemas/user.schema.ts @@ -1,85 +1,89 @@ -import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; -import { HydratedDocument, Types } from 'mongoose'; +import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn, UpdateDateColumn } from 'typeorm'; import { ClientType } from '../../common/enums/client-type.enum'; import { Role } from '../../common/enums/role.enum'; -export type UserDocument = HydratedDocument; - /** - * Unified user model — internal admins and external API clients share one collection. + * Unified user model — internal admins and external API clients share one table. * Designed for future extensions: API keys, HMAC, IP whitelist, permissions, multi-tenant. */ -@Schema({ timestamps: true, collection: 'users' }) +@Entity('users') +@Index(['role', 'isActive']) +@Index(['clientType', 'appName']) export class User { - @Prop({ required: true, trim: true }) + @PrimaryGeneratedColumn('uuid') + id!: string; + + @Column({ type: 'text' }) fullName!: string; - @Prop({ required: true, unique: true, lowercase: true, trim: true, index: true }) + @Index({ unique: true }) + @Column({ type: 'text' }) username!: string; - @Prop({ required: true, unique: true, lowercase: true, trim: true, index: true }) + @Index({ unique: true }) + @Column({ type: 'text' }) email!: string; - @Prop({ trim: true }) - mobile?: string; + @Column({ type: 'text', nullable: true }) + mobile?: string | null; - @Prop({ required: true, select: false }) + @Column({ type: 'text', select: false }) password!: string; - @Prop({ required: true, enum: Role, default: Role.USER, index: true }) + @Index() + @Column({ type: 'text' }) role!: Role; - @Prop({ required: true, enum: ClientType, default: ClientType.EXTERNAL, index: true }) + @Index() + @Column({ type: 'text' }) clientType!: ClientType; - @Prop({ trim: true, default: '' }) + @Column({ type: 'text', default: '' }) appName!: string; - @Prop({ trim: true, default: '' }) + @Column({ type: 'text', default: '' }) clientName!: string; - @Prop({ default: true }) + @Column({ type: 'boolean', default: true }) isActive!: boolean; - @Prop({ default: false }) + @Column({ type: 'boolean', default: false }) isBlocked!: boolean; /** Future: machine-to-machine auth without JWT. */ - @Prop({ select: false }) - apiKey?: string; + @Column({ type: 'text', nullable: true, select: false }) + apiKey?: string | null; - @Prop({ type: [String], default: [] }) + @Column({ type: 'text', array: true, default: () => "'{}'" }) allowedInquiries!: string[]; - @Prop({ default: 60 }) + @Column({ type: 'int', default: 60 }) requestLimitPerMinute!: number; - @Prop({ default: 10000 }) + @Column({ type: 'int', default: 10000 }) requestLimitPerDay!: number; - @Prop({ default: 0 }) + @Column({ type: 'int', default: 0 }) totalRequests!: number; - @Prop() - lastLoginAt?: Date; + @Column({ type: 'timestamptz', nullable: true }) + lastLoginAt?: Date | null; - @Prop() - passwordChangedAt?: Date; + @Column({ type: 'timestamptz', nullable: true }) + passwordChangedAt?: Date | null; - @Prop({ type: Types.ObjectId, ref: 'User' }) - createdBy?: Types.ObjectId; + @Column({ type: 'uuid', nullable: true }) + createdBy?: string | null; - @Prop({ select: false }) - refreshToken?: string; + @Column({ type: 'text', nullable: true, select: false }) + refreshToken?: string | null; - @Prop({ type: Object, default: {} }) + @Column({ type: 'jsonb', default: () => "'{}'::jsonb" }) metadata!: Record; + @CreateDateColumn({ type: 'timestamptz' }) createdAt!: Date; + + @UpdateDateColumn({ type: 'timestamptz' }) updatedAt!: Date; } - -export const UserSchema = SchemaFactory.createForClass(User); - -UserSchema.index({ role: 1, isActive: 1 }); -UserSchema.index({ clientType: 1, appName: 1 }); diff --git a/src/users/users.module.ts b/src/users/users.module.ts index 1bac8cb..89ca215 100644 --- a/src/users/users.module.ts +++ b/src/users/users.module.ts @@ -1,17 +1,14 @@ import { Module, forwardRef } from '@nestjs/common'; -import { MongooseModule } from '@nestjs/mongoose'; +import { TypeOrmModule } from '@nestjs/typeorm'; import { AuthModule } from '../auth/auth.module'; -import { User, UserSchema } from './schemas/user.schema'; +import { User } from './schemas/user.schema'; import { UsersController } from './users.controller'; import { UsersService } from './users.service'; @Module({ - imports: [ - MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]), - forwardRef(() => AuthModule), - ], + imports: [TypeOrmModule.forFeature([User]), forwardRef(() => AuthModule)], controllers: [UsersController], providers: [UsersService], - exports: [UsersService, MongooseModule], + exports: [UsersService], }) export class UsersModule {} diff --git a/src/users/users.service.ts b/src/users/users.service.ts index 65e0dfe..ec7dc55 100644 --- a/src/users/users.service.ts +++ b/src/users/users.service.ts @@ -1,11 +1,11 @@ -import { - Injectable, -} from '@nestjs/common'; -import { InjectModel } from '@nestjs/mongoose'; -import { Model, Types } from 'mongoose'; +import { Injectable } from '@nestjs/common'; +import { InjectRepository } from '@nestjs/typeorm'; import { randomBytes } from 'crypto'; +import { Not, QueryDeepPartialEntity, Repository } from 'typeorm'; import { AuditEvent } from '../common/enums/audit-event.enum'; import { ADMIN_ROLES, Role } from '../common/enums/role.enum'; +import { AppException } from '../common/exceptions/app-exception'; +import { isUniqueViolation, isUuid } from '../database/postgres.helpers'; import { AuditService } from '../audit/audit.service'; import { PasswordService } from '../auth/services/password.service'; import { AuthenticatedUser } from '../auth/interfaces/authenticated-user.interface'; @@ -13,9 +13,8 @@ import { CreateUserDto } from './dto/create-user.dto'; import { ResetPasswordDto } from './dto/reset-password.dto'; import { UpdateUserDto } from './dto/update-user.dto'; import { UserMapper } from './mappers/user.mapper'; -import { User, UserDocument } from './schemas/user.schema'; +import { User } from './schemas/user.schema'; import { UserResponseDto } from './dto/user-response.dto'; -import { AppException } from '../common/exceptions/app-exception'; export interface RequestContext { ip?: string; @@ -25,30 +24,35 @@ export interface RequestContext { @Injectable() export class UsersService { constructor( - @InjectModel(User.name) private readonly userModel: Model, + @InjectRepository(User) private readonly users: Repository, private readonly passwordService: PasswordService, private readonly auditService: AuditService, ) {} - async findById(id: string): Promise { - const user = await this.userModel.findById(id); + async findById(id: string): Promise { + if (!isUuid(id)) { + throw new AppException('USER_NOT_FOUND'); + } + const user = await this.users.findOne({ where: { id } }); if (!user) { throw new AppException('USER_NOT_FOUND'); } return user; } - async findByUsername(username: string, includePassword = false): Promise { - const query = this.userModel.findOne({ username: username.toLowerCase().trim() }); + async findByUsername(username: string, includePassword = false): Promise { + const query = this.users + .createQueryBuilder('user') + .where('user.username = :username', { username: username.toLowerCase().trim() }); if (includePassword) { - query.select('+password +refreshToken'); + query.addSelect('user.password').addSelect('user.refreshToken'); } - return query.exec(); + return query.getOne(); } async findAll(): Promise { - const users = await this.userModel.find().sort({ createdAt: -1 }); - return users.map((u) => UserMapper.toResponseDto(u)); + const users = await this.users.find({ order: { createdAt: 'DESC' } }); + return users.map((user) => UserMapper.toResponseDto(user)); } async create( @@ -61,9 +65,7 @@ export class UsersService { const username = dto.username.toLowerCase().trim(); const email = dto.email.toLowerCase().trim(); - const existing = await this.userModel.findOne({ - $or: [{ username }, { email }], - }); + const existing = await this.users.findOne({ where: [{ username }, { email }] }); if (existing) { throw new AppException('USERNAME_OR_EMAIL_EXISTS'); } @@ -71,29 +73,39 @@ export class UsersService { const passwordHash = await this.passwordService.hash(dto.password); const apiKey = this.generateApiKey(); - const user = await this.userModel.create({ - fullName: dto.fullName, - username, - email, - mobile: dto.mobile, - password: passwordHash, - role: dto.role, - clientType: dto.clientType, - appName: dto.appName ?? '', - clientName: dto.clientName ?? '', - isActive: dto.isActive ?? true, - allowedInquiries: dto.allowedInquiries ?? [], - requestLimitPerMinute: dto.requestLimitPerMinute ?? 60, - requestLimitPerDay: dto.requestLimitPerDay ?? 10000, - apiKey, - passwordChangedAt: new Date(), - createdBy: new Types.ObjectId(actor.id), - metadata: dto.metadata ?? {}, - }); + let user: User; + try { + user = await this.users.save( + this.users.create({ + fullName: dto.fullName, + username, + email, + mobile: dto.mobile, + password: passwordHash, + role: dto.role, + clientType: dto.clientType, + appName: dto.appName ?? '', + clientName: dto.clientName ?? '', + isActive: dto.isActive ?? true, + allowedInquiries: dto.allowedInquiries ?? [], + requestLimitPerMinute: dto.requestLimitPerMinute ?? 60, + requestLimitPerDay: dto.requestLimitPerDay ?? 10000, + apiKey, + passwordChangedAt: new Date(), + createdBy: isUuid(actor.id) ? actor.id : null, + metadata: dto.metadata ?? {}, + }), + ); + } catch (error) { + if (isUniqueViolation(error)) { + throw new AppException('USERNAME_OR_EMAIL_EXISTS'); + } + throw error; + } await this.auditService.log(AuditEvent.USER_CREATED, { actorId: actor.id, - userId: user._id.toString(), + userId: user.id, username: user.username, ip: context.ip, userAgent: context.userAgent, @@ -110,33 +122,36 @@ export class UsersService { this.assertCanAssignRole(actor.role, dto.role); } + const changes: Partial = {}; + if (dto.email) { const email = dto.email.toLowerCase().trim(); - const conflict = await this.userModel.findOne({ email, _id: { $ne: id } }); + const conflict = await this.users.findOne({ where: { email, id: Not(id) } }); if (conflict) { throw new AppException('EMAIL_ALREADY_IN_USE'); } - user.email = email; + changes.email = email; } - Object.assign(user, { - ...(dto.fullName !== undefined && { fullName: dto.fullName }), - ...(dto.mobile !== undefined && { mobile: dto.mobile }), - ...(dto.role !== undefined && { role: dto.role }), - ...(dto.clientType !== undefined && { clientType: dto.clientType }), - ...(dto.appName !== undefined && { appName: dto.appName }), - ...(dto.clientName !== undefined && { clientName: dto.clientName }), - ...(dto.isActive !== undefined && { isActive: dto.isActive }), - ...(dto.allowedInquiries !== undefined && { allowedInquiries: dto.allowedInquiries }), - ...(dto.requestLimitPerMinute !== undefined && { - requestLimitPerMinute: dto.requestLimitPerMinute, - }), - ...(dto.requestLimitPerDay !== undefined && { requestLimitPerDay: dto.requestLimitPerDay }), - ...(dto.metadata !== undefined && { metadata: dto.metadata }), - }); + if (dto.fullName !== undefined) changes.fullName = dto.fullName; + if (dto.mobile !== undefined) changes.mobile = dto.mobile; + if (dto.role !== undefined) changes.role = dto.role; + if (dto.clientType !== undefined) changes.clientType = dto.clientType; + if (dto.appName !== undefined) changes.appName = dto.appName; + if (dto.clientName !== undefined) changes.clientName = dto.clientName; + if (dto.isActive !== undefined) changes.isActive = dto.isActive; + if (dto.allowedInquiries !== undefined) changes.allowedInquiries = dto.allowedInquiries; + if (dto.requestLimitPerMinute !== undefined) { + changes.requestLimitPerMinute = dto.requestLimitPerMinute; + } + if (dto.requestLimitPerDay !== undefined) changes.requestLimitPerDay = dto.requestLimitPerDay; + if (dto.metadata !== undefined) changes.metadata = dto.metadata; - await user.save(); - return UserMapper.toResponseDto(user); + if (Object.keys(changes).length > 0) { + await this.users.update(user.id, changes as QueryDeepPartialEntity); + } + + return UserMapper.toResponseDto(await this.findById(id)); } async block( @@ -145,12 +160,10 @@ export class UsersService { context: RequestContext = {}, ): Promise { const user = await this.findById(id); - if (user._id.toString() === actor.id) { + if (user.id === actor.id) { throw new AppException('CANNOT_BLOCK_SELF'); } - user.isBlocked = true; - user.refreshToken = undefined; - await user.save(); + await this.users.update(user.id, { isBlocked: true, refreshToken: null }); await this.auditService.log(AuditEvent.USER_BLOCKED, { actorId: actor.id, @@ -160,7 +173,7 @@ export class UsersService { userAgent: context.userAgent, }); - return UserMapper.toResponseDto(user); + return UserMapper.toResponseDto(await this.findById(id)); } async unblock( @@ -169,8 +182,7 @@ export class UsersService { context: RequestContext = {}, ): Promise { const user = await this.findById(id); - user.isBlocked = false; - await user.save(); + await this.users.update(user.id, { isBlocked: false }); await this.auditService.log(AuditEvent.USER_UNBLOCKED, { actorId: actor.id, @@ -180,7 +192,7 @@ export class UsersService { userAgent: context.userAgent, }); - return UserMapper.toResponseDto(user); + return UserMapper.toResponseDto(await this.findById(id)); } async resetPassword( @@ -189,15 +201,12 @@ export class UsersService { actor: AuthenticatedUser, context: RequestContext = {}, ): Promise { - const user = await this.userModel.findById(id).select('+password +refreshToken'); - if (!user) { - throw new AppException('USER_NOT_FOUND'); - } - - user.password = await this.passwordService.hash(dto.newPassword); - user.passwordChangedAt = new Date(); - user.refreshToken = undefined; - await user.save(); + const user = await this.findById(id); + await this.users.update(user.id, { + password: await this.passwordService.hash(dto.newPassword), + passwordChangedAt: new Date(), + refreshToken: null, + }); await this.auditService.log(AuditEvent.PASSWORD_RESET, { actorId: actor.id, @@ -209,16 +218,23 @@ export class UsersService { } async saveRefreshToken(userId: string, refreshToken: string): Promise { + if (!isUuid(userId)) return; const hash = await this.passwordService.hash(refreshToken); - await this.userModel.findByIdAndUpdate(userId, { refreshToken: hash }); + await this.users.update(userId, { refreshToken: hash }); } async clearRefreshToken(userId: string): Promise { - await this.userModel.findByIdAndUpdate(userId, { $unset: { refreshToken: 1 } }); + if (!isUuid(userId)) return; + await this.users.update(userId, { refreshToken: null }); } async validateRefreshToken(userId: string, refreshToken: string): Promise { - const user = await this.userModel.findById(userId).select('+refreshToken'); + if (!isUuid(userId)) return false; + const user = await this.users + .createQueryBuilder('user') + .addSelect('user.refreshToken') + .where('user.id = :userId', { userId }) + .getOne(); if (!user?.refreshToken) { return false; } @@ -226,11 +242,13 @@ export class UsersService { } async recordLogin(userId: string): Promise { - await this.userModel.findByIdAndUpdate(userId, { lastLoginAt: new Date() }); + if (!isUuid(userId)) return; + await this.users.update(userId, { lastLoginAt: new Date() }); } async incrementTotalRequests(userId: string): Promise { - await this.userModel.findByIdAndUpdate(userId, { $inc: { totalRequests: 1 } }); + if (!isUuid(userId)) return; + await this.users.increment({ id: userId }, 'totalRequests', 1); } private assertCanAssignRole(actorRole: Role, targetRole: Role): void { diff --git a/test/unit/helpers-and-mappers.spec.ts b/test/unit/helpers-and-mappers.spec.ts index d42f9b1..4b7ce0a 100644 --- a/test/unit/helpers-and-mappers.spec.ts +++ b/test/unit/helpers-and-mappers.spec.ts @@ -81,7 +81,7 @@ describe('unit helpers and mappers', () => { it('maps user documents without leaking secrets', () => { const dto = UserMapper.toResponseDto({ - _id: { toString: () => 'user-1' }, + id: 'user-1', fullName: 'Admin User', username: 'admin', email: 'admin@example.com', diff --git a/test/unit/idempotency.service.spec.ts b/test/unit/idempotency.service.spec.ts index 5966197..683f2e5 100644 --- a/test/unit/idempotency.service.spec.ts +++ b/test/unit/idempotency.service.spec.ts @@ -1,46 +1,42 @@ import { IdempotencyService } from '../../src/idempotency/idempotency.service'; import { IdempotencyRecordStatus } from '../../src/idempotency/schemas/idempotency-record.schema'; -class FakeRecordModel { +class FakeRecordRepository { private readonly records = new Map(); - findOne(filter: { scopeHash: string }) { - return { exec: async () => this.records.get(filter.scopeHash) ?? null }; + create(record: any) { + return { ...record }; } - async create(record: any) { + async findOne(options: { where: { scopeHash: string } }) { + return this.records.get(options.where.scopeHash) ?? null; + } + + async save(record: any) { if (this.records.has(record.scopeHash)) { - throw Object.assign(new Error('duplicate'), { code: 11000 }); + throw Object.assign(new Error('duplicate'), { code: '23505' }); } - const saved = { ...record, _id: record.scopeHash }; + const saved = { ...record, id: record.scopeHash }; this.records.set(record.scopeHash, saved); return saved; } - updateOne(filter: { scopeHash: string; status: IdempotencyRecordStatus }, update: any) { - return { - exec: async () => { - const record = this.records.get(filter.scopeHash); - if (record?.status === filter.status) Object.assign(record, update.$set); - return { acknowledged: true }; - }, - }; + async update(filter: { scopeHash: string; status: IdempotencyRecordStatus }, values: any) { + const record = this.records.get(filter.scopeHash); + if (record?.status === filter.status) Object.assign(record, values); + return { affected: record ? 1 : 0 }; } - deleteOne(filter: { scopeHash: string; status: IdempotencyRecordStatus }) { - return { - exec: async () => { - const record = this.records.get(filter.scopeHash); - if (record?.status === filter.status) this.records.delete(filter.scopeHash); - return { acknowledged: true }; - }, - }; + async delete(filter: { scopeHash: string; status: IdempotencyRecordStatus }) { + const record = this.records.get(filter.scopeHash); + if (record?.status === filter.status) this.records.delete(filter.scopeHash); + return { affected: record ? 1 : 0 }; } } describe('IdempotencyService', () => { it('replays completed responses and rejects body reuse', async () => { - const service = new IdempotencyService(new FakeRecordModel() as never); + const service = new IdempotencyService(new FakeRecordRepository() as never); const input = { key: 'request-1', callerId: 'user-1', @@ -62,7 +58,7 @@ describe('IdempotencyService', () => { }); it('rejects a duplicate while the original request is in progress', async () => { - const service = new IdempotencyService(new FakeRecordModel() as never); + const service = new IdempotencyService(new FakeRecordRepository() as never); const input = { key: 'request-2', callerId: 'user-1', diff --git a/test/unit/tejarat-inquiries.spec.ts b/test/unit/tejarat-inquiries.spec.ts new file mode 100644 index 0000000..b6f9b95 --- /dev/null +++ b/test/unit/tejarat-inquiries.spec.ts @@ -0,0 +1,103 @@ +import { InquiryType } from '../../src/common/enums/inquiry-type.enum'; +import { TejaratNouProvider } from '../../src/providers/implementations/tejaratnou.provider'; + +function createProvider(inquiries?: Record) { + const getTejaratNouAccessToken = jest.fn().mockResolvedValue('tejarat-token'); + const config = { + enabled: true, + timeout: 15000, + maxRetries: 1, + baseUrl: 'https://accounts.tejaratnoins.ir', + inquiryBaseUrl: 'https://gateway.tejaratnoins.ir', + clientId: 'api-gateway', + clientSecret: 'secret', + username: 'user', + password: 'pass', + inquiries, + }; + const provider = new TejaratNouProvider( + { get: () => config } as never, + { getTejaratNouAccessToken } as never, + { + findPersonInquiry: jest.fn().mockResolvedValue(null), + savePersonInquiry: jest.fn().mockResolvedValue(undefined), + } as never, + ); + const request = jest + .spyOn((provider as unknown as { httpClient: { request: jest.Mock } }).httpClient, 'request') + .mockResolvedValue({ + data: { + isSuccess: true, + data: { name: 'Ali', family: 'Ahmadi', nationalCodeString: '0820270725', ReturnValue: true }, + }, + }); + + return { provider, request }; +} + +describe('Tejarat identity, shahkar, real estate, and sheba', () => { + it('posts a Jalali birth year to birthdate-year', async () => { + const { provider, request } = createProvider(); + + await provider.execute( + InquiryType.PERSON, + { nationalCode: '4311402422', birthDate: '1378' }, + { requestId: 'req-year', trackingCode: 'trk-year' }, + ); + + expect(request).toHaveBeenCalledWith( + expect.objectContaining({ + method: 'POST', + url: '/api/identity-inquiry/national-code/4311402422/birthdate-year/1378', + headers: expect.objectContaining({ Authorization: 'Bearer tejarat-token', Accept: 'text/plain' }), + }), + ); + }); + + it('gets a full Jalali birth date as a Gregorian birthdate', async () => { + const { provider, request } = createProvider(); + + await provider.execute( + InquiryType.PERSON, + { nationalCode: '0820270725', birthDate: '1373-10-12' }, + { requestId: 'req-date', trackingCode: 'trk-date' }, + ); + + expect(request).toHaveBeenCalledWith( + expect.objectContaining({ + method: 'GET', + url: '/api/identity-inquiry/national-code/0820270725/birthdate/1995-01-02', + }), + ); + }); + + it('posts sheba with the Tejarat account, national id, and sheba fields', async () => { + const { provider, request } = createProvider({ + [InquiryType.SHEBA]: { + url: 'https://gateway.tejaratnoins.ir/api/central-insurance-sheba-inquiry', + }, + }); + + await provider.execute( + InquiryType.SHEBA, + { + nationalCode: '0012345678', + sheba: 'IR090540202620101368196602', + accountOwnerType: '1', + }, + { requestId: 'req-sheba', trackingCode: 'trk-sheba' }, + ); + + expect(request).toHaveBeenCalledWith( + expect.objectContaining({ + method: 'POST', + url: 'https://gateway.tejaratnoins.ir/api/central-insurance-sheba-inquiry', + data: { + AccountOwnerType: 1, + NationalId: '0012345678', + ShebaId: 'IR090540202620101368196602', + }, + }), + ); + }); +}); diff --git a/test/unit/tejarat-policy-by-plate.spec.ts b/test/unit/tejarat-policy-by-plate.spec.ts new file mode 100644 index 0000000..0a9a035 --- /dev/null +++ b/test/unit/tejarat-policy-by-plate.spec.ts @@ -0,0 +1,72 @@ +import { InquiryType } from '../../src/common/enums/inquiry-type.enum'; +import { TejaratNouProvider } from '../../src/providers/implementations/tejaratnou.provider'; + +describe('Tejarat policy by plate', () => { + it('posts plate parts and national code to central-insurance-car-inquiry with the Tejarat token', async () => { + const getTejaratNouAccessToken = jest.fn().mockResolvedValue('tejarat-token'); + const config = { + enabled: true, + timeout: 15000, + maxRetries: 1, + baseUrl: 'https://accounts.tejaratnoins.ir', + inquiryBaseUrl: 'https://gateway.tejaratnoins.ir', + clientId: 'api-gateway', + clientSecret: 'secret', + username: 'user', + password: 'pass', + }; + const provider = new TejaratNouProvider( + { get: () => config } as never, + { getTejaratNouAccessToken } as never, + {} as never, + ); + const request = jest.spyOn((provider as unknown as { httpClient: { request: jest.Mock } }).httpClient, 'request').mockResolvedValue({ + data: { + isSuccess: true, + data: { PolicyNo: 'P-1', NtnlId: '4311402422' }, + }, + }); + + const result = await provider.execute( + InquiryType.POLICY_BY_PLATE, + { + nationalCode: '4311402422', + plk1: '12', + plk2: 'ب', + plk3: '345', + plksrl: '67', + }, + { requestId: 'req-1', trackingCode: 'trk-1' }, + ); + + expect(getTejaratNouAccessToken).toHaveBeenCalledWith(config, expect.any(AbortSignal)); + expect(request).toHaveBeenCalledWith( + expect.objectContaining({ + method: 'POST', + url: '/api/central-insurance-car-inquiry', + data: { + Part1: '12', + Part2: 'ب', + Part3: '345', + Part4: '67', + NationalCode: '4311402422', + }, + headers: { + Authorization: 'Bearer tejarat-token', + Accept: 'text/plain', + }, + }), + ); + expect(result).toEqual({ + raw: { + nationalCode: '4311402422', + plk1: '12', + plk2: 'ب', + plk3: '345', + plksrl: '67', + PolicyNo: 'P-1', + NtnlId: '4311402422', + }, + }); + }); +}); diff --git a/test/unit/third-party-car-rules.spec.ts b/test/unit/third-party-car-rules.spec.ts new file mode 100644 index 0000000..f3a98ae --- /dev/null +++ b/test/unit/third-party-car-rules.spec.ts @@ -0,0 +1,70 @@ +import { + getCurrentJalaliYear, + isValidPlateLetter, + mergePlateAndNationalPolicies, + normalizeSoapCarPolicy, + selectBestThirdPartyPolicy, +} from '../../src/common/helpers/third-party-car-rules.helper'; + +describe('third-party car rules', () => { + it('rejects invalid plate letters', () => { + expect(isValidPlateLetter('')).toBe(false); + expect(isValidPlateLetter('ب')).toBe(true); + }); + + it('prefers active newer policy when multiple acceptable policies exist', () => { + const older = normalizeSoapCarPolicy( + { + NtnlId: '4311402422', + VhcleGrpCd: '2', + PlcyBegnDt: '20260101', + PlcyEndDt: '20270101', + }, + '4311402422', + ); + const newer = normalizeSoapCarPolicy( + { + NtnlId: '4311402422', + VhcleGrpCd: '3', + PlcyBegnDt: '20260701', + PlcyEndDt: '20270701', + }, + '4311402422', + ); + + const selected = selectBestThirdPartyPolicy([older, newer], '4311402422'); + expect(selected?.raw.PlcyBegnDt).toBe('20260701'); + }); + + it('keeps plate result when national code points to another vehicle', () => { + const plate = normalizeSoapCarPolicy( + { + NtnlId: '4311402422', + ChassisNo: 'CHASSIS-A', + Plk1: '12', + Plk2: 'ب', + Plk3: '345', + PlkSrl: '67', + }, + '4311402422', + ); + const national = normalizeSoapCarPolicy( + { + NtnlId: '4311402422', + ChassisNo: 'CHASSIS-B', + Plk1: '99', + Plk2: 'ج', + Plk3: '111', + PlkSrl: '22', + }, + '4311402422', + ); + + const merged = mergePlateAndNationalPolicies(plate, national); + expect(merged?.chassisNo).toBe('CHASSIS-A'); + }); + + it('returns current jalali year', () => { + expect(getCurrentJalaliYear(new Date('2026-03-21T00:00:00Z'))).toBeGreaterThan(1400); + }); +});