forked from Shared/esg
282 lines
13 KiB
Markdown
282 lines
13 KiB
Markdown
# Inquiry Gateway
|
|
|
|
Production-grade **NestJS + MongoDB** 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)
|
|
→ MongoDB 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/ # MongoDB inquiry audit logs
|
|
├── health/ # Liveness and MongoDB readiness probes
|
|
├── idempotency/ # Mongo-backed idempotency keys for inquiry retries
|
|
├── providers/ # BaseProvider, LegacyApiProvider, factory, orchestrator
|
|
└── inquiry/ # Unified controllers & services
|
|
```
|
|
|
|
## Quick start
|
|
|
|
```bash
|
|
cp .env.example .env
|
|
# Edit .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 MongoDB dependency)
|
|
- Readiness: `GET /health/ready` (MongoDB, heap, and disk checks; returns `503` when a dependency is unavailable)
|
|
|
|
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. 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.
|
|
|
|
## 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 |
|
|
| `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**: MongoDB 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 `.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 MongoDB 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**: MongoDB collection 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
|
|
|
|
Key environment variables (see `.env.example` for complete list):
|
|
|
|
```env
|
|
# Application
|
|
NODE_ENV=development
|
|
PORT=8085
|
|
API_PREFIX=api
|
|
|
|
# Database
|
|
MONGODB_URI=mongodb://localhost:27017/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
|