Compare commits

...
1 Commits
Author SHA1 Message Date
s.hajizadeh 3ad66aa4dc documentation 2026-10-20 10:52:26 +03:30
3 changed files with 124 additions and 18 deletions
+29 -15
View File
@@ -1,6 +1,6 @@
# Inquiry Gateway # Inquiry Gateway
Production-grade **NestJS + MongoDB** unified inquiry gateway for external service providers. Production-grade **NestJS + PostgreSQL** unified inquiry gateway for external service providers.
## 📚 Documentation ## 📚 Documentation
@@ -18,7 +18,7 @@ Client → POST /inquiries/person (unified)
→ ProviderFactory → Hamta | Moallem | TejaratNou → ProviderFactory → Hamta | Moallem | TejaratNou
→ LegacyApiProvider (shared base for identical APIs) → LegacyApiProvider (shared base for identical APIs)
→ BaseProvider (retry, timeout, logging, error normalization) → BaseProvider (retry, timeout, logging, error normalization)
→ MongoDB inquiry_logs → PostgreSQL inquiry logs
``` ```
### Provider vs Authentication Service ### Provider vs Authentication Service
@@ -50,9 +50,9 @@ src/
├── users/ # Unified users (ADMIN / USER / SUPER_ADMIN) ├── users/ # Unified users (ADMIN / USER / SUPER_ADMIN)
├── audit/ # Security audit logs ├── audit/ # Security audit logs
├── rate-limit/ # Global + per-user throttling ├── rate-limit/ # Global + per-user throttling
├── logging/ # MongoDB inquiry audit logs ├── logging/ # PostgreSQL inquiry audit logs
├── health/ # Liveness and MongoDB readiness probes ├── health/ # Liveness, readiness, and admin inquiry diagnostics
├── idempotency/ # Mongo-backed idempotency keys for inquiry retries ├── idempotency/ # Database-backed idempotency keys for inquiry retries
├── providers/ # BaseProvider, LegacyApiProvider, factory, orchestrator ├── providers/ # BaseProvider, LegacyApiProvider, factory, orchestrator
└── inquiry/ # Unified controllers & services └── inquiry/ # Unified controllers & services
``` ```
@@ -60,8 +60,8 @@ src/
## Quick start ## Quick start
```bash ```bash
cp .env.example .env cp .env.example .local.env
# Edit .env with your provider credentials (see Environment Configuration Guide) # Edit .local.env with your provider credentials (see Environment Configuration Guide)
npm install npm install
npm run cli:create-super-admin # interactive — creates SUPER_ADMIN npm run cli:create-super-admin # interactive — creates SUPER_ADMIN
npm run start:dev npm run start:dev
@@ -70,8 +70,9 @@ npm run start:dev
- API: `http://localhost:8085` - API: `http://localhost:8085`
- Operations dashboard: `http://localhost:8085/dashboard/` (SUPER_ADMIN only) - Operations dashboard: `http://localhost:8085/dashboard/` (SUPER_ADMIN only)
- Swagger: `http://localhost:8085/api/docs` - Swagger: `http://localhost:8085/api/docs`
- Liveness: `GET /health/live` (process-level probe; no MongoDB dependency) - Liveness: `GET /health/live` (process-level probe; no database dependency)
- Readiness: `GET /health/ready` (MongoDB, heap, and disk checks; returns `503` when a dependency is unavailable) - Readiness: `GET /health/ready` (PostgreSQL, heap, and disk checks; returns `503` when a dependency is unavailable)
- Admin inquiry diagnostics: `POST /health/inquiries/check` for one live provider check; `POST /health/inquiries/check/batch` starts 1–50 sequential checks and `GET /health/inquiries/check/batch/:jobId` returns progress and results. These endpoints require an ADMIN or SUPER_ADMIN JWT. Batch jobs run in memory, only one can run at a time, and completed reports expire after one hour.
The dashboard is served by the same process and uses the existing JWT login flow. It does not expose a second credential store: only a user whose profile role is `SUPER_ADMIN` can enter it, and the inquiry-log/metrics endpoints enforce that role server-side as well. It provides readiness details, recent audit logs, metrics, manual inquiry execution, and formatted JSON/XML output. Metrics separate valid provider no-match results from operational failures: success rate is calculated over evaluated requests (successes plus operational failures), while no-match results remain visible as their own count. Dashboard panels can be collapsed independently, with their open/closed state remembered in the browser. Typed inquiry routes render field-based forms with examples matching their Swagger DTO definitions; legal-person remains an advanced JSON payload because its controller accepts a provider-specific object. The dashboard is served by the same process and uses the existing JWT login flow. It does not expose a second credential store: only a user whose profile role is `SUPER_ADMIN` can enter it, and the inquiry-log/metrics endpoints enforce that role server-side as well. It provides readiness details, recent audit logs, metrics, manual inquiry execution, and formatted JSON/XML output. Metrics separate valid provider no-match results from operational failures: success rate is calculated over evaluated requests (successes plus operational failures), while no-match results remain visible as their own count. Dashboard panels can be collapsed independently, with their open/closed state remembered in the browser. Typed inquiry routes render field-based forms with examples matching their Swagger DTO definitions; legal-person remains an advanced JSON payload because its controller accepts a provider-specific object.
@@ -178,7 +179,7 @@ See [API Documentation](docs/API_DOCUMENTATION.md) for detailed request/response
## Token management ## Token management
- **Token refresh**: Every 20 minutes automatically - **Token refresh**: Every 20 minutes automatically
- **Distributed refresh lock**: MongoDB lease lock prevents concurrent replicas from refreshing the same token - **Distributed refresh lock**: PostgreSQL lease lock prevents concurrent replicas from refreshing the same token
- **Token expiration**: Daily at 23:59:59 Tehran time - **Token expiration**: Daily at 23:59:59 Tehran time
- **Retry logic**: Automatic retry on transient network failures and HTTP 404/408/499/5xx responses (legacy gateways can return 404 transiently); exhausted attempts retain the provider HTTP/SOAP code for diagnosis - **Retry logic**: Automatic retry on transient network failures and HTTP 404/408/499/5xx responses (legacy gateways can return 404 transiently); exhausted attempts retain the provider HTTP/SOAP code for diagnosis
- **Error handling**: Graceful fallback to alternative providers - **Error handling**: Graceful fallback to alternative providers
@@ -197,7 +198,7 @@ See [API Documentation](docs/API_DOCUMENTATION.md) for detailed request/response
2. Create request/response DTOs with `class-validator` in `src/inquiry/dto/` 2. Create request/response DTOs with `class-validator` in `src/inquiry/dto/`
3. Add `POST /inquiries/<type>` in `InquiryController` 3. Add `POST /inquiries/<type>` in `InquiryController`
4. Implement service method using `ProviderOrchestratorService` 4. Implement service method using `ProviderOrchestratorService`
5. Configure routing and credentials in `.env` 5. Configure routing and credentials in `.local.env`
## Security ## Security
@@ -206,7 +207,7 @@ See [API Documentation](docs/API_DOCUMENTATION.md) for detailed request/response
- **Inquiry access**: `allowedInquiries` + `InquiryAccessGuard` (e.g. `PERSON_INQUIRY`) - **Inquiry access**: `allowedInquiries` + `InquiryAccessGuard` (e.g. `PERSON_INQUIRY`)
- **Rate limiting**: global throttler + per-user `requestLimitPerMinute` / `requestLimitPerDay` - **Rate limiting**: global throttler + per-user `requestLimitPerMinute` / `requestLimitPerDay`
- **Audit**: `audit_logs` for login, user lifecycle events - **Audit**: `audit_logs` for login, user lifecycle events
- **Request logging**: All inquiries logged to MongoDB with masked sensitive data - **Request logging**: All inquiries logged to PostgreSQL with masked sensitive data
## Error handling ## Error handling
@@ -223,7 +224,7 @@ The system provides comprehensive error handling:
## Monitoring & observability ## Monitoring & observability
- **OpenTelemetry**: Distributed tracing support - **OpenTelemetry**: Distributed tracing support
- **Inquiry logs**: MongoDB collection with full request/response audit trail - **Inquiry logs**: PostgreSQL tables with full request/response audit trail
- **Audit logs**: Security events and user actions - **Audit logs**: Security events and user actions
- **Performance metrics**: Request duration, provider response times - **Performance metrics**: Request duration, provider response times
- **Error tracking**: Normalized error codes and messages - **Error tracking**: Normalized error codes and messages
@@ -252,7 +253,20 @@ npm run format
## Environment variables ## Environment variables
Key environment variables (see `.env.example` for complete list): All local settings live in `.local.env`, grouped into shared application settings,
routing, AMITIS authentication, and one section per client. Copy `.env.example`
to `.local.env` for a new checkout and fill in the credentials.
The app, telemetry, admin CLI, and migration CLI load `.local.env` automatically
from the project root. Shell/container variables take priority, followed by
`.local.env`, then `.env` as a legacy fallback. The split `env/*.env` files and
the differently named `.env.local` are inactive. Restart after editing settings.
Docker Compose continues to inject settings from the single `.production.env`
file; it no longer mounts the split `env/` directory. Keep real environment files
out of Git and Docker images.
Key environment variables:
```env ```env
# Application # Application
@@ -261,7 +275,7 @@ PORT=8085
API_PREFIX=api API_PREFIX=api
# Database # Database
MONGODB_URI=mongodb://localhost:27017/inquiry-gateway DATABASE_URL=postgresql://esg:esg@localhost:5432/inquiry_gateway
# JWT # JWT
JWT_SECRET=your-secret-key JWT_SECRET=your-secret-key
+78
View File
@@ -9,6 +9,7 @@ Complete API reference for the ESG Inquiry Gateway with request/response example
- [Shahkar Inquiry](#shahkar-inquiry) - [Shahkar Inquiry](#shahkar-inquiry)
- [Postal Code Inquiry](#postal-code-inquiry) - [Postal Code Inquiry](#postal-code-inquiry)
- [Sheba Inquiry](#sheba-inquiry) - [Sheba Inquiry](#sheba-inquiry)
- [Health and Diagnostic Checks](#health-and-diagnostic-checks)
- [Error Responses](#error-responses) - [Error Responses](#error-responses)
## Base URL ## Base URL
@@ -32,6 +33,83 @@ X-API-Key: your-api-key-here
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
``` ```
## Health and Diagnostic Checks
### Liveness and readiness
`GET /health/live` reports whether the process is responding. `GET /health/ready`
checks PostgreSQL connectivity, heap usage, and disk usage. A failed readiness
check returns HTTP `503`; both probes are intended for deployment monitoring and
do not require a user JWT.
### Run one diagnostic inquiry
These administrative endpoints make a real request to the configured provider
using the supplied sample payload. They require a JWT for a user with the
`ADMIN` or `SUPER_ADMIN` role. Use the request body expected by the selected
inquiry type. The report includes provider, duration, tracking code, attempt
summary, and error details, but does not include the inquiry response data.
```http
POST /health/inquiries/check
Authorization: Bearer <accessToken>
Content-Type: application/json
```
```json
{
"inquiryType": "SHAHKAR",
"sampleData": {
"nationalCode": "4311402422",
"mobileNo": "09226187419"
}
}
```
The response reports `healthy: true` for a successful lookup or a valid no-match
result. Provider or operational errors report `healthy: false`.
### Run a batch of diagnostic inquiries
Submit between 1 and 50 checks. They run sequentially in the background. The
endpoint immediately returns a report with a `jobId`; poll that job to see
progress and the final per-check results.
```http
POST /health/inquiries/check/batch
Authorization: Bearer <accessToken>
Content-Type: application/json
```
```json
{
"checks": [
{
"caseId": "shahkar-row-1",
"inquiryType": "SHAHKAR",
"sampleData": {
"nationalCode": "4311402422",
"mobileNo": "09226187419"
}
}
]
}
```
The start request returns HTTP `202 Accepted`. Only one batch may be queued or
running at a time; another start request receives `409 Conflict`. Batch state is
held in process memory, and completed reports expire after one hour.
```http
GET /health/inquiries/check/batch/{jobId}
Authorization: Bearer <accessToken>
```
The report contains `status` (`QUEUED`, `RUNNING`, `COMPLETED`, or `FAILED`),
`totalChecks`, `completedChecks`, healthy/failed counts, a percentage, timestamps,
and per-check outcomes (`SUCCESS`, `NO_MATCH`, or `FAILURE`). A missing or expired
job returns `404 Not Found`.
## Person Inquiry ## Person Inquiry
Query person information using national code and birth date. Query person information using national code and birth date.
+17 -3
View File
@@ -2,6 +2,16 @@
This guide explains all environment variables used in the ESG Inquiry Gateway system. This guide explains all environment variables used in the ESG Inquiry Gateway system.
All local settings are in `.local.env`, organized into shared settings, routing,
AMITIS authentication, and sections for Asia, Hamta, Moallem, Parsian and Tejaratnou.
Copy `.env.example` to `.local.env` for a new installation.
The app and CLI commands load the file from the project root. Shell/container
variables override `.local.env`, which overrides `.env` as a legacy fallback.
Split files under `env/` and `.env.local` are no longer loaded. Restart after changes.
Docker Compose uses the single `.production.env` file and does not mount `env/`.
## Table of Contents ## Table of Contents
- [Application Settings](#application-settings) - [Application Settings](#application-settings)
- [Database Configuration](#database-configuration) - [Database Configuration](#database-configuration)
@@ -27,11 +37,15 @@ OTEL_NODE_RESOURCE_DETECTORS=env,host,os
## Database Configuration ## Database Configuration
### MongoDB ### PostgreSQL
```env ```env
MONGODB_URI=mongodb://localhost:27017/inquiry-gateway DATABASE_URL=postgresql://esg:esg@localhost:5432/inquiry_gateway
``` ```
The application, TypeORM data source, and readiness probe use PostgreSQL. Run
pending TypeORM migrations with `npm run migration:run`; use
`npm run migration:revert` to revert the most recent migration.
## Authentication & Security ## Authentication & Security
### API Authentication ### API Authentication
@@ -458,7 +472,7 @@ REAL_ESTATE_FALLBACK_ENABLED=false
## Security Best Practices ## Security Best Practices
1. **Never commit `.env` to git** - Use `.env.example` as template 1. **Never commit environment files containing secrets** - Use `.env.example` as template
2. **Rotate credentials regularly** - Update passwords every 90 days 2. **Rotate credentials regularly** - Update passwords every 90 days
3. **Use strong secrets** - Generate random strings for JWT secrets 3. **Use strong secrets** - Generate random strings for JWT secrets
4. **Limit API key distribution** - One key per client application 4. **Limit API key distribution** - One key per client application