From 3a6f9f46784264cfbfbea91c185950070727f128 Mon Sep 17 00:00:00 2001 From: aniebietafia Date: Tue, 11 Aug 2026 12:22:05 +0100 Subject: [PATCH] chore: updated stale prs to 356 days before close Signed-off-by: aniebietafia --- .github/workflows/stale.yml | 4 +- README.md | 2 + docs/comprehensive_api_docs.md | 939 ++++++++++++++++++ .../api/billing/api_docs/api_docs.md | 489 +++++++++ .../xtraction/api/core/api_docs/api_docs.md | 180 ++++ .../api/core/config/SecurityConfig.java | 7 +- .../api/extraction/ai/api_docs/api_docs.md | 147 +++ .../extraction/documents/api_docs/api_docs.md | 223 +++++ .../extraction/export/api_docs/api_docs.md | 68 ++ .../api/extraction/ocr/api_docs/api_docs.md | 181 ++++ .../extraction/search/api_docs/api_docs.md | 181 ++++ .../extraction/vision/api_docs/api_docs.md | 81 ++ .../api/identity/auth/impl/LoginUserImpl.java | 2 +- .../api/identity/oauth2/api_docs/api_docs.md | 106 ++ .../oauth2/config/OAuth2Properties.java | 2 +- .../oauth2/datamodel/AuthProvider.java | 2 +- .../oauth2/dto/GoogleOAuth2UserInfo.java | 2 +- .../OAuth2AuthenticationFailureHandler.java | 4 +- .../OAuth2AuthenticationSuccessHandler.java | 4 +- .../impl/OAuth2UserProvisioningImpl.java | 8 +- .../OAuth2UserProvisioningService.java | 4 +- .../service/CustomOAuth2UserService.java | 6 +- .../api/identity/user/model/User.java | 2 +- .../user/repository/UserRepository.java | 2 +- .../api/integration/api_docs/api_docs.md | 172 ++++ 25 files changed, 2793 insertions(+), 25 deletions(-) create mode 100644 docs/comprehensive_api_docs.md create mode 100644 src/main/java/com/xtraction/api/billing/api_docs/api_docs.md create mode 100644 src/main/java/com/xtraction/api/core/api_docs/api_docs.md create mode 100644 src/main/java/com/xtraction/api/extraction/ai/api_docs/api_docs.md create mode 100644 src/main/java/com/xtraction/api/extraction/documents/api_docs/api_docs.md create mode 100644 src/main/java/com/xtraction/api/extraction/export/api_docs/api_docs.md create mode 100644 src/main/java/com/xtraction/api/extraction/ocr/api_docs/api_docs.md create mode 100644 src/main/java/com/xtraction/api/extraction/search/api_docs/api_docs.md create mode 100644 src/main/java/com/xtraction/api/extraction/vision/api_docs/api_docs.md create mode 100644 src/main/java/com/xtraction/api/identity/oauth2/api_docs/api_docs.md rename src/main/java/com/xtraction/api/identity/{auth => }/oauth2/config/OAuth2Properties.java (92%) rename src/main/java/com/xtraction/api/identity/{auth => }/oauth2/datamodel/AuthProvider.java (78%) rename src/main/java/com/xtraction/api/identity/{auth => }/oauth2/dto/GoogleOAuth2UserInfo.java (85%) rename src/main/java/com/xtraction/api/identity/{auth => }/oauth2/handler/OAuth2AuthenticationFailureHandler.java (92%) rename src/main/java/com/xtraction/api/identity/{auth => }/oauth2/handler/OAuth2AuthenticationSuccessHandler.java (96%) rename src/main/java/com/xtraction/api/identity/{auth => }/oauth2/impl/OAuth2UserProvisioningImpl.java (96%) rename src/main/java/com/xtraction/api/identity/{auth => }/oauth2/interfaces/OAuth2UserProvisioningService.java (85%) rename src/main/java/com/xtraction/api/identity/{auth => }/oauth2/service/CustomOAuth2UserService.java (94%) create mode 100644 src/main/java/com/xtraction/api/integration/api_docs/api_docs.md diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index ec317f7..bdfab1a 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -16,8 +16,8 @@ jobs: - name: Mark Stale Issues and PRs uses: actions/stale@v9 with: - days-before-stale: 30 - days-before-close: 7 + days-before-stale: 356 + days-before-close: 30 stale-issue-message: | This issue has been automatically marked as stale because it has not had recent activity. It will be closed in 7 days if no further activity occurs. diff --git a/README.md b/README.md index 6619ad8..0628459 100644 --- a/README.md +++ b/README.md @@ -834,6 +834,8 @@ Xtraction uses **JWT Bearer tokens**. The typical flow: ### Endpoint Overview +For frontend implementation, please refer to the [Comprehensive API Documentation](docs/comprehensive_api_docs.md) detailing all endpoints, request/response models, WebSockets progress tracking, and admin endpoints. + Access the full interactive documentation at **http://localhost:8080/swagger-ui** once the API is running. | Category | Base Path | Auth Required | Description | diff --git a/docs/comprehensive_api_docs.md b/docs/comprehensive_api_docs.md new file mode 100644 index 0000000..39cbe13 --- /dev/null +++ b/docs/comprehensive_api_docs.md @@ -0,0 +1,939 @@ +# ๐ŸŒ Xtraction Comprehensive API Documentation + +Welcome to the comprehensive API documentation for **Xtraction**, an AI-powered document processing, OCR extraction, and insight platform. + +This unified document is designed to guide frontend developers through seamless integration with the Xtraction API. + +--- + +## ๐Ÿ› ๏ธ API Fundamentals + +### 1. Base URL +- **Local Development**: `http://localhost:8080` +- **Context Path**: All REST endpoints are prefixed with `/api/v1` unless specified otherwise. + +### 2. Global Response Envelope +Every response from the REST API is wrapped in a standard JSON envelope (`ApiResponse`). + +```json +{ + "success": true, + "statusCode": 200, + "message": "Resource retrieved successfully", + "data": { }, + "timestamp": "2026-07-07T15:20:00.000Z", + "path": "/api/v1/user/profile", + "traceId": "tr_f0932a...", + "errorCode": null, + "errors": null +} +``` + +#### Envelope Field Specification: +| Field | Type | Description | +|:-------------|:----------------------|:--------------------------------------------------------| +| `success` | Boolean | `true` for 2xx codes, `false` otherwise. | +| `statusCode` | Integer | HTTP Status Code (e.g. 200, 201, 400). | +| `message` | String | A human-readable description of the operation result. | +| `data` | Object / Array / Null | The payload return (corresponds to `T`). | +| `timestamp` | String | ISO 8601 UTC timestamp of response generation. | +| `path` | String | Request URI path. | +| `traceId` | String | Correlating ID for server-side debugging logs. | +| `errorCode` | String | Custom application error code (e.g., `ACCOUNT_LOCKED`). | +| `errors` | Array | List of validation errors for `400 Bad Request`. | + +### 3. Global Validation Error Structure +When payload fields fail constraint validation, the API returns `400 Bad Request` with validation metadata: + +```json +{ + "success": false, + "statusCode": 400, + "message": "Validation failed", + "data": null, + "errors": [ + { + "field": "email", + "rejectedValue": "invalid-email-address", + "message": "Must be a valid email address format" + } + ], + "timestamp": "2026-07-07T15:21:00.000Z" +} +``` + +### 4. Pagination Envelope (`PagedResponse`) +Endpoints that return lists are paginated and use the following format within the `data` envelope field: + +```json +{ + "content": [], + "page": 0, + "size": 20, + "totalElements": 45, + "totalPages": 3, + "first": true, + "last": false +} +``` + +--- + +## ๐Ÿ” Authentication & Security + +### 1. Token Mechanics +- **Access Tokens (JWT)**: Passed in request headers. Short-lived (1 hour). + - Header structure: `Authorization: Bearer ` +- **Refresh Tokens**: Set as a rolling `HttpOnly`, `Secure` (production only), `SameSite=Strict` cookie named `refreshToken`. Handled automatically by the browser. + +### 2. Lockout counter +Accounts are locked out for **5 days** after **4 consecutive failed login attempts**. Locking details are persisted in Redis. + +--- + +## ๐Ÿš€ Endpoint Guide + +### Module 1: Authentication & Identity + +#### Signup / Registration +- **URL**: `/api/v1/auth/signup` +- **Method**: `POST` +- **Authentication Required**: No +- **Request Body (`SignupRequestDto`)**: + ```json + { + "firstName": "Jane", + "lastName": "Doe", + "email": "janedoe@example.com", + "password": "SecureP@ssw0rd1!", + "confirmPassword": "SecureP@ssw0rd1!", + "acceptTerms": true, + "subscribeToMarketing": false, + "profession": "Developer", + "organization": "Brints", + "country": "Nigeria" + } + ``` +- **Response (`201 Created`)**: Returns registered user profile without tokens (email verification required). + +#### Login +- **URL**: `/api/v1/auth/login` +- **Method**: `POST` +- **Request Body (`LoginRequestDto`)**: + ```json + { + "email": "janedoe@example.com", + "password": "SecureP@ssw0rd1!" + } + ``` +- **Response (`200 OK`)**: Sets `refreshToken` cookie and returns `accessToken`: + ```json + { + "success": true, + "statusCode": 200, + "message": "User logged in successfully", + "data": { + "userId": "usr_9b1deb4d-3b7d-4bad-9bdd-2b0d7b3d4f82", + "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", + "tokenType": "Bearer", + "accessExpiresIn": 3600000 + } + } + ``` + +#### Email Verification (OTP) +- **URL**: `/api/v1/auth/verify-email` +- **Method**: `POST` +- **Request Body**: + ```json + { + "email": "janedoe@example.com", + "token": "verification-otp-or-token" + } + ``` +- **Response (`200 OK`)**: Returns verification success message. + +#### Resend Verification Email +- **URL**: `/api/v1/auth/resend-verification-email` +- **Method**: `POST` +- **Request Body**: `{ "email": "janedoe@example.com" }` +- **Response (`200 OK`)**: Standard response to prevent email enumeration. + +#### Refresh Access Token +- **URL**: `/api/v1/auth/refresh-token` +- **Method**: `POST` +- **Request cookies**: Cookie `refreshToken` must be present. +- **Response (`200 OK`)**: Returns new `accessToken` and sets rotated `refreshToken` cookie. + +#### Logout (Current Session) +- **URL**: `/api/v1/auth/logout` +- **Method**: `POST` +- **Headers**: `Authorization: Bearer ` +- **Response (`204 No Content`)**: Clears client refresh cookie. + +#### Logout (All Devices) +- **URL**: `/api/v1/auth/logout-all` +- **Method**: `POST` +- **Headers**: `Authorization: Bearer ` +- **Response (`204 No Content`)**: Revokes all refresh tokens linked to account. + +#### Password Generator Helper +- **URL**: `/api/v1/auth/generate-password` +- **Method**: `POST` +- **Request Body**: `{ "passwordLength": "16", "excludedChars": "@#$" }` +- **Response (`200 OK`)**: `{ "generatedPassword": "..." }` + +--- + +### Module 2: User Profile & Settings + +All endpoints below require `Authorization: Bearer ` in headers. + +#### Get Authenticated User Profile +- **URL**: `/api/v1/user/profile` +- **Method**: `GET` +- **Response (`200 OK`)**: Enriched profile details (creation date, status, verification status, profile picture CDN URL). + +#### Forgot Password +- **URL**: `/api/v1/user/forgot-password` +- **Method**: `POST` +- **Rate Limit**: Max 5 requests / hour. +- **Request Body**: `{ "email": "janedoe@example.com" }` + +#### Reset Password with Token +- **URL**: `/api/v1/user/reset-password` +- **Method**: `POST` +- **Rate Limit**: Max 10 attempts / hour. +- **Request Body**: + ```json + { + "email": "janedoe@example.com", + "token": "reset_token_abc...", + "newPassword": "NewSecurePassword99!", + "confirmNewPassword": "NewSecurePassword99!" + } + ``` + +#### Change Password (Session Authenticated) +- **URL**: `/api/v1/user/change-password` +- **Method**: `POST` +- **Request Body**: + ```json + { + "oldPassword": "SecureP@ssw0rd1!", + "newPassword": "BrandNewPassword123*", + "confirmNewPassword": "BrandNewPassword123*" + } + ``` + +#### Update Profile metadata +- **URL**: `/api/v1/user/profile/{userId}` +- **Method**: `PUT` +- **Request Body (`ProfileUpdateRequestDto`)**: + ```json + { + "firstName": "Janet", + "lastName": "Doe", + "country": "Canada", + "profession": "Senior Developer", + "organization": "Brints Corp" + } + ``` + +#### Upload Profile Picture +- **URL**: `/api/v1/user/profile/{userId}/upload` +- **Method**: `POST` +- **Content-Type**: `multipart/form-data` +- **Body**: File payload in key `file`. +- **Response (`200 OK`)**: Returns the CDN storage URL of the uploaded image. + +#### Delete Profile Picture +- **URL**: `/api/v1/user/profile/{userId}/delete` +- **Method**: `DELETE` + +#### Delete Account Immediately +- **URL**: `/api/v1/user/profile/{userId}` +- **Method**: `DELETE` +- **Response (`200 OK`)**: Returns text confirmation `"User profile deleted successfully"`. + +--- + +### Module 3: Document & Collection Management + +#### Upload Documents +- **URL**: `/api/v1/documents/upload` +- **Method**: `POST` +- **Content-Type**: `multipart/form-data` +- **Rate Limit**: 10 requests / minute. +- **Form Data Parameters**: + - `files` (MultipartFile[], Required): The documents to upload. + - `collectionName` (String, Optional): The target collection to upload files into. Creates a new collection if name is new. + - `enableEncryption` (Boolean, Default: false): Flags files to be encrypted at rest in storage. +- **Response (`202 Accepted` - Async Pipeline initiation)**: + ```json + { + "statusCode": 202, + "status": "success", + "message": "Upload initiated. Subscribe to WebSocket progress topic.", + "collectionId": "col_b8d348a0-2f3b-48cf-99bf-8cd64f201083", + "totalFiles": 2, + "wsSubscriptionTopic": "/user/queue/extraction-progress" + } + ``` + +#### Get All Collections For User +- **URL**: `/api/v1/documents/my-collections` +- **Method**: `GET` +- **Response (`200 OK`)**: Returns summary of user collections. + +#### Get Collection Details by ID +- **URL**: `/api/v1/documents/collection/{collectionId}` +- **Method**: `GET` +- **Response (`200 OK`)**: Returns list of file entries (metadata, upload status, size, OCR status) nested in the collection. + +#### Get File Details from Collection +- **URL**: `/api/v1/documents/collection/{collectionId}/document/{documentId}` +- **Method**: `GET` + +#### Delete Collection +- **URL**: `/api/v1/documents/collection/{collectionId}` +- **Method**: `DELETE` + +#### Delete File from Collection +- **URL**: `/api/v1/documents/collection/{collectionId}/document/{documentId}` +- **Method**: `DELETE` + +#### Clear All Collections (Factory Reset) +- **URL**: `/api/v1/documents/clear-all` +- **Method**: `DELETE` + +#### Move Document to Another Collection +- **URL**: `/api/v1/documents/move` +- **Method**: `POST` +- **Request Body (`MoveDocumentRequest`)**: + ```json + { + "sourceCollectionId": "col_123...", + "targetCollectionId": "col_456...", + "documentId": "doc_789..." + } + ``` + +#### Rename Collection +- **URL**: `/api/v1/documents/collection/{collectionId}` +- **Method**: `PUT` +- **Request Body**: `{ "name": "New Collection Name" }` + +#### Rename Document +- **URL**: `/api/v1/documents/collection/{collectionId}/document/{documentId}` +- **Method**: `PUT` +- **Request Body**: `{ "displayName": "new_invoice.pdf" }` + +--- + +### Module 4: OCR (Text Extraction) + +#### Run OCR Extract Text on Document +- **URL**: `/api/v1/collections/{collectionId}/document/{documentId}/extract` +- **Method**: `POST` +- **Query Parameters**: + - `startPage` (Integer, Optional): Start page of extraction. + - `endPage` (Integer, Optional): End page of extraction. + - `pages` (List, Optional): Discrete list of pages (e.g. `1,3,5`). + +#### Upload & Extract All (Shortcut) +- **URL**: `/api/v1/collections/upload/extract-all` +- **Method**: `POST` +- **Content-Type**: `multipart/form-data` +- **Form Data**: + - `files` (MultipartFile[]) + - `startPage`, `endPage`, `pages` (Optional filters) +- **Response (`202 Accepted`)**: Initiates extraction job. Track progress via WebSockets. + +#### Get Collection OCR Results +- **URL**: `/api/v1/collections/{collectionId}/document/results` +- **Method**: `GET` +- **Response (`200 OK`)**: List of OCR text contents for all completed documents in the collection. + +#### Get Document OCR Data +- **URL**: `/api/v1/collections/{collectionId}/document/{documentId}/ocr-data` +- **Method**: `GET` +- **Response (`200 OK`)**: Returns original OCR text, page count, and edit history. + +#### Update/Edit OCR Extracted Content +- **URL**: `/api/v1/collections/{collectionId}/document/{documentId}/content` +- **Method**: `PUT` +- **Request Body (`UpdateOcrContentRequest`)**: + ```json + { + "editedContent": "This is corrected invoice text...", + "contentFormat": "MARKDOWN or HTML" + } + ``` + +#### Download OCR Result as Docx File +- **URL**: `/api/v1/collections/{collectionId}/documents/{documentId}/download/docx` +- **Method**: `GET` +- **Query Parameters**: + - `type` (String, Default: "original"): Options are `"original"` or `"edited"`. +- **Response**: Streams binary word file (`application/vnd.openxmlformats-officedocument.wordprocessingml.document`) directly. + +--- + +### Module 5: AI Insights + +#### Summarize Document Text +- **URL**: `/api/v1/ai/summarize` +- **Method**: `POST` +- **Request Body (`SummarizeRequest`)**: + ```json + { + "documentId": "doc_123...", + "summaryType": "SHORT or DETAILED", + "modelPreference": "openai or mistral" + } + ``` +- **Response (`200 OK`)**: Returns AI summary text. + +#### Classify / Categorize Document +- **URL**: `/api/v1/ai/classify/{documentId}` +- **Method**: `POST` +- **Response (`200 OK`)**: Returns classified document category, key attributes, confidence score, and language indicators. + +--- + +### Module 6: Document Search (Elasticsearch) + +#### Advanced Document Search +- **URL**: `/api/v1/search/documents` +- **Method**: `POST` +- **Request Body (`SearchRequest`)**: + ```json + { + "query": "invoice matching string", + "page": 0, + "size": 10, + "sortBy": "createdAt", + "sortDirection": "desc", + "includeHighlights": true + } + ``` +- **Response (`200 OK`)**: Returns matching list of documents with highlight snippets containing query matches. + +#### Search Within Document Content +- **URL**: `/api/v1/search/documents/content` +- **Method**: `GET` +- **Query Params**: `query` (Required), `page` (Default: 0), `size` (Default: 10) + +#### Quick Document Search +- **URL**: `/api/v1/search/documents` +- **Method**: `GET` +- **Query Params**: `query`, `page`, `size`, `sortBy`, `sortDirection` + +--- + +### Module 7: Credit & Balance System + +#### Get Available Credit Packs +- **URL**: `/api/v1/credits/packs` +- **Method**: `GET` +- **Query Params**: `currency` (Optional, defaults to `"USD"`) +- **Response (`200 OK`)**: Lists packs (price, credit volume, active status). + +#### Get Current User Credit Balance +- **URL**: `/api/v1/credits/balance` +- **Method**: `GET` + +#### Initialize Credit Pack Purchase +- **URL**: `/api/v1/credits/purchase` +- **Method**: `POST` +- **Request Body (`PurchaseCreditPackRequest`)**: + ```json + { + "packId": "pack_uuid", + "paymentGateway": "PAYSTACK or PAYPAL", + "promoCode": "WELCOME10" + } + ``` +- **Response (`200 OK`)**: Returns payment checkout initialization URLs. + +#### Transfer Credits to Another User +- **URL**: `/api/v1/credits/transfer` +- **Method**: `POST` +- **Constraint**: Senders must retain a minimum of 5 credits. Transfers for regular users are capped at 30 credits / month. +- **Request Body (`TransferCreditsRequest`)**: + ```json + { + "recipientEmail": "friend@example.com", + "amount": 15 + } + ``` + +#### Get Credit Transaction History +- **URL**: `/api/v1/credits/transactions` +- **Method**: `GET` +- **Query Params**: `page`, `size` (paginated) + +#### Calculate Credit Cost for Upload +- **URL**: `/api/v1/credits/calculate` +- **Method**: `POST` +- **Content-Type**: `multipart/form-data` +- **Form Data**: `files` (MultipartFile[]) +- **Response (`200 OK`)**: Returns calculated pages, credits required, and if user has enough balance. + +--- + +### Module 8: Subscriptions & Plans + +#### Get Current Active Subscription +- **URL**: `/api/v1/subscriptions/me` +- **Method**: `GET` +- **Response (`200 OK`)**: returns plan tier, quotas (ocr limits, document limits, storage limits), reset dates. + +#### Activate Free Trial +- **URL**: `/api/v1/subscriptions/trial/{planId}` +- **Method**: `POST` +- **Response (`200 OK`)**: Success message. + +--- + +### Module 9: PayPal Payments & Subscriptions + +#### Get PayPal Plans (Public) +- **URL**: `/api/v1/paypal/plans` +- **Method**: `GET` + +#### Create PayPal Order (One-Time) +- **URL**: `/api/v1/paypal/orders` +- **Method**: `POST` +- **Request Body (`CreateOrderRequest`)**: + ```json + { + "packId": "pack_uuid", + "currency": "USD" + } + ``` +- **Response (`201 Created`)**: Returns order approval link to redirect user to PayPal. + +#### Capture PayPal Order +- **URL**: `/api/v1/paypal/orders/{orderId}/capture` +- **Method**: `POST` + +#### Get PayPal Order Details +- **URL**: `/api/v1/paypal/orders/{orderId}` +- **Method**: `GET` + +#### Refund PayPal Payment +- **URL**: `/api/v1/paypal/refund` +- **Method**: `POST` +- **Request Body**: `{ "captureId": "...", "amount": "9.99", "currency": "USD" }` + +#### Get PayPal Payment History +- **URL**: `/api/v1/paypal/payments/history` +- **Method**: `GET` + +#### Create PayPal Subscription (Recurring) +- **URL**: `/api/v1/paypal/subscriptions` +- **Method**: `POST` +- **Request Body (`CreateSubscriptionRequest`)**: + ```json + { + "planId": "plan_uuid" + } + ``` +- **Response (`201 Created`)**: Returns PayPal checkout link. + +#### Cancel / Suspend / Activate Subscription +- **URL**: `/api/v1/paypal/subscriptions/{subscriptionId}/cancel` +- **URL**: `/api/v1/paypal/subscriptions/{subscriptionId}/suspend` +- **URL**: `/api/v1/paypal/subscriptions/{subscriptionId}/activate` +- **Method**: `POST` +- **Query Params**: `reason` (Optional) + +#### PayPal Webhook Endpoint +- **URL**: `/api/v1/paypal/webhook` +- **Method**: `POST` +- **Headers Required**: PayPal authentication headers (Transmission ID, signature, etc.). + +--- + +### Module 10: Paystack Payments & Subscriptions + +#### Initialize Paystack Transaction +- **URL**: `/api/v1/paystack/transaction/initialize` +- **Method**: `POST` +- **Request Body (`InitializeTransactionRequest`)**: + ```json + { + "amount": 5000, // In minor unit (kobo/cents) + "email": "user@example.com", + "planCode": "PLN_...", // Optional + "callbackUrl": "https://frontend.com/callback" + } + ``` +- **Response (`200 OK`)**: Returns Paystack access code and redirect authorization URL. + +#### Verify Paystack Transaction +- **URL**: `/api/v1/paystack/transaction/verify/{reference}` +- **Method**: `GET` + +#### Get Paystack Payment History +- **URL**: `/api/v1/paystack/transaction/history` +- **Method**: `GET` + +#### Create Paystack Subscription +- **URL**: `/api/v1/paystack/subscription` +- **Method**: `POST` +- **Request Body**: `{ "plan": "PLN_code", "authorization": "AUTH_code" }` + +#### Enable / Disable Paystack Subscription +- **URL**: `/api/v1/paystack/subscription/{subscriptionCode}/enable` +- **URL**: `/api/v1/paystack/subscription/{subscriptionCode}/disable` +- **Method**: `POST` +- **Query Params**: `emailToken` (Required) + +#### Paystack Webhook Receiver +- **URL**: `/api/v1/paystack/webhook` +- **Method**: `POST` +- **Headers Required**: `x-paystack-signature` + +--- + +### Module 11: Receipts + +#### Get Receipts +- **URL**: `/api/v1/receipts` +- **Method**: `GET` +- **Query Params**: `page`, `size` + +#### Get Receipt Details +- **URL**: `/api/v1/receipts/{receiptNumber}` +- **Method**: `GET` + +#### Download Receipt (PDF CDN Link) +- **URL**: `/api/v1/receipts/{receiptNumber}/download` +- **Method**: `GET` +- **Response (`200 OK`)**: Returns the absolute file URL. + +#### Delete Receipt +- **URL**: `/api/v1/receipts/{receiptNumber}` +- **Method**: `DELETE` + +#### Bulk Delete Receipts +- **URL**: `/api/v1/receipts` +- **Method**: `DELETE` +- **Query Params**: `receiptNumbers` (Comma-separated list of identifiers) + +--- + +### Module 12: Promo Codes + +#### Validate Promo Code +- **URL**: `/api/v1/promo_codes/validate/{code}` +- **Method**: `GET` + +#### Apply Promo Code +- **URL**: `/api/v1/promo_codes/apply` +- **Method**: `POST` +- **Request Body (`ApplyPromoCodeRequest`)**: + ```json + { + "code": "PROMO10", + "amount": 100.00 + } + ``` + +#### List Available Promos for User +- **URL**: `/api/v1/promo_codes/available` +- **Method**: `GET` + +--- + +### Module 13: Currency & Rates + +#### Convert Currencies +- **URL**: `/api/v1/currency/convert` +- **Method**: `GET` +- **Query Params**: `amountInCents`, `from`, `to` + +#### Get Current Rates +- **URL**: `/api/v1/currency/rates` +- **Method**: `GET` + +--- + +### Module 14: Push Notifications & Preferences + +#### Register Device Token +- **URL**: `/api/v1/notifications/device` +- **Method**: `POST` +- **Request Body (`RegisterDeviceRequest`)**: + ```json + { + "token": "firebase-device-token", + "deviceType": "ios" // OR "android" + } + ``` + +#### Unregister Device Token +- **URL**: `/api/v1/notifications/device/{tokenId}` +- **Method**: `DELETE` + +#### Get Registered Devices +- **URL**: `/api/v1/notifications/devices` +- **Method**: `GET` + +#### Get Notifications list +- **URL**: `/api/v1/notifications` +- **Method**: `GET` +- **Query Params**: `page`, `size` + +#### Get Unread Notifications list +- **URL**: `/api/v1/notifications/unread` +- **Method**: `GET` + +#### Mark Notification as Read +- **URL**: `/api/v1/notifications/{id}/read` +- **Method**: `PATCH` + +#### Mark All Notifications as Read +- **URL**: `/api/v1/notifications/read-all` +- **Method**: `PATCH` + +#### Delete Notification +- **URL**: `/api/v1/notifications/{id}` +- **Method**: `DELETE` + +#### Get Notification Preferences +- **URL**: `/api/v1/notifications/preferences` +- **Method**: `GET` + +#### Update Notification Preferences +- **URL**: `/api/v1/notifications/preferences` +- **Method**: `PUT` +- **Request Body (`UpdatePreferencesRequest`)**: + ```json + { + "emailEnabled": true, + "pushEnabled": false, + "smsEnabled": false, + "marketingEnabled": true + } + ``` + +--- + +### Module 15: Storage Allocation + +#### Get Storage Information +- **URL**: `/api/v1/storage` +- **Method**: `GET` +- **Response (`200 OK`)**: + ```json + { + "success": true, + "statusCode": 200, + "message": "Storage information retrieved successfully", + "data": { + "userId": "usr_...", + "storageUsed": 1048576, // In bytes + "storageLimit": 10737418240, // In bytes (10GB) + "percentageUsed": 0.01 + } + } + ``` + +--- + +## ๐Ÿ”Œ WebSocket & Real-Time Progress Tracking + +For asynchronous operations (uploading large files, OCR page extractions, AI classification), Xtraction streams live updates via WebSockets (SockJS + STOMP protocol). + +### 1. The One-Time Ticket Handshake +Standard WebSockets do not support sending custom authentication headers in browsers. Xtraction solves this using a **one-time ticket exchange**: + +1. **Request Ticket**: Post to the ticket endpoint with your JWT bearer token in headers. + - **URL**: `/api/v1/ws/ticket` + - **Method**: `POST` + - **Headers**: `Authorization: Bearer ` + - **Response**: + ```json + { + "ticket": "ticket_uuid_string", + "wsUrl": "/ws/extraction-progress" + } + ``` +2. **Connect Handshake**: Connect to the SockJS endpoint `http://localhost:8080/ws/extraction-progress`. Include the `ticket` token in your STOMP connect headers: + ```javascript + const socket = new SockJS('http://localhost:8080/ws/extraction-progress'); + const stompClient = Stomp.over(socket); + stompClient.connect({ ticket: 'ticket_uuid_string' }, onConnect, onError); + ``` + +> [!IMPORTANT] +> The ticket is single-use and expires in Redis after **30 seconds** if not connected. + +### 2. Subscribing to Progress Channel +Once the connection is active, subscribe to your user-specific private queue: +- **Destination**: `/user/queue/extraction-progress` + +### 3. Event Payload Structure (`ExtractionProgressEvent`) +Messages dispatched from the server are JSON strings structured as: + +```json +{ + "collectionId": "col_b8d3...", + "documentId": "doc_e3d3...", + "fileName": "invoice_99.pdf", + "eventType": "EXTRACTION_PROGRESS", + "progress": 65, + "message": "Running Tesseract OCR on page 3", + "timestamp": "2026-07-07T15:22:00.123Z", + "metadata": { + "totalPages": 5, + "currentPage": 3 + } +} +``` + +#### Event Type Enums (`ProgressEventType`): +- `UPLOAD_STARTED`: Document streaming initiated. +- `FILE_UPLOADING`: Document actively streaming to cloud store. +- `FILE_UPLOADED`: Upload completed. +- `FILE_UPLOAD_FAILED`: Upload failed. +- `EXTRACTION_QUEUED`: Document queued for background OCR/Tesseract execution. +- `EXTRACTION_STARTED`: OCR process launched. +- `EXTRACTION_PROGRESS`: Progress update containing parsed pages info. +- `EXTRACTION_COMPLETED`: OCR finished. +- `EXTRACTION_FAILED`: OCR processing failure. +- `PIPELINE_COMPLETED`: Downstream NLP analysis and search indexing successfully finalized. + +--- + +## ๐Ÿ›ก๏ธ Administrative Console APIs + +These endpoints are strictly protected and require a user session with role `ADMIN`, `SUPER_ADMIN`, or `MODERATOR`. + +### 1. User Management + +#### Get All Users (Filtered & Paginated) +- **URL**: `/api/v1/admin/users` +- **Method**: `GET` +- **Query Filters**: `page`, `size`, `sortBy`, `sortOrder`, `search`, `role`, `isActive`, `isVerified`, `country`, `subscriptionPlan`. + +#### Enriched User Profile +- **URL**: `/api/v1/admin/{userId}` +- **Method**: `GET` +- **Response**: Aggregates metadata, usage quotas, credit balances, trial status, and Redis lockout status flags. + +#### Toggle User Status (Activate/Deactivate) +- **URL**: `/api/v1/admin/users/{userId}/activate` +- **URL**: `/api/v1/admin/users/{userId}/deactivate` +- **Method**: `PUT` +- **Request Body**: `{ "reason": "Reason details" }` + +#### Account Unlocks +- **URL**: `/api/v1/admin/users/{userId}/unlock` +- **Method**: `PUT` +- **Description**: Clears locked-out state flags in Redis database. + +#### Force Verify Email Address +- **URL**: `/api/v1/admin/users/{userId}/force-verify` +- **Method**: `PUT` + +#### Trigger Password Reset Email +- **URL**: `/api/v1/admin/users/{userId}/reset-password` +- **Method**: `POST` + +#### Change User Role +- **URL**: `/api/v1/admin/change-role` +- **Method**: `PUT` +- **Request Body**: `{ "userId": "...", "role": "ADMIN" }` + +#### Soft Delete Account +- **URL**: `/api/v1/admin/users/{userId}/soft-delete` +- **Method**: `DELETE` +- **Role Requirement**: `SUPER_ADMIN` only. + +#### Impersonate User +- **URL**: `/api/v1/admin/users/{userId}/impersonate` +- **Method**: `POST` +- **Role Requirement**: `SUPER_ADMIN` only. Generates a standard JWT token for the target user. Audit-logged at `WARN` level. +- **Request Body**: `{ "reason": "Reason details" }` + +#### Adjust User Subscription Limits +- **URL**: `/api/v1/admin/users/{userId}/subscription` +- **Method**: `PUT` +- **Role Requirement**: `SUPER_ADMIN` only. +- **Request Body**: + ```json + { + "plan": "PRO_MONTHLY", + "billingIntervalUnit": "MONTH", + "billingIntervalValue": 1, + "autoRenew": true, + "source": "ADMIN_OVERRIDE" + } + ``` + +#### Reset User Quotas +- **URL**: `/api/v1/admin/users/{userId}/quotas/reset` +- **Method**: `POST` + +--- + +### 2. Subscription Plan Management + +#### Create Subscription Plan +- **URL**: `/api/v1/admin/subscriptions/plans` +- **Method**: `POST` + +#### Update Plan Limits +- **URL**: `/api/v1/admin/subscriptions/plans/{planId}` +- **Method**: `PUT` +- **Role Requirement**: `SUPER_ADMIN` only. + +#### Toggle Plan Status (Activate/Deactivate) +- **URL**: `/api/v1/admin/subscriptions/plans/{planId}/status` +- **Method**: `PATCH` +- **Role Requirement**: `SUPER_ADMIN` only. +- **Query Params**: `isActive` (Boolean) +- **Request Body**: `{ "reason": "..." }` + +#### List Plan Subscribers +- **URL**: `/api/v1/admin/subscriptions/plans/{planId}/subscribers` +- **Method**: `GET` +- **Query Params**: `page`, `size` + +--- + +### 3. Analytics & Statistics + +These endpoints retrieve aggregated KPIs for system dashboard components: +- **Dashboard metrics summary**: `GET /api/v1/admin/dashboard/stats` +- **User signups statistics**: `GET /api/v1/admin/users/stats` +- **Subscriptions & revenue metrics**: `GET /api/v1/admin/subscriptions/stats` +- **Credits circulation analytics**: `GET /api/v1/admin/credits/stats` +- **Promo code usage analytics**: `GET /api/v1/admin/promo_codes/stats` +- **Document & collection storage metrics**: `GET /api/v1/admin/documents/stats` +- **Push notification statistics**: `GET /api/v1/admin/notifications/stats` +- **Failed logins & security blocks stats**: `GET /api/v1/admin/security/stats` +- **Payment gateways performance statistics**: `GET /api/v1/admin/payments/stats` + +--- + +### 4. Search Index Sync (Elasticsearch) + +- **Sync All DB records**: `POST /api/v1/admin/elasticsearch/sync` +- **Sync Users**: `POST /api/v1/admin/elasticsearch/sync/users` +- **Sync Documents**: `POST /api/v1/admin/elasticsearch/sync/documents` +- **Sync Payments**: `POST /api/v1/admin/elasticsearch/sync/payments` + +--- + +### 5. Storage Recalculation Migration + +- **URL**: `/api/v1/admin/storage/migrate` +- **Method**: `POST` +- **Role Requirement**: `SUPER_ADMIN` only. +- **Description**: Recalculates storage footprint sizing parameters for all existing profiles. diff --git a/src/main/java/com/xtraction/api/billing/api_docs/api_docs.md b/src/main/java/com/xtraction/api/billing/api_docs/api_docs.md new file mode 100644 index 0000000..4837b36 --- /dev/null +++ b/src/main/java/com/xtraction/api/billing/api_docs/api_docs.md @@ -0,0 +1,489 @@ +# ๐Ÿ’ณ Billing, Payments, and Subscriptions API Documentation + +This module manages currency conversions, plan pricing, user subscription lifecycles, credit transactions, PayPal and Paystack integrations, receipts, and promo code mechanics. + +--- + +## ๐Ÿ› ๏ธ Section 1: Currency & Pricing (Public APIs) + +These endpoints are publicly accessible to support landing pages, pricing grids, and currency selectors. + +### 1. Convert Amount between Currencies +- **URL**: `/api/v1/currency/convert` +- **Method**: `GET` +- **Authentication**: None +- **Query Parameters**: + - `amountInCents` (Long, Required): Amount in the smallest unit (e.g. 500 for $5.00, or 500 for 5.00 NGN). + - `from` (String, Optional, Default: `"USD"`): Code of origin currency. + - `to` (String, Required): Code of target currency. +- **Supported Currencies**: `USD`, `NGN`, `EUR`, `GBP`, `CAD`, `AUD`. +- **Response (`200 OK`)**: + ```json + { + "currency": "NGN", + "amount": 7500.00, + "formatted": "โ‚ฆ7,500.00", + "exchangeRate": 1500.000000 + } + ``` + +### 2. Get Exchange Rates +- **URL**: `/api/v1/currency/rates` +- **Method**: `GET` +- **Response (`200 OK`)**: + ```json + { + "baseCurrency": "USD", + "rates": { + "USD": 1.000000, + "NGN": 1500.000000, + "EUR": 0.920000, + "GBP": 0.780000, + "CAD": 1.360000, + "AUD": 1.480000 + } + } + ``` + +### 3. List Supported Currencies +- **URL**: `/api/v1/currency/supported` +- **Method**: `GET` +- **Response (`200 OK`)**: + ```json + [ + { "code": "USD", "symbol": "$", "name": "US Dollar" }, + { "code": "NGN", "symbol": "โ‚ฆ", "name": "Nigerian Naira" } + ] + ``` + +### 4. Get Subscription Plans with Pricing +- **URL**: `/api/v1/plans` +- **Method**: `GET` +- **Query Parameters**: + - `currency` (String, Optional, Default: `"USD"`): Convert prices to this currency. +- **Response (`200 OK` - `AllPlansWithPricingResponse`)**: + ```json + { + "currencyCode": "USD", + "currencySymbol": "$", + "individualPlans": [ + { + "id": "starter_uuid", + "name": "STARTER_MONTHLY", + "price": 9.00, + "billingInterval": "MONTH", + "limits": { + "storageBytes": 2791728742, + "ocrPages": 150, + "documentUploads": 30, + "aiOperations": 0 + } + } + ], + "teamPlans": [] + } + ``` + +--- + +## ๐Ÿ”‘ Section 2: User Subscriptions + +Requires `Authorization: Bearer ` in headers. + +### 1. Get Current Subscription details +- **URL**: `/api/v1/subscriptions/me` +- **Method**: `GET` +- **Response (`200 OK` - `UserSubscriptionDetailsDto`)**: + ```json + { + "success": true, + "statusCode": 200, + "message": "Subscription details retrieved successfully", + "data": { + "planName": "STARTER_MONTHLY", + "status": "active", + "periodStart": "2026-07-01T12:00:00Z", + "periodEnd": "2026-08-01T12:00:00Z", + "autoRenew": true, + "trialEndsAt": null, + "storageUsedBytes": 1048576, + "storageLimitBytes": 2791728742, + "ocrPagesUsed": 4, + "ocrPagesLimit": 150, + "documentsUploadedCount": 3, + "documentsUploadedLimit": 30 + } + } + ``` + +### 2. Activate Free Trial +- **URL**: `/api/v1/subscriptions/trial/{planId}` +- **Method**: `POST` +- **Response (`200 OK`)**: Activates a 10-day trial for the specified plan. Returns validation error if a trial was already activated. + +--- + +## ๐Ÿช™ Section 3: Credit Packs & transfers + +### 1. List Available Credit Packs +- **URL**: `/api/v1/credits/packs` +- **Method**: `GET` +- **Query Parameters**: + - `currency` (String, Optional): Defaults to `"USD"`. +- **Response (`200 OK`)**: + ```json + { + "success": true, + "statusCode": 200, + "message": "Credit packs retrieved", + "data": [ + { + "id": "pack_uuid_1", + "name": "STARTER_PACK", + "creditsIncluded": 20, + "priceInCents": 500, + "currency": "USD" + } + ] + } + ``` + +### 2. Get User Credit Balance +- **URL**: `/api/v1/credits/balance` +- **Method**: `GET` + +### 3. Initialize Credit Pack Purchase +- **URL**: `/api/v1/credits/purchase` +- **Method**: `POST` +- **Request Body (`PurchaseCreditPackRequest`)**: + ```json + { + "packId": "pack_uuid_1", + "paymentGateway": "PAYSTACK", // Or "PAYPAL" + "promoCode": "DISCOUNT10" // Optional + } + ``` +- **Response (`200 OK`)**: + ```json + { + "success": true, + "statusCode": 200, + "message": "Payment initialized", + "data": { + "purchaseId": "purch_uuid", + "paymentUrl": "https://checkout.paystack.com/...", // Redirect user here + "gatewayReference": "PAY_ref..." + } + } + ``` + +### 4. Transfer Credits to Another User +- **URL**: `/api/v1/credits/transfer` +- **Method**: `POST` +- **Constraints**: + - Senders must retain at least **5 credits** after transfer. + - Non-admin users are limited to transfers of **30 credits / month** maximum. +- **Request Body (`TransferCreditsRequest`)**: + ```json + { + "recipientEmail": "friend@example.com", + "amount": 10 + } + ``` +- **Response (`200 OK`)**: + ```json + { + "success": true, + "statusCode": 200, + "message": "Credits transferred successfully", + "data": { + "transferId": "tx_uuid", + "creditsTransferred": 10, + "senderBalanceAfter": 45, + "recipientEmail": "friend@example.com", + "recipientName": "John Friend" + } + } + ``` + +### 5. Get Transaction History +- **URL**: `/api/v1/credits/transactions` +- **Method**: `GET` +- **Query Parameters**: + - `page` (Integer, Optional, Default: 0): Page number. + - `size` (Integer, Optional, Default: 20): Page size (max 100). + +### 6. Calculate Credit Cost for Files +- **URL**: `/api/v1/credits/calculate` +- **Method**: `POST` +- **Content-Type**: `multipart/form-data` +- **Form Data**: + - `files` (MultipartFile[]): File array. +- **Response (`200 OK`)**: + ```json + { + "success": true, + "statusCode": 200, + "message": "Page count calculated", + "data": { + "totalPages": 5, + "creditsRequired": 5, + "currentBalance": 120, + "hasEnoughCredits": true + } + } + ``` + +--- + +## Section 4: PayPal Payment Gateway + +### 1. Create PayPal Order (One-Time) +- **URL**: `/api/v1/paypal/orders` +- **Method**: `POST` +- **Request Body (`CreateOrderRequest`)**: + ```json + { + "packId": "pack_uuid_1", + "currency": "USD" + } + ``` +- **Response (`201 Created`)**: + ```json + { + "status": true, + "message": "Order created successfully", + "data": { + "orderId": "5O0648...", + "status": "CREATED", + "approvalUrl": "https://www.paypal.com/checkoutnow?token=...", + "links": [ ] + } + } + ``` + +### 2. Capture PayPal Order +- **URL**: `/api/v1/paypal/orders/{orderId}/capture` +- **Method**: `POST` +- **Response (`200 OK`)**: + ```json + { + "status": true, + "message": "Payment captured successfully", + "data": { + "captureId": "CAP_123...", + "orderId": "5O0648...", + "status": "COMPLETED", + "amount": "5.00", + "currency": "USD" + } + } + ``` + +### 3. Get PayPal Order Details +- **URL**: `/api/v1/paypal/orders/{orderId}` +- **Method**: `GET` + +### 4. Create PayPal Subscription +- **URL**: `/api/v1/paypal/subscriptions` +- **Method**: `POST` +- **Request Body (`CreateSubscriptionRequest`)**: + ```json + { + "planId": "starter_uuid" + } + ``` +- **Response (`201 Created`)**: Returns order approvals links and `subscriptionId`. + +### 5. Cancel / Suspend / Activate Subscription +- **URL**: `/api/v1/paypal/subscriptions/{subscriptionId}/cancel` +- **URL**: `/api/v1/paypal/subscriptions/{subscriptionId}/suspend` +- **URL**: `/api/v1/paypal/subscriptions/{subscriptionId}/activate` +- **Method**: `POST` +- **Query Parameters**: + - `reason` (String, Optional): Reason text. + +--- + +## โšก Section 5: Paystack Payment Gateway + +### 1. Initialize Paystack Transaction +- **URL**: `/api/v1/paystack/transaction/initialize` +- **Method**: `POST` +- **Request Body (`InitializeTransactionRequest`)**: + ```json + { + "amount": 5000, // minor units (50.00 NGN) + "email": "janedoe@example.com", + "planCode": "PLN_starter", // Optional (for subscription initialization) + "callbackUrl": "https://yourfrontend.com/paystack/callback" + } + ``` +- **Response (`200 OK`)**: + ```json + { + "statusCode": 200, + "status": "success", + "message": "Transaction initialized successfully", + "data": { + "authorizationUrl": "https://checkout.paystack.com/39a...", + "accessCode": "39azl...", + "reference": "rf_123..." + } + } + ``` + +### 2. Verify Paystack Transaction +- **URL**: `/api/v1/paystack/transaction/verify/{reference}` +- **Method**: `GET` + +### 3. Enable / Disable Paystack Subscription +- **URL**: `/api/v1/paystack/subscription/{subscriptionCode}/enable` +- **URL**: `/api/v1/paystack/subscription/{subscriptionCode}/disable` +- **Method**: `POST` +- **Query Parameters**: + - `emailToken` (String, Required): Verification token sent to the user email. + +--- + +## ๐Ÿงพ Section 6: Receipts + +### 1. Get User Receipts +- **URL**: `/api/v1/receipts` +- **Method**: `GET` +- **Query Parameters**: + - `page`, `size` (paginated list of user receipts). + +### 2. Download Receipt PDF Link +- **URL**: `/api/v1/receipts/{receiptNumber}/download` +- **Method**: `GET` +- **Response (`200 OK`)**: Returns raw string link to download PDF copy. + +### 3. Bulk Delete Receipts +- **URL**: `/api/v1/receipts` +- **Method**: `DELETE` +- **Query Parameters**: + - `receiptNumbers` (List, Required): Comma-separated receipt number identifiers. + +--- + +## ๐Ÿท๏ธ Section 7: Promo Codes + +### 1. Validate Promo Code +- **URL**: `/api/v1/promo_codes/validate/{code}` +- **Method**: `GET` +- **Response (`200 OK`)**: + ```json + { + "success": true, + "statusCode": 200, + "message": "Promo code is valid", + "data": { + "code": "DISCOUNT10", + "valid": true, + "message": "Active discount rate: 10%" + } + } + ``` + +### 2. Apply Promo Code +- **URL**: `/api/v1/promo_codes/apply` +- **Method**: `POST` +- **Request Body (`ApplyPromoCodeRequest`)**: + ```json + { + "code": "DISCOUNT10", + "amount": 150.00 + } + ``` +- **Response (`200 OK` - `DiscountCalculationData`)**: + ```json + { + "originalAmount": 150.00, + "discountAmount": 15.00, + "finalAmount": 135.00, + "minPurchaseRequirementMet": true, + "minPurchaseAmount": 0.00 + } + ``` + +### 3. List Available User Promos +- **URL**: `/api/v1/promo_codes/available` +- **Method**: `GET` + +--- + +## ๐Ÿ›ก๏ธ Section 8: Admin Console Billing Endpoints + +Requires `ADMIN` or `SUPER_ADMIN` role session. + +### 1. Allocate Credits directly +- **URL**: `/api/v1/admin/credits/allocate` +- **Method**: `POST` +- **Request Body (`AllocateCreditsRequest`)**: + ```json + { + "userId": "usr_uuid", + "amount": 100, + "reason": "Direct administrative bonus" + } + ``` + +### 2. Create / Update Credit Pack +- **URL**: `/api/v1/admin/credits/packs` (`POST`) +- **URL**: `/api/v1/admin/credits/packs/{id}` (`PUT`) +- **Request Body (`CreateCreditPackRequest` / `UpdateCreditPackRequest`)**: + ```json + { + "name": "GIANT_PACK", + "displayName": "Giant Pack", + "priceInCents": 10000, + "creditsIncluded": 500 + } + ``` + +### 3. Adjust User Subscription Override +- **URL**: `/api/v1/admin/users/{userId}/subscription` +- **Method**: `PUT` +- **Role**: `SUPER_ADMIN` +- **Request Body**: + ```json + { + "plan": "BUSINESS_YEARLY", + "billingIntervalUnit": "YEAR", + "billingIntervalValue": 1, + "autoRenew": true, + "source": "ADMIN_OVERRIDE" + } + ``` + +### 4. Create Promo Code +- **URL**: `/api/v1/admin/promo_codes` +- **Method**: `POST` +- **Request Body (`CreatePromoCodeRequest`)**: + ```json + { + "customCode": "SUPERDEAL", + "description": "50% off for developer cohorts", + "discountPercentage": 50.00, + "recipientCategory": "ALL_USERS", + "validDurationValue": 7, + "validDurationUnit": "Days" + } + ``` + +### 5. Initiate Bulk Promo Code Generation +- **URL**: `/api/v1/admin/promo_codes/bulk-generate` +- **Method**: `POST` +- **Request Body (`BulkPromoCodeGenerationRequest`)**: + ```json + { + "templateId": "template_uuid", + "quantity": 100, + "discountPercentage": 10.00, + "codePrefix": "DEVCOHORT", + "recipientCategory": "SPECIFIC_USERS", + "autoDistribute": false + } + ``` +- **Response (`202 Accepted`)**: Returns bulk job tracking ID. Check progress status at `GET /api/v1/admin/promo_codes/bulk-jobs/{jobId}`. diff --git a/src/main/java/com/xtraction/api/core/api_docs/api_docs.md b/src/main/java/com/xtraction/api/core/api_docs/api_docs.md new file mode 100644 index 0000000..9d8d95e --- /dev/null +++ b/src/main/java/com/xtraction/api/core/api_docs/api_docs.md @@ -0,0 +1,180 @@ +# ๐Ÿ—๏ธ Core Package Architecture & Developer Reference + +This document details the cross-cutting concerns, infrastructure components, web envelopes, and foundational configurations of the Xtraction API found under the `com.xtraction.api.core` package. + +--- + +## ๐ŸŒ 1. Response Architecture (`core.web.response`) + +All REST endpoints in the system use the unified response and paging patterns to ensure consistency for client applications. + +### 1. Unified Response Envelope (`ApiResponse`) +Every JSON response returned is mapped to the `ApiResponse` envelope. It includes status details, custom error codes, path tracking, and trace logs. + +#### Fields: +- `success` (Boolean): Indicates if the operation completed successfully (2xx status codes). +- `statusCode` (Integer): The standard HTTP status code. +- `message` (String): Descriptive status text. +- `data` (T): The generic payload object or array (null if empty). +- `errors` (List): Populated on validation constraints failures (400 Bad Request). +- `errorCode` (String): A custom error code to identify specific domain errors. +- `timestamp` (Instant): The timestamp of response generation. +- `path` (String): Request URI mapping. +- `traceId` (String): Server-side correlation ID for trace log queries. + +#### Validation Error Schema (`ValidationError`): +```json +{ + "field": "password", + "rejectedValue": "123", + "message": "Password must be at least 8 characters long and contain at least one uppercase letter." +} +``` + +### 2. Pagination Envelope (`PagedResponse`) +For lists, arrays, and search result queries, the `data` field of `ApiResponse` is populated with a `PagedResponse` object mapping Spring Data `Page` collections: + +#### Fields: +- `content` (List): The payload list for the current page. +- `page` (Integer): Zero-indexed current page number. +- `size` (Integer): Items count per page. +- `totalElements` (Long): Total elements in the database matching query. +- `totalPages` (Integer): Total pages computed. +- `first` (Boolean): If the current page is the first page. +- `last` (Boolean): If the current page is the last page. + +--- + +## ๐Ÿ”’ 2. Security & JWT Engine (`core.security` & `core.config`) + +The security boundary uses **Spring Security 6.x** and JWT-based session state verification. + +### 1. Token Properties +- **Access Tokens (JWT)**: + - Header: `Authorization: Bearer ` + - Lifetime: 1 hour (`3600000` milliseconds). + - Signature Algorithm: HMAC-SHA256. + - Claims included: Subject (`userId`), Issue date (`iat`), Expiry date (`exp`), Granted authorities (`roles`). +- **Refresh Tokens (HttpOnly Cookie)**: + - Cookie Name: `refreshToken` + - Lifetime: 30 days (`2592000000` milliseconds). + - Scope: Rolling token rotation (invalidates current refresh token on request and issues a new one). + - Flags: `HttpOnly`, `Secure` (production only), `SameSite=Strict`. + +### 2. Brute Force counter / Account Lockouts +Failed login attempts are audited dynamically in Redis. +- **Fail threshold**: 4 consecutive failures. +- **Lock duration**: 5 days (calculated from Redis epoch scores). +- **Audit tracking keys**: + - `login_attempts:user:` (Hash) + - `login_attempts:blocked_users` (Sorted Set) + - `login_attempts:failed_logins_history` (Sorted Set) + +--- + +## โš ๏ธ 3. Global Exception Mapping (`core.exceptions`) + +Exceptions thrown in controllers or service implementations are caught globally using a `@RestControllerAdvice` mapping classes (`GlobalExceptionHandler`). + +### 1. Mapped Exceptions & Status Codes + +| Exception Class | HTTP Status | Custom `errorCode` | Description | +|:------------------------|:------------------------|:------------------------|:---------------------------------------------------------------------------------| +| `BadRequestException` | `400 Bad Request` | `BAD_REQUEST` | Malformed body payloads, schema validation errors, or invalid arguments. | +| `UnauthorizedException` | `401 Unauthorized` | `UNAUTHORIZED` | Missing or expired JWT header, missing credentials, invalid signature. | +| `ForbiddenException` | `403 Forbidden` | `ACCESS_DENIED` | Account locked out, account unverified, or role permissions mismatch. | +| `NotFoundException` | `404 Not Found` | `RESOURCE_NOT_FOUND` | Document, collection, profile, or plan not found in database. | +| `ConflictException` | `409 Conflict` | `CONFLICT` | Email already registered, promo code code duplication, active trial duplication. | +| `RateLimitException` | `429 Too Many Requests` | `RATE_LIMIT_EXCEEDED` | Request frequency exceeds subscription plan bucket constraints. | +| `InternalServerError` | `500 Server Error` | `INTERNAL_SERVER_ERROR` | Cloud bucket exceptions, database connection timeouts, OCR runtime failures. | + +--- + +## โฑ๏ธ 4. Redis-Backed Rate Limiting (`core.ratelimit`) + +The API enforces dynamic rate limits per user/subscription tier using the Token-Bucket algorithm (backed by Bucket4j and Redis). + +### 1. Response Headers +For rate-limited endpoints (such as `/api/v1/documents/upload`), the server appends these headers to client responses: +- `X-Rate-Limit-Limit`: Maximum requests permitted per window. +- `X-Rate-Limit-Remaining`: Remaining request quota. +- `X-Rate-Limit-Reset`: Time (in seconds) until quota resets. + +### 2. Limit Exceeded Response +If a client goes over limits, the API interrupts processing and returns `429 Too Many Requests`: +```json +{ + "success": false, + "statusCode": 429, + "message": "Rate limit exceeded. Please try again later.", + "data": null, + "errorCode": "RATE_LIMIT_EXCEEDED" +} +``` + +--- + +## ๐Ÿ” 5. Symmetric Data Encryption at Rest (`core.encryption`) + +To secure sensitive documents, Xtraction supports symmetric payload encryption at rest before uploading files to cloud storage (AWS S3 or Cloudinary). + +### 1. Encryption Scheme +- **Algorithm**: AES-256-GCM (Advanced Encryption Standard in Galois/Counter Mode). +- **Key Derivation**: Dynamic PBKDF2 with SHA-256 using a database-persisted salt. +- **Components**: + - A unique Initialization Vector (IV) is generated dynamically for every document upload. + - The resulting ciphertext consists of: `[12-byte IV] + [encrypted bytes] + [16-byte authentication tag]`. + +### 2. Implementation Flow +1. **Upload**: If `enableEncryption=true` is provided on `/upload`, the stream bytes are encrypted in memory prior to sending to cloud storage buckets. +2. **Download**: On docx exports or file requests, the encrypted stream is fetched, authenticated via the GCM tag, decrypted using the user's private key context, and streamed back to the client. + +--- + +## ๐Ÿ“ฃ 6. Kafka Event Broker Architecture (`core.kafka` & `integration.broker`) + +The application implements an event-driven architecture to coordinate background pipelines and email delivery asynchronously. + +### Topic Catalog & Events: + +| Topic | Event Payload | Producer | Consumer | Description | +|:-----------------|:--------------------------|:--------------------|:-------------------------------------------|:-------------------------------------------------------------------------------------| +| `user-auth` | `USER_REGISTERED` | `identity.auth` | `integration.messaging` | Sends the welcome email and verification OTP token. | +| `user-auth` | `USER_PASSWORD_RESET` | `identity.user` | `integration.messaging` | Dispatches password reset code emails. | +| `user-lifecycle` | `USER_DELETION_SCHEDULED` | `identity.user` | `integration.messaging` | Sends account deactivation warning emails. | +| `user-lifecycle` | `USER_DELETED` | `identity.user` | `integration.storage`, `extraction.search` | Deletes user database records, indexes in Elasticsearch, and clears S3 file buckets. | +| `promo-code` | `BULK_PROMO_GEN` | `billing.promocode` | `billing.promocode.consumer` | Triggers background creation and distribution of promo codes in bulk. | + +--- + +## ๐Ÿ“Š 7. Dashboard Metrics Console (`core.metrics`) + +Exposes a central system KPI analytics dashboard for platform moderators and administrators. + +- **URL**: `/api/v1/admin/dashboard/stats` +- **Method**: `GET` +- **Roles Required**: `ADMIN`, `SUPER_ADMIN`, `MODERATOR` +- **Response (`200 OK` - `DashboardKpiStatsDto`)**: + ```json + { + "statusCode": 200, + "status": "success", + "message": "Dashboard statistics retrieved successfully", + "data": { + "userKpis": { + "totalUsersCount": 1450, + "activeUsersCount": 1200, + "verifiedUsersCount": 1150 + }, + "subscriptionKpis": { + "activeSubscriptions": 450, + "mrr": 5200.50, + "averageLtv": 45.20 + }, + "storageKpis": { + "totalStorageUsedBytes": 107374182400, // 100 GB + "averageStoragePerUserBytes": 74051160 + } + } + } + ``` diff --git a/src/main/java/com/xtraction/api/core/config/SecurityConfig.java b/src/main/java/com/xtraction/api/core/config/SecurityConfig.java index ec35094..b1b107f 100644 --- a/src/main/java/com/xtraction/api/core/config/SecurityConfig.java +++ b/src/main/java/com/xtraction/api/core/config/SecurityConfig.java @@ -1,13 +1,12 @@ package com.xtraction.api.core.config; -import com.xtraction.api.core.security.*; import com.xtraction.api.core.security.CustomAccessDeniedHandler; import com.xtraction.api.core.security.JwtAuthenticationEntryPoint; import com.xtraction.api.core.security.JwtAuthenticationFilter; import com.xtraction.api.core.utils.CustomPermissionEvaluator; -import com.xtraction.api.identity.auth.oauth2.handler.OAuth2AuthenticationFailureHandler; -import com.xtraction.api.identity.auth.oauth2.handler.OAuth2AuthenticationSuccessHandler; -import com.xtraction.api.identity.auth.oauth2.service.CustomOAuth2UserService; +import com.xtraction.api.identity.oauth2.handler.OAuth2AuthenticationFailureHandler; +import com.xtraction.api.identity.oauth2.handler.OAuth2AuthenticationSuccessHandler; +import com.xtraction.api.identity.oauth2.service.CustomOAuth2UserService; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.Getter; import lombok.RequiredArgsConstructor; diff --git a/src/main/java/com/xtraction/api/extraction/ai/api_docs/api_docs.md b/src/main/java/com/xtraction/api/extraction/ai/api_docs/api_docs.md new file mode 100644 index 0000000..1115a36 --- /dev/null +++ b/src/main/java/com/xtraction/api/extraction/ai/api_docs/api_docs.md @@ -0,0 +1,147 @@ +# ๐Ÿค– AI-Powered Document Insights API Documentation + +This module manages AI-driven analysis of documents, utilizing large language models (LLMs) to perform summarization and classification on OCR-extracted text. + +--- + +## ๐Ÿ—๏ธ Architectural Flow + +The AI pipeline interfaces with AI models (OpenAI or Mistral AI) after a document has successfully completed the OCR extraction phase. + +```mermaid +sequenceDiagram + participant Client + participant Controller as AiController + participant Service as AiService + participant LLM as LLM Provider (OpenAI/Mistral) + participant Quota as Quota & Billing + + Client->>Controller: POST /api/v1/ai/summarize (Payload) + Controller->>Service: invoke summarization + Service->>Quota: check available quota/credits + alt Quota Insufficient + Quota-->>Controller: throw ForbiddenException + Controller-->>Client: 403 Forbidden (Quota Exceeded) + else Quota Available + Service->>LLM: send OCR text + system prompt + LLM-->>Service: return summary payload + Service->>Quota: charge user subscription/credits + Service-->>Controller: return SummarizeResponse + Controller-->>Client: 200 OK (ApiResponse) + end +``` + +--- + +## ๐Ÿ› ๏ธ Provider Configurations + +The platform integrates with: +1. **OpenAI**: Utilizes `gpt-4o-mini` or configured models for high-reasoning document analysis. +2. **Mistral AI**: Utilizes `mistral-small` or configured models for cost-efficient abstractive operations. + +Clients can override the default system-selected provider using the `modelPreference` parameter in request payloads. + +--- + +## ๐Ÿš€ Endpoint Reference + +Requires `Authorization: Bearer ` in request headers. + +### 1. Summarize Document +Generates a structured, concise summary of the document's OCR-extracted text. + +- **URL**: `/api/v1/ai/summarize` +- **Method**: `POST` +- **Headers**: + - `Content-Type: application/json` +- **Request Body (`SummarizeRequest`)**: + ```json + { + "documentId": "doc_9b1deb4d-3b7d-4bad-9bdd-2b0d7b3d4f82", + "summaryType": "SHORT", // ENUM: "SHORT" or "DETAILED" + "modelPreference": "openai" // Optional ENUM: "openai" or "mistral" + } + ``` + +#### Request Parameter Specifications: +| Parameter | Type | Required | Default | Constraints / Options | Description | +|:------------------|:-------|:---------|:---------------|:------------------------|:-------------------------------------------------------------------------------------------| +| `documentId` | String | Yes | - | Must be a valid UUID. | Target document. | +| `summaryType` | String | No | `"SHORT"` | `"SHORT"`, `"DETAILED"` | `"SHORT"` returns a 3-bullet summary; `"DETAILED"` returns a structured sectioned summary. | +| `modelPreference` | String | No | Server default | `"openai"`, `"mistral"` | Choose specific provider model engine. | + +#### Response Payload (`ApiResponse`) +- **Status Code**: `200 OK` +- **Response Example**: + ```json + { + "success": true, + "statusCode": 200, + "message": "Document summarized successfully.", + "data": { + "documentId": "doc_9b1deb4d-3b7d-4bad-9bdd-2b0d7b3d4f82", + "summary": "- Invoice #INV-1024 issued by ACME Corp.\n- Total balance due: $4,500.00.\n- Due date set for August 15, 2026.", + "summaryType": "SHORT", + "modelUsed": "gpt-4o-mini", + "creditsCharged": 1, + "billingSource": "subscription" + }, + "timestamp": "2026-07-07T20:15:00.123Z" + } + ``` + +#### Common Error Conditions: +- `400 Bad Request` (`errorCode: INVALID_INPUT`): Missing required parameters or invalid summary type options. +- `403 Forbidden` (`errorCode: QUOTA_EXCEEDED`): Insufficient monthly subscription AI operations quota or zero purchased credits balance. +- `404 Not Found` (`errorCode: RESOURCE_NOT_FOUND`): The requested document ID does not exist or does not belong to the authenticated user. + +--- + +### 2. Classify Document +Analyzes the OCR text content of the target document and classifies it into a document category with tagging. + +- **URL**: `/api/v1/ai/classify/{documentId}` +- **Method**: `POST` +- **Path Variables**: + - `documentId` (String, Required): UUID of the document. + +#### Response Payload (`ApiResponse`) +- **Status Code**: `200 OK` +- **Response Example**: + ```json + { + "success": true, + "statusCode": 200, + "message": "Document classified successfully.", + "data": { + "documentId": "doc_9b1deb4d-3b7d-4bad-9bdd-2b0d7b3d4f82", + "documentType": "INVOICE", // Mapped categories: INVOICE, RECEIPT, CONTRACT, MANUAL, OTHER + "tags": [ + "ACME Corp", + "Financial", + "USD", + "2026" + ], + "confidence": 0.985, + "modelUsed": "gpt-4o-mini", + "creditsCharged": 1, + "billingSource": "credits" + }, + "timestamp": "2026-07-07T20:16:00.456Z" + } + ``` + +#### Common Error Conditions: +- `403 Forbidden` (`errorCode: QUOTA_EXCEEDED`): No remaining AI operation quota or credits. +- `404 Not Found` (`errorCode: RESOURCE_NOT_FOUND`): Target document not found. + +--- + +## โšก Quota & Billing Deductions + +1. **Subscription Quotas**: + - Each classification or summarization counts as **1 AI operation** check. + - Mapped from the user's active plan limits (e.g., Enterprise plans include unlimited operations, Starter plans include 150 operations / month). +2. **Credits Balance**: + - If a user has depleted their subscription plan monthly operations limit, the system falls back to charge their purchased credit balance: **1 Credit / AI operation**. + - Verified dynamically in the quota engine before routing prompts. diff --git a/src/main/java/com/xtraction/api/extraction/documents/api_docs/api_docs.md b/src/main/java/com/xtraction/api/extraction/documents/api_docs/api_docs.md new file mode 100644 index 0000000..dcc2062 --- /dev/null +++ b/src/main/java/com/xtraction/api/extraction/documents/api_docs/api_docs.md @@ -0,0 +1,223 @@ +# ๐Ÿ“‚ Document & Collection Management API Documentation + +This module manages document uploads, collection grouping, file properties modifications (rename, move), encryption flags, and deletions. + +--- + +## ๐Ÿ—๏ธ Architectural Flow + +The document ingestion pipeline uses an asynchronous model where files are uploaded, stored in the cloud (AWS S3 or Cloudinary), and indexed in PostgreSQL before launching background OCR extraction tasks. + +```mermaid +sequenceDiagram + participant Client + participant Controller as DocumentController + participant Service as DocumentService + participant Storage as StorageAdapter (S3/Cloudinary) + participant DB as PostgreSQL + participant Kafka as Event Broker (Kafka) + + Client->>Controller: POST /api/v1/documents/upload (Files) + Controller->>Service: initiate upload & extraction + Service->>Storage: stream files to bucket + alt Upload Success + Storage-->>Service: return file URL & size + Service->>DB: create Collection & File records + Service->>Kafka: publish USER_UPLOADED event + Service-->>Controller: return StreamingUploadResponse + Controller-->>Client: 202 Accepted (Tracking ID) + else Upload Failure + Service-->>Controller: throw cloud exception + Controller-->>Client: 500 Internal Error + end +``` + +--- + +## ๐Ÿ› ๏ธ Security & Envelope Wrapper + +- **Headers Required**: `Authorization: Bearer ` on all endpoints. +- **Envelope Wrapper**: Responses are returned in the `DocumentCollectionResponse` envelope: + ```json + { + "statusCode": 200, + "status": "success", + "message": "Action completed successfully", + "data": { ... } + } + ``` + +--- + +## ๐Ÿš€ Endpoint Reference + +### 1. Upload Documents (Async Pipeline) +Streams one or more documents to cloud storage, groups them into a collection, and queues them for OCR processing. + +- **URL**: `/api/v1/documents/upload` +- **Method**: `POST` +- **Content-Type**: `multipart/form-data` +- **Rate Limit**: Max 10 requests / minute. +- **Form Data Parameters**: + - `files` (MultipartFile[], Required): Array of file binaries. + - `collectionName` (String, Optional): Groups files into a named collection. Creates a new collection if name doesn't exist. + - `enableEncryption` (Boolean, Optional, Default: `false`): Symmetric AES-256 encryption. + +#### Response Payload (`202 Accepted` - `StreamingUploadResponse`) +- **Response Example**: + ```json + { + "statusCode": 202, + "status": "success", + "message": "Upload initiated. Subscribe to WebSocket progress topic.", + "collectionId": "col_b8d348a0-2f3b-48cf-99bf-8cd64f201083", + "totalFiles": 2, + "wsSubscriptionTopic": "/user/queue/extraction-progress" + } + ``` + +#### Errors: +- `400 Bad Request` (`errorCode: INVALID_INPUT`): Empty files list. +- `429 Too Many Requests` (`errorCode: RATE_LIMIT_EXCEEDED`): Exceeded upload speed threshold. + +--- + +### 2. Get All User Collections +Retrieves a summary list of all document collections created by the authenticated user. + +- **URL**: `/api/v1/documents/my-collections` +- **Method**: `GET` + +#### Response Payload (`DocumentCollectionResponse>`) +- **Response Example**: + ```json + { + "statusCode": 200, + "status": "success", + "message": "Collections retrieved successfully", + "data": [ + { + "id": "col_b8d348a0-2f3b-48cf-99bf-8cd64f201083", + "name": "July Invoices", + "collectionStatus": "COMPLETED", // Enums: UPLOADED, COMPLETED, PROCESSING, FAILED_OCR, DELETED, etc. + "fileCount": 2, + "hasEncryptedFiles": false, + "uploadTimestamp": "2026-07-07T20:15:00Z", + "createdAt": "2026-07-07T20:15:00Z", + "updatedAt": "2026-07-07T20:18:00Z" + } + ] + } + ``` + +--- + +### 3. Get Collection Details +Retrieves details of a specific collection along with metadata of all nested documents. + +- **URL**: `/api/v1/documents/collection/{collectionId}` +- **Method**: `GET` +- **Path Variables**: + - `collectionId` (String, Required): UUID of the collection. + +#### Response Payload (`DocumentCollectionResponse`) +- **Response Example**: + ```json + { + "statusCode": 200, + "status": "success", + "message": "Collection retrieved successfully", + "data": { + "id": "col_b8d348a0-2f3b-48cf-99bf-8cd64f201083", + "name": "July Invoices", + "userId": "usr_9b1deb4d...", + "collectionStatus": "COMPLETED", + "uploadTimestamp": "2026-07-07T20:15:00Z", + "createdAt": "2026-07-07T20:15:00Z", + "updatedAt": "2026-07-07T20:18:00Z", + "files": [ + { + "documentId": "doc_e3d3b764-f6b0-41ab-8be0-b26a6358dbb2", + "originalFileName": "invoice_99.pdf", + "displayName": "invoice_99.pdf", + "fileSize": 1048576, // Bytes + "fileUrl": "https://s3.amazonaws.com/...", + "status": "completed", + "isEncrypted": false + } + ] + } + } + ``` + +#### Errors: +- `404 Not Found`: Collection not found or does not belong to the user. + +--- + +### 4. Get Individual File Entry details +- **URL**: `/api/v1/documents/collection/{collectionId}/document/{documentId}` +- **Method**: `GET` +- **Response Payload**: `DocumentCollectionResponse` + +--- + +### 5. Rename Collection +- **URL**: `/api/v1/documents/collection/{collectionId}` +- **Method**: `PUT` +- **Request Body (`UpdateCollectionRequest`)**: + ```json + { + "name": "Q3 Financial Reports" + } + ``` + +--- + +### 6. Rename Document (Display Name) +- **URL**: `/api/v1/documents/collection/{collectionId}/document/{documentId}` +- **Method**: `PUT` +- **Request Body (`UpdateDocumentRequest`)**: + ```json + { + "displayName": "monthly_report_clean.pdf" + } + ``` + +--- + +### 7. Move Document to Another Collection +- **URL**: `/api/v1/documents/move` +- **Method**: `POST` +- **Request Body (`MoveDocumentRequest`)**: + ```json + { + "sourceCollectionId": "col_b8d3...", + "targetCollectionId": "col_a11b...", + "documentId": "doc_e3d3..." + } + ``` +- **Response Payload**: `DocumentCollectionResponse` containing file entry detail. + +--- + +### 8. Delete Collection +Deletes the collection record and schedules deletions for all nested documents. +- **URL**: `/api/v1/documents/collection/{collectionId}` +- **Method**: `DELETE` +- **Response**: `204 No Content` + +--- + +### 9. Delete Document from Collection +- **URL**: `/api/v1/documents/collection/{collectionId}/document/{documentId}` +- **Method**: `DELETE` +- **Response**: `204 No Content` + +--- + +### 10. Clear All User Collections +Factory resets the user workspace by deleting all collection and document nodes. +- **URL**: `/api/v1/documents/clear-all` +- **Method**: `DELETE` +- **Response**: `204 No Content` diff --git a/src/main/java/com/xtraction/api/extraction/export/api_docs/api_docs.md b/src/main/java/com/xtraction/api/extraction/export/api_docs/api_docs.md new file mode 100644 index 0000000..edd565c --- /dev/null +++ b/src/main/java/com/xtraction/api/extraction/export/api_docs/api_docs.md @@ -0,0 +1,68 @@ +# ๐Ÿ’พ Word Document (.docx) Export API Documentation + +This module manages exporting the OCR-extracted text of a document as a formatted Microsoft Word (`.docx`) file download. + +--- + +## ๐Ÿ—๏ธ Architectural Flow + +The export engine reads the OCR text (either original or edited) from the database, builds a Word document structure dynamically using Apache POI, and streams the binary content back in the HTTP response. + +```mermaid +sequenceDiagram + participant Client + participant Controller as DownloadOcrCResultController + participant Service as DownloadOcrResultService + participant DB as PostgreSQL + participant POI as Document Generator (Apache POI) + + Client->>Controller: GET /download/docx (collectionId, documentId, type) + Controller->>Service: invoke docx generation + Service->>DB: fetch OCR text records (original/edited) + DB-->>Service: return OCR text + Service->>POI: create Word document layout & append text + POI-->>Service: return InputStreamResource + Service-->>Controller: return DownloadableFile wrapper + Controller-->>Client: 200 OK (Binary Stream with attachment headers) +``` + +--- + +## ๐Ÿš€ Endpoint Reference + +Requires `Authorization: Bearer ` in request headers. + +### 1. Download Extracted Text as DOCX +Generates and streams a formatted Word file containing the OCR text of the specified document. + +- **URL**: `/api/v1/collections/{collectionId}/documents/{documentId}/download/docx` +- **Method**: `GET` +- **Authentication Required**: Yes +- **Path Variables**: + - `collectionId` (String, Required): UUID of the collection. + - `documentId` (String, Required): UUID of the document whose OCR text is to be downloaded. +- **Query Parameters**: + - `type` (String, Optional, Default: `"original"`): The text source context to download: + - `"original"`: Exports the raw OCR text initially extracted from the document. + - `"edited"`: Exports the user-corrected/edited OCR text version. + +#### Response Headers: +The server appends headers to prompt the browser to display a download file dialog rather than rendering inline: + +| Header | Value / Format | Description | +|:---|:---|:---| +| `Content-Type` | `application/vnd.openxmlformats-officedocument.wordprocessingml.document` | Mime type for DOCX documents. | +| `Content-Disposition` | `attachment; filename="_ocr.docx"` | Forces file download dialog. | +| `Cache-Control` | `no-cache, no-store, must-revalidate` | Prevents browser caching. | +| `Pragma` | `no-cache` | Legacy cache control. | +| `Expires` | `0` | Immediately expires cache window. | + +#### Response Payload: +Returns the raw binary byte stream of the generated document. + +#### Common Error Conditions: +- `400 Bad Request` (`errorCode: INVALID_INPUT`): Invalid query parameters. +- `404 Not Found` (`errorCode: RESOURCE_NOT_FOUND`): + - Collection or document not found. + - Requested document OCR text is empty. + - Requesting `"edited"` type when no edited content is present. diff --git a/src/main/java/com/xtraction/api/extraction/ocr/api_docs/api_docs.md b/src/main/java/com/xtraction/api/extraction/ocr/api_docs/api_docs.md new file mode 100644 index 0000000..de3a1a0 --- /dev/null +++ b/src/main/java/com/xtraction/api/extraction/ocr/api_docs/api_docs.md @@ -0,0 +1,181 @@ +# ๐Ÿ” OCR (Optical Character Recognition) API Documentation + +This module manages document text extraction via Optical Character Recognition (OCR), result retrievals, and manual content corrections (editing). + +--- + +## ๐Ÿ—๏ธ Architectural Flow + +The OCR processor uses a background thread pool to parse PDF/images using Tesseract OCR, updating clients in real time via WebSockets. + +```mermaid +sequenceDiagram + participant Client + participant Controller as OcrDocumentController + participant Service as OcrDocumentService + participant Queue as Task Queue / Thread Pool + participant WS as WebSocket Progress Topic + + Client->>Controller: POST /extract (startPage, endPage, pages) + Controller->>Service: initiate OCR task + Service->>Queue: schedule background worker + Service-->>Controller: confirm task initialization + Controller-->>Client: 200 OK (Task Started) + + loop OCR In Progress + Queue->>WS: dispatch EXTRACTION_PROGRESS event (progress %) + end + + alt OCR Success + Queue->>WS: dispatch EXTRACTION_COMPLETED event + else OCR Failure + Queue->>WS: dispatch EXTRACTION_FAILED event + end +``` + +--- + +## ๐Ÿš€ Endpoint Reference + +Requires `Authorization: Bearer ` in request headers. + +### 1. Extract Text from Document +Triggers background OCR processing for a specific document with optional page range filters. + +- **URL**: `/api/v1/collections/{collectionId}/document/{documentId}/extract` +- **Method**: `POST` +- **Query Parameters**: + - `startPage` (Integer, Optional): Start page index (1-indexed) for PDF range cropping. + - `endPage` (Integer, Optional): End page index (1-indexed) for PDF range cropping. + - `pages` (List, Optional): Discrete page numbers to process (e.g. `pages=1,3,7`). + +#### Response Payload (`ApiResponse`) +- **Status Code**: `202 Accepted` / `200 OK` +- **Response Example**: + ```json + { + "success": true, + "statusCode": 200, + "message": "OCR text extraction initiated. Track progress via WebSockets.", + "data": null, + "timestamp": "2026-07-07T20:25:00.000Z" + } + ``` + +--- + +### 2. Upload & Extract All (Batch Shortcut) +Uploads multiple files and automatically initiates full text extractions on all files in one operation. + +- **URL**: `/api/v1/collections/upload/extract-all` +- **Method**: `POST` +- **Content-Type**: `multipart/form-data` +- **Form Data**: + - `files` (MultipartFile[], Required): Array of file binaries. + - `startPage` (Integer, Optional) + - `endPage` (Integer, Optional) + - `pages` (List, Optional) + +#### Response Payload (`ApiResponse`) +- **Status Code**: `202 Accepted` + +--- + +### 3. Get Collection OCR Results +Retrieves extracted text results and statuses for all documents within a collection. + +- **URL**: `/api/v1/collections/{collectionId}/document/results` +- **Method**: `GET` +- **Path Variables**: + - `collectionId` (String, Required): UUID of the collection. + +#### Response Payload (`ApiResponse`) +- **Response Example**: + ```json + { + "success": true, + "statusCode": 200, + "message": "OCR results retrieved successfully", + "data": { + "collectionId": "col_b8d348a0-2f3b-48cf-99bf-8cd64f201083", + "overallStatus": "COMPLETED", // Enums: UPLOADED, COMPLETED, PROCESSING, FAILED_OCR, etc. + "files": [ + { + "documentId": "doc_e3d3b764-f6b0-41ab-8be0-b26a6358dbb2", + "originalFileName": "invoice_99.pdf", + "status": "completed", + "errorMessage": null, + "createdAt": "2026-07-07T20:15:00Z", + "extractedText": "INVOICE #99 ... TOTAL: $100.00", + "editedContent": "INVOICE #99 ... TOTAL: $100.00 (Adjusted)", + "contentFormat": "MARKDOWN", + "editedBy": "usr_9b1deb4d...", + "editedAt": "2026-07-07T20:20:00Z", + "aiSummary": "Invoice 99 details...", + "documentType": "INVOICE", + "aiTags": ["invoice", "financial"] + } + ] + }, + "timestamp": "2026-07-07T20:26:00.000Z" + } + ``` + +--- + +### 4. Get Document OCR Data & History +Retrieves full text data, current editing blocks, and metadata for a specific document. + +- **URL**: `/api/v1/collections/{collectionId}/document/{documentId}/ocr-data` +- **Method**: `GET` +- **Path Variables**: + - `collectionId` (String, Required) + - `documentId` (String, Required) + +#### Response Payload (`ApiResponse`) +- **Response Example**: + ```json + { + "success": true, + "statusCode": 200, + "message": "Document OCR data retrieved.", + "data": { + "id": "ocr_uuid_123", + "documentId": "doc_e3d3b764-f6b0-41ab-8be0-b26a6358dbb2", + "status": "COMPLETED", // Enums: PENDING, PROCESSING, COMPLETED, FAILED + "extractedText": "INVOICE #99 ... TOTAL: $100.00", + "editedContent": null, + "contentFormat": "HTML", // Enums: HTML, MARKDOWN + "editedBy": null, + "editedAt": null, + "errorMessage": null, + "aiSummary": null, + "documentType": null, + "aiTags": null, + "createdAt": "2026-07-07T20:15:00Z", + "updatedAt": "2026-07-07T20:15:00Z" + }, + "timestamp": "2026-07-07T20:26:30.000Z" + } + ``` + +--- + +### 5. Edit OCR Extracted Content +Enables manual client-side corrections to be persisted for the document. + +- **URL**: `/api/v1/collections/{collectionId}/document/{documentId}/content` +- **Method**: `PUT` +- **Path Variables**: + - `collectionId` (String, Required) + - `documentId` (String, Required) +- **Request Body (`UpdateOcrContentRequest`)**: + ```json + { + "editedContent": "This is corrected invoice text to overwrite...", + "contentFormat": "MARKDOWN" // ENUM: "MARKDOWN" or "HTML" + } + ``` + +#### Response Payload (`ApiResponse`) +- **Response Example**: Returns updated `OcrData` payload containing populated `editedContent`, `editedBy` (authenticated user UUID), and `editedAt` fields. diff --git a/src/main/java/com/xtraction/api/extraction/search/api_docs/api_docs.md b/src/main/java/com/xtraction/api/extraction/search/api_docs/api_docs.md new file mode 100644 index 0000000..146c4b2 --- /dev/null +++ b/src/main/java/com/xtraction/api/extraction/search/api_docs/api_docs.md @@ -0,0 +1,181 @@ +# ๐Ÿ” Elasticsearch Document Search API Documentation + +This module manages full-text searches over user documents and OCR-extracted text, alongside administrative searches over users/payments and index synchronizations. + +--- + +## ๐Ÿ—๏ธ Architectural Flow + +The search engine uses a Postgres-to-Elasticsearch synchronization pipeline. Documents, users, and transactions created in Postgres are indexed in Elasticsearch via Kafka events or manual sync calls. + +```mermaid +sequenceDiagram + participant Client + participant Controller as DocumentSearchController + participant Service as DocumentSearchService + participant ES as Elasticsearch Server + + Client->>Controller: POST /search/documents (query, filters) + Controller->>Service: invoke search request + Service->>ES: execute Elasticsearch match/highlight query + ES-->>Service: return hits, highlights, & facets + Service-->>Controller: map results to SearchResponse + Controller-->>Client: 200 OK (ApiResponse wrapper) +``` + +--- + +## ๐Ÿ› ๏ธ Global Constraints + +- **Elasticsearch Activation**: Enforced conditionally based on configuration properties: `@ConditionalOnProperty(name = "spring.elasticsearch.uris")`. +- **Headers Required**: `Authorization: Bearer ` on all endpoints. + +--- + +## ๐Ÿš€ Endpoint Reference (User Scope) + +### 1. Advanced Full-Text Document Search +Executes an Elasticsearch query across document display names, original file names, and OCR-extracted text content. + +- **URL**: `/api/v1/search/documents` +- **Method**: `POST` +- **Request Body (`SearchRequest`)**: + ```json + { + "query": "invoice ACME", + "page": 0, + "size": 10, + "sortBy": "createdAt", + "sortDirection": "desc", + "includeHighlights": true, + "dateFrom": "2026-07-01T00:00:00Z", + "dateTo": "2026-07-08T00:00:00Z", + "filters": { + "collectionId": "col_b8d348a0..." + } + } + ``` + +#### Request Parameters: +| Field | Type | Required | Default | Description | +|:---|:---|:---|:---|:---| +| `query` | String | No | `null` | The keyword search string. Matches doc fields and OCR contents. | +| `page` | Integer | No | `0` | Zero-indexed page number. | +| `size` | Integer | No | `10` | Page size (limits max 100). | +| `sortBy` | String | No | `"createdAt"` | Target field sorting (e.g. `createdAt`, `fileSize`, `displayName`). | +| `sortDirection` | String | No | `"desc"` | Sorting direction (`"asc"` or `"desc"`). | +| `includeHighlights` | Boolean | No | `true` | Includes high-match HTML highlight tags (``) in response hits. | +| `dateFrom` | String | No | `null` | ISO 8601 offset start date range. | +| `dateTo` | String | No | `null` | ISO 8601 offset end date range. | +| `filters` | Map | No | `{}` | Key-value pairs for strict matching (e.g. `"isEncrypted": false`). | + +#### Response Payload (`SearchResponse`) +- **Status Code**: `200 OK` +- **Response Example**: + ```json + { + "results": [ + { + "documentId": "doc_e3d3b764-f6b0-41ab-8be0-b26a6358dbb2", + "collectionId": "col_b8d348a0-2f3b-48cf-99bf-8cd64f201083", + "userId": "usr_9b1deb4d...", + "originalFileName": "invoice_acme.pdf", + "displayName": "invoice_acme.pdf", + "fileSize": 1048576, + "isEncrypted": false, + "createdAt": "2026-07-07T20:15:00Z" + } + ], + "totalHits": 1, + "page": 0, + "size": 10, + "totalPages": 1, + "took": 42, // Milliseconds + "highlights": { + "doc_e3d3b764-f6b0-41ab-8be0-b26a6358dbb2": [ + "Extracted OCR: ACME Corp invoice details..." + ] + }, + "facets": {} + } + ``` + +--- + +### 2. Search Within Document Content +Search OCR-extracted texts specifically. + +- **URL**: `/api/v1/search/documents/content` +- **Method**: `GET` +- **Query Parameters**: + - `query` (String, Required): Text keywords. + - `page` (Integer, Default: 0) + - `size` (Integer, Default: 10) + +--- + +### 3. Quick Document Search +- **URL**: `/api/v1/search/documents` +- **Method**: `GET` +- **Query Parameters**: + - `query` (String, Optional) + - `page` (Integer, Default: 0) + - `size` (Integer, Default: 10) + - `sortBy` (String, Default: `"createdAt"`) + - `sortDirection` (String, Default: `"desc"`) + +--- + +## ๐Ÿ›ก๏ธ Administrative Search & Sync Endpoints + +Requires roles `ADMIN` or `SUPER_ADMIN`. + +### 1. Search Users +- **URL**: `/api/v1/admin/search/users` (`POST` with `SearchRequest` body) +- **URL**: `/api/v1/admin/search/users` (`GET` query parameter fallback) +- **Query filters**: `query`, `role`, `isActive`, `country`, `page`, `size`. + +--- + +### 2. Search Payment Transactions +Search credit packages purchases and billing logs. + +- **URL**: `/api/v1/admin/search/payments` (`POST` with `SearchRequest` body) +- **URL**: `/api/v1/admin/search/payments` (`GET` query parameter fallback) +- **Query filters**: `query` (matches email/name/receipt numbers), `paymentProvider`, `status`, `currency`. + +--- + +### 3. Find Payment by Receipt Number +- **URL**: `/api/v1/admin/search/payments/receipt/{receiptNumber}` +- **Method**: `GET` + +--- + +### 4. Elasticsearch Sync Controls + +Trigger indexing synchronizations from the Postgres database. + +#### Full Sync (Asynchronous background runner) +- **URL**: `/api/v1/admin/elasticsearch/sync` +- **Method**: `POST` +- **Response (`202 Accepted`)**: + ```json + { + "message": "Full synchronization started in background", + "status": "STARTED" + } + ``` + +#### Sync Specific Indexes (Synchronous count return) +- **URL**: `/api/v1/admin/elasticsearch/sync/users` (`POST` - Syncs users profiles index) +- **URL**: `/api/v1/admin/elasticsearch/sync/documents` (`POST` - Syncs documents index) +- **URL**: `/api/v1/admin/elasticsearch/sync/payments` (`POST` - Syncs payments index) + +##### Sync Response Example (`200 OK`): +```json +{ + "message": "User synchronization completed", + "usersIndexed": 1450 +} +``` diff --git a/src/main/java/com/xtraction/api/extraction/vision/api_docs/api_docs.md b/src/main/java/com/xtraction/api/extraction/vision/api_docs/api_docs.md new file mode 100644 index 0000000..2a89a0c --- /dev/null +++ b/src/main/java/com/xtraction/api/extraction/vision/api_docs/api_docs.md @@ -0,0 +1,81 @@ +# ๐Ÿ‘๏ธ Google Cloud Vision OCR Integration API Documentation + +This package implements high-accuracy text extraction utilizing the **Google Cloud Vision API** as a pluggable alternative/fallback to the Tesseract OCR engine. + +--- + +## ๐Ÿ—๏ธ Architectural Flow + +Google Vision OCR processing is integrated asynchronously using Kafka message events. When a document requires high-accuracy scanning, a request event is published, consumed, processed by the Google Vision provider, and the output is persisted. + +```mermaid +sequenceDiagram + participant User as User Ingestion + participant Event as VisionOcrEventPublisher + participant Broker as Kafka (Topic: vision-ocr-jobs) + participant Worker as VisionOcrConsumer + participant Provider as GoogleVisionOcrProvider + participant API as Google Cloud Vision API + + User->>Event: publish requested OCR job + Event->>Broker: publish VisionOcrRequestedEvent + Broker->>Worker: consume event + Worker->>Provider: execute text extraction + Provider->>API: batchAnnotateImages + API-->>Provider: return annotations (text) + Provider-->>Worker: return OcrResult + Worker->>Worker: update OcrData DB and publish completion status +``` + +--- + +## โš™๏ธ Foundational Properties + +To enable this provider, the following Spring property parameters must be defined: +- `ocr.google-vision.enabled`: Set to `true` to bootstrap this provider. +- `spring.cloud.gcp.credentials.location`: File path to the Google service account JSON key. +- `spring.cloud.gcp.project-id`: Google Cloud Platform project ID. + +--- + +## ๐Ÿš€ Event Integration Catalogue + +### 1. Vision OCR Request Event (`VisionOcrRequestedEvent`) +Published to coordinate async processing tasks. + +- **Kafka Topic**: `vision-ocr-jobs` +- **JSON Event Schema**: + ```json + { + "documentId": "doc_e3d3b764-f6b0-41ab-8be0-b26a6358dbb2", + "collectionId": "col_b8d348a0-2f3b-48cf-99bf-8cd64f201083", + "imageUrl": "https://s3.amazonaws.com/...", + "mimeType": "application/pdf", + "userId": "usr_9b1deb4d...", + "providerType": "GOOGLE_VISION", + "languageHint": "en", // ISO 639-1 code + "priority": 0, + "fallbackEnabled": true, + "createdAt": "2026-07-07T20:25:00.123Z", + "correlationId": "tx_uuid_9988...", + "metadata": {} + } + ``` + +#### Parameter Details: +- `fallbackEnabled` (Boolean): If set to `true`, the pipeline automatically falls back to the local Tesseract OCR engine if Google API connectivity limits are exceeded (e.g. rate limit codes or quota exhaustions). +- `priority` (Integer): Higher value indicates prioritised job processing sequence. + +--- + +## ๐Ÿฅ 2. Health Monitoring (`GoogleVisionHealthIndicator`) + +Provides a diagnostic component verifying API reachability. Used by admin console checkers or custom actuators. + +### Health Check response fields: +- `status`: `"UP"` (healthy/reachable) or `"DOWN"` (unreachable). +- `provider`: `"google-vision"`. +- `reason` / `error`: Exception detail message mapping on failures. + +> [!NOTE] +> Health check statuses are cached locally for **1 minute** to avoid duplicate Google API call overheads. diff --git a/src/main/java/com/xtraction/api/identity/auth/impl/LoginUserImpl.java b/src/main/java/com/xtraction/api/identity/auth/impl/LoginUserImpl.java index 433d042..c23a185 100644 --- a/src/main/java/com/xtraction/api/identity/auth/impl/LoginUserImpl.java +++ b/src/main/java/com/xtraction/api/identity/auth/impl/LoginUserImpl.java @@ -1,6 +1,6 @@ package com.xtraction.api.identity.auth.impl; -import com.xtraction.api.identity.auth.oauth2.datamodel.AuthProvider; +import com.xtraction.api.identity.oauth2.datamodel.AuthProvider; import com.xtraction.api.core.utils.logging.SanitizeLogging; import com.xtraction.api.core.web.response.ApiResponse; diff --git a/src/main/java/com/xtraction/api/identity/oauth2/api_docs/api_docs.md b/src/main/java/com/xtraction/api/identity/oauth2/api_docs/api_docs.md new file mode 100644 index 0000000..29686d3 --- /dev/null +++ b/src/main/java/com/xtraction/api/identity/oauth2/api_docs/api_docs.md @@ -0,0 +1,106 @@ +# ๐Ÿ”‘ OAuth2 Single Sign-On (SSO) API Documentation + +This module manages Federated Identity and Single Sign-On (SSO) logins using OAuth2 providers (Google and GitHub), handles automated user provisioning, and generates session JWTs. + +--- + +## ๐Ÿ—๏ธ Architectural Flow + +Federated login follows the standard OAuth2 Authorization Code Grant flow, completed in the browser using redirects: + +```mermaid +sequenceDiagram + participant Client as Frontend SPA + participant Browser + participant API as Spring Security Filter Chain + participant Provider as Identity Provider (Google/GitHub) + participant Handlers as Success/Failure Handlers + participant DB as PostgreSQL + + Client->>Browser: redirect to initiation endpoint + Browser->>API: GET /oauth2/authorization/{provider} + API-->>Browser: HTTP 302 Redirect to Provider Consent Screen + Browser->>Provider: User logs in & authorizes + Provider-->>Browser: HTTP 302 Redirect to /login/oauth2/code/{provider} with ?code=xyz + Browser->>API: GET /login/oauth2/code/{provider} + API->>Provider: Exchange code for tokens + Provider-->>API: returns user profile data (email, avatar) + API->>DB: custom provisioning (check if user exists, else insert) + API->>Handlers: invoke success/failure handler + alt Success Handler + Handlers->>Handlers: generate access token (JWT) & refresh token + Handlers->>Browser: set HttpOnly refresh cookie + Handlers-->>Browser: HTTP 302 Redirect to frontend callback ?token=jwt&profileComplete=true + Browser->>Client: load token into application memory state + else Failure Handler + Handlers-->>Browser: HTTP 302 Redirect to frontend callback ?error=url_encoded_msg + end +``` + +--- + +## ๐Ÿš€ Endpoint Reference + +These endpoints are handled directly in the browser. Do not call them via Axios or fetch/XHR libraries from frontend script codes. + +### 1. Initiate Google OAuth2 Login +- **URL**: `http://localhost:8080/oauth2/authorization/google` +- **Method**: `GET` +- **Authentication**: None +- **Redirects to**: Google accounts consent screen. + +--- + +### 2. Initiate GitHub OAuth2 Login +- **URL**: `http://localhost:8080/oauth2/authorization/github` +- **Method**: `GET` +- **Authentication**: None +- **Redirects to**: GitHub authorize application screen. + +--- + +## โšก User Provisioning Logic + +When a user completes authentication on Google or GitHub: +1. The backend searches the user registry database (`user` table) by email. +2. **Existing User**: + - Updates `lastLogin` timestamp. + - Proceeds to generate session tokens. +3. **New User (Automatic Provisioning)**: + - Registers user automatically. + - Sets `firstName` and `lastName` parsed from provider attributes. + - Sets `emailVerified` to `true` (since identity provider has verified it). + - Generates a random, high-entropy password (never exposed to client). + - Publishes `USER_REGISTERED` event to Kafka broker to send a welcome email. + +--- + +## ๐Ÿ”„ Callback & Redirect Specifications + +### 1. Success Redirect (`OAuth2AuthenticationSuccessHandler`) +On success, the user is redirected to the target URI bound to `app.oauth2.authorized-redirect-uri` (e.g. `http://localhost:4200/oauth2/callback`). + +#### Appended Cookie: +Sets a rolling `HttpOnly`, `Secure` (production only), `SameSite=Strict` cookie: +- **Name**: `refreshToken` +- **Max-Age**: 30 days (`2592000000` milliseconds). +- **Path**: `/api/v1/auth` + +#### Appended Query Parameters: +The redirect URL includes these parameters: +- `token` (String): The JWT access token (valid for 1 hour). Pass this in `Authorization: Bearer ` headers. +- `profileComplete` (Boolean): + - `true`: Profile metadata (country, profession) is complete. + - `false`: Onboarding metadata is missing. Redirect to registration onboarding details page. + +##### Redirect Example: +`https://yourfrontend.com/oauth2/callback?token=eyJhbGciOiJIUzI1Ni...&profileComplete=false` + +--- + +### 2. Failure Redirect (`OAuth2AuthenticationFailureHandler`) +On failure, the browser is redirected to the callback URI with: +- `error` (String): URL-encoded error description. + +##### Redirect Example: +`https://yourfrontend.com/oauth2/callback?error=Authentication+failed%3A+user+account+is+locked` diff --git a/src/main/java/com/xtraction/api/identity/auth/oauth2/config/OAuth2Properties.java b/src/main/java/com/xtraction/api/identity/oauth2/config/OAuth2Properties.java similarity index 92% rename from src/main/java/com/xtraction/api/identity/auth/oauth2/config/OAuth2Properties.java rename to src/main/java/com/xtraction/api/identity/oauth2/config/OAuth2Properties.java index c5e8bf5..94a2837 100644 --- a/src/main/java/com/xtraction/api/identity/auth/oauth2/config/OAuth2Properties.java +++ b/src/main/java/com/xtraction/api/identity/oauth2/config/OAuth2Properties.java @@ -1,4 +1,4 @@ -package com.xtraction.api.identity.auth.oauth2.config; +package com.xtraction.api.identity.oauth2.config; import lombok.Getter; import lombok.Setter; diff --git a/src/main/java/com/xtraction/api/identity/auth/oauth2/datamodel/AuthProvider.java b/src/main/java/com/xtraction/api/identity/oauth2/datamodel/AuthProvider.java similarity index 78% rename from src/main/java/com/xtraction/api/identity/auth/oauth2/datamodel/AuthProvider.java rename to src/main/java/com/xtraction/api/identity/oauth2/datamodel/AuthProvider.java index 3133676..060a4a2 100644 --- a/src/main/java/com/xtraction/api/identity/auth/oauth2/datamodel/AuthProvider.java +++ b/src/main/java/com/xtraction/api/identity/oauth2/datamodel/AuthProvider.java @@ -1,4 +1,4 @@ -package com.xtraction.api.identity.auth.oauth2.datamodel; +package com.xtraction.api.identity.oauth2.datamodel; /** * Represents the authentication provider used to create a user account. diff --git a/src/main/java/com/xtraction/api/identity/auth/oauth2/dto/GoogleOAuth2UserInfo.java b/src/main/java/com/xtraction/api/identity/oauth2/dto/GoogleOAuth2UserInfo.java similarity index 85% rename from src/main/java/com/xtraction/api/identity/auth/oauth2/dto/GoogleOAuth2UserInfo.java rename to src/main/java/com/xtraction/api/identity/oauth2/dto/GoogleOAuth2UserInfo.java index e095ada..e6035b2 100644 --- a/src/main/java/com/xtraction/api/identity/auth/oauth2/dto/GoogleOAuth2UserInfo.java +++ b/src/main/java/com/xtraction/api/identity/oauth2/dto/GoogleOAuth2UserInfo.java @@ -1,4 +1,4 @@ -package com.xtraction.api.identity.auth.oauth2.dto; +package com.xtraction.api.identity.oauth2.dto; import lombok.Builder; diff --git a/src/main/java/com/xtraction/api/identity/auth/oauth2/handler/OAuth2AuthenticationFailureHandler.java b/src/main/java/com/xtraction/api/identity/oauth2/handler/OAuth2AuthenticationFailureHandler.java similarity index 92% rename from src/main/java/com/xtraction/api/identity/auth/oauth2/handler/OAuth2AuthenticationFailureHandler.java rename to src/main/java/com/xtraction/api/identity/oauth2/handler/OAuth2AuthenticationFailureHandler.java index a4ee5c5..a82f92d 100644 --- a/src/main/java/com/xtraction/api/identity/auth/oauth2/handler/OAuth2AuthenticationFailureHandler.java +++ b/src/main/java/com/xtraction/api/identity/oauth2/handler/OAuth2AuthenticationFailureHandler.java @@ -1,6 +1,6 @@ -package com.xtraction.api.identity.auth.oauth2.handler; +package com.xtraction.api.identity.oauth2.handler; -import com.xtraction.api.identity.auth.oauth2.config.OAuth2Properties; +import com.xtraction.api.identity.oauth2.config.OAuth2Properties; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; diff --git a/src/main/java/com/xtraction/api/identity/auth/oauth2/handler/OAuth2AuthenticationSuccessHandler.java b/src/main/java/com/xtraction/api/identity/oauth2/handler/OAuth2AuthenticationSuccessHandler.java similarity index 96% rename from src/main/java/com/xtraction/api/identity/auth/oauth2/handler/OAuth2AuthenticationSuccessHandler.java rename to src/main/java/com/xtraction/api/identity/oauth2/handler/OAuth2AuthenticationSuccessHandler.java index 7c406f2..bfe364f 100644 --- a/src/main/java/com/xtraction/api/identity/auth/oauth2/handler/OAuth2AuthenticationSuccessHandler.java +++ b/src/main/java/com/xtraction/api/identity/oauth2/handler/OAuth2AuthenticationSuccessHandler.java @@ -1,9 +1,9 @@ -package com.xtraction.api.identity.auth.oauth2.handler; +package com.xtraction.api.identity.oauth2.handler; import com.xtraction.api.core.security.JwtTokenProvider; import com.xtraction.api.core.security.RefreshTokenService; import com.xtraction.api.core.utils.CookieUtil; -import com.xtraction.api.identity.auth.oauth2.config.OAuth2Properties; +import com.xtraction.api.identity.oauth2.config.OAuth2Properties; import com.xtraction.api.identity.user.model.User; import com.xtraction.api.identity.user.repository.UserRepository; import jakarta.servlet.http.HttpServletRequest; diff --git a/src/main/java/com/xtraction/api/identity/auth/oauth2/impl/OAuth2UserProvisioningImpl.java b/src/main/java/com/xtraction/api/identity/oauth2/impl/OAuth2UserProvisioningImpl.java similarity index 96% rename from src/main/java/com/xtraction/api/identity/auth/oauth2/impl/OAuth2UserProvisioningImpl.java rename to src/main/java/com/xtraction/api/identity/oauth2/impl/OAuth2UserProvisioningImpl.java index 5b68d6f..15ff043 100644 --- a/src/main/java/com/xtraction/api/identity/auth/oauth2/impl/OAuth2UserProvisioningImpl.java +++ b/src/main/java/com/xtraction/api/identity/oauth2/impl/OAuth2UserProvisioningImpl.java @@ -1,4 +1,4 @@ -package com.xtraction.api.identity.auth.oauth2.impl; +package com.xtraction.api.identity.oauth2.impl; import com.xtraction.api.billing.credit.service.CreditBalanceService; import com.xtraction.api.billing.subscription.impl.AssignSubscriptionService; @@ -7,9 +7,9 @@ import com.xtraction.api.extraction.search.events.IndexAction; import com.xtraction.api.extraction.search.service.ElasticsearchIndexingService; import com.xtraction.api.identity.auth.datamodel.Role; -import com.xtraction.api.identity.auth.oauth2.datamodel.AuthProvider; -import com.xtraction.api.identity.auth.oauth2.dto.GoogleOAuth2UserInfo; -import com.xtraction.api.identity.auth.oauth2.interfaces.OAuth2UserProvisioningService; +import com.xtraction.api.identity.oauth2.datamodel.AuthProvider; +import com.xtraction.api.identity.oauth2.dto.GoogleOAuth2UserInfo; +import com.xtraction.api.identity.oauth2.interfaces.OAuth2UserProvisioningService; import com.xtraction.api.identity.user.model.User; import com.xtraction.api.identity.user.repository.UserRepository; import com.xtraction.api.integration.notification.datamodel.NotificationType; diff --git a/src/main/java/com/xtraction/api/identity/auth/oauth2/interfaces/OAuth2UserProvisioningService.java b/src/main/java/com/xtraction/api/identity/oauth2/interfaces/OAuth2UserProvisioningService.java similarity index 85% rename from src/main/java/com/xtraction/api/identity/auth/oauth2/interfaces/OAuth2UserProvisioningService.java rename to src/main/java/com/xtraction/api/identity/oauth2/interfaces/OAuth2UserProvisioningService.java index cbd88eb..9fe1f12 100644 --- a/src/main/java/com/xtraction/api/identity/auth/oauth2/interfaces/OAuth2UserProvisioningService.java +++ b/src/main/java/com/xtraction/api/identity/oauth2/interfaces/OAuth2UserProvisioningService.java @@ -1,6 +1,6 @@ -package com.xtraction.api.identity.auth.oauth2.interfaces; +package com.xtraction.api.identity.oauth2.interfaces; -import com.xtraction.api.identity.auth.oauth2.dto.GoogleOAuth2UserInfo; +import com.xtraction.api.identity.oauth2.dto.GoogleOAuth2UserInfo; import com.xtraction.api.identity.user.model.User; /** diff --git a/src/main/java/com/xtraction/api/identity/auth/oauth2/service/CustomOAuth2UserService.java b/src/main/java/com/xtraction/api/identity/oauth2/service/CustomOAuth2UserService.java similarity index 94% rename from src/main/java/com/xtraction/api/identity/auth/oauth2/service/CustomOAuth2UserService.java rename to src/main/java/com/xtraction/api/identity/oauth2/service/CustomOAuth2UserService.java index 708c489..513f7b3 100644 --- a/src/main/java/com/xtraction/api/identity/auth/oauth2/service/CustomOAuth2UserService.java +++ b/src/main/java/com/xtraction/api/identity/oauth2/service/CustomOAuth2UserService.java @@ -1,7 +1,7 @@ -package com.xtraction.api.identity.auth.oauth2.service; +package com.xtraction.api.identity.oauth2.service; -import com.xtraction.api.identity.auth.oauth2.dto.GoogleOAuth2UserInfo; -import com.xtraction.api.identity.auth.oauth2.interfaces.OAuth2UserProvisioningService; +import com.xtraction.api.identity.oauth2.dto.GoogleOAuth2UserInfo; +import com.xtraction.api.identity.oauth2.interfaces.OAuth2UserProvisioningService; import com.xtraction.api.identity.user.model.User; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; diff --git a/src/main/java/com/xtraction/api/identity/user/model/User.java b/src/main/java/com/xtraction/api/identity/user/model/User.java index d185dde..d14d04b 100644 --- a/src/main/java/com/xtraction/api/identity/user/model/User.java +++ b/src/main/java/com/xtraction/api/identity/user/model/User.java @@ -4,7 +4,7 @@ import com.xtraction.api.identity.auth.model.UserVerification; import com.xtraction.api.extraction.documents.model.DocumentCollection; import com.xtraction.api.billing.subscription.model.UserSubscription; -import com.xtraction.api.identity.auth.oauth2.datamodel.AuthProvider; +import com.xtraction.api.identity.oauth2.datamodel.AuthProvider; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/com/xtraction/api/identity/user/repository/UserRepository.java b/src/main/java/com/xtraction/api/identity/user/repository/UserRepository.java index 640a7d3..411a487 100644 --- a/src/main/java/com/xtraction/api/identity/user/repository/UserRepository.java +++ b/src/main/java/com/xtraction/api/identity/user/repository/UserRepository.java @@ -1,6 +1,6 @@ package com.xtraction.api.identity.user.repository; -import com.xtraction.api.identity.auth.oauth2.datamodel.AuthProvider; +import com.xtraction.api.identity.oauth2.datamodel.AuthProvider; import com.xtraction.api.identity.user.model.User; import lombok.NonNull; import org.springframework.data.domain.Page; diff --git a/src/main/java/com/xtraction/api/integration/api_docs/api_docs.md b/src/main/java/com/xtraction/api/integration/api_docs/api_docs.md new file mode 100644 index 0000000..855f204 --- /dev/null +++ b/src/main/java/com/xtraction/api/integration/api_docs/api_docs.md @@ -0,0 +1,172 @@ +# ๐Ÿ”Œ System Integrations API Documentation + +This module manages WebSocket progression channels, push notification registrations, storage footprint allocations, and Mailgun webhook tracking processors under the `com.xtraction.api.integration` package. + +--- + +## ๐ŸŒ Section 1: WebSocket progress Tracking + +For asynchronous operations (uploading files, OCR scanning), the backend broadcasts progress metrics using SockJS and STOMP over WebSockets. + +### 1. Token Exchange REST Endpoint +WebSockets do not support headers natively in browser handshakes. Clients must first request a short-lived tickets token: + +- **URL**: `/api/v1/ws/ticket` +- **Method**: `POST` +- **Headers**: + - `Authorization: Bearer ` +- **Response Payload (`200 OK`)**: + ```json + { + "ticket": "ticket_uuid_string", + "wsUrl": "/ws/extraction-progress" + } + ``` + +> [!IMPORTANT] +> The ticket token is single-use and expires in Redis after **30 seconds** if no connection is established. + +### 2. Client Connection Handshake +Establish SockJS connection to the backend at `http://localhost:8080/ws/extraction-progress`. Include the token in the STOMP `CONNECT` frame: + +```javascript +const socket = new SockJS('http://localhost:8080/ws/extraction-progress'); +const stompClient = Stomp.over(socket); + +stompClient.connect( + { ticket: 'ticket_uuid_string' }, + (frame) => { + console.log('Connected: ' + frame); + // Subscribe to user-specific private queue + stompClient.subscribe('/user/queue/extraction-progress', (message) => { + const event = JSON.parse(message.body); + console.log('Progress Update:', event); + }); + }, + (error) => { + console.error('STOMP Connection error:', error); + } +); +``` + +### 3. Progress Event payload (`ExtractionProgressEvent`) +Dispatched messages are structured as: + +```json +{ + "collectionId": "col_b8d348a0...", + "documentId": "doc_e3d3b764...", + "fileName": "invoice.pdf", + "eventType": "EXTRACTION_PROGRESS", // Enums: UPLOAD_STARTED, FILE_UPLOADING, FILE_UPLOADED, EXTRACTION_STARTED, EXTRACTION_PROGRESS, EXTRACTION_COMPLETED, EXTRACTION_FAILED + "progress": 70, // Percentage + "message": "Running Tesseract OCR on page 4", + "timestamp": "2026-07-07T20:30:00Z", + "metadata": { + "totalPages": 5, + "currentPage": 4 + } +} +``` + +--- + +## ๐Ÿ”” Section 2: Push Notifications Engine + +Manages FCM (Firebase Cloud Messaging) device tokens, notification queues, and alerts preferences. + +### 1. Register Device Token +- **URL**: `/api/v1/notifications/device` +- **Method**: `POST` +- **Request Body (`RegisterDeviceRequest`)**: + ```json + { + "token": "fcm_token_abc...", + "deviceType": "ios" // ENUM: "ios" or "android" + } + ``` + +### 2. Unregister Device Token +- **URL**: `/api/v1/notifications/device/{tokenId}` +- **Method**: `DELETE` + +### 3. List User Notifications (Paginated) +- **URL**: `/api/v1/notifications` +- **Method**: `GET` +- **Query Parameters**: `page` (Default: 0), `size` (Default: 20) + +### 4. Mark Notification as Read +- **URL**: `/api/v1/notifications/{id}/read` +- **Method**: `PATCH` + +### 5. Mark All Notifications as Read +- **URL**: `/api/v1/notifications/read-all` +- **Method**: `PATCH` + +### 6. Delete Notification +- **URL**: `/api/v1/notifications/{id}` +- **Method**: `DELETE` + +### 7. Get Notification Preferences +- **URL**: `/api/v1/notifications/preferences` +- **Method**: `GET` +- **Response (`200 OK`)**: + ```json + { + "emailEnabled": true, + "pushEnabled": true, + "smsEnabled": false, + "marketingEnabled": false + } + ``` + +### 8. Update Notification Preferences +- **URL**: `/api/v1/notifications/preferences` +- **Method**: `PUT` +- **Request Body (`UpdatePreferencesRequest`)**: Same JSON body schema as the GET response. + +--- + +## ๐Ÿ’พ Section 3: Storage Allocations + +Monitors user cloud storage limits (footprint limits mapped from subscription plan tier settings). + +### 1. Get Storage footprints +- **URL**: `/api/v1/storage` +- **Method**: `GET` +- **Response (`200 OK`)**: + ```json + { + "success": true, + "statusCode": 200, + "message": "Storage information retrieved successfully", + "data": { + "userId": "usr_9b1deb4d...", + "storageUsed": 1048576, // In bytes + "storageLimit": 10737418240, // In bytes (10GB) + "percentageUsed": 0.01 + } + } + ``` + +### 2. Administrative Storagefootprint Recalculation +- **URL**: `/api/v1/admin/storage/migrate` +- **Method**: `POST` +- **Role Requirement**: `SUPER_ADMIN` only. + +--- + +## ๐Ÿ“ง Section 4: Mailgun Email Tracking Webhook + +Receives status telemetry logs directly from Mailgun mailservers. + +- **URL**: `/api/webhook/mailgun` +- **Method**: `POST` +- **Authentication Required**: None (Mailgun signature verify is conducted at filter levels) +- **Request Body (`WebhookResult`)**: + ```json + { + "recipient": "janedoe@example.com", + "event": "delivered" // ENUM: "delivered", "opened", "clicked", "failed" + } + ``` +- **Response**: `200 OK` (empty response).