@@ -8,7 +8,22 @@ The current implementation uses `com.banking.persistence` for data access.
...
@@ -8,7 +8,22 @@ The current implementation uses `com.banking.persistence` for data access.
**Decision**: All new repository logic for the web interface (e.g., retrieving all accounts, retrieving transaction history) must be added to `com.banking.persistence` rather than creating a new `com.banking.repository` package.
**Decision**: All new repository logic for the web interface (e.g., retrieving all accounts, retrieving transaction history) must be added to `com.banking.persistence` rather than creating a new `com.banking.repository` package.
## 2. BigDecimal and JSON Compatibility
## 2. Static File Serving in Java JDK HTTP Server (`com.sun.net.httpserver.HttpServer`)
### Pattern for Serving Static Files
The `HttpServer` API does not provide a built-in static file handler. The best pattern is to implement a custom `HttpHandler` that maps request URIs to files on the filesystem.
**Key Implementation Details:**
-**File Mapping**: Sanitize the request URI to prevent directory traversal attacks (e.g., removing `..` and ensuring the path stays within the intended static directory).
-**MIME Type Handling**: Use `java.nio.file.Files.probeContentType(Path path)` to determine the MIME type. Fall back to `application/octet-stream` if the type cannot be determined.
-**Efficient Reading**: Use `Files.readAllBytes(Path path)` for small files or `Files.copy(Path path, OutputStream out)` for larger files to stream the content directly to the `HttpExchange` response body.
-**Response Headers**: Set the `Content-Type` header based on the probed MIME type before calling `sendResponseHeaders(200, length)`.
### Recommended Approach
Create a `StaticFileHandler` class that takes a root directory as a constructor argument. In the `handle` method, resolve the requested path against this root, validate it, and stream the file.
## 3. BigDecimal and JSON Compatibility
### Current State
### Current State
-`RequestDTO` and `ResponseDTO` use `java.math.BigDecimal`.
-`RequestDTO` and `ResponseDTO` use `java.math.BigDecimal`.
-`RequestHandler` uses a default `ObjectMapper` instance.
-`RequestHandler` uses a default `ObjectMapper` instance.
...
@@ -25,7 +40,7 @@ To preserve backward compatibility for existing API clients while supporting the
...
@@ -25,7 +40,7 @@ To preserve backward compatibility for existing API clients while supporting the
-**Solution**: We will keep the `BigDecimal` fields as-is. For the web frontend, the browser's `JSON.parse()` will convert numeric JSON values to JS Numbers. Since we are only *displaying* these values and not performing calculations in JS, this is acceptable *provided* we ensure no precision-critical math happens on the client.
-**Solution**: We will keep the `BigDecimal` fields as-is. For the web frontend, the browser's `JSON.parse()` will convert numeric JSON values to JS Numbers. Since we are only *displaying* these values and not performing calculations in JS, this is acceptable *provided* we ensure no precision-critical math happens on the client.
-**Strict Requirement**: The frontend must treat monetary values as opaque strings for any operation. If calculation is needed, it must be sent to the server.
-**Strict Requirement**: The frontend must treat monetary values as opaque strings for any operation. If calculation is needed, it must be sent to the server.
## 3. Deterministic Fault Injection
## 4. Deterministic Fault Injection
The original `FaultInjector` uses global state, which is susceptible to "fault theft" by unrelated concurrent requests.
The original `FaultInjector` uses global state, which is susceptible to "fault theft" by unrelated concurrent requests.
@@ -48,28 +63,63 @@ To ensure the intended transaction is the one that experiences response loss:
...
@@ -48,28 +63,63 @@ To ensure the intended transaction is the one that experiences response loss:
- The response loss is triggered strictly *after*`conn.commit()` but *before*`sendResponse()`.
- The response loss is triggered strictly *after*`conn.commit()` but *before*`sendResponse()`.
- The `/__test/` endpoints are registered only if `-Denv=test` is set. To prevent accidental production activation, this check is performed during the `HttpServer` startup sequence, and no "fallback" or "default" production mode can enable these handlers.
- The `/__test/` endpoints are registered only if `-Denv=test` is set. To prevent accidental production activation, this check is performed during the `HttpServer` startup sequence, and no "fallback" or "default" production mode can enable these handlers.
## 4. Monetary Precision in the Browser
## 5. Monetary Precision in the Browser
### The Precision Problem
### The Precision Problem
While the backend uses `BigDecimal`, the standard `JSON.parse()` in JavaScript converts numeric JSON values into IEEE 754 Double Precision floats, causing rounding errors for high-scale or very large monetary values.
While the backend uses `BigDecimal`, the standard `JSON.parse()` in JavaScript converts numeric JSON values into IEEE 754 Double Precision floats, causing rounding errors for high-scale or very large monetary values.
### The Strategy: UI-Specific Response DTOs
### The Hybrid Strategy
To preserve the existing `POST /withdraw` response contract for backward compatibility while ensuring absolute precision for the UI:
To maintain compatibility with the existing `/withdraw` endpoint while ensuring precision for the rest of the UI:
1.**Dedicated UI DTOs**: The server will introduce a separate `UIResponseDTO` (and corresponding endpoints/handlers) specifically for the web interface.
2.**String Serialization**: In `UIResponseDTO`, all `BigDecimal` fields will be annotated with `@JsonFormat(shape = JsonFormat.Shape.STRING)`. This ensures that the JSON output is `"balance": "100.00"` rather than `"balance": 100.00`.
3.**Logic Delegation**: The UI handlers will call the existing `TransactionService` and `AccountRepository` to perform all business logic. They will merely wrap the resulting `BigDecimal` values into the `UIResponseDTO` for serialization.
4.**Zero-Math Policy**: The frontend will treat these JSON strings as opaque values for display. No JS-side arithmetic will be performed.
5.**Verification**: Automated integration tests will include "Stress Precision" cases using values like `1,000,000,000.00000001` to verify that the UI displays the exact string returned by the server without any floating-point corruption.
While the backend uses `BigDecimal`, the standard `JSON.parse()` in JavaScript converts numeric JSON values into IEEE 754 Double Precision floats. For extremely large balances or high-precision fractions, this leads to rounding errors.
- All `BigDecimal` fields in these DTOs will be annotated with `@JsonFormat(shape = JsonFormat.Shape.STRING)`.
- This ensures the JSON output is `"balance": "100.00"`, which is parsed as a string by the browser and preserves absolute precision.
### The Strategy: Lossless JSON Parsing
To preserve the original API response contract (which returns numeric values) while preventing precision loss in the browser:
2.**Existing API Endpoint (`POST /withdraw`)**:
1.**Lossless Parsing**: The frontend will use the `lossless-json` (v4.3.3) library.
- This endpoint keeps its original numeric JSON response to avoid breaking existing clients.
2.**Integration**: The library will be included as a local static asset (`src/main/resources/web/js/vendor/lossless-json.js`) and loaded via a `<script>` tag before the application logic.
- The frontend will use the `lossless-json` (v4.3.3) library to parse this specific response.
3.**Implementation**:
-`lossless-json` will be included as a local static asset (`src/main/resources/web/js/vendor/lossless-json.js`) and loaded via a `<script>` tag.
- Use `LosslessJSON.parse(responseText)` to handle the `POST /withdraw` response.
-`LosslessJSON.parse(responseText)` will be used to handle the response, and `LosslessNumber` objects will be converted to strings via `.toString()` for display.
- Convert `LosslessNumber` objects to strings using `.toString()` for UI display.
4.**Zero-Math Policy**: No arithmetic will be performed on monetary values in JS. Any needed calculations are delegated to the server.
3.**Zero-Math Policy**:
5.**Verification**: Automated integration tests will verify that high-precision `BigDecimal` values (e.g., `12345678901234567890.12345678` and `9007199254740993`) are preserved exactly from the raw HTTP response to the final displayed text.
- No arithmetic will be performed on monetary values in JS. Any needed calculations are delegated to the server.
4.**Verification**:
- Automated integration tests will verify that high-precision `BigDecimal` values (e.g., `1,000,000,000.00000001`) are preserved exactly from the raw HTTP response to the final displayed text in both the UI-specific and legacy endpoints.
## 6. Frontend State Management for Idempotent Retries
### Preserving Transaction Identity
In a vanilla JS application, maintaining the identity of a transaction (accountId, amount, sequenceKey) across timeouts or network failures is critical for idempotency.
**Patterns for State Management:**
-**SessionStorage**: Store the current pending transaction payload in `sessionStorage`. Unlike `localStorage`, `sessionStorage` is cleared when the tab is closed, which is appropriate for temporary transaction state.
-**URL State**: For simple retries, encoding the transaction ID in the URL as a query parameter allows the user to refresh the page or share the "retry" link without losing the context.
-**In-Memory Store with Persistence**: Use a simple JavaScript object to track the current state, but mirror it to `sessionStorage` on every change.
**Retry Workflow:**
1.**Initiation**: Generate the `sequenceKey` (idempotency key) on the client side.
2.**Persistence**: Save the entire request payload (including the key) to `sessionStorage`.
3.**Execution**: Send the request.
4.**Unknown Outcome**: If a timeout occurs, display a "Retry" button.
5.**Retry**: When clicked, retrieve the payload from `sessionStorage` and resend the exact same request (with the same `sequenceKey`).
## 7. Visual Indicators for Transaction Outcomes
### UX Patterns for Transaction States
Financial transactions require high clarity to avoid user anxiety. The following patterns are recommended for the specified states:
| State | Visual Indicator | User Message | Action |
| :--- | :--- | :--- | :--- |
| **SUCCESS** | Green Checkmark / Toast | "Transaction completed successfully." | View Receipt / Back to Home |
| **INSUFFICIENT_FUNDS** | Amber Warning Icon | "Insufficient funds to complete this transfer." | Top-up Account / Edit Amount |
| **STALE_KEY** | Blue Info Icon | "Your session has expired or the request is outdated." | Refresh Page / Start Over |
| **CONFLICTING_TRANSACTION** | Red Warning Icon | "A duplicate transaction is already being processed." | Check Transaction History |
| **INVALID_ACCOUNT** | Red Error Icon | "The destination account ID is invalid." | Verify Account Details |
| **UNKNOWN_OUTCOME** | Gray Question Mark | "We're unsure if the transaction went through." | **Retry Button** (using idempotent key) |
**General UX Guidelines:**
-**A11y**: Use both color and icons (don't rely on color alone).
-**Persistence**: For `UNKNOWN_OUTCOME`, provide a clear explanation that the system is verifying the state and that the "Retry" button is safe to use due to idempotency.
-**Loading State**: While the request is pending, disable the "Submit" button and show a spinner to prevent double-submissions.