database migrated to POSTGRESQL

This commit is contained in:
2026-10-13 16:11:51 +03:30
parent 41ad8c1063
commit 514c3ccaf0
47 changed files with 1500 additions and 891 deletions
+4 -5
View File
@@ -1,6 +1,7 @@
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'; import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { typeOrmConfig } from './database/typeorm.config';
import { CommonModule } from './common/common.module'; import { CommonModule } from './common/common.module';
import { RequestIdMiddleware } from './common/middleware/request-id.middleware'; import { RequestIdMiddleware } from './common/middleware/request-id.middleware';
import { AppConfigModule } from './config/config.module'; import { AppConfigModule } from './config/config.module';
@@ -23,11 +24,9 @@ import { IdempotencyModule } from './idempotency/idempotency.module';
AppConfigModule, AppConfigModule,
CommonModule, CommonModule,
AuditModule, AuditModule,
MongooseModule.forRootAsync({ TypeOrmModule.forRootAsync({
inject: [ConfigService], inject: [ConfigService],
useFactory: (config: ConfigService) => ({ useFactory: typeOrmConfig,
uri: config.get<string>('mongodb.uri'),
}),
}), }),
RateLimitModule, RateLimitModule,
LoggingModule, LoggingModule,
+3 -3
View File
@@ -1,11 +1,11 @@
import { Global, Module } from '@nestjs/common'; import { Global, Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose'; import { TypeOrmModule } from '@nestjs/typeorm';
import { AuditService } from './audit.service'; import { AuditService } from './audit.service';
import { AuditLog, AuditLogSchema } from './schemas/audit-log.schema'; import { AuditLog } from './schemas/audit-log.schema';
@Global() @Global()
@Module({ @Module({
imports: [MongooseModule.forFeature([{ name: AuditLog.name, schema: AuditLogSchema }])], imports: [TypeOrmModule.forFeature([AuditLog])],
providers: [AuditService], providers: [AuditService],
exports: [AuditService], exports: [AuditService],
}) })
+12 -9
View File
@@ -1,8 +1,9 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose'; import { InjectRepository } from '@nestjs/typeorm';
import { Model, Types } from 'mongoose'; import { Repository } from 'typeorm';
import { AuditEvent } from '../common/enums/audit-event.enum'; 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 { export interface AuditContext {
userId?: string; userId?: string;
@@ -19,19 +20,21 @@ export interface AuditContext {
@Injectable() @Injectable()
export class AuditService { export class AuditService {
constructor( constructor(
@InjectModel(AuditLog.name) @InjectRepository(AuditLog)
private readonly auditModel: Model<AuditLogDocument>, private readonly auditLogs: Repository<AuditLog>,
) {} ) {}
async log(event: AuditEvent, context: AuditContext = {}): Promise<void> { async log(event: AuditEvent, context: AuditContext = {}): Promise<void> {
await this.auditModel.create({ await this.auditLogs.save(
this.auditLogs.create({
event, event,
userId: context.userId ? new Types.ObjectId(context.userId) : undefined, userId: isUuid(context.userId) ? context.userId : null,
actorId: context.actorId ? new Types.ObjectId(context.actorId) : undefined, actorId: isUuid(context.actorId) ? context.actorId : null,
username: context.username, username: context.username,
ip: context.ip, ip: context.ip,
userAgent: context.userAgent, userAgent: context.userAgent,
metadata: context.metadata ?? {}, metadata: context.metadata ?? {},
}); }),
);
} }
} }
+24 -22
View File
@@ -1,37 +1,39 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
import { HydratedDocument, Types } from 'mongoose';
import { AuditEvent } from '../../common/enums/audit-event.enum'; import { AuditEvent } from '../../common/enums/audit-event.enum';
export type AuditLogDocument = HydratedDocument<AuditLog>;
/** /**
* Immutable security audit trail — separate from inquiry_logs (business audit). * 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 { export class AuditLog {
@Prop({ required: true, enum: AuditEvent, index: true }) @PrimaryGeneratedColumn('uuid')
id!: string;
@Index()
@Column({ type: 'text' })
event!: AuditEvent; event!: AuditEvent;
@Prop({ type: Types.ObjectId, ref: 'User', index: true }) @Index()
userId?: Types.ObjectId; @Column({ type: 'uuid', nullable: true })
userId?: string | null;
@Prop({ type: Types.ObjectId, ref: 'User' }) @Column({ type: 'uuid', nullable: true })
actorId?: Types.ObjectId; actorId?: string | null;
@Prop() @Column({ type: 'text', nullable: true })
username?: string; username?: string | null;
@Prop() @Column({ type: 'text', nullable: true })
ip?: string; ip?: string | null;
@Prop() @Column({ type: 'text', nullable: true })
userAgent?: string; userAgent?: string | null;
@Prop({ type: Object, default: {} }) @Column({ type: 'jsonb', default: () => "'{}'::jsonb" })
metadata!: Record<string, unknown>; metadata!: Record<string, unknown>;
@CreateDateColumn({ type: 'timestamptz' })
createdAt!: Date;
} }
export const AuditLogSchema = SchemaFactory.createForClass(AuditLog);
AuditLogSchema.index({ createdAt: -1 });
AuditLogSchema.index({ event: 1, createdAt: -1 });
+10 -10
View File
@@ -35,27 +35,27 @@ export class AuthService {
} }
if (!user.isActive) { 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'); throw new AppException('ACCOUNT_INACTIVE');
} }
if (user.isBlocked) { 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'); throw new AppException('ACCOUNT_BLOCKED');
} }
const valid = await this.passwordService.compare(dto.password, user.password); const valid = await this.passwordService.compare(dto.password, user.password);
if (!valid) { 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'); throw new AppException('INVALID_CREDENTIALS');
} }
const tokens = await this.issueTokens(user); 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.usersService.recordLogin(user._id.toString()); await this.usersService.recordLogin(user.id);
await this.auditService.log(AuditEvent.LOGIN, { await this.auditService.log(AuditEvent.LOGIN, {
userId: user._id.toString(), userId: user.id,
username: user.username, username: user.username,
ip: context.ip, ip: context.ip,
userAgent: context.userAgent, userAgent: context.userAgent,
@@ -86,10 +86,10 @@ export class AuthService {
} }
const tokens = await this.issueTokens(user); 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, { await this.auditService.log(AuditEvent.LOGIN, {
userId: user._id.toString(), userId: user.id,
username: user.username, username: user.username,
ip: context.ip, ip: context.ip,
userAgent: context.userAgent, userAgent: context.userAgent,
@@ -117,13 +117,13 @@ export class AuthService {
} }
private async issueTokens(user: { private async issueTokens(user: {
_id: { toString(): string }; id: string;
role: JwtPayload['role']; role: JwtPayload['role'];
clientType: JwtPayload['clientType']; clientType: JwtPayload['clientType'];
appName: string; appName: string;
}): Promise<AuthTokensDto> { }): Promise<AuthTokensDto> {
const payload: JwtPayload = { const payload: JwtPayload = {
sub: user._id.toString(), sub: user.id,
role: user.role, role: user.role,
clientType: user.clientType, clientType: user.clientType,
appName: user.appName, appName: user.appName,
+1 -1
View File
@@ -35,7 +35,7 @@ export class JwtStrategy extends PassportStrategy(Strategy, JWT_ACCESS_STRATEGY)
} }
return { return {
id: user._id.toString(), id: user.id,
username: user.username, username: user.username,
email: user.email, email: user.email,
role: user.role, role: user.role,
+7 -8
View File
@@ -1,9 +1,10 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { AppConfigModule } from '../config/config.module'; import { TypeOrmModule } from '@nestjs/typeorm';
import { PasswordService } from '../auth/services/password.service'; 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'; import { CreateSuperAdminService } from './create-super-admin.service';
/** /**
@@ -13,13 +14,11 @@ import { CreateSuperAdminService } from './create-super-admin.service';
@Module({ @Module({
imports: [ imports: [
AppConfigModule, AppConfigModule,
MongooseModule.forRootAsync({ TypeOrmModule.forRootAsync({
inject: [ConfigService], inject: [ConfigService],
useFactory: (config: ConfigService) => ({ useFactory: typeOrmConfig,
uri: config.get<string>('mongodb.uri'),
}), }),
}), TypeOrmModule.forFeature([User]),
MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
], ],
providers: [CreateSuperAdminService, PasswordService], providers: [CreateSuperAdminService, PasswordService],
}) })
+19 -10
View File
@@ -1,14 +1,15 @@
import { Injectable, Logger } from '@nestjs/common'; import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose'; import { InjectRepository } from '@nestjs/typeorm';
import { Model } from 'mongoose';
import { randomBytes } from 'crypto'; import { randomBytes } from 'crypto';
import { Repository } from 'typeorm';
import { ClientType } from '../common/enums/client-type.enum'; import { ClientType } from '../common/enums/client-type.enum';
import { Role } from '../common/enums/role.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 { 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 { UserMapper } from '../users/mappers/user.mapper';
import { UserResponseDto } from '../users/dto/user-response.dto'; import { UserResponseDto } from '../users/dto/user-response.dto';
import { AppException } from '../common/exceptions/app-exception';
export interface CreateSuperAdminInput { export interface CreateSuperAdminInput {
fullName: string; fullName: string;
@@ -22,7 +23,7 @@ export class CreateSuperAdminService {
private readonly logger = new Logger(CreateSuperAdminService.name); private readonly logger = new Logger(CreateSuperAdminService.name);
constructor( constructor(
@InjectModel(User.name) private readonly userModel: Model<UserDocument>, @InjectRepository(User) private readonly users: Repository<User>,
private readonly passwordService: PasswordService, private readonly passwordService: PasswordService,
) {} ) {}
@@ -34,19 +35,21 @@ export class CreateSuperAdminService {
const username = input.username.toLowerCase().trim(); const username = input.username.toLowerCase().trim();
const email = input.email.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) { if (existing) {
throw new AppException('USERNAME_OR_EMAIL_EXISTS'); 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) { if (superAdminExists) {
this.logger.warn('A SUPER_ADMIN already exists; creating another.'); this.logger.warn('A SUPER_ADMIN already exists; creating another.');
} }
const passwordHash = await this.passwordService.hash(input.password); const passwordHash = await this.passwordService.hash(input.password);
const user = await this.userModel.create({ try {
const user = await this.users.save(
this.users.create({
fullName: input.fullName.trim(), fullName: input.fullName.trim(),
username, username,
email, email,
@@ -60,8 +63,14 @@ export class CreateSuperAdminService {
allowedInquiries: [], allowedInquiries: [],
apiKey: `esg_${randomBytes(32).toString('hex')}`, apiKey: `esg_${randomBytes(32).toString('hex')}`,
passwordChangedAt: new Date(), passwordChangedAt: new Date(),
}); }),
);
return UserMapper.toResponseDto(user); return UserMapper.toResponseDto(user);
} catch (error) {
if (isUniqueViolation(error)) {
throw new AppException('USERNAME_OR_EMAIL_EXISTS');
}
throw error;
}
} }
} }
+1 -1
View File
@@ -12,7 +12,7 @@ export interface RequestLogContext {
/** /**
* Structured console logging for inquiry lifecycle events. * Structured console logging for inquiry lifecycle events.
* Complements MongoDB persistence in LoggingModule. * Complements inquiry log persistence in LoggingModule.
*/ */
export class RequestLogger { export class RequestLogger {
private readonly logger: Logger; private readonly logger: Logger;
@@ -68,6 +68,10 @@ function translateValidationConstraint(field: string, constraint: string): strin
return 'تاریخ تولد باید با فرمت YYYY-MM-DD باشد'; 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')) { if (constraint.includes('birthDate must be in YYYY-MM-DD or YYYYMMDD format')) {
return 'تاریخ تولد باید با فرمت YYYY-MM-DD یا YYYYMMDD باشد'; return 'تاریخ تولد باید با فرمت YYYY-MM-DD یا YYYYMMDD باشد';
} }
+8 -3
View File
@@ -37,6 +37,7 @@ export interface TejaratNouConfig {
clientSecret: string; clientSecret: string;
username: string; username: string;
password: string; password: string;
inquiries: Partial<Record<InquiryType, InquiryConfig>>;
} }
export interface InquiryRoutingConfig { export interface InquiryRoutingConfig {
@@ -54,8 +55,8 @@ export default () => ({
port: parseInt(process.env.PORT ?? '8085', 10), port: parseInt(process.env.PORT ?? '8085', 10),
nodeEnv: process.env.NODE_ENV ?? 'development', nodeEnv: process.env.NODE_ENV ?? 'development',
}, },
mongodb: { database: {
uri: process.env.MONGODB_URI ?? 'mongodb://localhost:27017/inquiry-gateway', url: process.env.DATABASE_URL ?? 'postgresql://esg:esg@localhost:5432/inquiry_gateway',
}, },
auth: { auth: {
apiKey: process.env.API_KEY ?? '', apiKey: process.env.API_KEY ?? '',
@@ -86,13 +87,17 @@ export default () => ({
enabled: process.env.TEJARATNOU_ENABLED !== 'false', enabled: process.env.TEJARATNOU_ENABLED !== 'false',
timeout: parseInt(process.env.TEJARATNOU_TIMEOUT ?? '15000', 10), timeout: parseInt(process.env.TEJARATNOU_TIMEOUT ?? '15000', 10),
maxRetries: parseInt(process.env.TEJARATNOU_MAX_RETRIES ?? '3', 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: inquiryBaseUrl:
process.env.TEJARATNOU_INQUIRY_BASE_URL ?? 'https://gateway.tejaratnoins.ir', process.env.TEJARATNOU_INQUIRY_BASE_URL ?? 'https://gateway.tejaratnoins.ir',
clientId: process.env.TEJARATNOU_CLIENT_ID ?? 'api-gateway', clientId: process.env.TEJARATNOU_CLIENT_ID ?? 'api-gateway',
clientSecret: process.env.TEJARATNOU_CLIENT_SECRET ?? '', clientSecret: process.env.TEJARATNOU_CLIENT_SECRET ?? '',
username: process.env.TEJARATNOU_USERNAME ?? '', username: process.env.TEJARATNOU_USERNAME ?? '',
password: process.env.TEJARATNOU_PASSWORD ?? '', password: process.env.TEJARATNOU_PASSWORD ?? '',
inquiries: buildProviderConfig('TEJARATNOU').inquiries,
} satisfies TejaratNouConfig, } satisfies TejaratNouConfig,
inquiryRouting: { inquiryRouting: {
[InquiryType.PERSON]: buildInquiryRoutingConfig('PERSON', ProviderName.PARSIAN, [ [InquiryType.PERSON]: buildInquiryRoutingConfig('PERSON', ProviderName.PARSIAN, [
+28
View File
@@ -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}')],
});
+3 -3
View File
@@ -1,10 +1,10 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose'; import { TypeOrmModule } from '@nestjs/typeorm';
import { User, UserSchema } from '../users/schemas/user.schema'; import { User } from '../users/schemas/user.schema';
import { DatabaseSeederService } from './database-seeder.service'; import { DatabaseSeederService } from './database-seeder.service';
@Module({ @Module({
imports: [MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])], imports: [TypeOrmModule.forFeature([User])],
providers: [DatabaseSeederService], providers: [DatabaseSeederService],
}) })
export class DatabaseSeederModule {} export class DatabaseSeederModule {}
+48 -20
View File
@@ -1,9 +1,10 @@
import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common'; import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose'; import { InjectRepository } from '@nestjs/typeorm';
import { existsSync, readFileSync } from 'fs'; import { existsSync, readFileSync } from 'fs';
import { join } from 'path'; import { join } from 'path';
import { Model, Types } from 'mongoose'; import { DeepPartial, Repository } from 'typeorm';
import { User, UserDocument } from '../users/schemas/user.schema'; import { isUuid } from '../database/postgres.helpers';
import { User } from '../users/schemas/user.schema';
type ExtendedJsonValue = type ExtendedJsonValue =
| string | string
@@ -14,7 +15,7 @@ type ExtendedJsonValue =
| { [key: string]: ExtendedJsonValue }; | { [key: string]: ExtendedJsonValue };
interface SeedUser { interface SeedUser {
_id?: Types.ObjectId; id?: string;
fullName: string; fullName: string;
username: string; username: string;
email: string; email: string;
@@ -32,7 +33,7 @@ interface SeedUser {
requestLimitPerDay: number; requestLimitPerDay: number;
totalRequests?: number; totalRequests?: number;
passwordChangedAt?: Date; passwordChangedAt?: Date;
createdBy?: Types.ObjectId; createdBy?: string | null;
createdAt?: Date; createdAt?: Date;
updatedAt?: Date; updatedAt?: Date;
lastLoginAt?: Date; lastLoginAt?: Date;
@@ -44,7 +45,7 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
private readonly logger = new Logger(DatabaseSeederService.name); private readonly logger = new Logger(DatabaseSeederService.name);
private readonly usersSeedFile = 'inquiry-gateway.users.json'; private readonly usersSeedFile = 'inquiry-gateway.users.json';
constructor(@InjectModel(User.name) private readonly userModel: Model<UserDocument>) {} constructor(@InjectRepository(User) private readonly users: Repository<User>) {}
async onApplicationBootstrap(): Promise<void> { async onApplicationBootstrap(): Promise<void> {
await this.seedUsers(); await this.seedUsers();
@@ -52,12 +53,17 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
private async seedUsers(): Promise<void> { private async seedUsers(): Promise<void> {
const users = this.loadSeedUsers(); const users = this.loadSeedUsers();
if (!users) {
this.logger.warn(`Seed file ${this.usersSeedFile} not found; skipping baseline user seed.`);
return;
}
let inserted = 0; let inserted = 0;
let skipped = 0; let skipped = 0;
for (const user of users) { for (const user of users) {
const existing = await this.userModel.exists({ const existing = await this.users.findOne({
$or: [{ _id: user._id }, { username: user.username }, { email: user.email }], where: [{ username: user.username }, { email: user.email }],
}); });
if (existing) { if (existing) {
@@ -65,7 +71,7 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
continue; continue;
} }
await this.userModel.create(user); await this.users.save(this.users.create(user as DeepPartial<User>));
inserted += 1; inserted += 1;
} }
@@ -77,8 +83,10 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
this.logger.log(`Baseline users already exist; skipped ${skipped} user(s).`); this.logger.log(`Baseline users already exist; skipped ${skipped} user(s).`);
} }
private loadSeedUsers(): SeedUser[] { private loadSeedUsers(): SeedUser[] | null {
const seedPath = this.resolveSeedPath(); const seedPath = this.resolveSeedPath();
if (!seedPath) return null;
const raw = readFileSync(seedPath, 'utf8'); const raw = readFileSync(seedPath, 'utf8');
const parsed = JSON.parse(raw) as ExtendedJsonValue; const parsed = JSON.parse(raw) as ExtendedJsonValue;
const normalized = this.normalizeExtendedJson(parsed); const normalized = this.normalizeExtendedJson(parsed);
@@ -92,27 +100,46 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
throw new Error(`${this.usersSeedFile} contains an invalid user document`); 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 { return {
...user, ...(id ? { id } : {}),
fullName: user.fullName,
username: user.username.toLowerCase().trim(), username: user.username.toLowerCase().trim(),
email: user.email.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 = [ const candidates = [
join(__dirname, 'seeds', this.usersSeedFile), join(__dirname, 'seeds', this.usersSeedFile),
join(process.cwd(), 'src', 'database', 'seeds', this.usersSeedFile), join(process.cwd(), 'src', 'database', 'seeds', this.usersSeedFile),
join(process.cwd(), 'dist', 'database', 'seeds', this.usersSeedFile), join(process.cwd(), 'dist', 'database', 'seeds', this.usersSeedFile),
]; ];
const seedPath = candidates.find((candidate) => existsSync(candidate)); return candidates.find((candidate) => existsSync(candidate));
if (!seedPath) {
throw new Error(`Unable to find seed file: ${this.usersSeedFile}`);
}
return seedPath;
} }
private normalizeExtendedJson(value: ExtendedJsonValue): unknown { private normalizeExtendedJson(value: ExtendedJsonValue): unknown {
@@ -125,7 +152,7 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
} }
if (typeof value.$oid === 'string') { if (typeof value.$oid === 'string') {
return new Types.ObjectId(value.$oid); return value.$oid;
} }
if (typeof value.$date === 'string') { if (typeof value.$date === 'string') {
@@ -133,12 +160,13 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
} }
return Object.entries(value).reduce<Record<string, unknown>>((acc, [key, child]) => { return Object.entries(value).reduce<Record<string, unknown>>((acc, [key, child]) => {
if (key === '__v') return acc;
acc[key] = this.normalizeExtendedJson(child); acc[key] = this.normalizeExtendedJson(child);
return acc; 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') { if (!value || typeof value !== 'object') {
return false; return false;
} }
@@ -0,0 +1,172 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class InitialPostgresSchema1760356800000 implements MigrationInterface {
name = 'InitialPostgresSchema1760356800000';
public async up(queryRunner: QueryRunner): Promise<void> {
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<void> {
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`);
}
}
+12
View File
@@ -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));
}
+40
View File
@@ -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}`);
}
}
+16
View File
@@ -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<string>('database.url'),
autoLoadEntities: true,
synchronize: false,
migrationsRun: true,
namingStrategy: new SnakeNamingStrategy(),
migrations: [join(__dirname, 'migrations', '*.{js,ts}')],
};
}
+3 -3
View File
@@ -4,7 +4,7 @@ import {
HealthCheck, HealthCheck,
HealthCheckService, HealthCheckService,
MemoryHealthIndicator, MemoryHealthIndicator,
MongooseHealthIndicator, TypeOrmHealthIndicator,
} from '@nestjs/terminus'; } from '@nestjs/terminus';
import { HealthService } from './health.service'; import { HealthService } from './health.service';
@@ -12,7 +12,7 @@ import { HealthService } from './health.service';
export class HealthController { export class HealthController {
constructor( constructor(
private readonly health: HealthCheckService, private readonly health: HealthCheckService,
private readonly mongoose: MongooseHealthIndicator, private readonly database: TypeOrmHealthIndicator,
private readonly memory: MemoryHealthIndicator, private readonly memory: MemoryHealthIndicator,
private readonly disk: DiskHealthIndicator, private readonly disk: DiskHealthIndicator,
private readonly healthService: HealthService, private readonly healthService: HealthService,
@@ -28,7 +28,7 @@ export class HealthController {
@HealthCheck({ swaggerDocumentation: false }) @HealthCheck({ swaggerDocumentation: false })
readiness() { readiness() {
return this.health.check([ 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.memory.checkHeap('memory_heap', this.healthService.heapThresholdBytes()),
() => () =>
this.disk.checkStorage('disk', { this.disk.checkStorage('disk', {
+1 -2
View File
@@ -1,11 +1,10 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { TerminusModule } from '@nestjs/terminus'; import { TerminusModule } from '@nestjs/terminus';
import { HealthController } from './health.controller'; import { HealthController } from './health.controller';
import { HealthService } from './health.service'; import { HealthService } from './health.service';
@Module({ @Module({
imports: [TerminusModule.forRoot(), MongooseModule], imports: [TerminusModule.forRoot()],
controllers: [HealthController], controllers: [HealthController],
providers: [HealthService], providers: [HealthService],
}) })
+3 -10
View File
@@ -1,18 +1,11 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose'; import { TypeOrmModule } from '@nestjs/typeorm';
import { IdempotencyInterceptor } from './idempotency.interceptor'; import { IdempotencyInterceptor } from './idempotency.interceptor';
import { IdempotencyService } from './idempotency.service'; import { IdempotencyService } from './idempotency.service';
import { import { IdempotencyRecord } from './schemas/idempotency-record.schema';
IdempotencyRecord,
IdempotencyRecordSchema,
} from './schemas/idempotency-record.schema';
@Module({ @Module({
imports: [ imports: [TypeOrmModule.forFeature([IdempotencyRecord])],
MongooseModule.forFeature([
{ name: IdempotencyRecord.name, schema: IdempotencyRecordSchema },
]),
],
providers: [IdempotencyService, IdempotencyInterceptor], providers: [IdempotencyService, IdempotencyInterceptor],
exports: [IdempotencyService, IdempotencyInterceptor], exports: [IdempotencyService, IdempotencyInterceptor],
}) })
+95 -50
View File
@@ -1,11 +1,11 @@
import { createHash } from 'node:crypto'; import { createHash } from 'node:crypto';
import { Injectable } from '@nestjs/common'; import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose'; import { InjectRepository } from '@nestjs/typeorm';
import { Model } from 'mongoose'; import { QueryDeepPartialEntity, Repository } from 'typeorm';
import { AppException } from '../common/exceptions/app-exception'; import { AppException } from '../common/exceptions/app-exception';
import { isUniqueViolation } from '../database/postgres.helpers';
import { import {
IdempotencyRecord, IdempotencyRecord,
IdempotencyRecordDocument,
IdempotencyRecordStatus, IdempotencyRecordStatus,
} from './schemas/idempotency-record.schema'; } from './schemas/idempotency-record.schema';
@@ -31,16 +31,30 @@ export interface IdempotencyBeginResult {
const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000; const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
const IN_PROGRESS_TTL_MS = 5 * 60 * 1000; const IN_PROGRESS_TTL_MS = 5 * 60 * 1000;
const CLEANUP_INTERVAL_MS = 15 * 60 * 1000;
@Injectable() @Injectable()
export class IdempotencyService { export class IdempotencyService implements OnModuleInit, OnModuleDestroy {
private readonly ttlMs = this.readPositiveEnv('IDEMPOTENCY_TTL_MS', DEFAULT_TTL_MS); private readonly ttlMs = this.readPositiveEnv('IDEMPOTENCY_TTL_MS', DEFAULT_TTL_MS);
private cleanupTimer?: NodeJS.Timeout;
constructor( constructor(
@InjectModel(IdempotencyRecord.name) @InjectRepository(IdempotencyRecord)
private readonly recordModel: Model<IdempotencyRecordDocument>, private readonly records: Repository<IdempotencyRecord>,
) {} ) {}
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<IdempotencyBeginResult> { async begin(input: IdempotencyBeginInput): Promise<IdempotencyBeginResult> {
const key = input.key.trim(); const key = input.key.trim();
if (!key || key.length > 256) { if (!key || key.length > 256) {
@@ -52,23 +66,32 @@ export class IdempotencyService {
const scopeHash = this.hash(`${input.callerId}:${input.method}:${input.path}:${key}`); const scopeHash = this.hash(`${input.callerId}:${input.method}:${input.path}:${key}`);
const requestFingerprint = this.hash(this.stableStringify(input.body)); const requestFingerprint = this.hash(this.stableStringify(input.body));
const now = Date.now(); 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; let created = false;
if (!record) { if (!record || record.expiresAt.getTime() <= now) {
try { try {
record = await this.recordModel.create({ record = await this.records.save(
this.records.create({
scopeHash, scopeHash,
requestFingerprint, requestFingerprint,
status: IdempotencyRecordStatus.IN_PROGRESS, status: IdempotencyRecordStatus.IN_PROGRESS,
expiresAt: new Date(now + Math.min(this.ttlMs, IN_PROGRESS_TTL_MS)), expiresAt: inProgressExpiresAt,
requestId: input.requestId, requestId: input.requestId,
}); }),
);
created = true; created = true;
} catch (error) { } catch (error) {
if (!this.isDuplicateKey(error)) throw error; if (!isUniqueViolation(error)) throw error;
record = await this.recordModel.findOne({ scopeHash }).exec(); record = await this.records.findOne({ where: { scopeHash } });
} }
} }
@@ -78,6 +101,13 @@ export class IdempotencyService {
if (created) return { scopeHash }; 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) { if (record.requestFingerprint !== requestFingerprint) {
throw new AppException('IDEMPOTENCY_KEY_REUSED'); 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'); throw new AppException('IDEMPOTENCY_REQUEST_IN_PROGRESS');
} }
async complete(scopeHash: string, responseBody: unknown, responseStatus = 200): Promise<void> { async complete(scopeHash: string, responseBody: unknown, responseStatus = 200): Promise<void> {
await this.recordModel const values: QueryDeepPartialEntity<IdempotencyRecord> = {
.updateOne(
{ scopeHash, status: IdempotencyRecordStatus.IN_PROGRESS },
{
$set: {
status: IdempotencyRecordStatus.COMPLETED, status: IdempotencyRecordStatus.COMPLETED,
responseStatus, responseStatus,
responseBody, responseBody: this.asJsonObject(responseBody) as QueryDeepPartialEntity<
IdempotencyRecord
>['responseBody'],
expiresAt: new Date(Date.now() + this.ttlMs), expiresAt: new Date(Date.now() + this.ttlMs),
}, };
}, await this.records.update(
) { scopeHash, status: IdempotencyRecordStatus.IN_PROGRESS },
.exec(); values,
);
} }
async abandon(scopeHash: string): Promise<void> { async abandon(scopeHash: string): Promise<void> {
await this.recordModel await this.records.delete({ scopeHash, status: IdempotencyRecordStatus.IN_PROGRESS });
.deleteOne({ scopeHash, status: IdempotencyRecordStatus.IN_PROGRESS }) }
.exec();
private async reclaim(
id: string,
requestFingerprint: string,
expiresAt: Date,
requestId?: string,
): Promise<boolean> {
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<void> {
await this.records
.createQueryBuilder()
.delete()
.from(IdempotencyRecord)
.where('expires_at <= :now', { now: new Date() })
.execute();
}
private asJsonObject(value: unknown): Record<string, unknown> | null {
if (value === null || value === undefined) return null;
if (typeof value === 'object' && !Array.isArray(value)) {
return value as Record<string, unknown>;
}
return { value };
} }
private hash(value: string): string { private hash(value: string): string {
@@ -150,10 +199,6 @@ export class IdempotencyService {
.join(',')}}`; .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 { private readPositiveEnv(name: string, fallback: number): number {
const value = Number.parseInt(process.env[name] ?? '', 10); const value = Number.parseInt(process.env[name] ?? '', 10);
return Number.isFinite(value) && value > 0 ? value : fallback; return Number.isFinite(value) && value > 0 ? value : fallback;
@@ -1,36 +1,41 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn, UpdateDateColumn } from 'typeorm';
import { HydratedDocument, Schema as MongooseSchema } from 'mongoose';
export type IdempotencyRecordDocument = HydratedDocument<IdempotencyRecord>;
export enum IdempotencyRecordStatus { export enum IdempotencyRecordStatus {
IN_PROGRESS = 'IN_PROGRESS', IN_PROGRESS = 'IN_PROGRESS',
COMPLETED = 'COMPLETED', COMPLETED = 'COMPLETED',
} }
@Schema({ timestamps: true, collection: 'idempotency_records' }) @Entity('idempotency_records')
export class IdempotencyRecord { export class IdempotencyRecord {
@Prop({ required: true, unique: true, index: true }) @PrimaryGeneratedColumn('uuid')
id!: string;
@Index({ unique: true })
@Column({ type: 'text' })
scopeHash!: string; scopeHash!: string;
@Prop({ required: true }) @Column({ type: 'text' })
requestFingerprint!: string; requestFingerprint!: string;
@Prop({ required: true, enum: IdempotencyRecordStatus }) @Column({ type: 'text' })
status!: IdempotencyRecordStatus; status!: IdempotencyRecordStatus;
@Prop({ required: true }) @Index()
@Column({ type: 'timestamptz' })
expiresAt!: Date; expiresAt!: Date;
@Prop() @Column({ type: 'int', nullable: true })
responseStatus?: number; responseStatus?: number | null;
@Prop({ type: MongooseSchema.Types.Mixed }) @Column({ type: 'jsonb', nullable: true })
responseBody?: unknown; responseBody?: Record<string, unknown> | null;
@Prop() @Column({ type: 'text', nullable: true })
requestId?: string; 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 });
@@ -9,8 +9,13 @@ export class PersonInquiryRequestDto {
@Matches(/^\d{10}$/, { message: 'nationalCode must be exactly 10 digits' }) @Matches(/^\d{10}$/, { message: 'nationalCode must be exactly 10 digits' })
nationalCode!: string; nationalCode!: string;
@ApiProperty({ example: '1378-11-24', description: 'Jalali birth date (YYYY-MM-DD)' }) @ApiProperty({
@Matches(/^\d{4}-\d{2}-\d{2}$/, { message: 'birthDate must be in YYYY-MM-DD format' }) 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() @IsNotEmpty()
birthDate!: string; birthDate!: string;
+224 -299
View File
@@ -1,22 +1,19 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose'; import { InjectRepository } from '@nestjs/typeorm';
import { FilterQuery, Model } from 'mongoose'; import { Repository } from 'typeorm';
import { AttemptSummaryDto } from '../common/dto/attempt-summary.dto'; import { AttemptSummaryDto } from '../common/dto/attempt-summary.dto';
import { import { InquiryStatus, NO_MATCH_ERROR_CODES } from '../common/enums/inquiry-status.enum';
InquiryStatus,
NO_MATCH_ERROR_CODES,
} from '../common/enums/inquiry-status.enum';
import { InquiryType } from '../common/enums/inquiry-type.enum'; import { InquiryType } from '../common/enums/inquiry-type.enum';
import { ProviderName } from '../common/enums/provider-name.enum'; import { ProviderName } from '../common/enums/provider-name.enum';
import { maskPayload } from '../common/helpers/mask-payload.helper'; import { maskPayload } from '../common/helpers/mask-payload.helper';
import type { OutboundRequestTrace } from '../common/helpers/http-client.helper';
import { import {
InquiryLogQueryDto, InquiryLogQueryDto,
InquiryLogTimelineQueryDto, InquiryLogTimelineQueryDto,
LogTimelineInterval, LogTimelineInterval,
LogTimeRangePreset, LogTimeRangePreset,
} from './dto/inquiry-log-query.dto'; } from './dto/inquiry-log-query.dto';
import { InquiryLog, InquiryLogDocument } from './schemas/inquiry-log.schema'; import { InquiryLog } from './schemas/inquiry-log.schema';
import type { OutboundRequestTrace } from '../common/helpers/http-client.helper';
export interface CreateInquiryLogInput { export interface CreateInquiryLogInput {
inquiryType: InquiryType; inquiryType: InquiryType;
@@ -94,20 +91,32 @@ export interface TimelineBucket {
@Injectable() @Injectable()
export class InquiryLogService { export class InquiryLogService {
constructor( constructor(
@InjectModel(InquiryLog.name) @InjectRepository(InquiryLog)
private readonly inquiryLogModel: Model<InquiryLogDocument>, private readonly inquiryLogs: Repository<InquiryLog>,
) {} ) {}
async create(input: CreateInquiryLogInput): Promise<InquiryLogDocument> { async create(input: CreateInquiryLogInput): Promise<InquiryLog> {
return this.inquiryLogModel.create({ return this.inquiryLogs.save(
...input, this.inquiryLogs.create({
inquiryType: input.inquiryType,
provider: input.provider,
requestPayload: input.requestPayload,
maskedRequest: maskPayload(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<string, unknown> | undefined) ?? null,
outboundRequests: (input.outboundRequests as Record<string, unknown>[] | undefined) ?? null,
}),
);
} }
async purgeAll(): Promise<{ deletedCount: number }> { async purgeAll(): Promise<{ deletedCount: number }> {
const result = await this.inquiryLogModel.deleteMany({}).exec(); const result = await this.inquiryLogs.createQueryBuilder().delete().from(InquiryLog).execute();
return { deletedCount: result.deletedCount ?? 0 }; return { deletedCount: result.affected ?? 0 };
} }
async findLogs(query: InquiryLogQueryDto): Promise<{ async findLogs(query: InquiryLogQueryDto): Promise<{
@@ -116,299 +125,239 @@ export class InquiryLogService {
limit: number; limit: number;
total: number; total: number;
}> { }> {
const filter = this.buildFilter(query); const params: unknown[] = [];
const where = this.buildWhere(query, params);
const limit = query.limit ?? 50; const limit = query.limit ?? 50;
const page = query.page ?? 1; const page = query.page ?? 1;
const skip = (page - 1) * limit; const skip = (page - 1) * limit;
const [logs, total] = await Promise.all([ const countRows = await this.inquiryLogs.query<Array<{ total: number }>>(
this.inquiryLogModel `SELECT COUNT(*)::int AS total FROM inquiry_logs WHERE ${where}`,
.find(filter) params,
.sort({ createdAt: -1 }) );
.skip(skip) const pageParams = [...params, limit, skip];
.limit(limit) const logs = await this.inquiryLogs.query<InquiryLogListItem[]>(
.select('inquiryType provider status duration requestId trackingCode maskedRequest responsePayload error outboundRequests createdAt') `SELECT id,
.lean() inquiry_type AS "inquiryType",
.exec(), provider,
this.inquiryLogModel.countDocuments(filter), 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 { return {
data: logs.map((log) => ({ data: logs,
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,
})),
page, page,
limit, limit,
total, total: countRows[0]?.total ?? 0,
}; };
} }
async getSummary(query: InquiryLogQueryDto): Promise<InquiryLogSummary> { async getSummary(query: InquiryLogQueryDto): Promise<InquiryLogSummary> {
const [summary] = await this.inquiryLogModel.aggregate<InquiryLogSummary>([ const params: unknown[] = [];
{ $match: this.buildFilter(query) }, const where = this.buildWhere(query, params);
{ params.push([...NO_MATCH_ERROR_CODES]);
$group: { const codesParam = `$${params.length}`;
_id: null, const rows = await this.inquiryLogs.query<
total: { $sum: 1 }, Array<{
success: { total: number;
$sum: { $cond: [{ $eq: ['$status', InquiryStatus.SUCCESS] }, 1, 0] }, success: number;
}, failure: number;
failure: { noMatch: number;
$sum: { $cond: [{ $eq: ['$status', InquiryStatus.FAILURE] }, 1, 0] }, partial: number;
}, averageDuration: string | number | null;
noMatch: { minDuration: number | null;
$sum: { maxDuration: number | null;
$cond: [ }>
{ >(
$or: [ `SELECT COUNT(*)::int AS total,
{ $eq: ['$status', InquiryStatus.NO_MATCH] }, COUNT(*) FILTER (WHERE status = '${InquiryStatus.SUCCESS}')::int AS success,
{ COUNT(*) FILTER (
$and: [ WHERE status = '${InquiryStatus.FAILURE}'
{ $eq: ['$status', InquiryStatus.FAILURE] }, AND COALESCE(error->>'code', '') <> ALL(${codesParam}::text[])
{ $in: ['$error.code', NO_MATCH_ERROR_CODES] }, )::int AS failure,
], COUNT(*) FILTER (
}, WHERE status = '${InquiryStatus.NO_MATCH}'
], OR (
}, status = '${InquiryStatus.FAILURE}'
1, AND error->>'code' = ANY(${codesParam}::text[])
0, )
], )::int AS "noMatch",
}, COUNT(*) FILTER (WHERE status = '${InquiryStatus.PARTIAL}')::int AS partial,
}, AVG(duration) AS "averageDuration",
noMatchFailure: { MIN(duration)::int AS "minDuration",
$sum: { MAX(duration)::int AS "maxDuration"
$cond: [ FROM inquiry_logs
{ WHERE ${where}`,
$and: [ params,
{ $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] },
},
},
]);
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<CommonErrorItem[]> { async getCommonErrors(query: InquiryLogQueryDto): Promise<CommonErrorItem[]> {
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<CommonErrorItem>([ return this.inquiryLogs.query<CommonErrorItem[]>(
{ `SELECT COALESCE(error->>'code', 'UNKNOWN_ERROR') AS code,
$match: { COALESCE(error->>'message', 'Unknown error') AS message,
...this.buildFilter(query), COUNT(*)::int AS count,
error: { $exists: true, $ne: null }, MAX(created_at) AS "lastSeenAt"
}, FROM inquiry_logs
}, WHERE ${where} AND error IS NOT NULL
{ GROUP BY 1, 2
$group: { ORDER BY count DESC, "lastSeenAt" DESC
_id: { LIMIT ${limitParam}`,
code: { $ifNull: ['$error.code', 'UNKNOWN_ERROR'] }, params,
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,
},
},
]);
} }
async getDurationExtremes(query: InquiryLogQueryDto): Promise<{ async getDurationExtremes(query: InquiryLogQueryDto): Promise<{
fastest: DurationExtremeItem[]; fastest: DurationExtremeItem[];
slowest: DurationExtremeItem[]; slowest: DurationExtremeItem[];
}> { }> {
const filter = this.buildFilter(query); const params: unknown[] = [];
const where = this.buildWhere(query, params);
const limit = query.limit ?? 10; const limit = query.limit ?? 10;
const projection = const select = `SELECT id,
'inquiryType provider status duration requestId trackingCode error createdAt'; 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([ const [fastest, slowest] = await Promise.all([
this.inquiryLogModel.find(filter).sort({ duration: 1 }).limit(limit).select(projection).lean(), this.inquiryLogs.query<DurationExtremeItem[]>(
this.inquiryLogModel.find(filter).sort({ duration: -1 }).limit(limit).select(projection).lean(), `${select} ORDER BY duration ASC LIMIT $${params.length + 1}`,
[...params, limit],
),
this.inquiryLogs.query<DurationExtremeItem[]>(
`${select} ORDER BY duration DESC LIMIT $${params.length + 1}`,
[...params, limit],
),
]); ]);
return { return { fastest, slowest };
fastest: fastest.map((log) => this.toDurationExtremeItem(log)),
slowest: slowest.map((log) => this.toDurationExtremeItem(log)),
};
} }
async getTimeline(query: InquiryLogTimelineQueryDto): Promise<TimelineBucket[]> { async getTimeline(query: InquiryLogTimelineQueryDto): Promise<TimelineBucket[]> {
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<TimelineBucket>([ const rows = await this.inquiryLogs.query<
{ $match: this.buildFilter(query) }, Array<TimelineBucket & { commonErrorCode: string | null }>
{ >(
$group: { `WITH grouped AS (
_id: { SELECT to_char(created_at AT TIME ZONE 'Asia/Tehran', ${formatParam}) AS bucket,
bucket: { error->>'code' AS error_code,
$dateToString: { COUNT(*)::int AS total,
format: this.timelineFormat(interval), COUNT(*) FILTER (WHERE status = '${InquiryStatus.SUCCESS}')::int AS success,
date: '$createdAt', COUNT(*) FILTER (WHERE status = '${InquiryStatus.FAILURE}')::int AS failure,
timezone: 'Asia/Tehran', 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
errorCode: { $ifNull: ['$error.code', null] }, FROM inquiry_logs
}, WHERE ${where}
total: { $sum: 1 }, GROUP BY 1, 2
success: { ),
$sum: { $cond: [{ $eq: ['$status', InquiryStatus.SUCCESS] }, 1, 0] }, ranked AS (
}, SELECT *,
failure: { ROW_NUMBER() OVER (
$sum: { $cond: [{ $eq: ['$status', InquiryStatus.FAILURE] }, 1, 0] }, PARTITION BY bucket
}, ORDER BY CASE WHEN error_code IS NOT NULL THEN total ELSE 0 END DESC
partial: { ) AS rn
$sum: { $cond: [{ $eq: ['$status', InquiryStatus.PARTIAL] }, 1, 0] }, FROM grouped
}, )
durationSum: { $sum: '$duration' }, SELECT bucket,
maxDuration: { $max: '$duration' }, SUM(total)::int AS total,
}, SUM(success)::int AS success,
}, SUM(failure)::int AS failure,
{ SUM(partial)::int AS partial,
$addFields: { CASE WHEN SUM(total) = 0 THEN 0 ELSE SUM(duration_sum) / SUM(total) END AS "averageDuration",
errorCount: { MAX(max_duration)::int AS "maxDuration",
$cond: [{ $ne: ['$_id.errorCode', null] }, '$total', 0], MAX(CASE WHEN rn = 1 THEN error_code END) AS "commonErrorCode"
}, FROM ranked
}, GROUP BY bucket
}, ORDER BY bucket`,
{ $sort: { '_id.bucket': 1, errorCount: -1 } }, params,
{ );
$group: {
_id: '$_id.bucket', return rows.map((row) => ({
total: { $sum: '$total' }, bucket: row.bucket,
success: { $sum: '$success' }, total: Number(row.total),
failure: { $sum: '$failure' }, success: Number(row.success),
partial: { $sum: '$partial' }, failure: Number(row.failure),
durationSum: { $sum: '$durationSum' }, partial: Number(row.partial),
maxDuration: { $max: '$maxDuration' }, averageDuration: Number(row.averageDuration),
commonErrorCode: { $first: '$_id.errorCode' }, maxDuration: Number(row.maxDuration),
}, ...(row.commonErrorCode ? { commonErrorCode: row.commonErrorCode } : {}),
}, }));
{ $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,
},
},
]);
} }
private buildFilter(query: InquiryLogQueryDto): FilterQuery<InquiryLogDocument> { private buildWhere(query: InquiryLogQueryDto, params: unknown[]): string {
const filter: FilterQuery<InquiryLogDocument> = {}; const clauses: string[] = [];
const createdAt = this.buildCreatedAtFilter(query); const add = (sql: string, value: unknown) => {
params.push(value);
if (createdAt) { clauses.push(sql.replace('?', `$${params.length}`));
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;
}
const to = query.to ? new Date(query.to) : undefined; 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 { return clauses.length ? clauses.join(' AND ') : 'TRUE';
...(from && { $gte: from }), }
...(to && { $lte: to }),
}; private likeContains(value: string): string {
return `%${value.replace(/[\\%_]/g, (character) => `\\${character}`)}%`;
} }
private defaultFromDate(preset?: LogTimeRangePreset): Date { private defaultFromDate(preset?: LogTimeRangePreset): Date {
@@ -429,12 +378,12 @@ export class InquiryLogService {
private timelineFormat(interval: LogTimelineInterval): string { private timelineFormat(interval: LogTimelineInterval): string {
switch (interval) { switch (interval) {
case LogTimelineInterval.MONTH: case LogTimelineInterval.MONTH:
return '%Y-%m'; return 'YYYY-MM';
case LogTimelineInterval.DAY: case LogTimelineInterval.DAY:
return '%Y-%m-%d'; return 'YYYY-MM-DD';
case LogTimelineInterval.HOUR: case LogTimelineInterval.HOUR:
default: default:
return '%Y-%m-%d %H:00'; return 'YYYY-MM-DD HH24:00';
} }
} }
@@ -453,28 +402,4 @@ export class InquiryLogService {
maxDuration: 0, maxDuration: 0,
}; };
} }
private toDurationExtremeItem(log: {
_id: unknown;
inquiryType: InquiryType;
provider: ProviderName;
status: InquiryStatus;
duration: number;
requestId: string;
trackingCode: string;
error?: Record<string, unknown>;
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,
};
}
} }
+3 -5
View File
@@ -1,13 +1,11 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose'; import { TypeOrmModule } from '@nestjs/typeorm';
import { InquiryLogsController } from './inquiry-logs.controller'; import { InquiryLogsController } from './inquiry-logs.controller';
import { InquiryLogService } from './inquiry-log.service'; import { InquiryLogService } from './inquiry-log.service';
import { InquiryLog, InquiryLogSchema } from './schemas/inquiry-log.schema'; import { InquiryLog } from './schemas/inquiry-log.schema';
@Module({ @Module({
imports: [ imports: [TypeOrmModule.forFeature([InquiryLog])],
MongooseModule.forFeature([{ name: InquiryLog.name, schema: InquiryLogSchema }]),
],
controllers: [InquiryLogsController], controllers: [InquiryLogsController],
providers: [InquiryLogService], providers: [InquiryLogService],
exports: [InquiryLogService], exports: [InquiryLogService],
+28 -29
View File
@@ -1,57 +1,56 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
import { HydratedDocument } from 'mongoose';
import { InquiryStatus } from '../../common/enums/inquiry-status.enum'; import { InquiryStatus } from '../../common/enums/inquiry-status.enum';
import { InquiryType } from '../../common/enums/inquiry-type.enum'; import { InquiryType } from '../../common/enums/inquiry-type.enum';
import { ProviderName } from '../../common/enums/provider-name.enum'; import { ProviderName } from '../../common/enums/provider-name.enum';
export type InquiryLogDocument = HydratedDocument<InquiryLog>;
/** /**
* 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 { export class InquiryLog {
@Prop({ required: true, enum: InquiryType }) @PrimaryGeneratedColumn('uuid')
id!: string;
@Column({ type: 'text' })
inquiryType!: InquiryType; inquiryType!: InquiryType;
@Prop({ required: true, enum: ProviderName }) @Column({ type: 'text' })
provider!: ProviderName; provider!: ProviderName;
@Prop({ type: Object, required: true }) @Column({ type: 'jsonb' })
requestPayload!: Record<string, unknown>; requestPayload!: Record<string, unknown>;
@Prop({ type: Object, required: true }) @Column({ type: 'jsonb' })
maskedRequest!: Record<string, unknown>; maskedRequest!: Record<string, unknown>;
@Prop({ type: Object }) @Column({ type: 'jsonb', nullable: true })
responsePayload?: Record<string, unknown>; responsePayload?: Record<string, unknown> | null;
@Prop({ required: true, enum: InquiryStatus }) @Column({ type: 'text' })
status!: InquiryStatus; status!: InquiryStatus;
@Prop({ required: true }) @Column({ type: 'int' })
duration!: number; duration!: number;
@Prop({ required: true, index: true }) @Index()
@Column({ type: 'text' })
requestId!: string; requestId!: string;
@Prop({ required: true, index: true }) @Index()
@Column({ type: 'text' })
trackingCode!: string; trackingCode!: string;
@Prop({ type: Object }) @Column({ type: 'jsonb', nullable: true })
error?: Record<string, unknown>; error?: Record<string, unknown> | null;
@Prop({ type: Object }) @Column({ type: 'jsonb', nullable: true })
attemptSummary?: Record<string, unknown>; attemptSummary?: Record<string, unknown> | null;
@Prop({ type: [Object] }) @Column({ type: 'jsonb', nullable: true })
outboundRequests?: Record<string, unknown>[]; outboundRequests?: Record<string, unknown>[] | 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 });
@@ -19,7 +19,7 @@ import {
} from '../../common/helpers/provider-resilience.helper'; } from '../../common/helpers/provider-resilience.helper';
import { withRetry } from '../../common/helpers/retry.helper'; import { withRetry } from '../../common/helpers/retry.helper';
import { AmitisAuthServiceConfig } from '../../config/configuration'; 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 { GeneralTokenService } from '../services/general-token.service';
import { DistributedLockService } from '../services/distributed-lock.service'; import { DistributedLockService } from '../services/distributed-lock.service';
@@ -172,7 +172,7 @@ export class AmitisProvider {
} }
private async refreshAccessToken( private async refreshAccessToken(
latestToken: GeneralTokenDocument, latestToken: GeneralToken,
providerName: ProviderName, providerName: ProviderName,
inquiryType: InquiryType, inquiryType: InquiryType,
signal?: AbortSignal, signal?: AbortSignal,
@@ -184,7 +184,7 @@ export class AmitisProvider {
RefreshToken: latestToken.refreshToken, RefreshToken: latestToken.refreshToken,
}, { signal }), }, { signal }),
); );
const token = this.extractToken(response.data, latestToken.refreshToken); const token = this.extractToken(response.data, latestToken.refreshToken ?? undefined);
await this.saveToken( await this.saveToken(
token, 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 // Access token expires in 20 minutes, add 60 second buffer
const refreshBufferMs = 60 * 1000; const refreshBufferMs = 60 * 1000;
return !token.expiresAt || Date.now() + refreshBufferMs >= token.expiresAt.getTime(); 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 * Check if token is within 24-hour window from creation
* Refresh token is valid for 24 hours after initial login * Refresh token is valid for 24 hours after initial login
*/ */
private isWithin24Hours(token: GeneralTokenDocument): boolean { private isWithin24Hours(token: GeneralToken): boolean {
if (!token.createdAt) { if (!token.createdAt) {
return false; return false;
} }
@@ -6,6 +6,7 @@ import {
CentInsurApiResponse, CentInsurApiResponse,
getCentInsurProviderError, getCentInsurProviderError,
} from '../../common/helpers/centinsur-response.helper'; } from '../../common/helpers/centinsur-response.helper';
import { getSayahProviderError, SayahApiResponse } from '../../common/helpers/sayah-response.helper';
import { InquiryType } from '../../common/enums/inquiry-type.enum'; import { InquiryType } from '../../common/enums/inquiry-type.enum';
import { ProviderName } from '../../common/enums/provider-name.enum'; import { ProviderName } from '../../common/enums/provider-name.enum';
import { jalaliDateToGregorianDate } from '../../common/helpers/jalali-date.helper'; import { jalaliDateToGregorianDate } from '../../common/helpers/jalali-date.helper';
@@ -69,10 +70,12 @@ export class TejaratNouProvider implements InquiryProvider<LegacyInquiryPayload,
readonly supportedInquiryTypes = [ readonly supportedInquiryTypes = [
InquiryType.PERSON, InquiryType.PERSON,
InquiryType.SHAHKAR, InquiryType.SHAHKAR,
InquiryType.SHEBA,
InquiryType.REAL_ESTATE, InquiryType.REAL_ESTATE,
InquiryType.CAR_BY_PLATE, InquiryType.CAR_BY_PLATE,
InquiryType.CAR_BY_CHASSIS, InquiryType.CAR_BY_CHASSIS,
InquiryType.THIRD_PARTY_CAR, InquiryType.THIRD_PARTY_CAR,
InquiryType.POLICY_BY_PLATE,
]; ];
private readonly logger = new Logger(TejaratNouProvider.name); private readonly logger = new Logger(TejaratNouProvider.name);
@@ -121,9 +124,12 @@ export class TejaratNouProvider implements InquiryProvider<LegacyInquiryPayload,
); );
case InquiryType.SHAHKAR: case InquiryType.SHAHKAR:
return this.inquireShahkar(payload, context); return this.inquireShahkar(payload, context);
case InquiryType.SHEBA:
return this.inquireSheba(payload, context);
case InquiryType.REAL_ESTATE: case InquiryType.REAL_ESTATE:
return this.inquireRealEstate(payload, context); return this.inquireRealEstate(payload, context);
case InquiryType.CAR_BY_PLATE: case InquiryType.CAR_BY_PLATE:
case InquiryType.POLICY_BY_PLATE:
return this.inquireCarByPlate(payload, context); return this.inquireCarByPlate(payload, context);
case InquiryType.CAR_BY_CHASSIS: case InquiryType.CAR_BY_CHASSIS:
return this.inquireCarByChassis(payload, context); return this.inquireCarByChassis(payload, context);
@@ -330,11 +336,14 @@ export class TejaratNouProvider implements InquiryProvider<LegacyInquiryPayload,
payload: PersonInquiryPayload, payload: PersonInquiryPayload,
context: ProviderExecutionContext, context: ProviderExecutionContext,
): Promise<PersonInquiryResult> { ): Promise<PersonInquiryResult> {
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<TejaratNouPersonInquiryData>( const response = await this.authenticatedRequest<TejaratNouPersonInquiryData>(
'POST', yearOnly ? 'POST' : 'GET',
`/api/identity-inquiry/national-code/${payload.nationalCode}/birthdate/${encodeURIComponent(providerBirthDate)}`, yearOnly
{}, ? `${root}/national-code/${payload.nationalCode}/birthdate-year/${payload.birthDate}`
: `${root}/national-code/${payload.nationalCode}/birthdate/${encodeURIComponent(this.toGregorianBirthDate(payload.birthDate))}`,
undefined,
context, context,
); );
@@ -361,7 +370,7 @@ export class TejaratNouProvider implements InquiryProvider<LegacyInquiryPayload,
async () => { async () => {
const data = await this.authenticatedRequest<unknown>( const data = await this.authenticatedRequest<unknown>(
'POST', 'POST',
'/api/compliance-inquiry/compatibility', this.configuredUrl(InquiryType.SHAHKAR, '/api/compliance-inquiry/compatibility'),
{ nationalCode, mobileNo }, { nationalCode, mobileNo },
context, context,
); );
@@ -396,7 +405,7 @@ export class TejaratNouProvider implements InquiryProvider<LegacyInquiryPayload,
async () => { async () => {
const data = await this.authenticatedRequest<CentInsurApiResponse | Record<string, unknown>>( const data = await this.authenticatedRequest<CentInsurApiResponse | Record<string, unknown>>(
'POST', 'POST',
'/api/central-insurance-amlak-inquiry', this.configuredUrl(InquiryType.REAL_ESTATE, '/api/central-insurance-amlak-inquiry'),
{ {
nationalId: nationalCode, nationalId: nationalCode,
postalCode: Number(postalCode), postalCode: Number(postalCode),
@@ -422,6 +431,66 @@ export class TejaratNouProvider implements InquiryProvider<LegacyInquiryPayload,
); );
} }
private async inquireSheba(
payload: LegacyInquiryPayload,
context: ProviderExecutionContext,
): Promise<{ raw: unknown }> {
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<SayahApiResponse | Record<string, unknown>>(
'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<string, unknown>) : { 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<T>( private async withResilience<T>(
fn: () => Promise<T>, fn: () => Promise<T>,
context: ProviderExecutionContext, context: ProviderExecutionContext,
@@ -449,7 +518,7 @@ export class TejaratNouProvider implements InquiryProvider<LegacyInquiryPayload,
); );
try { try {
const response = await this.httpClient.request<TejaratNouGatewayResponse<T>>({ const response = await this.httpClient.request<TejaratNouGatewayResponse<T> | string>({
method, method,
url: path, url: path,
data: method === 'POST' ? body : undefined, data: method === 'POST' ? body : undefined,
@@ -460,16 +529,18 @@ export class TejaratNouProvider implements InquiryProvider<LegacyInquiryPayload,
signal: context.signal, signal: context.signal,
}); });
const envelope = response.data; const envelope = this.parseGatewayBody(response.data);
if (envelope?.isSuccess === false || (envelope?.statusCode && envelope.statusCode >= 400)) { if (this.isGatewayEnvelope(envelope)) {
if (envelope.isSuccess === false || (envelope.statusCode && envelope.statusCode >= 400)) {
throw this.createProviderError( throw this.createProviderError(
envelope.message ?? 'TejaratNou inquiry failed', envelope.message ?? 'TejaratNou inquiry failed',
String(envelope.statusCode ?? 'PROVIDER_ERROR'), String(envelope.statusCode ?? 'PROVIDER_ERROR'),
); );
} }
if (envelope?.data !== undefined) { if (envelope.data !== undefined) {
return envelope.data; return envelope.data as T;
}
} }
return envelope as T; return envelope as T;
@@ -489,6 +560,27 @@ export class TejaratNouProvider implements InquiryProvider<LegacyInquiryPayload,
} }
} }
private parseGatewayBody(data: unknown): unknown {
if (typeof data !== 'string') {
return data;
}
const trimmed = data.trim();
if (!trimmed) {
return data;
}
try {
return JSON.parse(trimmed) as unknown;
} catch {
return data;
}
}
private isGatewayEnvelope(value: unknown): value is TejaratNouGatewayResponse {
return Boolean(value) && typeof value === 'object';
}
private getCentInsurBusinessError( private getCentInsurBusinessError(
data: CentInsurApiResponse | Record<string, unknown>, data: CentInsurApiResponse | Record<string, unknown>,
): { message: string; code: string } | null { ): { message: string; code: string } | null {
@@ -561,6 +653,10 @@ export class TejaratNouProvider implements InquiryProvider<LegacyInquiryPayload,
? 'VALIDATION_ERROR' ? 'VALIDATION_ERROR'
: providerCode === 'INQUIRY_NO_MATCH' : providerCode === 'INQUIRY_NO_MATCH'
? 'INQUIRY_NO_MATCH' ? 'INQUIRY_NO_MATCH'
: providerCode === 'SHEBA_MISMATCH'
? 'SHEBA_MISMATCH'
: providerCode === 'SAYAH_ERROR'
? 'SAYAH_ERROR'
: providerCode === 'UNSUPPORTED_INQUIRY' : providerCode === 'UNSUPPORTED_INQUIRY'
? 'UNSUPPORTED_INQUIRY' ? 'UNSUPPORTED_INQUIRY'
: 'PROVIDER_ERROR'; : 'PROVIDER_ERROR';
@@ -1,3 +1,6 @@
import { InquiryType } from '../../common/enums/inquiry-type.enum';
import type { InquiryConfig } from '../../config/configuration';
export interface TejaratNouConfig { export interface TejaratNouConfig {
enabled: boolean; enabled: boolean;
timeout: number; timeout: number;
@@ -10,4 +13,5 @@ export interface TejaratNouConfig {
clientSecret: string; clientSecret: string;
username: string; username: string;
password: string; password: string;
inquiries: Partial<Record<InquiryType, InquiryConfig>>;
} }
+5 -12
View File
@@ -1,5 +1,5 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose'; import { TypeOrmModule } from '@nestjs/typeorm';
import { ProviderFactory } from './factory/provider.factory'; import { ProviderFactory } from './factory/provider.factory';
import { HamtaProvider } from './implementations/hamta.provider'; import { HamtaProvider } from './implementations/hamta.provider';
import { MoallemProvider } from './implementations/moallem.provider'; import { MoallemProvider } from './implementations/moallem.provider';
@@ -8,28 +8,21 @@ import { TejaratNouProvider } from './implementations/tejaratnou.provider';
import { AmitisProvider } from './implementations/amitis.provider'; import { AmitisProvider } from './implementations/amitis.provider';
import { ProviderOrchestratorService } from './strategy/provider-orchestrator.service'; import { ProviderOrchestratorService } from './strategy/provider-orchestrator.service';
import { ProviderIsolationService } from './strategy/provider-isolation.service'; import { ProviderIsolationService } from './strategy/provider-isolation.service';
import { GeneralToken, GeneralTokenSchema } from './schemas/general-token.schema'; import { GeneralToken } from './schemas/general-token.schema';
import { import { InquiryResultCache } from './schemas/inquiry-result-cache.schema';
InquiryResultCache,
InquiryResultCacheSchema,
} from './schemas/inquiry-result-cache.schema';
import { CentInsurCarPolicyClient } from './shared/centinsur-car-policy.client'; import { CentInsurCarPolicyClient } from './shared/centinsur-car-policy.client';
import { CentInsurCarProviderSupport } from './shared/centinsur-car-provider.support'; import { CentInsurCarProviderSupport } from './shared/centinsur-car-provider.support';
import { GeneralTokenService } from './services/general-token.service'; import { GeneralTokenService } from './services/general-token.service';
import { InquiryResultCacheService } from './services/inquiry-result-cache.service'; import { InquiryResultCacheService } from './services/inquiry-result-cache.service';
import { DistributedLockService } from './services/distributed-lock.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. * Provider adapters, factory, and orchestration strategy.
*/ */
@Module({ @Module({
imports: [ imports: [
MongooseModule.forFeature([ TypeOrmModule.forFeature([GeneralToken, InquiryResultCache, DistributedLock]),
{ name: GeneralToken.name, schema: GeneralTokenSchema },
{ name: InquiryResultCache.name, schema: InquiryResultCacheSchema },
{ name: DistributedLock.name, schema: DistributedLockSchema },
]),
], ],
providers: [ providers: [
HamtaProvider, HamtaProvider,
@@ -1,21 +1,27 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn, UpdateDateColumn } from 'typeorm';
import { HydratedDocument } from 'mongoose';
export type DistributedLockDocument = HydratedDocument<DistributedLock>; @Entity('distributed_locks')
@Schema({ timestamps: true, collection: 'distributed_locks' })
export class DistributedLock { export class DistributedLock {
@Prop({ required: true, unique: true, index: true }) @PrimaryGeneratedColumn('uuid')
id!: string;
@Index({ unique: true })
@Column({ type: 'text' })
lockKey!: string; lockKey!: string;
@Prop({ required: true }) @Column({ type: 'text' })
ownerId!: string; ownerId!: string;
@Prop({ required: true, index: true }) @Index()
@Column({ type: 'timestamptz' })
leaseUntil!: Date; leaseUntil!: Date;
@Prop({ required: true, default: 0 }) @Column({ type: 'int', default: 0 })
fencingToken!: number; fencingToken!: number;
}
export const DistributedLockSchema = SchemaFactory.createForClass(DistributedLock); @CreateDateColumn({ type: 'timestamptz' })
createdAt!: Date;
@UpdateDateColumn({ type: 'timestamptz' })
updatedAt!: Date;
}
+21 -21
View File
@@ -1,44 +1,44 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
import { HydratedDocument } from 'mongoose';
export type GeneralTokenDocument = HydratedDocument<GeneralToken>;
/** OAuth tokens for outbound provider APIs — credentials stay in env, not stored here. */ /** 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 { export class GeneralToken {
@Prop({ required: true, index: true }) @PrimaryGeneratedColumn('uuid')
id!: string;
@Index()
@Column({ type: 'text' })
serviceProvider!: string; serviceProvider!: string;
@Prop({ required: true }) @Column({ type: 'text' })
tokenType!: string; tokenType!: string;
@Prop({ required: true }) @Column({ type: 'text' })
url!: string; url!: string;
@Prop({ required: true }) @Column({ type: 'text' })
clientId!: string; clientId!: string;
@Prop({ required: true }) @Column({ type: 'text' })
username!: string; username!: string;
@Prop({ required: true }) @Column({ type: 'text' })
scope!: string; scope!: string;
@Prop({ required: true }) @Column({ type: 'text' })
accessToken!: string; accessToken!: string;
@Prop() @Column({ type: 'text', nullable: true })
refreshToken?: string; refreshToken?: string | null;
@Prop({ required: true }) @Column({ type: 'int' })
expiresIn!: number; expiresIn!: number;
@Prop({ required: true, index: true }) @Index()
@Column({ type: 'timestamptz' })
expiresAt!: Date; expiresAt!: Date;
createdAt?: Date; @CreateDateColumn({ type: 'timestamptz' })
createdAt!: Date;
} }
export const GeneralTokenSchema = SchemaFactory.createForClass(GeneralToken);
GeneralTokenSchema.index({ serviceProvider: 1, createdAt: -1 });
@@ -1,36 +1,36 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
import { HydratedDocument, Schema as MongooseSchema } from 'mongoose';
import { InquiryType } from '../../common/enums/inquiry-type.enum'; import { InquiryType } from '../../common/enums/inquiry-type.enum';
import { ProviderName } from '../../common/enums/provider-name.enum'; import { ProviderName } from '../../common/enums/provider-name.enum';
export type InquiryResultCacheDocument = HydratedDocument<InquiryResultCache>;
/** /**
* 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: * Separate from inquiry_logs (operational audit per request) because:
* - Cache keys are inquiry-specific (nationalCode+birthDate, plate number, etc.) * - Cache keys are inquiry-specific (nationalCode+birthDate, plate number, etc.)
* - Data is immutable for most inquiries (civil registration identity) * - Data is immutable for most inquiries (civil registration identity)
* - Retention and query patterns differ from audit trails * - 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 { export class InquiryResultCache {
@Prop({ required: true, enum: InquiryType, index: true }) @PrimaryGeneratedColumn('uuid')
id!: string;
@Index()
@Column({ type: 'text' })
inquiryType!: InquiryType; inquiryType!: InquiryType;
/** Stable lookup key, e.g. "0012345678|1378-11-24" for person inquiry. */ /** Stable lookup key, e.g. "0012345678|1378-11-24" for person inquiry. */
@Prop({ required: true, index: true }) @Index()
@Column({ type: 'text' })
cacheKey!: string; cacheKey!: string;
@Prop({ required: true, enum: ProviderName }) @Column({ type: 'text' })
provider!: ProviderName; provider!: ProviderName;
@Prop({ type: MongooseSchema.Types.Mixed, required: true }) @Column({ type: 'jsonb' })
data!: Record<string, unknown>; data!: Record<string, unknown>;
createdAt?: Date; @CreateDateColumn({ type: 'timestamptz' })
createdAt!: Date;
} }
export const InquiryResultCacheSchema = SchemaFactory.createForClass(InquiryResultCache);
InquiryResultCacheSchema.index({ inquiryType: 1, cacheKey: 1 }, { unique: true });
@@ -1,11 +1,8 @@
import { randomUUID } from 'node:crypto'; import { randomUUID } from 'node:crypto';
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose'; import { InjectRepository } from '@nestjs/typeorm';
import { Model } from 'mongoose'; import { Repository } from 'typeorm';
import { import { DistributedLock } from '../schemas/distributed-lock.schema';
DistributedLock,
DistributedLockDocument,
} from '../schemas/distributed-lock.schema';
export interface LockOptions { export interface LockOptions {
leaseMs?: number; leaseMs?: number;
@@ -25,8 +22,8 @@ const DEFAULT_WAIT_MS = 10_000;
@Injectable() @Injectable()
export class DistributedLockService { export class DistributedLockService {
constructor( constructor(
@InjectModel(DistributedLock.name) @InjectRepository(DistributedLock)
private readonly lockModel: Model<DistributedLockDocument>, private readonly locks: Repository<DistributedLock>,
) {} ) {}
async acquire( async acquire(
@@ -35,44 +32,36 @@ export class DistributedLockService {
leaseMs = DEFAULT_LEASE_MS, leaseMs = DEFAULT_LEASE_MS,
): Promise<LockLease | null> { ): Promise<LockLease | null> {
const now = new Date(); const now = new Date();
try { const leaseUntil = new Date(now.getTime() + leaseMs);
const lock = await this.lockModel const rows = await this.locks.query<Array<{ lockKey: string; ownerId: string; fencingToken: number }>>(
.findOneAndUpdate( `INSERT INTO distributed_locks (lock_key, owner_id, lease_until, fencing_token)
{ VALUES ($1, $2, $3, 1)
lockKey, ON CONFLICT (lock_key) DO UPDATE
$or: [{ leaseUntil: { $lte: now } }, { leaseUntil: { $exists: false } }], SET owner_id = EXCLUDED.owner_id,
}, lease_until = EXCLUDED.lease_until,
{ fencing_token = distributed_locks.fencing_token + 1,
$set: { updated_at = now()
lockKey, WHERE distributed_locks.lease_until <= $4
ownerId, RETURNING lock_key AS "lockKey", owner_id AS "ownerId", fencing_token AS "fencingToken"`,
leaseUntil: new Date(now.getTime() + leaseMs), [lockKey, ownerId, leaseUntil, now],
}, );
$inc: { fencingToken: 1 },
},
{ new: true, upsert: true, setDefaultsOnInsert: true },
)
.exec();
const lock = rows[0];
if (!lock || lock.ownerId !== ownerId) return null; if (!lock || lock.ownerId !== ownerId) return null;
return { return {
lockKey, lockKey: lock.lockKey,
ownerId, ownerId: lock.ownerId,
fencingToken: lock.fencingToken, fencingToken: Number(lock.fencingToken),
}; };
} catch (error) {
if (this.isDuplicateKey(error)) return null;
throw error;
}
} }
async release(lease: LockLease): Promise<void> { async release(lease: LockLease): Promise<void> {
await this.lockModel await this.locks.query(
.updateOne( `UPDATE distributed_locks
{ lockKey: lease.lockKey, ownerId: lease.ownerId }, SET lease_until = $3, updated_at = now()
{ $set: { leaseUntil: new Date(0) } }, WHERE lock_key = $1 AND owner_id = $2`,
) [lease.lockKey, lease.ownerId, new Date(0)],
.exec(); );
} }
async withLock<T>( async withLock<T>(
@@ -132,13 +121,4 @@ export class DistributedLockService {
(error as NodeJS.ErrnoException).code = 'ECANCELED'; (error as NodeJS.ErrnoException).code = 'ECANCELED';
return error; return error;
} }
private isDuplicateKey(error: unknown): boolean {
return Boolean(
error &&
typeof error === 'object' &&
'code' in error &&
(error as { code?: number }).code === 11000,
);
}
} }
+17 -14
View File
@@ -1,7 +1,7 @@
import { Injectable, Logger } from '@nestjs/common'; import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import axios from 'axios'; import axios from 'axios';
import { InjectModel } from '@nestjs/mongoose'; import { Repository } from 'typeorm';
import { Model } from 'mongoose';
import { mergeOutboundAxiosConfig } from '../../common/helpers/http-client.helper'; import { mergeOutboundAxiosConfig } from '../../common/helpers/http-client.helper';
import { import {
AUTH_MAX_ATTEMPTS, AUTH_MAX_ATTEMPTS,
@@ -9,7 +9,7 @@ import {
isAuthTransportRetryable, isAuthTransportRetryable,
} from '../../common/helpers/provider-resilience.helper'; } from '../../common/helpers/provider-resilience.helper';
import { withRetry } from '../../common/helpers/retry.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 { TejaratNouConfig } from '../interfaces/tejaratnou-config.interface';
import { DistributedLockService } from './distributed-lock.service'; import { DistributedLockService } from './distributed-lock.service';
@@ -28,17 +28,20 @@ export class GeneralTokenService {
private readonly logger = new Logger(GeneralTokenService.name); private readonly logger = new Logger(GeneralTokenService.name);
constructor( constructor(
@InjectModel(GeneralToken.name) @InjectRepository(GeneralToken)
private readonly generalTokenModel: Model<GeneralTokenDocument>, private readonly generalTokens: Repository<GeneralToken>,
private readonly distributedLockService: DistributedLockService, private readonly distributedLockService: DistributedLockService,
) {} ) {}
async getLatestToken(serviceProvider: string): Promise<GeneralTokenDocument | null> { async getLatestToken(serviceProvider: string): Promise<GeneralToken | null> {
return this.generalTokenModel.findOne({ serviceProvider }).sort({ createdAt: -1 }).exec(); return this.generalTokens.findOne({
where: { serviceProvider },
order: { createdAt: 'DESC' },
});
} }
async isTokenExpired( async isTokenExpired(
token: GeneralTokenDocument, token: GeneralToken,
bufferSeconds = TOKEN_EXPIRY_BUFFER_SECONDS, bufferSeconds = TOKEN_EXPIRY_BUFFER_SECONDS,
): Promise<boolean> { ): Promise<boolean> {
if (!token.expiresAt) return true; 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. * otherwise fetches a new one via the supplied OAuth fetcher.
*/ */
async getValidAccessToken( async getValidAccessToken(
@@ -62,7 +65,7 @@ export class GeneralTokenService {
): Promise<string> { ): Promise<string> {
const latest = await this.getLatestToken(serviceProvider); const latest = await this.getLatestToken(serviceProvider);
if (latest && !(await this.isTokenExpired(latest))) { 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; return latest.accessToken;
} }
@@ -77,7 +80,7 @@ export class GeneralTokenService {
const fresh = await fetchNewToken(signal); const fresh = await fetchNewToken(signal);
const expiresAt = new Date(Date.now() + fresh.expiresIn * 1000); const expiresAt = new Date(Date.now() + fresh.expiresIn * 1000);
await this.generalTokenModel.create({ await this.generalTokens.save(this.generalTokens.create({
serviceProvider, serviceProvider,
tokenType: fresh.tokenType, tokenType: fresh.tokenType,
url: persistContext.url, url: persistContext.url,
@@ -87,7 +90,7 @@ export class GeneralTokenService {
accessToken: fresh.accessToken, accessToken: fresh.accessToken,
expiresIn: fresh.expiresIn, expiresIn: fresh.expiresIn,
expiresAt, expiresAt,
}); }));
this.logger.log(`Stored new ${serviceProvider} token, expires at ${expiresAt.toISOString()}`); this.logger.log(`Stored new ${serviceProvider} token, expires at ${expiresAt.toISOString()}`);
return fresh.accessToken; return fresh.accessToken;
@@ -108,8 +111,8 @@ export class GeneralTokenService {
refreshToken?: string; refreshToken?: string;
expiresIn: number; expiresIn: number;
expiresAt: Date; expiresAt: Date;
}): Promise<GeneralTokenDocument> { }): Promise<GeneralToken> {
return this.generalTokenModel.create(data); return this.generalTokens.save(this.generalTokens.create(data));
} }
/** OAuth2 password grant for Tejarat No identity gateway. */ /** OAuth2 password grant for Tejarat No identity gateway. */
@@ -1,12 +1,9 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose'; import { InjectRepository } from '@nestjs/typeorm';
import { Model } from 'mongoose'; import { Repository } from 'typeorm';
import { InquiryType } from '../../common/enums/inquiry-type.enum'; import { InquiryType } from '../../common/enums/inquiry-type.enum';
import { ProviderName } from '../../common/enums/provider-name.enum'; import { ProviderName } from '../../common/enums/provider-name.enum';
import { import { InquiryResultCache } from '../schemas/inquiry-result-cache.schema';
InquiryResultCache,
InquiryResultCacheDocument,
} from '../schemas/inquiry-result-cache.schema';
export interface PersonInquiryCacheData { export interface PersonInquiryCacheData {
nationalCode: string; nationalCode: string;
@@ -30,8 +27,8 @@ export interface PersonInquiryCacheData {
@Injectable() @Injectable()
export class InquiryResultCacheService { export class InquiryResultCacheService {
constructor( constructor(
@InjectModel(InquiryResultCache.name) @InjectRepository(InquiryResultCache)
private readonly cacheModel: Model<InquiryResultCacheDocument>, private readonly cache: Repository<InquiryResultCache>,
) {} ) {}
static personCacheKey(nationalCode: string, birthDate: string): string { static personCacheKey(nationalCode: string, birthDate: string): string {
@@ -42,44 +39,25 @@ export class InquiryResultCacheService {
nationalCode: string, nationalCode: string,
birthDate: string, birthDate: string,
): Promise<PersonInquiryCacheData | null> { ): Promise<PersonInquiryCacheData | null> {
const entry = await this.cacheModel const data = await this.find(
.findOne({ InquiryType.PERSON,
inquiryType: InquiryType.PERSON, InquiryResultCacheService.personCacheKey(nationalCode, birthDate),
cacheKey: InquiryResultCacheService.personCacheKey(nationalCode, birthDate), );
}) return data as PersonInquiryCacheData | null;
.exec();
if (!entry) return null;
return entry.data as unknown as PersonInquiryCacheData;
} }
async savePersonInquiry( async savePersonInquiry(provider: ProviderName, data: PersonInquiryCacheData): Promise<void> {
provider: ProviderName, await this.save(
data: PersonInquiryCacheData, InquiryType.PERSON,
): Promise<void> { InquiryResultCacheService.personCacheKey(data.nationalCode, data.birthDate),
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, provider,
data, data as unknown as Record<string, unknown>,
},
},
{ upsert: true },
); );
} }
/** Generic cache read for future inquiry types. */ /** Generic cache read for future inquiry types. */
async find( async find(inquiryType: InquiryType, cacheKey: string): Promise<Record<string, unknown> | null> {
inquiryType: InquiryType, const entry = await this.cache.findOne({ where: { inquiryType, cacheKey } });
cacheKey: string,
): Promise<Record<string, unknown> | null> {
const entry = await this.cacheModel.findOne({ inquiryType, cacheKey }).exec();
return entry?.data ?? null; return entry?.data ?? null;
} }
@@ -89,10 +67,13 @@ export class InquiryResultCacheService {
provider: ProviderName, provider: ProviderName,
data: Record<string, unknown>, data: Record<string, unknown>,
): Promise<void> { ): Promise<void> {
await this.cacheModel.updateOne( await this.cache.query(
{ inquiryType, cacheKey }, `INSERT INTO inquiry_result_cache (inquiry_type, cache_key, provider, data)
{ $set: { inquiryType, cacheKey, provider, data } }, VALUES ($1, $2, $3, $4::jsonb)
{ upsert: true }, ON CONFLICT (inquiry_type, cache_key) DO UPDATE
SET provider = EXCLUDED.provider,
data = EXCLUDED.data`,
[inquiryType, cacheKey, provider, JSON.stringify(data)],
); );
} }
} }
+1 -1
View File
@@ -783,7 +783,7 @@
} }
} }
async function clearInquiryLogs() { 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 { try {
const result = await request('/inquiry-logs', { method: 'DELETE' }); const result = await request('/inquiry-logs', { method: 'DELETE' });
$('logsBody').replaceChildren(); $('logOutput').textContent = 'Inquiry logs were cleared.'; $('logsBody').replaceChildren(); $('logOutput').textContent = 'Inquiry logs were cleared.';
+8 -8
View File
@@ -1,16 +1,16 @@
import { UserDocument } from '../schemas/user.schema'; import { User } from '../schemas/user.schema';
import { ProfileDto } from '../../auth/dto/profile.dto'; import { ProfileDto } from '../../auth/dto/profile.dto';
import { UserResponseDto } from '../dto/user-response.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 { export class UserMapper {
static toProfileDto(user: UserDocument): ProfileDto { static toProfileDto(user: User): ProfileDto {
return { return {
id: user._id.toString(), id: user.id,
fullName: user.fullName, fullName: user.fullName,
username: user.username, username: user.username,
email: user.email, email: user.email,
mobile: user.mobile, mobile: user.mobile ?? undefined,
role: user.role, role: user.role,
clientType: user.clientType, clientType: user.clientType,
appName: user.appName, appName: user.appName,
@@ -21,14 +21,14 @@ export class UserMapper {
requestLimitPerMinute: user.requestLimitPerMinute, requestLimitPerMinute: user.requestLimitPerMinute,
requestLimitPerDay: user.requestLimitPerDay, requestLimitPerDay: user.requestLimitPerDay,
totalRequests: user.totalRequests, totalRequests: user.totalRequests,
lastLoginAt: user.lastLoginAt, lastLoginAt: user.lastLoginAt ?? undefined,
passwordChangedAt: user.passwordChangedAt, passwordChangedAt: user.passwordChangedAt ?? undefined,
createdAt: user.createdAt, createdAt: user.createdAt,
updatedAt: user.updatedAt, updatedAt: user.updatedAt,
}; };
} }
static toResponseDto(user: UserDocument): UserResponseDto { static toResponseDto(user: User): UserResponseDto {
return UserMapper.toProfileDto(user); return UserMapper.toProfileDto(user);
} }
} }
+42 -38
View File
@@ -1,85 +1,89 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn, UpdateDateColumn } from 'typeorm';
import { HydratedDocument, Types } from 'mongoose';
import { ClientType } from '../../common/enums/client-type.enum'; import { ClientType } from '../../common/enums/client-type.enum';
import { Role } from '../../common/enums/role.enum'; import { Role } from '../../common/enums/role.enum';
export type UserDocument = HydratedDocument<User>;
/** /**
* 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. * 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 { export class User {
@Prop({ required: true, trim: true }) @PrimaryGeneratedColumn('uuid')
id!: string;
@Column({ type: 'text' })
fullName!: string; fullName!: string;
@Prop({ required: true, unique: true, lowercase: true, trim: true, index: true }) @Index({ unique: true })
@Column({ type: 'text' })
username!: string; username!: string;
@Prop({ required: true, unique: true, lowercase: true, trim: true, index: true }) @Index({ unique: true })
@Column({ type: 'text' })
email!: string; email!: string;
@Prop({ trim: true }) @Column({ type: 'text', nullable: true })
mobile?: string; mobile?: string | null;
@Prop({ required: true, select: false }) @Column({ type: 'text', select: false })
password!: string; password!: string;
@Prop({ required: true, enum: Role, default: Role.USER, index: true }) @Index()
@Column({ type: 'text' })
role!: Role; role!: Role;
@Prop({ required: true, enum: ClientType, default: ClientType.EXTERNAL, index: true }) @Index()
@Column({ type: 'text' })
clientType!: ClientType; clientType!: ClientType;
@Prop({ trim: true, default: '' }) @Column({ type: 'text', default: '' })
appName!: string; appName!: string;
@Prop({ trim: true, default: '' }) @Column({ type: 'text', default: '' })
clientName!: string; clientName!: string;
@Prop({ default: true }) @Column({ type: 'boolean', default: true })
isActive!: boolean; isActive!: boolean;
@Prop({ default: false }) @Column({ type: 'boolean', default: false })
isBlocked!: boolean; isBlocked!: boolean;
/** Future: machine-to-machine auth without JWT. */ /** Future: machine-to-machine auth without JWT. */
@Prop({ select: false }) @Column({ type: 'text', nullable: true, select: false })
apiKey?: string; apiKey?: string | null;
@Prop({ type: [String], default: [] }) @Column({ type: 'text', array: true, default: () => "'{}'" })
allowedInquiries!: string[]; allowedInquiries!: string[];
@Prop({ default: 60 }) @Column({ type: 'int', default: 60 })
requestLimitPerMinute!: number; requestLimitPerMinute!: number;
@Prop({ default: 10000 }) @Column({ type: 'int', default: 10000 })
requestLimitPerDay!: number; requestLimitPerDay!: number;
@Prop({ default: 0 }) @Column({ type: 'int', default: 0 })
totalRequests!: number; totalRequests!: number;
@Prop() @Column({ type: 'timestamptz', nullable: true })
lastLoginAt?: Date; lastLoginAt?: Date | null;
@Prop() @Column({ type: 'timestamptz', nullable: true })
passwordChangedAt?: Date; passwordChangedAt?: Date | null;
@Prop({ type: Types.ObjectId, ref: 'User' }) @Column({ type: 'uuid', nullable: true })
createdBy?: Types.ObjectId; createdBy?: string | null;
@Prop({ select: false }) @Column({ type: 'text', nullable: true, select: false })
refreshToken?: string; refreshToken?: string | null;
@Prop({ type: Object, default: {} }) @Column({ type: 'jsonb', default: () => "'{}'::jsonb" })
metadata!: Record<string, unknown>; metadata!: Record<string, unknown>;
@CreateDateColumn({ type: 'timestamptz' })
createdAt!: Date; createdAt!: Date;
@UpdateDateColumn({ type: 'timestamptz' })
updatedAt!: Date; updatedAt!: Date;
} }
export const UserSchema = SchemaFactory.createForClass(User);
UserSchema.index({ role: 1, isActive: 1 });
UserSchema.index({ clientType: 1, appName: 1 });
+4 -7
View File
@@ -1,17 +1,14 @@
import { Module, forwardRef } from '@nestjs/common'; import { Module, forwardRef } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose'; import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthModule } from '../auth/auth.module'; 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 { UsersController } from './users.controller';
import { UsersService } from './users.service'; import { UsersService } from './users.service';
@Module({ @Module({
imports: [ imports: [TypeOrmModule.forFeature([User]), forwardRef(() => AuthModule)],
MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
forwardRef(() => AuthModule),
],
controllers: [UsersController], controllers: [UsersController],
providers: [UsersService], providers: [UsersService],
exports: [UsersService, MongooseModule], exports: [UsersService],
}) })
export class UsersModule {} export class UsersModule {}
+82 -64
View File
@@ -1,11 +1,11 @@
import { import { Injectable } from '@nestjs/common';
Injectable, import { InjectRepository } from '@nestjs/typeorm';
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { randomBytes } from 'crypto'; import { randomBytes } from 'crypto';
import { Not, QueryDeepPartialEntity, Repository } from 'typeorm';
import { AuditEvent } from '../common/enums/audit-event.enum'; import { AuditEvent } from '../common/enums/audit-event.enum';
import { ADMIN_ROLES, Role } from '../common/enums/role.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 { AuditService } from '../audit/audit.service';
import { PasswordService } from '../auth/services/password.service'; import { PasswordService } from '../auth/services/password.service';
import { AuthenticatedUser } from '../auth/interfaces/authenticated-user.interface'; 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 { ResetPasswordDto } from './dto/reset-password.dto';
import { UpdateUserDto } from './dto/update-user.dto'; import { UpdateUserDto } from './dto/update-user.dto';
import { UserMapper } from './mappers/user.mapper'; 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 { UserResponseDto } from './dto/user-response.dto';
import { AppException } from '../common/exceptions/app-exception';
export interface RequestContext { export interface RequestContext {
ip?: string; ip?: string;
@@ -25,30 +24,35 @@ export interface RequestContext {
@Injectable() @Injectable()
export class UsersService { export class UsersService {
constructor( constructor(
@InjectModel(User.name) private readonly userModel: Model<UserDocument>, @InjectRepository(User) private readonly users: Repository<User>,
private readonly passwordService: PasswordService, private readonly passwordService: PasswordService,
private readonly auditService: AuditService, private readonly auditService: AuditService,
) {} ) {}
async findById(id: string): Promise<UserDocument> { async findById(id: string): Promise<User> {
const user = await this.userModel.findById(id); if (!isUuid(id)) {
throw new AppException('USER_NOT_FOUND');
}
const user = await this.users.findOne({ where: { id } });
if (!user) { if (!user) {
throw new AppException('USER_NOT_FOUND'); throw new AppException('USER_NOT_FOUND');
} }
return user; return user;
} }
async findByUsername(username: string, includePassword = false): Promise<UserDocument | null> { async findByUsername(username: string, includePassword = false): Promise<User | null> {
const query = this.userModel.findOne({ username: username.toLowerCase().trim() }); const query = this.users
.createQueryBuilder('user')
.where('user.username = :username', { username: username.toLowerCase().trim() });
if (includePassword) { if (includePassword) {
query.select('+password +refreshToken'); query.addSelect('user.password').addSelect('user.refreshToken');
} }
return query.exec(); return query.getOne();
} }
async findAll(): Promise<UserResponseDto[]> { async findAll(): Promise<UserResponseDto[]> {
const users = await this.userModel.find().sort({ createdAt: -1 }); const users = await this.users.find({ order: { createdAt: 'DESC' } });
return users.map((u) => UserMapper.toResponseDto(u)); return users.map((user) => UserMapper.toResponseDto(user));
} }
async create( async create(
@@ -61,9 +65,7 @@ export class UsersService {
const username = dto.username.toLowerCase().trim(); const username = dto.username.toLowerCase().trim();
const email = dto.email.toLowerCase().trim(); const email = dto.email.toLowerCase().trim();
const existing = await this.userModel.findOne({ const existing = await this.users.findOne({ where: [{ username }, { email }] });
$or: [{ username }, { email }],
});
if (existing) { if (existing) {
throw new AppException('USERNAME_OR_EMAIL_EXISTS'); throw new AppException('USERNAME_OR_EMAIL_EXISTS');
} }
@@ -71,7 +73,10 @@ export class UsersService {
const passwordHash = await this.passwordService.hash(dto.password); const passwordHash = await this.passwordService.hash(dto.password);
const apiKey = this.generateApiKey(); const apiKey = this.generateApiKey();
const user = await this.userModel.create({ let user: User;
try {
user = await this.users.save(
this.users.create({
fullName: dto.fullName, fullName: dto.fullName,
username, username,
email, email,
@@ -87,13 +92,20 @@ export class UsersService {
requestLimitPerDay: dto.requestLimitPerDay ?? 10000, requestLimitPerDay: dto.requestLimitPerDay ?? 10000,
apiKey, apiKey,
passwordChangedAt: new Date(), passwordChangedAt: new Date(),
createdBy: new Types.ObjectId(actor.id), createdBy: isUuid(actor.id) ? actor.id : null,
metadata: dto.metadata ?? {}, metadata: dto.metadata ?? {},
}); }),
);
} catch (error) {
if (isUniqueViolation(error)) {
throw new AppException('USERNAME_OR_EMAIL_EXISTS');
}
throw error;
}
await this.auditService.log(AuditEvent.USER_CREATED, { await this.auditService.log(AuditEvent.USER_CREATED, {
actorId: actor.id, actorId: actor.id,
userId: user._id.toString(), userId: user.id,
username: user.username, username: user.username,
ip: context.ip, ip: context.ip,
userAgent: context.userAgent, userAgent: context.userAgent,
@@ -110,33 +122,36 @@ export class UsersService {
this.assertCanAssignRole(actor.role, dto.role); this.assertCanAssignRole(actor.role, dto.role);
} }
const changes: Partial<User> = {};
if (dto.email) { if (dto.email) {
const email = dto.email.toLowerCase().trim(); 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) { if (conflict) {
throw new AppException('EMAIL_ALREADY_IN_USE'); throw new AppException('EMAIL_ALREADY_IN_USE');
} }
user.email = email; changes.email = email;
} }
Object.assign(user, { if (dto.fullName !== undefined) changes.fullName = dto.fullName;
...(dto.fullName !== undefined && { fullName: dto.fullName }), if (dto.mobile !== undefined) changes.mobile = dto.mobile;
...(dto.mobile !== undefined && { mobile: dto.mobile }), if (dto.role !== undefined) changes.role = dto.role;
...(dto.role !== undefined && { role: dto.role }), if (dto.clientType !== undefined) changes.clientType = dto.clientType;
...(dto.clientType !== undefined && { clientType: dto.clientType }), if (dto.appName !== undefined) changes.appName = dto.appName;
...(dto.appName !== undefined && { appName: dto.appName }), if (dto.clientName !== undefined) changes.clientName = dto.clientName;
...(dto.clientName !== undefined && { clientName: dto.clientName }), if (dto.isActive !== undefined) changes.isActive = dto.isActive;
...(dto.isActive !== undefined && { isActive: dto.isActive }), if (dto.allowedInquiries !== undefined) changes.allowedInquiries = dto.allowedInquiries;
...(dto.allowedInquiries !== undefined && { allowedInquiries: dto.allowedInquiries }), if (dto.requestLimitPerMinute !== undefined) {
...(dto.requestLimitPerMinute !== undefined && { changes.requestLimitPerMinute = dto.requestLimitPerMinute;
requestLimitPerMinute: dto.requestLimitPerMinute, }
}), if (dto.requestLimitPerDay !== undefined) changes.requestLimitPerDay = dto.requestLimitPerDay;
...(dto.requestLimitPerDay !== undefined && { requestLimitPerDay: dto.requestLimitPerDay }), if (dto.metadata !== undefined) changes.metadata = dto.metadata;
...(dto.metadata !== undefined && { metadata: dto.metadata }),
});
await user.save(); if (Object.keys(changes).length > 0) {
return UserMapper.toResponseDto(user); await this.users.update(user.id, changes as QueryDeepPartialEntity<User>);
}
return UserMapper.toResponseDto(await this.findById(id));
} }
async block( async block(
@@ -145,12 +160,10 @@ export class UsersService {
context: RequestContext = {}, context: RequestContext = {},
): Promise<UserResponseDto> { ): Promise<UserResponseDto> {
const user = await this.findById(id); const user = await this.findById(id);
if (user._id.toString() === actor.id) { if (user.id === actor.id) {
throw new AppException('CANNOT_BLOCK_SELF'); throw new AppException('CANNOT_BLOCK_SELF');
} }
user.isBlocked = true; await this.users.update(user.id, { isBlocked: true, refreshToken: null });
user.refreshToken = undefined;
await user.save();
await this.auditService.log(AuditEvent.USER_BLOCKED, { await this.auditService.log(AuditEvent.USER_BLOCKED, {
actorId: actor.id, actorId: actor.id,
@@ -160,7 +173,7 @@ export class UsersService {
userAgent: context.userAgent, userAgent: context.userAgent,
}); });
return UserMapper.toResponseDto(user); return UserMapper.toResponseDto(await this.findById(id));
} }
async unblock( async unblock(
@@ -169,8 +182,7 @@ export class UsersService {
context: RequestContext = {}, context: RequestContext = {},
): Promise<UserResponseDto> { ): Promise<UserResponseDto> {
const user = await this.findById(id); const user = await this.findById(id);
user.isBlocked = false; await this.users.update(user.id, { isBlocked: false });
await user.save();
await this.auditService.log(AuditEvent.USER_UNBLOCKED, { await this.auditService.log(AuditEvent.USER_UNBLOCKED, {
actorId: actor.id, actorId: actor.id,
@@ -180,7 +192,7 @@ export class UsersService {
userAgent: context.userAgent, userAgent: context.userAgent,
}); });
return UserMapper.toResponseDto(user); return UserMapper.toResponseDto(await this.findById(id));
} }
async resetPassword( async resetPassword(
@@ -189,15 +201,12 @@ export class UsersService {
actor: AuthenticatedUser, actor: AuthenticatedUser,
context: RequestContext = {}, context: RequestContext = {},
): Promise<void> { ): Promise<void> {
const user = await this.userModel.findById(id).select('+password +refreshToken'); const user = await this.findById(id);
if (!user) { await this.users.update(user.id, {
throw new AppException('USER_NOT_FOUND'); password: await this.passwordService.hash(dto.newPassword),
} passwordChangedAt: new Date(),
refreshToken: null,
user.password = await this.passwordService.hash(dto.newPassword); });
user.passwordChangedAt = new Date();
user.refreshToken = undefined;
await user.save();
await this.auditService.log(AuditEvent.PASSWORD_RESET, { await this.auditService.log(AuditEvent.PASSWORD_RESET, {
actorId: actor.id, actorId: actor.id,
@@ -209,16 +218,23 @@ export class UsersService {
} }
async saveRefreshToken(userId: string, refreshToken: string): Promise<void> { async saveRefreshToken(userId: string, refreshToken: string): Promise<void> {
if (!isUuid(userId)) return;
const hash = await this.passwordService.hash(refreshToken); 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<void> { async clearRefreshToken(userId: string): Promise<void> {
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<boolean> { async validateRefreshToken(userId: string, refreshToken: string): Promise<boolean> {
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) { if (!user?.refreshToken) {
return false; return false;
} }
@@ -226,11 +242,13 @@ export class UsersService {
} }
async recordLogin(userId: string): Promise<void> { async recordLogin(userId: string): Promise<void> {
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<void> { async incrementTotalRequests(userId: string): Promise<void> {
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 { private assertCanAssignRole(actorRole: Role, targetRole: Role): void {
+1 -1
View File
@@ -81,7 +81,7 @@ describe('unit helpers and mappers', () => {
it('maps user documents without leaking secrets', () => { it('maps user documents without leaking secrets', () => {
const dto = UserMapper.toResponseDto({ const dto = UserMapper.toResponseDto({
_id: { toString: () => 'user-1' }, id: 'user-1',
fullName: 'Admin User', fullName: 'Admin User',
username: 'admin', username: 'admin',
email: 'admin@example.com', email: 'admin@example.com',
+18 -22
View File
@@ -1,46 +1,42 @@
import { IdempotencyService } from '../../src/idempotency/idempotency.service'; import { IdempotencyService } from '../../src/idempotency/idempotency.service';
import { IdempotencyRecordStatus } from '../../src/idempotency/schemas/idempotency-record.schema'; import { IdempotencyRecordStatus } from '../../src/idempotency/schemas/idempotency-record.schema';
class FakeRecordModel { class FakeRecordRepository {
private readonly records = new Map<string, any>(); private readonly records = new Map<string, any>();
findOne(filter: { scopeHash: string }) { create(record: any) {
return { exec: async () => this.records.get(filter.scopeHash) ?? null }; return { ...record };
} }
async create(record: any) { async findOne(options: { where: { scopeHash: string } }) {
if (this.records.has(record.scopeHash)) { return this.records.get(options.where.scopeHash) ?? null;
throw Object.assign(new Error('duplicate'), { code: 11000 });
} }
const saved = { ...record, _id: record.scopeHash };
async save(record: any) {
if (this.records.has(record.scopeHash)) {
throw Object.assign(new Error('duplicate'), { code: '23505' });
}
const saved = { ...record, id: record.scopeHash };
this.records.set(record.scopeHash, saved); this.records.set(record.scopeHash, saved);
return saved; return saved;
} }
updateOne(filter: { scopeHash: string; status: IdempotencyRecordStatus }, update: any) { async update(filter: { scopeHash: string; status: IdempotencyRecordStatus }, values: any) {
return {
exec: async () => {
const record = this.records.get(filter.scopeHash); const record = this.records.get(filter.scopeHash);
if (record?.status === filter.status) Object.assign(record, update.$set); if (record?.status === filter.status) Object.assign(record, values);
return { acknowledged: true }; return { affected: record ? 1 : 0 };
},
};
} }
deleteOne(filter: { scopeHash: string; status: IdempotencyRecordStatus }) { async delete(filter: { scopeHash: string; status: IdempotencyRecordStatus }) {
return {
exec: async () => {
const record = this.records.get(filter.scopeHash); const record = this.records.get(filter.scopeHash);
if (record?.status === filter.status) this.records.delete(filter.scopeHash); if (record?.status === filter.status) this.records.delete(filter.scopeHash);
return { acknowledged: true }; return { affected: record ? 1 : 0 };
},
};
} }
} }
describe('IdempotencyService', () => { describe('IdempotencyService', () => {
it('replays completed responses and rejects body reuse', async () => { 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 = { const input = {
key: 'request-1', key: 'request-1',
callerId: 'user-1', callerId: 'user-1',
@@ -62,7 +58,7 @@ describe('IdempotencyService', () => {
}); });
it('rejects a duplicate while the original request is in progress', async () => { 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 = { const input = {
key: 'request-2', key: 'request-2',
callerId: 'user-1', callerId: 'user-1',
+103
View File
@@ -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<string, { url: string }>) {
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',
},
}),
);
});
});
+72
View File
@@ -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',
},
});
});
});
+70
View File
@@ -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);
});
});