Compare commits

..
8 Commits
Author SHA1 Message Date
s.hajizadeh ce75792d59 Merge pull request 'feat(providers): add asia person and real estate inquiries' (#19) from s.hajizadeh/esg:main into main
Reviewed-on: Shared/esg#19
2026-10-14 15:27:19 +03:30
s.hajizadeh 3194d6ed59 feat(providers): add asia person and real estate inquiries
Register Asia as a configurable inquiry provider. Use Asia JSON login and cached bearer tokens for person inquiries, and AMITIS credentials for real estate inquiries.

Add credential-free environment examples and tests for request contracts, authentication failures, response validation, and routing.
2026-10-14 15:26:21 +03:30
s.hajizadeh 8ed85bcfb7 Merge pull request 'database migrated to POSTGRESQL' (#18) from s.hajizadeh/esg:main into main
Reviewed-on: Shared/esg#18
2026-10-13 16:19:35 +03:30
s.hajizadeh 514c3ccaf0 database migrated to POSTGRESQL 2026-10-13 16:11:51 +03:30
s.yahyaee 41ad8c1063 Merge pull request 'main' (#17) from s.yahyaee/esg:main into main
Reviewed-on: Shared/esg#17
2026-09-30 17:04:13 +03:30
SepehrYahyaee b344333cba Merge branch 'main' of git.ittalie.com:s.yahyaee/esg 2026-09-30 17:02:58 +03:30
SepehrYahyaee 1c5ae77667 update README 2026-09-30 17:02:35 +03:30
SepehrYahyaee 1ec9b3262d add docs 2026-09-30 17:02:17 +03:30
55 changed files with 1828 additions and 893 deletions
+17
View File
@@ -56,6 +56,9 @@ SHEBA_FALLBACK_PROVIDERS=
CAR_PLATE_DEFAULT_PROVIDER=HAMTA
CAR_PLATE_FALLBACK_ENABLED=true
CAR_PLATE_FALLBACK_PROVIDERS=
CAR_BY_MOTOR_DEFAULT_PROVIDER=PARSIAN
CAR_BY_MOTOR_FALLBACK_ENABLED=false
CAR_BY_MOTOR_FALLBACK_PROVIDERS=
POLICY_BY_CHASSIS_DEFAULT_PROVIDER=PARSIAN
POLICY_BY_CHASSIS_FALLBACK_ENABLED=false
POLICY_BY_CHASSIS_FALLBACK_PROVIDERS=
@@ -125,3 +128,17 @@ TEJARATNOU_USERNAME=your_username
TEJARATNOU_PASSWORD=your_password
TEJARATNOU_TIMEOUT=15000
TEJARATNOU_ENABLED=true
# Asia: person uses Asia login; real estate uses CentInsur AMITIS login.
ASIA_ENABLED=true
ASIA_TIMEOUT=15000
ASIA_MAX_RETRIES=3
ASIA_LOGIN_URL=https://api.bimehasia.ir/v1/login
ASIA_PERSON_URL=https://api.bimehasia.ir/v1/sanhab/sabtahval
ASIA_PERSON_USERNAME=
ASIA_PERSON_PASSWORD=
ASIA_PERSON_AUTH_METHOD=ASIA
ASIA_REAL_ESTATE_URL=https://apigw.services.centinsur.ir/amlakeskanservice/amlakeskan/inquiry
ASIA_REAL_ESTATE_USERNAME=
ASIA_REAL_ESTATE_PASSWORD=
ASIA_REAL_ESTATE_AUTH_METHOD=AMITIS
+4 -1
View File
@@ -81,7 +81,7 @@ The dashboard includes a SUPER_ADMIN-only “clear inquiry logs” action. It is
Each expanded inquiry log also shows the outbound provider calls made underneath the gateway (including retries, fallbacks, and authentication calls). The endpoint, HTTP status, response preview, and a copyable **safe cURL** are shown per call. XML request and response bodies have local formatted/raw, XML-to-JSON, and scoped search views for SOAP troubleshooting. Credentials and authorization tokens are redacted intentionally; replace the `<REDACTED>` placeholders before running a copied command manually.
The **Batch input** panel accepts a JSON/TXT file or pasted JSON. It supports the `data` wrapper used by the current vehicle file, including fields such as `national_code`, `plaque_2`, `letter`, `plaque_3`, and `iran`. For Parsian third-party plate production traffic, `carByPlate` is the canonical one-factor route. `thirdPartyCar` and `policyByPlate` remain available for diagnostics/backward compatibility, but are not used by the sibling API integration. Every batch request uses the normal authenticated inquiry endpoint and creates its normal inquiry log. A delay can be configured to avoid overwhelming restricted provider services.
The **Batch input** panel accepts a JSON/TXT file or pasted JSON and supports the `data` wrapper used by the current vehicle file. It recognizes `national_code`, `plaque_2`, `letter`, `plaque_3`, `iran`, `vin`, and motor aliases such as `motorNo`, `motor_number`, and `engineNo` (plus the gateway camelCase aliases). Choose **By plate**, **By chassis / VIN**, **By motor number**, **Plate and chassis**, or **Plate, chassis, and motor**. In a combined plate + VIN run, coverage is calculated per input record: either lookup succeeding counts as answered, both returning no-match counts as no-answer, and operational/validation failures remain inconclusive. No-answer records are visually highlighted, can be filtered, and expose a **Test motor** follow-up without changing the original plate + VIN coverage figure. Each response still has its own expandable logs, outbound traces, and cURLs. Every batch request uses the normal authenticated endpoint and creates its normal inquiry log.
## Authentication & users
@@ -157,6 +157,9 @@ See [Environment Configuration Guide](docs/ENVIRONMENT_CONFIGURATION.md) for com
| `CIVIL_REGISTRATION_INQUIRY` | MOALLEM | Civil registration data |
| `SHEBA_INQUIRY` | PARSIAN, HAMTA, MOALLEM | Bank account (SHEBA) validation |
| `SAYAH_INQUIRY` | TEJARATNOU | Sayah system inquiry |
| `CAR_BY_PLATE_INQUIRY` | PARSIAN | Car policy lookup by plate with national-code ownership validation |
| `CAR_BY_CHASSIS_INQUIRY` | PARSIAN | Car policy lookup by VIN/chassis with national-code ownership validation |
| `CAR_BY_MOTOR_INQUIRY` | PARSIAN | Car policy lookup by motor number with national-code ownership validation |
| `POLICY_BY_CHASSIS_INQUIRY` | PARSIAN | Car policy history by chassis number |
| `POLICY_BY_PLATE_INQUIRY` | PARSIAN | Car policy history by national plate |
| `POLICY_BY_NATIONAL_CODE_INQUIRY` | PARSIAN | Car policy history by national code |
+17
View File
@@ -405,6 +405,23 @@ curl -X POST https://api.example.com/api/inquiry/sheba \
}'
```
## Car Insurance By Motor Number
### Endpoint
```
POST /api/inquiry/carByMotor
```
The Parsian provider calls the `CIIWSPolicyMotor` SOAP operation and only returns the policy when its owner national code matches the request.
### Request Body
```json
{
"nationalCode": "0123456789",
"motorNo": "147H0403219"
}
```
## Car Policy By Chassis
### Endpoint
+5
View File
@@ -220,6 +220,11 @@ PARSIAN_SHEBA_USERNAME=parsian.sayah
PARSIAN_SHEBA_PASSWORD=your-password
PARSIAN_SHEBA_AUTH_METHOD=AMITIS
# Car-by-motor routing (reuses the configured Parsian car-policy SOAP URL and credentials)
CAR_BY_MOTOR_DEFAULT_PROVIDER=PARSIAN
CAR_BY_MOTOR_FALLBACK_ENABLED=false
CAR_BY_MOTOR_FALLBACK_PROVIDERS=
# Car policy inquiry by chassis (SOAP auth)
PARSIAN_POLICY_BY_CHASSIS_URL=http://reinsure.centinsur.ir/CarAllPlcysV4
PARSIAN_POLICY_BY_CHASSIS_USERNAME=pa6476
+4 -5
View File
@@ -1,6 +1,7 @@
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { typeOrmConfig } from './database/typeorm.config';
import { CommonModule } from './common/common.module';
import { RequestIdMiddleware } from './common/middleware/request-id.middleware';
import { AppConfigModule } from './config/config.module';
@@ -23,11 +24,9 @@ import { IdempotencyModule } from './idempotency/idempotency.module';
AppConfigModule,
CommonModule,
AuditModule,
MongooseModule.forRootAsync({
TypeOrmModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
uri: config.get<string>('mongodb.uri'),
}),
useFactory: typeOrmConfig,
}),
RateLimitModule,
LoggingModule,
+3 -3
View File
@@ -1,11 +1,11 @@
import { Global, Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuditService } from './audit.service';
import { AuditLog, AuditLogSchema } from './schemas/audit-log.schema';
import { AuditLog } from './schemas/audit-log.schema';
@Global()
@Module({
imports: [MongooseModule.forFeature([{ name: AuditLog.name, schema: AuditLogSchema }])],
imports: [TypeOrmModule.forFeature([AuditLog])],
providers: [AuditService],
exports: [AuditService],
})
+12 -9
View File
@@ -1,8 +1,9 @@
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AuditEvent } from '../common/enums/audit-event.enum';
import { AuditLog, AuditLogDocument } from './schemas/audit-log.schema';
import { isUuid } from '../database/postgres.helpers';
import { AuditLog } from './schemas/audit-log.schema';
export interface AuditContext {
userId?: string;
@@ -19,19 +20,21 @@ export interface AuditContext {
@Injectable()
export class AuditService {
constructor(
@InjectModel(AuditLog.name)
private readonly auditModel: Model<AuditLogDocument>,
@InjectRepository(AuditLog)
private readonly auditLogs: Repository<AuditLog>,
) {}
async log(event: AuditEvent, context: AuditContext = {}): Promise<void> {
await this.auditModel.create({
await this.auditLogs.save(
this.auditLogs.create({
event,
userId: context.userId ? new Types.ObjectId(context.userId) : undefined,
actorId: context.actorId ? new Types.ObjectId(context.actorId) : undefined,
userId: isUuid(context.userId) ? context.userId : null,
actorId: isUuid(context.actorId) ? context.actorId : null,
username: context.username,
ip: context.ip,
userAgent: context.userAgent,
metadata: context.metadata ?? {},
});
}),
);
}
}
+24 -22
View File
@@ -1,37 +1,39 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument, Types } from 'mongoose';
import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
import { AuditEvent } from '../../common/enums/audit-event.enum';
export type AuditLogDocument = HydratedDocument<AuditLog>;
/**
* Immutable security audit trail — separate from inquiry_logs (business audit).
*/
@Schema({ timestamps: { createdAt: true, updatedAt: false }, collection: 'audit_logs' })
@Entity('audit_logs')
@Index(['createdAt'])
@Index(['event', 'createdAt'])
export class AuditLog {
@Prop({ required: true, enum: AuditEvent, index: true })
@PrimaryGeneratedColumn('uuid')
id!: string;
@Index()
@Column({ type: 'text' })
event!: AuditEvent;
@Prop({ type: Types.ObjectId, ref: 'User', index: true })
userId?: Types.ObjectId;
@Index()
@Column({ type: 'uuid', nullable: true })
userId?: string | null;
@Prop({ type: Types.ObjectId, ref: 'User' })
actorId?: Types.ObjectId;
@Column({ type: 'uuid', nullable: true })
actorId?: string | null;
@Prop()
username?: string;
@Column({ type: 'text', nullable: true })
username?: string | null;
@Prop()
ip?: string;
@Column({ type: 'text', nullable: true })
ip?: string | null;
@Prop()
userAgent?: string;
@Column({ type: 'text', nullable: true })
userAgent?: string | null;
@Prop({ type: Object, default: {} })
@Column({ type: 'jsonb', default: () => "'{}'::jsonb" })
metadata!: Record<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) {
await this.auditFailedLogin(user._id.toString(), user.username, 'inactive', context);
await this.auditFailedLogin(user.id, user.username, 'inactive', context);
throw new AppException('ACCOUNT_INACTIVE');
}
if (user.isBlocked) {
await this.auditFailedLogin(user._id.toString(), user.username, 'blocked', context);
await this.auditFailedLogin(user.id, user.username, 'blocked', context);
throw new AppException('ACCOUNT_BLOCKED');
}
const valid = await this.passwordService.compare(dto.password, user.password);
if (!valid) {
await this.auditFailedLogin(user._id.toString(), user.username, 'invalid_credentials', context);
await this.auditFailedLogin(user.id, user.username, 'invalid_credentials', context);
throw new AppException('INVALID_CREDENTIALS');
}
const tokens = await this.issueTokens(user);
await this.usersService.saveRefreshToken(user._id.toString(), tokens.refreshToken);
await this.usersService.recordLogin(user._id.toString());
await this.usersService.saveRefreshToken(user.id, tokens.refreshToken);
await this.usersService.recordLogin(user.id);
await this.auditService.log(AuditEvent.LOGIN, {
userId: user._id.toString(),
userId: user.id,
username: user.username,
ip: context.ip,
userAgent: context.userAgent,
@@ -86,10 +86,10 @@ export class AuthService {
}
const tokens = await this.issueTokens(user);
await this.usersService.saveRefreshToken(user._id.toString(), tokens.refreshToken);
await this.usersService.saveRefreshToken(user.id, tokens.refreshToken);
await this.auditService.log(AuditEvent.LOGIN, {
userId: user._id.toString(),
userId: user.id,
username: user.username,
ip: context.ip,
userAgent: context.userAgent,
@@ -117,13 +117,13 @@ export class AuthService {
}
private async issueTokens(user: {
_id: { toString(): string };
id: string;
role: JwtPayload['role'];
clientType: JwtPayload['clientType'];
appName: string;
}): Promise<AuthTokensDto> {
const payload: JwtPayload = {
sub: user._id.toString(),
sub: user.id,
role: user.role,
clientType: user.clientType,
appName: user.appName,
+1 -1
View File
@@ -35,7 +35,7 @@ export class JwtStrategy extends PassportStrategy(Strategy, JWT_ACCESS_STRATEGY)
}
return {
id: user._id.toString(),
id: user.id,
username: user.username,
email: user.email,
role: user.role,
+7 -8
View File
@@ -1,9 +1,10 @@
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { ConfigService } from '@nestjs/config';
import { AppConfigModule } from '../config/config.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { PasswordService } from '../auth/services/password.service';
import { User, UserSchema } from '../users/schemas/user.schema';
import { AppConfigModule } from '../config/config.module';
import { typeOrmConfig } from '../database/typeorm.config';
import { User } from '../users/schemas/user.schema';
import { CreateSuperAdminService } from './create-super-admin.service';
/**
@@ -13,13 +14,11 @@ import { CreateSuperAdminService } from './create-super-admin.service';
@Module({
imports: [
AppConfigModule,
MongooseModule.forRootAsync({
TypeOrmModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
uri: config.get<string>('mongodb.uri'),
useFactory: typeOrmConfig,
}),
}),
MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
TypeOrmModule.forFeature([User]),
],
providers: [CreateSuperAdminService, PasswordService],
})
+19 -10
View File
@@ -1,14 +1,15 @@
import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { InjectRepository } from '@nestjs/typeorm';
import { randomBytes } from 'crypto';
import { Repository } from 'typeorm';
import { ClientType } from '../common/enums/client-type.enum';
import { Role } from '../common/enums/role.enum';
import { AppException } from '../common/exceptions/app-exception';
import { isUniqueViolation } from '../database/postgres.helpers';
import { PasswordService } from '../auth/services/password.service';
import { User, UserDocument } from '../users/schemas/user.schema';
import { User } from '../users/schemas/user.schema';
import { UserMapper } from '../users/mappers/user.mapper';
import { UserResponseDto } from '../users/dto/user-response.dto';
import { AppException } from '../common/exceptions/app-exception';
export interface CreateSuperAdminInput {
fullName: string;
@@ -22,7 +23,7 @@ export class CreateSuperAdminService {
private readonly logger = new Logger(CreateSuperAdminService.name);
constructor(
@InjectModel(User.name) private readonly userModel: Model<UserDocument>,
@InjectRepository(User) private readonly users: Repository<User>,
private readonly passwordService: PasswordService,
) {}
@@ -34,19 +35,21 @@ export class CreateSuperAdminService {
const username = input.username.toLowerCase().trim();
const email = input.email.toLowerCase().trim();
const existing = await this.userModel.findOne({ $or: [{ username }, { email }] });
const existing = await this.users.findOne({ where: [{ username }, { email }] });
if (existing) {
throw new AppException('USERNAME_OR_EMAIL_EXISTS');
}
const superAdminExists = await this.userModel.exists({ role: Role.SUPER_ADMIN });
const superAdminExists = await this.users.exists({ where: { role: Role.SUPER_ADMIN } });
if (superAdminExists) {
this.logger.warn('A SUPER_ADMIN already exists; creating another.');
}
const passwordHash = await this.passwordService.hash(input.password);
const user = await this.userModel.create({
try {
const user = await this.users.save(
this.users.create({
fullName: input.fullName.trim(),
username,
email,
@@ -60,8 +63,14 @@ export class CreateSuperAdminService {
allowedInquiries: [],
apiKey: `esg_${randomBytes(32).toString('hex')}`,
passwordChangedAt: new Date(),
});
}),
);
return UserMapper.toResponseDto(user);
} catch (error) {
if (isUniqueViolation(error)) {
throw new AppException('USERNAME_OR_EMAIL_EXISTS');
}
throw error;
}
}
}
+1
View File
@@ -3,6 +3,7 @@
* Used by factory, configuration, and response normalization.
*/
export enum ProviderName {
ASIA = 'ASIA',
HAMTA = 'HAMTA',
MOALLEM = 'MOALLEM',
PARSIAN = 'PARSIAN',
+1 -1
View File
@@ -12,7 +12,7 @@ export interface RequestLogContext {
/**
* Structured console logging for inquiry lifecycle events.
* Complements MongoDB persistence in LoggingModule.
* Complements inquiry log persistence in LoggingModule.
*/
export class RequestLogger {
private readonly logger: Logger;
@@ -68,6 +68,10 @@ function translateValidationConstraint(field: string, constraint: string): strin
return 'تاریخ تولد باید با فرمت YYYY-MM-DD باشد';
}
if (constraint.includes('birthDate must be in YYYY or YYYY-MM-DD format')) {
return 'تاریخ تولد باید با فرمت YYYY یا YYYY-MM-DD باشد';
}
if (constraint.includes('birthDate must be in YYYY-MM-DD or YYYYMMDD format')) {
return 'تاریخ تولد باید با فرمت YYYY-MM-DD یا YYYYMMDD باشد';
}
+17 -4
View File
@@ -1,7 +1,11 @@
import { InquiryType } from '../common/enums/inquiry-type.enum';
import { ProviderName } from '../common/enums/provider-name.enum';
export type AuthMethod = 'AMITIS' | 'SOAP' | 'OAUTH2' | 'NONE';
export type AuthMethod = 'AMITIS' | 'ASIA' | 'SOAP' | 'OAUTH2' | 'NONE';
export interface AsiaConfig extends ProviderEnvConfig {
loginUrl: string;
}
export interface InquiryConfig {
url: string;
@@ -37,6 +41,7 @@ export interface TejaratNouConfig {
clientSecret: string;
username: string;
password: string;
inquiries: Partial<Record<InquiryType, InquiryConfig>>;
}
export interface InquiryRoutingConfig {
@@ -54,8 +59,8 @@ export default () => ({
port: parseInt(process.env.PORT ?? '8085', 10),
nodeEnv: process.env.NODE_ENV ?? 'development',
},
mongodb: {
uri: process.env.MONGODB_URI ?? 'mongodb://localhost:27017/inquiry-gateway',
database: {
url: process.env.DATABASE_URL ?? 'postgresql://esg:esg@localhost:5432/inquiry_gateway',
},
auth: {
apiKey: process.env.API_KEY ?? '',
@@ -79,6 +84,10 @@ export default () => ({
timeout: parseInt(process.env.AMITIS_TIMEOUT ?? '10000', 10),
enabled: process.env.AMITIS_ENABLED !== 'false',
} satisfies AmitisAuthServiceConfig,
asia: {
...buildProviderConfig('ASIA'),
loginUrl: process.env.ASIA_LOGIN_URL ?? 'https://api.bimehasia.ir/v1/login',
} satisfies AsiaConfig,
hamta: buildProviderConfig('HAMTA'),
moallem: buildProviderConfig('MOALLEM'),
parsian: buildProviderConfig('PARSIAN'),
@@ -86,13 +95,17 @@ export default () => ({
enabled: process.env.TEJARATNOU_ENABLED !== 'false',
timeout: parseInt(process.env.TEJARATNOU_TIMEOUT ?? '15000', 10),
maxRetries: parseInt(process.env.TEJARATNOU_MAX_RETRIES ?? '3', 10),
baseUrl: process.env.TEJARATNOU_BASE_URL ?? 'https://accounts.tejaratnoins.ir',
baseUrl:
process.env.TEJARATNOU_BASE_URL ??
process.env.TEJARATNOU_AUTH_URL ??
'https://accounts.tejaratnoins.ir',
inquiryBaseUrl:
process.env.TEJARATNOU_INQUIRY_BASE_URL ?? 'https://gateway.tejaratnoins.ir',
clientId: process.env.TEJARATNOU_CLIENT_ID ?? 'api-gateway',
clientSecret: process.env.TEJARATNOU_CLIENT_SECRET ?? '',
username: process.env.TEJARATNOU_USERNAME ?? '',
password: process.env.TEJARATNOU_PASSWORD ?? '',
inquiries: buildProviderConfig('TEJARATNOU').inquiries,
} satisfies TejaratNouConfig,
inquiryRouting: {
[InquiryType.PERSON]: buildInquiryRoutingConfig('PERSON', ProviderName.PARSIAN, [
+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 { MongooseModule } from '@nestjs/mongoose';
import { User, UserSchema } from '../users/schemas/user.schema';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from '../users/schemas/user.schema';
import { DatabaseSeederService } from './database-seeder.service';
@Module({
imports: [MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])],
imports: [TypeOrmModule.forFeature([User])],
providers: [DatabaseSeederService],
})
export class DatabaseSeederModule {}
+48 -20
View File
@@ -1,9 +1,10 @@
import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { InjectRepository } from '@nestjs/typeorm';
import { existsSync, readFileSync } from 'fs';
import { join } from 'path';
import { Model, Types } from 'mongoose';
import { User, UserDocument } from '../users/schemas/user.schema';
import { DeepPartial, Repository } from 'typeorm';
import { isUuid } from '../database/postgres.helpers';
import { User } from '../users/schemas/user.schema';
type ExtendedJsonValue =
| string
@@ -14,7 +15,7 @@ type ExtendedJsonValue =
| { [key: string]: ExtendedJsonValue };
interface SeedUser {
_id?: Types.ObjectId;
id?: string;
fullName: string;
username: string;
email: string;
@@ -32,7 +33,7 @@ interface SeedUser {
requestLimitPerDay: number;
totalRequests?: number;
passwordChangedAt?: Date;
createdBy?: Types.ObjectId;
createdBy?: string | null;
createdAt?: Date;
updatedAt?: Date;
lastLoginAt?: Date;
@@ -44,7 +45,7 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
private readonly logger = new Logger(DatabaseSeederService.name);
private readonly usersSeedFile = 'inquiry-gateway.users.json';
constructor(@InjectModel(User.name) private readonly userModel: Model<UserDocument>) {}
constructor(@InjectRepository(User) private readonly users: Repository<User>) {}
async onApplicationBootstrap(): Promise<void> {
await this.seedUsers();
@@ -52,12 +53,17 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
private async seedUsers(): Promise<void> {
const users = this.loadSeedUsers();
if (!users) {
this.logger.warn(`Seed file ${this.usersSeedFile} not found; skipping baseline user seed.`);
return;
}
let inserted = 0;
let skipped = 0;
for (const user of users) {
const existing = await this.userModel.exists({
$or: [{ _id: user._id }, { username: user.username }, { email: user.email }],
const existing = await this.users.findOne({
where: [{ username: user.username }, { email: user.email }],
});
if (existing) {
@@ -65,7 +71,7 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
continue;
}
await this.userModel.create(user);
await this.users.save(this.users.create(user as DeepPartial<User>));
inserted += 1;
}
@@ -77,8 +83,10 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
this.logger.log(`Baseline users already exist; skipped ${skipped} user(s).`);
}
private loadSeedUsers(): SeedUser[] {
private loadSeedUsers(): SeedUser[] | null {
const seedPath = this.resolveSeedPath();
if (!seedPath) return null;
const raw = readFileSync(seedPath, 'utf8');
const parsed = JSON.parse(raw) as ExtendedJsonValue;
const normalized = this.normalizeExtendedJson(parsed);
@@ -92,27 +100,46 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
throw new Error(`${this.usersSeedFile} contains an invalid user document`);
}
const rawId = (user as SeedUser & { _id?: string })._id ?? user.id;
const id = typeof rawId === 'string' && isUuid(rawId) ? rawId : undefined;
const createdBy = typeof user.createdBy === 'string' && isUuid(user.createdBy) ? user.createdBy : null;
return {
...user,
...(id ? { id } : {}),
fullName: user.fullName,
username: user.username.toLowerCase().trim(),
email: user.email.toLowerCase().trim(),
mobile: user.mobile,
password: user.password,
role: user.role,
clientType: user.clientType,
appName: user.appName ?? '',
clientName: user.clientName ?? '',
isActive: user.isActive,
isBlocked: user.isBlocked,
apiKey: user.apiKey,
allowedInquiries: user.allowedInquiries,
requestLimitPerMinute: user.requestLimitPerMinute,
requestLimitPerDay: user.requestLimitPerDay,
totalRequests: user.totalRequests ?? 0,
passwordChangedAt: user.passwordChangedAt,
createdBy,
createdAt: user.createdAt,
updatedAt: user.updatedAt,
lastLoginAt: user.lastLoginAt,
refreshToken: user.refreshToken,
};
});
}
private resolveSeedPath(): string {
private resolveSeedPath(): string | undefined {
const candidates = [
join(__dirname, 'seeds', this.usersSeedFile),
join(process.cwd(), 'src', 'database', 'seeds', this.usersSeedFile),
join(process.cwd(), 'dist', 'database', 'seeds', this.usersSeedFile),
];
const seedPath = candidates.find((candidate) => existsSync(candidate));
if (!seedPath) {
throw new Error(`Unable to find seed file: ${this.usersSeedFile}`);
}
return seedPath;
return candidates.find((candidate) => existsSync(candidate));
}
private normalizeExtendedJson(value: ExtendedJsonValue): unknown {
@@ -125,7 +152,7 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
}
if (typeof value.$oid === 'string') {
return new Types.ObjectId(value.$oid);
return value.$oid;
}
if (typeof value.$date === 'string') {
@@ -133,12 +160,13 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
}
return Object.entries(value).reduce<Record<string, unknown>>((acc, [key, child]) => {
if (key === '__v') return acc;
acc[key] = this.normalizeExtendedJson(child);
return acc;
}, {});
}
private isSeedUser(value: unknown): value is SeedUser {
private isSeedUser(value: unknown): value is SeedUser & { _id?: string; createdBy?: string } {
if (!value || typeof value !== 'object') {
return false;
}
@@ -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,
HealthCheckService,
MemoryHealthIndicator,
MongooseHealthIndicator,
TypeOrmHealthIndicator,
} from '@nestjs/terminus';
import { HealthService } from './health.service';
@@ -12,7 +12,7 @@ import { HealthService } from './health.service';
export class HealthController {
constructor(
private readonly health: HealthCheckService,
private readonly mongoose: MongooseHealthIndicator,
private readonly database: TypeOrmHealthIndicator,
private readonly memory: MemoryHealthIndicator,
private readonly disk: DiskHealthIndicator,
private readonly healthService: HealthService,
@@ -28,7 +28,7 @@ export class HealthController {
@HealthCheck({ swaggerDocumentation: false })
readiness() {
return this.health.check([
() => this.mongoose.pingCheck('mongodb', { timeout: 1000 }),
() => this.database.pingCheck('postgres', { timeout: 1000 }),
() => this.memory.checkHeap('memory_heap', this.healthService.heapThresholdBytes()),
() =>
this.disk.checkStorage('disk', {
+1 -2
View File
@@ -1,11 +1,10 @@
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { TerminusModule } from '@nestjs/terminus';
import { HealthController } from './health.controller';
import { HealthService } from './health.service';
@Module({
imports: [TerminusModule.forRoot(), MongooseModule],
imports: [TerminusModule.forRoot()],
controllers: [HealthController],
providers: [HealthService],
})
+3 -10
View File
@@ -1,18 +1,11 @@
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { TypeOrmModule } from '@nestjs/typeorm';
import { IdempotencyInterceptor } from './idempotency.interceptor';
import { IdempotencyService } from './idempotency.service';
import {
IdempotencyRecord,
IdempotencyRecordSchema,
} from './schemas/idempotency-record.schema';
import { IdempotencyRecord } from './schemas/idempotency-record.schema';
@Module({
imports: [
MongooseModule.forFeature([
{ name: IdempotencyRecord.name, schema: IdempotencyRecordSchema },
]),
],
imports: [TypeOrmModule.forFeature([IdempotencyRecord])],
providers: [IdempotencyService, IdempotencyInterceptor],
exports: [IdempotencyService, IdempotencyInterceptor],
})
+95 -50
View File
@@ -1,11 +1,11 @@
import { createHash } from 'node:crypto';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { QueryDeepPartialEntity, Repository } from 'typeorm';
import { AppException } from '../common/exceptions/app-exception';
import { isUniqueViolation } from '../database/postgres.helpers';
import {
IdempotencyRecord,
IdempotencyRecordDocument,
IdempotencyRecordStatus,
} from './schemas/idempotency-record.schema';
@@ -31,16 +31,30 @@ export interface IdempotencyBeginResult {
const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
const IN_PROGRESS_TTL_MS = 5 * 60 * 1000;
const CLEANUP_INTERVAL_MS = 15 * 60 * 1000;
@Injectable()
export class IdempotencyService {
export class IdempotencyService implements OnModuleInit, OnModuleDestroy {
private readonly ttlMs = this.readPositiveEnv('IDEMPOTENCY_TTL_MS', DEFAULT_TTL_MS);
private cleanupTimer?: NodeJS.Timeout;
constructor(
@InjectModel(IdempotencyRecord.name)
private readonly recordModel: Model<IdempotencyRecordDocument>,
@InjectRepository(IdempotencyRecord)
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> {
const key = input.key.trim();
if (!key || key.length > 256) {
@@ -52,23 +66,32 @@ export class IdempotencyService {
const scopeHash = this.hash(`${input.callerId}:${input.method}:${input.path}:${key}`);
const requestFingerprint = this.hash(this.stableStringify(input.body));
const now = Date.now();
const expiresAt = new Date(now + this.ttlMs);
const inProgressExpiresAt = new Date(now + Math.min(this.ttlMs, IN_PROGRESS_TTL_MS));
let record = await this.records.findOne({ where: { scopeHash } });
if (record && record.expiresAt.getTime() <= now) {
if (await this.reclaim(record.id, requestFingerprint, inProgressExpiresAt, input.requestId)) {
return { scopeHash };
}
record = await this.records.findOne({ where: { scopeHash } });
}
let record = await this.recordModel.findOne({ scopeHash }).exec();
let created = false;
if (!record) {
if (!record || record.expiresAt.getTime() <= now) {
try {
record = await this.recordModel.create({
record = await this.records.save(
this.records.create({
scopeHash,
requestFingerprint,
status: IdempotencyRecordStatus.IN_PROGRESS,
expiresAt: new Date(now + Math.min(this.ttlMs, IN_PROGRESS_TTL_MS)),
expiresAt: inProgressExpiresAt,
requestId: input.requestId,
});
}),
);
created = true;
} catch (error) {
if (!this.isDuplicateKey(error)) throw error;
record = await this.recordModel.findOne({ scopeHash }).exec();
if (!isUniqueViolation(error)) throw error;
record = await this.records.findOne({ where: { scopeHash } });
}
}
@@ -78,6 +101,13 @@ export class IdempotencyService {
if (created) return { scopeHash };
if (record.expiresAt.getTime() <= now) {
if (await this.reclaim(record.id, requestFingerprint, inProgressExpiresAt, input.requestId)) {
return { scopeHash };
}
throw new AppException('IDEMPOTENCY_REQUEST_IN_PROGRESS');
}
if (record.requestFingerprint !== requestFingerprint) {
throw new AppException('IDEMPOTENCY_KEY_REUSED');
}
@@ -93,47 +123,66 @@ export class IdempotencyService {
};
}
if (record.expiresAt.getTime() <= now) {
const reclaimed = await this.recordModel
.findOneAndUpdate(
{ _id: record._id, expiresAt: { $lte: new Date(now) } },
{
$set: {
requestFingerprint,
status: IdempotencyRecordStatus.IN_PROGRESS,
expiresAt,
requestId: input.requestId,
},
},
{ new: true },
)
.exec();
if (reclaimed) return { scopeHash };
}
throw new AppException('IDEMPOTENCY_REQUEST_IN_PROGRESS');
}
async complete(scopeHash: string, responseBody: unknown, responseStatus = 200): Promise<void> {
await this.recordModel
.updateOne(
{ scopeHash, status: IdempotencyRecordStatus.IN_PROGRESS },
{
$set: {
const values: QueryDeepPartialEntity<IdempotencyRecord> = {
status: IdempotencyRecordStatus.COMPLETED,
responseStatus,
responseBody,
responseBody: this.asJsonObject(responseBody) as QueryDeepPartialEntity<
IdempotencyRecord
>['responseBody'],
expiresAt: new Date(Date.now() + this.ttlMs),
},
},
)
.exec();
};
await this.records.update(
{ scopeHash, status: IdempotencyRecordStatus.IN_PROGRESS },
values,
);
}
async abandon(scopeHash: string): Promise<void> {
await this.recordModel
.deleteOne({ scopeHash, status: IdempotencyRecordStatus.IN_PROGRESS })
.exec();
await this.records.delete({ scopeHash, status: IdempotencyRecordStatus.IN_PROGRESS });
}
private async reclaim(
id: string,
requestFingerprint: string,
expiresAt: Date,
requestId?: string,
): Promise<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 {
@@ -150,10 +199,6 @@ export class IdempotencyService {
.join(',')}}`;
}
private isDuplicateKey(error: unknown): boolean {
return Boolean(error && typeof error === 'object' && 'code' in error && (error as { code?: number }).code === 11000);
}
private readPositiveEnv(name: string, fallback: number): number {
const value = Number.parseInt(process.env[name] ?? '', 10);
return Number.isFinite(value) && value > 0 ? value : fallback;
@@ -1,36 +1,41 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument, Schema as MongooseSchema } from 'mongoose';
export type IdempotencyRecordDocument = HydratedDocument<IdempotencyRecord>;
import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn, UpdateDateColumn } from 'typeorm';
export enum IdempotencyRecordStatus {
IN_PROGRESS = 'IN_PROGRESS',
COMPLETED = 'COMPLETED',
}
@Schema({ timestamps: true, collection: 'idempotency_records' })
@Entity('idempotency_records')
export class IdempotencyRecord {
@Prop({ required: true, unique: true, index: true })
@PrimaryGeneratedColumn('uuid')
id!: string;
@Index({ unique: true })
@Column({ type: 'text' })
scopeHash!: string;
@Prop({ required: true })
@Column({ type: 'text' })
requestFingerprint!: string;
@Prop({ required: true, enum: IdempotencyRecordStatus })
@Column({ type: 'text' })
status!: IdempotencyRecordStatus;
@Prop({ required: true })
@Index()
@Column({ type: 'timestamptz' })
expiresAt!: Date;
@Prop()
responseStatus?: number;
@Column({ type: 'int', nullable: true })
responseStatus?: number | null;
@Prop({ type: MongooseSchema.Types.Mixed })
responseBody?: unknown;
@Column({ type: 'jsonb', nullable: true })
responseBody?: Record<string, unknown> | null;
@Prop()
requestId?: string;
@Column({ type: 'text', nullable: true })
requestId?: string | null;
@CreateDateColumn({ type: 'timestamptz' })
createdAt!: Date;
@UpdateDateColumn({ type: 'timestamptz' })
updatedAt!: Date;
}
export const IdempotencyRecordSchema = SchemaFactory.createForClass(IdempotencyRecord);
IdempotencyRecordSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 });
@@ -9,8 +9,13 @@ export class PersonInquiryRequestDto {
@Matches(/^\d{10}$/, { message: 'nationalCode must be exactly 10 digits' })
nationalCode!: string;
@ApiProperty({ example: '1378-11-24', description: 'Jalali birth date (YYYY-MM-DD)' })
@Matches(/^\d{4}-\d{2}-\d{2}$/, { message: 'birthDate must be in YYYY-MM-DD format' })
@ApiProperty({
example: '1378-11-24',
description: 'Jalali birth date (YYYY-MM-DD) or Jalali birth year (YYYY)',
})
@Matches(/^\d{4}(-\d{2}-\d{2})?$/, {
message: 'birthDate must be in YYYY or YYYY-MM-DD format',
})
@IsNotEmpty()
birthDate!: string;
+224 -299
View File
@@ -1,22 +1,19 @@
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { FilterQuery, Model } from 'mongoose';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AttemptSummaryDto } from '../common/dto/attempt-summary.dto';
import {
InquiryStatus,
NO_MATCH_ERROR_CODES,
} from '../common/enums/inquiry-status.enum';
import { InquiryStatus, NO_MATCH_ERROR_CODES } from '../common/enums/inquiry-status.enum';
import { InquiryType } from '../common/enums/inquiry-type.enum';
import { ProviderName } from '../common/enums/provider-name.enum';
import { maskPayload } from '../common/helpers/mask-payload.helper';
import type { OutboundRequestTrace } from '../common/helpers/http-client.helper';
import {
InquiryLogQueryDto,
InquiryLogTimelineQueryDto,
LogTimelineInterval,
LogTimeRangePreset,
} from './dto/inquiry-log-query.dto';
import { InquiryLog, InquiryLogDocument } from './schemas/inquiry-log.schema';
import type { OutboundRequestTrace } from '../common/helpers/http-client.helper';
import { InquiryLog } from './schemas/inquiry-log.schema';
export interface CreateInquiryLogInput {
inquiryType: InquiryType;
@@ -94,20 +91,32 @@ export interface TimelineBucket {
@Injectable()
export class InquiryLogService {
constructor(
@InjectModel(InquiryLog.name)
private readonly inquiryLogModel: Model<InquiryLogDocument>,
@InjectRepository(InquiryLog)
private readonly inquiryLogs: Repository<InquiryLog>,
) {}
async create(input: CreateInquiryLogInput): Promise<InquiryLogDocument> {
return this.inquiryLogModel.create({
...input,
async create(input: CreateInquiryLogInput): Promise<InquiryLog> {
return this.inquiryLogs.save(
this.inquiryLogs.create({
inquiryType: input.inquiryType,
provider: input.provider,
requestPayload: input.requestPayload,
maskedRequest: maskPayload(input.requestPayload),
});
responsePayload: input.responsePayload ?? null,
status: input.status,
duration: input.duration,
requestId: input.requestId,
trackingCode: input.trackingCode,
error: input.error ?? null,
attemptSummary: (input.attemptSummary as Record<string, unknown> | undefined) ?? null,
outboundRequests: (input.outboundRequests as Record<string, unknown>[] | undefined) ?? null,
}),
);
}
async purgeAll(): Promise<{ deletedCount: number }> {
const result = await this.inquiryLogModel.deleteMany({}).exec();
return { deletedCount: result.deletedCount ?? 0 };
const result = await this.inquiryLogs.createQueryBuilder().delete().from(InquiryLog).execute();
return { deletedCount: result.affected ?? 0 };
}
async findLogs(query: InquiryLogQueryDto): Promise<{
@@ -116,299 +125,239 @@ export class InquiryLogService {
limit: number;
total: number;
}> {
const filter = this.buildFilter(query);
const params: unknown[] = [];
const where = this.buildWhere(query, params);
const limit = query.limit ?? 50;
const page = query.page ?? 1;
const skip = (page - 1) * limit;
const [logs, total] = await Promise.all([
this.inquiryLogModel
.find(filter)
.sort({ createdAt: -1 })
.skip(skip)
.limit(limit)
.select('inquiryType provider status duration requestId trackingCode maskedRequest responsePayload error outboundRequests createdAt')
.lean()
.exec(),
this.inquiryLogModel.countDocuments(filter),
]);
const countRows = await this.inquiryLogs.query<Array<{ total: number }>>(
`SELECT COUNT(*)::int AS total FROM inquiry_logs WHERE ${where}`,
params,
);
const pageParams = [...params, limit, skip];
const logs = await this.inquiryLogs.query<InquiryLogListItem[]>(
`SELECT id,
inquiry_type AS "inquiryType",
provider,
status,
duration,
request_id AS "requestId",
tracking_code AS "trackingCode",
masked_request AS "maskedRequest",
response_payload AS "responsePayload",
error,
outbound_requests AS "outboundRequests",
created_at AS "createdAt"
FROM inquiry_logs
WHERE ${where}
ORDER BY created_at DESC
LIMIT $${params.length + 1} OFFSET $${params.length + 2}`,
pageParams,
);
return {
data: logs.map((log) => ({
id: log._id.toString(),
inquiryType: log.inquiryType,
provider: log.provider,
status: log.status,
duration: log.duration,
requestId: log.requestId,
trackingCode: log.trackingCode,
maskedRequest: log.maskedRequest,
responsePayload: log.responsePayload,
error: log.error,
outboundRequests: log.outboundRequests,
createdAt: log.createdAt,
})),
data: logs,
page,
limit,
total,
total: countRows[0]?.total ?? 0,
};
}
async getSummary(query: InquiryLogQueryDto): Promise<InquiryLogSummary> {
const [summary] = await this.inquiryLogModel.aggregate<InquiryLogSummary>([
{ $match: this.buildFilter(query) },
{
$group: {
_id: null,
total: { $sum: 1 },
success: {
$sum: { $cond: [{ $eq: ['$status', InquiryStatus.SUCCESS] }, 1, 0] },
},
failure: {
$sum: { $cond: [{ $eq: ['$status', InquiryStatus.FAILURE] }, 1, 0] },
},
noMatch: {
$sum: {
$cond: [
{
$or: [
{ $eq: ['$status', InquiryStatus.NO_MATCH] },
{
$and: [
{ $eq: ['$status', InquiryStatus.FAILURE] },
{ $in: ['$error.code', NO_MATCH_ERROR_CODES] },
],
},
],
},
1,
0,
],
},
},
noMatchFailure: {
$sum: {
$cond: [
{
$and: [
{ $eq: ['$status', InquiryStatus.FAILURE] },
{ $in: ['$error.code', NO_MATCH_ERROR_CODES] },
],
},
1,
0,
],
},
},
partial: {
$sum: { $cond: [{ $eq: ['$status', InquiryStatus.PARTIAL] }, 1, 0] },
},
averageDuration: { $avg: '$duration' },
minDuration: { $min: '$duration' },
maxDuration: { $max: '$duration' },
},
},
{
$project: {
_id: 0,
total: 1,
success: 1,
failure: { $subtract: ['$failure', '$noMatchFailure'] },
evaluated: {
$add: ['$success', { $subtract: ['$failure', '$noMatchFailure'] }],
},
noMatch: 1,
partial: 1,
successRate: {
$cond: [
{ $eq: [{ $add: ['$success', { $subtract: ['$failure', '$noMatchFailure'] }] }, 0] },
0,
{ $divide: ['$success', { $add: ['$success', { $subtract: ['$failure', '$noMatchFailure'] }] }] },
],
},
failureRate: {
$cond: [
{ $eq: [{ $add: ['$success', { $subtract: ['$failure', '$noMatchFailure'] }] }, 0] },
0,
{ $divide: [{ $subtract: ['$failure', '$noMatchFailure'] }, { $add: ['$success', { $subtract: ['$failure', '$noMatchFailure'] }] }] },
],
},
averageDuration: { $ifNull: ['$averageDuration', 0] },
minDuration: { $ifNull: ['$minDuration', 0] },
maxDuration: { $ifNull: ['$maxDuration', 0] },
},
},
]);
const params: unknown[] = [];
const where = this.buildWhere(query, params);
params.push([...NO_MATCH_ERROR_CODES]);
const codesParam = `$${params.length}`;
const rows = await this.inquiryLogs.query<
Array<{
total: number;
success: number;
failure: number;
noMatch: number;
partial: number;
averageDuration: string | number | null;
minDuration: number | null;
maxDuration: number | null;
}>
>(
`SELECT COUNT(*)::int AS total,
COUNT(*) FILTER (WHERE status = '${InquiryStatus.SUCCESS}')::int AS success,
COUNT(*) FILTER (
WHERE status = '${InquiryStatus.FAILURE}'
AND COALESCE(error->>'code', '') <> ALL(${codesParam}::text[])
)::int AS failure,
COUNT(*) FILTER (
WHERE status = '${InquiryStatus.NO_MATCH}'
OR (
status = '${InquiryStatus.FAILURE}'
AND error->>'code' = ANY(${codesParam}::text[])
)
)::int AS "noMatch",
COUNT(*) FILTER (WHERE status = '${InquiryStatus.PARTIAL}')::int AS partial,
AVG(duration) AS "averageDuration",
MIN(duration)::int AS "minDuration",
MAX(duration)::int AS "maxDuration"
FROM inquiry_logs
WHERE ${where}`,
params,
);
return summary ?? this.emptySummary();
const row = rows[0];
if (!row || Number(row.total) === 0) return this.emptySummary();
const success = Number(row.success);
const failure = Number(row.failure);
const evaluated = success + failure;
return {
total: Number(row.total),
evaluated,
success,
failure,
noMatch: Number(row.noMatch),
partial: Number(row.partial),
successRate: evaluated === 0 ? 0 : success / evaluated,
failureRate: evaluated === 0 ? 0 : failure / evaluated,
averageDuration: Number(row.averageDuration ?? 0),
minDuration: Number(row.minDuration ?? 0),
maxDuration: Number(row.maxDuration ?? 0),
};
}
async getCommonErrors(query: InquiryLogQueryDto): Promise<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>([
{
$match: {
...this.buildFilter(query),
error: { $exists: true, $ne: null },
},
},
{
$group: {
_id: {
code: { $ifNull: ['$error.code', 'UNKNOWN_ERROR'] },
message: { $ifNull: ['$error.message', 'Unknown error'] },
},
count: { $sum: 1 },
lastSeenAt: { $max: '$createdAt' },
},
},
{ $sort: { count: -1, lastSeenAt: -1 } },
{ $limit: limit },
{
$project: {
_id: 0,
code: '$_id.code',
message: '$_id.message',
count: 1,
lastSeenAt: 1,
},
},
]);
return this.inquiryLogs.query<CommonErrorItem[]>(
`SELECT COALESCE(error->>'code', 'UNKNOWN_ERROR') AS code,
COALESCE(error->>'message', 'Unknown error') AS message,
COUNT(*)::int AS count,
MAX(created_at) AS "lastSeenAt"
FROM inquiry_logs
WHERE ${where} AND error IS NOT NULL
GROUP BY 1, 2
ORDER BY count DESC, "lastSeenAt" DESC
LIMIT ${limitParam}`,
params,
);
}
async getDurationExtremes(query: InquiryLogQueryDto): Promise<{
fastest: DurationExtremeItem[];
slowest: DurationExtremeItem[];
}> {
const filter = this.buildFilter(query);
const params: unknown[] = [];
const where = this.buildWhere(query, params);
const limit = query.limit ?? 10;
const projection =
'inquiryType provider status duration requestId trackingCode error createdAt';
const select = `SELECT id,
inquiry_type AS "inquiryType",
provider,
status,
duration,
request_id AS "requestId",
tracking_code AS "trackingCode",
error,
created_at AS "createdAt"
FROM inquiry_logs
WHERE ${where}`;
const [fastest, slowest] = await Promise.all([
this.inquiryLogModel.find(filter).sort({ duration: 1 }).limit(limit).select(projection).lean(),
this.inquiryLogModel.find(filter).sort({ duration: -1 }).limit(limit).select(projection).lean(),
this.inquiryLogs.query<DurationExtremeItem[]>(
`${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 {
fastest: fastest.map((log) => this.toDurationExtremeItem(log)),
slowest: slowest.map((log) => this.toDurationExtremeItem(log)),
};
return { fastest, slowest };
}
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>([
{ $match: this.buildFilter(query) },
{
$group: {
_id: {
bucket: {
$dateToString: {
format: this.timelineFormat(interval),
date: '$createdAt',
timezone: 'Asia/Tehran',
},
},
errorCode: { $ifNull: ['$error.code', null] },
},
total: { $sum: 1 },
success: {
$sum: { $cond: [{ $eq: ['$status', InquiryStatus.SUCCESS] }, 1, 0] },
},
failure: {
$sum: { $cond: [{ $eq: ['$status', InquiryStatus.FAILURE] }, 1, 0] },
},
partial: {
$sum: { $cond: [{ $eq: ['$status', InquiryStatus.PARTIAL] }, 1, 0] },
},
durationSum: { $sum: '$duration' },
maxDuration: { $max: '$duration' },
},
},
{
$addFields: {
errorCount: {
$cond: [{ $ne: ['$_id.errorCode', null] }, '$total', 0],
},
},
},
{ $sort: { '_id.bucket': 1, errorCount: -1 } },
{
$group: {
_id: '$_id.bucket',
total: { $sum: '$total' },
success: { $sum: '$success' },
failure: { $sum: '$failure' },
partial: { $sum: '$partial' },
durationSum: { $sum: '$durationSum' },
maxDuration: { $max: '$maxDuration' },
commonErrorCode: { $first: '$_id.errorCode' },
},
},
{ $sort: { _id: 1 } },
{
$project: {
_id: 0,
bucket: '$_id',
total: 1,
success: 1,
failure: 1,
partial: 1,
averageDuration: {
$cond: [{ $eq: ['$total', 0] }, 0, { $divide: ['$durationSum', '$total'] }],
},
maxDuration: { $ifNull: ['$maxDuration', 0] },
commonErrorCode: 1,
},
},
]);
const rows = await this.inquiryLogs.query<
Array<TimelineBucket & { commonErrorCode: string | null }>
>(
`WITH grouped AS (
SELECT to_char(created_at AT TIME ZONE 'Asia/Tehran', ${formatParam}) AS bucket,
error->>'code' AS error_code,
COUNT(*)::int AS total,
COUNT(*) FILTER (WHERE status = '${InquiryStatus.SUCCESS}')::int AS success,
COUNT(*) FILTER (WHERE status = '${InquiryStatus.FAILURE}')::int AS failure,
COUNT(*) FILTER (WHERE status = '${InquiryStatus.PARTIAL}')::int AS partial,
COALESCE(SUM(duration), 0)::float AS duration_sum,
COALESCE(MAX(duration), 0)::int AS max_duration
FROM inquiry_logs
WHERE ${where}
GROUP BY 1, 2
),
ranked AS (
SELECT *,
ROW_NUMBER() OVER (
PARTITION BY bucket
ORDER BY CASE WHEN error_code IS NOT NULL THEN total ELSE 0 END DESC
) AS rn
FROM grouped
)
SELECT bucket,
SUM(total)::int AS total,
SUM(success)::int AS success,
SUM(failure)::int AS failure,
SUM(partial)::int AS partial,
CASE WHEN SUM(total) = 0 THEN 0 ELSE SUM(duration_sum) / SUM(total) END AS "averageDuration",
MAX(max_duration)::int AS "maxDuration",
MAX(CASE WHEN rn = 1 THEN error_code END) AS "commonErrorCode"
FROM ranked
GROUP BY bucket
ORDER BY bucket`,
params,
);
return rows.map((row) => ({
bucket: row.bucket,
total: Number(row.total),
success: Number(row.success),
failure: Number(row.failure),
partial: Number(row.partial),
averageDuration: Number(row.averageDuration),
maxDuration: Number(row.maxDuration),
...(row.commonErrorCode ? { commonErrorCode: row.commonErrorCode } : {}),
}));
}
private buildFilter(query: InquiryLogQueryDto): FilterQuery<InquiryLogDocument> {
const filter: FilterQuery<InquiryLogDocument> = {};
const createdAt = this.buildCreatedAtFilter(query);
if (createdAt) {
filter.createdAt = createdAt;
}
if (query.inquiryType) {
filter.inquiryType = query.inquiryType;
}
if (query.provider) {
filter.provider = query.provider;
}
if (query.status) {
filter.status = query.status;
}
if (query.errorCode) {
filter['error.code'] = query.errorCode;
}
if (query.errorMessage) {
filter['error.message'] = { $regex: query.errorMessage, $options: 'i' };
}
if (query.trackingCode) {
filter.trackingCode = query.trackingCode;
}
return filter;
}
private buildCreatedAtFilter(query: InquiryLogQueryDto): { $gte?: Date; $lte?: Date } | undefined {
if (!query.from && !query.to && !query.preset) {
return undefined;
}
private buildWhere(query: InquiryLogQueryDto, params: unknown[]): string {
const clauses: string[] = [];
const add = (sql: string, value: unknown) => {
params.push(value);
clauses.push(sql.replace('?', `$${params.length}`));
};
const to = query.to ? new Date(query.to) : undefined;
const from = query.from ? new Date(query.from) : this.defaultFromDate(query.preset);
const from =
query.from ? new Date(query.from) : query.preset || query.to ? this.defaultFromDate(query.preset) : undefined;
if (from) add('created_at >= ?', from);
if (to) add('created_at <= ?', to);
if (query.inquiryType) add('inquiry_type = ?', query.inquiryType);
if (query.provider) add('provider = ?', query.provider);
if (query.status) add('status = ?', query.status);
if (query.errorCode) add(`error->>'code' = ?`, query.errorCode);
if (query.errorMessage) add(`error->>'message' ILIKE ? ESCAPE '\\'`, this.likeContains(query.errorMessage));
if (query.trackingCode) add('tracking_code = ?', query.trackingCode);
return {
...(from && { $gte: from }),
...(to && { $lte: to }),
};
return clauses.length ? clauses.join(' AND ') : 'TRUE';
}
private likeContains(value: string): string {
return `%${value.replace(/[\\%_]/g, (character) => `\\${character}`)}%`;
}
private defaultFromDate(preset?: LogTimeRangePreset): Date {
@@ -429,12 +378,12 @@ export class InquiryLogService {
private timelineFormat(interval: LogTimelineInterval): string {
switch (interval) {
case LogTimelineInterval.MONTH:
return '%Y-%m';
return 'YYYY-MM';
case LogTimelineInterval.DAY:
return '%Y-%m-%d';
return 'YYYY-MM-DD';
case LogTimelineInterval.HOUR:
default:
return '%Y-%m-%d %H:00';
return 'YYYY-MM-DD HH24:00';
}
}
@@ -453,28 +402,4 @@ export class InquiryLogService {
maxDuration: 0,
};
}
private toDurationExtremeItem(log: {
_id: unknown;
inquiryType: InquiryType;
provider: ProviderName;
status: InquiryStatus;
duration: number;
requestId: string;
trackingCode: string;
error?: Record<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 { MongooseModule } from '@nestjs/mongoose';
import { TypeOrmModule } from '@nestjs/typeorm';
import { InquiryLogsController } from './inquiry-logs.controller';
import { InquiryLogService } from './inquiry-log.service';
import { InquiryLog, InquiryLogSchema } from './schemas/inquiry-log.schema';
import { InquiryLog } from './schemas/inquiry-log.schema';
@Module({
imports: [
MongooseModule.forFeature([{ name: InquiryLog.name, schema: InquiryLogSchema }]),
],
imports: [TypeOrmModule.forFeature([InquiryLog])],
controllers: [InquiryLogsController],
providers: [InquiryLogService],
exports: [InquiryLogService],
+28 -29
View File
@@ -1,57 +1,56 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument } from 'mongoose';
import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
import { InquiryStatus } from '../../common/enums/inquiry-status.enum';
import { InquiryType } from '../../common/enums/inquiry-type.enum';
import { ProviderName } from '../../common/enums/provider-name.enum';
export type InquiryLogDocument = HydratedDocument<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 {
@Prop({ required: true, enum: InquiryType })
@PrimaryGeneratedColumn('uuid')
id!: string;
@Column({ type: 'text' })
inquiryType!: InquiryType;
@Prop({ required: true, enum: ProviderName })
@Column({ type: 'text' })
provider!: ProviderName;
@Prop({ type: Object, required: true })
@Column({ type: 'jsonb' })
requestPayload!: Record<string, unknown>;
@Prop({ type: Object, required: true })
@Column({ type: 'jsonb' })
maskedRequest!: Record<string, unknown>;
@Prop({ type: Object })
responsePayload?: Record<string, unknown>;
@Column({ type: 'jsonb', nullable: true })
responsePayload?: Record<string, unknown> | null;
@Prop({ required: true, enum: InquiryStatus })
@Column({ type: 'text' })
status!: InquiryStatus;
@Prop({ required: true })
@Column({ type: 'int' })
duration!: number;
@Prop({ required: true, index: true })
@Index()
@Column({ type: 'text' })
requestId!: string;
@Prop({ required: true, index: true })
@Index()
@Column({ type: 'text' })
trackingCode!: string;
@Prop({ type: Object })
error?: Record<string, unknown>;
@Column({ type: 'jsonb', nullable: true })
error?: Record<string, unknown> | null;
@Prop({ type: Object })
attemptSummary?: Record<string, unknown>;
@Column({ type: 'jsonb', nullable: true })
attemptSummary?: Record<string, unknown> | null;
@Prop({ type: [Object] })
outboundRequests?: Record<string, unknown>[];
@Column({ type: 'jsonb', nullable: true })
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 });
@@ -5,6 +5,7 @@ import { ProviderName } from '../../common/enums/provider-name.enum';
import { InquiryProvider } from '../../common/interfaces/inquiry-provider.interface';
import { InquiryRoutingConfig } from '../../config/configuration';
import { HamtaProvider } from '../implementations/hamta.provider';
import { AsiaProvider } from '../implementations/asia.provider';
import { MoallemProvider } from '../implementations/moallem.provider';
import { ParsianProvider } from '../implementations/parsian.provider';
import { TejaratNouProvider } from '../implementations/tejaratnou.provider';
@@ -25,8 +26,10 @@ export class ProviderFactory {
moallem: MoallemProvider,
parsian: ParsianProvider,
tejaratnou: TejaratNouProvider,
asia: AsiaProvider,
) {
this.registry = new Map<ProviderName, InquiryProvider>([
[ProviderName.ASIA, asia],
[ProviderName.HAMTA, hamta],
[ProviderName.MOALLEM, moallem],
[ProviderName.PARSIAN, parsian],
@@ -19,7 +19,7 @@ import {
} from '../../common/helpers/provider-resilience.helper';
import { withRetry } from '../../common/helpers/retry.helper';
import { AmitisAuthServiceConfig } from '../../config/configuration';
import { GeneralTokenDocument } from '../schemas/general-token.schema';
import { GeneralToken } from '../schemas/general-token.schema';
import { GeneralTokenService } from '../services/general-token.service';
import { DistributedLockService } from '../services/distributed-lock.service';
@@ -172,7 +172,7 @@ export class AmitisProvider {
}
private async refreshAccessToken(
latestToken: GeneralTokenDocument,
latestToken: GeneralToken,
providerName: ProviderName,
inquiryType: InquiryType,
signal?: AbortSignal,
@@ -184,7 +184,7 @@ export class AmitisProvider {
RefreshToken: latestToken.refreshToken,
}, { signal }),
);
const token = this.extractToken(response.data, latestToken.refreshToken);
const token = this.extractToken(response.data, latestToken.refreshToken ?? undefined);
await this.saveToken(
token,
@@ -276,7 +276,7 @@ export class AmitisProvider {
};
}
private isExpired(token: GeneralTokenDocument): boolean {
private isExpired(token: GeneralToken): boolean {
// Access token expires in 20 minutes, add 60 second buffer
const refreshBufferMs = 60 * 1000;
return !token.expiresAt || Date.now() + refreshBufferMs >= token.expiresAt.getTime();
@@ -286,7 +286,7 @@ export class AmitisProvider {
* Check if token is within 24-hour window from creation
* Refresh token is valid for 24 hours after initial login
*/
private isWithin24Hours(token: GeneralTokenDocument): boolean {
private isWithin24Hours(token: GeneralToken): boolean {
if (!token.createdAt) {
return false;
}
@@ -0,0 +1,117 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AxiosError } from 'axios';
import { InquiryType } from '../../common/enums/inquiry-type.enum';
import { ProviderName } from '../../common/enums/provider-name.enum';
import { AsiaConfig } from '../../config/configuration';
import { GeneralTokenService } from '../services/general-token.service';
import {
LegacyApiProvider,
PersonInquiryPayload,
PersonInquiryResult,
} from '../shared/legacy-api.provider.abstract';
import { AmitisProvider } from './amitis.provider';
interface AsiaResponse<T> {
isSuccess?: boolean;
message?: string;
result?: T;
}
@Injectable()
export class AsiaProvider extends LegacyApiProvider {
readonly name = ProviderName.ASIA;
readonly supportedInquiryTypes = [InquiryType.PERSON, InquiryType.REAL_ESTATE];
private readonly asiaConfig: AsiaConfig;
constructor(
configService: ConfigService,
amitisProvider: AmitisProvider,
private readonly generalTokenService: GeneralTokenService,
) {
const config = configService.get<AsiaConfig>('asia')!;
super(config, (provider, inquiry, username, password, signal) =>
amitisProvider.getAccessToken(provider, inquiry, username, password, signal),
);
this.asiaConfig = config;
}
protected async inquirePerson(
payload: PersonInquiryPayload,
inquiryType: InquiryType,
signal?: AbortSignal,
): Promise<PersonInquiryResult> {
const config = this.getInquiryConfig(inquiryType);
if (config.authMethod !== 'ASIA') {
throw this.formatProviderError('ASIA_PERSON_AUTH_METHOD must be ASIA');
}
if (!config.username || !config.password) {
throw this.formatProviderError('Asia person credentials are missing');
}
const birthDate = payload.birthDate?.replace(/-/g, '');
if (!/^\d{8}$/.test(birthDate ?? '') || !/^\d{10}$/.test(payload.nationalCode ?? '')) {
throw this.formatProviderError('Asia requires a 10-digit national code and a full Jalali birth date');
}
try {
const token = await this.generalTokenService.getValidAccessToken(
'ASIA_PERSON',
async (requestSignal) => {
const response = await this.httpClient.post<AsiaResponse<{ token?: string }>>(
this.asiaConfig.loginUrl,
{ userName: config.username, password: config.password },
{ signal: requestSignal },
);
const body = response.data;
const accessToken = body?.result?.token;
if (body?.isSuccess !== true || typeof accessToken !== 'string' || !accessToken.trim()) {
throw this.formatProviderError(body?.message || 'Asia login returned no valid token');
}
return {
accessToken,
tokenType: 'Bearer',
scope: 'person',
expiresIn: this.getTokenLifetime(accessToken),
};
},
{ url: this.asiaConfig.loginUrl, clientId: config.username, username: config.username },
signal,
);
const response = await this.httpClient.post<AsiaResponse<Record<string, unknown>>>(
config.url,
{ nin: Number(payload.nationalCode), birthDate: Number(birthDate), persianBirthDate: '' },
{ headers: { Authorization: `Bearer ${token}` }, signal },
);
const body = response.data;
// Reject empty or unrecognized responses rather than reporting an inquiry success.
if (body?.isSuccess !== true || !body.result || typeof body.result !== 'object' || Array.isArray(body.result)) {
throw this.formatProviderError(body?.message || 'Asia person inquiry returned no valid result');
}
return {
nationalCode: payload.nationalCode,
birthDate: payload.birthDate,
fullName: [body.result.name, body.result.family]
.filter((value): value is string => typeof value === 'string' && Boolean(value.trim()))
.join(' ') || undefined,
raw: { ...body.result, birthDate: payload.birthDate },
};
} catch (error) {
if (error instanceof AxiosError) throw this.formatAxiosError(error);
throw error;
}
}
private getTokenLifetime(token: string): number {
// The login returns a JWT with exp, but no separate expiry field. Use exp only
// for cache lifetime; opaque tokens are used once without assuming an expiry.
try {
const claims = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8'));
if (typeof claims.exp === 'number' && Number.isFinite(claims.exp)) {
return Math.max(0, Math.floor(claims.exp - Date.now() / 1000));
}
} catch {
// A token without readable expiry must not be reused from the cache.
}
return 0;
}
}
@@ -6,6 +6,7 @@ import {
CentInsurApiResponse,
getCentInsurProviderError,
} from '../../common/helpers/centinsur-response.helper';
import { getSayahProviderError, SayahApiResponse } from '../../common/helpers/sayah-response.helper';
import { InquiryType } from '../../common/enums/inquiry-type.enum';
import { ProviderName } from '../../common/enums/provider-name.enum';
import { jalaliDateToGregorianDate } from '../../common/helpers/jalali-date.helper';
@@ -69,10 +70,12 @@ export class TejaratNouProvider implements InquiryProvider<LegacyInquiryPayload,
readonly supportedInquiryTypes = [
InquiryType.PERSON,
InquiryType.SHAHKAR,
InquiryType.SHEBA,
InquiryType.REAL_ESTATE,
InquiryType.CAR_BY_PLATE,
InquiryType.CAR_BY_CHASSIS,
InquiryType.THIRD_PARTY_CAR,
InquiryType.POLICY_BY_PLATE,
];
private readonly logger = new Logger(TejaratNouProvider.name);
@@ -121,9 +124,12 @@ export class TejaratNouProvider implements InquiryProvider<LegacyInquiryPayload,
);
case InquiryType.SHAHKAR:
return this.inquireShahkar(payload, context);
case InquiryType.SHEBA:
return this.inquireSheba(payload, context);
case InquiryType.REAL_ESTATE:
return this.inquireRealEstate(payload, context);
case InquiryType.CAR_BY_PLATE:
case InquiryType.POLICY_BY_PLATE:
return this.inquireCarByPlate(payload, context);
case InquiryType.CAR_BY_CHASSIS:
return this.inquireCarByChassis(payload, context);
@@ -330,11 +336,14 @@ export class TejaratNouProvider implements InquiryProvider<LegacyInquiryPayload,
payload: PersonInquiryPayload,
context: ProviderExecutionContext,
): 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>(
'POST',
`/api/identity-inquiry/national-code/${payload.nationalCode}/birthdate/${encodeURIComponent(providerBirthDate)}`,
{},
yearOnly ? 'POST' : 'GET',
yearOnly
? `${root}/national-code/${payload.nationalCode}/birthdate-year/${payload.birthDate}`
: `${root}/national-code/${payload.nationalCode}/birthdate/${encodeURIComponent(this.toGregorianBirthDate(payload.birthDate))}`,
undefined,
context,
);
@@ -361,7 +370,7 @@ export class TejaratNouProvider implements InquiryProvider<LegacyInquiryPayload,
async () => {
const data = await this.authenticatedRequest<unknown>(
'POST',
'/api/compliance-inquiry/compatibility',
this.configuredUrl(InquiryType.SHAHKAR, '/api/compliance-inquiry/compatibility'),
{ nationalCode, mobileNo },
context,
);
@@ -396,7 +405,7 @@ export class TejaratNouProvider implements InquiryProvider<LegacyInquiryPayload,
async () => {
const data = await this.authenticatedRequest<CentInsurApiResponse | Record<string, unknown>>(
'POST',
'/api/central-insurance-amlak-inquiry',
this.configuredUrl(InquiryType.REAL_ESTATE, '/api/central-insurance-amlak-inquiry'),
{
nationalId: nationalCode,
postalCode: Number(postalCode),
@@ -422,6 +431,66 @@ export class TejaratNouProvider implements InquiryProvider<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>(
fn: () => Promise<T>,
context: ProviderExecutionContext,
@@ -449,7 +518,7 @@ export class TejaratNouProvider implements InquiryProvider<LegacyInquiryPayload,
);
try {
const response = await this.httpClient.request<TejaratNouGatewayResponse<T>>({
const response = await this.httpClient.request<TejaratNouGatewayResponse<T> | string>({
method,
url: path,
data: method === 'POST' ? body : undefined,
@@ -460,16 +529,18 @@ export class TejaratNouProvider implements InquiryProvider<LegacyInquiryPayload,
signal: context.signal,
});
const envelope = response.data;
if (envelope?.isSuccess === false || (envelope?.statusCode && envelope.statusCode >= 400)) {
const envelope = this.parseGatewayBody(response.data);
if (this.isGatewayEnvelope(envelope)) {
if (envelope.isSuccess === false || (envelope.statusCode && envelope.statusCode >= 400)) {
throw this.createProviderError(
envelope.message ?? 'TejaratNou inquiry failed',
String(envelope.statusCode ?? 'PROVIDER_ERROR'),
);
}
if (envelope?.data !== undefined) {
return envelope.data;
if (envelope.data !== undefined) {
return envelope.data as T;
}
}
return envelope as T;
@@ -489,6 +560,27 @@ export class TejaratNouProvider implements InquiryProvider<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(
data: CentInsurApiResponse | Record<string, unknown>,
): { message: string; code: string } | null {
@@ -561,6 +653,10 @@ export class TejaratNouProvider implements InquiryProvider<LegacyInquiryPayload,
? 'VALIDATION_ERROR'
: providerCode === 'INQUIRY_NO_MATCH'
? 'INQUIRY_NO_MATCH'
: providerCode === 'SHEBA_MISMATCH'
? 'SHEBA_MISMATCH'
: providerCode === 'SAYAH_ERROR'
? 'SAYAH_ERROR'
: providerCode === 'UNSUPPORTED_INQUIRY'
? 'UNSUPPORTED_INQUIRY'
: 'PROVIDER_ERROR';
@@ -1,3 +1,6 @@
import { InquiryType } from '../../common/enums/inquiry-type.enum';
import type { InquiryConfig } from '../../config/configuration';
export interface TejaratNouConfig {
enabled: boolean;
timeout: number;
@@ -10,4 +13,5 @@ export interface TejaratNouConfig {
clientSecret: string;
username: string;
password: string;
inquiries: Partial<Record<InquiryType, InquiryConfig>>;
}
+7 -12
View File
@@ -1,37 +1,32 @@
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ProviderFactory } from './factory/provider.factory';
import { HamtaProvider } from './implementations/hamta.provider';
import { AsiaProvider } from './implementations/asia.provider';
import { MoallemProvider } from './implementations/moallem.provider';
import { ParsianProvider } from './implementations/parsian.provider';
import { TejaratNouProvider } from './implementations/tejaratnou.provider';
import { AmitisProvider } from './implementations/amitis.provider';
import { ProviderOrchestratorService } from './strategy/provider-orchestrator.service';
import { ProviderIsolationService } from './strategy/provider-isolation.service';
import { GeneralToken, GeneralTokenSchema } from './schemas/general-token.schema';
import {
InquiryResultCache,
InquiryResultCacheSchema,
} from './schemas/inquiry-result-cache.schema';
import { GeneralToken } from './schemas/general-token.schema';
import { InquiryResultCache } from './schemas/inquiry-result-cache.schema';
import { CentInsurCarPolicyClient } from './shared/centinsur-car-policy.client';
import { CentInsurCarProviderSupport } from './shared/centinsur-car-provider.support';
import { GeneralTokenService } from './services/general-token.service';
import { InquiryResultCacheService } from './services/inquiry-result-cache.service';
import { DistributedLockService } from './services/distributed-lock.service';
import { DistributedLock, DistributedLockSchema } from './schemas/distributed-lock.schema';
import { DistributedLock } from './schemas/distributed-lock.schema';
/**
* Provider adapters, factory, and orchestration strategy.
*/
@Module({
imports: [
MongooseModule.forFeature([
{ name: GeneralToken.name, schema: GeneralTokenSchema },
{ name: InquiryResultCache.name, schema: InquiryResultCacheSchema },
{ name: DistributedLock.name, schema: DistributedLockSchema },
]),
TypeOrmModule.forFeature([GeneralToken, InquiryResultCache, DistributedLock]),
],
providers: [
AsiaProvider,
HamtaProvider,
MoallemProvider,
ParsianProvider,
@@ -1,21 +1,27 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument } from 'mongoose';
import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn, UpdateDateColumn } from 'typeorm';
export type DistributedLockDocument = HydratedDocument<DistributedLock>;
@Schema({ timestamps: true, collection: 'distributed_locks' })
@Entity('distributed_locks')
export class DistributedLock {
@Prop({ required: true, unique: true, index: true })
@PrimaryGeneratedColumn('uuid')
id!: string;
@Index({ unique: true })
@Column({ type: 'text' })
lockKey!: string;
@Prop({ required: true })
@Column({ type: 'text' })
ownerId!: string;
@Prop({ required: true, index: true })
@Index()
@Column({ type: 'timestamptz' })
leaseUntil!: Date;
@Prop({ required: true, default: 0 })
@Column({ type: 'int', default: 0 })
fencingToken!: number;
}
export const DistributedLockSchema = SchemaFactory.createForClass(DistributedLock);
@CreateDateColumn({ type: 'timestamptz' })
createdAt!: Date;
@UpdateDateColumn({ type: 'timestamptz' })
updatedAt!: Date;
}
+21 -21
View File
@@ -1,44 +1,44 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument } from 'mongoose';
export type GeneralTokenDocument = HydratedDocument<GeneralToken>;
import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
/** OAuth tokens for outbound provider APIs — credentials stay in env, not stored here. */
@Schema({ timestamps: { createdAt: true, updatedAt: false }, collection: 'general_tokens' })
@Entity('general_tokens')
@Index(['serviceProvider', 'createdAt'])
export class GeneralToken {
@Prop({ required: true, index: true })
@PrimaryGeneratedColumn('uuid')
id!: string;
@Index()
@Column({ type: 'text' })
serviceProvider!: string;
@Prop({ required: true })
@Column({ type: 'text' })
tokenType!: string;
@Prop({ required: true })
@Column({ type: 'text' })
url!: string;
@Prop({ required: true })
@Column({ type: 'text' })
clientId!: string;
@Prop({ required: true })
@Column({ type: 'text' })
username!: string;
@Prop({ required: true })
@Column({ type: 'text' })
scope!: string;
@Prop({ required: true })
@Column({ type: 'text' })
accessToken!: string;
@Prop()
refreshToken?: string;
@Column({ type: 'text', nullable: true })
refreshToken?: string | null;
@Prop({ required: true })
@Column({ type: 'int' })
expiresIn!: number;
@Prop({ required: true, index: true })
@Index()
@Column({ type: 'timestamptz' })
expiresAt!: Date;
createdAt?: Date;
@CreateDateColumn({ type: 'timestamptz' })
createdAt!: Date;
}
export const GeneralTokenSchema = SchemaFactory.createForClass(GeneralToken);
GeneralTokenSchema.index({ serviceProvider: 1, createdAt: -1 });
@@ -1,36 +1,36 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument, Schema as MongooseSchema } from 'mongoose';
import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
import { InquiryType } from '../../common/enums/inquiry-type.enum';
import { ProviderName } from '../../common/enums/provider-name.enum';
export type InquiryResultCacheDocument = HydratedDocument<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:
* - Cache keys are inquiry-specific (nationalCode+birthDate, plate number, etc.)
* - Data is immutable for most inquiries (civil registration identity)
* - Retention and query patterns differ from audit trails
*/
@Schema({ timestamps: { createdAt: true, updatedAt: false }, collection: 'inquiry_result_cache' })
@Entity('inquiry_result_cache')
@Index(['inquiryType', 'cacheKey'], { unique: true })
export class InquiryResultCache {
@Prop({ required: true, enum: InquiryType, index: true })
@PrimaryGeneratedColumn('uuid')
id!: string;
@Index()
@Column({ type: 'text' })
inquiryType!: InquiryType;
/** Stable lookup key, e.g. "0012345678|1378-11-24" for person inquiry. */
@Prop({ required: true, index: true })
@Index()
@Column({ type: 'text' })
cacheKey!: string;
@Prop({ required: true, enum: ProviderName })
@Column({ type: 'text' })
provider!: ProviderName;
@Prop({ type: MongooseSchema.Types.Mixed, required: true })
@Column({ type: 'jsonb' })
data!: Record<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 { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import {
DistributedLock,
DistributedLockDocument,
} from '../schemas/distributed-lock.schema';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { DistributedLock } from '../schemas/distributed-lock.schema';
export interface LockOptions {
leaseMs?: number;
@@ -25,8 +22,8 @@ const DEFAULT_WAIT_MS = 10_000;
@Injectable()
export class DistributedLockService {
constructor(
@InjectModel(DistributedLock.name)
private readonly lockModel: Model<DistributedLockDocument>,
@InjectRepository(DistributedLock)
private readonly locks: Repository<DistributedLock>,
) {}
async acquire(
@@ -35,44 +32,36 @@ export class DistributedLockService {
leaseMs = DEFAULT_LEASE_MS,
): Promise<LockLease | null> {
const now = new Date();
try {
const lock = await this.lockModel
.findOneAndUpdate(
{
lockKey,
$or: [{ leaseUntil: { $lte: now } }, { leaseUntil: { $exists: false } }],
},
{
$set: {
lockKey,
ownerId,
leaseUntil: new Date(now.getTime() + leaseMs),
},
$inc: { fencingToken: 1 },
},
{ new: true, upsert: true, setDefaultsOnInsert: true },
)
.exec();
const leaseUntil = new Date(now.getTime() + leaseMs);
const rows = await this.locks.query<Array<{ lockKey: string; ownerId: string; fencingToken: number }>>(
`INSERT INTO distributed_locks (lock_key, owner_id, lease_until, fencing_token)
VALUES ($1, $2, $3, 1)
ON CONFLICT (lock_key) DO UPDATE
SET owner_id = EXCLUDED.owner_id,
lease_until = EXCLUDED.lease_until,
fencing_token = distributed_locks.fencing_token + 1,
updated_at = now()
WHERE distributed_locks.lease_until <= $4
RETURNING lock_key AS "lockKey", owner_id AS "ownerId", fencing_token AS "fencingToken"`,
[lockKey, ownerId, leaseUntil, now],
);
const lock = rows[0];
if (!lock || lock.ownerId !== ownerId) return null;
return {
lockKey,
ownerId,
fencingToken: lock.fencingToken,
lockKey: lock.lockKey,
ownerId: lock.ownerId,
fencingToken: Number(lock.fencingToken),
};
} catch (error) {
if (this.isDuplicateKey(error)) return null;
throw error;
}
}
async release(lease: LockLease): Promise<void> {
await this.lockModel
.updateOne(
{ lockKey: lease.lockKey, ownerId: lease.ownerId },
{ $set: { leaseUntil: new Date(0) } },
)
.exec();
await this.locks.query(
`UPDATE distributed_locks
SET lease_until = $3, updated_at = now()
WHERE lock_key = $1 AND owner_id = $2`,
[lease.lockKey, lease.ownerId, new Date(0)],
);
}
async withLock<T>(
@@ -132,13 +121,4 @@ export class DistributedLockService {
(error as NodeJS.ErrnoException).code = 'ECANCELED';
return error;
}
private isDuplicateKey(error: unknown): boolean {
return Boolean(
error &&
typeof error === 'object' &&
'code' in error &&
(error as { code?: number }).code === 11000,
);
}
}
+17 -14
View File
@@ -1,7 +1,7 @@
import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import axios from 'axios';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Repository } from 'typeorm';
import { mergeOutboundAxiosConfig } from '../../common/helpers/http-client.helper';
import {
AUTH_MAX_ATTEMPTS,
@@ -9,7 +9,7 @@ import {
isAuthTransportRetryable,
} from '../../common/helpers/provider-resilience.helper';
import { withRetry } from '../../common/helpers/retry.helper';
import { GeneralToken, GeneralTokenDocument } from '../schemas/general-token.schema';
import { GeneralToken } from '../schemas/general-token.schema';
import { TejaratNouConfig } from '../interfaces/tejaratnou-config.interface';
import { DistributedLockService } from './distributed-lock.service';
@@ -28,17 +28,20 @@ export class GeneralTokenService {
private readonly logger = new Logger(GeneralTokenService.name);
constructor(
@InjectModel(GeneralToken.name)
private readonly generalTokenModel: Model<GeneralTokenDocument>,
@InjectRepository(GeneralToken)
private readonly generalTokens: Repository<GeneralToken>,
private readonly distributedLockService: DistributedLockService,
) {}
async getLatestToken(serviceProvider: string): Promise<GeneralTokenDocument | null> {
return this.generalTokenModel.findOne({ serviceProvider }).sort({ createdAt: -1 }).exec();
async getLatestToken(serviceProvider: string): Promise<GeneralToken | null> {
return this.generalTokens.findOne({
where: { serviceProvider },
order: { createdAt: 'DESC' },
});
}
async isTokenExpired(
token: GeneralTokenDocument,
token: GeneralToken,
bufferSeconds = TOKEN_EXPIRY_BUFFER_SECONDS,
): Promise<boolean> {
if (!token.expiresAt) return true;
@@ -47,7 +50,7 @@ export class GeneralTokenService {
}
/**
* Returns a valid access token — reuses MongoDB-stored token when not expired,
* Returns a valid access token — reuses the stored token when not expired,
* otherwise fetches a new one via the supplied OAuth fetcher.
*/
async getValidAccessToken(
@@ -62,7 +65,7 @@ export class GeneralTokenService {
): Promise<string> {
const latest = await this.getLatestToken(serviceProvider);
if (latest && !(await this.isTokenExpired(latest))) {
this.logger.debug(`Reusing ${serviceProvider} token ${latest._id}`);
this.logger.debug(`Reusing ${serviceProvider} token ${latest.id}`);
return latest.accessToken;
}
@@ -77,7 +80,7 @@ export class GeneralTokenService {
const fresh = await fetchNewToken(signal);
const expiresAt = new Date(Date.now() + fresh.expiresIn * 1000);
await this.generalTokenModel.create({
await this.generalTokens.save(this.generalTokens.create({
serviceProvider,
tokenType: fresh.tokenType,
url: persistContext.url,
@@ -87,7 +90,7 @@ export class GeneralTokenService {
accessToken: fresh.accessToken,
expiresIn: fresh.expiresIn,
expiresAt,
});
}));
this.logger.log(`Stored new ${serviceProvider} token, expires at ${expiresAt.toISOString()}`);
return fresh.accessToken;
@@ -108,8 +111,8 @@ export class GeneralTokenService {
refreshToken?: string;
expiresIn: number;
expiresAt: Date;
}): Promise<GeneralTokenDocument> {
return this.generalTokenModel.create(data);
}): Promise<GeneralToken> {
return this.generalTokens.save(this.generalTokens.create(data));
}
/** OAuth2 password grant for Tejarat No identity gateway. */
@@ -1,12 +1,9 @@
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { InquiryType } from '../../common/enums/inquiry-type.enum';
import { ProviderName } from '../../common/enums/provider-name.enum';
import {
InquiryResultCache,
InquiryResultCacheDocument,
} from '../schemas/inquiry-result-cache.schema';
import { InquiryResultCache } from '../schemas/inquiry-result-cache.schema';
export interface PersonInquiryCacheData {
nationalCode: string;
@@ -30,8 +27,8 @@ export interface PersonInquiryCacheData {
@Injectable()
export class InquiryResultCacheService {
constructor(
@InjectModel(InquiryResultCache.name)
private readonly cacheModel: Model<InquiryResultCacheDocument>,
@InjectRepository(InquiryResultCache)
private readonly cache: Repository<InquiryResultCache>,
) {}
static personCacheKey(nationalCode: string, birthDate: string): string {
@@ -42,44 +39,25 @@ export class InquiryResultCacheService {
nationalCode: string,
birthDate: string,
): Promise<PersonInquiryCacheData | null> {
const entry = await this.cacheModel
.findOne({
inquiryType: InquiryType.PERSON,
cacheKey: InquiryResultCacheService.personCacheKey(nationalCode, birthDate),
})
.exec();
if (!entry) return null;
return entry.data as unknown as PersonInquiryCacheData;
const data = await this.find(
InquiryType.PERSON,
InquiryResultCacheService.personCacheKey(nationalCode, birthDate),
);
return data as PersonInquiryCacheData | null;
}
async savePersonInquiry(
provider: ProviderName,
data: PersonInquiryCacheData,
): Promise<void> {
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),
async savePersonInquiry(provider: ProviderName, data: PersonInquiryCacheData): Promise<void> {
await this.save(
InquiryType.PERSON,
InquiryResultCacheService.personCacheKey(data.nationalCode, data.birthDate),
provider,
data,
},
},
{ upsert: true },
data as unknown as Record<string, unknown>,
);
}
/** Generic cache read for future inquiry types. */
async find(
inquiryType: InquiryType,
cacheKey: string,
): Promise<Record<string, unknown> | null> {
const entry = await this.cacheModel.findOne({ inquiryType, cacheKey }).exec();
async find(inquiryType: InquiryType, cacheKey: string): Promise<Record<string, unknown> | null> {
const entry = await this.cache.findOne({ where: { inquiryType, cacheKey } });
return entry?.data ?? null;
}
@@ -89,10 +67,13 @@ export class InquiryResultCacheService {
provider: ProviderName,
data: Record<string, unknown>,
): Promise<void> {
await this.cacheModel.updateOne(
{ inquiryType, cacheKey },
{ $set: { inquiryType, cacheKey, provider, data } },
{ upsert: true },
await this.cache.query(
`INSERT INTO inquiry_result_cache (inquiry_type, cache_key, provider, data)
VALUES ($1, $2, $3, $4::jsonb)
ON CONFLICT (inquiry_type, cache_key) DO UPDATE
SET provider = EXCLUDED.provider,
data = EXCLUDED.data`,
[inquiryType, cacheKey, provider, JSON.stringify(data)],
);
}
}
+1 -1
View File
@@ -783,7 +783,7 @@
}
}
async function clearInquiryLogs() {
if (!window.confirm('Delete every inquiry log from MongoDB? This cannot be undone.')) return;
if (!window.confirm('Delete every inquiry log from the database? This cannot be undone.')) return;
try {
const result = await request('/inquiry-logs', { method: 'DELETE' });
$('logsBody').replaceChildren(); $('logOutput').textContent = 'Inquiry logs were cleared.';
+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 { UserResponseDto } from '../dto/user-response.dto';
/** Maps Mongoose user documents to API DTOs (never exposes password/hash fields). */
/** Maps user rows to API DTOs (never exposes password or token fields). */
export class UserMapper {
static toProfileDto(user: UserDocument): ProfileDto {
static toProfileDto(user: User): ProfileDto {
return {
id: user._id.toString(),
id: user.id,
fullName: user.fullName,
username: user.username,
email: user.email,
mobile: user.mobile,
mobile: user.mobile ?? undefined,
role: user.role,
clientType: user.clientType,
appName: user.appName,
@@ -21,14 +21,14 @@ export class UserMapper {
requestLimitPerMinute: user.requestLimitPerMinute,
requestLimitPerDay: user.requestLimitPerDay,
totalRequests: user.totalRequests,
lastLoginAt: user.lastLoginAt,
passwordChangedAt: user.passwordChangedAt,
lastLoginAt: user.lastLoginAt ?? undefined,
passwordChangedAt: user.passwordChangedAt ?? undefined,
createdAt: user.createdAt,
updatedAt: user.updatedAt,
};
}
static toResponseDto(user: UserDocument): UserResponseDto {
static toResponseDto(user: User): UserResponseDto {
return UserMapper.toProfileDto(user);
}
}
+42 -38
View File
@@ -1,85 +1,89 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument, Types } from 'mongoose';
import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn, UpdateDateColumn } from 'typeorm';
import { ClientType } from '../../common/enums/client-type.enum';
import { Role } from '../../common/enums/role.enum';
export type UserDocument = HydratedDocument<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.
*/
@Schema({ timestamps: true, collection: 'users' })
@Entity('users')
@Index(['role', 'isActive'])
@Index(['clientType', 'appName'])
export class User {
@Prop({ required: true, trim: true })
@PrimaryGeneratedColumn('uuid')
id!: string;
@Column({ type: 'text' })
fullName!: string;
@Prop({ required: true, unique: true, lowercase: true, trim: true, index: true })
@Index({ unique: true })
@Column({ type: 'text' })
username!: string;
@Prop({ required: true, unique: true, lowercase: true, trim: true, index: true })
@Index({ unique: true })
@Column({ type: 'text' })
email!: string;
@Prop({ trim: true })
mobile?: string;
@Column({ type: 'text', nullable: true })
mobile?: string | null;
@Prop({ required: true, select: false })
@Column({ type: 'text', select: false })
password!: string;
@Prop({ required: true, enum: Role, default: Role.USER, index: true })
@Index()
@Column({ type: 'text' })
role!: Role;
@Prop({ required: true, enum: ClientType, default: ClientType.EXTERNAL, index: true })
@Index()
@Column({ type: 'text' })
clientType!: ClientType;
@Prop({ trim: true, default: '' })
@Column({ type: 'text', default: '' })
appName!: string;
@Prop({ trim: true, default: '' })
@Column({ type: 'text', default: '' })
clientName!: string;
@Prop({ default: true })
@Column({ type: 'boolean', default: true })
isActive!: boolean;
@Prop({ default: false })
@Column({ type: 'boolean', default: false })
isBlocked!: boolean;
/** Future: machine-to-machine auth without JWT. */
@Prop({ select: false })
apiKey?: string;
@Column({ type: 'text', nullable: true, select: false })
apiKey?: string | null;
@Prop({ type: [String], default: [] })
@Column({ type: 'text', array: true, default: () => "'{}'" })
allowedInquiries!: string[];
@Prop({ default: 60 })
@Column({ type: 'int', default: 60 })
requestLimitPerMinute!: number;
@Prop({ default: 10000 })
@Column({ type: 'int', default: 10000 })
requestLimitPerDay!: number;
@Prop({ default: 0 })
@Column({ type: 'int', default: 0 })
totalRequests!: number;
@Prop()
lastLoginAt?: Date;
@Column({ type: 'timestamptz', nullable: true })
lastLoginAt?: Date | null;
@Prop()
passwordChangedAt?: Date;
@Column({ type: 'timestamptz', nullable: true })
passwordChangedAt?: Date | null;
@Prop({ type: Types.ObjectId, ref: 'User' })
createdBy?: Types.ObjectId;
@Column({ type: 'uuid', nullable: true })
createdBy?: string | null;
@Prop({ select: false })
refreshToken?: string;
@Column({ type: 'text', nullable: true, select: false })
refreshToken?: string | null;
@Prop({ type: Object, default: {} })
@Column({ type: 'jsonb', default: () => "'{}'::jsonb" })
metadata!: Record<string, unknown>;
@CreateDateColumn({ type: 'timestamptz' })
createdAt!: Date;
@UpdateDateColumn({ type: 'timestamptz' })
updatedAt!: Date;
}
export const UserSchema = SchemaFactory.createForClass(User);
UserSchema.index({ role: 1, isActive: 1 });
UserSchema.index({ clientType: 1, appName: 1 });
+4 -7
View File
@@ -1,17 +1,14 @@
import { Module, forwardRef } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthModule } from '../auth/auth.module';
import { User, UserSchema } from './schemas/user.schema';
import { User } from './schemas/user.schema';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
@Module({
imports: [
MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
forwardRef(() => AuthModule),
],
imports: [TypeOrmModule.forFeature([User]), forwardRef(() => AuthModule)],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService, MongooseModule],
exports: [UsersService],
})
export class UsersModule {}
+82 -64
View File
@@ -1,11 +1,11 @@
import {
Injectable,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { randomBytes } from 'crypto';
import { Not, QueryDeepPartialEntity, Repository } from 'typeorm';
import { AuditEvent } from '../common/enums/audit-event.enum';
import { ADMIN_ROLES, Role } from '../common/enums/role.enum';
import { AppException } from '../common/exceptions/app-exception';
import { isUniqueViolation, isUuid } from '../database/postgres.helpers';
import { AuditService } from '../audit/audit.service';
import { PasswordService } from '../auth/services/password.service';
import { AuthenticatedUser } from '../auth/interfaces/authenticated-user.interface';
@@ -13,9 +13,8 @@ import { CreateUserDto } from './dto/create-user.dto';
import { ResetPasswordDto } from './dto/reset-password.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { UserMapper } from './mappers/user.mapper';
import { User, UserDocument } from './schemas/user.schema';
import { User } from './schemas/user.schema';
import { UserResponseDto } from './dto/user-response.dto';
import { AppException } from '../common/exceptions/app-exception';
export interface RequestContext {
ip?: string;
@@ -25,30 +24,35 @@ export interface RequestContext {
@Injectable()
export class UsersService {
constructor(
@InjectModel(User.name) private readonly userModel: Model<UserDocument>,
@InjectRepository(User) private readonly users: Repository<User>,
private readonly passwordService: PasswordService,
private readonly auditService: AuditService,
) {}
async findById(id: string): Promise<UserDocument> {
const user = await this.userModel.findById(id);
async findById(id: string): Promise<User> {
if (!isUuid(id)) {
throw new AppException('USER_NOT_FOUND');
}
const user = await this.users.findOne({ where: { id } });
if (!user) {
throw new AppException('USER_NOT_FOUND');
}
return user;
}
async findByUsername(username: string, includePassword = false): Promise<UserDocument | null> {
const query = this.userModel.findOne({ username: username.toLowerCase().trim() });
async findByUsername(username: string, includePassword = false): Promise<User | null> {
const query = this.users
.createQueryBuilder('user')
.where('user.username = :username', { username: username.toLowerCase().trim() });
if (includePassword) {
query.select('+password +refreshToken');
query.addSelect('user.password').addSelect('user.refreshToken');
}
return query.exec();
return query.getOne();
}
async findAll(): Promise<UserResponseDto[]> {
const users = await this.userModel.find().sort({ createdAt: -1 });
return users.map((u) => UserMapper.toResponseDto(u));
const users = await this.users.find({ order: { createdAt: 'DESC' } });
return users.map((user) => UserMapper.toResponseDto(user));
}
async create(
@@ -61,9 +65,7 @@ export class UsersService {
const username = dto.username.toLowerCase().trim();
const email = dto.email.toLowerCase().trim();
const existing = await this.userModel.findOne({
$or: [{ username }, { email }],
});
const existing = await this.users.findOne({ where: [{ username }, { email }] });
if (existing) {
throw new AppException('USERNAME_OR_EMAIL_EXISTS');
}
@@ -71,7 +73,10 @@ export class UsersService {
const passwordHash = await this.passwordService.hash(dto.password);
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,
username,
email,
@@ -87,13 +92,20 @@ export class UsersService {
requestLimitPerDay: dto.requestLimitPerDay ?? 10000,
apiKey,
passwordChangedAt: new Date(),
createdBy: new Types.ObjectId(actor.id),
createdBy: isUuid(actor.id) ? actor.id : null,
metadata: dto.metadata ?? {},
});
}),
);
} catch (error) {
if (isUniqueViolation(error)) {
throw new AppException('USERNAME_OR_EMAIL_EXISTS');
}
throw error;
}
await this.auditService.log(AuditEvent.USER_CREATED, {
actorId: actor.id,
userId: user._id.toString(),
userId: user.id,
username: user.username,
ip: context.ip,
userAgent: context.userAgent,
@@ -110,33 +122,36 @@ export class UsersService {
this.assertCanAssignRole(actor.role, dto.role);
}
const changes: Partial<User> = {};
if (dto.email) {
const email = dto.email.toLowerCase().trim();
const conflict = await this.userModel.findOne({ email, _id: { $ne: id } });
const conflict = await this.users.findOne({ where: { email, id: Not(id) } });
if (conflict) {
throw new AppException('EMAIL_ALREADY_IN_USE');
}
user.email = email;
changes.email = email;
}
Object.assign(user, {
...(dto.fullName !== undefined && { fullName: dto.fullName }),
...(dto.mobile !== undefined && { mobile: dto.mobile }),
...(dto.role !== undefined && { role: dto.role }),
...(dto.clientType !== undefined && { clientType: dto.clientType }),
...(dto.appName !== undefined && { appName: dto.appName }),
...(dto.clientName !== undefined && { clientName: dto.clientName }),
...(dto.isActive !== undefined && { isActive: dto.isActive }),
...(dto.allowedInquiries !== undefined && { allowedInquiries: dto.allowedInquiries }),
...(dto.requestLimitPerMinute !== undefined && {
requestLimitPerMinute: dto.requestLimitPerMinute,
}),
...(dto.requestLimitPerDay !== undefined && { requestLimitPerDay: dto.requestLimitPerDay }),
...(dto.metadata !== undefined && { metadata: dto.metadata }),
});
if (dto.fullName !== undefined) changes.fullName = dto.fullName;
if (dto.mobile !== undefined) changes.mobile = dto.mobile;
if (dto.role !== undefined) changes.role = dto.role;
if (dto.clientType !== undefined) changes.clientType = dto.clientType;
if (dto.appName !== undefined) changes.appName = dto.appName;
if (dto.clientName !== undefined) changes.clientName = dto.clientName;
if (dto.isActive !== undefined) changes.isActive = dto.isActive;
if (dto.allowedInquiries !== undefined) changes.allowedInquiries = dto.allowedInquiries;
if (dto.requestLimitPerMinute !== undefined) {
changes.requestLimitPerMinute = dto.requestLimitPerMinute;
}
if (dto.requestLimitPerDay !== undefined) changes.requestLimitPerDay = dto.requestLimitPerDay;
if (dto.metadata !== undefined) changes.metadata = dto.metadata;
await user.save();
return UserMapper.toResponseDto(user);
if (Object.keys(changes).length > 0) {
await this.users.update(user.id, changes as QueryDeepPartialEntity<User>);
}
return UserMapper.toResponseDto(await this.findById(id));
}
async block(
@@ -145,12 +160,10 @@ export class UsersService {
context: RequestContext = {},
): Promise<UserResponseDto> {
const user = await this.findById(id);
if (user._id.toString() === actor.id) {
if (user.id === actor.id) {
throw new AppException('CANNOT_BLOCK_SELF');
}
user.isBlocked = true;
user.refreshToken = undefined;
await user.save();
await this.users.update(user.id, { isBlocked: true, refreshToken: null });
await this.auditService.log(AuditEvent.USER_BLOCKED, {
actorId: actor.id,
@@ -160,7 +173,7 @@ export class UsersService {
userAgent: context.userAgent,
});
return UserMapper.toResponseDto(user);
return UserMapper.toResponseDto(await this.findById(id));
}
async unblock(
@@ -169,8 +182,7 @@ export class UsersService {
context: RequestContext = {},
): Promise<UserResponseDto> {
const user = await this.findById(id);
user.isBlocked = false;
await user.save();
await this.users.update(user.id, { isBlocked: false });
await this.auditService.log(AuditEvent.USER_UNBLOCKED, {
actorId: actor.id,
@@ -180,7 +192,7 @@ export class UsersService {
userAgent: context.userAgent,
});
return UserMapper.toResponseDto(user);
return UserMapper.toResponseDto(await this.findById(id));
}
async resetPassword(
@@ -189,15 +201,12 @@ export class UsersService {
actor: AuthenticatedUser,
context: RequestContext = {},
): Promise<void> {
const user = await this.userModel.findById(id).select('+password +refreshToken');
if (!user) {
throw new AppException('USER_NOT_FOUND');
}
user.password = await this.passwordService.hash(dto.newPassword);
user.passwordChangedAt = new Date();
user.refreshToken = undefined;
await user.save();
const user = await this.findById(id);
await this.users.update(user.id, {
password: await this.passwordService.hash(dto.newPassword),
passwordChangedAt: new Date(),
refreshToken: null,
});
await this.auditService.log(AuditEvent.PASSWORD_RESET, {
actorId: actor.id,
@@ -209,16 +218,23 @@ export class UsersService {
}
async saveRefreshToken(userId: string, refreshToken: string): Promise<void> {
if (!isUuid(userId)) return;
const hash = await this.passwordService.hash(refreshToken);
await this.userModel.findByIdAndUpdate(userId, { refreshToken: hash });
await this.users.update(userId, { refreshToken: hash });
}
async clearRefreshToken(userId: string): Promise<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> {
const user = await this.userModel.findById(userId).select('+refreshToken');
if (!isUuid(userId)) return false;
const user = await this.users
.createQueryBuilder('user')
.addSelect('user.refreshToken')
.where('user.id = :userId', { userId })
.getOne();
if (!user?.refreshToken) {
return false;
}
@@ -226,11 +242,13 @@ export class UsersService {
}
async recordLogin(userId: string): Promise<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> {
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 {
+153
View File
@@ -0,0 +1,153 @@
import { ConfigService } from '@nestjs/config';
import { AxiosError, AxiosHeaders, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import configuration, { AsiaConfig } from '../../src/config/configuration';
import { InquiryType } from '../../src/common/enums/inquiry-type.enum';
import { ProviderName } from '../../src/common/enums/provider-name.enum';
import { AsiaProvider } from '../../src/providers/implementations/asia.provider';
import { AmitisProvider } from '../../src/providers/implementations/amitis.provider';
import { GeneralTokenService } from '../../src/providers/services/general-token.service';
import { ProviderFactory } from '../../src/providers/factory/provider.factory';
class TestAsiaProvider extends AsiaProvider {
get client() { return this.httpClient; }
}
const context = { requestId: 'asia-test', trackingCode: 'asia-test' };
const payload = { nationalCode: '0012345678', birthDate: '1378-11-24' };
function setup() {
const config: AsiaConfig = {
enabled: true, timeout: 1000, maxRetries: 1, loginUrl: 'https://asia.test/login',
inquiries: {
[InquiryType.PERSON]: {
url: 'https://asia.test/person', username: 'person-user', password: 'person-password',
apiKey: '', authMethod: 'ASIA',
},
[InquiryType.REAL_ESTATE]: {
url: 'https://centinsur.test/estate', username: 'estate-user', password: 'estate-password',
apiKey: '', authMethod: 'AMITIS',
},
},
};
const amitis = { getAccessToken: jest.fn().mockResolvedValue('estate-token') };
const tokens = { getValidAccessToken: jest.fn(async (_key, fetch, _persist, signal) => (await fetch(signal)).accessToken) };
const provider = new TestAsiaProvider(
new ConfigService({ asia: config }),
amitis as unknown as AmitisProvider,
tokens as unknown as GeneralTokenService,
);
const token = `header.${Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 600 })).toString('base64url')}.signature`;
const requests: InternalAxiosRequestConfig[] = [];
const responses: Array<{ status: number; data: unknown }> = [
{ status: 200, data: { isSuccess: true, result: { token } } },
{ status: 200, data: { isSuccess: true, result: { name: 'Test', family: 'Person', birthDate: 13781124 } } },
];
provider.client.defaults.adapter = async (request) => {
requests.push(request);
const next = responses.shift();
if (!next) throw new Error('Unexpected outbound request');
const response: AxiosResponse = { ...next, config: request, statusText: '', headers: new AxiosHeaders() };
if (next.status >= 400) throw new AxiosError('Provider HTTP failure', 'ERR_BAD_RESPONSE', request, undefined, response);
return response;
};
return { provider, config, amitis, tokens, token, requests, responses };
}
describe('Asia provider', () => {
it('logs in with Asia JSON credentials, sends the supplied person contract, and keeps the original national code', async () => {
const { provider, requests, token, tokens, amitis } = setup();
const signal = new AbortController().signal;
const result = await provider.execute(InquiryType.PERSON, payload, { ...context, signal });
expect(JSON.parse(requests[0].data)).toEqual({ userName: 'person-user', password: 'person-password' });
expect(requests[0].url).toBe('https://asia.test/login');
expect(JSON.parse(requests[1].data)).toEqual({ nin: 12345678, birthDate: 13781124, persianBirthDate: '' });
expect(requests[1].headers.Authorization).toBe(`Bearer ${token}`);
expect(requests[0].signal).toBeInstanceOf(AbortSignal);
expect(requests[1].signal).toBe(requests[0].signal);
expect(tokens.getValidAccessToken).toHaveBeenCalledWith('ASIA_PERSON', expect.any(Function),
{ url: 'https://asia.test/login', clientId: 'person-user', username: 'person-user' }, requests[0].signal);
expect(amitis.getAccessToken).not.toHaveBeenCalled();
expect(result).toMatchObject({ ...payload, fullName: 'Test Person',
raw: { name: 'Test', family: 'Person', birthDate: payload.birthDate } });
});
it('uses the token expiry for caching', async () => {
const { provider, tokens } = setup();
tokens.getValidAccessToken.mockImplementationOnce(async (_key, fetch, _persist, signal) => {
const fresh = await fetch(signal);
expect(fresh.expiresIn).toBeGreaterThan(590);
expect(fresh.expiresIn).toBeLessThanOrEqual(600);
return fresh.accessToken;
});
await provider.execute(InquiryType.PERSON, payload, context);
});
it.each([
{ isSuccess: false, message: 'Login denied' },
{ isSuccess: true, result: {} },
])('stops before the inquiry when authentication fails: %j', async (data) => {
const { provider, responses, requests } = setup();
responses[0].data = data;
await expect(provider.execute(InquiryType.PERSON, payload, context)).rejects.toThrow();
expect(requests).toHaveLength(1);
});
it.each([
{ status: 500, data: '' },
{ status: 200, data: '' },
{ status: 200, data: { isSuccess: false, message: 'Inquiry rejected' } },
{ status: 200, data: { isSuccess: true, result: null } },
])('does not treat a failed or malformed inquiry as success: %j', async response => {
const { provider, responses } = setup();
responses[1] = response;
await expect(provider.execute(InquiryType.PERSON, payload, context)).rejects.toThrow();
});
it('uses separate AMITIS credentials and the existing real estate contract', async () => {
const { provider, responses, requests, amitis, tokens } = setup();
responses.splice(0, responses.length, { status: 200, data: { IsSucceed: true, Result: { Result: true } } });
const signal = new AbortController().signal;
await expect(provider.execute(InquiryType.REAL_ESTATE,
{ nationalCode: payload.nationalCode, postalCode: '1234567890' }, { ...context, signal },
)).resolves.toMatchObject({ raw: { IsSucceed: true, Result: { Result: true } } });
expect(amitis.getAccessToken).toHaveBeenCalledWith(ProviderName.ASIA, InquiryType.REAL_ESTATE,
'estate-user', 'estate-password', signal);
expect(tokens.getValidAccessToken).not.toHaveBeenCalled();
expect(requests[0].headers.Authorization).toBe('Bearer estate-token');
expect(JSON.parse(requests[0].data)).toEqual({ NationalId: payload.nationalCode, PostalCode: '1234567890' });
});
it('rejects a year-only person date before login', async () => {
const { provider, requests } = setup();
await expect(provider.execute(InquiryType.PERSON, { ...payload, birthDate: '1378' }, context)).rejects.toThrow('full Jalali birth date');
expect(requests).toHaveLength(0);
});
it('preserves real estate no-match errors', async () => {
const { provider, responses } = setup();
responses.splice(0, responses.length, { status: 200, data: { IsSucceed: true, Result: { Result: false } } });
await expect(provider.execute(InquiryType.REAL_ESTATE,
{ nationalCode: payload.nationalCode, postalCode: '1234567890' }, context,
)).rejects.toMatchObject({ normalizedError: { code: 'INQUIRY_NO_MATCH' } });
});
it('registers Asia for configured routing', () => {
const { provider } = setup();
const config = new ConfigService({ inquiryRouting: {
[InquiryType.PERSON]: { defaultProvider: ProviderName.ASIA, fallbackEnabled: false, fallbackProviders: [] },
} });
const factory = new ProviderFactory(config, undefined!, undefined!, undefined!, undefined!, provider);
expect(factory.getProvidersForInquiry(InquiryType.PERSON)).toEqual([provider]);
});
it('loads ASIA as the person authentication method from the environment', () => {
const before = { ...process.env };
try {
process.env.ASIA_PERSON_URL = 'https://asia.test/person';
process.env.ASIA_PERSON_AUTH_METHOD = 'ASIA';
expect(configuration().asia.inquiries[InquiryType.PERSON]?.authMethod).toBe('ASIA');
} finally {
process.env = before;
}
});
});
+1 -1
View File
@@ -81,7 +81,7 @@ describe('unit helpers and mappers', () => {
it('maps user documents without leaking secrets', () => {
const dto = UserMapper.toResponseDto({
_id: { toString: () => 'user-1' },
id: 'user-1',
fullName: 'Admin User',
username: 'admin',
email: 'admin@example.com',
+18 -22
View File
@@ -1,46 +1,42 @@
import { IdempotencyService } from '../../src/idempotency/idempotency.service';
import { IdempotencyRecordStatus } from '../../src/idempotency/schemas/idempotency-record.schema';
class FakeRecordModel {
class FakeRecordRepository {
private readonly records = new Map<string, any>();
findOne(filter: { scopeHash: string }) {
return { exec: async () => this.records.get(filter.scopeHash) ?? null };
create(record: any) {
return { ...record };
}
async create(record: any) {
if (this.records.has(record.scopeHash)) {
throw Object.assign(new Error('duplicate'), { code: 11000 });
async findOne(options: { where: { scopeHash: string } }) {
return this.records.get(options.where.scopeHash) ?? null;
}
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);
return saved;
}
updateOne(filter: { scopeHash: string; status: IdempotencyRecordStatus }, update: any) {
return {
exec: async () => {
async update(filter: { scopeHash: string; status: IdempotencyRecordStatus }, values: any) {
const record = this.records.get(filter.scopeHash);
if (record?.status === filter.status) Object.assign(record, update.$set);
return { acknowledged: true };
},
};
if (record?.status === filter.status) Object.assign(record, values);
return { affected: record ? 1 : 0 };
}
deleteOne(filter: { scopeHash: string; status: IdempotencyRecordStatus }) {
return {
exec: async () => {
async delete(filter: { scopeHash: string; status: IdempotencyRecordStatus }) {
const record = this.records.get(filter.scopeHash);
if (record?.status === filter.status) this.records.delete(filter.scopeHash);
return { acknowledged: true };
},
};
return { affected: record ? 1 : 0 };
}
}
describe('IdempotencyService', () => {
it('replays completed responses and rejects body reuse', async () => {
const service = new IdempotencyService(new FakeRecordModel() as never);
const service = new IdempotencyService(new FakeRecordRepository() as never);
const input = {
key: 'request-1',
callerId: 'user-1',
@@ -62,7 +58,7 @@ describe('IdempotencyService', () => {
});
it('rejects a duplicate while the original request is in progress', async () => {
const service = new IdempotencyService(new FakeRecordModel() as never);
const service = new IdempotencyService(new FakeRecordRepository() as never);
const input = {
key: 'request-2',
callerId: 'user-1',
+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);
});
});