forked from Shared/esg
299 lines
14 KiB
Markdown
299 lines
14 KiB
Markdown
# Inquiry Gateway
|
||
|
||
Production-grade **NestJS + PostgreSQL** unified inquiry gateway for external service providers.
|
||
|
||
## 📚 Documentation
|
||
|
||
- **[Environment Configuration Guide](docs/ENVIRONMENT_CONFIGURATION.md)** - Complete guide for configuring providers, authentication, and inquiry routing
|
||
- **[API Documentation](docs/API_DOCUMENTATION.md)** - Full API reference with examples, Swagger definitions, and best practices
|
||
- **[Remote Provider Testing](docs/REMOTE_PROVIDER_TESTING.md)** - Test restricted provider integrations through an authorized server using OpenSSH
|
||
|
||
## Architecture
|
||
|
||
```
|
||
Client → POST /inquiries/person (unified)
|
||
→ InquiryController
|
||
→ InquiryService
|
||
→ ProviderOrchestratorService (strategy + fallback)
|
||
→ ProviderFactory → Hamta | Moallem | TejaratNou
|
||
→ LegacyApiProvider (shared base for identical APIs)
|
||
→ BaseProvider (retry, timeout, logging, error normalization)
|
||
→ PostgreSQL inquiry logs
|
||
```
|
||
|
||
### Provider vs Authentication Service
|
||
|
||
The system distinguishes between:
|
||
- **Inquiry Providers** (HAMTA, MOALLEM, TEJARATNOU): Handle actual inquiry requests
|
||
- **Authentication Services** (AMITIS): Provide authentication tokens for providers
|
||
|
||
Each inquiry type can be configured with its own credentials and authentication method. See [Environment Configuration Guide](docs/ENVIRONMENT_CONFIGURATION.md) for details.
|
||
|
||
### Design patterns
|
||
|
||
| Pattern | Usage |
|
||
|---------|--------|
|
||
| **Strategy** | `ProviderOrchestratorService` selects and executes providers |
|
||
| **Factory** | `ProviderFactory` registers and resolves provider instances |
|
||
| **Template method** | `BaseProvider` defines execution pipeline; subclasses implement `callProvider` |
|
||
| **Shared adapter** | `LegacyApiProvider` for Hamta/Moallem identical APIs |
|
||
|
||
### Project structure
|
||
|
||
```
|
||
src/
|
||
├── main.ts
|
||
├── app.module.ts
|
||
├── common/ # DTOs, filters, interceptors, helpers, enums
|
||
├── config/ # @nestjs/config + inquiry routing
|
||
├── auth/ # JWT, RBAC, inquiry access guards
|
||
├── users/ # Unified users (ADMIN / USER / SUPER_ADMIN)
|
||
├── audit/ # Security audit logs
|
||
├── rate-limit/ # Global + per-user throttling
|
||
├── logging/ # PostgreSQL inquiry audit logs
|
||
├── health/ # Liveness, readiness, and admin inquiry diagnostics
|
||
├── idempotency/ # Database-backed idempotency keys for inquiry retries
|
||
├── providers/ # BaseProvider, LegacyApiProvider, factory, orchestrator
|
||
└── inquiry/ # Unified controllers & services
|
||
```
|
||
|
||
## Quick start
|
||
|
||
```bash
|
||
cp .env.example .local.env
|
||
# Edit .local.env with your provider credentials (see Environment Configuration Guide)
|
||
npm install
|
||
npm run cli:create-super-admin # interactive — creates SUPER_ADMIN
|
||
npm run start:dev
|
||
```
|
||
|
||
- API: `http://localhost:8085`
|
||
- Operations dashboard: `http://localhost:8085/dashboard/` (SUPER_ADMIN only)
|
||
- Swagger: `http://localhost:8085/api/docs`
|
||
- Liveness: `GET /health/live` (process-level probe; no database dependency)
|
||
- 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.
|
||
|
||
Health thresholds can be adjusted per deployment with `HEALTH_HEAP_MB`, `HEALTH_DISK_THRESHOLD_PERCENT`, and `HEALTH_DISK_PATH` (see `.env.example`). The liveness and readiness response shapes follow Nest Terminus' standard `{ status, info, error, details }` format.
|
||
|
||
The dashboard includes a SUPER_ADMIN-only “clear inquiry logs” action. It is disabled unless `INQUIRY_LOG_PURGE_ENABLED=true`; enable it only for local maintenance/testing. Every purge is also recorded in the separate security audit collection.
|
||
|
||
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 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
|
||
|
||
| Role | Capabilities |
|
||
|------|----------------|
|
||
| `SUPER_ADMIN` | Full access; create any user including other super admins |
|
||
| `ADMIN` | Manage users; all inquiry types |
|
||
| `USER` | Inquiry access per `allowedInquiries` |
|
||
|
||
**Auth endpoints:** `POST /auth/login`, `POST /auth/refresh`, `POST /auth/logout`, `GET /auth/profile`
|
||
|
||
**User management:** `POST/GET/PATCH /users`, block/unblock, reset password (ADMIN+ only)
|
||
|
||
```bash
|
||
# Login
|
||
curl -X POST http://localhost:8085/auth/login \
|
||
-H "Content-Type: application/json" \
|
||
-d '{"username":"admin","password":"your-password"}'
|
||
|
||
# Person inquiry (JWT)
|
||
curl -X POST http://localhost:8085/inquiry/person \
|
||
-H "Content-Type: application/json" \
|
||
-H "Authorization: Bearer <accessToken>" \
|
||
-H "Idempotency-Key: person-lookup-001" \
|
||
-d '{"nationalCode":"0012345678","birthDate":"1370-05-15"}'
|
||
```
|
||
|
||
`Idempotency-Key` is optional. When supplied, it is scoped to the authenticated caller and route. Reusing it with the same body replays the stored response; reusing it with a different body returns `409`. A duplicate request that is still running also returns `409` with `Retry-After: 1`.
|
||
|
||
Response envelope (`BaseInquiryResponseDto`):
|
||
|
||
```json
|
||
{
|
||
"success": true,
|
||
"provider": "HAMTA",
|
||
"trackingCode": "INQ-20250525-A1B2C3D4",
|
||
"message": "Person inquiry completed successfully",
|
||
"data": { "nationalCode": "0012345678", "birthDate": "1370-05-15", "fullName": "..." },
|
||
"duration": 342
|
||
}
|
||
```
|
||
|
||
## Provider configuration
|
||
|
||
Per-inquiry configuration via environment variables:
|
||
|
||
```env
|
||
# Default provider and fallback chain
|
||
PERSON_DEFAULT_PROVIDER=PARSIAN
|
||
PERSON_FALLBACK_PROVIDERS=HAMTA,TEJARATNOU
|
||
|
||
# Per-inquiry credentials and authentication
|
||
PARSIAN_PERSON_URL=http://reinsure.centinsur.ir/SabtV3Out
|
||
PARSIAN_PERSON_USERNAME=user123
|
||
PARSIAN_PERSON_PASSWORD=pass123
|
||
PARSIAN_PERSON_AUTH_METHOD=SOAP
|
||
|
||
# AMITIS authentication service
|
||
AMITIS_LOGIN_URL=https://auth.services.centinsur.ir/api/security/login
|
||
AMITIS_REFRESH_URL=https://auth.services.centinsur.ir/api/security/RefreshToken
|
||
```
|
||
|
||
See [Environment Configuration Guide](docs/ENVIRONMENT_CONFIGURATION.md) for complete configuration options.
|
||
|
||
## Supported inquiry types
|
||
|
||
| Inquiry Type | Providers | Description |
|
||
|--------------|-----------|-------------|
|
||
| `PERSON_INQUIRY` | PARSIAN, HAMTA, TEJARATNOU, MOALLEM | Person information by national code and birth date |
|
||
| `REAL_ESTATE_INQUIRY` | HAMTA | Real estate ownership information |
|
||
| `POSTAL_CODE_INQUIRY` | HAMTA, MOALLEM | Address validation by postal code |
|
||
| `SHAHKAR_INQUIRY` | PARSIAN, HAMTA, MOALLEM | Mobile number verification |
|
||
| `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 |
|
||
|
||
See [API Documentation](docs/API_DOCUMENTATION.md) for detailed request/response formats.
|
||
|
||
## Authentication methods
|
||
|
||
| Method | Description | Use Case |
|
||
|--------|-------------|----------|
|
||
| `AMITIS` | Token-based auth via AMITIS service | Most CentInsur APIs |
|
||
| `SOAP` | Direct SOAP authentication | Legacy XML-based services |
|
||
| `OAUTH2` | OAuth 2.0 flow | Modern REST APIs |
|
||
| `NONE` | No authentication required | Public APIs |
|
||
|
||
## Token management
|
||
|
||
- **Token refresh**: Every 20 minutes automatically
|
||
- **Distributed refresh lock**: PostgreSQL lease lock prevents concurrent replicas from refreshing the same token
|
||
- **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
|
||
- **Error handling**: Graceful fallback to alternative providers
|
||
|
||
## Adding a new provider
|
||
|
||
1. Add `ProviderName` enum value in `src/common/enums/provider-name.enum.ts`
|
||
2. Add provider configuration in `src/config/configuration.ts`
|
||
3. Implement provider (extend `BaseProvider` or `LegacyApiProvider`)
|
||
4. Register in `src/providers/factory/provider.factory.ts`
|
||
5. Update inquiry routing env vars — **no new HTTP routes required**
|
||
|
||
## Adding a new inquiry type
|
||
|
||
1. Add `InquiryType` enum in `src/common/enums/inquiry-type.enum.ts`
|
||
2. Create request/response DTOs with `class-validator` in `src/inquiry/dto/`
|
||
3. Add `POST /inquiries/<type>` in `InquiryController`
|
||
4. Implement service method using `ProviderOrchestratorService`
|
||
5. Configure routing and credentials in `.local.env`
|
||
|
||
## Security
|
||
|
||
- **JWT**: access + refresh tokens (`JWT_SECRET`, `JWT_REFRESH_SECRET`)
|
||
- **RBAC**: `@Roles()` + `RolesGuard`
|
||
- **Inquiry access**: `allowedInquiries` + `InquiryAccessGuard` (e.g. `PERSON_INQUIRY`)
|
||
- **Rate limiting**: global throttler + per-user `requestLimitPerMinute` / `requestLimitPerDay`
|
||
- **Audit**: `audit_logs` for login, user lifecycle events
|
||
- **Request logging**: All inquiries logged to PostgreSQL with masked sensitive data
|
||
|
||
## Error handling
|
||
|
||
The system provides comprehensive error handling:
|
||
- Network errors: Automatic retry with exponential backoff
|
||
- HTTP 404/408/499/5xx errors: Automatic retry (configurable attempts; 429 is intentionally not retried)
|
||
- SOAP business no-match responses: Classified as `NO_MATCH`/`CAR_POLICY_NOT_FOUND`, not an operational provider outage; the upstream `<Key>` is preserved as `providerCode`
|
||
- HTTP/SOAP provider failures: Automatic fallback to alternative providers when configured
|
||
- Provider isolation: Per-provider circuit breaker and concurrency bulkhead
|
||
- Request deduplication: Optional Mongo-backed idempotency for inquiry POSTs
|
||
- Validation errors: Detailed error messages with field-level validation
|
||
- Authentication errors: Automatic token refresh and retry
|
||
|
||
## Monitoring & observability
|
||
|
||
- **OpenTelemetry**: Distributed tracing support
|
||
- **Inquiry logs**: PostgreSQL tables with full request/response audit trail
|
||
- **Audit logs**: Security events and user actions
|
||
- **Performance metrics**: Request duration, provider response times
|
||
- **Error tracking**: Normalized error codes and messages
|
||
|
||
## Development
|
||
|
||
```bash
|
||
# Development mode with hot reload
|
||
npm run start:dev
|
||
|
||
# Build for production
|
||
npm run build
|
||
|
||
# Run tests
|
||
npm run test
|
||
|
||
# Run tests with coverage
|
||
npm run test:cov
|
||
|
||
# Lint code
|
||
npm run lint
|
||
|
||
# Format code
|
||
npm run format
|
||
```
|
||
|
||
## Environment variables
|
||
|
||
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
|
||
# Application
|
||
NODE_ENV=development
|
||
PORT=8085
|
||
API_PREFIX=api
|
||
|
||
# Database
|
||
DATABASE_URL=postgresql://esg:esg@localhost:5432/inquiry_gateway
|
||
|
||
# JWT
|
||
JWT_SECRET=your-secret-key
|
||
JWT_EXPIRES_IN=15m
|
||
JWT_REFRESH_SECRET=your-refresh-secret
|
||
JWT_REFRESH_EXPIRES_IN=7d
|
||
|
||
# Rate limiting
|
||
# Set RATE_LIMIT_ENABLED=false only for local batch testing. This disables both
|
||
# the global Nest throttler and per-user inquiry limits; it defaults to enabled.
|
||
RATE_LIMIT_ENABLED=true
|
||
THROTTLE_TTL=60
|
||
THROTTLE_LIMIT=100
|
||
|
||
# Provider configuration (see Environment Configuration Guide)
|
||
```
|
||
|
||
## License
|
||
|
||
MIT
|